Merge branch 'hugo-shipping-notice' into dev
This commit is contained in:
commit
3985b34dda
606 files changed
+52167
-36839
No files matched your search
@@ -319,6 +319,14 @@ export const saveShippingInventorySource = (payload: Record<string, unknown>, id
|
||||
`/api/admin/shipping-notice/sources${id ? `/${id}` : ''}`,
|
||||
{ method: id ? 'PUT' : 'POST', body: JSON.stringify(payload), ...jsonAuth() },
|
||||
);
|
||||
/** 读取/保存站点独立收料配置;严禁通过库存站点保存接口夹带这些字段。 */
|
||||
export const getShippingReceiptReportConfig = (sourceId: number) => requestJson<Record<string, unknown> | null>(
|
||||
`/api/admin/shipping-notice/sources/${sourceId}/receipt-report-config`, auth(),
|
||||
);
|
||||
export const saveShippingReceiptReportConfig = (sourceId: number, payload: Record<string, unknown>) => requestJson<Record<string, unknown>>(
|
||||
`/api/admin/shipping-notice/sources/${sourceId}/receipt-report-config`,
|
||||
{ method: 'PUT', body: JSON.stringify(payload), ...jsonAuth() },
|
||||
);
|
||||
/** 直接绑定停用库存站点到已发布解析方案;服务端自动写入操作审计。 */
|
||||
export const bindShippingInventorySourceParsingProfile = (id: number, payload: { parsing_profile_id: number }) => requestJson<unknown>(
|
||||
`/api/admin/shipping-notice/sources/${id}/bind-parsing-profile`, { method: 'POST', body: JSON.stringify(payload), ...jsonAuth() },
|
||||
|
||||
@@ -249,14 +249,12 @@ export const generateOrderProfileOcrCoordinateEvidence = (documentId: number, ta
|
||||
},
|
||||
);
|
||||
|
||||
/** 三步向导的唯一落库动作:原子创建草稿、主样本、Revision 和编辑租约。 */
|
||||
/** 三步向导只冻结统一视觉主表;XFA datasets 集合与镜像在编辑阶段另行保存。 */
|
||||
export const completeOrderDocumentProfileWizard = (payload: {
|
||||
display_name: string;
|
||||
schema_version_id: number;
|
||||
document_id: number;
|
||||
main_table_id?: string;
|
||||
authoritative_collection_path_id?: string;
|
||||
mirror_collection_path_ids?: string[];
|
||||
main_table_id: string;
|
||||
browser_session_id: string;
|
||||
operation_id: string;
|
||||
}) => requestJson<ShippingOrderDocumentProfile & {
|
||||
@@ -269,14 +267,14 @@ export const completeOrderDocumentProfileWizard = (payload: {
|
||||
/** 读取样本文档 XFA 字段树(脱敏值,不含明文路径)。 */
|
||||
export const getOrderProfileSampleXfaFieldTree = (documentId: number) =>
|
||||
requestJson<import('../types/shipping-order-document-profile.types').XfaFieldTreeResponse>(
|
||||
`/api/admin/shipping-notice/order-document-profile-samples/${documentId}/xfa/field-tree`,
|
||||
`/api/admin/shipping-notice/order-document-profile-samples/${documentId}/value-adapter/field-tree`,
|
||||
auth(),
|
||||
);
|
||||
|
||||
/** 读取 XFA 明细集合候选。 */
|
||||
export const getOrderProfileSampleXfaCollections = (documentId: number) =>
|
||||
requestJson<import('../types/shipping-order-document-profile.types').XfaCollectionsResponse>(
|
||||
`/api/admin/shipping-notice/order-document-profile-samples/${documentId}/xfa/collections`,
|
||||
`/api/admin/shipping-notice/order-document-profile-samples/${documentId}/value-adapter/collections`,
|
||||
auth(),
|
||||
);
|
||||
|
||||
@@ -287,88 +285,42 @@ export const previewOrderProfileSampleXfaValue = (
|
||||
options?: { reveal?: boolean },
|
||||
) =>
|
||||
requestJson<import('../types/shipping-order-document-profile.types').XfaValuePreviewResponse>(
|
||||
`/api/admin/shipping-notice/order-document-profile-samples/${documentId}/xfa/value-preview`,
|
||||
`/api/admin/shipping-notice/order-document-profile-samples/${documentId}/value-adapter/value-preview`,
|
||||
{ method: 'POST', body: JSON.stringify({ path_id: pathId, reveal: Boolean(options?.reveal) }), ...jsonAuth() },
|
||||
);
|
||||
|
||||
/** 生成或复用绑定冻结 Analysis 的 XFA 合成预览(身份 + 页元数据,不含大图)。 */
|
||||
export const requestOrderProfileSampleXfaSyntheticPreview = (
|
||||
documentId: number,
|
||||
options?: { force?: boolean },
|
||||
) => requestJson<import('../types/shipping-order-document-profile.types').XfaSyntheticPreviewResponse>(
|
||||
`/api/admin/shipping-notice/order-document-profile-samples/${documentId}/xfa/preview`,
|
||||
{ method: 'POST', body: JSON.stringify({ force: Boolean(options?.force) }), ...jsonAuth() },
|
||||
);
|
||||
|
||||
/** 列出最新 ready 合成预览页并重新签发短时 token。 */
|
||||
export const listOrderProfileSampleXfaSyntheticPreviewPages = (documentId: number) =>
|
||||
requestJson<import('../types/shipping-order-document-profile.types').XfaSyntheticPreviewResponse>(
|
||||
`/api/admin/shipping-notice/order-document-profile-samples/${documentId}/xfa/preview/pages`,
|
||||
auth(),
|
||||
);
|
||||
|
||||
/**
|
||||
* 合成预览单页 PNG 的受控路径(配合 preview_token 用 fetch 拉取 blob)。
|
||||
* @param documentId 样本文档 ID
|
||||
* @param pageNo 1-based 页码
|
||||
*/
|
||||
export const orderProfileSampleXfaSyntheticPreviewPagePath = (documentId: number, pageNo: number) =>
|
||||
`/api/admin/shipping-notice/order-document-profile-samples/${documentId}/xfa/preview/pages/${pageNo}`;
|
||||
|
||||
/** 入队 XFA OCR 自动标记 Job(须合成预览 ready)。 */
|
||||
export const enqueueOrderProfileXfaOcrAutomark = (
|
||||
/** 入队统一 PDF 自动标记;服务端按 Profile 能力选择坐标或 XFA 多源证据。 */
|
||||
export const enqueueOrderProfilePdfAutomark = (
|
||||
profileId: number,
|
||||
payload: { document_id: number; force?: boolean },
|
||||
) => requestJson<{ job_id: number; status: string; preview_render_checksum?: string }>(
|
||||
`/api/admin/shipping-notice/order-document-profiles/${profileId}/xfa/automark`,
|
||||
payload: { document_id: number; table_id?: string; schema_version_id?: number; page_no?: number; force?: boolean },
|
||||
) => requestJson<{ job_id: number; status: string }>(
|
||||
`/api/admin/shipping-notice/order-document-profiles/${profileId}/pdf-automark`,
|
||||
{ method: 'POST', body: JSON.stringify(payload), ...jsonAuth() },
|
||||
);
|
||||
|
||||
/** 轮询 OCR 自动标记 Job 状态与建议。 */
|
||||
export const getOrderProfileXfaOcrAutomarkJob = (profileId: number, jobId: number) =>
|
||||
/** 轮询统一 PDF 自动标记 Job;候选格式不暴露模板类型。 */
|
||||
export const getOrderProfilePdfAutomarkJob = (profileId: number, jobId: number) =>
|
||||
requestJson<{
|
||||
job_id: number;
|
||||
status: string;
|
||||
suggestions?: Array<Record<string, unknown>>;
|
||||
error_code?: string | null;
|
||||
kind?: 'field_binding_candidates' | null;
|
||||
candidates?: Array<Record<string, unknown>>;
|
||||
diagnostics?: Record<string, unknown>;
|
||||
preview_render_checksum?: string | null;
|
||||
renderer_version?: string | null;
|
||||
error_code?: string | null;
|
||||
message?: string | null;
|
||||
}>(
|
||||
`/api/admin/shipping-notice/order-document-profiles/${profileId}/xfa/automark/jobs/${jobId}`,
|
||||
`/api/admin/shipping-notice/order-document-profiles/${profileId}/pdf-automark/jobs/${jobId}`,
|
||||
auth(),
|
||||
);
|
||||
|
||||
/** 接受自动标记建议(high→confirmed;medium/low→suggested)。 */
|
||||
export const acceptOrderProfileXfaOcrAutomarkSuggestion = (
|
||||
profileId: number,
|
||||
suggestionId: string,
|
||||
payload: {
|
||||
job_id?: number;
|
||||
preview_render_checksum: string;
|
||||
render_mode?: string;
|
||||
browser_session_id?: string;
|
||||
lease_token?: string;
|
||||
},
|
||||
) => requestJson<Record<string, unknown>>(
|
||||
`/api/admin/shipping-notice/order-document-profiles/${profileId}/xfa/automark/suggestions/${encodeURIComponent(suggestionId)}/accept`,
|
||||
{ method: 'POST', body: JSON.stringify(payload), ...jsonAuth() },
|
||||
);
|
||||
|
||||
/** 拒绝自动标记建议。 */
|
||||
export const rejectOrderProfileXfaOcrAutomarkSuggestion = (
|
||||
profileId: number,
|
||||
suggestionId: string,
|
||||
payload?: { job_id?: number; browser_session_id?: string; lease_token?: string },
|
||||
) => requestJson<Record<string, unknown>>(
|
||||
`/api/admin/shipping-notice/order-document-profiles/${profileId}/xfa/automark/suggestions/${encodeURIComponent(suggestionId)}/reject`,
|
||||
{ method: 'POST', body: JSON.stringify(payload || {}), ...jsonAuth() },
|
||||
);
|
||||
|
||||
/** 预览拆分规则并签发确认令牌;默认脱敏,reveal 需敏感读权限。 */
|
||||
export const previewOrderProfileSampleXfaSplitRules = (
|
||||
documentId: number,
|
||||
payload: { path_id: string; rule_set: Record<string, unknown>; profile_id?: number; reveal?: boolean },
|
||||
) => requestJson<import('../types/shipping-order-document-profile.types').XfaSplitRulesPreviewResponse>(
|
||||
`/api/admin/shipping-notice/order-document-profile-samples/${documentId}/xfa/split-rules/preview`,
|
||||
`/api/admin/shipping-notice/order-document-profile-samples/${documentId}/value-adapter/split-rules/preview`,
|
||||
{ method: 'POST', body: JSON.stringify(payload), ...jsonAuth() },
|
||||
);
|
||||
|
||||
@@ -377,7 +329,7 @@ export const validateOrderProfileXfaSplitRules = (
|
||||
profileId: number,
|
||||
payload: { split_rules?: import('../types/shipping-order-document-profile.types').XfaSplitRuleSet[] },
|
||||
) => requestJson<import('../types/shipping-order-document-profile.types').XfaSplitRulesValidateResponse>(
|
||||
`/api/admin/shipping-notice/order-document-profiles/${profileId}/xfa/split-rules/validate`,
|
||||
`/api/admin/shipping-notice/order-document-profiles/${profileId}/value-adapter/split-rules/validate`,
|
||||
{ method: 'POST', body: JSON.stringify(payload), ...jsonAuth() },
|
||||
);
|
||||
|
||||
@@ -386,69 +338,7 @@ export const suggestOrderProfileXfaSplitRules = (
|
||||
profileId: number,
|
||||
payload: { document_id: number; path_id?: string | null },
|
||||
) => requestJson<import('../types/shipping-order-document-profile.types').XfaSplitRulesSuggestResponse>(
|
||||
`/api/admin/shipping-notice/order-document-profiles/${profileId}/xfa/split-rules/suggest`,
|
||||
{ method: 'POST', body: JSON.stringify(payload), ...jsonAuth() },
|
||||
);
|
||||
|
||||
/** 统一返回视觉 + 拆分规则建议;不写 Draft。 */
|
||||
export const suggestOrderProfileXfaUnifiedMapping = (
|
||||
profileId: number,
|
||||
payload: {
|
||||
document_id: number;
|
||||
page_no: number;
|
||||
normalized_bbox: import('../types/shipping-order-document-profile.types').XfaNormalizedBBox;
|
||||
path_id?: string | null;
|
||||
include_visual?: boolean;
|
||||
include_split?: boolean;
|
||||
},
|
||||
) => requestJson<import('../types/shipping-order-document-profile.types').XfaUnifiedMappingSuggestResponse>(
|
||||
`/api/admin/shipping-notice/order-document-profiles/${profileId}/xfa/unified-mapping/suggest`,
|
||||
{ method: 'POST', body: JSON.stringify(payload), ...jsonAuth() },
|
||||
);
|
||||
|
||||
/** 为页面区域生成 XFA 视觉绑定候选;歧义不自动确认。 */
|
||||
export const suggestOrderProfileXfaVisualBindings = (
|
||||
profileId: number,
|
||||
payload: {
|
||||
document_id: number;
|
||||
page_no: number;
|
||||
normalized_bbox: import('../types/shipping-order-document-profile.types').XfaNormalizedBBox;
|
||||
},
|
||||
) => requestJson<import('../types/shipping-order-document-profile.types').XfaVisualBindingsSuggestResponse>(
|
||||
`/api/admin/shipping-notice/order-document-profiles/${profileId}/xfa/visual-bindings/suggest`,
|
||||
{ method: 'POST', body: JSON.stringify(payload), ...jsonAuth() },
|
||||
);
|
||||
|
||||
/** 确认视觉绑定;须携带 Lease / operation_id / 合成预览证据。 */
|
||||
export const confirmOrderProfileXfaVisualBinding = (
|
||||
profileId: number,
|
||||
bindingId: string,
|
||||
payload: {
|
||||
visual_binding: import('../types/shipping-order-document-profile.types').XfaVisualBinding;
|
||||
path_id?: string | null;
|
||||
browser_session_id: string;
|
||||
lease_token: string;
|
||||
operation_id: string;
|
||||
preview_render_checksum?: string | null;
|
||||
render_mode?: string | null;
|
||||
},
|
||||
) => requestJson<import('../types/shipping-order-document-profile.types').XfaVisualBindingMutationResponse>(
|
||||
`/api/admin/shipping-notice/order-document-profiles/${profileId}/xfa/visual-bindings/${encodeURIComponent(bindingId)}/confirm`,
|
||||
{ method: 'POST', body: JSON.stringify(payload), ...jsonAuth() },
|
||||
);
|
||||
|
||||
/** 驳回视觉绑定建议;须携带 Lease / operation_id。 */
|
||||
export const rejectOrderProfileXfaVisualBinding = (
|
||||
profileId: number,
|
||||
bindingId: string,
|
||||
payload: {
|
||||
reason_code?: string | null;
|
||||
browser_session_id: string;
|
||||
lease_token: string;
|
||||
operation_id: string;
|
||||
},
|
||||
) => requestJson<import('../types/shipping-order-document-profile.types').XfaVisualBindingMutationResponse>(
|
||||
`/api/admin/shipping-notice/order-document-profiles/${profileId}/xfa/visual-bindings/${encodeURIComponent(bindingId)}/reject`,
|
||||
`/api/admin/shipping-notice/order-document-profiles/${profileId}/value-adapter/split-rules/suggest`,
|
||||
{ method: 'POST', body: JSON.stringify(payload), ...jsonAuth() },
|
||||
);
|
||||
|
||||
@@ -561,11 +451,11 @@ export const runOrderProfileCurrentSample = (profileId: number, payload: {
|
||||
{ method: 'POST', body: JSON.stringify(payload), ...jsonAuth() },
|
||||
);
|
||||
|
||||
/** 生成当前草稿版面签名;服务端更新 Profile 轻量引用,不接收前端 matcher 分数。 */
|
||||
export const runOrderProfileLayoutSignature = (profileId: number, payload: {
|
||||
/** 生成当前草稿统一身份签名;值源算法仅在服务端 adapter 内选择。 */
|
||||
export const runOrderProfileIdentitySignature = (profileId: number, payload: {
|
||||
browser_session_id: string; lease_token: string; operation_id: string;
|
||||
}) => requestJson<import('@/features/admin/types/shipping-order-document-profile.types').OrderProfileValidationRun>(
|
||||
`/api/admin/shipping-notice/order-document-profiles/${profileId}/validation-runs/layout-signature`,
|
||||
`/api/admin/shipping-notice/order-document-profiles/${profileId}/validation-runs/profile-identity-signature`,
|
||||
{ method: 'POST', body: JSON.stringify(payload), ...jsonAuth() },
|
||||
);
|
||||
|
||||
@@ -645,6 +535,16 @@ export const authorizeOrderProfilePreviewPages = (profileId: number, documentId:
|
||||
},
|
||||
);
|
||||
|
||||
/** 为统一编辑画布申请一次性原 PDF 内存读取令牌;响应绝不包含存储地址。 */
|
||||
export const authorizeOrderProfilePdfPreview = (profileId: number, documentId: number) =>
|
||||
requestJson<import('../types/shipping-order-document-profile.types').OrderProfilePdfPreviewGrant>(
|
||||
`/api/admin/shipping-notice/order-document-profiles/${profileId}/pdf-preview`, {
|
||||
method: 'POST', body: JSON.stringify({ document_id: documentId }), ...jsonAuth(),
|
||||
},
|
||||
);
|
||||
|
||||
/** @deprecated 旧 XFA 调用方兼容别名;新代码使用 authorizeOrderProfilePdfPreview。 */
|
||||
|
||||
/** 为冻结样本绑定申请只读详情页逐页预览授权,禁止回退到当前 document layout。 */
|
||||
export const authorizeOrderProfileFrozenSamplePreviewPages = (profileId: number, sampleBindingId: number) =>
|
||||
requestJson<OrderProfilePreviewPages>(
|
||||
|
||||
@@ -175,6 +175,29 @@
|
||||
</div>
|
||||
<button type="button" class="btn-secondary btn-sm full" @click="addParameter">{{ t('admin.shippingInventory.addParameter') }}</button>
|
||||
</template>
|
||||
<section v-if="selectedId" class="receipt-report-config full">
|
||||
<div class="subsection">{{ t('admin.shippingInventory.receiptReportConfig') }}<small>{{ t('admin.shippingInventory.receiptReportConfigHint') }}</small></div>
|
||||
<div class="switch-field"><span>{{ t('admin.shippingInventory.receiptReportEnabled') }}</span><button type="button" class="status-switch" :class="{ on: receiptConfig.enabled }" role="switch" :aria-checked="receiptConfig.enabled" @click="receiptConfig.enabled = !receiptConfig.enabled"><i></i><b>{{ receiptConfig.enabled ? t('admin.shippingInventory.enabledState') : t('admin.shippingInventory.disabledState') }}</b></button></div>
|
||||
<template v-if="source.connector_type === 'dbs'">
|
||||
<label><span>{{ t('admin.shippingInventory.programGroup') }}</span><input v-model="receiptConfig.report_path_json.program_group" class="input-field" required></label>
|
||||
<label><span>{{ t('admin.shippingInventory.programLabel') }}</span><input v-model="receiptConfig.report_path_json.program_label" class="input-field" required></label>
|
||||
<label><span>{{ t('admin.shippingInventory.reportGroup') }}</span><input v-model="receiptConfig.report_path_json.report_group" class="input-field" required></label>
|
||||
<label><span>{{ t('admin.shippingInventory.reportName') }}</span><input v-model="receiptConfig.report_path_json.report_name" class="input-field" required></label>
|
||||
<label class="full"><span>{{ t('admin.shippingInventory.receiptWarehouses') }}</span><input class="input-field" :value="receiptConfig.warehouse_ids_json.join(', ')" :placeholder="t('admin.shippingInventory.receiptWarehousesHint')" @input="receiptConfig.warehouse_ids_json = splitValues(($event.target as HTMLInputElement).value)"></label>
|
||||
<div class="subsection full">{{ t('admin.shippingInventory.receiptOptionalParameters') }}</div>
|
||||
<div v-for="(parameter, index) in receiptConfig.query_parameters_json" :key="`receipt-${index}-${parameter.name}`" class="parameter-row full">
|
||||
<input v-model="parameter.name" class="input-field" :placeholder="t('admin.shippingInventory.parameterName')">
|
||||
<select v-model="parameter.mode" class="select-field"><option value="single">{{ t('admin.shippingInventory.single') }}</option><option value="multi_text">{{ t('admin.shippingInventory.multiText') }}</option><option value="multi_select">{{ t('admin.shippingInventory.multiSelect') }}</option></select>
|
||||
<input class="input-field" :value="parameter.values.join(', ')" :placeholder="t('admin.shippingInventory.parameterValues')" @input="parameter.values = splitValues(($event.target as HTMLInputElement).value)">
|
||||
<label class="inline-check"><input v-model="parameter.required" type="checkbox">{{ t('admin.shippingInventory.required') }}</label>
|
||||
<label class="inline-check"><input v-model="parameter.select_all" type="checkbox">{{ t('admin.shippingInventory.selectAll') }}</label>
|
||||
<button type="button" class="btn-danger btn-sm" @click="receiptConfig.query_parameters_json.splice(index, 1)">{{ t('admin.delete') }}</button>
|
||||
</div>
|
||||
<button type="button" class="btn-secondary btn-sm full" @click="addReceiptParameter">{{ t('admin.shippingInventory.addParameter') }}</button>
|
||||
</template>
|
||||
<p v-else class="form-tip full">{{ t('admin.shippingInventory.receiptCraneFixedPath') }}</p>
|
||||
<div class="receipt-config-actions full"><button type="button" class="btn-secondary btn-sm" :disabled="receiptConfigLoading || receiptConfigSaving" @click="saveReceiptConfig">{{ receiptConfigSaving ? t('admin.shippingInventory.saving') : t('admin.shippingInventory.saveReceiptReportConfig') }}</button></div>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<template v-else-if="activeTab === 'parsing'">
|
||||
@@ -457,10 +480,13 @@ import {
|
||||
saveShippingInventorySource,
|
||||
saveShippingRpaProfile,
|
||||
bulkBindShippingInventorySourceParsingProfile,
|
||||
getShippingReceiptReportConfig,
|
||||
saveShippingReceiptReportConfig,
|
||||
} from '@/features/admin/api/admin.api';
|
||||
import type { ShippingInventoryConfigurationTest, ShippingInventoryReadinessCheck, ShippingInventoryValidationBatch } from '@/features/admin/api/admin.api';
|
||||
import { isConfigurationTestRunning, needsReadinessAction, readinessMarkerKind } from './shippingInventoryReadiness';
|
||||
import { normaliseInventoryReportPath } from './shippingInventorySourceForm';
|
||||
import { buildReceiptReportConfigPayload } from './receiptReportConfigForm';
|
||||
|
||||
type TabKey = 'profiles' | 'parsing' | 'inventoryFields' | 'templates' | 'sources' | 'rules' | 'snapshots' | 'exports' | 'mappings';
|
||||
type Item = Record<string, any>;
|
||||
@@ -548,6 +574,9 @@ const bulkBinding = reactive({ visible: false, sourceIds: [] as number[], profil
|
||||
const batchValidation = reactive({ visible: false, sourceIds: [] as number[], query: '', statusFilter: 'all' as 'all' | 'processing' | 'completed' | 'completed_empty' | 'failed', saving: false, result: null as ShippingInventoryValidationBatch | null });
|
||||
let batchValidationTimer: number | null = null;
|
||||
const source = reactive({ source_code: '', display_name: '', connector_type: 'dbs', rpa_profile_id: 0, parsing_profile_id: 0, excel_template_id: 0, warehouse_resolution_mode: 'fixed', fixed_warehouse_id: '', snapshot_ttl_seconds: 86400, report_path_json: { program_group: '', program_label: '', report_group: 'Inventory', report_name: '' }, query_parameters_json: [] as Parameter[], enabled: false, activation: { ready: false, checks: [] as ShippingInventoryReadinessCheck[], missing_requirements: [] as string[] } as SourceActivation });
|
||||
const receiptConfig = reactive({ enabled: false, report_path_json: { program_group: '', program_label: '', report_group: 'Inbound', report_name: '' } as Record<string, string>, query_parameters_json: [] as Parameter[], warehouse_ids_json: [] as string[] });
|
||||
const receiptConfigLoading = ref(false);
|
||||
const receiptConfigSaving = ref(false);
|
||||
const sourceBaseline = ref('');
|
||||
const rule = reactive({ rule_code: '', rule_name: '', scope: 'line', priority: 100, conditions: [{ source_kind: 'order_field', order_field_id: '', operator: 'prefix', expected: '' }] as RuleCondition[], source_codes: [] as string[] });
|
||||
const mapping = reactive({ inventory_source_id: 0, freight_warehouse_id: '', external_system_code: 'TOPGP', external_organization_code: '', external_site_code: '', external_warehouse_code: '', external_warehouse_name: '', enabled: true });
|
||||
@@ -766,6 +795,55 @@ async function load(): Promise<void> {
|
||||
}
|
||||
}
|
||||
|
||||
/** 重置当前站点的独立收料表单,不借用库存报表路径或查询条件。 */
|
||||
function resetReceiptConfig(connectorType: unknown): void {
|
||||
Object.assign(receiptConfig, {
|
||||
enabled: false,
|
||||
report_path_json: String(connectorType || '').toLowerCase() === 'crane'
|
||||
? { report_name: 'Inbound Details' }
|
||||
: { program_group: '', program_label: '', report_group: 'Inbound', report_name: '' },
|
||||
query_parameters_json: [],
|
||||
warehouse_ids_json: [],
|
||||
});
|
||||
}
|
||||
|
||||
/** 读取收料独立配置;读取失败不影响库存站点配置和既有库存运行。 */
|
||||
async function loadReceiptConfig(sourceId: number, connectorType: unknown): Promise<void> {
|
||||
receiptConfigLoading.value = true;
|
||||
resetReceiptConfig(connectorType);
|
||||
try {
|
||||
const config = await getShippingReceiptReportConfig(sourceId);
|
||||
if (!config) return;
|
||||
const isCrane = String(connectorType || '').toLowerCase() === 'crane';
|
||||
Object.assign(receiptConfig, {
|
||||
enabled: Boolean(config.enabled),
|
||||
report_path_json: isCrane
|
||||
? { report_name: 'Inbound Details' }
|
||||
: { program_group: '', program_label: '', report_group: 'Inbound', report_name: '', ...((config.report_path_json || {}) as Record<string, string>) },
|
||||
query_parameters_json: Array.isArray(config.query_parameters_json) ? config.query_parameters_json.map((parameter) => ({ ...parameter })) : [],
|
||||
warehouse_ids_json: Array.isArray(config.warehouse_ids_json) ? [...config.warehouse_ids_json].map(String) : [],
|
||||
});
|
||||
} catch (cause) { showError(cause, 'loadFailed'); }
|
||||
finally { receiptConfigLoading.value = false; }
|
||||
}
|
||||
|
||||
/** 新增 DBS 可选收料条件;Crane 固定默认查询,不维护查询条件。 */
|
||||
function addReceiptParameter(): void {
|
||||
receiptConfig.query_parameters_json.push({ name: '', mode: 'single', values: [], required: false, select_all: false });
|
||||
}
|
||||
|
||||
/** 仅提交白名单收料字段到独立 API,绝不调用库存 Source 保存接口。 */
|
||||
async function saveReceiptConfig(): Promise<void> {
|
||||
if (!selectedId.value) return;
|
||||
receiptConfigSaving.value = true;
|
||||
try {
|
||||
await saveShippingReceiptReportConfig(selectedId.value, buildReceiptReportConfigPayload(receiptConfig));
|
||||
await loadReceiptConfig(selectedId.value, source.connector_type);
|
||||
message.success(t('admin.shippingInventory.receiptReportSaved'));
|
||||
} catch (cause) { showError(cause, 'saveFailed'); }
|
||||
finally { receiptConfigSaving.value = false; }
|
||||
}
|
||||
|
||||
/** 切换管理对象时同步深链并清空选择,避免不同对象的数据残留在编辑器中。 */
|
||||
function selectTab(tab: TabKey): void {
|
||||
activeTab.value = tab;
|
||||
@@ -809,6 +887,7 @@ function createNew(): void {
|
||||
}
|
||||
if (activeTab.value === 'sources') {
|
||||
Object.assign(source, { source_code: '', display_name: '', connector_type: 'dbs', rpa_profile_id: 0, parsing_profile_id: 0, excel_template_id: 0, warehouse_resolution_mode: 'fixed', fixed_warehouse_id: '', snapshot_ttl_seconds: 86400, report_path_json: { program_group: '', program_label: '', report_group: 'Inventory', report_name: '' }, query_parameters_json: [], enabled: false, activation: { ready: false, checks: [], missing_requirements: ['configuration_test'] } });
|
||||
resetReceiptConfig('dbs');
|
||||
sourceBaseline.value = '';
|
||||
}
|
||||
if (activeTab.value === 'rules') Object.assign(rule, { rule_code: '', rule_name: '', scope: 'line', priority: 100, conditions: [{ source_kind: 'order_field', order_field_id: '', operator: 'prefix', expected: '' }], source_codes: [] });
|
||||
@@ -860,6 +939,7 @@ function selectItem(item: Item): void {
|
||||
Object.assign(source, { ...item, fixed_warehouse_id: item.fixed_warehouse_id || '', report_path_json: normaliseInventoryReportPath(item.connector_type, reportPath), query_parameters_json: (item.query_parameters_json || []).map((parameter: Parameter) => ({ ...parameter })) });
|
||||
sourceBaseline.value = serialiseSourceInput();
|
||||
void restoreConfigurationTest(Number(item.id));
|
||||
void loadReceiptConfig(Number(item.id), String(item.connector_type || ''));
|
||||
}
|
||||
if (activeTab.value === 'rules') Object.assign(rule, {
|
||||
rule_code: item.rule_code || '', rule_name: item.rule_name || '', scope: item.scope || 'line', priority: item.priority || 0,
|
||||
@@ -977,6 +1057,7 @@ function closeDrawer(): void {
|
||||
if (configurationTestTimer !== null) window.clearTimeout(configurationTestTimer);
|
||||
configurationTestTimer = null;
|
||||
configurationTest.value = null;
|
||||
resetReceiptConfig(source.connector_type);
|
||||
sourceBaseline.value = '';
|
||||
drawerOpen.value = false;
|
||||
selectedId.value = null;
|
||||
@@ -1523,6 +1604,9 @@ onMounted(load);
|
||||
.sample-evidence-card dl { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 8px 16px; margin: 0; }.sample-evidence-card dl div { min-width: 0; }.sample-evidence-card dt { color: #8190a0; font-size: 11px; }.sample-evidence-card dd { margin: 3px 0 0; overflow-wrap: anywhere; color: #475569; font-size: 12px; font-weight: 600; }
|
||||
.sample-replacement-input { display: grid; gap: 6px; border-top: 1px solid #e5edf3; padding-top: 11px; color: #52677a; font-size: 12px; font-weight: 600; }.sample-replacement-input input { max-width: 100%; }.sample-replacement-warning { border-left: 3px solid #e5a21a; background: #fff9eb; padding: 8px 10px; color: #855e00 !important; }.sample-replacement-warning p { margin: 0; }.sample-replacement-warning ul { display: grid; gap: 3px; margin: 7px 0 0; padding-left: 17px; }
|
||||
.parameter-row { display: grid; align-items: center; grid-template-columns: 1.1fr .9fr 1.25fr auto auto auto; gap: 8px; border-radius: 8px; background: #f8fafc; padding: 9px; }
|
||||
.receipt-report-config { display: grid; grid-column: 1 / -1; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 14px; border-top: 1px solid #dbe8ee; margin-top: 8px; padding-top: 14px; }
|
||||
.receipt-report-config .subsection, .receipt-report-config .full { grid-column: 1 / -1; }
|
||||
.receipt-config-actions { display: flex; justify-content: flex-end; }
|
||||
.condition-row, .mapping-row, .template-mapping { display: grid; align-items: center; gap: 8px; border-radius: 8px; background: #f8fafc; padding: 9px; }
|
||||
.condition-row { grid-template-columns: 1.15fr .9fr 1fr auto; }
|
||||
.mapping-row { grid-template-columns: 1fr 1fr auto; }
|
||||
@@ -1563,5 +1647,5 @@ onMounted(load);
|
||||
.object-list .empty-state { grid-column: 1 / -1; display: grid; min-height: 260px; place-items: center; }
|
||||
.empty-state { border: 1px dashed #c9d7e5; border-radius: 10px; background: #f9fbfd; padding: 38px 18px; color: #7b899a; font-size: 13px; text-align: center; }
|
||||
@media (max-width: 980px) { .parameter-row, .condition-row, .mapping-row, .template-mapping, .record-card { grid-template-columns: 1fr 1fr; } .mapping-value-row { grid-template-columns: minmax(0, 1.6fr) minmax(180px, 1fr); }.readiness-audit { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
|
||||
@media (max-width: 640px) { .inventory-console { padding: 18px; } .editor-form, .parameter-row, .condition-row, .mapping-row, .template-mapping, .record-card, .mapping-value-row, .parsing-mapping-card, .readonly-mapping-section .parsing-mapping-card, .parsing-summary { grid-template-columns: 1fr; } .mapping-arrow { transform: rotate(90deg); }.workbench-heading { display: block; } .workbench-heading .btn-primary { margin-top: 12px; }.batch-source-list { grid-template-columns: 1fr; }.batch-stat-grid { grid-template-columns: repeat(3, minmax(0, 1fr)); }.batch-run { grid-template-columns: 9px minmax(0, 1fr); }.batch-run-error { grid-column: 2; }.readiness-heading { display: grid; }.readiness-count { justify-self: start; }.readiness-steps li { grid-template-columns: 24px minmax(0, 1fr); }.readiness-action { grid-column: 2; justify-self: start; }.readiness-footer { justify-content: stretch; }.readiness-footer .btn-primary { width: 100%; } }
|
||||
@media (max-width: 640px) { .inventory-console { padding: 18px; } .editor-form, .parameter-row, .condition-row, .mapping-row, .template-mapping, .record-card, .mapping-value-row, .parsing-mapping-card, .readonly-mapping-section .parsing-mapping-card, .parsing-summary, .receipt-report-config { grid-template-columns: 1fr; } .mapping-arrow { transform: rotate(90deg); }.workbench-heading { display: block; } .workbench-heading .btn-primary { margin-top: 12px; }.batch-source-list { grid-template-columns: 1fr; }.batch-stat-grid { grid-template-columns: repeat(3, minmax(0, 1fr)); }.batch-run { grid-template-columns: 9px minmax(0, 1fr); }.batch-run-error { grid-column: 2; }.readiness-heading { display: grid; }.readiness-count { justify-self: start; }.readiness-steps li { grid-template-columns: 24px minmax(0, 1fr); }.readiness-action { grid-column: 2; justify-self: start; }.readiness-footer { justify-content: stretch; }.readiness-footer .btn-primary { width: 100%; } }
|
||||
</style>
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
/**
|
||||
* features/admin/modules/shipping-inventory/receiptReportConfigForm.spec.ts
|
||||
* 用途:覆盖收料报表表单的独立载荷边界。
|
||||
* 依赖:receiptReportConfigForm、vitest。
|
||||
* 逻辑:防止收料配置保存时把库存站点路径、库存查询条件或启停状态误发到库存接口。
|
||||
*/
|
||||
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { buildReceiptReportConfigPayload } from './receiptReportConfigForm';
|
||||
|
||||
describe('receiptReportConfigForm', () => {
|
||||
it('builds a receipt-only payload without inventory source fields', () => {
|
||||
// 关键断言:收料路径、条件与仓库必须走独立 API,不能夹带库存 RPA 配置。
|
||||
const payload = buildReceiptReportConfigPayload({
|
||||
enabled: true,
|
||||
report_path_json: { program_group: 'Bison', program_label: 'AWSBI', report_group: 'Inbound', report_name: 'Receipt Detail' },
|
||||
query_parameters_json: [{ name: 'Owner', mode: 'single', values: ['AWS'], required: false, select_all: false }],
|
||||
warehouse_ids_json: ['A', 'B'],
|
||||
source_code: 'INVENTORY-SHOULD-NOT-LEAK',
|
||||
snapshot_ttl_seconds: 86400,
|
||||
inventory_report_path_json: { report_name: 'On Hand' },
|
||||
});
|
||||
|
||||
expect(payload).toEqual({
|
||||
enabled: true,
|
||||
report_path_json: { program_group: 'Bison', program_label: 'AWSBI', report_group: 'Inbound', report_name: 'Receipt Detail' },
|
||||
query_parameters_json: [{ name: 'Owner', mode: 'single', values: ['AWS'], required: false, select_all: false }],
|
||||
warehouse_ids_json: ['A', 'B'],
|
||||
});
|
||||
expect(payload).not.toHaveProperty('source_code');
|
||||
expect(payload).not.toHaveProperty('snapshot_ttl_seconds');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,28 @@
|
||||
/**
|
||||
* features/admin/modules/shipping-inventory/receiptReportConfigForm.ts
|
||||
* 用途:构建独立收料报表配置的受限保存载荷。
|
||||
* 依赖:无外部依赖。
|
||||
* 逻辑:页面仅将收料路径、可选条件和 Warehouse 列表提交到收料配置 API,隔离库存站点字段。
|
||||
*/
|
||||
|
||||
export type ReceiptReportConfigInput = {
|
||||
enabled: boolean;
|
||||
report_path_json: Record<string, unknown>;
|
||||
query_parameters_json: Array<Record<string, unknown>>;
|
||||
warehouse_ids_json: string[];
|
||||
};
|
||||
|
||||
/**
|
||||
* 构造独立收料配置保存载荷。
|
||||
* 核心逻辑:白名单复制可配置业务字段,不允许调用方把库存源、Profile 或启停字段带入收料 API。
|
||||
* @param input - 抽屉中的收料配置表单状态。
|
||||
* @returns 仅包含收料配置 API 支持字段的深拷贝载荷。
|
||||
*/
|
||||
export function buildReceiptReportConfigPayload(input: ReceiptReportConfigInput): ReceiptReportConfigInput {
|
||||
return {
|
||||
enabled: Boolean(input.enabled),
|
||||
report_path_json: { ...(input.report_path_json || {}) },
|
||||
query_parameters_json: (input.query_parameters_json || []).map((item) => ({ ...item })),
|
||||
warehouse_ids_json: [...(input.warehouse_ids_json || [])],
|
||||
};
|
||||
}
|
||||
+4
-23
@@ -2,8 +2,8 @@
|
||||
features/admin/modules/shipping-order-document-profiles/OrderProfileBlindTestPage.vue
|
||||
用途:维护订单模板草稿的独立盲测证据,并完成执行和批准。
|
||||
依赖:盲测 API、Profile 详情、Vue Router、统一业务错误提示和四语言文案。
|
||||
逻辑:验证页进入本页;coordinate 走表格候选,xfa_dataset 走文档级结构分析候选;
|
||||
管理员复核候选后写入真值,再执行并批准,最后回到发布检查。不回显盲测真值。
|
||||
逻辑:验证页进入本页;所有模板按统一视觉表候选和字段证据复核;
|
||||
末端值源差异由服务端 adapter 投影,管理员复核后写入真值,再执行并批准。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, onBeforeUnmount, onMounted, ref } from 'vue';
|
||||
@@ -17,7 +17,6 @@ import {
|
||||
createOrderProfileTestSuite,
|
||||
executeOrderProfileTestSuite,
|
||||
createOrderProfileSample,
|
||||
getOrderDocumentProfileDetail,
|
||||
getOrderProfileSampleStatus,
|
||||
listOrderProfileBlindTestAvailableSamples,
|
||||
listOrderProfileBoundSamples,
|
||||
@@ -30,9 +29,7 @@ import type {
|
||||
OrderProfileBlindTestAvailableSample,
|
||||
OrderProfileBlindTestCandidate,
|
||||
OrderProfileTestSuite,
|
||||
OrderProfileTemplateMode,
|
||||
} from '@/features/admin/types/shipping-order-document-profile.types';
|
||||
import { isXfaDatasetProfileDefinition } from '@/features/admin/types/shipping-order-document-profile.types';
|
||||
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
@@ -41,12 +38,9 @@ const { t } = useI18n();
|
||||
const profileId = Number(route.params.profileId);
|
||||
const sessionId = String(route.query.editorSessionId || '').trim() || crypto.randomUUID();
|
||||
const suite = ref<OrderProfileTestSuite | null>(null);
|
||||
const templateMode = ref<OrderProfileTemplateMode>('coordinate');
|
||||
const availableSamples = ref<OrderProfileBlindTestAvailableSample[]>([]);
|
||||
const selectedSampleKey = ref('');
|
||||
const candidate = ref<OrderProfileBlindTestCandidate | null>(null);
|
||||
/** XFA 盲测使用文档级结构证据,不依赖坐标表格。 */
|
||||
const isXfa = computed(() => templateMode.value === 'xfa_dataset');
|
||||
const rowReviews = ref<Array<{ correct: boolean; correction: string }>>([]);
|
||||
const orderFieldReviews = ref<Record<string, { correct: boolean; value: string }>>({});
|
||||
const loading = ref(false);
|
||||
@@ -67,14 +61,6 @@ function sampleLabel(sample: OrderProfileBlindTestAvailableSample): string {
|
||||
if (sample.table_id === '__document_candidate__') {
|
||||
return t('admin.shippingOrderProfiles.blindTest.documentCandidateOption', { filename: sample.filename });
|
||||
}
|
||||
if (sample.table_id === 'xfa-authoritative-lines' || isXfa.value) {
|
||||
const identity = sample.header_preview.filter(Boolean).join(' · ');
|
||||
return t('admin.shippingOrderProfiles.blindTest.xfaSampleOption', {
|
||||
filename: sample.filename,
|
||||
rows: sample.row_count,
|
||||
identity: identity || '—',
|
||||
});
|
||||
}
|
||||
const header = sample.header_preview.join(' / ');
|
||||
return t('admin.shippingOrderProfiles.blindTest.sampleOption', {
|
||||
filename: sample.filename, page: sample.page_no, table: sample.table_index,
|
||||
@@ -136,15 +122,10 @@ function sampleFailureMessage(): string {
|
||||
async function loadSuite(): Promise<void> {
|
||||
loading.value = true;
|
||||
try {
|
||||
const [nextSuite, boundSamples, profile] = await Promise.all([
|
||||
const [nextSuite, boundSamples] = await Promise.all([
|
||||
createOrderProfileTestSuite(profileId),
|
||||
listOrderProfileBoundSamples(profileId),
|
||||
getOrderDocumentProfileDetail(profileId),
|
||||
]);
|
||||
templateMode.value = (
|
||||
profile.template_mode === 'xfa_dataset'
|
||||
|| isXfaDatasetProfileDefinition(profile.definition)
|
||||
) ? 'xfa_dataset' : 'coordinate';
|
||||
suite.value = nextSuite;
|
||||
hasTrainingSample.value = boundSamples.some((item) => item.sample_role === 'training');
|
||||
} catch (error) {
|
||||
@@ -425,7 +406,7 @@ onBeforeUnmount(() => {
|
||||
<header>
|
||||
<div>
|
||||
<h1 class="section-title">{{ t('admin.shippingOrderProfiles.blindTest.title') }}</h1>
|
||||
<p class="section-desc mt-1">{{ isXfa ? t('admin.shippingOrderProfiles.blindTest.xfaReviewHint') : t('admin.shippingOrderProfiles.blindTest.reviewHint') }}</p>
|
||||
<p class="section-desc mt-1">{{ t('admin.shippingOrderProfiles.blindTest.reviewHint') }}</p>
|
||||
</div>
|
||||
<div class="actions"><button type="button" class="btn-secondary" @click="backToValidation">{{ t('admin.shippingOrderProfiles.blindTest.backToValidation') }}</button><button v-if="suite?.status === 'approved'" type="button" class="btn-primary" @click="goToPublishCheck">{{ t('admin.shippingOrderProfiles.blindTest.goPublishCheck') }}</button></div>
|
||||
</header>
|
||||
|
||||
+15
-57
@@ -1,8 +1,8 @@
|
||||
<!--
|
||||
features/admin/modules/shipping-order-document-profiles/OrderProfileCreateWizardPage.vue
|
||||
用途:以三步向导创建订单文档模板草稿(坐标或 XFA 自动分流)。
|
||||
依赖:Schema/样本/表格/XFA API、步骤组件和 Vue Router。
|
||||
逻辑:样本 xfa_analysis_ready 时第三步改为集合确认;否则保持表格选择;原子创建草稿与 Lease。
|
||||
用途:以三步向导创建订单文档模板草稿。
|
||||
依赖:Schema/样本/表格 API、步骤组件和 Vue Router。
|
||||
逻辑:所有有明细的样本在第三步选择同一视觉主表;XFA datasets/OCR 差异只在编辑器的字段取值映射中配置。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, onBeforeUnmount, onMounted, reactive, ref, watch } from 'vue';
|
||||
@@ -18,7 +18,6 @@ import type { ShippingOrderSchemaVersion } from '@/features/admin/types/shipping
|
||||
import OrderProfileIdentityStep from './components/OrderProfileIdentityStep.vue';
|
||||
import OrderProfileSampleStep from './components/OrderProfileSampleStep.vue';
|
||||
import OrderProfileModelStartStep from './components/OrderProfileModelStartStep.vue';
|
||||
import OrderProfileXfaConfirmStep from './components/OrderProfileXfaConfirmStep.vue';
|
||||
|
||||
type Identity = { displayName: string; schemaId: number };
|
||||
|
||||
@@ -34,24 +33,14 @@ const tables = ref<Array<{ table_id: string; page_no: number; row_count: number;
|
||||
const identity = reactive<Identity>({ displayName: '', schemaId: 0 });
|
||||
const documentId = ref(0);
|
||||
const tableId = ref('');
|
||||
const authoritativePathId = ref('');
|
||||
const mirrorPathIds = ref<string[]>([]);
|
||||
const xfaContextReady = ref(false);
|
||||
const browserSessionId = crypto.randomUUID();
|
||||
let sampleRefreshTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
|
||||
const selectedSample = computed(() => samples.value.find((item) => item.document_id === documentId.value) || null);
|
||||
const isXfaSample = computed(() => Boolean(selectedSample.value?.xfa_analysis_ready));
|
||||
const publishedSchemas = computed(() => schemas.value.filter((item) => item.status === 'published'));
|
||||
const stepThreeLabel = computed(() => (
|
||||
isXfaSample.value
|
||||
? t('admin.shippingOrderProfiles.wizard.xfa.stepTitle')
|
||||
: t('admin.shippingOrderProfiles.wizard.tableStep')
|
||||
));
|
||||
const stepThreeLabel = computed(() => t('admin.shippingOrderProfiles.wizard.tableStep'));
|
||||
const canNext = computed(() => {
|
||||
if (step.value === 1) return Boolean(identity.displayName.trim() && identity.schemaId);
|
||||
if (step.value === 2) return Boolean(documentId.value);
|
||||
if (isXfaSample.value) return Boolean(xfaContextReady.value && authoritativePathId.value);
|
||||
return Boolean(tableId.value);
|
||||
});
|
||||
const steps = computed(() => [
|
||||
@@ -98,21 +87,14 @@ function scheduleSampleRefresh(): void {
|
||||
});
|
||||
}
|
||||
|
||||
/** 加载选定样本的可用表格;XFA 样本跳过表格加载。 */
|
||||
/** 加载选定样本的统一视觉表格;XFA 与普通 PDF 走同一 main_table_id 选择。 */
|
||||
async function loadTables(id: number): Promise<void> {
|
||||
if (samples.value.find((item) => item.document_id === id)?.xfa_analysis_ready) {
|
||||
tables.value = [];
|
||||
return;
|
||||
}
|
||||
try { tables.value = (await getOrderProfileSampleTables(id)).tables; }
|
||||
catch (error) { message.error(error instanceof BusinessError ? error.message : t('admin.shippingOrderProfiles.wizard.tableLoadFailed')); }
|
||||
}
|
||||
|
||||
watch(documentId, async (id) => {
|
||||
tableId.value = '';
|
||||
authoritativePathId.value = '';
|
||||
mirrorPathIds.value = [];
|
||||
xfaContextReady.value = false;
|
||||
tables.value = [];
|
||||
if (!id) return;
|
||||
await loadTables(id);
|
||||
@@ -123,7 +105,7 @@ watch(step, (currentStep) => {
|
||||
else stopSampleRefresh();
|
||||
});
|
||||
|
||||
/** 前进仅校验当前步骤;XFA 样本进入集合确认,单表坐标样本可直接创建。 */
|
||||
/** 前进仅校验当前步骤;所有模板共享视觉主表选择,单表样本可直接创建。 */
|
||||
async function next(): Promise<void> {
|
||||
if (!canNext.value) {
|
||||
message.error(step.value === 1 && !publishedSchemas.value.length
|
||||
@@ -132,10 +114,6 @@ async function next(): Promise<void> {
|
||||
return;
|
||||
}
|
||||
if (step.value === 2) {
|
||||
if (isXfaSample.value) {
|
||||
step.value = 3;
|
||||
return;
|
||||
}
|
||||
if (!tables.value.length) await loadTables(documentId.value);
|
||||
const onlyTable = tables.value.length === 1 ? tables.value[0] : undefined;
|
||||
if (onlyTable) {
|
||||
@@ -151,29 +129,19 @@ async function next(): Promise<void> {
|
||||
if (step.value < 3) step.value += 1;
|
||||
}
|
||||
|
||||
/** 单事务完成后进入草稿编辑路由;XFA 与坐标共享同一审计动作入口。 */
|
||||
/** 单事务完成后进入统一草稿编辑路由;字段取值 source 在编辑器内配置。 */
|
||||
async function finish(enterEditor: boolean): Promise<void> {
|
||||
if (!canNext.value) return;
|
||||
saving.value = true;
|
||||
try {
|
||||
const payload = isXfaSample.value
|
||||
? {
|
||||
display_name: identity.displayName,
|
||||
schema_version_id: identity.schemaId,
|
||||
document_id: documentId.value,
|
||||
authoritative_collection_path_id: authoritativePathId.value,
|
||||
mirror_collection_path_ids: mirrorPathIds.value,
|
||||
browser_session_id: browserSessionId,
|
||||
operation_id: crypto.randomUUID(),
|
||||
}
|
||||
: {
|
||||
display_name: identity.displayName,
|
||||
schema_version_id: identity.schemaId,
|
||||
document_id: documentId.value,
|
||||
main_table_id: tableId.value,
|
||||
browser_session_id: browserSessionId,
|
||||
operation_id: crypto.randomUUID(),
|
||||
};
|
||||
const payload = {
|
||||
display_name: identity.displayName,
|
||||
schema_version_id: identity.schemaId,
|
||||
document_id: documentId.value,
|
||||
main_table_id: tableId.value,
|
||||
browser_session_id: browserSessionId,
|
||||
operation_id: crypto.randomUUID(),
|
||||
};
|
||||
const profile = await completeOrderDocumentProfileWizard(payload);
|
||||
message.success(t('admin.shippingOrderProfiles.created'));
|
||||
await router.push(enterEditor
|
||||
@@ -216,16 +184,6 @@ onBeforeUnmount(stopSampleRefresh);
|
||||
@update:model-value="updateIdentity"
|
||||
/>
|
||||
<OrderProfileSampleStep v-else-if="step === 2" v-model="documentId" :samples="samples" @uploaded="refreshSamples(false)" @refresh="refreshSamples()" />
|
||||
<OrderProfileXfaConfirmStep
|
||||
v-else-if="isXfaSample"
|
||||
:document-id="documentId"
|
||||
:sample="selectedSample"
|
||||
:authoritative-path-id="authoritativePathId"
|
||||
:mirror-path-ids="mirrorPathIds"
|
||||
@update:authoritative-path-id="authoritativePathId = $event"
|
||||
@update:mirror-path-ids="mirrorPathIds = $event"
|
||||
@update:context-ready="xfaContextReady = $event"
|
||||
/>
|
||||
<OrderProfileModelStartStep v-else v-model="tableId" :tables="tables" />
|
||||
</main>
|
||||
|
||||
|
||||
+861
-826
File diff suppressed because it is too large.
Load diff
+39
-33
@@ -35,10 +35,12 @@ const sessionId = String(route.query.editorSessionId || '').trim() || crypto.ran
|
||||
const leaseToken = ref('');
|
||||
|
||||
const validationRun = computed(() => runs.value.find((item) => item.run_type === 'current_sample' && item.status === 'passed') || null);
|
||||
const layoutSignatureRun = computed(() => runs.value.find((item) => item.run_type === 'layout_signature' && item.status === 'passed') || null);
|
||||
const xfaStructureSignatureRun = computed(() => runs.value.find((item) => item.run_type === 'xfa_structure_signature' && item.status === 'passed') || null);
|
||||
const signatureRun = computed(() => xfaStructureSignatureRun.value || layoutSignatureRun.value);
|
||||
const isXfaReport = computed(() => report.value?.template_mode === 'xfa_dataset' || !!report.value?.xfa_structure_signature_status);
|
||||
/** 所有模板共用同一份视觉 layout signature;datasets 身份在其 evidence 中展示。 */
|
||||
const signatureRun = computed(() => runs.value.find((item) => (
|
||||
item.run_type === 'layout_signature' && item.status === 'passed'
|
||||
)) || null);
|
||||
const signatureStatusDetail = computed(() => report.value?.profile_identity_signature_status || null);
|
||||
const signatureIdentityDetails = computed(() => signatureStatusDetail.value?.identity_details || null);
|
||||
const overlapRun = computed(() => runs.value.find((item) => item.run_type === 'cross_template_overlap' && item.status === 'passed') || null);
|
||||
const publishable = computed(() => report.value?.status === 'valid' && !report.value.blocking_items.length && confirmed.value.length === (report.value.warning_items?.length || 0));
|
||||
const conflictProfiles = computed<OrderProfileOverlapConflictProfile[]>(() => report.value?.conflict_profiles || report.value?.overlap_summary?.conflict_profiles || []);
|
||||
@@ -47,29 +49,37 @@ const gateStatus = computed<'pass' | 'blocked' | 'pending'>(() => {
|
||||
return report.value.blocking_items.length ? 'blocked' : 'pass';
|
||||
});
|
||||
|
||||
/** XFA 统一验证指标:来自 current_sample 运行 summary(阶段 5–6)。 */
|
||||
const xfaValidationMetrics = computed<{
|
||||
visual: number | null;
|
||||
mirror: number | null;
|
||||
evidence: number | null;
|
||||
} | null>(() => {
|
||||
if (!isXfaReport.value) return null;
|
||||
/**
|
||||
* 统一将 value adapter 的验证指标投影为键值项。
|
||||
* 核心逻辑:页面只渲染公共指标卡;coordinate adapter 可返回空数组,XFA datasets
|
||||
* 则提供视觉/镜像/evidence 门禁证据,避免模板类型决定 DOM 结构。
|
||||
*/
|
||||
const adapterValidationMetrics = computed<Array<{ label: string; value: number | null }>>(() => {
|
||||
const summary = validationRun.value?.summary;
|
||||
if (!summary || typeof summary !== 'object') return null;
|
||||
if (!summary || typeof summary !== 'object') return [];
|
||||
const asRate = (value: unknown): number | null => (
|
||||
typeof value === 'number' && Number.isFinite(value) ? value : null
|
||||
);
|
||||
const visual = asRate(summary.visual_coverage_rate);
|
||||
const mirror = asRate(summary.mirror_consistency_rate);
|
||||
const evidence = asRate(summary.evidence_retention_rate);
|
||||
if (visual == null && mirror == null && evidence == null) return null;
|
||||
return { visual, mirror, evidence };
|
||||
return [
|
||||
{ label: t('admin.orderProfilePublishCheck.xfaVisualCoverage'), value: asRate(summary.visual_coverage_rate) },
|
||||
{ label: t('admin.orderProfilePublishCheck.xfaMirrorConsistency'), value: asRate(summary.mirror_consistency_rate) },
|
||||
{ label: t('admin.orderProfilePublishCheck.xfaEvidenceRetention'), value: asRate(summary.evidence_retention_rate) },
|
||||
].filter((item) => item.value != null);
|
||||
});
|
||||
|
||||
/** 安全格式化 XFA 指标,避免 template 对 Record 字段推断为 unknown。 */
|
||||
function formatXfaMetric(value: number | null | undefined): string {
|
||||
return formatRate(value);
|
||||
}
|
||||
/** 将 identity adapter 返回的可选证据投影为通用签名指标。 */
|
||||
const signatureIdentityMetrics = computed<Array<{ label: string; value: string }>>(() => {
|
||||
const details = signatureIdentityDetails.value;
|
||||
if (!details) return [];
|
||||
const metrics: Array<{ label: string; value: string }> = [];
|
||||
if (typeof details.header_token_coverage === 'number') {
|
||||
metrics.push({ label: t('admin.orderProfilePublishCheck.signatureHeaderCoverage'), value: formatRate(details.header_token_coverage) });
|
||||
}
|
||||
if (details.dataset_structure_fingerprint) {
|
||||
metrics.push({ label: t('admin.orderProfilePublishCheck.xfaStructureFingerprint'), value: details.dataset_structure_fingerprint });
|
||||
}
|
||||
return metrics;
|
||||
});
|
||||
|
||||
/** 显示统一业务错误,避免发布页暴露服务端实现细节。 */
|
||||
function fail(error: unknown): void {
|
||||
@@ -164,8 +174,7 @@ function itemMessage(item: Record<string, unknown>): string {
|
||||
cross_template_margin_insufficient: t('admin.orderProfilePublishCheck.crossTemplateMarginInsufficient'),
|
||||
sample_role_pollution: t('admin.orderProfilePublishCheck.sampleRolePollution'),
|
||||
cross_template_conflict_profiles: t('admin.orderProfilePublishCheck.crossTemplateConflictProfiles'),
|
||||
xfa_visual_bindings_required: t('admin.orderProfilePublishCheck.xfaVisualBindingsRequired'),
|
||||
xfa_visual_binding_incomplete: t('admin.orderProfilePublishCheck.xfaVisualBindingIncomplete'),
|
||||
xfa_mapping_required: t('admin.orderProfilePublishCheck.xfaFieldMappingsRequired'),
|
||||
xfa_visual_coverage_insufficient: t('admin.orderProfilePublishCheck.xfaVisualCoverageInsufficient'),
|
||||
xfa_evidence_retention_insufficient: t('admin.orderProfilePublishCheck.xfaEvidenceRetentionInsufficient'),
|
||||
xfa_mirror_consistency_insufficient: t('admin.orderProfilePublishCheck.xfaMirrorConsistencyInsufficient'),
|
||||
@@ -242,13 +251,12 @@ onMounted(loadRuns);
|
||||
</section>
|
||||
|
||||
<section class="card">
|
||||
<h3>{{ isXfaReport ? t('admin.orderProfilePublishCheck.xfaStructureSignatureTitle') : t('admin.orderProfilePublishCheck.layoutSignatureTitle') }}</h3>
|
||||
<h3>{{ t('admin.orderProfilePublishCheck.layoutSignatureTitle') }}</h3>
|
||||
<dl class="metrics">
|
||||
<div><dt>{{ t('admin.orderProfilePublishCheck.signatureStatus') }}</dt><dd :class="`status-${(isXfaReport ? report.xfa_structure_signature_status : report.layout_signature_status)?.status || 'unknown'}`">{{ signatureStatus((isXfaReport ? report.xfa_structure_signature_status : report.layout_signature_status)?.status) }}</dd></div>
|
||||
<div><dt>{{ t('admin.orderProfilePublishCheck.signatureSampleCount') }}</dt><dd>{{ (isXfaReport ? report.xfa_structure_signature_status : report.layout_signature_status)?.source_sample_count ?? '—' }}</dd></div>
|
||||
<div v-if="!isXfaReport"><dt>{{ t('admin.orderProfilePublishCheck.signatureHeaderCoverage') }}</dt><dd>{{ formatRate(report.layout_signature_status?.header_token_coverage) }}</dd></div>
|
||||
<div v-if="isXfaReport"><dt>{{ t('admin.orderProfilePublishCheck.xfaStructureFingerprint') }}</dt><dd>{{ report.xfa_structure_signature_status?.dataset_structure_fingerprint || report.xfa_structure_signature_summary?.dataset_structure_fingerprint || '—' }}</dd></div>
|
||||
<div><dt>{{ t('admin.orderProfilePublishCheck.matcherPolicyVersion') }}</dt><dd>{{ report.matcher_policy_version || (isXfaReport ? report.xfa_structure_signature_status : report.layout_signature_status)?.matcher_policy_version || '—' }}</dd></div>
|
||||
<div><dt>{{ t('admin.orderProfilePublishCheck.signatureStatus') }}</dt><dd :class="`status-${signatureStatusDetail?.status || 'unknown'}`">{{ signatureStatus(signatureStatusDetail?.status) }}</dd></div>
|
||||
<div><dt>{{ t('admin.orderProfilePublishCheck.signatureSampleCount') }}</dt><dd>{{ signatureStatusDetail?.source_sample_count ?? '—' }}</dd></div>
|
||||
<div v-for="metric in signatureIdentityMetrics" :key="metric.label"><dt>{{ metric.label }}</dt><dd>{{ metric.value }}</dd></div>
|
||||
<div><dt>{{ t('admin.orderProfilePublishCheck.matcherPolicyVersion') }}</dt><dd>{{ report.matcher_policy_version || signatureStatusDetail?.matcher_policy_version || '—' }}</dd></div>
|
||||
</dl>
|
||||
</section>
|
||||
|
||||
@@ -266,12 +274,10 @@ onMounted(loadRuns);
|
||||
</dl>
|
||||
</section>
|
||||
|
||||
<section v-if="xfaValidationMetrics" class="card">
|
||||
<section v-if="adapterValidationMetrics.length" class="card">
|
||||
<h3>{{ t('admin.orderProfilePublishCheck.xfaUnifiedMetricsTitle') }}</h3>
|
||||
<dl class="metrics">
|
||||
<div><dt>{{ t('admin.orderProfilePublishCheck.xfaVisualCoverage') }}</dt><dd>{{ formatXfaMetric(xfaValidationMetrics.visual) }}</dd></div>
|
||||
<div><dt>{{ t('admin.orderProfilePublishCheck.xfaMirrorConsistency') }}</dt><dd>{{ formatXfaMetric(xfaValidationMetrics.mirror) }}</dd></div>
|
||||
<div><dt>{{ t('admin.orderProfilePublishCheck.xfaEvidenceRetention') }}</dt><dd>{{ formatXfaMetric(xfaValidationMetrics.evidence) }}</dd></div>
|
||||
<div v-for="metric in adapterValidationMetrics" :key="metric.label"><dt>{{ metric.label }}</dt><dd>{{ formatRate(metric.value) }}</dd></div>
|
||||
</dl>
|
||||
</section>
|
||||
|
||||
|
||||
+57
-125
@@ -17,24 +17,18 @@ import {
|
||||
getOrderDocumentProfileDetail,
|
||||
listOrderProfileBoundSamples,
|
||||
listOrderProfileValidationRuns,
|
||||
previewOrderProfileOrderFieldValues,
|
||||
previewOrderProfileRegion,
|
||||
runOrderProfileCurrentSample,
|
||||
runOrderProfileInstantCheck,
|
||||
createOrderProfileTestSuite,
|
||||
} from '@/features/admin/api/shipping-order-document-profile.api';
|
||||
import type {
|
||||
CoordinateReconstructionPreview,
|
||||
OrderFieldValuePreview,
|
||||
OrderProfileBoundSample,
|
||||
OrderProfileValidationEvidence,
|
||||
OrderProfileValidationEvidenceField,
|
||||
OrderProfileValidationRun,
|
||||
OrderProfileTestSuite,
|
||||
ShippingOrderDocumentProfile,
|
||||
} from '@/features/admin/types/shipping-order-document-profile.types';
|
||||
import {
|
||||
asCoordinateProfileDefinition,
|
||||
isXfaDatasetProfileDefinition,
|
||||
} from '@/features/admin/types/shipping-order-document-profile.types';
|
||||
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
@@ -47,27 +41,24 @@ const executing = ref(false);
|
||||
const leaseToken = ref('');
|
||||
const profile = ref<ShippingOrderDocumentProfile | null>(null);
|
||||
const sample = ref<OrderProfileBoundSample | null>(null);
|
||||
const headerValues = ref<OrderFieldValuePreview[]>([]);
|
||||
const linePreview = ref<CoordinateReconstructionPreview | null>(null);
|
||||
const resultLoading = ref(false);
|
||||
const resultFailed = ref(false);
|
||||
const fieldNames = ref(new Map<string, string>());
|
||||
const sessionId = String(route.query.editorSessionId || '').trim() || crypto.randomUUID();
|
||||
const blindTestSuite = ref<OrderProfileTestSuite | null>(null);
|
||||
const isXfa = computed(() => (
|
||||
!!profile.value
|
||||
&& (profile.value.template_mode === 'xfa_dataset' || isXfaDatasetProfileDefinition(profile.value.definition))
|
||||
));
|
||||
const xfaSummary = computed(() => sampleRun.value?.summary || null);
|
||||
const xfaHeaderFields = computed(() => {
|
||||
const rows = xfaSummary.value?.header_fields;
|
||||
return Array.isArray(rows) ? rows as Array<Record<string, unknown>> : [];
|
||||
const validationEvidence = computed<OrderProfileValidationEvidence | null>(() => {
|
||||
const raw = sampleRun.value?.summary?.validation_evidence;
|
||||
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;
|
||||
const value = raw as Record<string, unknown>;
|
||||
return {
|
||||
header_fields: Array.isArray(value.header_fields) ? value.header_fields as OrderProfileValidationEvidenceField[] : [],
|
||||
lines: Array.isArray(value.lines) ? value.lines as OrderProfileValidationEvidence['lines'] : [],
|
||||
cross_checks: value.cross_checks && typeof value.cross_checks === 'object' && !Array.isArray(value.cross_checks)
|
||||
? value.cross_checks as Record<string, unknown>
|
||||
: {},
|
||||
};
|
||||
});
|
||||
const xfaLines = computed(() => {
|
||||
const rows = xfaSummary.value?.lines;
|
||||
return Array.isArray(rows) ? rows as Array<Record<string, unknown>> : [];
|
||||
});
|
||||
const XFA_CROSS_CHECK_KEYS = [
|
||||
const evidenceHeaderFields = computed(() => validationEvidence.value?.header_fields || []);
|
||||
const evidenceLines = computed(() => validationEvidence.value?.lines || []);
|
||||
const ADAPTER_CROSS_CHECK_KEYS = [
|
||||
'mirror_status',
|
||||
'acroform_status',
|
||||
'line_amount_status',
|
||||
@@ -75,37 +66,32 @@ const XFA_CROSS_CHECK_KEYS = [
|
||||
] as const;
|
||||
|
||||
/**
|
||||
* 从字段预览中取标准化值。
|
||||
* 从统一字段预览中取标准化值。
|
||||
*/
|
||||
function xfaFieldNormalized(
|
||||
fields: Array<Record<string, unknown>>,
|
||||
function evidenceFieldNormalized(
|
||||
fields: OrderProfileValidationEvidenceField[],
|
||||
fieldCode: string,
|
||||
): string {
|
||||
const hit = fields.find((item) => String(item.field_code || '') === fieldCode);
|
||||
return String(hit?.normalized_value ?? '').trim();
|
||||
const hit = fields.find((item) => item.field_code === fieldCode);
|
||||
return (hit?.normalized_value ?? '').trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* 将交叉校验技术状态映射为管理员可读说明(含金额计算过程)。
|
||||
* 将 adapter 交叉校验状态映射为管理员可读说明(含金额计算过程)。
|
||||
*/
|
||||
const xfaCrossCheckEntries = computed(() => {
|
||||
const checks = xfaSummary.value?.cross_checks;
|
||||
const adapterCrossCheckEntries = computed(() => {
|
||||
const checks = validationEvidence.value?.cross_checks;
|
||||
if (!checks || typeof checks !== 'object' || Array.isArray(checks)) return [];
|
||||
const map = checks as Record<string, unknown>;
|
||||
const firstLineFields = Array.isArray(xfaLines.value[0]?.fields)
|
||||
? (xfaLines.value[0].fields as Array<Record<string, unknown>>)
|
||||
: [];
|
||||
const qty = xfaFieldNormalized(firstLineFields, 'quantity');
|
||||
const unitPrice = xfaFieldNormalized(firstLineFields, 'unit_price');
|
||||
const priceUnit = xfaFieldNormalized(firstLineFields, 'price_unit') || '1';
|
||||
const amount = xfaFieldNormalized(firstLineFields, 'amount');
|
||||
const total = xfaFieldNormalized(xfaHeaderFields.value, 'total_amount')
|
||||
|| xfaFieldNormalized(xfaHeaderFields.value, 'order_amount');
|
||||
const lineSum = xfaLines.value.reduce((sum, line) => {
|
||||
const fields = Array.isArray(line.fields)
|
||||
? (line.fields as Array<Record<string, unknown>>)
|
||||
: [];
|
||||
const raw = xfaFieldNormalized(fields, 'amount').replace(/,/g, '');
|
||||
const firstLineFields = evidenceLines.value[0]?.fields || [];
|
||||
const qty = evidenceFieldNormalized(firstLineFields, 'quantity');
|
||||
const unitPrice = evidenceFieldNormalized(firstLineFields, 'unit_price');
|
||||
const amount = evidenceFieldNormalized(firstLineFields, 'amount');
|
||||
const total = evidenceFieldNormalized(evidenceHeaderFields.value, 'total_amount')
|
||||
|| evidenceFieldNormalized(evidenceHeaderFields.value, 'order_amount');
|
||||
const lineSum = evidenceLines.value.reduce((sum, line) => {
|
||||
const fields = line.fields || [];
|
||||
const raw = evidenceFieldNormalized(fields, 'amount').replace(/,/g, '');
|
||||
const n = Number(raw);
|
||||
return Number.isFinite(n) ? sum + n : sum;
|
||||
}, 0);
|
||||
@@ -113,7 +99,7 @@ const xfaCrossCheckEntries = computed(() => {
|
||||
? String(Number(lineSum.toFixed(2)))
|
||||
: amount;
|
||||
|
||||
return XFA_CROSS_CHECK_KEYS
|
||||
return ADAPTER_CROSS_CHECK_KEYS
|
||||
.filter((key) => map[key] != null && String(map[key]).trim() !== '')
|
||||
.map((key) => {
|
||||
const status = String(map[key] ?? '').trim().toLowerCase();
|
||||
@@ -124,10 +110,9 @@ const xfaCrossCheckEntries = computed(() => {
|
||||
);
|
||||
let detail = '';
|
||||
if (key === 'line_amount_status' && qty && unitPrice && amount) {
|
||||
detail = t('admin.orderProfileValidation.xfaAmountFormula', {
|
||||
detail = t('admin.orderProfileValidation.xfaAmountFormulaWithoutPriceUnit', {
|
||||
quantity: qty,
|
||||
unitPrice,
|
||||
priceUnit,
|
||||
amount,
|
||||
});
|
||||
} else if (key === 'total_amount_status' && total && lineSumText) {
|
||||
@@ -149,7 +134,8 @@ const xfaCrossCheckEntries = computed(() => {
|
||||
if (key === 'line_amount_status' && Array.isArray(map.line_amount_failures) && map.line_amount_failures.length) {
|
||||
detail = map.line_amount_failures.map((item) => {
|
||||
const failure = item as Record<string, unknown>;
|
||||
return `#${String(failure.row_index || '-')}: ${String(failure.quantity ?? '-')} × ${String(failure.unit_price ?? '-')} ÷ ${String(failure.price_unit ?? '1')} = ${String(failure.expected_amount ?? '?')},amount=${String(failure.amount ?? '-')}`;
|
||||
const formula = `${String(failure.quantity ?? '-')} × ${String(failure.unit_price ?? '-')}`;
|
||||
return `#${String(failure.row_index || '-')}: ${formula} = ${String(failure.expected_amount ?? '?')},amount=${String(failure.amount ?? '-')}`;
|
||||
}).join(';');
|
||||
}
|
||||
return { key, label, statusLabel, detail, status };
|
||||
@@ -215,47 +201,6 @@ async function loadContext(): Promise<void> {
|
||||
/** Schema 显示名称服务于业务核对;稳定编码仅作为辅助追溯信息保留。 */
|
||||
function fieldName(fieldCode: string): string { return fieldNames.value.get(fieldCode) || fieldCode; }
|
||||
|
||||
/** 使用本次草稿定义重读全部已绑定表头页和明细;XFA 从验证摘要读取字段级结果。 */
|
||||
async function loadReadResults(): Promise<void> {
|
||||
if (!profile.value || !sample.value) return;
|
||||
if (isXfa.value) {
|
||||
// XFA 字段级结果来自 current_sample summary,不请求坐标预览。
|
||||
headerValues.value = [];
|
||||
linePreview.value = null;
|
||||
resultFailed.value = false;
|
||||
return;
|
||||
}
|
||||
if (!sample.value.table_id) return;
|
||||
resultLoading.value = true;
|
||||
resultFailed.value = false;
|
||||
try {
|
||||
const definition = asCoordinateProfileDefinition(profile.value.definition);
|
||||
const pageNos = Array.from(new Set((definition.order_field_layouts || []).map((item) => (
|
||||
item.page_scope === 'exact_page' ? (item.page_no || 1) : 1
|
||||
)))).sort((left, right) => left - right);
|
||||
const pageNo = pageNos[0] || sample.value.table_identity_snapshot?.page_no || 1;
|
||||
let failed = false;
|
||||
try {
|
||||
const headers = await previewOrderProfileOrderFieldValues(
|
||||
sample.value.document_id, profile.value.schema_version_id, pageNo, definition, pageNos,
|
||||
);
|
||||
headerValues.value = headers.fields;
|
||||
} catch {
|
||||
headerValues.value = [];
|
||||
failed = true;
|
||||
}
|
||||
try {
|
||||
linePreview.value = await previewOrderProfileRegion(
|
||||
profileId, sample.value.document_id, sample.value.table_id || '', definition,
|
||||
);
|
||||
} catch {
|
||||
linePreview.value = null;
|
||||
failed = true;
|
||||
}
|
||||
resultFailed.value = failed;
|
||||
} finally { resultLoading.value = false; }
|
||||
}
|
||||
|
||||
/** 为本页获取单写者租约,避免验证或发布检查绕过草稿编辑保护。 */
|
||||
async function ensureLease(): Promise<boolean> {
|
||||
if (leaseToken.value) return true;
|
||||
@@ -284,7 +229,6 @@ async function validateCurrentDraft(): Promise<void> {
|
||||
// uses the same binding and definition that the server just validated.
|
||||
await loadContext();
|
||||
await loadBlindTestSuite();
|
||||
await loadReadResults();
|
||||
message.success(t('admin.orderProfileValidation.completed'));
|
||||
} catch (error) { report(error); } finally { executing.value = false; }
|
||||
}
|
||||
@@ -307,7 +251,6 @@ function backToEditor(): void {
|
||||
|
||||
onMounted(async () => {
|
||||
await Promise.all([loadRuns(), loadContext()]);
|
||||
await loadReadResults();
|
||||
if (canStartBlindTest.value) {
|
||||
await loadBlindTestSuite();
|
||||
}
|
||||
@@ -353,18 +296,14 @@ onMounted(async () => {
|
||||
</section>
|
||||
|
||||
<section v-if="profile && sample" class="results" :aria-label="t('admin.orderProfileValidation.resultsTitle')">
|
||||
<div class="results-heading"><div><h2>{{ t('admin.orderProfileValidation.resultsTitle') }}</h2><p>{{ isXfa ? t('admin.orderProfileValidation.xfaResultsHint') : t('admin.orderProfileValidation.resultsHint') }}</p></div><button v-if="!isXfa" type="button" class="btn-secondary btn-sm" :disabled="resultLoading" @click="loadReadResults">{{ t('admin.orderProfileValidation.refreshResults') }}</button></div>
|
||||
<template v-if="isXfa">
|
||||
<div class="results-heading"><div><h2>{{ t('admin.orderProfileValidation.resultsTitle') }}</h2><p>{{ t('admin.orderProfileValidation.resultsHint') }}</p></div></div>
|
||||
<template v-if="validationEvidence">
|
||||
<dl class="header-results">
|
||||
<div><dt>{{ t('admin.orderProfileValidation.xfaTemplateMode') }}</dt><dd>XFA</dd></div>
|
||||
<div><dt>{{ t('admin.orderProfileValidation.xfaLineRows') }}</dt><dd>{{ xfaSummary?.line_row_count ?? '-' }}</dd></div>
|
||||
<div><dt>{{ t('admin.orderProfileValidation.xfaCrossChecks') }}</dt><dd>{{ Array.isArray(xfaSummary?.cross_check_failures) && xfaSummary.cross_check_failures.length ? xfaSummary.cross_check_failures.join(', ') : t('admin.orderProfileValidation.xfaCrossChecksPassed') }}</dd></div>
|
||||
<div v-if="adapterCrossCheckEntries.length"><dt>{{ t('admin.orderProfileValidation.xfaCrossCheckStatus') }}</dt><dd>{{ adapterCrossCheckEntries.length }}</dd></div>
|
||||
</dl>
|
||||
|
||||
<h3>{{ t('admin.orderProfileValidation.xfaCrossCheckStatus') }}</h3>
|
||||
<dl v-if="xfaCrossCheckEntries.length" class="header-results">
|
||||
<dl v-if="adapterCrossCheckEntries.length" class="header-results">
|
||||
<div
|
||||
v-for="item in xfaCrossCheckEntries"
|
||||
v-for="item in adapterCrossCheckEntries"
|
||||
:key="item.key"
|
||||
:class="`field-${item.status === 'matched' || item.status === 'passed' || item.status === 'skipped' ? 'passed' : 'failed'}`"
|
||||
>
|
||||
@@ -374,51 +313,44 @@ onMounted(async () => {
|
||||
</div>
|
||||
</dl>
|
||||
|
||||
<h3>{{ t('admin.orderProfileValidation.xfaHeaderFields') }}</h3>
|
||||
<dl v-if="xfaHeaderFields.length" class="header-results">
|
||||
<h3>{{ t('admin.orderProfileValidation.headerResults') }}</h3>
|
||||
<dl v-if="evidenceHeaderFields.length" class="header-results">
|
||||
<div
|
||||
v-for="field in xfaHeaderFields"
|
||||
v-for="field in evidenceHeaderFields"
|
||||
:key="String(field.field_id || field.field_code)"
|
||||
:class="`field-${String(field.status || 'missing')}`"
|
||||
>
|
||||
<dt>{{ fieldName(String(field.field_code || '')) }}</dt>
|
||||
<dd class="field-code">{{ field.field_code }}</dd>
|
||||
<dd>{{ t('admin.orderProfileValidation.xfaRawValue') }}:{{ field.raw_value || t('admin.orderProfileValidation.noValue') }}</dd>
|
||||
<dd>{{ t('admin.orderProfileValidation.xfaNormalized') }}:{{ field.normalized_value || t('admin.orderProfileValidation.noValue') }}</dd>
|
||||
<dd>{{ t('admin.orderProfileValidation.read') }}:{{ field.normalized_value || t('admin.orderProfileValidation.noValue') }}</dd>
|
||||
<dd v-if="field.raw_value && field.raw_value !== field.normalized_value" class="field-code">{{ field.raw_value }}</dd>
|
||||
<dd v-if="field.issues.length" class="field-issues">{{ field.issues.join(', ') }}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
<p v-else>{{ t('admin.orderProfileValidation.xfaNoFieldPreview') }}</p>
|
||||
<p v-else>{{ t('admin.orderProfileValidation.noHeaderResults') }}</p>
|
||||
|
||||
<h3>{{ t('admin.orderProfileValidation.xfaLineFields') }}</h3>
|
||||
<div v-if="xfaLines.length" class="line-results">
|
||||
<article v-for="line in xfaLines" :key="String(line.row_index)" class="xfa-line-card">
|
||||
<h3>{{ t('admin.orderProfileValidation.lineResults') }}</h3>
|
||||
<div v-if="evidenceLines.length" class="line-results">
|
||||
<article v-for="line in evidenceLines" :key="String(line.row_index)" class="xfa-line-card">
|
||||
<h4>#{{ Number(line.row_index) + 1 }}</h4>
|
||||
<dl class="header-results">
|
||||
<div
|
||||
v-for="field in (Array.isArray(line.fields) ? line.fields : [])"
|
||||
v-for="field in line.fields"
|
||||
:key="String(field.field_id || field.field_code)"
|
||||
:class="`field-${String(field.status || 'missing')}`"
|
||||
>
|
||||
<dt>{{ fieldName(String(field.field_code || '')) }}</dt>
|
||||
<dd class="field-code">{{ field.field_code }}</dd>
|
||||
<dd>{{ t('admin.orderProfileValidation.xfaRawValue') }}:{{ field.raw_value || t('admin.orderProfileValidation.noValue') }}</dd>
|
||||
<dd>{{ t('admin.orderProfileValidation.xfaNormalized') }}:{{ field.normalized_value || t('admin.orderProfileValidation.noValue') }}</dd>
|
||||
<dd>{{ t('admin.orderProfileValidation.read') }}:{{ field.normalized_value || t('admin.orderProfileValidation.noValue') }}</dd>
|
||||
<dd v-if="field.raw_value && field.raw_value !== field.normalized_value" class="field-code">{{ field.raw_value }}</dd>
|
||||
<dd v-if="field.issues.length" class="field-issues">{{ field.issues.join(', ') }}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
</article>
|
||||
</div>
|
||||
<p v-else>{{ t('admin.orderProfileValidation.xfaNoFieldPreview') }}</p>
|
||||
</template>
|
||||
<p v-else-if="resultLoading">{{ t('admin.orderProfileValidation.resultsLoading') }}</p>
|
||||
<p v-else-if="resultFailed" class="result-error">{{ t('admin.orderProfileValidation.resultsFailed') }}</p>
|
||||
<template v-else>
|
||||
<h3>{{ t('admin.orderProfileValidation.headerResults') }}</h3>
|
||||
<dl v-if="headerValues.length" class="header-results"><div v-for="field in headerValues" :key="`${field.field_id}:${field.page_no || 0}`" :class="`field-${field.status}`"><dt>{{ fieldName(field.field_code) }}</dt><dd class="field-code">{{ field.field_code }} · P{{ field.page_no || '-' }}</dd><dd>{{ field.value || t('admin.orderProfileValidation.noValue') }}</dd><dd v-if="field.issues.length" class="field-issues">{{ field.issues.join(', ') }}</dd></div></dl>
|
||||
<p v-else>{{ t('admin.orderProfileValidation.noHeaderResults') }}</p>
|
||||
<h3>{{ t('admin.orderProfileValidation.lineResults') }}</h3>
|
||||
<div v-if="linePreview?.rows?.length" class="line-results"><table><thead><tr><th v-for="field in linePreview.rows[0]" :key="field"><span>{{ fieldName(field) }}</span><small>{{ field }}</small></th><th>{{ t('admin.orderProfileValidation.rowStatus') }}</th></tr></thead><tbody><tr v-for="(row, index) in linePreview.rows.slice(1)" :key="index" :class="linePreview.row_roles[index + 1] === 'deleted' ? 'deleted-row' : ''"><td v-for="(value, cellIndex) in row" :key="cellIndex">{{ value || t('admin.orderProfileValidation.noValue') }}</td><td>{{ linePreview.row_roles[index + 1] === 'deleted' ? t('admin.orderProfileValidation.deleted') : t('admin.orderProfileValidation.read') }}</td></tr></tbody></table></div>
|
||||
<p v-else>{{ t('admin.orderProfileValidation.noLineResults') }}</p>
|
||||
</template>
|
||||
<p v-else class="result-error">{{ t('admin.orderProfileValidation.resultsFailed') }}</p>
|
||||
</section>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
-394
@@ -1,394 +0,0 @@
|
||||
/**
|
||||
* features/admin/modules/shipping-order-document-profiles/OrderProfileXfaWorkbench.spec.ts
|
||||
* 用途:冒烟验证弃用薄包装与 useOrderProfileXfaDesk 默认 synthetic / dirty 契约。
|
||||
* 依赖:Vitest、@vue/test-utils、OrderProfileXfaWorkbench、useOrderProfileXfaDesk。
|
||||
* 逻辑:不再断言三栏 datasets 左栏;断言 desk 可加载且默认原生 PDF 画布。
|
||||
*/
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { mount, flushPromises } from '@vue/test-utils';
|
||||
import { createI18n } from 'vue-i18n';
|
||||
import { defineComponent, h, nextTick } from 'vue';
|
||||
import OrderProfileXfaWorkbench from './OrderProfileXfaWorkbench.vue';
|
||||
import { useOrderProfileXfaDesk } from './composables/useOrderProfileXfaDesk';
|
||||
|
||||
const { saveDraftMock, splitPreviewMock, detailDefinition } = vi.hoisted(() => ({
|
||||
saveDraftMock: vi.fn(),
|
||||
splitPreviewMock: vi.fn(),
|
||||
detailDefinition: { value: null as Record<string, unknown> | null },
|
||||
}));
|
||||
|
||||
const defaultProps = {
|
||||
profileId: 52,
|
||||
leaseToken: 'lease',
|
||||
saveState: 'saved' as const,
|
||||
editorSessionId: 'editor-session',
|
||||
};
|
||||
|
||||
const baseDefinition = {
|
||||
template_mode: 'xfa_dataset' as const,
|
||||
source_contract: {
|
||||
template_packet_checksum: 'sha256:tpl',
|
||||
dataset_structure_fingerprint: 'sha256:fp',
|
||||
dataset_root_path: '/data',
|
||||
authoritative_line_collection_path: '/data/ITEMS/DATA',
|
||||
mirror_collection_paths: [],
|
||||
},
|
||||
header_mappings: [],
|
||||
line_mapping: { row_path: '/data/ITEMS/DATA', fields: [] },
|
||||
cross_checks: {
|
||||
acroform_enabled: true,
|
||||
mirror_collection_policy: 'must_match_when_present' as const,
|
||||
line_amount_formula: 'quantity_times_unit_price' as const,
|
||||
total_amount_policy: 'must_equal_line_sum' as const,
|
||||
},
|
||||
split_rules: [],
|
||||
bindings: [],
|
||||
};
|
||||
|
||||
vi.mock('vue-router', () => ({
|
||||
useRoute: () => ({ params: { profileId: '52', profileCode: 'ODP-TEST' }, query: {} }),
|
||||
useRouter: () => ({ push: vi.fn() }),
|
||||
}));
|
||||
|
||||
vi.mock('@/shared/composables/useMessage', () => ({
|
||||
useMessage: () => ({ success: vi.fn(), error: vi.fn(), info: vi.fn() }),
|
||||
}));
|
||||
|
||||
vi.mock('@/features/admin/api/shipping-order-document-profile.api', () => ({
|
||||
getOrderDocumentProfileDetail: vi.fn(async () => ({
|
||||
id: 52,
|
||||
profile_code: 'ODP-TEST',
|
||||
display_name: 'Fox PO',
|
||||
schema_version_id: 1,
|
||||
lock_version: 1,
|
||||
template_mode: 'xfa_dataset',
|
||||
definition: structuredClone(detailDefinition.value || baseDefinition),
|
||||
})),
|
||||
listOrderProfileBoundSamples: vi.fn(async () => [{ document_id: 85, sample_role: 'annotation' }]),
|
||||
getOrderProfileSampleXfaFieldTree: vi.fn(async () => ({
|
||||
tree: {
|
||||
path_id: 'root-data', local_name: 'data', data_path_hash: 'h0', depth: 0, cardinality: 'one',
|
||||
is_leaf: false, is_collection_candidate: false, children: [
|
||||
{
|
||||
path_id: 'invoiced-to-path', local_name: 'INVOICED_TO', data_path_hash: 'hh', depth: 1, cardinality: 'one',
|
||||
is_leaf: true, sample_value_display: 'Cloud Network', display_policy: 'full',
|
||||
},
|
||||
{
|
||||
path_id: 'items-data', local_name: 'DATA', data_path_hash: 'h', depth: 1, cardinality: 'many',
|
||||
is_leaf: false, is_collection_candidate: true, children: [{
|
||||
path_id: 'material-path', local_name: 'MATNR', data_path_hash: 'h2', depth: 2, cardinality: 'one',
|
||||
is_leaf: true, sample_value_display: 'TEMP-S', display_policy: 'full',
|
||||
}],
|
||||
},
|
||||
],
|
||||
},
|
||||
})),
|
||||
getOrderProfileSampleXfaCollections: vi.fn(async () => ({
|
||||
collection_candidates: [{ path_id: 'items-data', collection_path_hash: 'h', row_count: 1 }],
|
||||
})),
|
||||
authorizeOrderProfilePreviewPages: vi.fn(async () => ({
|
||||
document_id: 85,
|
||||
page_count: 1,
|
||||
pages: [{ page_no: 1, preview_token: 'token' }],
|
||||
expires_in_seconds: 60,
|
||||
})),
|
||||
requestOrderProfileSampleXfaSyntheticPreview: vi.fn(async () => ({
|
||||
document_id: 85,
|
||||
identity: {
|
||||
document_id: 85,
|
||||
layout_version_id: 1,
|
||||
structure_analysis_id: 1,
|
||||
source_content_hash: 'a'.repeat(64),
|
||||
template_packet_checksum: 't',
|
||||
datasets_packet_checksum: 'd',
|
||||
dataset_structure_fingerprint: 'f',
|
||||
preview_render_checksum: 'r'.repeat(64),
|
||||
render_mode: 'xfa_dataset_preview',
|
||||
renderer_version: 'hxops.xfa_static_preview.v1',
|
||||
page_count: 1,
|
||||
},
|
||||
status: 'ready',
|
||||
render_mode: 'xfa_dataset_preview',
|
||||
renderer_version: 'hxops.xfa_static_preview.v1',
|
||||
preview_render_checksum: 'r'.repeat(64),
|
||||
page_count: 1,
|
||||
pages: [{ page_no: 1, preview_token: 'synth-token' }],
|
||||
expires_in_seconds: 60,
|
||||
cache_hit: false,
|
||||
})),
|
||||
listOrderProfileSampleXfaSyntheticPreviewPages: vi.fn(),
|
||||
enqueueOrderProfileXfaOcrAutomark: vi.fn(async () => ({ job_id: 9, status: 'queued' })),
|
||||
getOrderProfileXfaOcrAutomarkJob: vi.fn(async () => ({
|
||||
job_id: 9,
|
||||
status: 'succeeded',
|
||||
suggestions: [],
|
||||
preview_render_checksum: 'r'.repeat(64),
|
||||
})),
|
||||
acceptOrderProfileXfaOcrAutomarkSuggestion: vi.fn(),
|
||||
rejectOrderProfileXfaOcrAutomarkSuggestion: vi.fn(),
|
||||
suggestOrderProfileXfaUnifiedMapping: vi.fn(),
|
||||
acquireOrderDocumentProfileEditLease: vi.fn(async () => ({ lease_token: 'lease', expires_at: new Date().toISOString() })),
|
||||
renewOrderDocumentProfileEditLease: vi.fn(),
|
||||
releaseOrderDocumentProfileEditLease: vi.fn(),
|
||||
saveOrderDocumentProfileDraft: (...args: unknown[]) => saveDraftMock(...args),
|
||||
previewOrderProfileSampleXfaSplitRules: (...args: unknown[]) => splitPreviewMock(...args),
|
||||
previewOrderProfileSampleXfaValue: vi.fn(),
|
||||
confirmOrderProfileXfaVisualBinding: vi.fn(),
|
||||
rejectOrderProfileXfaVisualBinding: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('@/features/admin/api/shipping-order-schema.api', () => ({
|
||||
getShippingOrderSchemaState: vi.fn(async () => ({
|
||||
versions: [{
|
||||
id: 1,
|
||||
definition: {
|
||||
fields: [{
|
||||
field_id: 'f1', field_code: 'customer_po_no', scope: 'header', display_name: 'PO', required: true,
|
||||
enabled: true, aliases: [], normalizer_key: 'trim', validator_keys: [], enum_options: [],
|
||||
evidence_policy: { required: false, source_precedence: [], conflict_policy: 'fail', allow_single_source: true },
|
||||
comparator_key: 'exact',
|
||||
}],
|
||||
},
|
||||
}],
|
||||
})),
|
||||
}));
|
||||
|
||||
describe('OrderProfileXfaWorkbench (deprecated thin wrapper)', () => {
|
||||
const i18n = createI18n({
|
||||
legacy: false,
|
||||
locale: 'zh',
|
||||
messages: { zh: { common: { close: '关闭' }, admin: { shippingOrderProfiles: { xfaWorkbench: { loading: '加载中' } } } } },
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
detailDefinition.value = structuredClone(baseDefinition);
|
||||
saveDraftMock.mockReset();
|
||||
splitPreviewMock.mockReset();
|
||||
// Canvas-related absolute URL safety: relative /api fetch must not throw in jsdom.
|
||||
vi.stubGlobal('fetch', vi.fn(async (input: RequestInfo | URL) => {
|
||||
const url = String(input);
|
||||
expect(url.startsWith('/') || url.startsWith('http')).toBe(true);
|
||||
return {
|
||||
ok: true,
|
||||
blob: async () => new Blob(['png'], { type: 'image/png' }),
|
||||
};
|
||||
}));
|
||||
});
|
||||
|
||||
const mountPage = async () => {
|
||||
const wrapper = mount(OrderProfileXfaWorkbench, {
|
||||
props: defaultProps,
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
for (let i = 0; i < 30; i += 1) {
|
||||
await flushPromises();
|
||||
await nextTick();
|
||||
if (wrapper.find('[data-testid="xfa-thin-canvas"]').exists()) break;
|
||||
}
|
||||
return wrapper;
|
||||
};
|
||||
|
||||
it('mounts thin deprecated desk without three-column left datasets tree', async () => {
|
||||
const wrapper = await mountPage();
|
||||
expect(wrapper.find('[data-testid="xfa-workbench-deprecated"]').exists()).toBe(true);
|
||||
expect(wrapper.find('.xfa-workbench__desk').exists()).toBe(true);
|
||||
expect(wrapper.find('.xfa-workbench__left').exists()).toBe(false);
|
||||
expect(wrapper.find('.xfa-workbench__panel').exists()).toBe(false);
|
||||
}, 15000);
|
||||
|
||||
it('defaults to native preview mode after load', async () => {
|
||||
const wrapper = await mountPage();
|
||||
const vm = wrapper.vm as unknown as { getDesk: () => { previewMode: string; syntheticPreviewStatus: string } };
|
||||
const desk = vm.getDesk();
|
||||
expect(desk.previewMode).toBe('native');
|
||||
expect(['ready', 'loading', 'unavailable', 'failed', 'stale', 'idle']).toContain(desk.syntheticPreviewStatus);
|
||||
}, 15000);
|
||||
|
||||
it('emits dirty-change when local definition diverges from saved snapshot', async () => {
|
||||
const wrapper = await mountPage();
|
||||
expect(wrapper.emitted('dirty-change')?.[0]).toEqual([false]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('useOrderProfileXfaDesk', () => {
|
||||
beforeEach(() => {
|
||||
detailDefinition.value = structuredClone(baseDefinition);
|
||||
vi.stubGlobal('fetch', vi.fn(async () => ({
|
||||
ok: true,
|
||||
blob: async () => new Blob(['png'], { type: 'image/png' }),
|
||||
})));
|
||||
});
|
||||
|
||||
it('demotes confirmed visual bindings when collections are reconfirmed', async () => {
|
||||
detailDefinition.value = {
|
||||
...structuredClone(baseDefinition),
|
||||
bindings: [{
|
||||
binding_id: 'b1',
|
||||
field_id: 'f1',
|
||||
field_code: 'customer_po_no',
|
||||
scope: 'header',
|
||||
value_binding: { type: 'xfa_dataset', path_id: 'invoiced-to-path', data_path: null },
|
||||
visual_binding: {
|
||||
page_no: 1,
|
||||
normalized_bbox: { x0: 0.1, y0: 0.1, x1: 0.2, y1: 0.2 },
|
||||
source: 'user_drawn',
|
||||
status: 'confirmed',
|
||||
region_kind: 'field',
|
||||
confirmed_on: 'xfa_dataset_preview',
|
||||
preview_render_checksum: 'r'.repeat(64),
|
||||
},
|
||||
}],
|
||||
};
|
||||
|
||||
let desk!: ReturnType<typeof useOrderProfileXfaDesk>;
|
||||
const Host = defineComponent({
|
||||
setup() {
|
||||
desk = useOrderProfileXfaDesk({
|
||||
profileId: 52,
|
||||
leaseToken: 'lease',
|
||||
saveState: 'saved',
|
||||
editorSessionId: 'sess',
|
||||
enabled: true,
|
||||
});
|
||||
return () => h('div');
|
||||
},
|
||||
});
|
||||
mount(Host, {
|
||||
global: {
|
||||
plugins: [createI18n({ legacy: false, locale: 'zh', messages: { zh: { admin: { shippingOrderProfiles: {
|
||||
xfaWorkbench: { blocker: { authoritative_collection_required: 'need auth' }, loadFailed: 'fail' },
|
||||
xfaDesk: { collectionsReconfirmedHint: 'ok' },
|
||||
xfaAutoMark: { enqueueFailed: 'e', jobFailed: 'j' },
|
||||
} } } } })],
|
||||
},
|
||||
});
|
||||
|
||||
for (let i = 0; i < 40; i += 1) {
|
||||
await flushPromises();
|
||||
if (!desk.loading.value && desk.definition.value) break;
|
||||
}
|
||||
expect(desk.definition.value).toBeTruthy();
|
||||
expect(desk.loadError.value).toBe(false);
|
||||
|
||||
desk.draftAuthoritativePathId.value = 'items-data';
|
||||
desk.draftMirrorPathIds.value = [];
|
||||
desk.confirmReconfirmCollections();
|
||||
expect(desk.authoritativePathId.value).toBe('items-data');
|
||||
expect(desk.definition.value?.bindings?.[0]?.visual_binding.status).toBe('suggested');
|
||||
}, 15000);
|
||||
|
||||
it('duplicateSelectedBinding clears path/schema and keeps geometry', async () => {
|
||||
detailDefinition.value = {
|
||||
...structuredClone(baseDefinition),
|
||||
bindings: [{
|
||||
binding_id: 'b1',
|
||||
field_id: 'f1',
|
||||
field_code: 'customer_po_no',
|
||||
scope: 'header',
|
||||
value_binding: { type: 'xfa_dataset', path_id: 'invoiced-to-path', data_path: null },
|
||||
visual_binding: {
|
||||
page_no: 1,
|
||||
normalized_bbox: { x0: 0.1, y0: 0.1, x1: 0.2, y1: 0.2 },
|
||||
source: 'user_drawn',
|
||||
status: 'confirmed',
|
||||
region_kind: 'header',
|
||||
confirmed_on: 'xfa_dataset_preview',
|
||||
},
|
||||
}],
|
||||
};
|
||||
|
||||
let desk!: ReturnType<typeof useOrderProfileXfaDesk>;
|
||||
const Host = defineComponent({
|
||||
setup() {
|
||||
desk = useOrderProfileXfaDesk({
|
||||
profileId: 52,
|
||||
leaseToken: 'lease',
|
||||
saveState: 'saved',
|
||||
editorSessionId: 'sess',
|
||||
enabled: true,
|
||||
});
|
||||
return () => h('div');
|
||||
},
|
||||
});
|
||||
mount(Host, {
|
||||
global: {
|
||||
plugins: [createI18n({ legacy: false, locale: 'zh', messages: { zh: { admin: { shippingOrderProfiles: {
|
||||
xfaWorkbench: { loadFailed: 'fail' },
|
||||
xfaAutoMark: { enqueueFailed: 'e', jobFailed: 'j' },
|
||||
} } } } })],
|
||||
},
|
||||
});
|
||||
for (let i = 0; i < 40; i += 1) {
|
||||
await flushPromises();
|
||||
if (!desk.loading.value && desk.definition.value) break;
|
||||
}
|
||||
desk.selectedBindingId.value = 'b1';
|
||||
desk.duplicateSelectedBinding();
|
||||
const copy = desk.definition.value?.bindings?.find((item) => item.binding_id !== 'b1');
|
||||
expect(copy).toBeTruthy();
|
||||
expect(copy?.field_code).toBe('');
|
||||
expect(copy?.value_binding.path_id).toBe('');
|
||||
expect(copy?.visual_binding.status).toBe('suggested');
|
||||
expect((copy?.visual_binding as { region_kind?: string }).region_kind).toBe('header');
|
||||
expect(copy?.visual_binding.normalized_bbox).toEqual({ x0: 0.1, y0: 0.1, x1: 0.2, y1: 0.2 });
|
||||
}, 15000);
|
||||
|
||||
it('annotationDisabled when native pages missing; datasets hidden for anchor', async () => {
|
||||
detailDefinition.value = structuredClone(baseDefinition);
|
||||
let desk!: ReturnType<typeof useOrderProfileXfaDesk>;
|
||||
const Host = defineComponent({
|
||||
setup() {
|
||||
desk = useOrderProfileXfaDesk({
|
||||
profileId: 52,
|
||||
leaseToken: 'lease',
|
||||
saveState: 'saved',
|
||||
editorSessionId: 'sess',
|
||||
enabled: true,
|
||||
});
|
||||
return () => h('div');
|
||||
},
|
||||
});
|
||||
mount(Host, {
|
||||
global: {
|
||||
plugins: [createI18n({ legacy: false, locale: 'zh', messages: { zh: { admin: { shippingOrderProfiles: {
|
||||
xfaWorkbench: { loadFailed: 'fail' },
|
||||
xfaAutoMark: { enqueueFailed: 'e', jobFailed: 'j' },
|
||||
} } } } })],
|
||||
},
|
||||
});
|
||||
for (let i = 0; i < 40; i += 1) {
|
||||
await flushPromises();
|
||||
if (!desk.loading.value && desk.definition.value) break;
|
||||
}
|
||||
// 原生页授权就绪后,synthetic 失败不应禁标注。
|
||||
desk.pageGrants.value = [{ page_no: 1, preview_token: 'token' }];
|
||||
desk.pageGrant.value = { page_no: 1, preview_token: 'token' };
|
||||
desk.pageLoadError.value = null;
|
||||
desk.syntheticPreviewStatus.value = 'unavailable';
|
||||
expect(desk.annotationDisabled.value).toBe(false);
|
||||
|
||||
desk.pageGrant.value = null;
|
||||
desk.pageGrants.value = [];
|
||||
expect(desk.annotationDisabled.value).toBe(true);
|
||||
|
||||
desk.definition.value = {
|
||||
...desk.definition.value!,
|
||||
bindings: [{
|
||||
binding_id: 'anchor-1',
|
||||
field_id: 'a1',
|
||||
field_code: '',
|
||||
scope: 'header',
|
||||
value_binding: { type: 'xfa_dataset', path_id: '', data_path: null },
|
||||
visual_binding: {
|
||||
page_no: 1,
|
||||
normalized_bbox: { x0: 0.1, y0: 0.1, x1: 0.2, y1: 0.2 },
|
||||
source: 'user_drawn',
|
||||
status: 'suggested',
|
||||
region_kind: 'anchor',
|
||||
},
|
||||
}],
|
||||
};
|
||||
desk.selectedBindingId.value = 'anchor-1';
|
||||
expect(desk.showDatasetsSection.value).toBe(false);
|
||||
}, 15000);
|
||||
});
|
||||
-67
@@ -1,67 +0,0 @@
|
||||
<!--
|
||||
features/admin/modules/shipping-order-document-profiles/OrderProfileXfaWorkbench.vue
|
||||
用途:【已弃用】历史三栏 XFA Workbench 薄包装;正式 UI 由 OrderProfileEditorPage + useOrderProfileXfaDesk 承载。
|
||||
依赖:useOrderProfileXfaDesk。
|
||||
逻辑:仅暴露 saveDraft/reload 供遗留调用或冒烟测试;不再渲染独立三栏壳。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, reactive } from 'vue';
|
||||
import { useOrderProfileXfaDesk } from './composables/useOrderProfileXfaDesk';
|
||||
|
||||
const props = defineProps<{
|
||||
profileId: number;
|
||||
leaseToken: string;
|
||||
saveState: 'saved' | 'saving' | 'failed' | 'readonly';
|
||||
editorSessionId: string;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
'dirty-change': [dirty: boolean];
|
||||
'save-request': [];
|
||||
'save-state-change': [state: 'saved' | 'saving' | 'failed' | 'readonly'];
|
||||
'profile-saved': [payload: { lockVersion: number }];
|
||||
'validate-blocked-change': [blocked: boolean];
|
||||
}>();
|
||||
|
||||
/**
|
||||
* 薄包装:复用统一 desk composable,不再自建三栏布局。
|
||||
*/
|
||||
const desk = reactive(useOrderProfileXfaDesk({
|
||||
profileId: computed(() => props.profileId),
|
||||
leaseToken: computed(() => props.leaseToken),
|
||||
saveState: computed(() => props.saveState),
|
||||
editorSessionId: computed(() => props.editorSessionId),
|
||||
enabled: computed(() => props.profileId > 0),
|
||||
onDirtyChange: (dirty) => emit('dirty-change', dirty),
|
||||
onSaveStateChange: (state) => emit('save-state-change', state),
|
||||
onProfileSaved: (payload) => emit('profile-saved', payload),
|
||||
onValidateBlockedChange: (blocked) => emit('validate-blocked-change', blocked),
|
||||
onSaveRequest: () => emit('save-request'),
|
||||
}));
|
||||
|
||||
defineExpose({
|
||||
saveDraft: () => desk.saveDraft(),
|
||||
reload: () => desk.load(),
|
||||
/** 测试用:暴露 desk 快照。 */
|
||||
getDesk: () => desk,
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="xfa-workbench xfa-workbench--deprecated" data-testid="xfa-workbench-deprecated">
|
||||
<p v-if="desk.loading" class="loading">loading</p>
|
||||
<p v-else-if="desk.loadError" class="error">load-failed</p>
|
||||
<div v-else-if="desk.definition" class="xfa-workbench__desk xfa-workbench__desk--thin">
|
||||
<main class="xfa-workbench__canvas" data-testid="xfa-thin-canvas">
|
||||
<span>{{ desk.previewMode }}</span>
|
||||
<span>{{ desk.syntheticPreviewStatus }}</span>
|
||||
</main>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.xfa-workbench { display: flex; flex-direction: column; gap: 8px; }
|
||||
.xfa-workbench__desk--thin { display: block; }
|
||||
.loading, .error { padding: 16px; }
|
||||
</style>
|
||||
+100
@@ -0,0 +1,100 @@
|
||||
/**
|
||||
* features/admin/modules/shipping-order-document-profiles/canvasActions.utils.spec.ts
|
||||
* 用途:验证共享画布操作 adapter 的能力选择与事件转发。
|
||||
* 依赖:Vitest、canvasActions.utils。
|
||||
* 逻辑:编辑页按 Profile capability 选择 adapter;画布事件不再分别编排 XFA 与坐标流程。
|
||||
*/
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import {
|
||||
resolveCanvasActions,
|
||||
resolveDeskAdapter,
|
||||
resolveSharedCanvasDocument,
|
||||
resolveValueAdapterKey,
|
||||
type OrderProfileCanvasActions,
|
||||
} from './canvasActions.utils';
|
||||
|
||||
function actions(): OrderProfileCanvasActions {
|
||||
return {
|
||||
create: vi.fn(), select: vi.fn(), dragStart: vi.fn(), dragEnd: vi.fn(), change: vi.fn(),
|
||||
undo: vi.fn(), redo: vi.fn(), duplicate: vi.fn(), remove: vi.fn(), page: vi.fn(), draw: vi.fn(),
|
||||
};
|
||||
}
|
||||
|
||||
describe('resolveCanvasActions', () => {
|
||||
it('selects one capability adapter for the entire shared canvas interaction', () => {
|
||||
const coordinate = actions();
|
||||
const xfa = actions();
|
||||
|
||||
const active = resolveCanvasActions({
|
||||
adapterKey: 'xfa_dataset', adapters: { coordinate_ocr: coordinate, xfa_dataset: xfa },
|
||||
});
|
||||
active.select('binding-1');
|
||||
active.undo();
|
||||
active.page(2);
|
||||
|
||||
expect(xfa.select).toHaveBeenCalledWith('binding-1');
|
||||
expect(xfa.undo).toHaveBeenCalledOnce();
|
||||
expect(xfa.page).toHaveBeenCalledWith(2);
|
||||
expect(coordinate.select).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('selects one desk adapter before shared save and sample lifecycle work begins', () => {
|
||||
const coordinate = { kind: 'coordinate', save: vi.fn() };
|
||||
const xfa = { kind: 'xfa', save: vi.fn() };
|
||||
|
||||
const active = resolveDeskAdapter({
|
||||
adapterKey: 'xfa_dataset', adapters: { coordinate_ocr: coordinate, xfa_dataset: xfa },
|
||||
});
|
||||
|
||||
expect(active).toBe(xfa);
|
||||
});
|
||||
|
||||
it('uses one editor-owned preview context without branching on the value adapter', () => {
|
||||
expect(resolveSharedCanvasDocument({
|
||||
documentId: 12,
|
||||
mainTableId: '',
|
||||
sampleTableId: 'table-1',
|
||||
})).toEqual({ documentId: 12, tableId: 'table-1' });
|
||||
expect(resolveSharedCanvasDocument({
|
||||
documentId: 12,
|
||||
mainTableId: 'visual-main-table',
|
||||
sampleTableId: 'table-1',
|
||||
})).toEqual({ documentId: 12, tableId: 'visual-main-table' });
|
||||
});
|
||||
|
||||
it('keeps the shared save shell independent from XFA confirmation-token naming', async () => {
|
||||
const saved = vi.fn().mockResolvedValue(true);
|
||||
const adapter = {
|
||||
hasUnsavedChanges: true,
|
||||
skipUnchangedManualSave: true,
|
||||
canSave: true,
|
||||
canValidate: false,
|
||||
exportDefinition: vi.fn(() => ({
|
||||
template_mode: 'xfa_dataset',
|
||||
source_contract: {},
|
||||
header_mappings: [],
|
||||
line_mapping: { fields: [] },
|
||||
cross_checks: [],
|
||||
main_table_id: 'table-1',
|
||||
bindings: [],
|
||||
})),
|
||||
buildPayload: vi.fn(() => ({
|
||||
definition: { template_mode: 'xfa_dataset' },
|
||||
splitRuleConfirmationTokens: { path_1: 'token_1' },
|
||||
})),
|
||||
applySavedDraft: saved,
|
||||
};
|
||||
|
||||
const payload = adapter.buildPayload();
|
||||
expect(payload?.splitRuleConfirmationTokens).toEqual({ path_1: 'token_1' });
|
||||
expect(adapter.exportDefinition()).toMatchObject({ template_mode: 'xfa_dataset' });
|
||||
expect(adapter.canValidate).toBe(false);
|
||||
await adapter.applySavedDraft({ id: 1 });
|
||||
expect(saved).toHaveBeenCalledWith({ id: 1 });
|
||||
});
|
||||
|
||||
it('resolves persisted format only at the adapter boundary', () => {
|
||||
expect(resolveValueAdapterKey({ template_mode: 'xfa_dataset' } as any)).toBe('xfa_dataset');
|
||||
expect(resolveValueAdapterKey({ template_mode: 'coordinate' } as any)).toBe('coordinate_ocr');
|
||||
});
|
||||
});
|
||||
+149
@@ -0,0 +1,149 @@
|
||||
/**
|
||||
* features/admin/modules/shipping-order-document-profiles/canvasActions.utils.ts
|
||||
* 用途:为订单模板共享 PDF 画布提供 capability-neutral 的操作接口。
|
||||
* 依赖:OrderProfileEditorPage 的末端值源 adapter。
|
||||
* 逻辑:页面按已持久化的模板能力选择一次 adapter;画布组件与工具栏只调用同一组动作。
|
||||
*/
|
||||
import type { OrderProfileCanvasRegion, OrderProfileRelativeRegion } from '@/features/admin/types/shipping-order-document-profile.types';
|
||||
import type { OrderProfileDefinition } from '@/features/admin/types/shipping-order-document-profile.types';
|
||||
import type { ShippingOrderDocumentProfile } from '@/features/admin/types/shipping-order-document-profile.types';
|
||||
import type { OrderProfileRecognitionResult } from './orderProfileForm.utils';
|
||||
|
||||
/** 共享画布需要的最小动作面;底层可以持有不同 adapter 的持久化载体。 */
|
||||
export interface OrderProfileCanvasActions {
|
||||
create(region: OrderProfileRelativeRegion): void | Promise<void>;
|
||||
select(id: string): void;
|
||||
dragStart(id: string): void;
|
||||
dragEnd(): void;
|
||||
change(id: string, region: OrderProfileRelativeRegion): void;
|
||||
undo(): void;
|
||||
redo(): void;
|
||||
duplicate(): void;
|
||||
remove(): void;
|
||||
page(pageNo: number): void;
|
||||
draw(kind: OrderProfileCanvasRegion['kind']): void;
|
||||
}
|
||||
|
||||
/**
|
||||
* 共享 Editor 消费的视觉画布状态。
|
||||
*
|
||||
* 取值 adapter 可以使用不同的持久化载体,但在
|
||||
* 进入 Editor 后都必须投影为这一份视觉状态。这样 PDF 预览、工具栏和 DocumentCanvas
|
||||
* 不再知道模板模式,更不能因此分出第二套交互生命周期。
|
||||
*/
|
||||
export interface OrderProfileVisualCanvasAdapter {
|
||||
actions: OrderProfileCanvasActions;
|
||||
documentReady: boolean;
|
||||
preview: { document_id: number; preview_token: string; expires_in_seconds: number } | null;
|
||||
previewPagePath: string;
|
||||
regions: OrderProfileCanvasRegion[];
|
||||
selectedRegionId: string | null;
|
||||
creationKind: OrderProfileCanvasRegion['kind'] | null;
|
||||
pageNo: number;
|
||||
pageCount: number;
|
||||
saveDisabled: boolean;
|
||||
autoSuggestDisabled: boolean;
|
||||
emptyHint: string | null;
|
||||
loadError: string | null;
|
||||
undoDisabled: boolean;
|
||||
redoDisabled: boolean;
|
||||
duplicateDisabled: boolean;
|
||||
deleteDisabled: boolean;
|
||||
setRenderedPageCount(count: number): void;
|
||||
hasSelection: boolean;
|
||||
selectedKindLabel: string;
|
||||
selectedGeometry: string;
|
||||
activePageHasLines: boolean;
|
||||
headerRecognitionResults: OrderProfileRecognitionResult[];
|
||||
lineRecognitionResults: OrderProfileRecognitionResult[];
|
||||
/** 共同画布状态与动作;错误语义由 adapter 投影,Editor 不再判断模板模式。 */
|
||||
canvasReadonly: boolean;
|
||||
warningVisible: boolean;
|
||||
warningText: string | null;
|
||||
retryCanvas(): void;
|
||||
reportCanvasLoadFailed(): void;
|
||||
applyAutomarkCandidates(candidates: Array<Record<string, unknown>>): boolean;
|
||||
canRender: boolean;
|
||||
retryLabel: string;
|
||||
acceptSuggestion(): void;
|
||||
rejectSuggestion(): void;
|
||||
}
|
||||
|
||||
/**
|
||||
* 共享草稿保存 adapter。
|
||||
*
|
||||
* Editor 统一负责租约、乐观锁、Revision 保存和失败恢复;adapter 只把当前视觉标注
|
||||
* 转为其正式值源所需的 definition,并在服务端返回后消费该 adapter 的附加证据。
|
||||
*/
|
||||
export interface OrderProfileDraftSaveAdapter {
|
||||
hasUnsavedChanges: boolean;
|
||||
skipUnchangedManualSave: boolean;
|
||||
canSave: boolean;
|
||||
canValidate: boolean;
|
||||
exportDefinition(): OrderProfileDefinition | null;
|
||||
buildPayload(visualDefinition: OrderProfileDefinition): {
|
||||
definition: OrderProfileDefinition;
|
||||
splitRuleConfirmationTokens?: Record<string, string>;
|
||||
allowFormalBindingDeletions?: string[];
|
||||
} | null;
|
||||
applySavedDraft(saved: unknown): Promise<boolean>;
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析 Profile 的末端值源 capability key。
|
||||
* 编辑器只消费这个 capability,不得直接依据 PDF/XFA 格式分叉流程。
|
||||
*/
|
||||
export function resolveValueAdapterKey(profile: ShippingOrderDocumentProfile | null): string {
|
||||
return profile?.template_mode === 'xfa_dataset' ? 'xfa_dataset' : 'coordinate_ocr';
|
||||
}
|
||||
|
||||
/**
|
||||
* 返回当前 Profile 的唯一画布动作 adapter。
|
||||
* 核心逻辑:选择只依据末端值源的 capability key;其后画布事件不再识别文件格式。
|
||||
* @param options.adapterKey - 已持久化的末端值源 capability key。
|
||||
* @param options.adapters - 各值源的画布状态 adapter。
|
||||
* @returns 当前画布应使用的统一动作集合。
|
||||
*/
|
||||
export function resolveCanvasActions(options: {
|
||||
adapterKey: string;
|
||||
adapters: Record<string, OrderProfileCanvasActions>;
|
||||
}): OrderProfileCanvasActions {
|
||||
const adapter = options.adapters[options.adapterKey];
|
||||
if (!adapter) throw new Error(`Unsupported order-profile value adapter: ${options.adapterKey}`);
|
||||
return adapter;
|
||||
}
|
||||
|
||||
/**
|
||||
* 返回共享编辑器壳层当前唯一的值源 desk adapter。
|
||||
* 核心逻辑:保存、样本上下文和自动标记 Job 由壳层统一编排;adapter 只生成
|
||||
* payload 或应用取值专属结果,避免这些公共生命周期再次分为 XFA/PDF 两条路径。
|
||||
*/
|
||||
export function resolveDeskAdapter<T>(options: {
|
||||
adapterKey: string;
|
||||
adapters: Record<string, T>;
|
||||
}): T {
|
||||
const adapter = options.adapters[options.adapterKey];
|
||||
if (!adapter) throw new Error(`Unsupported order-profile value adapter: ${options.adapterKey}`);
|
||||
return adapter;
|
||||
}
|
||||
|
||||
/**
|
||||
* 返回唯一由 Editor 消费的 PDF 画布文档上下文。
|
||||
* 核心逻辑:所有 Profile 先使用共同冻结的 annotation document + main_table_id;
|
||||
* 历史草稿缺失 main_table_id 时才回退样本 table_id。预览授权、页码和 PDF.js 渲染始终
|
||||
* 由共享 Editor 持有,值源 adapter 不得参与上下文选择。
|
||||
* @param options.documentId - 共同 annotation 文档身份。
|
||||
* @param options.mainTableId - definition 中冻结的共同视觉主表。
|
||||
* @param options.sampleTableId - 历史样本的兼容回退表身份。
|
||||
* @returns 共享画布唯一使用的文档和表身份。
|
||||
*/
|
||||
export function resolveSharedCanvasDocument(options: {
|
||||
documentId: number;
|
||||
mainTableId: string;
|
||||
sampleTableId: string;
|
||||
}): { documentId: number; tableId: string } {
|
||||
return {
|
||||
documentId: options.documentId,
|
||||
tableId: options.mainTableId || options.sampleTableId,
|
||||
};
|
||||
}
|
||||
+1
-1
@@ -32,7 +32,7 @@ const filters = reactive({
|
||||
createdTo: "",
|
||||
});
|
||||
|
||||
const VISUAL_EVENT_PREFIXES = ["xfa_visual_binding_", "xfa_split_", "order_profile_unified_migration_"];
|
||||
const VISUAL_EVENT_PREFIXES = ["xfa_split_", "order_profile_unified_migration_"];
|
||||
|
||||
/**
|
||||
* 判断是否为统一视觉 / 拆分 / 迁移审计事件。
|
||||
|
||||
+85
@@ -0,0 +1,85 @@
|
||||
/**
|
||||
* 用途:验证 XFA 受控原 PDF 预览使用 PDF.js 普通页面外观渲染。
|
||||
* 依赖:Vitest、Vue Test Utils、OrderProfileDocumentCanvas。
|
||||
* 逻辑:hybrid XFA 的 getXfa() 可为空;预览必须走 page.render(),保留实际页面外观流。
|
||||
*/
|
||||
import { flushPromises, mount } from '@vue/test-utils';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { createI18n } from 'vue-i18n';
|
||||
import OrderProfileDocumentCanvas from './OrderProfileDocumentCanvas.vue';
|
||||
|
||||
const { getDocumentMock, getPageMock, renderMock } = vi.hoisted(() => ({
|
||||
getDocumentMock: vi.fn(),
|
||||
getPageMock: vi.fn(),
|
||||
renderMock: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('pdfjs-dist', () => ({
|
||||
GlobalWorkerOptions: {},
|
||||
getDocument: (...args: unknown[]) => getDocumentMock(...args),
|
||||
}));
|
||||
vi.mock('pdfjs-dist/build/pdf.worker.min.mjs?url', () => ({ default: '/pdf.worker.min.mjs' }));
|
||||
vi.mock('@/shared/utils/auth', () => ({ getAuthHeaders: () => ({ Authorization: 'Bearer test' }) }));
|
||||
|
||||
describe('OrderProfileDocumentCanvas PDF preview', () => {
|
||||
beforeEach(() => {
|
||||
vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockReturnValue({} as CanvasRenderingContext2D);
|
||||
renderMock.mockReset();
|
||||
renderMock.mockReturnValue({ promise: Promise.resolve() });
|
||||
getPageMock.mockReset();
|
||||
getPageMock.mockResolvedValue({
|
||||
getViewport: vi.fn(({ scale }: { scale: number }) => ({ width: 600 * scale, height: 800 * scale })),
|
||||
render: renderMock,
|
||||
getXfa: vi.fn(async () => null),
|
||||
});
|
||||
getDocumentMock.mockReset();
|
||||
getDocumentMock.mockReturnValue({ promise: Promise.resolve({ numPages: 2, getPage: getPageMock }) });
|
||||
vi.stubGlobal('fetch', vi.fn(async () => new Response(new Uint8Array([37, 80, 68, 70]), { status: 200 })));
|
||||
});
|
||||
|
||||
it('renders hybrid XFA through the ordinary page appearance when getXfa is empty', async () => {
|
||||
const wrapper = mount(OrderProfileDocumentCanvas, {
|
||||
props: {
|
||||
profileId: 71,
|
||||
pdfPreview: { preview_token: 'single-use-token' },
|
||||
regions: [], pageNo: 1, pageCount: 1,
|
||||
},
|
||||
global: { plugins: [createI18n({ legacy: false, locale: 'zh', messages: { zh: {} } })] },
|
||||
});
|
||||
await flushPromises();
|
||||
await flushPromises();
|
||||
|
||||
// 关键断言:hybrid XFA 不依赖 getXfa/XfaLayer,使用页面外观流渲染动态可见值。
|
||||
expect(getDocumentMock).toHaveBeenCalledWith(expect.objectContaining({ data: expect.any(Uint8Array) }));
|
||||
expect(getPageMock).toHaveBeenCalledWith(1);
|
||||
expect(renderMock).toHaveBeenCalledWith(expect.objectContaining({ canvasContext: expect.anything() }));
|
||||
expect(wrapper.find('canvas.pdf-page').exists()).toBe(true);
|
||||
expect(wrapper.emitted('pageCount')?.[0]).toEqual([2]);
|
||||
});
|
||||
|
||||
it('keeps XFA suggestion regions on the same scaled coordinate plane as the PDF page', async () => {
|
||||
const wrapper = mount(OrderProfileDocumentCanvas, {
|
||||
props: {
|
||||
profileId: 71,
|
||||
pdfPreview: { preview_token: 'single-use-token' },
|
||||
regions: [{
|
||||
id: 'automark:sugg-1', kind: 'order_field', label: '自动标注', pageNo: 1,
|
||||
region: { x0: .5, y0: .5, x1: .75, y1: .75 },
|
||||
}],
|
||||
pageNo: 1,
|
||||
pageCount: 1,
|
||||
},
|
||||
global: { plugins: [createI18n({ legacy: false, locale: 'zh', messages: { zh: {} } })] },
|
||||
});
|
||||
await flushPromises();
|
||||
await flushPromises();
|
||||
|
||||
await wrapper.findAll('.zoom-control button')[1].trigger('click');
|
||||
await flushPromises();
|
||||
await flushPromises();
|
||||
|
||||
// PDF.js 的 viewport 已是 125%(750px);覆盖框必须以同一宽度百分比定位,不能二次放大到 937.5px。
|
||||
expect(wrapper.find('.canvas-stage').attributes('style')).toContain('width: 750px');
|
||||
expect(wrapper.find('.region').attributes('style')).toContain('left: 50%');
|
||||
});
|
||||
});
|
||||
+89
-25
@@ -6,17 +6,38 @@
|
||||
画布区域 aria-label 走四语言 i18n;可选 emptyHint/loadError 区分 XFA page_unavailable 与 PDF 缺样本空态。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, onBeforeUnmount, ref, watch } from 'vue';
|
||||
import { computed, nextTick, onBeforeUnmount, ref, watch } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { Anchor, ArrowLeft, ArrowRight, Columns3, Copy, Eraser, Minus, Plus, Redo2, RotateCcw, Rows3, Save, TableProperties, Tag, TextCursorInput, Trash2, WandSparkles } from 'lucide-vue-next';
|
||||
import { getAuthHeaders } from '@/shared/utils/auth';
|
||||
import type { OrderProfileCanvasRegion, OrderProfilePreviewPageGrant } from '@/features/admin/types/shipping-order-document-profile.types';
|
||||
import type { PDFDocumentProxy } from 'pdfjs-dist';
|
||||
|
||||
type PdfJsModule = typeof import('pdfjs-dist');
|
||||
let pdfjsLoader: Promise<PdfJsModule> | null = null;
|
||||
|
||||
/** 动态加载 PDF.js 与 worker;坐标 PDF 与 XFA 在受控管理员画布按需共用。 */
|
||||
async function loadPdfJs(): Promise<PdfJsModule> {
|
||||
if (!pdfjsLoader) {
|
||||
pdfjsLoader = (async () => {
|
||||
const [pdfjs, workerMod] = await Promise.all([
|
||||
import('pdfjs-dist'),
|
||||
import('pdfjs-dist/build/pdf.worker.min.mjs?url'),
|
||||
]);
|
||||
pdfjs.GlobalWorkerOptions.workerSrc = workerMod.default;
|
||||
return pdfjs;
|
||||
})();
|
||||
}
|
||||
return pdfjsLoader;
|
||||
}
|
||||
|
||||
const props = defineProps<{
|
||||
profileId: number | null;
|
||||
grant?: OrderProfilePreviewPageGrant | null;
|
||||
mode?: 'edit' | 'readonly';
|
||||
previewPagePath?: string | null;
|
||||
/** 原 PDF 令牌;启用后用 PDF.js 页面外观流渲染,绝不生成可下载 URL。 */
|
||||
pdfPreview?: { preview_token: string } | null;
|
||||
regions: OrderProfileCanvasRegion[];
|
||||
selectedRegionId?: string | null;
|
||||
creationKind?: OrderProfileCanvasRegion['kind'] | null;
|
||||
@@ -34,8 +55,6 @@ const props = defineProps<{
|
||||
pendingSuggestionCount?: number;
|
||||
orderFieldValues?: Record<string, string | null>;
|
||||
orderFieldValueState?: 'idle' | 'loading' | 'ready' | 'failed';
|
||||
/** full=坐标全工具;xfa_visual=仅 XFA 画框。 */
|
||||
annotationToolSet?: 'full' | 'xfa_visual';
|
||||
/** 无图时空态文案;缺省为「选择已绑定的 PDF 样本」。 */
|
||||
emptyHint?: string | null;
|
||||
/** 外部注入的页加载错误(如 XFA page_unavailable);优先于空态提示。 */
|
||||
@@ -43,7 +62,6 @@ const props = defineProps<{
|
||||
}>();
|
||||
const { t } = useI18n();
|
||||
const readonlyMode = computed(() => props.mode === 'readonly');
|
||||
const xfaVisualTools = computed(() => props.annotationToolSet === 'xfa_visual');
|
||||
const emit = defineEmits<{
|
||||
select: [regionId: string];
|
||||
start: [regionId: string];
|
||||
@@ -58,6 +76,7 @@ const emit = defineEmits<{
|
||||
delete: [];
|
||||
save: [];
|
||||
page: [pageNo: number];
|
||||
pageCount: [count: number];
|
||||
acceptSuggestion: [];
|
||||
rejectSuggestion: [];
|
||||
/** 页图拉取失败(父级可标 page_unavailable)。 */
|
||||
@@ -67,6 +86,10 @@ const emit = defineEmits<{
|
||||
}>();
|
||||
|
||||
const imageUrl = ref('');
|
||||
const pdfCanvas = ref<HTMLCanvasElement | null>(null);
|
||||
const pdfRendered = ref(false);
|
||||
const pdfPageSize = ref<{ width: number; height: number } | null>(null);
|
||||
let pdfDocument: PDFDocumentProxy | null = null;
|
||||
const loading = ref(false);
|
||||
/** 本组件内 fetch 失败文案;与 props.loadError 合并展示。 */
|
||||
const internalLoadError = ref<string | null>(null);
|
||||
@@ -87,26 +110,62 @@ const emptyStateText = computed(() => (
|
||||
props.emptyHint || t('admin.shippingOrderProfiles.workbench.selectBoundPdf')
|
||||
));
|
||||
|
||||
/**
|
||||
* 将内存中的原 PDF 按真实页面外观流绘制到 Canvas。
|
||||
* 核心逻辑:坐标 PDF 与 hybrid XFA 都用 page.render(),不生成可下载 URL。
|
||||
*/
|
||||
const renderPdfPage = async (pdf: PDFDocumentProxy) => {
|
||||
await nextTick();
|
||||
const targetPage = Math.min(Math.max(props.pageNo, 1), pdf.numPages);
|
||||
const page = await pdf.getPage(targetPage);
|
||||
const canvas = pdfCanvas.value;
|
||||
const context = canvas?.getContext('2d');
|
||||
if (!canvas || !context) throw new Error('PDF canvas is unavailable');
|
||||
const viewport = page.getViewport({ scale: zoom.value });
|
||||
pdfPageSize.value = { width: viewport.width, height: viewport.height };
|
||||
canvas.width = Math.ceil(viewport.width);
|
||||
canvas.height = Math.ceil(viewport.height);
|
||||
await page.render({ canvas, canvasContext: context, viewport }).promise;
|
||||
pdfRendered.value = true;
|
||||
};
|
||||
|
||||
/**
|
||||
* 下载一次性 PNG 并在组件卸载或切页时回收浏览器 blob。
|
||||
* 核心逻辑:失败时写入 internalLoadError 并 emit loadFailed,避免误导为「未绑定样本」。
|
||||
*/
|
||||
const loadPage = async () => {
|
||||
if (!props.profileId || !props.grant) {
|
||||
if (!props.profileId || (!props.grant && !props.pdfPreview)) {
|
||||
URL.revokeObjectURL(imageUrl.value);
|
||||
imageUrl.value = '';
|
||||
pdfRendered.value = false;
|
||||
internalLoadError.value = null;
|
||||
return;
|
||||
}
|
||||
loading.value = true;
|
||||
URL.revokeObjectURL(imageUrl.value);
|
||||
imageUrl.value = '';
|
||||
pdfRendered.value = false;
|
||||
internalLoadError.value = null;
|
||||
try {
|
||||
const previewPath = props.previewPagePath
|
||||
|| `/api/admin/shipping-notice/order-document-profiles/${props.profileId}/preview-pages`;
|
||||
if (props.pdfPreview) {
|
||||
const response = await fetch(
|
||||
`${previewPath}?preview_token=${encodeURIComponent(props.pdfPreview.preview_token)}`,
|
||||
{ headers: getAuthHeaders(), cache: 'no-store' },
|
||||
);
|
||||
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
||||
const pdfjs = await loadPdfJs();
|
||||
const bytes = new Uint8Array(await response.arrayBuffer());
|
||||
pdfDocument = await pdfjs.getDocument({ data: bytes, enableXfa: true }).promise;
|
||||
emit('pageCount', pdfDocument.numPages);
|
||||
await renderPdfPage(pdfDocument);
|
||||
return;
|
||||
}
|
||||
const grant = props.grant;
|
||||
if (!grant) throw new Error('PDF preview grant is unavailable');
|
||||
const response = await fetch(
|
||||
`${previewPath}/${props.grant.page_no}?preview_token=${encodeURIComponent(props.grant.preview_token)}`,
|
||||
`${previewPath}/${grant.page_no}?preview_token=${encodeURIComponent(grant.preview_token)}`,
|
||||
{ headers: getAuthHeaders(), cache: 'no-store' },
|
||||
);
|
||||
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
||||
@@ -216,10 +275,6 @@ const displayRegionLabel = (region: OrderProfileCanvasRegion): string => {
|
||||
return `${region.label} · ${region.recognizedValue || t('admin.shippingOrderProfiles.workbench.sampleValueUnavailable')}`;
|
||||
}
|
||||
if (region.kind !== 'order_field') {
|
||||
if (region.kind === 'xfa_visual' && region.visualBindingStatus) {
|
||||
const statusKey = `admin.shippingOrderProfiles.xfaUnified.visualStatus.${region.visualBindingStatus}`;
|
||||
return `${region.label} · ${t(statusKey)}`;
|
||||
}
|
||||
return region.label;
|
||||
}
|
||||
const state = props.orderFieldValueState || 'idle';
|
||||
@@ -244,8 +299,14 @@ const goToPage = () => {
|
||||
if (nextPage !== props.pageNo) emit('page', nextPage);
|
||||
};
|
||||
defineExpose({ zoomIn: () => adjustZoom(.25), zoomOut: () => adjustZoom(-.25), resetZoom });
|
||||
watch(() => props.grant?.preview_token, () => { void loadPage(); }, { immediate: true });
|
||||
watch(() => props.pageNo, (value) => { pageInput.value = value; });
|
||||
watch(() => [props.grant?.preview_token, props.pdfPreview?.preview_token], () => { void loadPage(); }, { immediate: true });
|
||||
watch(() => props.pageNo, async (value) => {
|
||||
pageInput.value = value;
|
||||
if (props.pdfPreview && pdfDocument) await renderPdfPage(pdfDocument);
|
||||
});
|
||||
watch(zoom, async () => {
|
||||
if (props.pdfPreview && pdfDocument) await renderPdfPage(pdfDocument);
|
||||
});
|
||||
onBeforeUnmount(() => { endMove(); endPan(); endCreation(); URL.revokeObjectURL(imageUrl.value); });
|
||||
</script>
|
||||
|
||||
@@ -256,7 +317,7 @@ onBeforeUnmount(() => { endMove(); endPan(); endCreation(); URL.revokeObjectURL(
|
||||
? t('admin.shippingOrderProfiles.workbench.readonlyCanvasAriaLabel')
|
||||
: t('admin.shippingOrderProfiles.workbench.annotationCanvasAriaLabel')"
|
||||
>
|
||||
<header v-if="imageUrl" class="canvas-toolbar">
|
||||
<header v-if="imageUrl || pdfRendered" class="canvas-toolbar">
|
||||
<div class="toolbar-actions">
|
||||
<template v-if="!readonlyMode">
|
||||
<button type="button" :disabled="undoDisabled" :title="t('admin.shippingOrderProfiles.workbench.undo')" @click="emit('undo')"><RotateCcw /></button>
|
||||
@@ -287,20 +348,16 @@ onBeforeUnmount(() => { endMove(); endPan(); endCreation(); URL.revokeObjectURL(
|
||||
<button type="button" class="fit-action" @click="resetZoom">{{ t('admin.shippingOrderProfiles.workbench.fitPage') }}</button>
|
||||
</div>
|
||||
</header>
|
||||
<div v-if="loading" class="canvas-state">{{ t('admin.shippingOrderProfiles.workbench.loadingPage') }}</div>
|
||||
<div v-if="loading && !pdfPreview" class="canvas-state">{{ t('admin.shippingOrderProfiles.workbench.loadingPage') }}</div>
|
||||
<div v-else-if="displayLoadError" class="canvas-state canvas-state--error" role="alert">
|
||||
<p>{{ displayLoadError }}</p>
|
||||
<button type="button" class="canvas-retry" @click="onRetryClick">
|
||||
{{ t('admin.shippingOrderProfiles.workbench.retryCanvas') }}
|
||||
</button>
|
||||
</div>
|
||||
<div v-else-if="!imageUrl" class="canvas-state">{{ emptyStateText }}</div>
|
||||
<div v-else-if="!imageUrl && !pdfRendered && !pdfPreview" class="canvas-state">{{ emptyStateText }}</div>
|
||||
<div v-else class="canvas-work-area" :class="{ readonly: readonlyMode }">
|
||||
<aside v-if="!readonlyMode" class="annotation-tools">
|
||||
<template v-if="xfaVisualTools">
|
||||
<button type="button" :aria-label="t('admin.shippingOrderProfiles.xfaUnified.drawFieldBox')" :title="t('admin.shippingOrderProfiles.xfaUnified.drawFieldBox')" :class="{ active: creationKind === 'xfa_visual' }" @click="emit('draw', 'xfa_visual')"><TextCursorInput /></button>
|
||||
</template>
|
||||
<template v-else>
|
||||
<button type="button" :aria-label="t('admin.shippingOrderProfiles.workbench.drawDocumentMatchAnchorShortcut')" :title="t('admin.shippingOrderProfiles.workbench.drawDocumentMatchAnchorShortcut')" :class="{ active: creationKind === 'document_anchor_label' || creationKind === 'document_anchor_value' }" @click="emit('draw', 'document_anchor_label')"><Anchor /></button>
|
||||
<button type="button" :aria-label="t('admin.shippingOrderProfiles.workbench.drawOrderAnchorShortcut')" :title="t('admin.shippingOrderProfiles.workbench.drawOrderAnchorShortcut')" :class="{ active: creationKind === 'order_anchor' }" @click="emit('draw', 'order_anchor')"><Tag /></button>
|
||||
<button type="button" :aria-label="t('admin.shippingOrderProfiles.workbench.drawOrderFieldShortcut')" :title="t('admin.shippingOrderProfiles.workbench.drawOrderFieldShortcut')" :class="{ active: creationKind === 'order_field' }" @click="emit('draw', 'order_field')"><TextCursorInput /></button>
|
||||
@@ -309,12 +366,20 @@ onBeforeUnmount(() => { endMove(); endPan(); endCreation(); URL.revokeObjectURL(
|
||||
<button type="button" :aria-label="t('admin.shippingOrderProfiles.workbench.drawFieldShortcut')" :title="t('admin.shippingOrderProfiles.workbench.drawFieldShortcut')" :class="{ active: creationKind === 'field' }" @click="emit('draw', 'field')"><Columns3 /></button>
|
||||
<button type="button" :aria-label="t('admin.shippingOrderProfiles.workbench.drawExclusionShortcut')" :title="t('admin.shippingOrderProfiles.workbench.drawExclusionShortcut')" :class="{ active: creationKind === 'exclusion' }" @click="emit('draw', 'exclusion')"><Eraser /></button>
|
||||
<button type="button" class="suggest" :aria-label="t('admin.shippingOrderProfiles.workbench.autoSuggestShortcut')" :title="t('admin.shippingOrderProfiles.workbench.autoSuggestShortcut')" :disabled="autoSuggestDisabled || suggesting" @click="emit('suggest')"><WandSparkles /></button>
|
||||
</template>
|
||||
<p v-if="suggestionProgress" class="suggestion-progress" :class="{ failed: !suggesting }">{{ suggestionProgress }}</p>
|
||||
</aside>
|
||||
<div ref="viewport" class="canvas-viewport" :class="{ panning: !creationKind || readonlyMode }" @wheel.prevent="handleWheel">
|
||||
<div ref="canvas" class="canvas-stage" :class="{ drawing: creationKind && !readonlyMode }" :style="{ '--canvas-zoom': zoom }" @pointerdown="beginCreation">
|
||||
<img :src="imageUrl" :alt="t('admin.shippingOrderProfiles.workbench.pagePreviewAlt')" draggable="false" />
|
||||
<div
|
||||
ref="canvas"
|
||||
class="canvas-stage"
|
||||
:class="{ drawing: creationKind && !readonlyMode, 'canvas-stage--xfa': Boolean(pdfPageSize) }"
|
||||
:style="pdfPageSize
|
||||
? { width: `${pdfPageSize.width}px`, minWidth: '0', '--canvas-zoom': zoom }
|
||||
: { '--canvas-zoom': zoom }"
|
||||
@pointerdown="beginCreation"
|
||||
>
|
||||
<img v-if="imageUrl" :src="imageUrl" :alt="t('admin.shippingOrderProfiles.workbench.pagePreviewAlt')" draggable="false" />
|
||||
<canvas v-else ref="pdfCanvas" class="pdf-page" aria-label="XFA PDF preview" />
|
||||
<div
|
||||
v-for="region in regions"
|
||||
:key="region.id"
|
||||
@@ -387,6 +452,7 @@ onBeforeUnmount(() => { endMove(); endPan(); endCreation(); URL.revokeObjectURL(
|
||||
.canvas-viewport.panning:active { cursor: grabbing; }
|
||||
.canvas-stage { position: relative; margin: auto; width: calc(100% * var(--canvas-zoom)); min-width: 42rem; box-shadow: 0 16px 40px rgba(0,0,0,.35); }
|
||||
.canvas-stage img { display: block; width: 100%; user-select: none; }
|
||||
.canvas-stage canvas.pdf-page { display: block; background: white; pointer-events: none; user-select: none; }
|
||||
.canvas-stage.drawing { cursor: crosshair; }
|
||||
.creation-region { position: absolute; z-index: 5; box-sizing: border-box; border: 2px dashed #34d399; background: rgb(16 185 129 / .18); pointer-events: none; }
|
||||
.annotation-tools { display: grid; align-content: start; gap: .3rem; flex: 0 0 2.65rem; padding: .3rem; border: 1px solid rgb(71 85 105 / .9); border-radius: .5rem; background: rgb(15 23 42 / .94); box-shadow: 0 8px 24px rgb(15 23 42 / .3); }
|
||||
@@ -430,9 +496,7 @@ onBeforeUnmount(() => { endMove(); endPan(); endCreation(); URL.revokeObjectURL(
|
||||
.line-hit-w { left: -6px; }
|
||||
.region-exclusion { z-index: 3; border-style: dashed; border-color: #f87171; background: rgb(248 113 113 / .1); }
|
||||
.region-exclusion .region-label, .region-exclusion .resize-handle { background: #b91c1c; }
|
||||
.region-xfa_visual { z-index: 2; border: 1.5px solid #38bdf8; background: rgb(14 165 233 / .12); }
|
||||
.region-xfa_visual .region-label, .region-xfa_visual .resize-handle { background: #0369a1; }
|
||||
.region-visual--suggested { border-color: #f59e0b; background: rgb(245 158 11 / .14); }
|
||||
.region-visual--suggested { border-style: dashed; border-color: #f59e0b; background: rgb(245 158 11 / .14); }
|
||||
.region-visual--suggested .region-label { background: #b45309; }
|
||||
.region-visual--confirmed { border-color: #22c55e; background: rgb(34 197 94 / .12); }
|
||||
.region-visual--confirmed .region-label { background: #15803d; }
|
||||
|
||||
+4
-8
@@ -2,7 +2,8 @@
|
||||
features/admin/modules/shipping-order-document-profiles/components/OrderProfileReadOnlyCanvas.vue
|
||||
用途:在版本详情页展示基于冻结样本绑定的只读画布。
|
||||
依赖:冻结样本预览 API、OrderProfileDocumentCanvas、冻结证据面板。
|
||||
逻辑:只允许 annotation/training 样本进入普通画布;blind_test 继续留在摘要层,不进入样本选择器。
|
||||
逻辑:所有模板共用 annotation/training 冻结样本画布;XFA datasets 映射仅作为侧栏证据,
|
||||
blind_test 继续留在摘要层,不进入样本选择器。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, ref, watch } from 'vue';
|
||||
@@ -22,17 +23,12 @@ import OrderProfileDocumentCanvas from './OrderProfileDocumentCanvas.vue';
|
||||
import OrderProfileFrozenEvidencePanel from './OrderProfileFrozenEvidencePanel.vue';
|
||||
import XfaReadOnlyMapping from './XfaReadOnlyMapping.vue';
|
||||
import { buildOrderProfileReadonlyRegions } from '../orderProfileReadonlyCanvas.utils';
|
||||
import { isXfaDatasetProfileDefinition } from '@/features/admin/types/shipping-order-document-profile.types';
|
||||
|
||||
const props = defineProps<{
|
||||
detail: ShippingOrderDocumentProfile;
|
||||
}>();
|
||||
|
||||
const { t } = useI18n();
|
||||
const isXfa = computed(() => (
|
||||
props.detail.template_mode === 'xfa_dataset'
|
||||
|| isXfaDatasetProfileDefinition(props.detail.definition)
|
||||
));
|
||||
const loading = ref(false);
|
||||
const errorMessage = ref('');
|
||||
const selectedSampleId = ref<number | null>(null);
|
||||
@@ -144,8 +140,7 @@ watch([selectedSampleId, pageNo], () => {
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<XfaReadOnlyMapping v-if="isXfa" :detail="detail" />
|
||||
<section v-else class="readonly-layout">
|
||||
<section class="readonly-layout">
|
||||
<div v-if="!immutable" class="state-card">
|
||||
{{ t('admin.shippingOrderProfiles.versionCenter.draftCanvasHint') }}
|
||||
</div>
|
||||
@@ -184,6 +179,7 @@ watch([selectedSampleId, pageNo], () => {
|
||||
/>
|
||||
<div class="side-panel">
|
||||
<OrderProfileFrozenEvidencePanel :sample="selectedSample" />
|
||||
<XfaReadOnlyMapping :detail="detail" />
|
||||
<section class="panel">
|
||||
<h3>{{ t('admin.shippingOrderProfiles.versionCenter.regionSummaryTitle') }}</h3>
|
||||
<p v-if="diagnosticsLoading" class="diagnostic-state">{{ t('admin.shippingOrderProfiles.versionCenter.regionDiagnosticsLoading') }}</p>
|
||||
|
||||
+8
-35
@@ -8,7 +8,6 @@
|
||||
import { computed } from "vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import type { ShippingOrderDocumentProfile } from "@/features/admin/types/shipping-order-document-profile.types";
|
||||
import { isXfaDatasetProfileDefinition } from "@/features/admin/types/shipping-order-document-profile.types";
|
||||
|
||||
const props = defineProps<{
|
||||
detail: ShippingOrderDocumentProfile;
|
||||
@@ -16,14 +15,8 @@ const props = defineProps<{
|
||||
|
||||
const { t } = useI18n();
|
||||
|
||||
/** XFA 版本概览展示结构身份与路径映射规模,不展示坐标表区域指标。 */
|
||||
const isXfa = computed(() => (
|
||||
props.detail.template_mode === "xfa_dataset"
|
||||
|| isXfaDatasetProfileDefinition(props.detail.definition)
|
||||
|| props.detail.definition_stats?.template_mode === "xfa_dataset"
|
||||
));
|
||||
|
||||
const xfaIdentity = computed(() => props.detail.xfa_structure_identity || null);
|
||||
/** 末端值源证据由服务端 adapter 作为可选摘要投影,公共概览不判断模板模式。 */
|
||||
const valueSourceIdentity = computed(() => props.detail.value_source_identity || null);
|
||||
|
||||
const formatDateTime = (value?: string | null) =>
|
||||
value ? new Date(value).toLocaleString() : "-";
|
||||
@@ -50,11 +43,6 @@ const testStatusLabel = computed(() => {
|
||||
return t(`admin.shippingOrderProfiles.versionCenter.testStatus.${status}`);
|
||||
});
|
||||
|
||||
const templateModeLabel = computed(() => (
|
||||
isXfa.value
|
||||
? t("admin.shippingOrderProfiles.versionCenter.templateModeXfa")
|
||||
: t("admin.shippingOrderProfiles.versionCenter.templateModeCoordinate")
|
||||
));
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -68,7 +56,6 @@ const templateModeLabel = computed(() => (
|
||||
</div>
|
||||
<div class="hero-meta">
|
||||
<span class="meta-chip meta-chip--status" :class="statusClass">{{ statusLabel }}</span>
|
||||
<span class="meta-chip">{{ templateModeLabel }}</span>
|
||||
<span class="meta-chip">
|
||||
{{ t("admin.shippingOrderProfiles.versionCenter.schemaVersion") }}
|
||||
{{ detail.schema_summary?.version ?? "-" }}
|
||||
@@ -84,21 +71,7 @@ const templateModeLabel = computed(() => (
|
||||
<div class="summary-grid">
|
||||
<article class="summary-card">
|
||||
<h3>{{ t("admin.shippingOrderProfiles.versionCenter.definitionStats") }}</h3>
|
||||
<dl v-if="isXfa">
|
||||
<div>
|
||||
<dt>{{ t("admin.shippingOrderProfiles.versionCenter.headerMappings") }}</dt>
|
||||
<dd>{{ detail.definition_stats?.header_mapping_count || 0 }}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>{{ t("admin.shippingOrderProfiles.versionCenter.lineMappings") }}</dt>
|
||||
<dd>{{ detail.definition_stats?.line_mapping_count || 0 }}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>{{ t("admin.shippingOrderProfiles.versionCenter.mirrorCollections") }}</dt>
|
||||
<dd>{{ detail.definition_stats?.mirror_collection_count || 0 }}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
<dl v-else>
|
||||
<dl>
|
||||
<div>
|
||||
<dt>{{ t("admin.shippingOrderProfiles.versionCenter.tableRegions") }}</dt>
|
||||
<dd>{{ detail.definition_stats?.table_region_count || 0 }}</dd>
|
||||
@@ -118,24 +91,24 @@ const templateModeLabel = computed(() => (
|
||||
</dl>
|
||||
</article>
|
||||
|
||||
<article v-if="isXfa && xfaIdentity" class="summary-card">
|
||||
<article v-if="valueSourceIdentity" class="summary-card">
|
||||
<h3>{{ t("admin.shippingOrderProfiles.versionCenter.xfaStructureIdentity") }}</h3>
|
||||
<dl>
|
||||
<div>
|
||||
<dt>{{ t("admin.shippingOrderProfiles.versionCenter.xfaTemplateChecksum") }}</dt>
|
||||
<dd>{{ xfaIdentity.template_packet_checksum || "-" }}</dd>
|
||||
<dd>{{ valueSourceIdentity.template_packet_checksum || "-" }}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>{{ t("admin.shippingOrderProfiles.versionCenter.xfaDatasetFingerprint") }}</dt>
|
||||
<dd>{{ xfaIdentity.dataset_structure_fingerprint || "-" }}</dd>
|
||||
<dd>{{ valueSourceIdentity.dataset_structure_fingerprint || "-" }}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>{{ t("admin.shippingOrderProfiles.versionCenter.xfaAuthoritativeCollection") }}</dt>
|
||||
<dd>{{ xfaIdentity.has_authoritative_collection ? t("common.yes") : t("common.no") }}</dd>
|
||||
<dd>{{ valueSourceIdentity.has_authoritative_collection ? t("common.yes") : t("common.no") }}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>{{ t("admin.shippingOrderProfiles.versionCenter.mirrorCollections") }}</dt>
|
||||
<dd>{{ xfaIdentity.mirror_collection_count ?? 0 }}</dd>
|
||||
<dd>{{ valueSourceIdentity.mirror_collection_count ?? 0 }}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
</article>
|
||||
|
||||
-115
@@ -1,115 +0,0 @@
|
||||
/**
|
||||
* features/admin/modules/shipping-order-document-profiles/components/OrderProfileXfaConfirmStep.spec.ts
|
||||
* 用途:验证 XFA 集合候选在未选择权威集合时仍可见,且真正无候选时才显示空状态。
|
||||
* 依赖:Vitest、@vue/test-utils、OrderProfileXfaConfirmStep 及其 XFA API。
|
||||
*/
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { mount } from '@vue/test-utils';
|
||||
import { createI18n } from 'vue-i18n';
|
||||
import OrderProfileXfaConfirmStep from './OrderProfileXfaConfirmStep.vue';
|
||||
|
||||
const { getFieldTree, getCollections, reparseSample } = vi.hoisted(() => ({
|
||||
getFieldTree: vi.fn(),
|
||||
getCollections: vi.fn(),
|
||||
reparseSample: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('@/features/admin/api/shipping-order-document-profile.api', () => ({
|
||||
getOrderProfileSampleXfaFieldTree: getFieldTree,
|
||||
getOrderProfileSampleXfaCollections: getCollections,
|
||||
reparseOrderProfileSampleLayout: reparseSample,
|
||||
}));
|
||||
|
||||
const i18n = createI18n({
|
||||
legacy: false,
|
||||
locale: 'zh-CN',
|
||||
messages: {
|
||||
'zh-CN': {
|
||||
admin: {
|
||||
shippingOrderProfiles: {
|
||||
wizard: {
|
||||
sampleSelected: '已选样本',
|
||||
xfa: {
|
||||
loading: '加载中',
|
||||
loadErrorTitle: '加载失败',
|
||||
loadErrorHint: '请重试',
|
||||
reload: '重新加载',
|
||||
reparseSample: '重新解析样本',
|
||||
noCollections: '没有可用数据集',
|
||||
intro: 'XFA',
|
||||
noBlankPdf: '不使用空白 PDF',
|
||||
scriptNotice: '不会执行脚本',
|
||||
},
|
||||
},
|
||||
xfaUnified: { createBlockersTitle: '创建前阻断项' },
|
||||
xfaWorkbench: {
|
||||
collectionsTitle: '集合',
|
||||
collectionEvidenceHint: '证据',
|
||||
authoritativeCollection: '权威集合',
|
||||
mirrorCollections: '镜像集合',
|
||||
recommendedAuthoritative: '推荐权威',
|
||||
selectedAuthoritative: '已选权威',
|
||||
rowCount: '{count} 行',
|
||||
nonEmptyCoverage: '{filled}/{total} {percent}',
|
||||
excludedCollections: '排除集合 {count}',
|
||||
allCandidatesExcluded: '全部被排除',
|
||||
emptyStructureReason: '空结构',
|
||||
collectionReason: { data_description_structure: '结构描述', empty_structure: '空结构' },
|
||||
},
|
||||
xfa: { documentKinds: { xfa_hybrid: 'XFA 动态表单' } },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const sample = {
|
||||
document_id: 132,
|
||||
intake_id: 1,
|
||||
intake_no: 'INT-1',
|
||||
filename: '4510039227.pdf',
|
||||
table_count: 0,
|
||||
document_kind: 'xfa_hybrid',
|
||||
xfa_analysis_ready: true,
|
||||
purpose: 'order_document_profile_sample' as const,
|
||||
parse_status: 'ready',
|
||||
is_template_sample: true,
|
||||
can_delete: true,
|
||||
};
|
||||
|
||||
function mountStep() {
|
||||
return mount(OrderProfileXfaConfirmStep, {
|
||||
global: { plugins: [i18n] },
|
||||
props: { documentId: 132, sample, authoritativePathId: '', mirrorPathIds: [] },
|
||||
});
|
||||
}
|
||||
|
||||
describe('OrderProfileXfaConfirmStep', () => {
|
||||
it('未选择权威集合时仍显示可选数据集', async () => {
|
||||
getFieldTree.mockResolvedValue({ tree: {} });
|
||||
getCollections.mockResolvedValue({
|
||||
collection_candidates: [{
|
||||
path_id: 'items', collection_path_hash: 'h1', row_count: 1,
|
||||
path_label: 'datasets / data / ITEMS / DATA', field_names: ['MATNR'],
|
||||
field_count: 1, non_empty_field_count: 1, non_empty_rate: 1,
|
||||
sample_fields: [{ field_name: 'MATNR', display_value: 'TEMP-S', display_policy: 'partial' }],
|
||||
selectable: true, recommended_role: 'authoritative',
|
||||
}],
|
||||
excluded_collection_candidates: [],
|
||||
});
|
||||
|
||||
const wrapper = mountStep();
|
||||
await vi.waitFor(() => expect(wrapper.text()).toContain('datasets / data / ITEMS / DATA'), { timeout: 10000 });
|
||||
expect(wrapper.find('input[type="radio"]').exists()).toBe(true);
|
||||
expect(wrapper.text()).toContain('创建前阻断项');
|
||||
}, 15000);
|
||||
|
||||
it('没有任何候选集合时才显示空状态', async () => {
|
||||
getFieldTree.mockResolvedValue({ tree: {} });
|
||||
getCollections.mockResolvedValue({ collection_candidates: [], excluded_collection_candidates: [] });
|
||||
|
||||
const wrapper = mountStep();
|
||||
await vi.waitFor(() => expect(wrapper.text()).toContain('没有可用数据集'), { timeout: 10000 });
|
||||
expect(wrapper.find('input[type="radio"]').exists()).toBe(false);
|
||||
}, 15000);
|
||||
});
|
||||
-227
@@ -1,227 +0,0 @@
|
||||
<!--
|
||||
features/admin/modules/shipping-order-document-profiles/components/OrderProfileXfaConfirmStep.vue
|
||||
用途:创建向导第三步——XFA 样本结构与明细集合确认(不要求 table_id)。
|
||||
依赖:XFA collections/field-tree API、layout-reparse API、XfaCollectionSelector、vue-i18n。
|
||||
逻辑:父级传入 documentId 与 v-model 集合 path_id;加载失败以独立错误态阻断创建,
|
||||
区分「无合格集合」与「分析不可用」;重新解析需二次确认且不自动触发。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, ref, watch } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { BusinessError, resolveLocalizedErrorMessage } from '@/shared/api/client';
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
import {
|
||||
getOrderProfileSampleXfaCollections,
|
||||
getOrderProfileSampleXfaFieldTree,
|
||||
reparseOrderProfileSampleLayout,
|
||||
} from '@/features/admin/api/shipping-order-document-profile.api';
|
||||
import type { OrderProfileSampleDocument } from '@/features/admin/types/shipping-order-document-profile.types';
|
||||
import { flattenXfaTreeNodes } from '../xfaProfileMapping.utils';
|
||||
import XfaCollectionSelector from './XfaCollectionSelector.vue';
|
||||
|
||||
const props = defineProps<{
|
||||
documentId: number;
|
||||
sample?: OrderProfileSampleDocument | null;
|
||||
authoritativePathId: string;
|
||||
mirrorPathIds: string[];
|
||||
}>();
|
||||
const emit = defineEmits<{
|
||||
'update:authoritativePathId': [value: string];
|
||||
'update:mirrorPathIds': [value: string[]];
|
||||
/** 加载失败态变化:父级须据此阻断创建按钮 */
|
||||
'update:contextReady': [value: boolean];
|
||||
}>();
|
||||
|
||||
const { t } = useI18n();
|
||||
const message = useMessage();
|
||||
const loading = ref(false);
|
||||
const reparsing = ref(false);
|
||||
const loadError = ref<{ code?: string; message: string } | null>(null);
|
||||
const collections = ref<Awaited<ReturnType<typeof getOrderProfileSampleXfaCollections>> | null>(null);
|
||||
const flatNodes = ref(flattenXfaTreeNodes(null));
|
||||
const excludedCollections = computed(() => collections.value?.excluded_collection_candidates || []);
|
||||
const contextReady = computed(() => !loading.value && !loadError.value && collections.value != null);
|
||||
|
||||
/**
|
||||
* 创建草稿前的阻断摘要(权威集合必选等);加载失败时不计入“无集合”。
|
||||
*/
|
||||
const createBlockers = computed(() => {
|
||||
if (loadError.value || !collections.value) return [];
|
||||
const items: string[] = [];
|
||||
const selectable = (collections.value.collection_candidates || []).filter((item) => item.selectable !== false);
|
||||
if (!props.authoritativePathId && selectable.length) {
|
||||
items.push(t('admin.shippingOrderProfiles.xfaWorkbench.blocker.authoritative_collection_required'));
|
||||
}
|
||||
if (!selectable.length && !props.authoritativePathId) {
|
||||
items.push(t('admin.shippingOrderProfiles.xfaWorkbench.allCandidatesExcluded'));
|
||||
}
|
||||
return items;
|
||||
});
|
||||
|
||||
const documentKindLabel = computed(() => {
|
||||
const kind = props.sample?.document_kind || collections.value?.document_kind || 'xfa_hybrid';
|
||||
return t(`admin.shippingOrderProfiles.xfa.documentKinds.${kind}`, kind);
|
||||
});
|
||||
|
||||
/**
|
||||
* 将 BusinessError 映射为用户可见文案(优先四语言 errors.codes)。
|
||||
* @param error - 捕获异常
|
||||
*/
|
||||
function resolveLoadErrorMessage(error: unknown): { code?: string; message: string } {
|
||||
if (error instanceof BusinessError) {
|
||||
const code = String(error.code || '').trim() || undefined;
|
||||
return {
|
||||
code,
|
||||
message: resolveLocalizedErrorMessage(code, error.message)
|
||||
|| t('admin.shippingOrderProfiles.wizard.xfa.loadFailed'),
|
||||
};
|
||||
}
|
||||
return { message: t('admin.shippingOrderProfiles.wizard.xfa.loadFailed') };
|
||||
}
|
||||
|
||||
/**
|
||||
* 加载 XFA 集合候选与字段树(用于展示标签)。
|
||||
* 核心逻辑:并发请求;失败写入 loadError 且清空 collections,禁止误显示“没有集合”。
|
||||
*/
|
||||
async function loadXfaContext(): Promise<void> {
|
||||
if (!props.documentId) return;
|
||||
loading.value = true;
|
||||
loadError.value = null;
|
||||
collections.value = null;
|
||||
flatNodes.value = flattenXfaTreeNodes(null);
|
||||
emit('update:contextReady', false);
|
||||
try {
|
||||
const [treeResp, collectionResp] = await Promise.all([
|
||||
getOrderProfileSampleXfaFieldTree(props.documentId),
|
||||
getOrderProfileSampleXfaCollections(props.documentId),
|
||||
]);
|
||||
collections.value = collectionResp;
|
||||
flatNodes.value = flattenXfaTreeNodes(
|
||||
treeResp.tree as import('@/features/admin/types/shipping-order-document-profile.types').XfaFieldTreeNode,
|
||||
);
|
||||
if (!props.authoritativePathId && collectionResp.collection_candidates.length === 1) {
|
||||
const only = collectionResp.collection_candidates[0];
|
||||
if (only?.path_id) emit('update:authoritativePathId', only.path_id);
|
||||
}
|
||||
emit('update:contextReady', true);
|
||||
} catch (error) {
|
||||
loadError.value = resolveLoadErrorMessage(error);
|
||||
message.error(loadError.value.message);
|
||||
emit('update:contextReady', false);
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 仅重新请求字段树与集合(不触发样本重新解析)。
|
||||
*/
|
||||
async function reloadContext(): Promise<void> {
|
||||
await loadXfaContext();
|
||||
}
|
||||
|
||||
/**
|
||||
* 独立“重新解析样本”:二次确认后调用 layout-reparse;成功后提示用户再点重新加载。
|
||||
*/
|
||||
async function reparseSample(): Promise<void> {
|
||||
if (!props.documentId || reparsing.value) return;
|
||||
const ok = window.confirm(t('admin.shippingOrderProfiles.wizard.xfa.reparseConfirm'));
|
||||
if (!ok) return;
|
||||
reparsing.value = true;
|
||||
try {
|
||||
await reparseOrderProfileSampleLayout(props.documentId);
|
||||
message.success(t('admin.shippingOrderProfiles.wizard.xfa.reparseStarted'));
|
||||
} catch (error) {
|
||||
message.error(
|
||||
error instanceof BusinessError
|
||||
? resolveLocalizedErrorMessage(error.code, error.message)
|
||||
: t('admin.shippingOrderProfiles.wizard.xfa.reparseFailed'),
|
||||
);
|
||||
} finally {
|
||||
reparsing.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
watch(() => props.documentId, () => void loadXfaContext(), { immediate: true });
|
||||
watch(contextReady, (ready) => emit('update:contextReady', ready));
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="xfa-confirm-step">
|
||||
<article v-if="sample" class="xfa-confirm-step__card">
|
||||
<header>
|
||||
<strong>{{ sample.filename || t('admin.shippingOrderProfiles.wizard.sampleSelected') }}</strong>
|
||||
<span class="xfa-confirm-step__badge">{{ documentKindLabel }}</span>
|
||||
</header>
|
||||
<p>{{ t('admin.shippingOrderProfiles.wizard.xfa.intro') }}</p>
|
||||
<ul class="xfa-confirm-step__checks">
|
||||
<li>{{ t('admin.shippingOrderProfiles.wizard.xfa.noBlankPdf') }}</li>
|
||||
<li>{{ t('admin.shippingOrderProfiles.wizard.xfa.scriptNotice') }}</li>
|
||||
</ul>
|
||||
</article>
|
||||
|
||||
<p v-if="loading" class="xfa-confirm-step__loading">{{ t('admin.shippingOrderProfiles.wizard.xfa.loading') }}</p>
|
||||
|
||||
<aside v-else-if="loadError" class="xfa-confirm-step__error" role="alert">
|
||||
<strong>{{ t('admin.shippingOrderProfiles.wizard.xfa.loadErrorTitle') }}</strong>
|
||||
<p>{{ loadError.message }}</p>
|
||||
<p v-if="loadError.code" class="xfa-confirm-step__error-code">{{ loadError.code }}</p>
|
||||
<p class="xfa-confirm-step__error-hint">{{ t('admin.shippingOrderProfiles.wizard.xfa.loadErrorHint') }}</p>
|
||||
<div class="xfa-confirm-step__error-actions">
|
||||
<button type="button" class="xfa-confirm-step__btn" @click="reloadContext">
|
||||
{{ t('admin.shippingOrderProfiles.wizard.xfa.reload') }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="xfa-confirm-step__btn xfa-confirm-step__btn--secondary"
|
||||
:disabled="reparsing"
|
||||
@click="reparseSample"
|
||||
>
|
||||
{{ t('admin.shippingOrderProfiles.wizard.xfa.reparseSample') }}
|
||||
</button>
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
<XfaCollectionSelector
|
||||
v-else-if="collections && (collections.collection_candidates?.length || excludedCollections.length)"
|
||||
:candidates="collections.collection_candidates || []"
|
||||
:excluded-candidates="excludedCollections"
|
||||
:authoritative-path-id="authoritativePathId"
|
||||
:mirror-path-ids="mirrorPathIds"
|
||||
@update:authoritative-path-id="emit('update:authoritativePathId', $event)"
|
||||
@update:mirror-path-ids="emit('update:mirrorPathIds', $event)"
|
||||
/>
|
||||
|
||||
<aside v-if="createBlockers.length" class="xfa-confirm-step__blockers" role="status">
|
||||
<strong>{{ t('admin.shippingOrderProfiles.xfaUnified.createBlockersTitle') }}</strong>
|
||||
<ul>
|
||||
<li v-for="(item, index) in createBlockers" :key="index">{{ item }}</li>
|
||||
</ul>
|
||||
</aside>
|
||||
|
||||
<p
|
||||
v-if="collections && !collections.collection_candidates?.length && !excludedCollections.length"
|
||||
class="xfa-confirm-step__loading"
|
||||
>
|
||||
{{ t('admin.shippingOrderProfiles.wizard.xfa.noCollections') }}
|
||||
</p>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.xfa-confirm-step { display: flex; flex-direction: column; gap: 16px; }
|
||||
.xfa-confirm-step__card { padding: 16px 18px; border: 1px solid var(--border-default); border-radius: var(--radius-control); background: var(--bg-surface-soft); }
|
||||
.xfa-confirm-step__card header { display: flex; align-items: center; justify-content: space-between; gap: 10px; margin-bottom: 8px; }
|
||||
.xfa-confirm-step__badge { padding: 2px 8px; border-radius: 999px; background: var(--status-info-bg); color: var(--status-info-fg); font-size: .72rem; font-weight: 700; }
|
||||
.xfa-confirm-step__checks { margin: 8px 0 0; padding-left: 18px; color: var(--text-secondary); font-size: .86rem; }
|
||||
.xfa-confirm-step__loading { margin: 0; color: var(--text-muted); }
|
||||
.xfa-confirm-step__blockers { padding: 12px 14px; border: 1px solid var(--status-warning-border); border-radius: var(--radius-control); background: var(--status-warning-bg); color: var(--status-warning-fg); font-size: .84rem; }
|
||||
.xfa-confirm-step__blockers ul { margin: 6px 0 0; padding-left: 18px; }
|
||||
.xfa-confirm-step__error { padding: 14px 16px; border: 1px solid var(--status-danger-border, #f1aeb5); border-radius: var(--radius-control); background: var(--status-danger-bg, #fff5f5); color: var(--status-danger-fg, #9b1c1c); font-size: .86rem; display: flex; flex-direction: column; gap: 8px; }
|
||||
.xfa-confirm-step__error-code { margin: 0; font-family: ui-monospace, monospace; font-size: .75rem; opacity: .85; }
|
||||
.xfa-confirm-step__error-hint { margin: 0; color: var(--text-secondary); }
|
||||
.xfa-confirm-step__error-actions { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 4px; }
|
||||
.xfa-confirm-step__btn { padding: 6px 12px; border-radius: var(--radius-control); border: 1px solid var(--border-default); background: var(--bg-surface); cursor: pointer; font-size: .84rem; }
|
||||
.xfa-confirm-step__btn--secondary { background: transparent; }
|
||||
.xfa-confirm-step__btn:disabled { opacity: .6; cursor: not-allowed; }
|
||||
</style>
|
||||
+2
-3
@@ -82,7 +82,7 @@ const canvasRegions = computed<OrderProfileCanvasRegion[]>(() => {
|
||||
}
|
||||
regions.push({
|
||||
id: `vc:${nr.region_id}`,
|
||||
kind: 'xfa_visual',
|
||||
kind: 'order_field',
|
||||
label: nr.label,
|
||||
region: { ...nr.region },
|
||||
pageNo,
|
||||
@@ -294,10 +294,9 @@ const orderedRegions = computed(() => {
|
||||
:mode="readonly ? 'readonly' : 'edit'"
|
||||
:regions="canvasRegions"
|
||||
:selected-region-id="selectedOrderRegionId"
|
||||
:creation-kind="readonly ? null : 'xfa_visual'"
|
||||
:creation-kind="readonly ? null : 'order_field'"
|
||||
:page-no="pageNo"
|
||||
:page-count="pageCount"
|
||||
annotation-tool-set="xfa_visual"
|
||||
@select="onCanvasSelect"
|
||||
@create="onCanvasCreate"
|
||||
@change="onCanvasChange"
|
||||
|
||||
-281
@@ -1,281 +0,0 @@
|
||||
<!--
|
||||
features/admin/modules/shipping-order-document-profiles/components/XfaAutoMarkPanel.vue
|
||||
用途:XFA OCR/Widget 自动标记建议面板;支持轮询进度与接受/调整/拒绝。
|
||||
依赖:vue-i18n;由 OrderProfileEditorPage(XFA desk)嵌入并接线 automark API。
|
||||
逻辑:props 驱动 suggestions/jobStatus;动作按钮在非 disabled 时 emit 给父级持久化。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, ref, watch } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
|
||||
/** 自动标记建议条目。 */
|
||||
export interface XfaAutoMarkSuggestion {
|
||||
suggestion_id: string;
|
||||
field_key?: string | null;
|
||||
field_code?: string | null;
|
||||
suggestion_origin?: 'widget_template' | 'ocr' | string | null;
|
||||
confidence?: number | null;
|
||||
status?: string | null;
|
||||
match_class?: string | null;
|
||||
summary?: string | null;
|
||||
ocr_text?: string | null;
|
||||
dataset_value?: string | null;
|
||||
iou?: number | null;
|
||||
needs_review?: boolean | null;
|
||||
}
|
||||
|
||||
const props = withDefaults(defineProps<{
|
||||
suggestions?: XfaAutoMarkSuggestion[];
|
||||
disabled?: boolean;
|
||||
initiallyExpanded?: boolean;
|
||||
/** queued|running|succeeded|failed|idle */
|
||||
jobStatus?: string | null;
|
||||
jobError?: string | null;
|
||||
}>(), {
|
||||
suggestions: () => [],
|
||||
disabled: false,
|
||||
initiallyExpanded: true,
|
||||
jobStatus: 'idle',
|
||||
jobError: null,
|
||||
});
|
||||
|
||||
const emit = defineEmits<{
|
||||
accept: [suggestion: XfaAutoMarkSuggestion];
|
||||
adjust: [suggestion: XfaAutoMarkSuggestion];
|
||||
reject: [suggestion: XfaAutoMarkSuggestion];
|
||||
retry: [];
|
||||
'run-full': [];
|
||||
}>();
|
||||
|
||||
const { t } = useI18n();
|
||||
const expanded = ref(props.initiallyExpanded);
|
||||
|
||||
watch(() => props.initiallyExpanded, (v) => { expanded.value = v; });
|
||||
|
||||
const items = computed(() => props.suggestions || []);
|
||||
const empty = computed(() => items.value.length === 0);
|
||||
const running = computed(() => ['queued', 'running', 'pending'].includes(String(props.jobStatus || '')));
|
||||
|
||||
/**
|
||||
* 切换面板展开/收起。
|
||||
*/
|
||||
function toggleExpanded(): void {
|
||||
expanded.value = !expanded.value;
|
||||
}
|
||||
|
||||
/**
|
||||
* 发出接受建议事件。
|
||||
*/
|
||||
function onAccept(suggestion: XfaAutoMarkSuggestion): void {
|
||||
if (props.disabled || suggestion.needs_review || suggestion.match_class === 'needs_review') return;
|
||||
emit('accept', suggestion);
|
||||
}
|
||||
|
||||
/**
|
||||
* 发出调整建议事件(定位到画布手工改框)。
|
||||
*/
|
||||
function onAdjust(suggestion: XfaAutoMarkSuggestion): void {
|
||||
if (props.disabled) return;
|
||||
emit('adjust', suggestion);
|
||||
}
|
||||
|
||||
/**
|
||||
* 发出驳回建议事件。
|
||||
*/
|
||||
function onReject(suggestion: XfaAutoMarkSuggestion): void {
|
||||
if (props.disabled) return;
|
||||
emit('reject', suggestion);
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析建议来源展示文案。
|
||||
*/
|
||||
function originLabel(origin: string | null | undefined): string {
|
||||
if (origin === 'widget_template') return t('admin.shippingOrderProfiles.xfaAutoMark.originWidget');
|
||||
if (origin === 'ocr') return t('admin.shippingOrderProfiles.xfaAutoMark.originOcr');
|
||||
return t('admin.shippingOrderProfiles.xfaAutoMark.originUnknown');
|
||||
}
|
||||
|
||||
/**
|
||||
* mismatch / needs_review 禁止直接接受。
|
||||
*/
|
||||
function acceptBlocked(item: XfaAutoMarkSuggestion): boolean {
|
||||
return Boolean(item.needs_review || item.match_class === 'needs_review');
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="xfa-auto-mark" :aria-label="t('admin.shippingOrderProfiles.xfaAutoMark.title')">
|
||||
<button
|
||||
type="button"
|
||||
class="xfa-auto-mark__header"
|
||||
:aria-expanded="expanded"
|
||||
@click="toggleExpanded"
|
||||
>
|
||||
<span class="xfa-auto-mark__title">
|
||||
{{ t('admin.shippingOrderProfiles.xfaAutoMark.title') }}
|
||||
</span>
|
||||
<span class="xfa-auto-mark__count">
|
||||
{{ t('admin.shippingOrderProfiles.xfaAutoMark.count', { count: items.length }) }}
|
||||
</span>
|
||||
<span v-if="running" class="xfa-auto-mark__job">{{ t('admin.shippingOrderProfiles.xfaAutoMark.running') }}</span>
|
||||
<span class="xfa-auto-mark__chevron">{{ expanded ? '▾' : '▸' }}</span>
|
||||
</button>
|
||||
|
||||
<div v-if="expanded" class="xfa-auto-mark__body">
|
||||
<p class="xfa-auto-mark__hint">
|
||||
{{ t('admin.shippingOrderProfiles.xfaAutoMark.hint') }}
|
||||
</p>
|
||||
<div class="xfa-auto-mark__toolbar">
|
||||
<button type="button" class="action-btn" :disabled="disabled || running" @click="emit('run-full')">
|
||||
{{ t('admin.shippingOrderProfiles.xfaAutoMark.runFull') }}
|
||||
</button>
|
||||
<button
|
||||
v-if="jobStatus === 'failed'"
|
||||
type="button"
|
||||
class="action-btn"
|
||||
:disabled="disabled"
|
||||
@click="emit('retry')"
|
||||
>
|
||||
{{ t('admin.shippingOrderProfiles.xfaAutoMark.retry') }}
|
||||
</button>
|
||||
</div>
|
||||
<p v-if="jobError" class="xfa-auto-mark__error">{{ jobError }}</p>
|
||||
<p v-if="empty && !running" class="xfa-auto-mark__empty">
|
||||
{{ t('admin.shippingOrderProfiles.xfaAutoMark.empty') }}
|
||||
</p>
|
||||
<ul v-else class="xfa-auto-mark__list">
|
||||
<li
|
||||
v-for="item in items"
|
||||
:key="item.suggestion_id"
|
||||
class="xfa-auto-mark__item"
|
||||
>
|
||||
<div class="xfa-auto-mark__meta">
|
||||
<span class="xfa-auto-mark__field">
|
||||
{{ item.field_code || item.field_key || item.suggestion_id }}
|
||||
</span>
|
||||
<span class="xfa-auto-mark__origin">{{ originLabel(item.suggestion_origin) }}</span>
|
||||
<span v-if="item.match_class" class="xfa-auto-mark__class">{{ item.match_class }}</span>
|
||||
<span v-if="item.confidence != null" class="xfa-auto-mark__confidence">
|
||||
{{ t('admin.shippingOrderProfiles.xfaAutoMark.confidence', {
|
||||
value: Math.round(Number(item.confidence) * 100),
|
||||
}) }}
|
||||
</span>
|
||||
</div>
|
||||
<p v-if="item.summary" class="xfa-auto-mark__summary">{{ item.summary }}</p>
|
||||
<p v-else-if="item.ocr_text || item.dataset_value" class="xfa-auto-mark__summary">
|
||||
OCR: {{ item.ocr_text || '—' }} · datasets: {{ item.dataset_value || '—' }}
|
||||
</p>
|
||||
<div class="xfa-auto-mark__actions">
|
||||
<button
|
||||
type="button"
|
||||
class="action-btn action-btn--active"
|
||||
:disabled="disabled || acceptBlocked(item)"
|
||||
@click="onAccept(item)"
|
||||
>
|
||||
{{ t('admin.shippingOrderProfiles.xfaAutoMark.accept') }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="action-btn action-btn--active"
|
||||
:disabled="disabled"
|
||||
@click="onAdjust(item)"
|
||||
>
|
||||
{{ t('admin.shippingOrderProfiles.xfaAutoMark.adjust') }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="action-btn action-btn--active action-btn--danger"
|
||||
:disabled="disabled"
|
||||
@click="onReject(item)"
|
||||
>
|
||||
{{ t('admin.shippingOrderProfiles.xfaAutoMark.reject') }}
|
||||
</button>
|
||||
</div>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.xfa-auto-mark {
|
||||
border-top: 1px solid #7dd3fc;
|
||||
border-radius: 0;
|
||||
background: #ecfeff;
|
||||
overflow: hidden;
|
||||
color: #155e75;
|
||||
}
|
||||
.xfa-auto-mark__header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
width: 100%;
|
||||
padding: 0.65rem 0.9rem;
|
||||
border: 0;
|
||||
background: transparent;
|
||||
cursor: pointer;
|
||||
text-align: left;
|
||||
color: #155e75;
|
||||
}
|
||||
.xfa-auto-mark__title { font-size: 0.75rem; font-weight: 600; }
|
||||
.xfa-auto-mark__count, .xfa-auto-mark__job {
|
||||
border-radius: 999px;
|
||||
background: #bae6fd;
|
||||
padding: 0.15rem 0.4rem;
|
||||
font-size: 0.72rem;
|
||||
color: #0e7490;
|
||||
}
|
||||
.xfa-auto-mark__chevron { margin-left: auto; color: #0e7490; font-size: 0.75rem; }
|
||||
.xfa-auto-mark__body { padding: 0 0.9rem 0.75rem; border-top: 1px solid #a5f3fc; }
|
||||
.xfa-auto-mark__hint, .xfa-auto-mark__empty { margin: 0.5rem 0 0; font-size: 0.75rem; color: #0e7490; }
|
||||
.xfa-auto-mark__error { margin: 0.35rem 0 0; font-size: 0.75rem; color: #b91c1c; }
|
||||
.xfa-auto-mark__toolbar { display: flex; gap: 0.35rem; margin-top: 0.45rem; }
|
||||
.xfa-auto-mark__toolbar .action-btn {
|
||||
border: 1px solid #0891b2;
|
||||
border-radius: 0.35rem;
|
||||
background: #fff;
|
||||
padding: 0.35rem 0.55rem;
|
||||
color: #0e7490;
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
.xfa-auto-mark__list {
|
||||
list-style: none;
|
||||
margin: 0.5rem 0 0;
|
||||
padding: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.5rem;
|
||||
max-height: 220px;
|
||||
overflow: auto;
|
||||
}
|
||||
.xfa-auto-mark__item {
|
||||
padding: 0.5rem;
|
||||
border: 1px solid #e2e8f0;
|
||||
border-radius: 0.375rem;
|
||||
background: #fff;
|
||||
}
|
||||
.xfa-auto-mark__meta { display: flex; flex-wrap: wrap; gap: 0.4rem; align-items: center; }
|
||||
.xfa-auto-mark__field { font-size: 0.8125rem; font-weight: 600; color: #0f172a; }
|
||||
.xfa-auto-mark__origin, .xfa-auto-mark__confidence, .xfa-auto-mark__class {
|
||||
font-size: 0.6875rem;
|
||||
color: #64748b;
|
||||
background: #f1f5f9;
|
||||
border-radius: 0.25rem;
|
||||
padding: 0.1rem 0.35rem;
|
||||
}
|
||||
.xfa-auto-mark__summary { margin: 0.35rem 0 0; font-size: 0.75rem; color: #475569; }
|
||||
.xfa-auto-mark__actions { display: flex; gap: 0.35rem; margin-top: 0.45rem; }
|
||||
.action-btn {
|
||||
font-size: 0.75rem;
|
||||
padding: 0.2rem 0.5rem;
|
||||
border-radius: 0.25rem;
|
||||
border: 1px solid #cbd5e1;
|
||||
background: #f8fafc;
|
||||
color: #334155;
|
||||
}
|
||||
.action-btn:disabled { cursor: not-allowed; opacity: 0.45; }
|
||||
.action-btn--active { cursor: pointer; opacity: 1; }
|
||||
.action-btn--active:hover:not(:disabled) { border-color: #60a5fa; background: #eff6ff; }
|
||||
.action-btn--danger { color: #991b1b; border-color: #fecaca; }
|
||||
</style>
|
||||
-151
@@ -1,151 +0,0 @@
|
||||
<!--
|
||||
features/admin/modules/shipping-order-document-profiles/components/XfaPreviewModeToggle.vue
|
||||
用途:【已废止 / DEPRECATED】原 XFA 原始 PDF / 合成预览双模式切换。
|
||||
依赖:vue-i18n、XfaPreviewCanvasMode 类型。
|
||||
逻辑:硬冻结后 EditorPage 不再导入;保留文件仅防旧引用,请勿在新产品路径使用。
|
||||
替代:唯一 flatten 合成图源;见 useOrderProfileXfaDesk + OrderProfileEditorPage 共享 desk。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import type { XfaPreviewCanvasMode } from '@/features/admin/types/shipping-order-document-profile.types';
|
||||
|
||||
/** @deprecated 双预览模式已废止;请勿再挂载本组件。 */
|
||||
const props = withDefaults(defineProps<{
|
||||
modelValue: XfaPreviewCanvasMode;
|
||||
status?: 'idle' | 'loading' | 'ready' | 'failed' | 'stale' | 'unavailable';
|
||||
pageCount?: number;
|
||||
disabled?: boolean;
|
||||
}>(), {
|
||||
status: 'idle',
|
||||
pageCount: 0,
|
||||
disabled: false,
|
||||
});
|
||||
|
||||
const emit = defineEmits<{
|
||||
'update:modelValue': [mode: XfaPreviewCanvasMode];
|
||||
'mode-change': [mode: XfaPreviewCanvasMode];
|
||||
}>();
|
||||
|
||||
const { t } = useI18n();
|
||||
|
||||
const statusText = computed(() => {
|
||||
switch (props.status) {
|
||||
case 'loading':
|
||||
return t('admin.shippingOrderProfiles.xfaWorkbench.previewMode.statusLoading');
|
||||
case 'ready':
|
||||
return t('admin.shippingOrderProfiles.xfaWorkbench.previewMode.statusReady', {
|
||||
pages: props.pageCount || 0,
|
||||
});
|
||||
case 'failed':
|
||||
return t('admin.shippingOrderProfiles.xfaWorkbench.previewMode.statusFailed');
|
||||
case 'stale':
|
||||
return t('admin.shippingOrderProfiles.xfaWorkbench.previewMode.statusStale');
|
||||
case 'unavailable':
|
||||
return t('admin.shippingOrderProfiles.xfaWorkbench.previewMode.statusUnavailable');
|
||||
default:
|
||||
return '';
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* 切换预览模式并同步 v-model / mode-change。
|
||||
* @param mode 目标模式
|
||||
*/
|
||||
function selectMode(mode: XfaPreviewCanvasMode): void {
|
||||
if (props.disabled || mode === props.modelValue) return;
|
||||
emit('update:modelValue', mode);
|
||||
emit('mode-change', mode);
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div
|
||||
class="xfa-preview-mode-toggle"
|
||||
role="group"
|
||||
:aria-label="t('admin.shippingOrderProfiles.xfaWorkbench.previewMode.label')"
|
||||
>
|
||||
<span class="xfa-preview-mode-toggle__label">
|
||||
{{ t('admin.shippingOrderProfiles.xfaWorkbench.previewMode.label') }}
|
||||
</span>
|
||||
<div class="xfa-preview-mode-toggle__buttons">
|
||||
<button
|
||||
type="button"
|
||||
class="mode-btn"
|
||||
:class="{ active: modelValue === 'original' }"
|
||||
:disabled="disabled"
|
||||
:aria-pressed="modelValue === 'original'"
|
||||
@click="selectMode('original')"
|
||||
>
|
||||
{{ t('admin.shippingOrderProfiles.xfaWorkbench.previewMode.original') }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="mode-btn"
|
||||
:class="{ active: modelValue === 'synthetic' }"
|
||||
:disabled="disabled"
|
||||
:aria-pressed="modelValue === 'synthetic'"
|
||||
@click="selectMode('synthetic')"
|
||||
>
|
||||
{{ t('admin.shippingOrderProfiles.xfaWorkbench.previewMode.synthetic') }}
|
||||
</button>
|
||||
</div>
|
||||
<p v-if="statusText" class="xfa-preview-mode-toggle__status" :data-status="status">
|
||||
{{ statusText }}
|
||||
</p>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.xfa-preview-mode-toggle {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 0.5rem 0.75rem;
|
||||
margin-bottom: 0.5rem;
|
||||
padding: 0.35rem 0;
|
||||
}
|
||||
.xfa-preview-mode-toggle__label {
|
||||
font-size: 0.75rem;
|
||||
font-weight: 600;
|
||||
color: #475569;
|
||||
}
|
||||
.xfa-preview-mode-toggle__buttons {
|
||||
display: inline-flex;
|
||||
border: 1px solid #cbd5e1;
|
||||
border-radius: 0.375rem;
|
||||
overflow: hidden;
|
||||
}
|
||||
.mode-btn {
|
||||
appearance: none;
|
||||
border: 0;
|
||||
background: #f8fafc;
|
||||
color: #334155;
|
||||
font-size: 0.75rem;
|
||||
padding: 0.3rem 0.65rem;
|
||||
cursor: pointer;
|
||||
}
|
||||
.mode-btn + .mode-btn {
|
||||
border-left: 1px solid #cbd5e1;
|
||||
}
|
||||
.mode-btn.active {
|
||||
background: #0f172a;
|
||||
color: #f8fafc;
|
||||
}
|
||||
.mode-btn:disabled {
|
||||
opacity: 0.55;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
.xfa-preview-mode-toggle__status {
|
||||
margin: 0;
|
||||
font-size: 0.7rem;
|
||||
color: #64748b;
|
||||
}
|
||||
.xfa-preview-mode-toggle__status[data-status='failed'],
|
||||
.xfa-preview-mode-toggle__status[data-status='stale'] {
|
||||
color: #b45309;
|
||||
}
|
||||
.xfa-preview-mode-toggle__status[data-status='ready'] {
|
||||
color: #047857;
|
||||
}
|
||||
</style>
|
||||
+17
-1
@@ -36,6 +36,22 @@ const i18n = createI18n({
|
||||
});
|
||||
|
||||
describe('XfaReadOnlyMapping', () => {
|
||||
it('renders the shared adapter-evidence empty state for coordinate profiles', () => {
|
||||
const wrapper = mount(XfaReadOnlyMapping, {
|
||||
props: {
|
||||
detail: {
|
||||
id: 2, profile_code: 'COORD', display_name: 'COORD', version: 1,
|
||||
status: 'published', schema_version_id: 1, structure_fingerprint: 'b'.repeat(64),
|
||||
definition: {}, template_mode: 'coordinate', lock_version: 1,
|
||||
} as never,
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
|
||||
expect(wrapper.text()).toContain('暂无映射');
|
||||
expect(wrapper.text()).not.toContain('不显示空白 PDF');
|
||||
});
|
||||
|
||||
it('renders structure identity and mappings without requesting PDF', () => {
|
||||
const wrapper = mount(XfaReadOnlyMapping, {
|
||||
props: {
|
||||
@@ -50,7 +66,7 @@ describe('XfaReadOnlyMapping', () => {
|
||||
definition: { template_mode: 'xfa_dataset' },
|
||||
template_mode: 'xfa_dataset',
|
||||
lock_version: 1,
|
||||
xfa_readonly_mapping: {
|
||||
value_source_readonly_mapping: {
|
||||
source_contract: {
|
||||
template_packet_checksum: 'sha256:tpl',
|
||||
dataset_structure_fingerprint: 'sha256:fp',
|
||||
|
||||
+8
-6
@@ -1,8 +1,9 @@
|
||||
<!--
|
||||
features/admin/modules/shipping-order-document-profiles/components/XfaReadOnlyMapping.vue
|
||||
用途:版本详情页 XFA 只读映射证据,替代空白 PDF 画布。
|
||||
依赖:vue-i18n、XFA readonly mapping DTO。
|
||||
逻辑:展示结构身份、Header/Line 映射与集合策略;不请求 PDF 预览页。
|
||||
用途:版本详情页统一值源 adapter 的只读证据面板。
|
||||
依赖:vue-i18n、Profile readonly mapping DTO。
|
||||
逻辑:所有模板均挂载该面板;coordinate 没有额外值源证据时展示空态,
|
||||
XFA 才显示 datasets 结构身份、Header/Line 路径映射与集合策略;不请求 PDF 预览页。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue';
|
||||
@@ -16,7 +17,7 @@ const props = defineProps<{
|
||||
const { t } = useI18n();
|
||||
|
||||
const mapping = computed(() => (props.detail as ShippingOrderDocumentProfile & {
|
||||
xfa_readonly_mapping?: {
|
||||
value_source_readonly_mapping?: {
|
||||
source_contract?: Record<string, unknown>;
|
||||
header_mappings?: Array<Record<string, unknown>>;
|
||||
line_mappings?: Array<Record<string, unknown>>;
|
||||
@@ -24,7 +25,8 @@ const mapping = computed(() => (props.detail as ShippingOrderDocumentProfile & {
|
||||
frozen_samples?: Array<Record<string, unknown>>;
|
||||
matching_signature_checksum?: string | null;
|
||||
};
|
||||
}).xfa_readonly_mapping || null);
|
||||
}).value_source_readonly_mapping || null);
|
||||
const hasValueSourceEvidence = computed(() => Boolean(mapping.value));
|
||||
|
||||
const source = computed(() => mapping.value?.source_contract || {});
|
||||
const headerMaps = computed(() => mapping.value?.header_mappings || []);
|
||||
@@ -33,7 +35,7 @@ const lineMaps = computed(() => mapping.value?.line_mappings || []);
|
||||
|
||||
<template>
|
||||
<section class="xfa-readonly" :aria-label="t('admin.shippingOrderProfiles.xfaReadonly.title')">
|
||||
<p class="hint">{{ t('admin.shippingOrderProfiles.xfaReadonly.noPdfHint') }}</p>
|
||||
<p v-if="hasValueSourceEvidence" class="hint">{{ t('admin.shippingOrderProfiles.xfaReadonly.noPdfHint') }}</p>
|
||||
<div v-if="!mapping" class="empty">{{ t('admin.shippingOrderProfiles.xfaReadonly.missing') }}</div>
|
||||
<template v-else>
|
||||
<div class="identity">
|
||||
|
||||
-70
@@ -1,70 +0,0 @@
|
||||
/**
|
||||
* features/admin/modules/shipping-order-document-profiles/components/XfaSchemaMappingPanel.spec.ts
|
||||
* 用途:验证 XFA Schema 映射面板渲染与 bind-field 事件。
|
||||
* 依赖:Vitest、@vue/test-utils、XfaSchemaMappingPanel。
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { mount } from '@vue/test-utils';
|
||||
import { createI18n } from 'vue-i18n';
|
||||
import XfaSchemaMappingPanel from './XfaSchemaMappingPanel.vue';
|
||||
|
||||
const i18n = createI18n({
|
||||
legacy: false,
|
||||
locale: 'zh-CN',
|
||||
messages: {
|
||||
'zh-CN': {
|
||||
admin: {
|
||||
shippingOrderProfiles: {
|
||||
xfaWorkbench: {
|
||||
schemaTitle: 'Schema',
|
||||
filter: { all: '全部', unmapped: '未映射' },
|
||||
scope: { header: '表头', line: '明细' },
|
||||
selectLeafFirst: '选叶子',
|
||||
unbind: '解除',
|
||||
requiredCoverage: '{mapped}/{total}',
|
||||
currentNode: '节点',
|
||||
noneSelected: '无',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const definition = {
|
||||
template_mode: 'xfa_dataset' as const,
|
||||
source_contract: {
|
||||
template_packet_checksum: 'a', dataset_structure_fingerprint: 'b', dataset_root_path: '/data',
|
||||
authoritative_line_collection_path: '/data/ITEMS', mirror_collection_paths: [],
|
||||
},
|
||||
header_mappings: [],
|
||||
line_mapping: { row_path: '/data/ITEMS', fields: [] },
|
||||
cross_checks: {
|
||||
acroform_enabled: true,
|
||||
mirror_collection_policy: 'must_match_when_present' as const,
|
||||
line_amount_formula: 'quantity_times_unit_price' as const,
|
||||
total_amount_policy: 'must_equal_line_sum' as const,
|
||||
},
|
||||
};
|
||||
|
||||
describe('XfaSchemaMappingPanel', () => {
|
||||
it('emits bind-field when a schema field is clicked with leaf selected', async () => {
|
||||
const wrapper = mount(XfaSchemaMappingPanel, {
|
||||
global: { plugins: [i18n] },
|
||||
props: {
|
||||
schemaFields: [{
|
||||
field_id: 'f1', field_code: 'customer_po_no', scope: 'header', display_name: 'PO', required: true,
|
||||
enabled: true, aliases: [], normalizer_key: 'trim', validator_keys: [], enum_options: [],
|
||||
evidence_policy: { required: false, source_precedence: [], conflict_policy: 'fail', allow_single_source: true },
|
||||
comparator_key: 'exact',
|
||||
}],
|
||||
definition,
|
||||
selectedPathId: 'leaf-path',
|
||||
selectedPathIsLeaf: true,
|
||||
selectedSourceScope: 'header',
|
||||
},
|
||||
});
|
||||
await wrapper.find('button.field').trigger('click');
|
||||
expect(wrapper.emitted('bind-field')?.[0]?.[0]).toMatchObject({ field_code: 'customer_po_no' });
|
||||
});
|
||||
});
|
||||
-163
@@ -1,163 +0,0 @@
|
||||
<!--
|
||||
features/admin/modules/shipping-order-document-profiles/components/XfaSchemaMappingPanel.vue
|
||||
用途:中栏 Schema 字段绑定面板(同 scope、类型兼容高亮)。
|
||||
依赖:vue-i18n、订单 Schema 字段。
|
||||
逻辑:点击字段绑定当前选中的原始 path 或拆分规则结果;仅过滤全部/未映射。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, ref } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import type { OrderXfaDatasetProfileDefinition } from '@/features/admin/types/shipping-order-document-profile.types';
|
||||
import type { ShippingOrderFieldConfig } from '@/features/admin/types/shipping-order-schema.types';
|
||||
|
||||
const props = defineProps<{
|
||||
schemaFields: ShippingOrderFieldConfig[];
|
||||
definition: OrderXfaDatasetProfileDefinition;
|
||||
selectedPathId?: string | null;
|
||||
selectedPathIsLeaf?: boolean;
|
||||
selectedRuleId?: string | null;
|
||||
selectedSourceScope?: 'header' | 'line' | null;
|
||||
filterMode?: 'all' | 'unmapped';
|
||||
mappedFieldPreviews?: {
|
||||
header: Array<{ fieldCode: string; pathLabel: string; value: string | null }>;
|
||||
line: Array<{ fieldCode: string; pathLabel: string; value: string | null }>;
|
||||
};
|
||||
}>();
|
||||
const emit = defineEmits<{
|
||||
'bind-field': [field: ShippingOrderFieldConfig, scope: 'header' | 'line'];
|
||||
'unbind-field': [fieldId: string];
|
||||
'update:filterMode': [mode: 'all' | 'unmapped'];
|
||||
}>();
|
||||
const { t } = useI18n();
|
||||
const localFilter = ref<'all' | 'unmapped'>(props.filterMode || 'all');
|
||||
|
||||
const boundIds = computed(() => {
|
||||
const ids = new Set<string>();
|
||||
for (const item of props.definition.header_mappings || []) ids.add(item.field_id);
|
||||
for (const item of props.definition.line_mapping?.fields || []) ids.add(item.field_id);
|
||||
for (const ruleSet of props.definition.split_rules || []) {
|
||||
for (const rule of ruleSet.rules || []) {
|
||||
if (rule.segment.handling === 'mapped' && rule.segment.target_field_id) ids.add(rule.segment.target_field_id);
|
||||
}
|
||||
}
|
||||
return ids;
|
||||
});
|
||||
|
||||
const mappingByFieldCode = computed(() => new Map(
|
||||
[...(props.mappedFieldPreviews?.header || []), ...(props.mappedFieldPreviews?.line || [])]
|
||||
.map((item) => [item.fieldCode, item]),
|
||||
));
|
||||
|
||||
/** 返回字段当前映射的路径与识别值,用于字段行内直接核对。 */
|
||||
function mappingFor(field: ShippingOrderFieldConfig) {
|
||||
return field.field_code ? mappingByFieldCode.value.get(field.field_code) : undefined;
|
||||
}
|
||||
|
||||
const groups = computed(() => {
|
||||
const mode = localFilter.value;
|
||||
const header: ShippingOrderFieldConfig[] = [];
|
||||
const line: ShippingOrderFieldConfig[] = [];
|
||||
for (const field of props.schemaFields) {
|
||||
if (!field.enabled) continue;
|
||||
const mapped = boundIds.value.has(field.field_id);
|
||||
if (mode === 'unmapped' && mapped) continue;
|
||||
if (field.scope === 'line') line.push(field);
|
||||
else header.push(field);
|
||||
}
|
||||
return { header, line };
|
||||
});
|
||||
|
||||
/**
|
||||
* 绑定当前原始叶子或拆分规则到 Schema 字段。
|
||||
* 拆分规则继承源节点作用域,只允许绑定同作用域字段。
|
||||
*/
|
||||
function bind(field: ShippingOrderFieldConfig): void {
|
||||
if (!props.selectedPathId || !props.selectedPathIsLeaf) return;
|
||||
if (props.selectedRuleId && field.scope !== props.selectedSourceScope) return;
|
||||
emit('bind-field', field, field.scope === 'line' ? 'line' : 'header');
|
||||
}
|
||||
|
||||
/** 将筛选按钮作为普通分段控制切换,避免声明不完整的 Tab 语义。 */
|
||||
function setFilter(mode: 'all' | 'unmapped'): void {
|
||||
localFilter.value = mode;
|
||||
emit('update:filterMode', mode);
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="xfa-schema" :aria-label="t('admin.shippingOrderProfiles.xfaWorkbench.schemaTitle')">
|
||||
<div class="xfa-schema__filters" role="group" :aria-label="t('admin.shippingOrderProfiles.xfaWorkbench.filterLabel')">
|
||||
<button
|
||||
v-for="mode in (['all', 'unmapped'] as const)"
|
||||
:key="mode"
|
||||
type="button"
|
||||
:aria-pressed="localFilter === mode"
|
||||
:class="{ active: localFilter === mode }"
|
||||
@click="setFilter(mode)"
|
||||
>
|
||||
{{ t(`admin.shippingOrderProfiles.xfaWorkbench.filter.${mode}`) }}
|
||||
</button>
|
||||
</div>
|
||||
<p v-if="!selectedPathIsLeaf" class="hint" id="xfa-schema-hint">{{ t('admin.shippingOrderProfiles.xfaWorkbench.selectLeafFirst') }}</p>
|
||||
<div v-for="(fields, scope) in { header: groups.header, line: groups.line }" :key="scope" class="group">
|
||||
<h3>{{ t(`admin.shippingOrderProfiles.xfaWorkbench.scope.${scope}`) }}</h3>
|
||||
<ul>
|
||||
<li v-for="field in fields" :key="field.field_id">
|
||||
<button
|
||||
type="button"
|
||||
class="field"
|
||||
:class="{ mapped: boundIds.has(field.field_id), disabled: !selectedPathIsLeaf || Boolean(selectedRuleId && field.scope !== selectedSourceScope) }"
|
||||
:disabled="!selectedPathIsLeaf || Boolean(selectedRuleId && field.scope !== selectedSourceScope)"
|
||||
:aria-describedby="!selectedPathIsLeaf ? 'xfa-schema-hint' : undefined"
|
||||
@click="bind(field)"
|
||||
>
|
||||
<span class="field__identity">
|
||||
<span>{{ field.display_name || field.field_code }}</span>
|
||||
<small>{{ field.field_code }}</small>
|
||||
</span>
|
||||
<span v-if="mappingFor(field)" class="field__mapping">
|
||||
<span class="field__path">← {{ mappingFor(field)?.pathLabel }}</span>
|
||||
<strong v-if="mappingFor(field)?.value" class="field__value">{{ mappingFor(field)?.value }}</strong>
|
||||
</span>
|
||||
<span v-else class="field__empty">{{ t('admin.shippingOrderProfiles.xfaWorkbench.unmappedValue') }}</span>
|
||||
<strong v-if="boundIds.has(field.field_id)" class="field__check">✓</strong>
|
||||
</button>
|
||||
<button
|
||||
v-if="boundIds.has(field.field_id)"
|
||||
type="button"
|
||||
class="unbind"
|
||||
@click="emit('unbind-field', field.field_id)"
|
||||
>
|
||||
{{ t('admin.shippingOrderProfiles.xfaWorkbench.unbind') }}
|
||||
</button>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.xfa-schema { display: flex; flex-direction: column; gap: 12px; min-height: 0; height: 100%; overflow: auto; }
|
||||
.xfa-schema__filters { display: flex; gap: 6px; }
|
||||
.xfa-schema__filters button { padding: 6px 10px; border: 1px solid var(--border-default); border-radius: 999px; background: var(--bg-surface); color: var(--text-secondary); }
|
||||
.xfa-schema__filters button.active { border-color: var(--status-info-border); color: var(--status-info-fg); background: var(--status-info-bg); }
|
||||
.hint { margin: 0; color: var(--status-warning-fg); font-size: .85rem; }
|
||||
.group h3 { margin: 0 0 8px; font-size: .9rem; }
|
||||
.group ul { margin: 0 0 14px; padding: 0; list-style: none; }
|
||||
.group li { display: flex; gap: 6px; margin-bottom: 6px; }
|
||||
.field { flex: 1; display: grid; grid-template-columns: minmax(180px, .7fr) minmax(260px, 1.3fr) auto; gap: 12px; align-items: center; min-width: 0; padding: 9px 12px; border: 1px solid var(--border-default); border-radius: var(--radius-control); background: var(--bg-surface); color: var(--text-primary); text-align: left; }
|
||||
.field.mapped { border-color: var(--status-success-border); background: var(--status-success-bg); }
|
||||
.field:focus-visible { outline: 2px solid var(--focus-ring); }
|
||||
.field__identity { display: flex; min-width: 0; align-items: baseline; gap: 8px; }
|
||||
.field__identity > span, .field__identity small { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.field small { color: var(--text-muted); }
|
||||
.field__mapping { display: flex; min-width: 0; align-items: center; justify-content: space-between; gap: 12px; }
|
||||
.field__path { min-width: 0; overflow: hidden; color: var(--text-secondary); font-size: .76rem; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.field__value { flex: 0 0 auto; max-width: 180px; overflow: hidden; color: var(--status-success-fg); font-size: .76rem; font-weight: 650; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.field__empty { color: var(--text-muted); font-size: .76rem; }
|
||||
.field__check { color: var(--status-success-fg); }
|
||||
.unbind { border: 0; background: transparent; color: var(--status-error-fg); cursor: pointer; }
|
||||
@media (max-width: 1100px) {
|
||||
.field { grid-template-columns: minmax(150px, .8fr) minmax(180px, 1.2fr) auto; }
|
||||
}
|
||||
</style>
|
||||
+110
@@ -244,6 +244,81 @@ describe('XfaSplitRulePanel', () => {
|
||||
expect(ruleSet?.requires_confirmation).toBe(true);
|
||||
});
|
||||
|
||||
it('maps a split segment only to an enabled Schema field and clears its target when kept as evidence', async () => {
|
||||
const wrapper = mountPanel({
|
||||
definition: { ...baseDefinition, split_rules: [makePipelineRuleSet()] },
|
||||
schemaFields: [
|
||||
{
|
||||
field_id: 'unit-price-id',
|
||||
field_code: 'unit_price',
|
||||
display_name: '单价',
|
||||
scope: 'line',
|
||||
enabled: true,
|
||||
required: false,
|
||||
value_type: 'decimal',
|
||||
aliases: [],
|
||||
normalizer_key: 'decimal',
|
||||
validator_keys: [],
|
||||
enum_options: [],
|
||||
evidence_policy: {
|
||||
required: true,
|
||||
source_precedence: [],
|
||||
conflict_policy: 'needs_review',
|
||||
allow_single_source: true,
|
||||
},
|
||||
comparator_key: 'decimal',
|
||||
},
|
||||
{
|
||||
field_id: 'retired-price-unit-id',
|
||||
field_code: 'price_unit',
|
||||
display_name: '价格单位',
|
||||
scope: 'line',
|
||||
enabled: false,
|
||||
required: false,
|
||||
value_type: 'decimal',
|
||||
aliases: [],
|
||||
normalizer_key: 'decimal',
|
||||
validator_keys: [],
|
||||
enum_options: [],
|
||||
evidence_policy: {
|
||||
required: true,
|
||||
source_precedence: [],
|
||||
conflict_policy: 'needs_review',
|
||||
allow_single_source: true,
|
||||
},
|
||||
comparator_key: 'decimal',
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
await wrapper.get('[data-testid="xfa-split-handling"]').setValue('mapped');
|
||||
let emitted = wrapper.emitted('update:split-rules');
|
||||
let nextDefinition = {
|
||||
...baseDefinition,
|
||||
split_rules: emitted?.[emitted.length - 1]?.[0] as typeof baseDefinition.split_rules,
|
||||
};
|
||||
await wrapper.setProps({ definition: nextDefinition });
|
||||
const target = wrapper.get('[data-testid="xfa-split-target-field"]');
|
||||
expect(target.text()).toContain('unit_price');
|
||||
expect(target.text()).not.toContain('price_unit');
|
||||
await target.setValue('unit-price-id');
|
||||
|
||||
emitted = wrapper.emitted('update:split-rules');
|
||||
let rule = (emitted?.[emitted.length - 1]?.[0] as typeof baseDefinition.split_rules)?.[0]?.rules[0];
|
||||
expect(rule?.segment).toMatchObject({
|
||||
handling: 'mapped',
|
||||
target_field_id: 'unit-price-id',
|
||||
target_field_code: 'unit_price',
|
||||
});
|
||||
|
||||
await wrapper.get('[data-testid="xfa-split-handling"]').setValue('evidence_only');
|
||||
emitted = wrapper.emitted('update:split-rules');
|
||||
rule = (emitted?.[emitted.length - 1]?.[0] as typeof baseDefinition.split_rules)?.[0]?.rules[0];
|
||||
expect(rule?.segment).toMatchObject({ handling: 'evidence_only' });
|
||||
expect(rule?.segment.target_field_id).toBeNull();
|
||||
expect(rule?.segment.target_field_code).toBeNull();
|
||||
});
|
||||
|
||||
it('editing a confirmed rule emits draft with bumped rule_version', async () => {
|
||||
const wrapper = mountPanel({
|
||||
definition: {
|
||||
@@ -299,6 +374,41 @@ describe('XfaSplitRulePanel', () => {
|
||||
expect(confirmed).toBeFalsy();
|
||||
});
|
||||
|
||||
it('blocks confirm when a mapped segment has no Schema target', async () => {
|
||||
previewMock.mockResolvedValue({
|
||||
preview_token: 'tok-mapped-empty',
|
||||
preview: {
|
||||
status: 'ok',
|
||||
mapped_fields: {},
|
||||
segments: [],
|
||||
evidence_only_segments: [],
|
||||
diagnostics: [],
|
||||
},
|
||||
});
|
||||
const wrapper = mountPanel({
|
||||
definition: {
|
||||
...baseDefinition,
|
||||
split_rules: [makePipelineRuleSet({
|
||||
rules: [{
|
||||
...makePipelineRuleSet().rules[0],
|
||||
segment: {
|
||||
...makePipelineRuleSet().rules[0].segment,
|
||||
handling: 'mapped',
|
||||
target_field_id: null,
|
||||
target_field_code: null,
|
||||
},
|
||||
}],
|
||||
})],
|
||||
},
|
||||
});
|
||||
await exposedActions(wrapper).runPreview();
|
||||
await flushPromises();
|
||||
exposedActions(wrapper).confirmRules();
|
||||
|
||||
expect(messageError).toHaveBeenCalledWith('目标必填');
|
||||
expect(wrapper.emitted('confirmed')).toBeUndefined();
|
||||
});
|
||||
|
||||
it('configures consecutive line extraction with range and join mode', async () => {
|
||||
const wrapper = mountPanel({
|
||||
definition: { ...baseDefinition, split_rules: [makePipelineRuleSet()] },
|
||||
|
||||
+68
@@ -24,6 +24,7 @@ import type {
|
||||
XfaSplitStage,
|
||||
XfaSplitStageType,
|
||||
} from '@/features/admin/types/shipping-order-document-profile.types';
|
||||
import type { ShippingOrderFieldConfig } from '@/features/admin/types/shipping-order-schema.types';
|
||||
|
||||
/** updateRule 局部补丁:segment/stages/matcher 允许浅合并字段 */
|
||||
type XfaSplitRulePatch = Omit<Partial<XfaSplitRule>, 'segment' | 'stages' | 'matcher'> & {
|
||||
@@ -49,6 +50,8 @@ const props = defineProps<{
|
||||
dirtyUnsaved?: boolean;
|
||||
persistedConfirmed?: boolean;
|
||||
autoAddRule?: boolean;
|
||||
/** 仅允许将 split segment 映射到当前启用 Schema 的正式字段。 */
|
||||
schemaFields?: ShippingOrderFieldConfig[];
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
@@ -71,6 +74,11 @@ const SEGMENT_CODE_RE = /^[a-z][a-z0-9_]{1,63}$/;
|
||||
|
||||
const isReadonly = computed(() => props.readonly || props.canEdit === false);
|
||||
|
||||
/** 可被拆分段正式写入的字段;Schema 外字段只能作为 evidence 保留。 */
|
||||
const splitTargetFields = computed(() => (props.schemaFields || []).filter((field) => (
|
||||
field.enabled !== false && Boolean(field.field_id && field.field_code)
|
||||
)));
|
||||
|
||||
const activeRuleSet = computed(() => {
|
||||
const pathId = props.selectedPathId || '';
|
||||
return (props.definition.split_rules || []).find((item) => item.source_path_id === pathId) || null;
|
||||
@@ -288,6 +296,13 @@ async function runPreview(): Promise<void> {
|
||||
*/
|
||||
function confirmRules(): void {
|
||||
if (!activeRuleSet.value || isReadonly.value) return;
|
||||
if (activeRuleSet.value.rules.some((rule) => (
|
||||
rule.segment.handling === 'mapped'
|
||||
&& (!rule.segment.target_field_id || !rule.segment.target_field_code)
|
||||
))) {
|
||||
message.error(t('admin.shippingOrderProfiles.xfaSplit.validationMappedTarget'));
|
||||
return;
|
||||
}
|
||||
const currentHash = hashRuleSet(activeRuleSet.value);
|
||||
if (!preview.value || previewRuleSetHash.value !== currentHash || !previewConfirmationToken.value) {
|
||||
message.error(t('admin.shippingOrderProfiles.xfaSplit.confirmNeedsPreview'));
|
||||
@@ -526,6 +541,29 @@ function updateRule(ruleId: string, patch: XfaSplitRulePatch): void {
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置拆分段的处理方式;仅证据段不可残留正式目标,避免后端隐式写值。
|
||||
*/
|
||||
function updateSegmentHandling(ruleId: string, handling: XfaSplitSegment['handling']): void {
|
||||
updateRule(ruleId, {
|
||||
segment: handling === 'evidence_only'
|
||||
? { handling, target_field_id: null, target_field_code: null }
|
||||
: { handling },
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 将 mapped 拆分段绑定到 Schema 字段 ID;从白名单反查 code,拒绝任意前端注入字段。
|
||||
*/
|
||||
function updateSegmentTarget(ruleId: string, fieldId: string): void {
|
||||
const field = splitTargetFields.value.find((item) => item.field_id === fieldId);
|
||||
updateRule(ruleId, {
|
||||
segment: field
|
||||
? { handling: 'mapped', target_field_id: field.field_id, target_field_code: field.field_code || null }
|
||||
: { handling: 'mapped', target_field_id: null, target_field_code: null },
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新 unmatched_line_policy。
|
||||
*/
|
||||
@@ -872,6 +910,36 @@ watch(activeRuleSet, (current, previous) => {
|
||||
@input="updateRule(rule.rule_id, { segment: { note: ($event.target as HTMLInputElement).value || null } })"
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
{{ t('admin.shippingOrderProfiles.xfaSplit.handling') }}
|
||||
<select
|
||||
data-testid="xfa-split-handling"
|
||||
:disabled="isReadonly"
|
||||
:value="rule.segment.handling"
|
||||
@change="updateSegmentHandling(rule.rule_id, ($event.target as HTMLSelectElement).value as XfaSplitSegment['handling'])"
|
||||
>
|
||||
<option value="evidence_only">{{ t('admin.shippingOrderProfiles.xfaSplit.evidenceOnly') }}</option>
|
||||
<option value="mapped">{{ t('admin.shippingOrderProfiles.xfaSplit.mapped') }}</option>
|
||||
</select>
|
||||
</label>
|
||||
<label v-if="rule.segment.handling === 'mapped'">
|
||||
{{ t('admin.shippingOrderProfiles.xfaSplit.targetField') }}
|
||||
<select
|
||||
data-testid="xfa-split-target-field"
|
||||
:disabled="isReadonly"
|
||||
:value="rule.segment.target_field_id || ''"
|
||||
:class="{ 'xfa-split__invalid': !rule.segment.target_field_id }"
|
||||
@change="updateSegmentTarget(rule.rule_id, ($event.target as HTMLSelectElement).value)"
|
||||
>
|
||||
<option value="">{{ t('admin.shippingOrderProfiles.xfaSplit.selectField') }}</option>
|
||||
<option v-for="field in splitTargetFields" :key="field.field_id" :value="field.field_id">
|
||||
{{ field.display_name }} ({{ field.field_code }})
|
||||
</option>
|
||||
</select>
|
||||
<small v-if="!rule.segment.target_field_id" class="xfa-split__hint-error">
|
||||
{{ t('admin.shippingOrderProfiles.xfaSplit.validationMappedTarget') }}
|
||||
</small>
|
||||
</label>
|
||||
|
||||
<div class="xfa-split__extraction">
|
||||
<label>
|
||||
|
||||
-94
@@ -1,94 +0,0 @@
|
||||
/**
|
||||
* features/admin/modules/shipping-order-document-profiles/components/XfaStructuredPreview.spec.ts
|
||||
* 用途:断言预览面板展示阻断摘要、脱敏样本与交叉校验策略。
|
||||
* 依赖:Vitest、@vue/test-utils、XfaStructuredPreview。
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { mount } from '@vue/test-utils';
|
||||
import { createI18n } from 'vue-i18n';
|
||||
import XfaStructuredPreview from './XfaStructuredPreview.vue';
|
||||
import type { OrderXfaDatasetProfileDefinition } from '@/features/admin/types/shipping-order-document-profile.types';
|
||||
|
||||
const i18n = createI18n({
|
||||
legacy: false,
|
||||
locale: 'zh-CN',
|
||||
messages: {
|
||||
'zh-CN': {
|
||||
common: { yes: '是', no: '否' },
|
||||
admin: {
|
||||
shippingOrderProfiles: {
|
||||
xfaWorkbench: {
|
||||
previewTitle: '预览', blockersTitle: '阻断', currentNode: '节点', noneSelected: '无',
|
||||
headerMaps: '表头', lineMaps: '明细', requiredCoverage: '必填 {mapped}/{total}',
|
||||
maskedSample: '脱敏样本值', noMappings: '暂无映射',
|
||||
crossChecksTitle: '交叉校验策略',
|
||||
crossCheck: {
|
||||
acroform: 'AcroForm 对账', mirror: '镜像集合',
|
||||
lineAmount: '明细金额公式', totalAmount: '表头总额策略',
|
||||
},
|
||||
previewHint: '请在验证页查看干跑结果',
|
||||
blocker: { required_fields_unmapped: '必填未映射' },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const definition: OrderXfaDatasetProfileDefinition = {
|
||||
template_mode: 'xfa_dataset',
|
||||
source_contract: {
|
||||
template_packet_checksum: 'tpl', dataset_structure_fingerprint: 'fp', dataset_root_path: '/data',
|
||||
authoritative_line_collection_path: '/data/ITEMS/DATA', mirror_collection_paths: [],
|
||||
},
|
||||
header_mappings: [{
|
||||
mapping_id: 'm1', field_id: 'f1', field_code: 'customer_po_no',
|
||||
data_path: '', path_id: 'hdr-ebeln', value_type: 'string',
|
||||
}],
|
||||
line_mapping: { row_path: '/data/ITEMS/DATA', fields: [] },
|
||||
cross_checks: {
|
||||
acroform_enabled: true, mirror_collection_policy: 'must_match_when_present',
|
||||
line_amount_formula: 'quantity_times_unit_price', total_amount_policy: 'must_equal_line_sum',
|
||||
},
|
||||
};
|
||||
|
||||
describe('XfaStructuredPreview', () => {
|
||||
it('renders template-local blockers without Schema required coverage', () => {
|
||||
const wrapper = mount(XfaStructuredPreview, {
|
||||
global: { plugins: [i18n] },
|
||||
props: {
|
||||
definition,
|
||||
coverage: {
|
||||
requiredTotal: 0, requiredMapped: 0,
|
||||
missingRequired: [],
|
||||
duplicateFieldIds: [], authoritativeMissing: true,
|
||||
},
|
||||
blockers: ['authoritative_collection_required'],
|
||||
},
|
||||
});
|
||||
expect(wrapper.find('[role="alert"]').exists()).toBe(true);
|
||||
});
|
||||
|
||||
it('shows compact mapping summary without internal cross-check details', () => {
|
||||
const wrapper = mount(XfaStructuredPreview, {
|
||||
global: { plugins: [i18n] },
|
||||
props: {
|
||||
definition,
|
||||
coverage: {
|
||||
requiredTotal: 1, requiredMapped: 1,
|
||||
missingRequired: [], duplicateFieldIds: [], authoritativeMissing: false,
|
||||
},
|
||||
mappedFieldPreviews: {
|
||||
header: [{
|
||||
mappingId: 'm1', fieldCode: 'customer_po_no', pathId: 'hdr-ebeln',
|
||||
pathLabel: 'EBELN', value: '4510000227',
|
||||
}],
|
||||
line: [],
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(wrapper.text()).toContain('customer_po_no');
|
||||
expect(wrapper.text()).not.toContain('交叉校验策略');
|
||||
expect(wrapper.text()).not.toContain('quantity_times_unit_price');
|
||||
});
|
||||
});
|
||||
-100
@@ -1,100 +0,0 @@
|
||||
<!--
|
||||
features/admin/modules/shipping-order-document-profiles/components/XfaStructuredPreview.vue
|
||||
用途:右侧阻断摘要与已完成字段映射的紧凑预览。
|
||||
依赖:vue-i18n、覆盖率摘要类型。
|
||||
逻辑:仅展示需要即时处理的阻断项和已完成映射;当前节点由左侧树/中间编辑区表达,交叉校验策略由验证页承担。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import type {
|
||||
OrderXfaDatasetProfileDefinition,
|
||||
XfaMappingCoverageSummary,
|
||||
} from '@/features/admin/types/shipping-order-document-profile.types';
|
||||
|
||||
export interface XfaMappedFieldPreviewRow {
|
||||
mappingId: string;
|
||||
fieldCode: string;
|
||||
pathId: string;
|
||||
pathLabel: string;
|
||||
value: string | null;
|
||||
}
|
||||
|
||||
const props = defineProps<{
|
||||
definition: OrderXfaDatasetProfileDefinition;
|
||||
coverage: XfaMappingCoverageSummary;
|
||||
mappedFieldPreviews?: {
|
||||
header: XfaMappedFieldPreviewRow[];
|
||||
line: XfaMappedFieldPreviewRow[];
|
||||
};
|
||||
blockers?: string[];
|
||||
}>();
|
||||
|
||||
const { t } = useI18n();
|
||||
|
||||
const headerRows = computed(() => props.mappedFieldPreviews?.header?.length
|
||||
? props.mappedFieldPreviews.header
|
||||
: (props.definition.header_mappings || []).map((item) => ({
|
||||
mappingId: item.mapping_id,
|
||||
fieldCode: item.field_code,
|
||||
pathId: item.path_id,
|
||||
pathLabel: item.path_id,
|
||||
value: null as string | null,
|
||||
})));
|
||||
|
||||
const lineRows = computed(() => props.mappedFieldPreviews?.line?.length
|
||||
? props.mappedFieldPreviews.line
|
||||
: (props.definition.line_mapping?.fields || []).map((item) => ({
|
||||
mappingId: item.mapping_id,
|
||||
fieldCode: item.field_code,
|
||||
pathId: item.path_id,
|
||||
pathLabel: item.path_id,
|
||||
value: null as string | null,
|
||||
})));
|
||||
const mappingRows = computed(() => [...headerRows.value, ...lineRows.value]);
|
||||
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="xfa-preview" :aria-label="t('admin.shippingOrderProfiles.xfaWorkbench.previewTitle')">
|
||||
<div v-if="blockers?.length" class="blockers" role="alert" tabindex="-1">
|
||||
<h3>{{ t('admin.shippingOrderProfiles.xfaWorkbench.blockersTitle') }}</h3>
|
||||
<ul>
|
||||
<li v-for="code in blockers" :key="code">{{ t(`admin.shippingOrderProfiles.xfaWorkbench.blocker.${code}`) }}</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div class="maps">
|
||||
<div class="maps__heading">
|
||||
<h3>{{ t('admin.shippingOrderProfiles.xfaWorkbench.mappingRelations') }}</h3>
|
||||
<span>{{ mappingRows.length }}</span>
|
||||
</div>
|
||||
<ul v-if="mappingRows.length" class="maps__list">
|
||||
<li v-for="item in mappingRows" :key="item.mappingId">
|
||||
<strong>{{ item.fieldCode }}</strong>
|
||||
← {{ item.pathLabel }}
|
||||
<span v-if="item.value" class="value">({{ item.value }})</span>
|
||||
</li>
|
||||
</ul>
|
||||
<p v-else class="empty">{{ t('admin.shippingOrderProfiles.xfaWorkbench.noMappings') }}</p>
|
||||
|
||||
</div>
|
||||
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.xfa-preview { display: flex; flex-direction: column; gap: 10px; min-height: 0; height: 100%; overflow: auto; }
|
||||
.blockers { padding: 10px; border: 1px solid var(--status-error-border); border-radius: var(--radius-control); background: var(--status-error-bg); color: var(--status-error-fg); }
|
||||
.blockers:focus { outline: 2px solid var(--focus-ring); }
|
||||
.maps { min-width: 0; padding: 10px; border: 1px solid var(--border-default); border-radius: var(--radius-control); background: var(--bg-surface); }
|
||||
.maps__heading { display: flex; align-items: center; justify-content: space-between; gap: 8px; }
|
||||
.maps__heading span { min-width: 1.5rem; border-radius: 999px; background: var(--bg-page); color: var(--text-muted); font-size: .68rem; text-align: center; }
|
||||
.maps__heading--line { margin-top: 12px; }
|
||||
.maps__list { display: grid; gap: 4px; margin: 0; padding: 0; list-style: none; }
|
||||
.maps li { min-width: 0; overflow: hidden; color: var(--text-secondary); font-size: .75rem; line-height: 1.35; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.value { color: var(--status-success-fg); }
|
||||
.empty { margin: 4px 0 0; color: var(--text-muted); font-size: .78rem; }
|
||||
h3 { margin: 0 0 8px; font-size: .9rem; }
|
||||
p { margin: 0; color: var(--text-secondary); }
|
||||
</style>
|
||||
+552
@@ -0,0 +1,552 @@
|
||||
/**
|
||||
* features/admin/modules/shipping-order-document-profiles/composables/useOrderProfileValueAdapter.spec.ts
|
||||
* 用途:验证 XFA datasets 末端值源不会吞掉共同画布字段选择。
|
||||
* 依赖:Vitest、Vue、useOrderProfileValueAdapter、Profile/Schema API mock。
|
||||
* 逻辑:共同 Editor 可先恢复并选中视觉字段;本测试确保 datasets 异步加载完成后仍创建
|
||||
* 未绑定值源槽位,供用户选择 path_id,且不影响共同 OCR 样本值展示流程。
|
||||
*/
|
||||
import { defineComponent, nextTick, ref } from 'vue';
|
||||
import { flushPromises, mount } from '@vue/test-utils';
|
||||
import { createI18n } from 'vue-i18n';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
|
||||
vi.mock('@/shared/composables/useMessage', () => ({
|
||||
useMessage: () => ({ error: vi.fn(), info: vi.fn() }),
|
||||
}));
|
||||
|
||||
vi.mock('@/features/admin/api/shipping-order-schema.api', () => ({
|
||||
getShippingOrderSchemaState: vi.fn().mockResolvedValue({
|
||||
versions: [{
|
||||
id: 7,
|
||||
definition: { fields: [
|
||||
{ field_id: 'field-po', field_code: 'customer_po_number', scope: 'header' },
|
||||
{ field_id: 'field-material', field_code: 'material_number', scope: 'line' },
|
||||
] },
|
||||
}],
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock('@/features/admin/api/shipping-order-document-profile.api', () => ({
|
||||
getOrderDocumentProfileDetail: vi.fn().mockResolvedValue({
|
||||
id: 9,
|
||||
lock_version: 1,
|
||||
display_name: 'XFA sample',
|
||||
profile_code: 'XFA-TEST',
|
||||
schema_version_id: 7,
|
||||
definition: {
|
||||
template_mode: 'xfa_dataset',
|
||||
source_contract: {},
|
||||
header_mappings: [],
|
||||
line_mapping: { fields: [] },
|
||||
cross_checks: {},
|
||||
bindings: [],
|
||||
split_rules: [],
|
||||
},
|
||||
}),
|
||||
listOrderProfileBoundSamples: vi.fn().mockResolvedValue([{ document_id: 101, sample_role: 'annotation' }]),
|
||||
getOrderProfileSampleXfaFieldTree: vi.fn().mockResolvedValue({
|
||||
tree: {
|
||||
path_id: 'root', local_name: 'data', data_path_hash: 'root-hash', depth: 0,
|
||||
cardinality: 'one', is_leaf: false, children: [{
|
||||
path_id: 'header-po', parent_path_id: 'root', local_name: 'HEADER_PO', data_path_hash: 'header-po-hash', depth: 1,
|
||||
cardinality: 'one', is_leaf: true, children: [],
|
||||
}, {
|
||||
path_id: 'items-collection', parent_path_id: 'root', local_name: 'ITEMS', data_path_hash: 'items-hash', depth: 1,
|
||||
cardinality: 'many', is_leaf: false, children: [{
|
||||
path_id: 'po-path', parent_path_id: 'items-collection', local_name: 'EBELN', data_path_hash: 'po-hash', depth: 2,
|
||||
cardinality: 'one', is_leaf: true, children: [],
|
||||
}],
|
||||
}],
|
||||
},
|
||||
}),
|
||||
getOrderProfileSampleXfaCollections: vi.fn().mockResolvedValue({ collection_candidates: [], excluded_collection_candidates: [] }),
|
||||
previewOrderProfileSampleXfaValue: vi.fn().mockResolvedValue({
|
||||
path_id: 'po-path', display_value: '4510039227', sample_value_masked: '4510******', display_policy: 'full',
|
||||
}),
|
||||
previewOrderProfileSampleXfaSplitRules: vi.fn(),
|
||||
}));
|
||||
|
||||
import { useOrderProfileValueAdapter } from './useOrderProfileValueAdapter';
|
||||
import type { OrderProfileDefinition } from '@/features/admin/types/shipping-order-document-profile.types';
|
||||
|
||||
const i18n = createI18n({ legacy: false, locale: 'zh-CN', messages: { 'zh-CN': {} } });
|
||||
|
||||
describe('useOrderProfileValueAdapter', () => {
|
||||
it('restores a shared visual selection made before the datasets definition finishes loading', async () => {
|
||||
const enabled = ref(false);
|
||||
const state = ref<'saved' | 'saving' | 'failed' | 'readonly'>('saved');
|
||||
let desk: ReturnType<typeof useOrderProfileValueAdapter> | null = null;
|
||||
const Harness = defineComponent({
|
||||
setup() {
|
||||
desk = useOrderProfileValueAdapter({ profileId: () => 9, saveState: state, enabled });
|
||||
// Assertion intent: canvas selection precedes the async datasets tree response.
|
||||
desk.selectSharedField('customer_po_number', 'order_field_1_1');
|
||||
return () => null;
|
||||
},
|
||||
});
|
||||
|
||||
mount(Harness, { global: { plugins: [i18n] } });
|
||||
await desk?.load();
|
||||
await flushPromises();
|
||||
await nextTick();
|
||||
|
||||
expect(desk?.selectedBinding.value?.field_layout_id).toBe('order_field_1_1');
|
||||
expect(desk?.selectedBinding.value?.value_binding.path_id).toBeNull();
|
||||
expect(desk?.showDatasetsSection.value).toBe(true);
|
||||
});
|
||||
|
||||
it('does not serialize a Schema-bound shared layout as an unbound datasets draft', async () => {
|
||||
const enabled = ref(false);
|
||||
const state = ref<'saved' | 'saving' | 'failed' | 'readonly'>('saved');
|
||||
let desk: ReturnType<typeof useOrderProfileValueAdapter> | null = null;
|
||||
const Harness = defineComponent({
|
||||
setup() {
|
||||
desk = useOrderProfileValueAdapter({ profileId: () => 9, saveState: state, enabled });
|
||||
return () => null;
|
||||
},
|
||||
});
|
||||
|
||||
mount(Harness, { global: { plugins: [i18n] } });
|
||||
await desk?.load();
|
||||
desk!.authoritativePathId.value = 'root';
|
||||
const visualDefinition = {
|
||||
document_match: { document_type: 'purchase_order', page_pattern: 'one_or_more', required_anchors: [], optional_anchors: [] },
|
||||
table_regions: [],
|
||||
order_field_layouts: [{
|
||||
layout_id: 'order_field_1_1', field_id: 'field-po', field_code: 'customer_po_number',
|
||||
scope: 'header', page_scope: 'exact_page', page_no: 1, anchor: null,
|
||||
absolute_value_region: null, fallback_value_region: { x0: .1, y0: .1, x1: .2, y1: .2 },
|
||||
value_mode: 'single_line', stop_anchors: [], normalizer_key: 'trim', required: false,
|
||||
minimum_evidence_level: 'coordinate',
|
||||
}],
|
||||
draft_unbound_order_field_layouts: Array.from({ length: 6 }, () => ({
|
||||
layout_id: 'order_field_1_1', label: '客户 PO 号', page_scope: 'exact_page', page_no: 1,
|
||||
anchor: null, absolute_value_region: null,
|
||||
fallback_value_region: { x0: .1, y0: .1, x1: .2, y1: .2 },
|
||||
value_mode: 'single_line', stop_anchors: [], minimum_evidence_level: 'coordinate',
|
||||
})),
|
||||
} as unknown as OrderProfileDefinition;
|
||||
|
||||
const payload = desk?.buildDraftPayload(visualDefinition);
|
||||
|
||||
// 关键断言:datasets 尚未选择路径不改变共同 Schema 绑定,也不得制造 unbound 重复项。
|
||||
expect(payload?.definition.draft_unbound_order_field_layouts).toEqual([]);
|
||||
expect(payload?.definition.bindings).toEqual([]);
|
||||
});
|
||||
|
||||
it('loads the controlled datasets sample value after selecting a shared field path', async () => {
|
||||
const enabled = ref(false);
|
||||
const state = ref<'saved' | 'saving' | 'failed' | 'readonly'>('saved');
|
||||
let desk: ReturnType<typeof useOrderProfileValueAdapter> | null = null;
|
||||
const Harness = defineComponent({
|
||||
setup() {
|
||||
desk = useOrderProfileValueAdapter({ profileId: () => 9, saveState: state, enabled });
|
||||
return () => null;
|
||||
},
|
||||
});
|
||||
|
||||
mount(Harness, { global: { plugins: [i18n] } });
|
||||
await desk?.load();
|
||||
desk?.selectSharedField('customer_po_number', 'order_field_1_2');
|
||||
desk?.updateSelectedDatasetsPath('po-path', true);
|
||||
await flushPromises();
|
||||
|
||||
// 关键断言:datasets 样本值来自受控 value-preview API,而不是树 DTO 的旧缓存。
|
||||
expect(desk?.selectedSampleValue.value).toBe('4510039227');
|
||||
});
|
||||
|
||||
it('keeps a datasets binding attached to a shared line field when saving', async () => {
|
||||
const enabled = ref(false);
|
||||
const state = ref<'saved' | 'saving' | 'failed' | 'readonly'>('saved');
|
||||
let desk: ReturnType<typeof useOrderProfileValueAdapter> | null = null;
|
||||
const Harness = defineComponent({
|
||||
setup() {
|
||||
desk = useOrderProfileValueAdapter({ profileId: () => 9, saveState: state, enabled });
|
||||
return () => null;
|
||||
},
|
||||
});
|
||||
|
||||
mount(Harness, { global: { plugins: [i18n] } });
|
||||
await desk?.load();
|
||||
desk!.authoritativePathId.value = 'items-collection';
|
||||
desk?.selectSharedField('material_number', 'line_1:material_number');
|
||||
desk?.updateSelectedDatasetsPath('po-path', true);
|
||||
await flushPromises();
|
||||
const visualDefinition = {
|
||||
document_match: { document_type: 'purchase_order', page_pattern: 'one_or_more', required_anchors: [], optional_anchors: [] },
|
||||
order_field_layouts: [], draft_unbound_order_field_layouts: [],
|
||||
table_regions: [{
|
||||
region_id: 'main_lines_page_1', page_scope: 'exact_page', page_no: 1,
|
||||
region: { x0: .1, y0: .2, x1: .9, y1: .8 }, header_layouts: [],
|
||||
line_layouts: [{
|
||||
layout_id: 'line_1', row_offset: 0, role: 'main', region: { x0: .1, y0: .3, x1: .9, y1: .4 },
|
||||
field_regions: [{
|
||||
field_id: 'field-material', field_code: 'material_number', scope: 'line',
|
||||
region: { x0: .2, y0: .3, x1: .4, y1: .4 }, extractor_key: 'direct',
|
||||
allowed_sources: ['pdf_coordinate'], minimum_evidence_level: 'coordinate',
|
||||
}], new_line_anchor: null, continuation_conditions: [], required_fields: [], allowed_empty_fields: [],
|
||||
}], continuation_rule: { allow_cross_page: false, required_anchor_ids: [] },
|
||||
termination_rules: [], exclusion_regions: [],
|
||||
}],
|
||||
} as unknown as OrderProfileDefinition;
|
||||
|
||||
const payload = desk?.buildDraftPayload(visualDefinition);
|
||||
|
||||
// 关键断言:XFA 只追加 path;共同明细视觉框仍是唯一布局身份,保存不可丢 binding。
|
||||
expect(payload?.definition.bindings).toEqual(expect.arrayContaining([
|
||||
expect.objectContaining({ field_layout_id: 'line_1:material_number', value_binding: expect.objectContaining({ path_id: 'po-path' }) }),
|
||||
]));
|
||||
});
|
||||
|
||||
it('uses the visual field scope when header and line reuse one Schema code', async () => {
|
||||
const enabled = ref(false);
|
||||
const state = ref<'saved' | 'saving' | 'failed' | 'readonly'>('saved');
|
||||
let desk: ReturnType<typeof useOrderProfileValueAdapter> | null = null;
|
||||
const Harness = defineComponent({
|
||||
setup() {
|
||||
desk = useOrderProfileValueAdapter({ profileId: () => 9, saveState: state, enabled });
|
||||
return () => null;
|
||||
},
|
||||
});
|
||||
|
||||
mount(Harness, { global: { plugins: [i18n] } });
|
||||
await desk?.load();
|
||||
desk!.schemaFields.value = [
|
||||
{ field_id: 'reservation-header', field_code: 'reservation_id', scope: 'header' },
|
||||
{ field_id: 'reservation-line', field_code: 'reservation_id', scope: 'line' },
|
||||
];
|
||||
desk!.selectSharedField('reservation_id', 'line_1:reservation_id', 'line');
|
||||
|
||||
// 关键断言:相同 code 不能让明细画框错误绑定到 Header 字段。
|
||||
expect(desk!.selectedBinding.value).toMatchObject({
|
||||
field_id: 'reservation-line', field_code: 'reservation_id', scope: 'line',
|
||||
});
|
||||
});
|
||||
|
||||
it('keeps a table-header visual field in the line datasets binding scope', async () => {
|
||||
const enabled = ref(false);
|
||||
const state = ref<'saved' | 'saving' | 'failed' | 'readonly'>('saved');
|
||||
let desk: ReturnType<typeof useOrderProfileValueAdapter> | null = null;
|
||||
const Harness = defineComponent({
|
||||
setup() {
|
||||
desk = useOrderProfileValueAdapter({ profileId: () => 9, saveState: state, enabled });
|
||||
return () => null;
|
||||
},
|
||||
});
|
||||
|
||||
mount(Harness, { global: { plugins: [i18n] } });
|
||||
await desk?.load();
|
||||
desk!.schemaFields.value = [
|
||||
{ field_id: 'line-material', field_code: 'material_number', scope: 'line' },
|
||||
];
|
||||
desk!.selectSharedField('material_number', 'header_1:material_number', 'line');
|
||||
|
||||
// 关键断言:表格列头是明细字段的视觉入口,正式 datasets binding 仍必须落到 line scope。
|
||||
expect(desk!.selectedBinding.value).toMatchObject({
|
||||
field_id: 'line-material', field_code: 'material_number', scope: 'line',
|
||||
field_layout_id: 'header_1:material_number',
|
||||
});
|
||||
});
|
||||
|
||||
it('moves one configured datasets path when its shared visual field is rebound', async () => {
|
||||
const enabled = ref(false);
|
||||
const state = ref<'saved' | 'saving' | 'failed' | 'readonly'>('saved');
|
||||
let desk: ReturnType<typeof useOrderProfileValueAdapter> | null = null;
|
||||
const Harness = defineComponent({
|
||||
setup() {
|
||||
desk = useOrderProfileValueAdapter({ profileId: () => 9, saveState: state, enabled });
|
||||
return () => null;
|
||||
},
|
||||
});
|
||||
|
||||
mount(Harness, { global: { plugins: [i18n] } });
|
||||
await desk?.load();
|
||||
desk!.schemaFields.value = [
|
||||
{ field_id: 'line-material', field_code: 'material_number', scope: 'line' },
|
||||
{ field_id: 'line-internal', field_code: 'part_number', scope: 'line' },
|
||||
];
|
||||
desk!.definition.value = {
|
||||
...desk!.definition.value!,
|
||||
bindings: [{
|
||||
binding_id: 'material-binding', field_id: 'line-material', field_code: 'material_number', scope: 'line',
|
||||
field_layout_id: 'header_1:material_number',
|
||||
value_binding: { type: 'xfa_dataset', path_id: 'po-path', data_path: '/data/items/material' },
|
||||
}],
|
||||
};
|
||||
|
||||
desk!.migrateUniqueSharedFieldBinding(
|
||||
'material_number', 'header_1:material_number', 'part_number', 'header_1:part_number', 'line',
|
||||
);
|
||||
|
||||
// 关键断言:用户改绑同一视觉列时,唯一正式路径随框迁移,不遗留孤儿旧 identity。
|
||||
expect(desk!.definition.value?.bindings).toEqual([expect.objectContaining({
|
||||
field_id: 'line-internal', field_code: 'part_number', scope: 'line',
|
||||
field_layout_id: 'header_1:part_number',
|
||||
value_binding: expect.objectContaining({ path_id: 'po-path' }),
|
||||
})]);
|
||||
});
|
||||
|
||||
it('does not infer a migration when one visual field has multiple formal bindings', async () => {
|
||||
const enabled = ref(false);
|
||||
const state = ref<'saved' | 'saving' | 'failed' | 'readonly'>('saved');
|
||||
let desk: ReturnType<typeof useOrderProfileValueAdapter> | null = null;
|
||||
const Harness = defineComponent({
|
||||
setup() {
|
||||
desk = useOrderProfileValueAdapter({ profileId: () => 9, saveState: state, enabled });
|
||||
return () => null;
|
||||
},
|
||||
});
|
||||
|
||||
mount(Harness, { global: { plugins: [i18n] } });
|
||||
await desk?.load();
|
||||
desk!.schemaFields.value = [{ field_id: 'line-internal', field_code: 'part_number', scope: 'line' }];
|
||||
desk!.definition.value = {
|
||||
...desk!.definition.value!,
|
||||
bindings: [
|
||||
{ binding_id: 'first', field_id: 'one', field_code: 'one', scope: 'line', field_layout_id: 'line_1:old', value_binding: { type: 'xfa_dataset', path_id: 'po-path', data_path: null } },
|
||||
{ binding_id: 'second', field_id: 'two', field_code: 'two', scope: 'line', field_layout_id: 'line_1:old', value_binding: { type: 'xfa_dataset', path_id: 'header-po', data_path: null } },
|
||||
],
|
||||
};
|
||||
|
||||
desk!.migrateUniqueSharedFieldBinding('old', 'line_1:old', 'part_number', 'line_1:part_number', 'line');
|
||||
|
||||
// 关键断言:多个正式字段共享一个视觉框时保持 fail-closed,不能擅自选一个迁移。
|
||||
expect(desk!.definition.value?.bindings.map((item) => item.field_layout_id)).toEqual(['line_1:old', 'line_1:old']);
|
||||
});
|
||||
|
||||
it('keeps multiple datasets bindings that intentionally share one visual field layout', async () => {
|
||||
const enabled = ref(false);
|
||||
const state = ref<'saved' | 'saving' | 'failed' | 'readonly'>('saved');
|
||||
let desk: ReturnType<typeof useOrderProfileValueAdapter> | null = null;
|
||||
const Harness = defineComponent({
|
||||
setup() {
|
||||
desk = useOrderProfileValueAdapter({ profileId: () => 9, saveState: state, enabled });
|
||||
return () => null;
|
||||
},
|
||||
});
|
||||
|
||||
mount(Harness, { global: { plugins: [i18n] } });
|
||||
await desk?.load();
|
||||
desk!.authoritativePathId.value = 'items-collection';
|
||||
desk!.definition.value = {
|
||||
...desk!.definition.value!,
|
||||
bindings: [
|
||||
{
|
||||
binding_id: 'customer-part', field_id: 'field-customer-part', field_code: 'customer_part_number', scope: 'line',
|
||||
field_layout_id: 'line_1:customer_part_number',
|
||||
value_binding: { type: 'xfa_dataset', path_id: 'customer-path', data_path: '/data/items/MATNR' },
|
||||
},
|
||||
{
|
||||
binding_id: 'internal-part', field_id: 'field-internal-part', field_code: 'part_number', scope: 'line',
|
||||
field_layout_id: 'line_1:customer_part_number',
|
||||
value_binding: { type: 'xfa_dataset', path_id: 'internal-path', data_path: '/data/items/MATNR' },
|
||||
},
|
||||
],
|
||||
};
|
||||
const visualDefinition = {
|
||||
document_match: { document_type: 'purchase_order', page_pattern: 'one_or_more', required_anchors: [], optional_anchors: [] },
|
||||
order_field_layouts: [], draft_unbound_order_field_layouts: [],
|
||||
table_regions: [{
|
||||
region_id: 'main_lines_page_1', page_scope: 'exact_page', page_no: 1,
|
||||
region: { x0: .1, y0: .2, x1: .9, y1: .8 }, header_layouts: [],
|
||||
line_layouts: [{
|
||||
layout_id: 'line_1', row_offset: 0, role: 'main', region: { x0: .1, y0: .3, x1: .9, y1: .4 },
|
||||
field_regions: [{
|
||||
field_id: 'field-customer-part', field_code: 'customer_part_number', scope: 'line',
|
||||
region: { x0: .2, y0: .3, x1: .4, y1: .4 }, extractor_key: 'direct',
|
||||
allowed_sources: ['pdf_coordinate'], minimum_evidence_level: 'coordinate',
|
||||
}], new_line_anchor: null, continuation_conditions: [], required_fields: [], allowed_empty_fields: [],
|
||||
}], continuation_rule: { allow_cross_page: false, required_anchor_ids: [] },
|
||||
termination_rules: [], exclusion_regions: [],
|
||||
}],
|
||||
} as unknown as OrderProfileDefinition;
|
||||
|
||||
const payload = desk!.buildDraftPayload(visualDefinition);
|
||||
expect(payload?.definition.bindings.map((item) => item.binding_id)).toEqual(['customer-part', 'internal-part']);
|
||||
});
|
||||
|
||||
it('blocks saving when an existing formal datasets binding has no shared visual layout', async () => {
|
||||
const enabled = ref(false);
|
||||
const state = ref<'saved' | 'saving' | 'failed' | 'readonly'>('saved');
|
||||
let desk: ReturnType<typeof useOrderProfileValueAdapter> | null = null;
|
||||
const Harness = defineComponent({
|
||||
setup() {
|
||||
desk = useOrderProfileValueAdapter({ profileId: () => 9, saveState: state, enabled });
|
||||
return () => null;
|
||||
},
|
||||
});
|
||||
|
||||
mount(Harness, { global: { plugins: [i18n] } });
|
||||
await desk?.load();
|
||||
desk!.authoritativePathId.value = 'root';
|
||||
desk!.definition.value = {
|
||||
...desk!.definition.value!,
|
||||
bindings: [{
|
||||
binding_id: 'currency-binding', field_id: 'field-currency', field_code: 'currency', scope: 'header',
|
||||
field_layout_id: 'xfa_header_currency',
|
||||
value_binding: { type: 'xfa_dataset', path_id: 'po-path', data_path: '/data/currency' },
|
||||
}],
|
||||
};
|
||||
const visualDefinition = {
|
||||
document_match: { document_type: 'purchase_order', page_pattern: 'one_or_more', required_anchors: [], optional_anchors: [] },
|
||||
order_field_layouts: [], draft_unbound_order_field_layouts: [], table_regions: [],
|
||||
} as unknown as OrderProfileDefinition;
|
||||
|
||||
const payload = desk!.buildDraftPayload(visualDefinition);
|
||||
|
||||
// 关键断言:正式 datasets binding 不得因本次画布缺少其共同框而被静默删除。
|
||||
expect(payload).toBeNull();
|
||||
});
|
||||
|
||||
it('carries an explicit formal binding deletion through the save payload', async () => {
|
||||
const enabled = ref(false);
|
||||
const state = ref<'saved' | 'saving' | 'failed' | 'readonly'>('saved');
|
||||
let desk: ReturnType<typeof useOrderProfileValueAdapter> | null = null;
|
||||
const Harness = defineComponent({
|
||||
setup() {
|
||||
desk = useOrderProfileValueAdapter({ profileId: () => 9, saveState: state, enabled });
|
||||
return () => null;
|
||||
},
|
||||
});
|
||||
|
||||
mount(Harness, { global: { plugins: [i18n] } });
|
||||
await desk?.load();
|
||||
desk!.authoritativePathId.value = 'root';
|
||||
desk!.definition.value = {
|
||||
...desk!.definition.value!,
|
||||
bindings: [{
|
||||
binding_id: 'currency-binding', field_id: 'field-currency', field_code: 'currency', scope: 'header',
|
||||
field_layout_id: 'xfa_header_currency',
|
||||
value_binding: { type: 'xfa_dataset', path_id: 'po-path', data_path: '/data/currency' },
|
||||
}],
|
||||
};
|
||||
desk!.selectSharedField('currency', 'xfa_header_currency');
|
||||
desk!.deleteSelectedBinding();
|
||||
const payload = desk!.buildDraftPayload({
|
||||
document_match: { document_type: 'purchase_order', page_pattern: 'one_or_more', required_anchors: [], optional_anchors: [] },
|
||||
order_field_layouts: [], draft_unbound_order_field_layouts: [], table_regions: [],
|
||||
} as unknown as OrderProfileDefinition);
|
||||
|
||||
// 关键断言:只有用户明确解除后,保存请求才携带允许删除的正式 binding ID。
|
||||
expect(payload?.definition.bindings).toEqual([]);
|
||||
expect(payload?.allow_formal_binding_deletions).toEqual(['currency-binding']);
|
||||
});
|
||||
|
||||
it('restores an empty visual field id from its unique datasets binding when saving', async () => {
|
||||
const enabled = ref(false);
|
||||
const state = ref<'saved' | 'saving' | 'failed' | 'readonly'>('saved');
|
||||
let desk: ReturnType<typeof useOrderProfileValueAdapter> | null = null;
|
||||
const Harness = defineComponent({
|
||||
setup() {
|
||||
desk = useOrderProfileValueAdapter({ profileId: () => 9, saveState: state, enabled });
|
||||
return () => null;
|
||||
},
|
||||
});
|
||||
|
||||
mount(Harness, { global: { plugins: [i18n] } });
|
||||
await desk?.load();
|
||||
desk!.authoritativePathId.value = 'root';
|
||||
desk!.definition.value = {
|
||||
...desk!.definition.value!,
|
||||
bindings: [{
|
||||
binding_id: 'line-material', field_id: 'field-material', field_code: 'material_number', scope: 'line',
|
||||
field_layout_id: 'line_1:material_number', value_binding: { type: 'xfa_dataset', path_id: 'po-path', data_path: null },
|
||||
}],
|
||||
};
|
||||
const visualDefinition = {
|
||||
document_match: { document_type: 'purchase_order', page_pattern: 'one_or_more', required_anchors: [], optional_anchors: [] },
|
||||
order_field_layouts: [], draft_unbound_order_field_layouts: [],
|
||||
table_regions: [{
|
||||
region_id: 'main_lines_page_1', page_scope: 'exact_page', page_no: 1,
|
||||
region: { x0: .1, y0: .2, x1: .9, y1: .8 }, header_layouts: [],
|
||||
line_layouts: [{
|
||||
layout_id: 'line_1', row_offset: 0, role: 'main', region: { x0: .1, y0: .3, x1: .9, y1: .4 },
|
||||
field_regions: [{
|
||||
field_id: '', field_code: 'material_number', scope: 'line',
|
||||
region: { x0: .2, y0: .3, x1: .4, y1: .4 }, extractor_key: 'direct',
|
||||
allowed_sources: ['pdf_coordinate'], minimum_evidence_level: 'coordinate',
|
||||
}], new_line_anchor: null, continuation_conditions: [], required_fields: [], allowed_empty_fields: [],
|
||||
}], continuation_rule: { allow_cross_page: false, required_anchor_ids: [] },
|
||||
termination_rules: [], exclusion_regions: [],
|
||||
}],
|
||||
} as unknown as OrderProfileDefinition;
|
||||
|
||||
const payload = desk!.buildDraftPayload(visualDefinition);
|
||||
|
||||
// 关键断言:已有唯一正式 binding 时,视觉布局必须复用其 Schema ID,避免签名阶段失败。
|
||||
expect(payload?.definition.table_regions[0]?.line_layouts[0]?.field_regions[0]?.field_id).toBe('field-material');
|
||||
});
|
||||
|
||||
it('keeps a line Schema field bound from an auto-marked table header when saving', async () => {
|
||||
const enabled = ref(false);
|
||||
const state = ref<'saved' | 'saving' | 'failed' | 'readonly'>('saved');
|
||||
let desk: ReturnType<typeof useOrderProfileValueAdapter> | null = null;
|
||||
const Harness = defineComponent({
|
||||
setup() {
|
||||
desk = useOrderProfileValueAdapter({ profileId: () => 9, saveState: state, enabled });
|
||||
return () => null;
|
||||
},
|
||||
});
|
||||
|
||||
mount(Harness, { global: { plugins: [i18n] } });
|
||||
await desk?.load();
|
||||
desk!.authoritativePathId.value = 'items-collection';
|
||||
desk!.definition.value = {
|
||||
...desk!.definition.value!,
|
||||
bindings: [{
|
||||
binding_id: 'header-material', field_id: 'field-material', field_code: 'material_number', scope: 'line',
|
||||
field_layout_id: 'header_1:material_number',
|
||||
value_binding: { type: 'xfa_dataset', path_id: 'po-path', data_path: '/data/items/material' },
|
||||
}],
|
||||
};
|
||||
const visualDefinition = {
|
||||
document_match: { document_type: 'purchase_order', page_pattern: 'one_or_more', required_anchors: [], optional_anchors: [] },
|
||||
order_field_layouts: [], draft_unbound_order_field_layouts: [],
|
||||
table_regions: [{
|
||||
region_id: 'main_lines_page_1', page_scope: 'exact_page', page_no: 1,
|
||||
region: { x0: .1, y0: .2, x1: .9, y1: .8 },
|
||||
header_layouts: [{
|
||||
layout_id: 'header_1', region: { x0: .1, y0: .2, x1: .9, y1: .3 },
|
||||
field_regions: [{
|
||||
field_id: '', field_code: 'material_number', scope: 'line',
|
||||
region: { x0: .2, y0: .2, x1: .4, y1: .3 }, extractor_key: 'direct',
|
||||
allowed_sources: ['pdf_coordinate'], minimum_evidence_level: 'coordinate',
|
||||
}],
|
||||
}],
|
||||
line_layouts: [], continuation_rule: { allow_cross_page: false, required_anchor_ids: [] },
|
||||
termination_rules: [], exclusion_regions: [],
|
||||
}],
|
||||
} as unknown as OrderProfileDefinition;
|
||||
|
||||
const payload = desk!.buildDraftPayload(visualDefinition);
|
||||
|
||||
// 关键断言:ITEM/QTY 等视觉表头可绑定 line 字段,二次保存不可将其视为缺失布局。
|
||||
expect(payload?.definition.table_regions[0]?.header_layouts[0]?.field_regions[0]?.field_id).toBe('field-material');
|
||||
expect(payload?.definition.bindings).toEqual(expect.arrayContaining([
|
||||
expect.objectContaining({ field_layout_id: 'header_1:material_number' }),
|
||||
]));
|
||||
});
|
||||
|
||||
it('marks a Header datasets value chosen for a shared line field as inherited', async () => {
|
||||
const enabled = ref(false);
|
||||
const state = ref<'saved' | 'saving' | 'failed' | 'readonly'>('saved');
|
||||
let desk: ReturnType<typeof useOrderProfileValueAdapter> | null = null;
|
||||
const Harness = defineComponent({
|
||||
setup() {
|
||||
desk = useOrderProfileValueAdapter({ profileId: () => 9, saveState: state, enabled });
|
||||
return () => null;
|
||||
},
|
||||
});
|
||||
|
||||
mount(Harness, { global: { plugins: [i18n] } });
|
||||
await desk?.load();
|
||||
desk!.authoritativePathId.value = 'items-collection';
|
||||
desk?.selectSharedField('material_number', 'line_1:material_number');
|
||||
desk?.updateSelectedDatasetsPath('header-po', true);
|
||||
await flushPromises();
|
||||
|
||||
// 关键断言:Header 叶子仍能绑定 line 字段,但 UI 必须明确展示逐行继承语义。
|
||||
expect(desk?.lineBindingInheritsHeader.value).toBe(true);
|
||||
});
|
||||
|
||||
});
|
||||
+1051
File diff suppressed because it is too large.
Load diff
-1668
File diff suppressed because it is too large.
Load diff
+254
@@ -13,11 +13,29 @@ import {
|
||||
shouldShowStandardOrderProfilePreview,
|
||||
toOrderProfileAnchorId,
|
||||
buildOrderProfileRecognitionResults,
|
||||
selectCurrentDatasetsValidationEvidence,
|
||||
normalizeOrderProfileRelativeRegion,
|
||||
groupUniqueOrderProfileLineFields,
|
||||
buildAutomarkSuggestedRegions,
|
||||
normalizeAutomarkFieldCandidates,
|
||||
selectAutomarkReconstruction,
|
||||
summarizeAutomarkTableCandidates,
|
||||
toOrderProfileHeaderFieldRegion,
|
||||
resolveCoordinateFieldScope,
|
||||
isOrderProfileVisualFieldEligible,
|
||||
} from './orderProfileForm.utils';
|
||||
|
||||
describe('order profile form rules', () => {
|
||||
it('keeps datasets-only Schema fields available for XFA visual positioning only', () => {
|
||||
const datasetsOnly = { enabled: true, allowed_sources: ['xfa_dataset'] };
|
||||
|
||||
// 关键断言:XFA 画框是定位证据,不能因没有 pdf_coordinate 正式取值权限而无法选择字段。
|
||||
expect(isOrderProfileVisualFieldEligible(datasetsOnly, true)).toBe(true);
|
||||
// 普通 PDF 仍不允许把未授权字段写入 coordinate definition。
|
||||
expect(isOrderProfileVisualFieldEligible(datasetsOnly, false)).toBe(false);
|
||||
expect(isOrderProfileVisualFieldEligible({ enabled: false, allowed_sources: ['xfa_dataset'] }, true)).toBe(false);
|
||||
});
|
||||
|
||||
it.each(['line_no', 'customer_po_line_no'])(
|
||||
'keeps %s available after resolving the main-line fields',
|
||||
(startFieldCode) => {
|
||||
@@ -149,6 +167,55 @@ describe('order profile form rules', () => {
|
||||
expect(results.header).toMatchObject([{ id: 'address-value', value: null, status: 'unavailable' }]);
|
||||
});
|
||||
|
||||
it('displays the current AcroForm widget visual sample value for an XFA header frame', () => {
|
||||
const results = buildOrderProfileRecognitionResults([{
|
||||
id: 'po-value', kind: 'order_field' as const, label: 'PO', fieldCode: 'customer_po_number',
|
||||
pageNo: 1, region: { x0: .4, y0: .1, x1: .8, y1: .2 },
|
||||
}], [{
|
||||
field_id: 'po-field', field_code: 'customer_po_number', value: '4510039227',
|
||||
source: 'acroform_widget', status: 'needs_review', page_no: 1,
|
||||
issues: ['order_field_acroform_widget_needs_review'],
|
||||
}], null, 'ready');
|
||||
|
||||
// Widget 值来自当前受控视觉回读,必须显示,不得回退为自动标记缓存。
|
||||
expect(results.header).toMatchObject([{ id: 'po-value', value: '4510039227', status: 'read' }]);
|
||||
});
|
||||
|
||||
it('projects XFA line results only from datasets validation evidence', () => {
|
||||
const regions = [
|
||||
{ id: 'part-column', kind: 'field' as const, label: 'Part', fieldCode: 'customer_part_number', pageNo: 1, region: { x0: .1, y0: .3, x1: .2, y1: .4 } },
|
||||
{ id: 'qty-column', kind: 'field' as const, label: 'Qty', fieldCode: 'quantity', pageNo: 1, region: { x0: .2, y0: .3, x1: .3, y1: .4 } },
|
||||
];
|
||||
|
||||
const results = buildOrderProfileRecognitionResults(regions, [], null, 'ready', {
|
||||
header_fields: [],
|
||||
lines: [{ row_index: 0, fields: [
|
||||
{ field_id: 'part', field_code: 'customer_part_number', raw_value: 'TEMP-S000218922', normalized_value: 'TEMP-S000218922', status: 'passed', issues: [] },
|
||||
{ field_id: 'qty', field_code: 'quantity', raw_value: '30', normalized_value: '30', status: 'passed', issues: [] },
|
||||
] }],
|
||||
cross_checks: {},
|
||||
});
|
||||
|
||||
// XFA 的正式行值只能来自 datasets 验证证据;坐标表头/旧 preview 不得混入。
|
||||
expect(results.line).toMatchObject([
|
||||
{ id: 'part-column', fieldCode: 'customer_part_number', value: 'TEMP-S000218922', status: 'read', rowNo: 1 },
|
||||
{ id: 'qty-column', fieldCode: 'quantity', value: '30', status: 'read', rowNo: 1 },
|
||||
]);
|
||||
});
|
||||
|
||||
it('selects only the current XFA validation evidence for the active draft checksum', () => {
|
||||
const evidence = {
|
||||
header_fields: [], lines: [{ row_index: 0, fields: [] }], cross_checks: {},
|
||||
};
|
||||
|
||||
// 旧草稿或非当前样本 Run 不能回灌至共同工作台,避免显示过期的正式样本值。
|
||||
expect(selectCurrentDatasetsValidationEvidence([
|
||||
{ id: 3, run_type: 'current_sample', status: 'passed', definition_checksum: 'old', summary: { validation_evidence: evidence } },
|
||||
{ id: 2, run_type: 'instant_check', status: 'passed', definition_checksum: 'current', summary: { validation_evidence: evidence } },
|
||||
{ id: 1, run_type: 'current_sample', status: 'passed', definition_checksum: 'current', summary: { validation_evidence: evidence } },
|
||||
], 'current')).toEqual(evidence);
|
||||
});
|
||||
|
||||
it('reports reading and failure without reusing a prior suggested value', () => {
|
||||
const regions = [{
|
||||
id: 'address-value', kind: 'order_field' as const, label: 'Address', fieldCode: 'bill_to_address',
|
||||
@@ -188,4 +255,191 @@ describe('order profile form rules', () => {
|
||||
expect(normalizeOrderProfileRelativeRegion({ x0: 1.1, y0: .2, x1: 1.2, y1: .3 })).toBeNull();
|
||||
});
|
||||
|
||||
it('keeps header field candidates when visual row reconstruction needs review', () => {
|
||||
const regions = buildAutomarkSuggestedRegions({
|
||||
reconstruction: null,
|
||||
orderFieldCandidates: [{
|
||||
field_id: 'po', field_code: 'customer_po_number', display_name: 'PO Number',
|
||||
source: 'ocr_coordinate', status: 'suggested', issue: null,
|
||||
value_region: { x0: .4, y0: .1, x1: .8, y1: .16 },
|
||||
}],
|
||||
pageNo: 1,
|
||||
unboundColumnLabel: (count) => `Unbound ${count}`,
|
||||
lineLabel: (count) => `Line ${count}`,
|
||||
});
|
||||
|
||||
// 行证据为空时,只保留可复核的抬头框;不得为了满足旧表格结构虚构明细行。
|
||||
expect(regions).toMatchObject([{
|
||||
kind: 'order_field', fieldCode: 'customer_po_number', pageNo: 1,
|
||||
region: { x0: .4, y0: .1, x1: .8, y1: .16 },
|
||||
}]);
|
||||
expect(regions.some((region) => region.kind === 'line' || region.kind === 'field')).toBe(false);
|
||||
});
|
||||
|
||||
it('serializes accepted header fields with header scope', () => {
|
||||
// 表头候选接受后必须进入 header_layouts;写成 line 会被后端契约拒绝,导致表头刷新后消失。
|
||||
expect(toOrderProfileHeaderFieldRegion({
|
||||
fieldCode: 'delivery_date',
|
||||
region: { x0: .2, y0: .1, x1: .4, y1: .16 },
|
||||
})).toEqual({
|
||||
field_id: '', field_code: 'delivery_date', scope: 'header',
|
||||
region: { x0: .2, y0: .1, x1: .4, y1: .16 },
|
||||
extractor_key: 'direct', allowed_sources: ['pdf_coordinate'], minimum_evidence_level: 'coordinate',
|
||||
});
|
||||
expect(toOrderProfileHeaderFieldRegion({
|
||||
fieldCode: null,
|
||||
region: { x0: .2, y0: .1, x1: .4, y1: .16 },
|
||||
})).toBeNull();
|
||||
// 视觉表头中的 ITEM/QTY 等列名属于明细 Schema,必须保留 line scope。
|
||||
expect(toOrderProfileHeaderFieldRegion({
|
||||
fieldCode: 'qty',
|
||||
region: { x0: .4, y0: .1, x1: .5, y1: .16 },
|
||||
}, 'line')?.scope).toBe('line');
|
||||
// Schema 只允许 datasets 时,视觉框不能丢失,也不能伪造 coordinate 正式绑定;
|
||||
// 页面定义序列化层会将其放入 draft_unbound_field_regions。
|
||||
});
|
||||
|
||||
it('keeps a cross-scope visual header candidate unbound until an administrator decides', () => {
|
||||
// 同名字段跨 header/line 时,仅凭视觉列名不足以做业务语义选择。
|
||||
expect(resolveCoordinateFieldScope('qty', ['customer_po_number'], ['qty'])).toBe('line');
|
||||
expect(resolveCoordinateFieldScope('customer_po_number', ['customer_po_number'], ['qty'])).toBe('header');
|
||||
expect(resolveCoordinateFieldScope('reservation_id', ['reservation_id'], ['reservation_id'])).toBeNull();
|
||||
expect(resolveCoordinateFieldScope('dataset_only', [], [])).toBeNull();
|
||||
});
|
||||
|
||||
it('does not choose a table layout when native and OCR candidates coexist', () => {
|
||||
const native = {
|
||||
table_id: 'table-1', subrow_layouts: [{ row_offset: 0, column_boundaries: [0, 1] }],
|
||||
};
|
||||
|
||||
// 两路候选即使暂未计算出冲突,画布也不能按 native 优先投影为已选择的明细框。
|
||||
expect(selectAutomarkReconstruction(native, [
|
||||
{ source: 'pdf_coordinate', status: 'needs_review' },
|
||||
{ source: 'ocr_coordinate', status: 'needs_review' },
|
||||
], [])).toBeNull();
|
||||
expect(selectAutomarkReconstruction(native, [
|
||||
{ source: 'pdf_coordinate', status: 'needs_review' },
|
||||
], [{ code: 'table_reconstruction_source_conflict' }])).toBeNull();
|
||||
expect(selectAutomarkReconstruction(native, [
|
||||
{ source: 'pdf_coordinate', status: 'needs_review' },
|
||||
], [])).toBe(native);
|
||||
});
|
||||
|
||||
it('uses the explicitly selected Widget table candidate when coordinate reconstruction is absent', () => {
|
||||
const widget = {
|
||||
table_id: 'table-1', status: 'needs_review' as const,
|
||||
subrow_layouts: [{ row_offset: 0, column_boundaries: [0, .5, 1] }],
|
||||
};
|
||||
|
||||
// XFA 外观层可能没有可重建的 native/OCR 文本行;管理员选择唯一 Widget 几何后,
|
||||
// 共同画布必须使用该结构生成待确认明细框,而不能退化为“无明细行”。
|
||||
expect(selectAutomarkReconstruction(null, [
|
||||
{ source: 'acroform_widget_geometry', status: 'needs_review' },
|
||||
], [], widget)).toBe(widget);
|
||||
});
|
||||
|
||||
it('projects fused Widget geometry and coordinate header text as header fields', () => {
|
||||
const widget = {
|
||||
table_id: 'table-1', status: 'needs_review' as const,
|
||||
subrow_layouts: [{
|
||||
row_offset: 0, column_boundaries: [0, .25, 1],
|
||||
suggested_field_codes: [null, null],
|
||||
}],
|
||||
header_regions: [{
|
||||
region: { x0: .1, y0: .15, x1: .9, y1: .2 },
|
||||
fields: [{
|
||||
text: 'ITEM', field_code: 'line_no',
|
||||
region: { x0: .1, y0: .15, x1: .3, y1: .2 },
|
||||
evidence_sources: ['acroform_widget_geometry', 'pdf_coordinate'],
|
||||
}],
|
||||
}],
|
||||
};
|
||||
|
||||
const regions = buildAutomarkSuggestedRegions({
|
||||
reconstruction: selectAutomarkReconstruction(null, [
|
||||
{ source: 'acroform_widget_geometry', status: 'needs_review' },
|
||||
], [], widget),
|
||||
orderFieldCandidates: [], pageNo: 1,
|
||||
unboundColumnLabel: (count) => `Unbound ${count}`,
|
||||
lineLabel: (count) => `Line ${count}`,
|
||||
});
|
||||
|
||||
// Widget 仅提供列几何;融合后的表头文字必须随所选候选进入共同画布。
|
||||
expect(regions).toContainEqual({
|
||||
id: 'header_1_1-field-1', kind: 'header_field', parentId: 'header_1_1',
|
||||
label: 'line_no', fieldCode: 'line_no', pageNo: 1,
|
||||
region: { x0: .1, y0: .15, x1: .3, y1: .2 },
|
||||
});
|
||||
});
|
||||
|
||||
it('preserves the backend evidence source when projecting automark field candidates', () => {
|
||||
const candidates = normalizeAutomarkFieldCandidates([{
|
||||
candidate_kind: 'field_binding',
|
||||
evidence_sources: ['ocr_coordinate'],
|
||||
needs_review: true,
|
||||
binding: {
|
||||
field_id: 'po', field_code: 'customer_po_number',
|
||||
visual_binding: { normalized_bbox: { x0: .4, y0: .1, x1: .8, y1: .16 } },
|
||||
},
|
||||
}]);
|
||||
|
||||
// OCR 视觉候选不能在前端被降级伪装为 native PDF 坐标候选。
|
||||
expect(candidates).toMatchObject([{
|
||||
source: 'ocr_coordinate', status: 'suggested',
|
||||
value_region: { x0: .4, y0: .1, x1: .8, y1: .16 },
|
||||
issue: 'visual_candidate_needs_review',
|
||||
}]);
|
||||
});
|
||||
|
||||
it('keeps AcroForm Widget as a visual-only candidate source', () => {
|
||||
const candidates = normalizeAutomarkFieldCandidates([{
|
||||
candidate_kind: 'field_binding',
|
||||
evidence_sources: ['acroform_widget'],
|
||||
needs_review: true,
|
||||
binding: {
|
||||
field_id: 'po', field_code: 'customer_po_number',
|
||||
visual_binding: { normalized_bbox: { x0: .4, y0: .1, x1: .8, y1: .16 } },
|
||||
},
|
||||
}]);
|
||||
|
||||
// Widget 只保留为待复核的定位来源;归一化 DTO 中没有也不得生成正式 value_binding。
|
||||
expect(candidates).toMatchObject([{
|
||||
source: 'acroform_widget', status: 'suggested',
|
||||
issue: 'visual_candidate_needs_review',
|
||||
}]);
|
||||
});
|
||||
|
||||
it('projects an unmatched AcroForm Widget as an unbound visual candidate', () => {
|
||||
const candidates = normalizeAutomarkFieldCandidates([{
|
||||
candidate_kind: 'field_binding',
|
||||
evidence_sources: ['acroform_widget'],
|
||||
needs_review: true,
|
||||
binding: {
|
||||
field_id: '', field_code: '', display_name: 'EBELN',
|
||||
visual_binding: { normalized_bbox: { x0: .4, y0: .1, x1: .8, y1: .16 } },
|
||||
},
|
||||
}]);
|
||||
|
||||
// Widget 名称不是业务字段映射;画布只能显示待确认框,不能自动写入 Schema field_code。
|
||||
expect(candidates).toMatchObject([{
|
||||
field_code: '', display_name: 'EBELN', source: 'acroform_widget',
|
||||
issue: 'visual_candidate_needs_review',
|
||||
}]);
|
||||
});
|
||||
|
||||
it('summarizes every parallel table candidate and marks source conflicts', () => {
|
||||
// 断言三路视觉候选都可见,摘要只提供结构信息,不替用户选正式值源。
|
||||
expect(summarizeAutomarkTableCandidates([
|
||||
{ source: 'pdf_coordinate', reconstruction: { table_id: 't', status: 'needs_review', subrow_layouts: [{ row_offset: 0, column_boundaries: [0, .5, 1] }] } },
|
||||
{ source: 'ocr_coordinate', reconstruction: { table_id: 't', status: 'needs_review', subrow_layouts: [{ row_offset: 0, column_boundaries: [0, 1] }, { row_offset: 1, column_boundaries: [0, 1] }] } },
|
||||
{ source: 'opencv_geometry', reconstruction: { table_id: 't', status: 'needs_review', subrow_layouts: [] } },
|
||||
{ source: 'acroform_widget_geometry', reconstruction: { table_id: 't', status: 'needs_review', subrow_layouts: [{ row_offset: 0, column_boundaries: [0, .25, .75, 1] }] } },
|
||||
], [{ code: 'table_reconstruction_source_conflict', sources: ['pdf_coordinate', 'opencv_geometry'] }])).toEqual([
|
||||
{ source: 'pdf_coordinate', rowCount: 1, columnCount: 2, conflictCodes: ['table_reconstruction_source_conflict'], status: 'needs_review' },
|
||||
{ source: 'ocr_coordinate', rowCount: 2, columnCount: 1, conflictCodes: [], status: 'needs_review' },
|
||||
{ source: 'opencv_geometry', rowCount: 0, columnCount: 0, conflictCodes: ['table_reconstruction_source_conflict'], status: 'needs_review' },
|
||||
{ source: 'acroform_widget_geometry', rowCount: 1, columnCount: 3, conflictCodes: [], status: 'needs_review' },
|
||||
]);
|
||||
});
|
||||
|
||||
});
|
||||
+294
-1
@@ -6,11 +6,16 @@
|
||||
*/
|
||||
|
||||
import type {
|
||||
CoordinateReconstructionSuggestion,
|
||||
CoordinateReconstructionPreview,
|
||||
OrderFieldLayoutSuggestion,
|
||||
OrderFieldValuePreview,
|
||||
OrderProfileCanvasRegion,
|
||||
OrderProfileFieldRegion,
|
||||
OrderProfileRelativeRegion,
|
||||
OrderProfileTableRegion,
|
||||
OrderProfileValidationEvidence,
|
||||
OrderProfileValidationRun,
|
||||
} from '@/features/admin/types/shipping-order-document-profile.types';
|
||||
|
||||
export interface OrderProfileLineFieldGroups {
|
||||
@@ -18,6 +23,68 @@ export interface OrderProfileLineFieldGroups {
|
||||
boundRegionIds: Set<string>;
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断 Schema 字段能否出现在共同视觉画布的绑定下拉中。
|
||||
* 核心逻辑:普通 PDF 的视觉框同时承载 coordinate 正式取值,必须具备该证据授权;
|
||||
* XFA 的视觉框只承担定位和样本展示,正式值由 datasets binding 另行控制,因此只要字段启用即可。
|
||||
* @param field - Schema 字段的最小权限信息。
|
||||
* @param usesExternalValueSource - 是否使用 datasets 等独立正式值源。
|
||||
* @returns 字段是否可作为当前工作台的视觉绑定目标。
|
||||
*/
|
||||
export const isOrderProfileVisualFieldEligible = (
|
||||
field: { enabled?: boolean; allowed_sources?: string[] },
|
||||
usesExternalValueSource: boolean,
|
||||
): boolean => (
|
||||
field.enabled !== false
|
||||
&& (usesExternalValueSource || Boolean(field.allowed_sources?.includes('pdf_coordinate')))
|
||||
);
|
||||
|
||||
/**
|
||||
* 将画布中的视觉表头文字转换为 v2 字段区域。
|
||||
* 核心逻辑:视觉位置不是业务 scope;调用方必须按 Schema 传入 header/line,
|
||||
* 未绑定框由调用方进入草稿未绑定区,不能猜测业务字段。
|
||||
* @param item - 已确认的表头画布区域。
|
||||
* @param scope - Schema 规定的业务字段作用域;视觉表头中的列名通常是 line。
|
||||
* @returns 可持久化的表头字段区域;没有 fieldCode 时返回 null。
|
||||
*/
|
||||
export const toOrderProfileHeaderFieldRegion = (
|
||||
item: Pick<OrderProfileCanvasRegion, 'fieldCode' | 'region'>,
|
||||
scope: 'header' | 'line' = 'header',
|
||||
): OrderProfileFieldRegion | null => {
|
||||
if (!item.fieldCode) return null;
|
||||
return {
|
||||
field_id: '',
|
||||
field_code: item.fieldCode,
|
||||
scope,
|
||||
region: item.region,
|
||||
extractor_key: 'direct',
|
||||
allowed_sources: ['pdf_coordinate'],
|
||||
minimum_evidence_level: 'coordinate',
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* 依据已获坐标证据授权的 Schema 字段解析视觉表头的业务作用域。
|
||||
* 核心逻辑:同一 field_code 同时存在 header/line 时,视觉文字不足以裁决业务语义;
|
||||
* 返回 null 使调用方保留未绑定框,等待管理员明确确认。
|
||||
* @param fieldCode - 自动候选给出的字段代码。
|
||||
* @param headerFieldCodes - 可使用坐标证据的 Header 字段代码。
|
||||
* @param lineFieldCodes - 可使用坐标证据的 Line 字段代码。
|
||||
* @returns 唯一作用域;未授权、未知或跨作用域歧义时返回 null。
|
||||
*/
|
||||
export const resolveCoordinateFieldScope = (
|
||||
fieldCode: string | null | undefined,
|
||||
headerFieldCodes: Iterable<string | null | undefined>,
|
||||
lineFieldCodes: Iterable<string | null | undefined>,
|
||||
): 'header' | 'line' | null => {
|
||||
if (!fieldCode) return null;
|
||||
const header = new Set([...headerFieldCodes].filter((code): code is string => Boolean(code)));
|
||||
const line = new Set([...lineFieldCodes].filter((code): code is string => Boolean(code)));
|
||||
const inHeader = header.has(fieldCode);
|
||||
const inLine = line.has(fieldCode);
|
||||
return inHeader === inLine ? null : inHeader ? 'header' : 'line';
|
||||
};
|
||||
|
||||
/**
|
||||
* 按物理行顺序收集唯一的明细字段绑定,供起行字段选择和最终定义复用同一份结果。
|
||||
* 核心逻辑:每个 Schema 字段只归属首个物理行;返回结果可重复读取,不会因预览起行字段而消费绑定。
|
||||
@@ -62,6 +129,187 @@ export const normalizeOrderProfileRelativeRegion = (
|
||||
return x0 < x1 && y0 < y1 ? { x0, y0, x1, y1 } : null;
|
||||
};
|
||||
|
||||
/**
|
||||
* 将统一自动标记结果投影为画布区域。
|
||||
* 核心逻辑:字段视觉候选与行重建是并行证据;行重建缺失时仍保留抬头字段框供人工复核,
|
||||
* 但绝不合成 line/field 明细区域。此函数不决定正式取值源。
|
||||
* @param options.reconstruction - 可选的表格行/列重建诊断。
|
||||
* @param options.orderFieldCandidates - 共同视觉字段框候选。
|
||||
* @returns 待确认画布区域,调用方再计算审计摘要和持久化建议。
|
||||
*/
|
||||
export const buildAutomarkSuggestedRegions = (options: {
|
||||
reconstruction: CoordinateReconstructionSuggestion | null | undefined;
|
||||
orderFieldCandidates: OrderFieldLayoutSuggestion[];
|
||||
pageNo: number;
|
||||
unboundColumnLabel: (count: number) => string;
|
||||
lineLabel: (count: number) => string;
|
||||
}): OrderProfileCanvasRegion[] => {
|
||||
const { reconstruction, orderFieldCandidates, pageNo, unboundColumnLabel, lineLabel } = options;
|
||||
const suggestedRegions: OrderProfileCanvasRegion[] = [];
|
||||
for (const [index, header] of (reconstruction?.header_regions || []).entries()) {
|
||||
const headerId = `header_${pageNo}_${index + 1}`;
|
||||
for (const [fieldIndex, field] of (header.fields || []).entries()) {
|
||||
suggestedRegions.push({
|
||||
id: `${headerId}-field-${fieldIndex + 1}`,
|
||||
kind: 'header_field', parentId: headerId,
|
||||
label: field.field_code || field.text || unboundColumnLabel(fieldIndex + 1),
|
||||
region: field.region, fieldCode: field.field_code || null, pageNo,
|
||||
});
|
||||
}
|
||||
}
|
||||
for (const [index, candidate] of orderFieldCandidates.entries()) {
|
||||
if (candidate.scope === 'line') continue;
|
||||
if (candidate.status !== 'suggested' || !candidate.value_region) continue;
|
||||
const orderFieldId = `order_field_${pageNo}_${candidate.field_code}_${index + 1}`;
|
||||
if (candidate.anchor_region && candidate.anchor_text) {
|
||||
suggestedRegions.push({
|
||||
id: `${orderFieldId}_anchor`, kind: 'order_anchor', label: candidate.anchor_text,
|
||||
region: candidate.anchor_region, orderFieldId, pageNo,
|
||||
});
|
||||
}
|
||||
suggestedRegions.push({
|
||||
id: orderFieldId, kind: 'order_field',
|
||||
label: candidate.field_code ? candidate.display_name : `${candidate.display_name} · ${unboundColumnLabel(index + 1)}`,
|
||||
region: candidate.value_region, fieldCode: candidate.field_code || null, orderFieldId,
|
||||
valueMode: candidate.value_mode, suggestedValue: candidate.suggested_value || null,
|
||||
evidenceSource: candidate.source, pageNo,
|
||||
});
|
||||
}
|
||||
const layouts = (reconstruction?.subrow_layouts || []).slice().sort(
|
||||
(left, right) => left.row_offset - right.row_offset,
|
||||
);
|
||||
for (const layout of layouts) {
|
||||
const lineId = `line_${pageNo}_${layout.row_offset + 1}`;
|
||||
const region = layout.region || {
|
||||
x0: 0.04, y0: 0.22 + layout.row_offset * 0.075,
|
||||
x1: 0.96, y1: 0.285 + layout.row_offset * 0.075,
|
||||
};
|
||||
suggestedRegions.push({
|
||||
id: lineId, kind: 'line', label: lineLabel(layout.row_offset + 1), region, pageNo,
|
||||
});
|
||||
layout.column_boundaries.slice(0, -1).forEach((left, index) => {
|
||||
const right = layout.column_boundaries[index + 1];
|
||||
if (right === undefined) return;
|
||||
const fieldCode = layout.row_offset === 0 ? layout.suggested_field_codes[index] || null : null;
|
||||
suggestedRegions.push({
|
||||
id: `${lineId}-field-${index + 1}`, kind: 'field', parentId: lineId,
|
||||
label: fieldCode || unboundColumnLabel(index + 1), fieldCode,
|
||||
region: {
|
||||
x0: region.x0 + (region.x1 - region.x0) * left, y0: region.y0,
|
||||
x1: region.x0 + (region.x1 - region.x0) * right, y1: region.y1,
|
||||
}, pageNo,
|
||||
});
|
||||
});
|
||||
}
|
||||
for (const [index, candidate] of orderFieldCandidates.entries()) {
|
||||
if (candidate.scope !== 'line' || candidate.status !== 'suggested' || !candidate.value_region) continue;
|
||||
const centerX = (candidate.value_region.x0 + candidate.value_region.x1) / 2;
|
||||
const centerY = (candidate.value_region.y0 + candidate.value_region.y1) / 2;
|
||||
const matchingLayouts = layouts.filter((layout) => {
|
||||
const region = layout.region || {
|
||||
x0: 0.04, y0: 0.22 + layout.row_offset * 0.075,
|
||||
x1: 0.96, y1: 0.285 + layout.row_offset * 0.075,
|
||||
};
|
||||
return centerX >= region.x0 && centerX <= region.x1 && centerY >= region.y0 && centerY <= region.y1;
|
||||
});
|
||||
// 无唯一候选行时不私自挂靠到任一明细行,保留待复核事实。
|
||||
if (matchingLayouts.length !== 1) continue;
|
||||
const lineId = `line_${pageNo}_${matchingLayouts[0]!.row_offset + 1}`;
|
||||
suggestedRegions.push({
|
||||
id: `${lineId}-widget-${index + 1}`,
|
||||
kind: 'field', parentId: lineId,
|
||||
label: candidate.field_code || candidate.display_name || unboundColumnLabel(index + 1),
|
||||
fieldCode: candidate.field_code || null,
|
||||
region: candidate.value_region,
|
||||
evidenceSource: candidate.source,
|
||||
pageNo,
|
||||
});
|
||||
}
|
||||
return suggestedRegions;
|
||||
};
|
||||
|
||||
/**
|
||||
* 仅在没有多来源候选或结构冲突时选择行重建结果。
|
||||
* 核心逻辑:native/OCR 都是候选证据;多来源时禁止沿用后端的优先投影,避免前端静默裁决。
|
||||
* @param reconstruction - 后端为兼容旧画布返回的单一路径投影
|
||||
* @param tableReconstructions - 各证据来源的候选摘要
|
||||
* @param conflicts - 后端检测到的结构冲突
|
||||
* @returns 可安全用于生成行框的重建结果;存在并行候选或冲突时返回 null
|
||||
*/
|
||||
export const selectAutomarkReconstruction = (
|
||||
reconstruction: CoordinateReconstructionSuggestion | null | undefined,
|
||||
tableReconstructions: unknown,
|
||||
conflicts: unknown,
|
||||
selectedCandidate?: CoordinateReconstructionSuggestion | null,
|
||||
): CoordinateReconstructionSuggestion | null => {
|
||||
// 管理员已明确选择(或 UI 已确认唯一)的候选时,应使用该来源本身;特别是
|
||||
// 动态 XFA 只有 Widget 几何而 coordinate_reconstruction 为 null 的情形。
|
||||
if (selectedCandidate) return selectedCandidate;
|
||||
if (!reconstruction) return null;
|
||||
if (Array.isArray(conflicts) && conflicts.length > 0) return null;
|
||||
if (Array.isArray(tableReconstructions) && tableReconstructions.length > 1) return null;
|
||||
return reconstruction;
|
||||
};
|
||||
|
||||
/**
|
||||
* 为多证据表格候选生成只读摘要,供人工确认区展示。
|
||||
* 核心逻辑:摘要只反映行/列几何与冲突来源,不显示或选择任何正式 datasets 值。
|
||||
*/
|
||||
export const summarizeAutomarkTableCandidates = (
|
||||
candidates: Array<{ source: string; reconstruction: CoordinateReconstructionSuggestion }>,
|
||||
conflicts: unknown,
|
||||
): Array<{ source: string; rowCount: number; columnCount: number; conflictCodes: string[]; status: 'needs_review' }> => {
|
||||
const conflictItems = Array.isArray(conflicts) ? conflicts.filter((item): item is Record<string, unknown> => Boolean(item && typeof item === 'object')) : [];
|
||||
return candidates.map((candidate) => {
|
||||
const layouts = Array.isArray(candidate.reconstruction.subrow_layouts) ? candidate.reconstruction.subrow_layouts : [];
|
||||
const columnCount = layouts.reduce((max, layout) => {
|
||||
const boundaries = Array.isArray(layout.column_boundaries) ? layout.column_boundaries.length - 1 : 0;
|
||||
return Math.max(max, boundaries);
|
||||
}, 0);
|
||||
const conflictCodes = conflictItems
|
||||
.filter((item) => Array.isArray(item.sources) && item.sources.map(String).includes(candidate.source))
|
||||
.map((item) => String(item.code || 'table_reconstruction_source_conflict'));
|
||||
return { source: candidate.source, rowCount: layouts.length, columnCount, conflictCodes, status: 'needs_review' };
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* 将后端统一 field_binding DTO 转为旧页面候选形状,并保留真实证据来源。
|
||||
* 核心逻辑:只接受视觉 binding;evidence_sources 为空时按不可确认处理,禁止默认宣称 native。
|
||||
* @param candidates - 自动标记 Job 返回的候选 DTO。
|
||||
* @param pageNo - 当前画布页码。
|
||||
* @returns 仅供页面复核的订单字段候选。
|
||||
*/
|
||||
export const normalizeAutomarkFieldCandidates = (
|
||||
candidates: Array<Record<string, unknown>>,
|
||||
): OrderFieldLayoutSuggestion[] => candidates
|
||||
.filter((item) => item.candidate_kind === 'field_binding' && item.binding && typeof item.binding === 'object')
|
||||
.map((item) => {
|
||||
const binding = item.binding as Record<string, unknown>;
|
||||
const visual = binding.visual_binding && typeof binding.visual_binding === 'object'
|
||||
? binding.visual_binding as Record<string, unknown> : {};
|
||||
const sources = Array.isArray(item.evidence_sources)
|
||||
? item.evidence_sources.map((source) => String(source || '')).filter(Boolean)
|
||||
: [];
|
||||
const source = sources[0] === 'ocr_coordinate' || sources[0] === 'acroform_widget'
|
||||
? sources[0] : 'pdf_coordinate';
|
||||
const needsReview = item.needs_review === true || !sources.length;
|
||||
return {
|
||||
field_id: String(binding.field_id || ''),
|
||||
field_code: String(binding.field_code || ''),
|
||||
// 未匹配的 XFA/AcroForm Widget 只有技术控件名和几何;它必须作为
|
||||
// 未绑定视觉候选进入共同画布,不能因 field_code 为空而丢失,也不能猜业务字段。
|
||||
display_name: String(binding.field_code || binding.display_name || binding.field_id || ''),
|
||||
scope: binding.scope === 'line' ? 'line' : 'header',
|
||||
source,
|
||||
status: 'suggested',
|
||||
issue: needsReview ? 'visual_candidate_needs_review' : null,
|
||||
anchor_text: undefined,
|
||||
anchor_region: undefined,
|
||||
value_region: visual.normalized_bbox as OrderProfileRelativeRegion | undefined,
|
||||
} satisfies OrderFieldLayoutSuggestion;
|
||||
});
|
||||
|
||||
/**
|
||||
* 判断是否显示普通表格预览;可直接创建 Profile 的表格不受上一张表多物理行状态影响。
|
||||
* @param profileCreationAllowed - 当前表格是否可直接创建 Profile
|
||||
@@ -148,6 +396,7 @@ export const buildOrderProfileRecognitionResults = (
|
||||
fieldValues: OrderFieldValuePreview[],
|
||||
reconstruction: CoordinateReconstructionPreview | null,
|
||||
fieldValueState: 'idle' | 'loading' | 'ready' | 'failed' = 'idle',
|
||||
datasetsEvidence: OrderProfileValidationEvidence | null = null,
|
||||
): { header: OrderProfileRecognitionResult[]; line: OrderProfileRecognitionResult[] } => {
|
||||
const valuesByCode = new Map(fieldValues.map((item) => [item.field_code, item]));
|
||||
const header = pageRegions
|
||||
@@ -165,12 +414,29 @@ export const buildOrderProfileRecognitionResults = (
|
||||
: fieldValueState === 'failed' ? 'failed' as const : 'unavailable' as const,
|
||||
};
|
||||
});
|
||||
if (!reconstruction) return { header, line: [] };
|
||||
const regionsByCode = new Map(
|
||||
pageRegions
|
||||
.filter((item) => item.kind === 'field' && item.fieldCode)
|
||||
.map((item) => [item.fieldCode!, item.id]),
|
||||
);
|
||||
// XFA datasets 是正式明细值源;共同视觉坐标只定位和交叉校验,不能把表头或
|
||||
// OCR 候选伪装成已读取的行值。传入此证据时完全忽略 coordinate reconstruction。
|
||||
if (datasetsEvidence) {
|
||||
const line = datasetsEvidence.lines.flatMap((row) => (
|
||||
row.fields.map((field) => ({
|
||||
id: regionsByCode.get(field.field_code) || null,
|
||||
key: `xfa-${row.row_index}-${field.field_code}`,
|
||||
fieldCode: field.field_code,
|
||||
value: field.normalized_value || null,
|
||||
status: field.status === 'passed' && field.normalized_value
|
||||
? 'read' as const
|
||||
: 'unavailable' as const,
|
||||
rowNo: row.row_index + 1,
|
||||
}))
|
||||
));
|
||||
return { header, line };
|
||||
}
|
||||
if (!reconstruction) return { header, line: [] };
|
||||
const fieldCodes = reconstruction.rows[0] || [];
|
||||
const line = reconstruction.rows.slice(1).flatMap((row, rowIndex) => {
|
||||
const sourceIndex = rowIndex + 1;
|
||||
@@ -190,6 +456,33 @@ export const buildOrderProfileRecognitionResults = (
|
||||
return { header, line };
|
||||
};
|
||||
|
||||
/**
|
||||
* 选择与当前草稿精确匹配的 XFA 当前样本正式证据。
|
||||
* 核心逻辑:验证 Run 是不可变的;只消费 current_sample、passed、checksum 相同的
|
||||
* datasets 证据,旧版本或其他运行类型不能在编辑工作台伪装成当前样本值。
|
||||
*/
|
||||
export const selectCurrentDatasetsValidationEvidence = (
|
||||
runs: OrderProfileValidationRun[],
|
||||
definitionChecksum: string | null | undefined,
|
||||
): OrderProfileValidationEvidence | null => {
|
||||
if (!definitionChecksum) return null;
|
||||
const run = runs.find((item) => (
|
||||
item.run_type === 'current_sample'
|
||||
&& item.status === 'passed'
|
||||
&& item.definition_checksum === definitionChecksum
|
||||
));
|
||||
const evidence = run?.summary?.validation_evidence;
|
||||
if (!evidence || typeof evidence !== 'object' || Array.isArray(evidence)) return null;
|
||||
const value = evidence as Partial<OrderProfileValidationEvidence>;
|
||||
if (!Array.isArray(value.header_fields) || !Array.isArray(value.lines)) return null;
|
||||
return {
|
||||
header_fields: value.header_fields,
|
||||
lines: value.lines,
|
||||
cross_checks: value.cross_checks && typeof value.cross_checks === 'object' && !Array.isArray(value.cross_checks)
|
||||
? value.cross_checks : {},
|
||||
} as OrderProfileValidationEvidence;
|
||||
};
|
||||
|
||||
/**
|
||||
* 根据已确认表头的横向覆盖关系建议明细字段;冲突或覆盖不足时拒绝猜测。
|
||||
* @param fieldRegion - 当前待绑定的明细字段区域
|
||||
|
||||
+2
-2
@@ -9,7 +9,7 @@ import type {
|
||||
OrderProfileCanvasRegion,
|
||||
ShippingOrderDocumentProfile,
|
||||
} from '@/features/admin/types/shipping-order-document-profile.types';
|
||||
import { asCoordinateProfileDefinition } from '@/features/admin/types/shipping-order-document-profile.types';
|
||||
import { asVisualProfileDefinition } from '@/features/admin/types/shipping-order-document-profile.types';
|
||||
import { restoreOrderProfileRegionPageNo } from './orderProfileForm.utils';
|
||||
|
||||
const mergeEquivalentOrderAnchors = (items: OrderProfileCanvasRegion[]) => {
|
||||
@@ -61,7 +61,7 @@ const pageNoOf = (pageScope: 'first_page' | 'all_pages' | 'exact_page', pageNo?:
|
||||
export const buildOrderProfileReadonlyRegions = (
|
||||
profile: ShippingOrderDocumentProfile,
|
||||
): OrderProfileCanvasRegion[] => {
|
||||
const definition = asCoordinateProfileDefinition(profile.definition);
|
||||
const definition = asVisualProfileDefinition(profile.definition);
|
||||
const restored: OrderProfileCanvasRegion[] = [
|
||||
...(definition.document_match.required_anchors || []).flatMap<OrderProfileCanvasRegion>((anchor) => {
|
||||
if (!anchor.label_region || !anchor.value_region || !anchor.page_no) return [];
|
||||
|
||||
+74
-1
@@ -9,9 +9,16 @@ import {
|
||||
collectBoundXfaFieldIds,
|
||||
computeXfaMappingCoverage,
|
||||
flattenXfaTreeNodes,
|
||||
hashXfaDataPath,
|
||||
resolveAuthoritativePathId,
|
||||
resolveMirrorPathIds,
|
||||
summarizeXfaMappingBlockers,
|
||||
} from './xfaProfileMapping.utils';
|
||||
import type { OrderXfaDatasetProfileDefinition, XfaFieldTreeNode } from '@/features/admin/types/shipping-order-document-profile.types';
|
||||
import type {
|
||||
OrderXfaDatasetProfileDefinition,
|
||||
XfaCollectionCandidate,
|
||||
XfaFieldTreeNode,
|
||||
} from '@/features/admin/types/shipping-order-document-profile.types';
|
||||
|
||||
const baseDefinition: OrderXfaDatasetProfileDefinition = {
|
||||
template_mode: 'xfa_dataset',
|
||||
@@ -123,4 +130,70 @@ describe('xfaProfileMapping split utils', () => {
|
||||
const flatMulti = flattenXfaTreeNodes(multiline);
|
||||
expect((flatMulti[0]?.lineCount || 0) > 1).toBe(true);
|
||||
});
|
||||
|
||||
it('restores legacy source contract collection path ids by exact path hash', async () => {
|
||||
const authoritativePath = '/data/ORDER/ITEMS/DATA';
|
||||
const mirrorPath = '/data/ORDER/ITEMS_COPY/DATA';
|
||||
const candidates: XfaCollectionCandidate[] = [{
|
||||
path_id: 'path-unrelated',
|
||||
collection_path_hash: await hashXfaDataPath('/data/OTHER/DATA'),
|
||||
path_label: 'Same display name',
|
||||
local_name: 'DATA',
|
||||
field_names: [],
|
||||
field_count: 0,
|
||||
non_empty_field_count: 0,
|
||||
non_empty_rate: 0,
|
||||
row_count: 0,
|
||||
selectable: true,
|
||||
recommended_role: 'candidate',
|
||||
recommendation_reasons: [],
|
||||
exclusion_reasons: [],
|
||||
sibling_collection_path_hashes: [],
|
||||
}, {
|
||||
path_id: 'path-authoritative',
|
||||
collection_path_hash: await hashXfaDataPath(authoritativePath),
|
||||
path_label: 'Same display name',
|
||||
local_name: 'DATA',
|
||||
field_names: [],
|
||||
field_count: 0,
|
||||
non_empty_field_count: 0,
|
||||
non_empty_rate: 0,
|
||||
row_count: 1,
|
||||
selectable: true,
|
||||
recommended_role: 'authoritative',
|
||||
recommendation_reasons: [],
|
||||
exclusion_reasons: [],
|
||||
sibling_collection_path_hashes: [],
|
||||
}, {
|
||||
path_id: 'path-mirror',
|
||||
collection_path_hash: await hashXfaDataPath(mirrorPath),
|
||||
path_label: 'Same display name',
|
||||
local_name: 'DATA',
|
||||
field_names: [],
|
||||
field_count: 0,
|
||||
non_empty_field_count: 0,
|
||||
non_empty_rate: 0,
|
||||
row_count: 1,
|
||||
selectable: true,
|
||||
recommended_role: 'mirror',
|
||||
recommendation_reasons: [],
|
||||
exclusion_reasons: [],
|
||||
sibling_collection_path_hashes: [],
|
||||
}];
|
||||
const definition: OrderXfaDatasetProfileDefinition = {
|
||||
...baseDefinition,
|
||||
source_contract: {
|
||||
...baseDefinition.source_contract,
|
||||
authoritative_line_collection_path: authoritativePath,
|
||||
mirror_collection_paths: [mirrorPath],
|
||||
},
|
||||
};
|
||||
|
||||
const authoritativePathId = await resolveAuthoritativePathId(definition, candidates, []);
|
||||
const mirrorPathIds = await resolveMirrorPathIds(definition, candidates, authoritativePathId);
|
||||
|
||||
// 关键断言:历史定义只能以完整路径哈希恢复,不得按同名 DATA 或候选排序猜测。
|
||||
expect(authoritativePathId).toBe('path-authoritative');
|
||||
expect(mirrorPathIds).toEqual(['path-mirror']);
|
||||
});
|
||||
});
|
||||
@@ -65,23 +65,34 @@ export interface OrderProfileOrderFieldLayout { layout_id: string; field_id: str
|
||||
export interface OrderProfileDraftUnboundOrderFieldLayout { layout_id: string; label: string; page_scope: 'first_page' | 'all_pages' | 'exact_page'; page_no?: number | null; anchor?: OrderProfileAnchorRule | null; value_region?: OrderProfileAnchorRelativeRegion | null; absolute_value_region?: OrderProfileRelativeRegion | null; fallback_value_region?: OrderProfileRelativeRegion | null; value_mode: 'single_line' | 'multi_line' | 'right_of_anchor' | 'below_anchor'; stop_anchors: OrderProfileAnchorRule[]; minimum_evidence_level: OrderProfileEvidenceLevel; }
|
||||
export interface OrderProfileHeaderLayout { layout_id: string; region: OrderProfileRelativeRegion; field_regions: OrderProfileFieldRegion[]; }
|
||||
export interface OrderProfileLineLayout { layout_id: string; row_offset: number; role: 'main' | 'continuation'; region: OrderProfileRelativeRegion; field_regions: OrderProfileFieldRegion[]; new_line_anchor?: OrderProfileAnchorRule | null; continuation_conditions: OrderProfileAnchorRule[]; required_fields: string[]; allowed_empty_fields: string[]; }
|
||||
export interface OrderProfileTableRegion { region_id: string; page_scope: 'first_page' | 'all_pages' | 'continuation_pages' | 'exact_page'; page_no?: number | null; region: OrderProfileRelativeRegion; /** 逻辑明细起行锚点;默认 customer_po_line_no;line_no 为可识别内部项次亦可绑定。 */ line_start_field_code?: string; /** 默认固定子行;仅显式启用时允许在同一逻辑明细内跨视觉行按列重建。 */ row_reconstruction_mode?: OrderProfileRowReconstructionMode; header_layouts: OrderProfileHeaderLayout[]; line_layouts: OrderProfileLineLayout[]; continuation_rule: { allow_cross_page: boolean; required_anchor_ids: string[] }; termination_rules: Array<{ rule_id: string; anchor: OrderProfileAnchorRule }>; exclusion_regions: OrderProfileRelativeRegion[]; draft_unbound_field_regions?: Array<{ region_id: string; parent_layout_id: string; label: string; region: OrderProfileRelativeRegion }>; }
|
||||
export interface OrderProfileTableRegion { region_id: string; page_scope: 'first_page' | 'all_pages' | 'continuation_pages' | 'exact_page'; page_no?: number | null; region: OrderProfileRelativeRegion; /** 逻辑明细起行锚点;默认 customer_po_line_no;line_no 为可识别内部项次亦可绑定。 */ line_start_field_code?: string; /** 默认固定子行;仅显式启用时允许在同一逻辑明细内跨视觉行按列重建。 */ row_reconstruction_mode?: OrderProfileRowReconstructionMode; /** 管理员确认的视觉行结构来源;审计用途,不是字段正式值源。 */ visual_evidence_source?: 'pdf_coordinate' | 'ocr_coordinate' | 'opencv_geometry' | 'acroform_widget_geometry' | null; header_layouts: OrderProfileHeaderLayout[]; line_layouts: OrderProfileLineLayout[]; continuation_rule: { allow_cross_page: boolean; required_anchor_ids: string[] }; termination_rules: Array<{ rule_id: string; anchor: OrderProfileAnchorRule }>; exclusion_regions: OrderProfileRelativeRegion[]; draft_unbound_field_regions?: Array<{ region_id: string; parent_layout_id: string; label: string; region: OrderProfileRelativeRegion }>; }
|
||||
export interface OrderProfileDocumentMatch { document_type: 'purchase_order'; page_pattern: 'one_or_more'; required_anchors: OrderProfileDocumentMatchAnchor[]; optional_anchors: OrderProfileDocumentMatchAnchor[]; minimum_score: number; minimum_margin: number; }
|
||||
|
||||
/** coordinate 模式 definition:不得与 XFA 映射字段混用。 */
|
||||
export interface OrderCoordinateProfileDefinition {
|
||||
template_mode?: 'coordinate';
|
||||
/**
|
||||
* 所有模板共用的视觉 matcher 与画布定义。
|
||||
*
|
||||
* PDF/OCR 与 XFA 都用同一份 document/table/field 几何配置选择 Profile、编辑、
|
||||
* 预览、自动标注和盲测;最终字段值如何读取不属于这一层。
|
||||
*/
|
||||
export interface OrderProfileVisualDefinition {
|
||||
main_table_id?: string | null;
|
||||
document_match: OrderProfileDocumentMatch;
|
||||
table_regions: OrderProfileTableRegion[];
|
||||
order_field_layouts?: OrderProfileOrderFieldLayout[];
|
||||
draft_unbound_order_field_layouts?: OrderProfileDraftUnboundOrderFieldLayout[];
|
||||
}
|
||||
|
||||
/** coordinate/OCR adapter 仅复用共同视觉定义,不增加独立生命周期字段。 */
|
||||
export interface OrderCoordinateProfileDefinition extends OrderProfileVisualDefinition {
|
||||
template_mode?: 'coordinate';
|
||||
}
|
||||
|
||||
export interface XfaSourceContract {
|
||||
template_packet_checksum: string;
|
||||
dataset_structure_fingerprint: string;
|
||||
dataset_root_path: string;
|
||||
authoritative_line_collection_path: string;
|
||||
/** 编辑器配置前允许为空;发布检查必须补齐。 */
|
||||
authoritative_line_collection_path?: string | null;
|
||||
mirror_collection_paths: string[];
|
||||
}
|
||||
|
||||
@@ -97,7 +108,8 @@ export interface XfaFieldMapping {
|
||||
}
|
||||
|
||||
export interface XfaLineMapping {
|
||||
row_path: string;
|
||||
/** 编辑器配置前允许为空;配置字段值映射后必须与权威集合一致。 */
|
||||
row_path?: string | null;
|
||||
fields: XfaFieldMapping[];
|
||||
}
|
||||
|
||||
@@ -116,12 +128,12 @@ export interface XfaNormalizedBBox {
|
||||
y1: number;
|
||||
}
|
||||
|
||||
export type XfaValueBindingType = 'xfa_dataset' | 'pdf_coordinate' | 'ocr_coordinate';
|
||||
export type XfaValueBindingType = 'xfa_dataset';
|
||||
export type XfaVisualBindingSource = 'acroform_widget' | 'user_drawn' | 'system_suggested';
|
||||
export type XfaVisualBindingStatus = 'suggested' | 'confirmed' | 'rejected' | 'needs_review';
|
||||
export type XfaBindingScope = 'header' | 'line';
|
||||
|
||||
/** 正式值绑定:XFA 仅 datasets 路径;普通 PDF 允许坐标/OCR。 */
|
||||
/** 正式值绑定:XFA 仅 datasets 路径;共同字段布局负责视觉标签与值区域。 */
|
||||
export interface XfaValueBinding {
|
||||
type: XfaValueBindingType;
|
||||
path_id?: string | null;
|
||||
@@ -129,7 +141,7 @@ export interface XfaValueBinding {
|
||||
region_id?: string | null;
|
||||
}
|
||||
|
||||
/** 视觉绑定:页码 + 归一化框 + 确认状态;发布前正式字段须 confirmed。 */
|
||||
/** @deprecated 历史 XFA 草稿视觉绑定;新保存只引用共同 order_field_layouts。 */
|
||||
export interface XfaVisualBinding {
|
||||
page_no: number;
|
||||
normalized_bbox: XfaNormalizedBBox;
|
||||
@@ -153,19 +165,21 @@ export interface XfaSplitRuleRef {
|
||||
segment_id: string;
|
||||
}
|
||||
|
||||
/** 统一字段绑定:value_binding + visual_binding + 可选 split_rule_ref。 */
|
||||
/** XFA 末端适配:共同字段布局引用 + datasets 路径 + 可选拆分段。 */
|
||||
export interface XfaUnifiedFieldBinding {
|
||||
binding_id: string;
|
||||
field_id: string;
|
||||
field_code: string;
|
||||
scope: XfaBindingScope;
|
||||
field_layout_id?: string | null;
|
||||
value_binding: XfaValueBinding;
|
||||
visual_binding: XfaVisualBinding;
|
||||
/** 仅用于读取尚未重存的历史草稿。 */
|
||||
visual_binding?: XfaVisualBinding | null;
|
||||
split_rule_ref?: XfaSplitRuleRef | null;
|
||||
}
|
||||
|
||||
/** xfa_dataset 模式 definition:禁止混入 table_regions / order_field_layouts。 */
|
||||
export interface OrderXfaDatasetProfileDefinition {
|
||||
/** XFA datasets adapter:在共同视觉定义之外增加末端权威取值契约。 */
|
||||
export interface OrderXfaDatasetProfileDefinition extends OrderProfileVisualDefinition {
|
||||
template_mode: 'xfa_dataset';
|
||||
source_contract: XfaSourceContract;
|
||||
header_mappings: XfaFieldMapping[];
|
||||
@@ -319,46 +333,6 @@ export interface XfaSplitRulesValidateResponse {
|
||||
}
|
||||
|
||||
/** 视觉绑定候选(suggest 返回;歧义不自动确认)。 */
|
||||
export interface XfaVisualPathCandidate {
|
||||
path_id: string;
|
||||
dataset_value_masked?: string | null;
|
||||
score?: number;
|
||||
reason_codes?: string[];
|
||||
}
|
||||
|
||||
export interface XfaVisualBindingCandidate {
|
||||
candidate_id?: string;
|
||||
binding_id?: string;
|
||||
widget_id?: string;
|
||||
page_no?: number;
|
||||
normalized_bbox?: XfaNormalizedBBox;
|
||||
acroform_field_name_tail?: string | null;
|
||||
path_id?: string | null;
|
||||
field_code?: string | null;
|
||||
display_name?: string | null;
|
||||
confidence?: number;
|
||||
status?: XfaVisualBindingStatus | 'suggested';
|
||||
visual_binding?: XfaVisualBinding;
|
||||
path_candidates?: Array<XfaVisualPathCandidate & {
|
||||
data_path_hash?: string;
|
||||
match_hint?: string;
|
||||
confidence?: number;
|
||||
}>;
|
||||
reason_codes?: string[];
|
||||
}
|
||||
|
||||
export interface XfaVisualBindingsSuggestResponse {
|
||||
profile_id?: number;
|
||||
document_id: number;
|
||||
page_no?: number;
|
||||
normalized_bbox?: XfaNormalizedBBox;
|
||||
candidates: XfaVisualBindingCandidate[];
|
||||
diagnostics?: Array<{ code: string; message: string }> | Record<string, unknown>;
|
||||
}
|
||||
|
||||
/** @deprecated 使用 XfaVisualBindingsSuggestResponse */
|
||||
export type XfaVisualBindingSuggestResponse = XfaVisualBindingsSuggestResponse;
|
||||
|
||||
export interface XfaVisualBindingMutationResponse {
|
||||
binding_id: string;
|
||||
visual_binding?: XfaVisualBinding;
|
||||
@@ -383,17 +357,6 @@ export interface XfaSplitRulesSuggestResponse {
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface XfaUnifiedMappingSuggestResponse {
|
||||
profile_id: number;
|
||||
document_id: number;
|
||||
suggestion_status?: string;
|
||||
suggestion_id?: string;
|
||||
suggestion_checksum?: string;
|
||||
visual_suggestion?: XfaVisualBindingsSuggestResponse | null;
|
||||
split_rule_suggestion?: XfaSplitRulesSuggestResponse | null;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export type OrderProfileDefinition = OrderCoordinateProfileDefinition | OrderXfaDatasetProfileDefinition;
|
||||
|
||||
/**
|
||||
@@ -407,18 +370,19 @@ export function isXfaDatasetProfileDefinition(
|
||||
}
|
||||
|
||||
/**
|
||||
* 将 definition 收窄为 coordinate 分支;XFA 模式不得进入坐标画布逻辑。
|
||||
* 返回所有模板共有的视觉定义,供同一张 PDF 画布恢复区域。
|
||||
* 最终值源 adapter 由调用方另行处理,不能在此拒绝 XFA 的共同视觉字段。
|
||||
* @param definition Profile definition 联合类型
|
||||
*/
|
||||
export function asCoordinateProfileDefinition(
|
||||
export function asVisualProfileDefinition(
|
||||
definition: OrderProfileDefinition,
|
||||
): OrderCoordinateProfileDefinition {
|
||||
if (isXfaDatasetProfileDefinition(definition)) {
|
||||
throw new Error('XFA dataset definition cannot be projected as coordinate regions');
|
||||
}
|
||||
): OrderProfileVisualDefinition {
|
||||
return definition;
|
||||
}
|
||||
|
||||
/** @deprecated 使用 asVisualProfileDefinition;保留兼容旧调用方。 */
|
||||
export const asCoordinateProfileDefinition = asVisualProfileDefinition;
|
||||
|
||||
export interface XfaFieldEvidenceRef {
|
||||
source: 'xfa_dataset';
|
||||
document_id: number;
|
||||
@@ -442,6 +406,8 @@ export interface ShippingOrderDocumentProfile {
|
||||
schema_checksum?: string | null;
|
||||
definition: OrderProfileDefinition;
|
||||
checksum?: string | null;
|
||||
/** 当前草稿定义的服务端冻结结构指纹;用于拒绝旧验证证据的回显。 */
|
||||
structure_fingerprint?: string | null;
|
||||
lock_version: number;
|
||||
change_note?: string | null;
|
||||
source_profile_id?: number | null;
|
||||
@@ -493,7 +459,7 @@ export interface ShippingOrderDocumentProfile {
|
||||
line_mapping_count?: number;
|
||||
mirror_collection_count?: number;
|
||||
};
|
||||
xfa_structure_identity?: {
|
||||
value_source_identity?: {
|
||||
template_packet_checksum?: string | null;
|
||||
dataset_structure_fingerprint?: string | null;
|
||||
has_authoritative_collection?: boolean;
|
||||
@@ -501,7 +467,7 @@ export interface ShippingOrderDocumentProfile {
|
||||
header_mapping_count?: number;
|
||||
line_mapping_count?: number;
|
||||
} | null;
|
||||
xfa_readonly_mapping?: {
|
||||
value_source_readonly_mapping?: {
|
||||
source_contract?: Record<string, unknown>;
|
||||
header_mappings?: Array<Record<string, unknown>>;
|
||||
line_mappings?: Array<Record<string, unknown>>;
|
||||
@@ -568,6 +534,29 @@ export interface OrderProfileEditLease {
|
||||
lock_version: number;
|
||||
}
|
||||
|
||||
/** 当前样本验证的统一字段证据;value adapter 仅改变证据产生方式。 */
|
||||
export interface OrderProfileValidationEvidenceField {
|
||||
field_id: string;
|
||||
field_code: string;
|
||||
raw_value: string | null;
|
||||
normalized_value: string | null;
|
||||
status: 'passed' | 'failed' | 'missing' | string;
|
||||
issues: string[];
|
||||
}
|
||||
|
||||
/** 当前样本验证的统一明细行证据。 */
|
||||
export interface OrderProfileValidationEvidenceLine {
|
||||
row_index: number;
|
||||
fields: OrderProfileValidationEvidenceField[];
|
||||
}
|
||||
|
||||
/** 所有模板共用的当前样本验证证据投影;XFA 对账仅作为 cross_checks 扩展。 */
|
||||
export interface OrderProfileValidationEvidence {
|
||||
header_fields: OrderProfileValidationEvidenceField[];
|
||||
lines: OrderProfileValidationEvidenceLine[];
|
||||
cross_checks: Record<string, unknown>;
|
||||
}
|
||||
|
||||
/** 绑定精确草稿 checksum 的不可变验证运行摘要。 */
|
||||
export interface OrderProfileValidationRun {
|
||||
id: number;
|
||||
@@ -600,6 +589,15 @@ export interface OrderProfileLayoutSignatureStatus {
|
||||
template_packet_checksum?: string | null;
|
||||
matcher_policy_version?: string | null;
|
||||
provider_versions?: Array<Record<string, unknown>> | null;
|
||||
adapter_run_type?: 'layout_signature' | 'xfa_structure_signature' | null;
|
||||
identity_details?: {
|
||||
adapter?: 'coordinate_ocr' | 'xfa_dataset';
|
||||
header_token_coverage?: number | null;
|
||||
dataset_structure_fingerprint?: string | null;
|
||||
template_packet_checksum?: string | null;
|
||||
parser_identity?: string | null;
|
||||
analysis_count?: number | null;
|
||||
} | null;
|
||||
}
|
||||
|
||||
export interface OrderProfileOverlapConflictProfile {
|
||||
@@ -649,10 +647,8 @@ export interface OrderProfilePublishCheckReport {
|
||||
operation_id: string;
|
||||
created_at: string;
|
||||
consumed_at: string | null;
|
||||
layout_signature_status?: OrderProfileLayoutSignatureStatus | null;
|
||||
layout_signature_summary?: Record<string, unknown> | null;
|
||||
xfa_structure_signature_status?: OrderProfileLayoutSignatureStatus | null;
|
||||
xfa_structure_signature_summary?: Record<string, unknown> | null;
|
||||
profile_identity_signature_status?: OrderProfileLayoutSignatureStatus | null;
|
||||
profile_identity_signature_summary?: Record<string, unknown> | null;
|
||||
template_mode?: 'coordinate' | 'xfa_dataset' | null;
|
||||
overlap_summary?: OrderProfileOverlapSummary | null;
|
||||
conflict_profiles?: OrderProfileOverlapConflictProfile[];
|
||||
@@ -824,71 +820,10 @@ export interface OrderProfileUsagePage {
|
||||
|
||||
/** 受控预览授权只对单页生效,令牌不得持久化或复用。 */
|
||||
export interface OrderProfilePreviewPageGrant { page_no: number; preview_token: string; }
|
||||
|
||||
/** XFA 合成预览身份上下文(与后端 PreviewIdentityContext 对齐)。 */
|
||||
export interface XfaSyntheticPreviewIdentity {
|
||||
document_id: number | null;
|
||||
layout_version_id: number | null;
|
||||
structure_analysis_id: number | string | null;
|
||||
source_content_hash: string;
|
||||
template_packet_checksum: string;
|
||||
datasets_packet_checksum: string;
|
||||
dataset_structure_fingerprint: string;
|
||||
preview_render_checksum: string;
|
||||
render_mode: string;
|
||||
renderer_version: string;
|
||||
page_count: number;
|
||||
}
|
||||
|
||||
/** 合成预览页元数据(含短时 token,不含 PNG)。 */
|
||||
export interface XfaSyntheticPreviewPageMeta {
|
||||
page_no: number;
|
||||
preview_token: string;
|
||||
width?: number;
|
||||
height?: number;
|
||||
drawn_echo_count?: number;
|
||||
}
|
||||
|
||||
/** 可写入 definition.xfa_preview 的发布证据(无 PNG)。 */
|
||||
export interface XfaPreviewDefinitionMeta {
|
||||
status?: string | null;
|
||||
preview_render_checksum?: string | null;
|
||||
render_mode?: string;
|
||||
renderer_version?: string;
|
||||
page_count?: number;
|
||||
pages_ready?: number[];
|
||||
source_page_count?: number | null;
|
||||
synthetic_page_count?: number | null;
|
||||
pages?: Array<{
|
||||
page_no?: number;
|
||||
source_page_box?: Record<string, number>;
|
||||
synthetic_page_box?: Record<string, number>;
|
||||
page_identity_hash?: string;
|
||||
}>;
|
||||
}
|
||||
|
||||
/** POST/GET xfa/preview 响应摘要。 */
|
||||
export interface XfaSyntheticPreviewResponse {
|
||||
document_id: number | null;
|
||||
identity: XfaSyntheticPreviewIdentity;
|
||||
status: 'ready' | 'needs_review' | 'failed' | 'stale' | string;
|
||||
error_code?: string | null;
|
||||
render_mode: string;
|
||||
renderer_version: string;
|
||||
page_count: number;
|
||||
preview_render_checksum?: string | null;
|
||||
pages: XfaSyntheticPreviewPageMeta[];
|
||||
expires_in_seconds: number;
|
||||
cache_hit: boolean;
|
||||
diagnostics?: Record<string, unknown>;
|
||||
/** BE-3:前端落库 definition.xfa_preview 用 */
|
||||
definition_preview_meta?: XfaPreviewDefinitionMeta;
|
||||
source_page_count?: number | null;
|
||||
synthetic_page_count?: number | null;
|
||||
}
|
||||
|
||||
/** 工作台预览模式:原始 PDFium 对照 vs datasets 合成权威画布。 */
|
||||
export type XfaPreviewCanvasMode = 'original' | 'synthetic';
|
||||
/** 管理员编辑画布的原 PDF 单次内存预览授权,坐标 PDF 与 XFA 共用。 */
|
||||
export interface OrderProfilePdfPreviewGrant { document_id: number; preview_token: string; expires_in_seconds: number; }
|
||||
/** @deprecated 使用 OrderProfilePdfPreviewGrant;保留给旧 XFA 调用方。 */
|
||||
export type OrderProfileXfaPdfPreviewGrant = OrderProfilePdfPreviewGrant;
|
||||
|
||||
export interface OrderProfileBoundSample {
|
||||
id: number;
|
||||
@@ -984,7 +919,7 @@ export interface OrderProfileBlindTestCandidate {
|
||||
/** 工作台的本地几何状态;保存前转为 v2 相对区域定义。 */
|
||||
export interface OrderProfileCanvasRegion {
|
||||
id: string;
|
||||
kind: 'header' | 'header_field' | 'line' | 'field' | 'order_anchor' | 'order_field' | 'exclusion' | 'document_anchor_label' | 'document_anchor_value' | 'xfa_visual';
|
||||
kind: 'header' | 'header_field' | 'line' | 'field' | 'order_anchor' | 'order_field' | 'exclusion' | 'document_anchor_label' | 'document_anchor_value';
|
||||
label: string;
|
||||
region: OrderProfileRelativeRegion;
|
||||
fieldCode?: string | null;
|
||||
@@ -1002,11 +937,11 @@ export interface OrderProfileCanvasRegion {
|
||||
/** 必需锚点固定值是否命中;普通字段没有配置值时为 null。 */
|
||||
matchesConfigured?: boolean | null;
|
||||
/** 自动建议实际使用的坐标证据来源,保存时映射到最小证据等级。 */
|
||||
evidenceSource?: 'pdf_coordinate' | 'ocr_coordinate';
|
||||
evidenceSource?: 'pdf_coordinate' | 'ocr_coordinate' | 'acroform_widget';
|
||||
stopAnchorText?: string | null;
|
||||
/** 标记所属文档页;画布切页时仅渲染当前页的区域。 */
|
||||
pageNo: number;
|
||||
/** XFA 视觉绑定确认状态;仅 kind=xfa_visual 时使用。 */
|
||||
/** datasets adapter 可附加的视觉证据确认状态,不影响共同画布区域种类。 */
|
||||
visualBindingStatus?: XfaVisualBindingStatus;
|
||||
}
|
||||
|
||||
@@ -1020,7 +955,6 @@ export interface OrderProfileSampleDocument {
|
||||
provider_version?: string | null;
|
||||
table_count: number;
|
||||
document_kind?: string | null;
|
||||
xfa_analysis_ready?: boolean;
|
||||
created_at?: string | null;
|
||||
purpose: 'order_document_profile_sample';
|
||||
parse_status: string;
|
||||
@@ -1181,7 +1115,10 @@ export interface OrderFieldLayoutSuggestion {
|
||||
field_id: string;
|
||||
field_code: string;
|
||||
display_name: string;
|
||||
source: 'pdf_coordinate' | 'ocr_coordinate';
|
||||
/** 仅由已冻结主表几何归类为 line;不代表已映射 Schema 字段。 */
|
||||
scope?: 'header' | 'line';
|
||||
/** 仅限画布定位/复核证据;不能替代 XFA datasets 正式取值绑定。 */
|
||||
source: 'pdf_coordinate' | 'ocr_coordinate' | 'acroform_widget';
|
||||
status: 'suggested' | 'ambiguous' | 'unavailable';
|
||||
binding_status?: 'bound' | 'unbound';
|
||||
issue: string | null;
|
||||
@@ -1205,6 +1142,7 @@ export interface OrderFieldValuePreview {
|
||||
field_code: string;
|
||||
value: string | null;
|
||||
status: 'confirmed' | 'needs_review' | 'unavailable';
|
||||
source?: 'pdf_coordinate' | 'ocr_coordinate' | 'acroform_widget' | null;
|
||||
page_no: number | null;
|
||||
issues: string[];
|
||||
}
|
||||
|
||||
@@ -9,11 +9,11 @@
|
||||
*/
|
||||
import { BusinessError, requestJson } from '@/shared/api/client';
|
||||
import { getAuthHeaders } from '@/shared/utils/auth';
|
||||
import { reportShippingDebugEvent } from '../shipping/shippingDebugReporter';
|
||||
import {
|
||||
normalizeShippingProcessingProjection,
|
||||
normalizeShippingProcessingWorkItems,
|
||||
} from '../shipping/normalizeShippingProcessing';
|
||||
import { normalizeConversationProcessingProjection } from '../shipping/conversationProcessingProjection';
|
||||
import type {
|
||||
ShippingDecisionResponse,
|
||||
ShippingOrderExtractionDocumentsResponse,
|
||||
@@ -30,6 +30,9 @@ import type {
|
||||
ShippingOrderExtractionRun,
|
||||
ShippingOrderExtractionProgressEvent,
|
||||
ShippingOrderExtractionRunCreateResponse,
|
||||
ShippingOrderReviewQueue,
|
||||
ShippingOrderReviewEmailEvidencePreview,
|
||||
ShippingOrderReviewIntakeParseContext,
|
||||
OrderExtractionSubmissionRequest,
|
||||
OrderExtractionSubmissionResponse,
|
||||
ConversationProcessingProjection,
|
||||
@@ -48,8 +51,6 @@ import type {
|
||||
ShippingDuplicateAction,
|
||||
ShippingOrderReviewDraftWrite,
|
||||
ShippingOrderReviewEvidence,
|
||||
ShippingOrderReviewInventoryCandidatesWrite,
|
||||
ShippingOrderReviewInventoryRoutingDecisionWrite,
|
||||
ShippingOrderReviewInventoryRoutingRerouteWrite,
|
||||
ShippingOrderReviewLlmAdjudicationPayload,
|
||||
ShippingOrderReviewLlmSuggestion,
|
||||
@@ -91,28 +92,6 @@ function jsonPost(body?: unknown): RequestInit {
|
||||
};
|
||||
}
|
||||
|
||||
/** 订单处理工作台履约写归属上下文(与后端 assert_notice_task_ownership 对齐)。 */
|
||||
export type ShippingFulfillmentOwnershipContext = {
|
||||
expectedOrderTaskNo?: string;
|
||||
expectedReviewCaseNo?: string;
|
||||
expectedRunNo?: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* 将归属上下文序列化为 API snake_case 载荷字段。
|
||||
*/
|
||||
function ownershipPayload(ownership?: ShippingFulfillmentOwnershipContext | null): Record<string, string> {
|
||||
if (!ownership) return {};
|
||||
const out: Record<string, string> = {};
|
||||
const ot = String(ownership.expectedOrderTaskNo || '').trim();
|
||||
const caseNo = String(ownership.expectedReviewCaseNo || '').trim();
|
||||
const run = String(ownership.expectedRunNo || '').trim();
|
||||
if (ot) out.expected_order_task_no = ot;
|
||||
if (caseNo) out.expected_review_case_no = caseNo;
|
||||
if (run) out.expected_run_no = run;
|
||||
return out;
|
||||
}
|
||||
|
||||
function assertShippingOk<T extends ShippingApiStatusPayload>(body: T): T {
|
||||
if (body.status === 'failed') {
|
||||
throw new BusinessError({
|
||||
@@ -125,20 +104,13 @@ function assertShippingOk<T extends ShippingApiStatusPayload>(body: T): T {
|
||||
return body;
|
||||
}
|
||||
|
||||
// #region debug-point E:workspace-api
|
||||
const reportRetryRpaDebug = (hypothesisId: string, msg: string, data: Record<string, unknown>) =>
|
||||
reportShippingDebugEvent('shipping.api.ts', hypothesisId, msg, data);
|
||||
// #endregion
|
||||
|
||||
export const listWorkspaceShippingTasks = (params?: {
|
||||
process_status?: string;
|
||||
lifecycle_status?: string;
|
||||
page?: number;
|
||||
page_size?: number;
|
||||
}) => {
|
||||
/** 拉取当前用户可见的发货任务列表。 */
|
||||
const sp = new URLSearchParams();
|
||||
if (params?.process_status) sp.set('process_status', params.process_status);
|
||||
if (params?.lifecycle_status) sp.set('lifecycle_status', params.lifecycle_status);
|
||||
if (params?.page) sp.set('page', String(params.page));
|
||||
if (params?.page_size) sp.set('page_size', String(params.page_size));
|
||||
@@ -177,6 +149,14 @@ export const getWorkspaceShippingTaskUiState = (taskNo: string) =>
|
||||
export const workspaceShippingExportUrl = (taskNo: string) =>
|
||||
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/export`;
|
||||
|
||||
/** 当前任务已关联库存快照的受控下载 URL;后端会再次校验任务归属与活动 link。 */
|
||||
export const workspaceShippingInventoryFileUrl = (taskNo: string) =>
|
||||
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/inventory-file`;
|
||||
|
||||
/** 当前任务指定明细匹配快照的受控下载 URL;文件号必须由行级投影提供。 */
|
||||
export const workspaceShippingLineInventoryFileUrl = (taskNo: string, inventoryFileNo: string) =>
|
||||
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/inventory-files/${encodeURIComponent(inventoryFileNo)}`;
|
||||
|
||||
/** 下载一个批次或显式任务集合的当前 ready 发货 Excel ZIP。 */
|
||||
export async function downloadWorkspaceShippingExportArchive(payload: { batch_no?: string; task_nos?: string[] }) {
|
||||
const response = await fetch('/api/workspace/shipping-exports/archive', {
|
||||
@@ -219,8 +199,8 @@ export const createWorkspaceOrderExtractionSubmission = (
|
||||
|
||||
/**
|
||||
* 拉取统一 ShippingProcessingProjection(唯一进度读源;含 order_intake / order_task)。
|
||||
* 核心逻辑:内嵌 conversation_processing 可选;缺省时前端由 work_items 合成分组;
|
||||
* 旧 conversation processing GET 已移除(无历史兼容)。
|
||||
* 核心逻辑:内嵌 conversation_processing.status_groups 是新版批次列表唯一读源;
|
||||
* 仅旧服务端未返回该字段时才由 work_items 合成兼容分组;旧 GET 已移除。
|
||||
*/
|
||||
type WorkspaceShippingProcessingResponse = {
|
||||
conversation_id: string;
|
||||
@@ -258,7 +238,11 @@ export const getWorkspaceShippingProcessing = async (
|
||||
.then((raw): WorkspaceShippingProcessingResponse => ({
|
||||
conversation_id: String(raw?.conversation_id || normalized),
|
||||
work_items: normalizeShippingProcessingWorkItems(raw?.work_items),
|
||||
conversation_processing: raw?.conversation_processing ?? null,
|
||||
// 会话级 status_groups / 四阶段 / 产物均已由后端裁决;在 API 边界一次规范任务字段,
|
||||
// 保证对话卡与批次中心消费同一份 DTO,后续组件不得再做 snake/camel 兼容分支。
|
||||
conversation_processing: raw?.conversation_processing
|
||||
? normalizeConversationProcessingProjection(raw.conversation_processing)
|
||||
: null,
|
||||
}))
|
||||
.finally(() => {
|
||||
clearTimeout(timeout);
|
||||
@@ -370,10 +354,24 @@ export const reparseWorkspaceShippingOrderExtractionRun = (
|
||||
jsonPost(payload),
|
||||
);
|
||||
|
||||
/** 在批次中心按 PDF 子任务创建重解析版本;已确认/履约文件由服务端排除。 */
|
||||
export const reparseWorkspaceShippingOrderExtractionBatch = (
|
||||
runNo: string,
|
||||
payload: { reason: 'rule_updated' | 'field_mapping_error' | 'document_quality' | 'other'; comment?: string },
|
||||
) => requestJson<{
|
||||
batch_reparse_id: string;
|
||||
source_run_no: string;
|
||||
created: Array<{ case_no: string; document_id: number; run_no: string; reused: boolean }>;
|
||||
excluded: Array<{ case_no: string; document_id: number; reason_code: string }>;
|
||||
}>(
|
||||
`/api/workspace/shipping-notice/order-extraction-runs/${encodeURIComponent(runNo)}/reparse-batch`,
|
||||
jsonPost(payload),
|
||||
);
|
||||
|
||||
/** 获取当前订单抽取 Run 的按 PDF 归并详情。 */
|
||||
export const listWorkspaceShippingOrderExtractionDocuments = (runNo: string) =>
|
||||
export const listWorkspaceShippingOrderExtractionDocuments = (runNo: string, uploadBatchId?: string | null) =>
|
||||
requestJson<ShippingOrderExtractionDocumentsResponse>(
|
||||
`/api/workspace/shipping-notice/order-extraction-runs/${encodeURIComponent(runNo)}/documents`,
|
||||
`/api/workspace/shipping-notice/order-extraction-runs/${encodeURIComponent(runNo)}/documents${uploadBatchId ? `?upload_batch_id=${encodeURIComponent(uploadBatchId)}` : ''}`,
|
||||
);
|
||||
|
||||
/** 获取 Run 下每份 PDF 的建单前复核摘要,服务端负责 owner 隔离。 */
|
||||
@@ -423,7 +421,7 @@ export const deleteWorkspaceShippingOrderReviewLine = (caseNo: string, lineKey:
|
||||
);
|
||||
|
||||
export const validateWorkspaceShippingOrderReviewDraft = (caseNo: string, expectedDraftVersion: number) =>
|
||||
requestJson<ShippingOrderReviewCase>(
|
||||
requestJson<{ case: ShippingOrderReviewCase }>(
|
||||
`/api/workspace/shipping-notice/order-review-cases/${encodeURIComponent(caseNo)}/draft/validate`,
|
||||
{ method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ expected_draft_version: expectedDraftVersion }) },
|
||||
);
|
||||
@@ -446,41 +444,6 @@ export const retryWorkspaceShippingOrderStpAutoCreate = (caseNo: string) =>
|
||||
{ method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({}) },
|
||||
);
|
||||
|
||||
/**
|
||||
* 对话级「重试自动推进」:服务端扫描会话下可恢复 Case/正式 OT。
|
||||
* 核心逻辑:前端不提交对象列表;返回 summary + 逐对象 items。
|
||||
* @param conversationId - 会话 ID
|
||||
* @param reason - 可选原因码
|
||||
*/
|
||||
export const retryWorkspaceConversationAutoProgress = (
|
||||
conversationId: string,
|
||||
reason = 'user_retry_auto_progress',
|
||||
) =>
|
||||
requestJson<{
|
||||
conversation_id: string;
|
||||
summary: {
|
||||
total: number;
|
||||
retried: number;
|
||||
skipped: number;
|
||||
failed: number;
|
||||
blocked?: number;
|
||||
};
|
||||
items: Array<{
|
||||
object_type: 'review_case' | 'formal_task' | string;
|
||||
object_ref: string;
|
||||
action?: string | null;
|
||||
outcome: 'queued' | 'skipped' | 'failed' | string;
|
||||
reason_code?: string | null;
|
||||
}>;
|
||||
}>(
|
||||
`/api/workspace/shipping-conversations/${encodeURIComponent(conversationId)}/retry-auto-progress`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ reason }),
|
||||
},
|
||||
);
|
||||
|
||||
/**
|
||||
* 为复核明细人工选定一个或多个已启用库存源候选。
|
||||
* 核心逻辑:携带 expected_draft_version 乐观锁;服务端写入行级 inventory_routing 后重跑资格校验。
|
||||
@@ -488,15 +451,6 @@ export const retryWorkspaceConversationAutoProgress = (
|
||||
* @param lineKey - Draft 行稳定标识 line_key
|
||||
* @param payload - 候选编码与强制说明
|
||||
*/
|
||||
export const putWorkspaceShippingOrderReviewInventoryCandidates = (
|
||||
caseNo: string,
|
||||
lineKey: string,
|
||||
payload: ShippingOrderReviewInventoryCandidatesWrite,
|
||||
) => requestJson<ShippingOrderReviewCase>(
|
||||
`/api/workspace/shipping-notice/order-review-cases/${encodeURIComponent(caseNo)}/draft/lines/${encodeURIComponent(lineKey)}/inventory-candidates`,
|
||||
{ method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) },
|
||||
);
|
||||
|
||||
/**
|
||||
* 读取正式 Task 当前库存候选版本与历史摘要。
|
||||
*/
|
||||
@@ -527,38 +481,6 @@ export const postWorkspaceShippingOrderReviewInventoryRoutingReroute = (
|
||||
{ method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) },
|
||||
);
|
||||
|
||||
/**
|
||||
* 采纳行级规则建议为有效库存源候选。
|
||||
* 核心逻辑:清除 suggestion_pending;服务端写入后重跑建单资格。
|
||||
* @param caseNo - 复核 Case 编号
|
||||
* @param lineKey - Draft 行稳定标识
|
||||
* @param payload - 版本锁、幂等键与可选原因
|
||||
*/
|
||||
export const postWorkspaceShippingOrderReviewInventoryRoutingAdoptSuggestion = (
|
||||
caseNo: string,
|
||||
lineKey: string,
|
||||
payload: ShippingOrderReviewInventoryRoutingDecisionWrite,
|
||||
) => requestJson<ShippingOrderReviewCase>(
|
||||
`/api/workspace/shipping-notice/order-review-cases/${encodeURIComponent(caseNo)}/draft/lines/${encodeURIComponent(lineKey)}/inventory-routing/adopt-suggestion`,
|
||||
{ method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) },
|
||||
);
|
||||
|
||||
/**
|
||||
* 保留当前人工库存路由结果并忽略待决规则建议。
|
||||
* 核心逻辑:清除 suggestion_pending;不覆盖已选人工候选。
|
||||
* @param caseNo - 复核 Case 编号
|
||||
* @param lineKey - Draft 行稳定标识
|
||||
* @param payload - 版本锁、幂等键与可选原因
|
||||
*/
|
||||
export const postWorkspaceShippingOrderReviewInventoryRoutingKeepManual = (
|
||||
caseNo: string,
|
||||
lineKey: string,
|
||||
payload: ShippingOrderReviewInventoryRoutingDecisionWrite,
|
||||
) => requestJson<ShippingOrderReviewCase>(
|
||||
`/api/workspace/shipping-notice/order-review-cases/${encodeURIComponent(caseNo)}/draft/lines/${encodeURIComponent(lineKey)}/inventory-routing/keep-manual`,
|
||||
{ method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) },
|
||||
);
|
||||
|
||||
/**
|
||||
* 复核工作台重新识别客户(不重解析 PDF)。
|
||||
*/
|
||||
@@ -712,20 +634,6 @@ export const reparseWorkspaceShippingOrderReviewDocument = (caseNo: string, reas
|
||||
jsonPost({ reason, comment }),
|
||||
);
|
||||
|
||||
/** 绑定已上传的替代 PDF;预解析成功后再单独创建替代识别 Run。 */
|
||||
export const createWorkspaceShippingOrderReviewReplacementIntake = (caseNo: string, assetNo: string) =>
|
||||
requestJson<ShippingNoticeIntakeResponse>(
|
||||
`/api/workspace/shipping-notice/order-review-cases/${encodeURIComponent(caseNo)}/replacement-intakes`,
|
||||
jsonPost({ asset_no: assetNo }),
|
||||
);
|
||||
|
||||
/** 替代 Intake 解析成唯一 PDF 后创建新的单文档 Run。 */
|
||||
export const createWorkspaceShippingOrderReviewReplacementRun = (caseNo: string, intakeNo: string) =>
|
||||
requestJson<ShippingOrderReviewReparseResponse>(
|
||||
`/api/workspace/shipping-notice/order-review-cases/${encodeURIComponent(caseNo)}/replacement-runs`,
|
||||
jsonPost({ intake_no: intakeNo }),
|
||||
);
|
||||
|
||||
/**
|
||||
* 获取复核字段的安全证据摘要(含 highlight_quality / highlight_bbox 契约字段)。
|
||||
* PDF 二进制继续由受控同源预览接口提供;坐标缺失不影响字段值。
|
||||
@@ -848,6 +756,7 @@ export const decideWorkspaceShippingOrderReviewLineFulfillment = (
|
||||
line_key: string;
|
||||
decision_code: ShippingOrderReviewLineFulfillmentDecisionCode | string;
|
||||
reason?: string;
|
||||
release_field_values?: Record<string, string>;
|
||||
expected_draft_version?: number;
|
||||
},
|
||||
) => requestJson<{
|
||||
@@ -934,10 +843,28 @@ export async function getWorkspaceShippingOrderReviewPreview(caseNo: string): Pr
|
||||
return response.blob();
|
||||
}
|
||||
|
||||
/** 读取当前 Case 同 Intake 的邮件证据安全预览;evidenceId 仅用于受控唯一范围高亮。 */
|
||||
export const getWorkspaceShippingOrderReviewEmailEvidencePreview = (caseNo: string, documentId: number, evidenceId?: string) =>
|
||||
requestJson<ShippingOrderReviewEmailEvidencePreview>(
|
||||
`/api/workspace/shipping-notice/order-review-cases/${encodeURIComponent(caseNo)}/email-evidence-preview/${documentId}${evidenceId ? `?evidence_id=${encodeURIComponent(evidenceId)}` : ''}`,
|
||||
);
|
||||
|
||||
/** 获取当前 Case 所属附件与同 Intake 邮件正文;仅在接收解析工作面打开时调用。 */
|
||||
export const getWorkspaceShippingOrderReviewIntakeParseContext = (caseNo: string) =>
|
||||
requestJson<ShippingOrderReviewIntakeParseContext>(
|
||||
`/api/workspace/shipping-notice/order-review-cases/${encodeURIComponent(caseNo)}/intake-parse-context`,
|
||||
);
|
||||
|
||||
/** 获取当前 Run 所属会话的有效订单队列。 */
|
||||
export const getWorkspaceShippingOrderReviewQueue = (runNo: string) =>
|
||||
requestJson<ShippingOrderReviewQueue>(
|
||||
`/api/workspace/shipping-notice/order-review-queue/${encodeURIComponent(runNo)}`,
|
||||
);
|
||||
|
||||
/** 用户展开状态卡时获取脱敏进度时间线;不返回节点或Workflow诊断数据。 */
|
||||
export const listWorkspaceShippingOrderExtractionProgressEvents = (runNo: string) =>
|
||||
export const listWorkspaceShippingOrderExtractionProgressEvents = (runNo: string, uploadBatchId?: string | null) =>
|
||||
requestJson<{ items: ShippingOrderExtractionProgressEvent[] }>(
|
||||
`/api/workspace/shipping-notice/order-extraction-runs/${encodeURIComponent(runNo)}/progress-events`,
|
||||
`/api/workspace/shipping-notice/order-extraction-runs/${encodeURIComponent(runNo)}/progress-events${uploadBatchId ? `?upload_batch_id=${encodeURIComponent(uploadBatchId)}` : ''}`,
|
||||
);
|
||||
|
||||
/** 在终态状态卡已投影到当前会话后确认已查看,避免只因预加载会话列表而消除提醒。 */
|
||||
@@ -1003,20 +930,6 @@ export const purgeWorkspaceShippingTasks = (taskNos: string[], reason: string) =
|
||||
'/api/workspace/shipping-tasks/batch-purge', jsonPost({ task_nos: taskNos, reason }),
|
||||
);
|
||||
|
||||
/**
|
||||
* 确认当前任务的库存 RPA 来源。
|
||||
* @param taskNo - 发货任务编号
|
||||
* @param sourceCode - 已配置的库存源编码
|
||||
* @returns RPA 库存导出触发结果
|
||||
*/
|
||||
export async function confirmWorkspaceShippingInventorySource(taskNo: string, sourceCode: string) {
|
||||
const body = await requestJson<ShippingDecisionResponse & ShippingApiStatusPayload>(
|
||||
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/confirm-inventory-source`,
|
||||
jsonPost({ source_code: sourceCode }),
|
||||
);
|
||||
return assertShippingOk(body);
|
||||
}
|
||||
|
||||
/** 搜索可供业务用户确认的启用标准客户。 */
|
||||
export const listWorkspaceShippingCustomerOptions = (query = '') => {
|
||||
const params = new URLSearchParams({ limit: '200' });
|
||||
@@ -1112,37 +1025,6 @@ export async function retryWorkspaceShippingTaskLine(
|
||||
return assertShippingOk(body);
|
||||
}
|
||||
|
||||
/**
|
||||
* 提交人工决策。
|
||||
* @param taskNo - 发货任务编号
|
||||
* @param decision - 决策 ID,如 confirm、reject、reparse
|
||||
* @param comment - 可选备注
|
||||
* @returns 决策执行结果
|
||||
*/
|
||||
export async function submitWorkspaceShippingDecision(taskNo: string, decision: string, comment?: string) {
|
||||
// #region debug-point E:submit-decision-entry
|
||||
void reportRetryRpaDebug('E', 'submitWorkspaceShippingDecision entry', {
|
||||
taskNo,
|
||||
decision,
|
||||
hasComment: Boolean(comment),
|
||||
});
|
||||
// #endregion
|
||||
const body = await requestJson<ShippingDecisionResponse & ShippingApiStatusPayload>(
|
||||
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/submit-decision`,
|
||||
jsonPost({ decision, ...(comment ? { comment } : {}) }),
|
||||
);
|
||||
// #region debug-point E:submit-decision-response
|
||||
void reportRetryRpaDebug('E', 'submitWorkspaceShippingDecision response', {
|
||||
taskNo,
|
||||
decision,
|
||||
status: String(body?.status || ''),
|
||||
message: String(body?.message || ''),
|
||||
code: String(body?.code || ''),
|
||||
});
|
||||
// #endregion
|
||||
return assertShippingOk(body);
|
||||
}
|
||||
|
||||
/** 人工复核证据只允许已绑定文档单元格或具名人工输入。 */
|
||||
export type ShippingReviewEvidence =
|
||||
| { evidence_type: 'document_cell'; document_id: number; observation_id: number; page_no: number; table_id: string; cell_id: string }
|
||||
@@ -1175,24 +1057,6 @@ export async function updateWorkspaceShippingNoticeFields(
|
||||
return assertShippingOk(body);
|
||||
}
|
||||
|
||||
/**
|
||||
* 冻结已复核的订单数据为后续库存、Excel 与上传唯一读取的履约快照。
|
||||
* @param taskNo - 当前任务编号
|
||||
* @param expectedOrderDataVersion - 用户看到的订单版本,用于拒绝并发覆盖
|
||||
*/
|
||||
export async function freezeWorkspaceShippingOrder(
|
||||
taskNo: string,
|
||||
expectedOrderDataVersion: number,
|
||||
) {
|
||||
const body = await requestJson<ShippingApiStatusPayload & {
|
||||
data?: { task_no: string; snapshot_id: number; order_data_version: number; frozen_at: string };
|
||||
}>(
|
||||
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/freeze-order`,
|
||||
jsonPost({ expected_order_data_version: expectedOrderDataVersion }),
|
||||
);
|
||||
return assertShippingOk(body);
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新指定订单行。
|
||||
* @param taskNo - 发货任务编号
|
||||
@@ -1364,23 +1228,6 @@ export async function markWorkspaceShippingManualUploaded(
|
||||
return assertShippingOk(body);
|
||||
}
|
||||
|
||||
/**
|
||||
* 重试将发货 Excel 上传至货代系统。
|
||||
* @param taskNo - 发货任务编号
|
||||
* @param ownership - 可选工作台归属上下文
|
||||
* @returns RPA 上传触发或等待结果
|
||||
*/
|
||||
export async function retryWorkspaceShippingUpload(
|
||||
taskNo: string,
|
||||
ownership?: ShippingFulfillmentOwnershipContext | null,
|
||||
) {
|
||||
const body = await requestJson<ShippingDecisionResponse & ShippingApiStatusPayload>(
|
||||
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/retry-upload`,
|
||||
jsonPost(ownershipPayload(ownership)),
|
||||
);
|
||||
return assertShippingOk(body);
|
||||
}
|
||||
|
||||
/** 发货通知 Agent 应用类型标识(运行时识别)。 */
|
||||
export const SHIPPING_NOTICE_AGENT_CODE = 'shipping_notice';
|
||||
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
/**
|
||||
* features/chat/components/ChatInputBar.spec.ts
|
||||
* 用途:验证采购合同双文件在聊天输入栏中的统一卡片展示与删除交互。
|
||||
* 依赖:Vue Test Utils、Vue I18n、ChatInputBar。
|
||||
* 逻辑:我方原合同和卖方回传合同均以附件卡片展示;删除我方原合同必须通知上层清除对应资产状态。
|
||||
*/
|
||||
import { mount } from '@vue/test-utils';
|
||||
import { ref } from 'vue';
|
||||
import { createI18n } from 'vue-i18n';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import ChatInputBar from './ChatInputBar.vue';
|
||||
|
||||
const i18n = createI18n({
|
||||
legacy: false,
|
||||
locale: 'zh-CN',
|
||||
messages: { 'zh-CN': {} },
|
||||
});
|
||||
|
||||
/** 创建采购合同双文件输入栏所需的最小属性。 */
|
||||
function mountProcurementInputBar() {
|
||||
return mount(ChatInputBar, {
|
||||
props: {
|
||||
modelValue: '',
|
||||
procurementReviewMode: 'compare',
|
||||
attachments: [{
|
||||
id: 'seller-contract',
|
||||
kind: 'local',
|
||||
file: new File(['seller'], '卖方回传合同.md', { type: 'text/markdown' }),
|
||||
type: 'document',
|
||||
uploadStatus: 'waiting',
|
||||
uploadProgress: 0,
|
||||
}],
|
||||
attachmentPolicy: { anyEnabled: true, canLocal: true, canRemote: false, accept: '.md' },
|
||||
isThinking: false,
|
||||
isVoiceRecording: false,
|
||||
isVoiceTranscribing: false,
|
||||
isUploadingAttachments: false,
|
||||
canSendMessage: true,
|
||||
isShippingNoticeAgent: false,
|
||||
isProcurementContractAgent: true,
|
||||
procurementOriginalContractName: '我方原合同.md',
|
||||
isMaintenanceAgent: false,
|
||||
canManageMaintenance: false,
|
||||
canForceCreateShippingDuplicate: false,
|
||||
shippingSuggestedPrompt: '',
|
||||
shippingPickerRefHolder: { pickerRef: ref(null) },
|
||||
shippingNoticePickerRefHolder: { pickerRef: ref(null) },
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
}
|
||||
|
||||
/** 创建仅选择我方原合同、尚未选择卖方回传合同的输入栏。 */
|
||||
function mountOriginalContractOnlyInputBar() {
|
||||
return mount(ChatInputBar, {
|
||||
props: {
|
||||
modelValue: '',
|
||||
procurementReviewMode: 'compare',
|
||||
attachments: [],
|
||||
attachmentPolicy: { anyEnabled: true, canLocal: true, canRemote: false, accept: '.md' },
|
||||
isThinking: false,
|
||||
isVoiceRecording: false,
|
||||
isVoiceTranscribing: false,
|
||||
isUploadingAttachments: true,
|
||||
canSendMessage: false,
|
||||
isShippingNoticeAgent: false,
|
||||
isProcurementContractAgent: true,
|
||||
procurementOriginalContractName: '我方原合同.md',
|
||||
isMaintenanceAgent: false,
|
||||
canManageMaintenance: false,
|
||||
canForceCreateShippingDuplicate: false,
|
||||
shippingSuggestedPrompt: '',
|
||||
shippingPickerRefHolder: { pickerRef: ref(null) },
|
||||
shippingNoticePickerRefHolder: { pickerRef: ref(null) },
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
}
|
||||
|
||||
describe('ChatInputBar procurement contract attachments', () => {
|
||||
it('shows the original contract immediately even before a seller contract is selected', () => {
|
||||
const wrapper = mountOriginalContractOnlyInputBar();
|
||||
|
||||
// 原合同上传中时卖方附件数组为空,仍必须显示原合同卡片提供明确反馈。
|
||||
expect(wrapper.get('[data-testid="chat-attachment-list"]')).toBeTruthy();
|
||||
expect(wrapper.get('[data-testid="procurement-original-contract-card"]')).toBeTruthy();
|
||||
expect(wrapper.findAll('[data-testid="chat-attachment-card"]')).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('renders the original contract as a standard attachment card and clears it on delete', async () => {
|
||||
const wrapper = mountProcurementInputBar();
|
||||
|
||||
// 断言两份合同使用同一附件卡片结构,防止我方原合同退化回独立小标签。
|
||||
expect(wrapper.get('[data-testid="procurement-original-contract-card"]')).toBeTruthy();
|
||||
expect(wrapper.findAll('[data-testid="chat-attachment-card"], [data-testid="procurement-original-contract-card"]')).toHaveLength(2);
|
||||
|
||||
await wrapper.get('[data-testid="remove-procurement-original-contract"]').trigger('click');
|
||||
|
||||
// 删除操作必须交由父级清空 originalContractAssetNo 与名称,避免残留无形基准文件。
|
||||
expect(wrapper.emitted('clear-procurement-original-contract')).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('keeps original-contract delete pointer events out of the attachment drag surface', async () => {
|
||||
const wrapper = mountProcurementInputBar();
|
||||
let dragSurfaceReceivedPointerDown = false;
|
||||
wrapper.get('[data-testid="chat-attachment-list"]').element.addEventListener('pointerdown', () => {
|
||||
dragSurfaceReceivedPointerDown = true;
|
||||
});
|
||||
|
||||
// 删除按钮不能触发横向拖拽容器,否则指针捕获会干扰实际 click 事件。
|
||||
await wrapper.get('[data-testid="remove-procurement-original-contract"]').trigger('pointerdown');
|
||||
|
||||
expect(dragSurfaceReceivedPointerDown).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -159,6 +159,12 @@ const hasProcurementContractAttachment = computed(() =>
|
||||
&& props.attachments.some((item) => item.kind === 'local'),
|
||||
);
|
||||
|
||||
/** 显示我方原合同卡片的文件扩展名;没有扩展名时使用通用文档标识。 */
|
||||
function getProcurementOriginalContractExtension(name: string): string {
|
||||
const extension = name.split('.').pop()?.trim();
|
||||
return extension ? extension.toUpperCase().slice(0, 4) : 'DOC';
|
||||
}
|
||||
|
||||
const procurementQuickActions = computed(() => {
|
||||
const actions = [
|
||||
{
|
||||
@@ -457,7 +463,7 @@ watch(
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="attachments.length > 0"
|
||||
v-if="attachments.length > 0 || (isProcurementContractAgent && procurementReviewMode === 'compare' && procurementOriginalContractName)"
|
||||
data-testid="chat-attachment-list"
|
||||
class="relative flex items-center gap-1 px-2.5 pb-2 pt-1"
|
||||
>
|
||||
@@ -473,9 +479,44 @@ watch(
|
||||
@pointercancel="stopAttachmentDrag"
|
||||
@pointerleave="stopAttachmentDrag"
|
||||
>
|
||||
<article
|
||||
v-if="isProcurementContractAgent && procurementReviewMode === 'compare' && procurementOriginalContractName"
|
||||
data-testid="procurement-original-contract-card"
|
||||
class="group relative flex h-[68px] w-[250px] shrink-0 items-center gap-3 rounded-xl border border-[#9cc7f2] bg-[#eef6ff] px-3 py-2.5 transition-colors"
|
||||
:title="procurementOriginalContractName"
|
||||
>
|
||||
<div
|
||||
class="flex h-11 w-10 shrink-0 flex-col items-center justify-center rounded-lg bg-brand-50 text-brand-700 dark:bg-brand-900/30 dark:text-brand-300"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<FileText class="h-4.5 w-4.5" />
|
||||
<span class="mt-0.5 max-w-9 truncate text-[9px] font-bold leading-none">{{ getProcurementOriginalContractExtension(procurementOriginalContractName) }}</span>
|
||||
</div>
|
||||
<div class="min-w-0 flex-1 pr-5">
|
||||
<p class="truncate text-sm font-medium text-primary">
|
||||
<span class="mr-1 text-[#2f80d1]">{{ $t('chat.procurementContract.originalContractChip', { name: '' }) }}</span>
|
||||
{{ procurementOriginalContractName }}
|
||||
</p>
|
||||
<div class="mt-1 flex min-w-0 items-center gap-1.5 text-[11px] leading-none text-muted">
|
||||
<span>{{ $t('chat.attachment.pending') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
data-testid="remove-procurement-original-contract"
|
||||
class="absolute right-1.5 top-1.5 flex h-6 w-6 items-center justify-center rounded-full text-muted opacity-80 transition hover:bg-surface hover:text-red-500 focus-visible:opacity-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-400"
|
||||
:title="t('chat.attachment.remove')"
|
||||
:aria-label="t('chat.attachment.removeNamed', { name: procurementOriginalContractName })"
|
||||
@pointerdown.stop
|
||||
@click.stop="emit('clear-procurement-original-contract')"
|
||||
>
|
||||
<X class="h-3.5 w-3.5" />
|
||||
</button>
|
||||
</article>
|
||||
<article
|
||||
v-for="a in attachments"
|
||||
:key="a.id"
|
||||
data-testid="chat-attachment-card"
|
||||
class="group relative flex h-[68px] w-[250px] shrink-0 items-center gap-3 rounded-xl px-3 py-2.5 transition-colors"
|
||||
:class="isProcurementContractAgent && a.kind === 'local'
|
||||
? 'border border-[#9cc7f2] bg-[#eef6ff]'
|
||||
@@ -572,7 +613,8 @@ watch(
|
||||
:disabled="isAttachmentRemoveDisabled(a)"
|
||||
:title="t('chat.attachment.remove')"
|
||||
:aria-label="t('chat.attachment.removeNamed', { name: getAttachmentName(a) })"
|
||||
@click="emit('remove-attachment', a.id)"
|
||||
@pointerdown.stop
|
||||
@click.stop="emit('remove-attachment', a.id)"
|
||||
>
|
||||
<X class="h-3.5 w-3.5" />
|
||||
</button>
|
||||
@@ -606,19 +648,6 @@ watch(
|
||||
@change="emit('procurement-original-contract-selected', $event)"
|
||||
/>
|
||||
|
||||
<div
|
||||
v-if="isProcurementContractAgent && procurementReviewMode === 'compare' && procurementOriginalContractName"
|
||||
class="flex flex-wrap gap-2 px-3 pb-1"
|
||||
>
|
||||
<div class="flex items-center gap-2 rounded-lg border border-dashed border-[#8db8e6] bg-[#eef6ff] px-2 py-1 text-xs font-semibold text-[#1f5f99]">
|
||||
<FileText class="h-3.5 w-3.5" />
|
||||
<span class="max-w-[260px] truncate">{{ $t('chat.procurementContract.originalContractChip', { name: procurementOriginalContractName }) }}</span>
|
||||
<button type="button" class="text-[#1f5f99] hover:opacity-80" @click="emit('clear-procurement-original-contract')">
|
||||
<X class="h-3.5 w-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="hasProcurementContractAttachment"
|
||||
class="flex flex-wrap items-center gap-2 px-3 pb-1"
|
||||
|
||||
@@ -48,6 +48,7 @@ const {
|
||||
pinMessagesToBottom?: boolean;
|
||||
/** 供父级滚动逻辑绑定 main 元素 */
|
||||
scrollContainerHolder: { el: Ref<HTMLElement | null> };
|
||||
compactShippingProgress?: boolean;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
@@ -61,6 +62,7 @@ const emit = defineEmits<{
|
||||
'maintenance-edit-record': [record: MaintenanceRecord];
|
||||
'maintenance-view-record-history': [device: MaintenanceDevice];
|
||||
'maintenance-create-record-for-device': [device: MaintenanceDevice];
|
||||
'open-batch-workbench': [];
|
||||
}>();
|
||||
|
||||
const bindScrollContainer = (node: unknown) => {
|
||||
@@ -77,32 +79,45 @@ const getMessageKey = (msg: ChatMessage, index: number) => (
|
||||
|| `${msg.role}:${msg.run_id || 'none'}:${String(msg.content || '').slice(0, 40)}:${index}`
|
||||
);
|
||||
|
||||
/** 同一 Run 只展示最后一张状态卡,避免历史恢复/SSE 补帧造成重复窗口。 */
|
||||
/** 同一 Run 或同一次上传批次只展示最后一张状态卡,避免历史恢复/SSE 补帧造成重复窗口。 */
|
||||
const isDuplicateShippingExtractionMessage = (items: ChatMessage[], index: number): boolean => {
|
||||
const current = items[index];
|
||||
if (!current?.shipping_order_extraction_state) return false;
|
||||
const payload = current.payload && typeof current.payload === 'object'
|
||||
? current.payload as Record<string, unknown>
|
||||
: {};
|
||||
const identity = String(
|
||||
const runIdentity = String(
|
||||
payload.order_extraction_run_no
|
||||
|| payload.formId
|
||||
|| current.shipping_order_extraction_state.runNo
|
||||
|| '',
|
||||
).trim();
|
||||
if (!identity) return false;
|
||||
const batchIdentity = String(
|
||||
payload.shipping_order_extraction_upload_batch_id
|
||||
|| current.shipping_order_extraction_state.uploadBatchId
|
||||
|| '',
|
||||
).trim();
|
||||
if (!runIdentity && !batchIdentity) return false;
|
||||
return items.slice(index + 1).some((candidate) => {
|
||||
if (!candidate?.shipping_order_extraction_state) return false;
|
||||
const candidatePayload = candidate.payload && typeof candidate.payload === 'object'
|
||||
? candidate.payload as Record<string, unknown>
|
||||
: {};
|
||||
const candidateIdentity = String(
|
||||
const candidateRunIdentity = String(
|
||||
candidatePayload.order_extraction_run_no
|
||||
|| candidatePayload.formId
|
||||
|| candidate.shipping_order_extraction_state.runNo
|
||||
|| '',
|
||||
).trim();
|
||||
return candidateIdentity === identity;
|
||||
const candidateBatchIdentity = String(
|
||||
candidatePayload.shipping_order_extraction_upload_batch_id
|
||||
|| candidate.shipping_order_extraction_state.uploadBatchId
|
||||
|| '',
|
||||
).trim();
|
||||
return Boolean(
|
||||
(batchIdentity && candidateBatchIdentity === batchIdentity)
|
||||
|| (runIdentity && candidateRunIdentity === runIdentity),
|
||||
);
|
||||
});
|
||||
};
|
||||
|
||||
@@ -153,6 +168,7 @@ const isLatestAssistantMessage = (items: ChatMessage[], index: number) => {
|
||||
:leave-handlers="leaveHandlers"
|
||||
:shipping-handlers="shippingHandlers"
|
||||
:training-handlers="trainingHandlers"
|
||||
:compact-shipping-progress="compactShippingProgress"
|
||||
@copy="emit('copy', { message: msg, index })"
|
||||
@edit="emit('edit', $event)"
|
||||
@resend="emit('resend', $event)"
|
||||
@@ -161,6 +177,7 @@ const isLatestAssistantMessage = (items: ChatMessage[], index: number) => {
|
||||
@maintenance-edit-record="emit('maintenance-edit-record', $event)"
|
||||
@maintenance-view-record-history="emit('maintenance-view-record-history', $event)"
|
||||
@maintenance-create-record-for-device="emit('maintenance-create-record-for-device', $event)"
|
||||
@open-batch-workbench="emit('open-batch-workbench')"
|
||||
/>
|
||||
<ToolRunProgressCard
|
||||
v-if="shouldRenderMessage(msg) && shouldShowToolRunProgressAfterMessage(msg, index)"
|
||||
|
||||
@@ -88,7 +88,8 @@ const route = useRoute();
|
||||
|
||||
const shippingProcessing = useShippingNoticeWorkflow({
|
||||
// 历史会话首屏直接使用路由 ID,与聊天消息并行拉取统一进度。
|
||||
conversationId: () => page.conversationId || String(route.query.conversation_id || ''),
|
||||
// 路由切换先于 page 历史消息回填;必须先切换 Projection,禁止短暂复用旧会话卡片。
|
||||
conversationId: () => String(route.query.conversation_id || page.conversationId || ''),
|
||||
refreshTrigger: () => page.workflowRefreshTrigger,
|
||||
});
|
||||
provide(SHIPPING_WORKFLOW_KEY, shippingProcessing);
|
||||
@@ -151,13 +152,39 @@ const activeExtractionRunNo = computed(() => {
|
||||
|
||||
});
|
||||
|
||||
/** 批次进度工作台按需打开;关闭时不占用对话区右侧布局。 */
|
||||
const batchWorkbenchOpen = ref(false);
|
||||
|
||||
|
||||
|
||||
const showShippingWorkflowTimeline = computed(() => (
|
||||
page.isShippingNoticeAgent
|
||||
&& batchWorkbenchOpen.value
|
||||
&& Boolean(page.conversationId || activeExtractionRunNo.value)
|
||||
));
|
||||
|
||||
const compactShippingProgress = computed(() => batchWorkbenchOpen.value);
|
||||
|
||||
function openBatchWorkbench() {
|
||||
batchWorkbenchOpen.value = true;
|
||||
}
|
||||
|
||||
function closeBatchWorkbench() {
|
||||
batchWorkbenchOpen.value = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 批次中心只服务于用户主动打开时所在的会话。切换历史会话或 Agent 后必须关闭,
|
||||
* 否则旧会话的右侧投影会短暂占用新会话的对话区并造成“本次处理”串批错觉。
|
||||
*/
|
||||
watch(
|
||||
() => [String(page.conversationId || ''), Number(page.currentAgentId || 0)] as const,
|
||||
(next, previous) => {
|
||||
if (!previous || next[0] === previous[0] && next[1] === previous[1]) return;
|
||||
batchWorkbenchOpen.value = false;
|
||||
},
|
||||
);
|
||||
|
||||
const embeddedIframeSrc = computed(() => {
|
||||
|
||||
const agent = page.currentAgent;
|
||||
@@ -480,9 +507,9 @@ watch(() => page.currentAgentId, () => {
|
||||
|
||||
<ShippingOrderReviewView v-if="isOrderReviewMode" />
|
||||
|
||||
<div v-else class="flex min-h-0 min-w-0 flex-1">
|
||||
<div v-else class="flex min-h-0 min-w-0 flex-1" :class="showShippingWorkflowTimeline ? 'shipping-workbench-layout' : ''">
|
||||
|
||||
<div class="flex min-h-0 min-w-0 flex-1 flex-col">
|
||||
<div class="flex min-h-0 min-w-0 flex-1 flex-col" :class="showShippingWorkflowTimeline ? 'shipping-chat-column' : ''">
|
||||
|
||||
<TrainingWorkspacePanel
|
||||
|
||||
@@ -560,6 +587,8 @@ watch(() => page.currentAgentId, () => {
|
||||
|
||||
:scroll-container-holder="page.scrollContainerHolder"
|
||||
|
||||
:compact-shipping-progress="compactShippingProgress"
|
||||
|
||||
@copy="page.copyToClipboard($event.message, $event.index)"
|
||||
|
||||
@edit="page.input = $event"
|
||||
@@ -580,6 +609,8 @@ watch(() => page.currentAgentId, () => {
|
||||
|
||||
@maintenance-create-record-for-device="openMaintenanceRecordCreate"
|
||||
|
||||
@open-batch-workbench="openBatchWorkbench"
|
||||
|
||||
/>
|
||||
|
||||
|
||||
@@ -666,6 +697,8 @@ watch(() => page.currentAgentId, () => {
|
||||
:conversation-id="page.conversationId"
|
||||
:refresh-trigger="page.workflowRefreshTrigger"
|
||||
:controller="shippingProcessing"
|
||||
|
||||
@close="closeBatchWorkbench"
|
||||
/>
|
||||
|
||||
|
||||
@@ -816,3 +849,16 @@ watch(() => page.currentAgentId, () => {
|
||||
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
/** 打开批次工作台后,左侧对话保留为压缩入口,右侧取得主工作区宽度。 */
|
||||
@media (min-width: 1024px) {
|
||||
.shipping-workbench-layout {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.shipping-chat-column {
|
||||
flex: 0 0 clamp(360px, 32vw, 520px);
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
/**
|
||||
* features/chat/components/ShippingWorkflowStepper.vue
|
||||
* 用途:货代发货七步流程 Stepper 展示组件。
|
||||
* 用途:货代发货四阶段 Stepper 展示组件。
|
||||
* 依赖:shipping/shippingStepper、vue-i18n。
|
||||
* 逻辑:Chat 与工作台传入 steps 数组;本组件只负责步骤高亮与标签渲染。
|
||||
*/
|
||||
@@ -33,7 +33,7 @@ const dotClass = (status: ShippingWorkflowStepItem['status']) => {
|
||||
<template>
|
||||
<div class="space-y-2">
|
||||
<div class="text-[11px] font-semibold uppercase tracking-[0.18em] text-muted">{{ t('chat.shippingNoticeUi.stepperTitle') }}</div>
|
||||
<div class="grid gap-2" :class="compact ? 'sm:grid-cols-4 xl:grid-cols-7' : 'md:grid-cols-4 xl:grid-cols-7'">
|
||||
<div class="grid gap-2" :class="compact ? 'sm:grid-cols-4' : 'md:grid-cols-4'">
|
||||
<div
|
||||
v-for="(step, index) in steps"
|
||||
:key="step.id"
|
||||
|
||||
@@ -72,6 +72,7 @@ const {
|
||||
leaveHandlers: LeaveMessageHandlers;
|
||||
shippingHandlers: ShippingMessageHandlers;
|
||||
trainingHandlers: TrainingHandlers;
|
||||
compactShippingProgress?: boolean;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
@@ -83,6 +84,7 @@ const emit = defineEmits<{
|
||||
'maintenance-edit-record': [record: MaintenanceRecord];
|
||||
'maintenance-view-record-history': [device: MaintenanceDevice];
|
||||
'maintenance-create-record-for-device': [device: MaintenanceDevice];
|
||||
'open-batch-workbench': [];
|
||||
}>();
|
||||
|
||||
const authStore = useAuthStore();
|
||||
@@ -712,7 +714,9 @@ function handleInlineDownload(file: InlineDownloadFile): void {
|
||||
? 'rounded-2xl rounded-tr-sm bg-brand-600 px-5 py-2.5 text-white shadow-sm shadow-brand-500/15'
|
||||
: isContractReviewMessage
|
||||
? 'w-full'
|
||||
: 'chat-msg-assistant'"
|
||||
: shippingOrderExtractionState
|
||||
? 'w-full'
|
||||
: 'chat-msg-assistant'"
|
||||
>
|
||||
<template v-if="message.role === 'user'">
|
||||
<ChatMessageAttachmentList
|
||||
@@ -731,9 +735,11 @@ function handleInlineDownload(file: InlineDownloadFile): void {
|
||||
:retrying="retryingOrderExtraction"
|
||||
:refreshing="refreshingOrderExtraction"
|
||||
:cancelling="cancellingOrderExtraction"
|
||||
:compact-progress="compactShippingProgress"
|
||||
@retry="retryShippingOrderExtraction"
|
||||
@refresh="refreshShippingOrderExtraction"
|
||||
@cancel="cancelShippingOrderExtraction"
|
||||
@open-batch-workbench="emit('open-batch-workbench')"
|
||||
/>
|
||||
<LeaveMessageBlock
|
||||
v-if="isLeaveMessage"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<!--
|
||||
features/chat/components/shipping-review/ReviewActionConfirmDialog.vue
|
||||
用途:复核页破坏性/不可逆操作的二次确认弹窗(确认建单、重识别、非订单、质量异常、替代 PDF)。
|
||||
用途:复核页破坏性/不可逆操作的二次确认弹窗(确认建单、重识别、非订单、质量异常)。
|
||||
依赖:vue-i18n、dialog-overlay / dialog-panel 设计系统样式。
|
||||
逻辑:ShippingOrderReviewView 以 v-model 控制显隐;质量异常须选原因码,other 时备注必填;
|
||||
非订单/重识别将说明写入 comment,并附带稳定 reasonCode。
|
||||
@@ -9,7 +9,7 @@
|
||||
import { computed, onBeforeUnmount, ref, watch } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
|
||||
export type ReviewConfirmAction = 'confirm' | 'reparse' | 'non_order' | 'replace' | 'quality_issue';
|
||||
export type ReviewConfirmAction = 'confirm' | 'reparse' | 'non_order' | 'quality_issue';
|
||||
|
||||
/** 确认弹窗提交载荷:稳定原因码 + 自由说明,供后端审计复盘。 */
|
||||
export type ReviewConfirmPayload = {
|
||||
|
||||
+45
@@ -18,6 +18,8 @@ const i18n = createI18n({
|
||||
line: '第 {index} 行',
|
||||
buildEligibility: {
|
||||
overallResult: '整单结果', canBuildYes: '可建单', canBuildNo: '待处理',
|
||||
manualBuildLabel: '人工建单', autoBuildLabel: '自动建单',
|
||||
autoBuildYes: '可自动建单', autoBuildNo: '暂不可自动建单',
|
||||
manualConfirmOnly: '需人工确认', blockReasons: { unknown: '未知阻断' },
|
||||
routingStatus: { unknown: '未知' },
|
||||
},
|
||||
@@ -40,6 +42,49 @@ const eligibility = {
|
||||
};
|
||||
|
||||
describe('ReviewBuildEligibilityDetailsDrawer', () => {
|
||||
it('separates manual buildability from automatic creation eligibility', () => {
|
||||
const wrapper = mount(ReviewBuildEligibilityDetailsDrawer, {
|
||||
props: {
|
||||
open: true,
|
||||
eligibility: {
|
||||
can_build: true,
|
||||
can_auto_create: false,
|
||||
status: 'ready',
|
||||
failed_gates: ['field_conflicts_resolved'],
|
||||
issues: [],
|
||||
line_projections: [],
|
||||
},
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
|
||||
// 关键断言:抽屉不能只写“可建单”而让自动门禁失败看似矛盾。
|
||||
expect(wrapper.find('[data-testid="review-eligibility-manual-status"]').text()).toContain('可建单');
|
||||
expect(wrapper.find('[data-testid="review-eligibility-auto-status"]').text()).toContain('暂不可自动建单');
|
||||
});
|
||||
|
||||
it('does not render an empty diagnostic section when there are no diagnostic facts', () => {
|
||||
const wrapper = mount(ReviewBuildEligibilityDetailsDrawer, {
|
||||
props: {
|
||||
open: true,
|
||||
eligibility: {
|
||||
can_build: true,
|
||||
can_auto_create: false,
|
||||
status: 'ready',
|
||||
issues: [],
|
||||
failed_gates: [],
|
||||
assessment: { missing_required_fields: [] },
|
||||
line_projections: [{ line_key: 'L1', line_index: 0, can_build: true }],
|
||||
},
|
||||
fieldConflicts: [],
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
|
||||
// 关键断言:没有问题明细时不能留下无内容的边框占位区。
|
||||
expect(wrapper.findAll('section')).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('lists the exact conflicting field, line, sources and values', () => {
|
||||
const wrapper = mount(ReviewBuildEligibilityDetailsDrawer, {
|
||||
props: {
|
||||
|
||||
+31
-4
@@ -134,6 +134,15 @@ const unexplainedBlocked = computed(() => Boolean(
|
||||
&& !props.eligibility.assessment?.missing_required_fields?.length
|
||||
&& !(props.eligibility.line_projections || []).some((line) => line.can_build === false),
|
||||
));
|
||||
|
||||
/** 有可解释的诊断事实时才渲染中段,避免通过订单留下空白占位框。 */
|
||||
const hasDiagnosticDetails = computed(() => Boolean(
|
||||
props.eligibility?.assessment?.missing_required_fields?.length
|
||||
|| nonConflictIssues.value.length
|
||||
|| unexplainedBlocked.value
|
||||
|| props.fieldConflicts?.length
|
||||
|| hasFieldConflictIssue.value
|
||||
));
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -163,12 +172,27 @@ const unexplainedBlocked = computed(() => Boolean(
|
||||
: 'border-amber-200 bg-amber-50 text-amber-900 dark:border-amber-900 dark:bg-amber-950/30 dark:text-amber-100'"
|
||||
data-testid="review-eligibility-details-overall"
|
||||
>
|
||||
<div class="flex items-center justify-between gap-2">
|
||||
<div class="flex flex-wrap items-center justify-between gap-2">
|
||||
<span class="font-semibold">{{ t('chat.shippingOrderReview.buildEligibility.overallResult') }}</span>
|
||||
<span class="text-slate-600 dark:text-slate-300">{{ t('chat.shippingOrderReview.buildEligibility.manualBuildLabel') }}</span>
|
||||
<span class="rounded-full px-2 py-0.5 font-medium" :class="eligibility.can_build ? 'bg-emerald-100 text-emerald-800 dark:bg-emerald-900/60 dark:text-emerald-100' : 'bg-amber-100 text-amber-900 dark:bg-amber-900/60 dark:text-amber-100'">
|
||||
{{ eligibility.can_build
|
||||
<span data-testid="review-eligibility-manual-status">{{ eligibility.can_build
|
||||
? t('chat.shippingOrderReview.buildEligibility.canBuildYes')
|
||||
: t('chat.shippingOrderReview.buildEligibility.canBuildNo') }}
|
||||
: t('chat.shippingOrderReview.buildEligibility.canBuildNo') }}</span>
|
||||
</span>
|
||||
</div>
|
||||
<div class="mt-2 flex flex-wrap items-center justify-between gap-2">
|
||||
<span class="text-slate-600 dark:text-slate-300">{{ t('chat.shippingOrderReview.buildEligibility.autoBuildLabel') }}</span>
|
||||
<span
|
||||
class="rounded-full px-2 py-0.5 font-medium"
|
||||
:class="eligibility.can_auto_create
|
||||
? 'bg-emerald-100 text-emerald-800 dark:bg-emerald-900/60 dark:text-emerald-100'
|
||||
: 'bg-amber-100 text-amber-900 dark:bg-amber-900/60 dark:text-amber-100'"
|
||||
data-testid="review-eligibility-auto-status"
|
||||
>
|
||||
{{ eligibility.can_auto_create
|
||||
? t('chat.shippingOrderReview.buildEligibility.autoBuildYes')
|
||||
: t('chat.shippingOrderReview.buildEligibility.autoBuildNo') }}
|
||||
</span>
|
||||
</div>
|
||||
<p v-if="eligibility.can_build && eligibility.can_auto_create === false" class="mt-1">
|
||||
@@ -183,7 +207,10 @@ const unexplainedBlocked = computed(() => Boolean(
|
||||
</ul>
|
||||
</div>
|
||||
</section>
|
||||
<section class="rounded-lg border border-slate-200 bg-slate-50 p-3 text-xs dark:border-slate-700 dark:bg-slate-950/40">
|
||||
<section
|
||||
v-if="hasDiagnosticDetails"
|
||||
class="rounded-lg border border-slate-200 bg-slate-50 p-3 text-xs dark:border-slate-700 dark:bg-slate-950/40"
|
||||
>
|
||||
<div v-if="eligibility.assessment?.missing_required_fields?.length" class="mt-2">
|
||||
<div class="font-medium">{{ t('chat.shippingOrderReview.workbench.requiredFields') }}</div>
|
||||
<div class="mt-1 text-rose-700 dark:text-rose-300">
|
||||
|
||||
+12
-9
@@ -165,8 +165,8 @@ describe('ReviewBuildEligibilitySummary', () => {
|
||||
expect(wrapper.text()).not.toContain('can_auto_create');
|
||||
});
|
||||
|
||||
it('hides primary-block under focusBuildability for inventory combo (UI-03)', () => {
|
||||
// 关键断言:库存阻断由 Gate 卡表达时,资格摘要不得再输出首要阻断标题。
|
||||
it('keeps primary-block under focusBuildability for inventory combo (UI-03)', () => {
|
||||
// 关键断言:当前任务卡只承载动作,资格摘要仍保留库存门禁的具体解释。
|
||||
const i18n = createI18n({
|
||||
legacy: false,
|
||||
locale: 'zh-CN',
|
||||
@@ -218,13 +218,14 @@ describe('ReviewBuildEligibilitySummary', () => {
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
expect(wrapper.find('[data-testid="review-build-eligibility-summary"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="review-eligibility-primary-block"]').exists()).toBe(false);
|
||||
expect(wrapper.find('[data-testid="review-eligibility-gate-checklist"]').exists()).toBe(false);
|
||||
expect(wrapper.find('[data-testid="review-eligibility-primary-block"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="review-eligibility-gate-checklist"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="review-exception-nav"]').exists()).toBe(true);
|
||||
});
|
||||
|
||||
it('hides primary-block under focusBuildability for field completeness combo (UI-03)', () => {
|
||||
// 关键断言:字段阻断组合态下资格卡只保留摘要与异常导航,不输出第二份首要阻断。
|
||||
it('keeps concrete missing-field diagnostics visible under focusBuildability (UI-03)', () => {
|
||||
// 关键断言:当前任务卡只承载动作;建单资格卡仍必须给出缺失字段和首要阻断,
|
||||
// 否则用户无法从泛化 Gate 文案定位订单明细问题。
|
||||
const wrapper = mount(ReviewBuildEligibilitySummary, {
|
||||
props: {
|
||||
eligibility: {
|
||||
@@ -280,11 +281,13 @@ describe('ReviewBuildEligibilitySummary', () => {
|
||||
})],
|
||||
},
|
||||
});
|
||||
expect(wrapper.find('[data-testid="review-eligibility-primary-block"]').exists()).toBe(false);
|
||||
expect(wrapper.find('[data-testid="review-eligibility-primary-block"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="review-eligibility-gate-checklist"]').exists()).toBe(true);
|
||||
expect(wrapper.text()).toContain('缺失必填:PO');
|
||||
});
|
||||
|
||||
it('hides primary-block when technical_auto_only leaves business gate inactive (UI-03)', () => {
|
||||
// 关键断言:仅技术 Gate pending 时 focusBuildability=false,资格卡可展示阻断;本测验证开启 focus 时仍唯一。
|
||||
it('keeps passing eligibility concise when focusBuildability is enabled (UI-03)', () => {
|
||||
// 关键断言:无阻断时不额外渲染首要阻断;focusBuildability 不影响资格事实展示。
|
||||
const wrapper = mount(ReviewBuildEligibilitySummary, {
|
||||
props: {
|
||||
eligibility: {
|
||||
|
||||
+5
-5
@@ -21,8 +21,8 @@ const props = defineProps<{
|
||||
/** 当前定位异常序号;未定位时为 0。 */
|
||||
exceptionOrdinal?: number;
|
||||
/**
|
||||
* 为 true 时只展示能否建单/自动建单与异常导航,隐藏门禁清单与首要阻断文案,
|
||||
* 避免与 ProcessGateRecoveryCard 重复表达同一业务阻断。
|
||||
* 兼容旧调用方的展示偏好。当前任务卡只承载动作,建单门禁仍须完整展示,
|
||||
* 因此该参数不再隐藏字段级诊断,避免用户只能看到泛化阻断原因。
|
||||
*/
|
||||
focusBuildability?: boolean;
|
||||
}>();
|
||||
@@ -233,7 +233,7 @@ const gateChecklist = computed(() => {
|
||||
{{ t('chat.shippingOrderReview.buildEligibility.manualConfirmOnly') }}
|
||||
</p>
|
||||
<ul
|
||||
v-if="!focusBuildability && gateChecklist.length"
|
||||
v-if="gateChecklist.length"
|
||||
class="mt-2 space-y-1 text-xs"
|
||||
data-testid="review-eligibility-gate-checklist"
|
||||
>
|
||||
@@ -285,7 +285,7 @@ const gateChecklist = computed(() => {
|
||||
<p v-if="conflictFields.length"><span class="font-semibold">{{ t('chat.shippingOrderReview.workbench.conflictFields') }}:</span>{{ [...new Set(conflictFields)].join('、') }}</p>
|
||||
</div>
|
||||
<div
|
||||
v-if="!focusBuildability && lowConfidenceFields.length"
|
||||
v-if="lowConfidenceFields.length"
|
||||
class="mt-2 rounded-lg border border-amber-200 bg-amber-50 px-2.5 py-2 text-xs text-amber-950 dark:border-amber-900 dark:bg-amber-950/30 dark:text-amber-100"
|
||||
data-testid="review-low-confidence-fields"
|
||||
>
|
||||
@@ -298,7 +298,7 @@ const gateChecklist = computed(() => {
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="!focusBuildability && !eligibility.can_build && primaryBlockMessage"
|
||||
v-if="!eligibility.can_build && primaryBlockMessage"
|
||||
class="mt-2 rounded-lg border border-amber-200 bg-amber-50 px-2.5 py-2 text-xs text-amber-950 dark:border-amber-900 dark:bg-amber-950/30 dark:text-amber-100"
|
||||
data-testid="review-eligibility-primary-block"
|
||||
>
|
||||
|
||||
-87
@@ -1,87 +0,0 @@
|
||||
<!--
|
||||
features/chat/components/shipping-review/ReviewConversationRetryDrawer.vue
|
||||
用途:按需展示本次对话级自动推进重试的逐项结果,不占用订单复核主内容。
|
||||
依赖:vue-i18n、对话级重试 API 返回的摘要和对象结果。
|
||||
逻辑:仅用户主动从顶栏打开;按结果分类展示,关闭不改变任务真实状态。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue';
|
||||
import { RefreshCw } from 'lucide-vue-next';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
|
||||
type RetryItem = {
|
||||
object_type: string;
|
||||
object_ref: string;
|
||||
action?: string | null;
|
||||
outcome: string;
|
||||
reason_code?: string | null;
|
||||
};
|
||||
|
||||
const props = defineProps<{
|
||||
open: boolean;
|
||||
result: {
|
||||
summary: { total: number; retried: number; skipped: number; failed: number; blocked?: number };
|
||||
items: RetryItem[];
|
||||
} | null;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{ close: [] }>();
|
||||
const { t, te } = useI18n();
|
||||
|
||||
const items = computed(() => props.result?.items || []);
|
||||
|
||||
function itemLabel(item: RetryItem): string {
|
||||
const code = String(item.reason_code || '').trim();
|
||||
const key = `chat.shippingOrderReview.conversationRetry.reason.${code}`;
|
||||
return code && te(key) ? t(key) : outcomeLabel(item.outcome);
|
||||
}
|
||||
|
||||
function outcomeLabel(outcome: string): string {
|
||||
const key = `chat.shippingOrderReview.conversationRetry.outcome.${String(outcome || '').trim()}`;
|
||||
return te(key) ? t(key) : t('chat.shippingOrderReview.conversationRetry.outcome.unknown');
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div
|
||||
v-if="open && result"
|
||||
class="fixed inset-0 z-40 flex justify-end bg-slate-900/10"
|
||||
data-testid="review-conversation-retry-drawer"
|
||||
@click.self="emit('close')"
|
||||
>
|
||||
<aside class="flex h-full w-full max-w-[360px] flex-col border-l border-slate-200 bg-white shadow-2xl dark:border-slate-800 dark:bg-slate-900">
|
||||
<header class="flex items-center justify-between gap-3 border-b border-slate-200 px-3 py-2.5 dark:border-slate-800">
|
||||
<div class="flex min-w-0 items-center gap-2">
|
||||
<span class="flex h-6 w-6 shrink-0 items-center justify-center rounded-full bg-amber-100 text-amber-700 dark:bg-amber-900/60 dark:text-amber-200">
|
||||
<RefreshCw class="h-3.5 w-3.5" />
|
||||
</span>
|
||||
<div class="min-w-0">
|
||||
<h2 class="text-sm font-semibold">{{ t('chat.shippingOrderReview.conversationRetry.title') }}</h2>
|
||||
<p class="truncate text-[11px] text-muted">{{ t('chat.shippingOrderReview.conversationRetry.subtitle') }}</p>
|
||||
</div>
|
||||
</div>
|
||||
<button type="button" class="rounded border border-slate-300 px-2 py-1 text-xs hover:bg-slate-50 dark:border-slate-600 dark:hover:bg-slate-800" data-testid="review-conversation-retry-drawer-close" @click="emit('close')">
|
||||
{{ t('chat.shippingOrderReview.workbench.close') }}
|
||||
</button>
|
||||
</header>
|
||||
<div class="flex flex-wrap gap-1.5 border-b border-slate-200 px-3 py-2 dark:border-slate-800">
|
||||
<p class="rounded-full bg-emerald-50 px-2 py-1 text-[11px] text-emerald-700 dark:bg-emerald-950/40 dark:text-emerald-300" data-testid="review-conversation-retry-retried">{{ t('chat.shippingOrderReview.conversationRetry.retried') }} <strong>{{ result.summary.retried }}</strong></p>
|
||||
<p class="rounded-full bg-slate-100 px-2 py-1 text-[11px] text-slate-600 dark:bg-slate-800 dark:text-slate-300" data-testid="review-conversation-retry-skipped">{{ t('chat.shippingOrderReview.conversationRetry.skipped') }} <strong>{{ result.summary.skipped }}</strong></p>
|
||||
<p class="rounded-full bg-rose-50 px-2 py-1 text-[11px] text-rose-700 dark:bg-rose-950/40 dark:text-rose-300" data-testid="review-conversation-retry-failed">{{ t('chat.shippingOrderReview.conversationRetry.failed') }} <strong>{{ result.summary.failed }}</strong></p>
|
||||
<p class="rounded-full bg-violet-50 px-2 py-1 text-[11px] text-violet-700 dark:bg-violet-950/40 dark:text-violet-300" data-testid="review-conversation-retry-blocked">{{ t('chat.shippingOrderReview.conversationRetry.blocked') }} <strong>{{ result.summary.blocked || 0 }}</strong></p>
|
||||
</div>
|
||||
<ul class="min-h-0 flex-1 divide-y divide-slate-100 overflow-y-auto dark:divide-slate-800" data-testid="review-conversation-retry-item-list">
|
||||
<li v-for="item in items" :key="`${item.object_type}:${item.object_ref}`" class="px-3 py-2.5 text-xs">
|
||||
<div class="flex items-center justify-between gap-2">
|
||||
<p class="min-w-0 truncate font-medium text-slate-800 dark:text-slate-100">{{ item.object_ref }}</p>
|
||||
<span
|
||||
class="shrink-0 rounded-full px-1.5 py-0.5 text-[10px]"
|
||||
:class="item.outcome === 'queued' ? 'bg-emerald-50 text-emerald-700 dark:bg-emerald-950/40 dark:text-emerald-300' : item.outcome === 'needs_human' ? 'bg-amber-50 text-amber-700 dark:bg-amber-950/40 dark:text-amber-300' : 'bg-slate-100 text-slate-600 dark:bg-slate-800 dark:text-slate-300'"
|
||||
>{{ outcomeLabel(item.outcome) }}</span>
|
||||
</div>
|
||||
<p class="mt-0.5 text-[11px] text-muted">{{ itemLabel(item) }}</p>
|
||||
</li>
|
||||
</ul>
|
||||
</aside>
|
||||
</div>
|
||||
</template>
|
||||
+146
-4
@@ -15,6 +15,39 @@ const i18n = createI18n({
|
||||
messages: {
|
||||
'zh-CN': {
|
||||
'chat.shippingOrderReview.processGate.actionCodes.retry_inventory_matching': '重新库存匹配',
|
||||
workspace: {
|
||||
shippingNotice: {
|
||||
processGate: {
|
||||
actionCodes: {
|
||||
retry_inventory_preparation: '重新获取库存',
|
||||
},
|
||||
inventoryActions: {
|
||||
retryInventoryMatching: '重新库存匹配',
|
||||
retryInventoryPreparation: '重新获取库存',
|
||||
},
|
||||
reasons: {
|
||||
inventory_shortage_review_required: '存在库存缺口,需要人工处理',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
chat: {
|
||||
shippingOrderReview: {
|
||||
saveOrderAndValidate: '保存订单并校验',
|
||||
currentProcessing: {
|
||||
waitingStart: '等待系统启动',
|
||||
},
|
||||
currentTask: {
|
||||
statusRunning: '系统处理中',
|
||||
nextStepWaitingExternal: '等待外部系统回执,暂不需要人工操作',
|
||||
},
|
||||
},
|
||||
shippingProcessing: {
|
||||
gateReasons: {
|
||||
generic: '当前步骤需要人工处理',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
@@ -44,6 +77,20 @@ describe('ReviewCurrentProcessingCard', () => {
|
||||
expect(wrapper.find('[data-testid="review-current-processing-retry"]').exists()).toBe(true);
|
||||
});
|
||||
|
||||
it('hides the order-review entry when the user is already in the lifecycle workbench', () => {
|
||||
const wrapper = mount(ReviewCurrentProcessingCard, {
|
||||
props: {
|
||||
stageCode: 'order_review',
|
||||
userStatus: 'waiting_human',
|
||||
primaryAction: { code: 'open_order_review', i18nKey: 'chat.shippingProcessing.action.open_order_review' },
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
|
||||
// 批次中心可以用它进入工作台;工作台当前阶段不能再显示同一个自跳转入口。
|
||||
expect(wrapper.find('[data-testid="review-current-task-primary-action"]').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it('renders Gate label_key for every primary action presentation', () => {
|
||||
const wrapper = mount(ReviewCurrentProcessingCard, {
|
||||
props: {
|
||||
@@ -60,18 +107,113 @@ describe('ReviewCurrentProcessingCard', () => {
|
||||
expect(wrapper.find('[data-testid="review-current-task-primary-action"]').text()).toBe('重新库存匹配');
|
||||
});
|
||||
|
||||
it('renders server-provided recovery actions without duplicating the primary action', async () => {
|
||||
it('does not render save and validate as a current-task action', () => {
|
||||
const wrapper = mount(ReviewCurrentProcessingCard, {
|
||||
props: {
|
||||
stageCode: 'order_review',
|
||||
userStatus: 'waiting_human',
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
|
||||
// 保存订单并校验是底栏唯一动作;未提交校验必须给出明确交接提示,不能显示系统处理中。
|
||||
expect(wrapper.find('[data-testid="review-current-task-primary-action"]').exists()).toBe(false);
|
||||
expect(wrapper.get('[data-testid="review-current-task-next-step-text"]').text()).toBe('保存订单并校验');
|
||||
});
|
||||
|
||||
it('labels an unqueued automatic Gate as waiting for system start', () => {
|
||||
const wrapper = mount(ReviewCurrentProcessingCard, {
|
||||
props: {
|
||||
stageCode: 'fulfillment_prep',
|
||||
userStatus: 'running',
|
||||
gateStatus: 'pending',
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
|
||||
expect(wrapper.get('[data-testid="review-current-task-status"]').text()).toContain('等待系统启动');
|
||||
});
|
||||
|
||||
it('explains external wait without calling it generic system processing', () => {
|
||||
const wrapper = mount(ReviewCurrentProcessingCard, {
|
||||
props: {
|
||||
stageCode: 'upload_complete',
|
||||
userStatus: 'running',
|
||||
gateStatus: 'waiting_external',
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
|
||||
expect(wrapper.get('[data-testid="review-current-task-next-step-text"]').text())
|
||||
.toBe('等待外部系统回执,暂不需要人工操作');
|
||||
});
|
||||
|
||||
it('never exposes an internal action code when its presentation is absent', () => {
|
||||
const wrapper = mount(ReviewCurrentProcessingCard, {
|
||||
props: {
|
||||
stageCode: 'order_review',
|
||||
userStatus: 'waiting_human',
|
||||
primaryAction: { code: 'edit_draft' },
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
|
||||
// 回退显示 edit_draft 会泄漏内部能力码;必须 fail-closed 隐藏。
|
||||
expect(wrapper.find('[data-testid="review-current-task-primary-action"]').exists()).toBe(false);
|
||||
expect(wrapper.text()).not.toContain('edit_draft');
|
||||
});
|
||||
|
||||
it('renders a localized reason instead of an internal blocking code in the next step', () => {
|
||||
const wrapper = mount(ReviewCurrentProcessingCard, {
|
||||
props: {
|
||||
stageCode: 'inventory_matching',
|
||||
userStatus: 'waiting_human',
|
||||
blockingReason: { code: 'inventory_shortage_review_required' },
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
|
||||
const nextStep = wrapper.get('[data-testid="review-current-task-next-step-text"]').text();
|
||||
expect(nextStep).toBe('存在库存缺口,需要人工处理');
|
||||
expect(nextStep).not.toContain('inventory_shortage_review_required');
|
||||
});
|
||||
|
||||
it('hides internal inventory recovery targets while retaining the stable primary action', async () => {
|
||||
const wrapper = mount(ReviewCurrentProcessingCard, {
|
||||
props: {
|
||||
stageCode: 'inventory_matching',
|
||||
userStatus: 'waiting_human',
|
||||
primaryAction: { code: 'retry_inventory_matching', i18nKey: 'retry_inventory_matching' },
|
||||
recoveryActions: [{ code: 'retry_inventory_from_preparation' }],
|
||||
recoveryActions: [{
|
||||
code: 'retry_inventory_from_preparation',
|
||||
i18nKey: 'chat.shippingOrderReview.processGate.actionCodes.retry_inventory_matching',
|
||||
}],
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
|
||||
expect(wrapper.find('[data-testid="review-current-task-recovery-retry_inventory_from_preparation"]').exists()).toBe(true);
|
||||
expect(wrapper.findAll('button').length).toBe(2);
|
||||
expect(wrapper.find('[data-testid="review-current-task-recovery-retry_inventory_from_preparation"]').exists()).toBe(false);
|
||||
expect(wrapper.findAll('button').length).toBe(1);
|
||||
});
|
||||
|
||||
it('emits rematch and RPA refresh as distinct actions for a shortage with an active inventory file', async () => {
|
||||
const wrapper = mount(ReviewCurrentProcessingCard, {
|
||||
props: {
|
||||
stageCode: 'fulfillment_prep',
|
||||
userStatus: 'waiting_human',
|
||||
primaryAction: { code: 'retry_inventory_matching' },
|
||||
recoveryActions: [{ code: 'retry_inventory_preparation' }],
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
|
||||
await wrapper.get('[data-testid="review-current-task-primary-action"]').trigger('click');
|
||||
await wrapper.get('[data-testid="review-current-task-recovery-retry_inventory_preparation"]').trigger('click');
|
||||
|
||||
// 两个稳定 action 码分别进入 Gate API:重匹配不可误触 RPA,重新获取库存才会触发 RPA。
|
||||
expect(wrapper.emitted('action')).toEqual([
|
||||
['retry_inventory_matching', {}],
|
||||
['retry_inventory_preparation', {}],
|
||||
]);
|
||||
});
|
||||
});
|
||||
+81
-24
@@ -8,13 +8,16 @@
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue';
|
||||
import { RefreshCw, Crosshair } from 'lucide-vue-next';
|
||||
import { Bot, RefreshCw, Crosshair } from 'lucide-vue-next';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import type {
|
||||
ShippingProcessingBlockingReason,
|
||||
ShippingProcessingPrimaryAction,
|
||||
} from '@/features/chat/types/shipping.api.types';
|
||||
import { resolveShippingProcessingStageLabel } from '@/features/chat/shipping/shippingProcessingLabels';
|
||||
import { resolveGateReasonLabel } from '@/features/shipping-progress/gateReasonLabel';
|
||||
import { lookupWorkbenchAction, shouldRenderWorkbenchAction } from '@/features/shipping-progress/workbenchActionRegistry';
|
||||
import { inventoryActionLabelKey, isInternalInventoryAction } from '@/features/shipping-progress/actionPresentation';
|
||||
|
||||
const props = defineProps<{
|
||||
stageCode?: string | null;
|
||||
@@ -41,14 +44,14 @@ const props = defineProps<{
|
||||
label_key?: string | null;
|
||||
parameters?: Record<string, unknown>;
|
||||
}>;
|
||||
/** 正式 Gate 原始状态仅用于区分未入队、运行中与外部回执等待;不参与按钮裁决。 */
|
||||
gateStatus?: string | null;
|
||||
|
||||
taskMissing?: boolean;
|
||||
confirmedTaskId?: number | null;
|
||||
showAdminDiagnosis?: boolean;
|
||||
retrying?: boolean;
|
||||
locating?: boolean;
|
||||
/** 题7A:自动次数已耗尽但允许人工继续的源;不为空时按钮语义提示「人工继续」+ tooltip 列名。 */
|
||||
retryExhaustedSources?: string[] | null;
|
||||
/** 仅 UI 展示的 running 文案(如 inventory_preparation 正在跑时主卡按钮 loading 附加信息)。 */
|
||||
automation?: {
|
||||
status?: string | null;
|
||||
@@ -103,12 +106,16 @@ const statusLabel = computed(() => {
|
||||
if (props.taskMissing) {
|
||||
return t('chat.shippingOrderReview.currentProcessing.taskMissing');
|
||||
}
|
||||
if (s === 'running' && String(props.gateStatus || '').trim().toLowerCase() === 'pending') {
|
||||
return t('chat.shippingOrderReview.currentProcessing.waitingStart');
|
||||
}
|
||||
if (!s) return t('chat.shippingOrderReview.currentProcessing.statusIdle');
|
||||
return map[s] ?? t('chat.shippingOrderReview.currentProcessing.statusIdle');
|
||||
});
|
||||
|
||||
/**
|
||||
* 下一步(「下一步」section 的问题/说明文案):优先展示 blocking_reason,否则按 user_status 给系统态文案。
|
||||
* 下一步(「下一步」section 的问题/说明文案):优先展示 blocking_reason 的统一 i18n 映射,
|
||||
* 否则按 user_status 给系统态文案;禁止将后端内部原因码直接展示给用户。
|
||||
*/
|
||||
const nextStepText = computed(() => {
|
||||
const safeMessage = (value: unknown): string => {
|
||||
@@ -136,8 +143,27 @@ const nextStepText = computed(() => {
|
||||
if (i18nKey && te(i18nKey)) {
|
||||
return t(i18nKey);
|
||||
}
|
||||
// i18n 键缺失时回落为 code(不裸露给普通用户,最终 QA 期间应全部补齐)
|
||||
return safeMessage(br.code) || t('chat.shippingOrderReview.currentTask.nextStepUnknown');
|
||||
return resolveGateReasonLabel(br.code, { t, te })
|
||||
|| t('chat.shippingOrderReview.currentTask.nextStepUnknown');
|
||||
}
|
||||
// 建单前订单冻结校验尚未提交时,明确告诉用户下一步是保存并校验。
|
||||
// 保存是底栏唯一的表单提交入口,不升级为右栏 CTA;该分支也兼容历史响应
|
||||
// 仍携带 validate 的情形,避免「待人工」与「无需操作」产生语义矛盾。
|
||||
if (
|
||||
String(props.stageCode || '').trim() === 'order_review'
|
||||
&& !props.blockingReason
|
||||
&& (
|
||||
String(props.primaryAction?.code || '').trim() === 'validate'
|
||||
|| String(props.userStatus || '').trim() === 'waiting_human'
|
||||
)
|
||||
) {
|
||||
return t('chat.shippingOrderReview.saveOrderAndValidate');
|
||||
}
|
||||
if (
|
||||
String(props.userStatus || '').trim() === 'running'
|
||||
&& String(props.gateStatus || '').trim().toLowerCase() === 'waiting_external'
|
||||
) {
|
||||
return t('chat.shippingOrderReview.currentTask.nextStepWaitingExternal');
|
||||
}
|
||||
// 2) 无阻断时,按 user_status 给系统说明文案
|
||||
const s = String(props.userStatus || '').trim() as ReviewCurrentUserStatus | '';
|
||||
@@ -168,9 +194,33 @@ const showNextStep = computed(() => {
|
||||
return !['completed', 'cancelled'].includes(status);
|
||||
});
|
||||
|
||||
/**
|
||||
* 判断当前工作台是否应隐藏后端下发的纯导航动作。
|
||||
* 批次中心可用它打开工作台;进入工作台后必须复用注册表规则,避免当前阶段再次显示
|
||||
* 「进入订单复核」或「编辑正式任务」等自跳转入口。
|
||||
*/
|
||||
function isHiddenWorkbenchNavigationAction(code: string): boolean {
|
||||
const entry = lookupWorkbenchAction(code);
|
||||
return Boolean(entry && !shouldRenderWorkbenchAction(entry, {
|
||||
actionsExecutable: true,
|
||||
surface: 'review',
|
||||
actionCode: code,
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* 当前任务卡只承载正式 Gate 的可执行业务动作。
|
||||
*
|
||||
* 草稿编辑/建草稿是页面能力,保存校验是底栏唯一提交;它们即使出现在历史响应中,
|
||||
* 也不能升级为右栏 CTA,更不能因缺失文案泄漏内部动作码。
|
||||
*/
|
||||
function isNonTaskCapabilityAction(code: string): boolean {
|
||||
return new Set(['edit_draft', 'create_draft', 'validate']).has(code.trim().toLowerCase());
|
||||
}
|
||||
|
||||
/**
|
||||
* 业务动作按钮:后端确认 retryable=true → 主按钮为「重试」;
|
||||
* 否则若 primary_action.code 非 retry → 用 primary_action.code + i18n_key 渲染对应人工动作(进入复核/确认客户等)。
|
||||
* 否则若 primary_action.code 非 retry 且不是工作台内自跳转 → 渲染对应人工动作。
|
||||
*/
|
||||
const showBusinessAction = computed(() => {
|
||||
if (props.loading) return false;
|
||||
@@ -180,21 +230,23 @@ const showBusinessAction = computed(() => {
|
||||
if (props.userStatus === 'running') return false;
|
||||
if (props.retryable) return true;
|
||||
const code = String(props.primaryAction?.code || '').trim();
|
||||
if (isInternalInventoryAction(code)) return false;
|
||||
if (!code) return false;
|
||||
if (isNonTaskCapabilityAction(code)) return false;
|
||||
if (isHiddenWorkbenchNavigationAction(code)) return false;
|
||||
// retry 仅当 retryable=true 时展示(避免按钮闪烁矛盾)
|
||||
if (code === 'retry') return false;
|
||||
return true;
|
||||
});
|
||||
|
||||
const businessActionLabel = computed(() => {
|
||||
if (props.retryable) {
|
||||
if ((props.retryExhaustedSources || []).length > 0) {
|
||||
return t('chat.shippingOrderReview.currentTask.actionRetryWithExhausted');
|
||||
}
|
||||
return t('chat.shippingOrderReview.currentTask.actionRetry');
|
||||
}
|
||||
const code = String(props.primaryAction?.code || '').trim();
|
||||
const inventoryKey = inventoryActionLabelKey(code);
|
||||
if (inventoryKey && te(inventoryKey)) return t(inventoryKey);
|
||||
if (props.retryable) return t('chat.shippingOrderReview.currentTask.actionRetry');
|
||||
const pa = props.primaryAction;
|
||||
if (!pa) return '';
|
||||
if (isNonTaskCapabilityAction(String(pa.code || ''))) return '';
|
||||
// Gate action presentation uses label_key; normalize it at the shared card boundary
|
||||
// so every gate renders its business label instead of exposing the action code.
|
||||
const i18nKey = String(
|
||||
@@ -210,17 +262,11 @@ const businessActionLabel = computed(() => {
|
||||
if (te(legacyKey)) {
|
||||
return t(legacyKey);
|
||||
}
|
||||
return pa.code;
|
||||
// 当前任务按钮没有受控文案时 fail-closed,禁止泄漏内部 action code。
|
||||
return '';
|
||||
});
|
||||
|
||||
/** 题7A:按钮 tooltip(exhausted_sources 列表与文案)。 */
|
||||
const businessActionTitle = computed(() => {
|
||||
const exhausted = Array.isArray(props.retryExhaustedSources) ? props.retryExhaustedSources.filter(Boolean) : [];
|
||||
if (exhausted.length > 0) {
|
||||
return t('chat.shippingOrderReview.currentTask.actionRetryExhaustedTooltip', {
|
||||
sources: exhausted.join(', '),
|
||||
});
|
||||
}
|
||||
const retryingFlag = Boolean(props.retrying);
|
||||
if (retryingFlag) {
|
||||
return t('chat.shippingOrderReview.currentTask.actionRetryRunningTooltip');
|
||||
@@ -229,18 +275,28 @@ const businessActionTitle = computed(() => {
|
||||
});
|
||||
|
||||
const actionIsRetry = computed(() => Boolean(props.retryable) || String(props.primaryAction?.code || '') === 'retry');
|
||||
const actionIsInventoryRpa = computed(() => String(props.primaryAction?.code || '').trim() === 'retry_inventory_preparation');
|
||||
const recoveryActions = computed(() => (props.recoveryActions || []).filter((action) => {
|
||||
const code = String(action.code || '').trim();
|
||||
return code && code !== String(props.primaryAction?.code || '').trim();
|
||||
if (!code || isNonTaskCapabilityAction(code) || isInternalInventoryAction(code)) return false;
|
||||
if (code === String(props.primaryAction?.code || '').trim()) return false;
|
||||
const key = String(
|
||||
action.i18nKey
|
||||
|| action.label_key
|
||||
|| `workspace.shippingNotice.processGate.actionCodes.${code}`,
|
||||
).trim();
|
||||
return Boolean(key && te(key));
|
||||
}));
|
||||
|
||||
function recoveryActionLabel(action: (typeof recoveryActions.value)[number]): string {
|
||||
const inventoryKey = inventoryActionLabelKey(action.code);
|
||||
if (inventoryKey && te(inventoryKey)) return t(inventoryKey);
|
||||
const key = String(
|
||||
action.i18nKey
|
||||
|| action.label_key
|
||||
|| `workspace.shippingNotice.processGate.actionCodes.${action.code}`,
|
||||
).trim();
|
||||
return key && te(key) ? t(key) : action.code;
|
||||
return key && te(key) ? t(key) : '';
|
||||
}
|
||||
|
||||
function handleBusinessActionClick() {
|
||||
@@ -383,8 +439,9 @@ type ReviewCurrentUserStatus =
|
||||
:title="businessActionTitle"
|
||||
@click="handleBusinessActionClick"
|
||||
>
|
||||
<Bot v-if="actionIsInventoryRpa" class="h-3.5 w-3.5" />
|
||||
<RefreshCw
|
||||
v-if="actionIsRetry"
|
||||
v-else-if="actionIsRetry"
|
||||
class="h-3.5 w-3.5"
|
||||
:class="{ 'animate-spin': Boolean(retrying) }"
|
||||
/>
|
||||
|
||||
+15
@@ -246,6 +246,21 @@ describe('ReviewDocumentEvidenceDrawer', () => {
|
||||
expect(wrapper.find('[data-testid="review-evidence-no-bbox"]').text()).toContain('10 EA');
|
||||
});
|
||||
|
||||
it('renders email evidence through the safe HTML preview URL', () => {
|
||||
const wrapper = mountDrawer({
|
||||
emailPreview: {
|
||||
document_id: 9,
|
||||
filename: 'source.eml',
|
||||
text: 'fallback text',
|
||||
render_kind: 'safe_html',
|
||||
preview_url: '/email-preview?token=one-shot',
|
||||
},
|
||||
});
|
||||
expect(wrapper.find('[data-testid="review-email-evidence-html"]').attributes('src'))
|
||||
.toBe('/email-preview?token=one-shot');
|
||||
expect(wrapper.find('[data-testid="review-email-evidence-preview"]').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it('does not render when closed', () => {
|
||||
const wrapper = mountDrawer({ open: false });
|
||||
expect(wrapper.find('[data-testid="review-document-evidence-drawer"]').exists()).toBe(false);
|
||||
|
||||
+14
-1
@@ -44,6 +44,7 @@ const props = defineProps<{
|
||||
docked: boolean;
|
||||
floatSide: 'right' | 'left';
|
||||
src: string;
|
||||
emailPreview?: { document_id: number; filename: string; text: string; render_kind: 'safe_html' | 'text'; preview_url?: string } | null;
|
||||
evidence: ShippingOrderReviewEvidence | null;
|
||||
evidenceList: ShippingOrderReviewEvidence[];
|
||||
fieldLabel?: string;
|
||||
@@ -729,8 +730,20 @@ onBeforeUnmount(() => {
|
||||
</div>
|
||||
|
||||
<div class="grid min-h-0 flex-1 grid-rows-[minmax(0,1fr)_auto]">
|
||||
<iframe
|
||||
v-if="emailPreview?.render_kind === 'safe_html' && emailPreview.preview_url"
|
||||
:src="emailPreview.preview_url"
|
||||
sandbox=""
|
||||
referrerpolicy="no-referrer"
|
||||
:title="fieldLabel || t('chat.shippingOrderReview.evidenceDrawer.title')"
|
||||
class="min-h-0 h-full w-full border-0 bg-white"
|
||||
data-testid="review-email-evidence-html"
|
||||
/>
|
||||
<div v-else-if="emailPreview" class="min-h-0 overflow-auto whitespace-pre-wrap p-4 font-mono text-xs leading-6 text-slate-700 dark:text-slate-200" data-testid="review-email-evidence-preview">
|
||||
{{ emailPreview.text }}
|
||||
</div>
|
||||
<ReviewDocumentPreview
|
||||
v-if="src"
|
||||
v-else-if="src"
|
||||
class="min-h-0"
|
||||
:src="src"
|
||||
:evidence="evidence"
|
||||
|
||||
+80
-2
@@ -20,6 +20,13 @@ const i18n = createI18n({
|
||||
unnamedDocument: '未命名 PDF',
|
||||
documentNavigation: '导航',
|
||||
caseStatuses: { draft: '草稿', unknown: '未知' },
|
||||
lifecycle: {
|
||||
stages: {
|
||||
order_review: '订单复核',
|
||||
fulfillment_prep: '通知准备',
|
||||
upload_complete: '通知完成',
|
||||
},
|
||||
},
|
||||
otNav: {
|
||||
listTitle: '订单列表 · {count}',
|
||||
searchPlaceholder: '搜索',
|
||||
@@ -71,16 +78,66 @@ describe('ReviewDocumentNavigation', () => {
|
||||
expect(wrapper.find('[data-testid="review-document-navigation"]').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it('uses top tabs for 2–4 OTs', () => {
|
||||
const wrapper = mountNav(3, 'tabs');
|
||||
it('uses compact top tabs for 2–4 OTs', () => {
|
||||
const wrapper = mountNav(3);
|
||||
expect(wrapper.find('[data-testid="review-doc-nav-tabs"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="review-doc-nav-list"]').exists()).toBe(false);
|
||||
expect(wrapper.attributes('data-nav-mode')).toBe('tabs');
|
||||
});
|
||||
|
||||
it('uses sidebar list for 5–20 OTs', () => {
|
||||
const wrapper = mountNav(8, 'sidebar');
|
||||
expect(wrapper.find('[data-testid="review-doc-nav-list"]').exists()).toBe(true);
|
||||
expect(wrapper.attributes('data-nav-mode')).toBe('sidebar');
|
||||
expect(wrapper.classes()).toContain('sticky');
|
||||
});
|
||||
|
||||
it('keeps the sidebar collapse rail and the explicitly forced sidebar mode', async () => {
|
||||
const wrapper = mount(ReviewDocumentNavigation, {
|
||||
props: {
|
||||
items: items(8),
|
||||
activeCaseNo: 'C-1',
|
||||
navAriaLabel: 'nav',
|
||||
forceMode: 'sidebar',
|
||||
initiallyCollapsed: true,
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
|
||||
// 关键断言:收起后仍保留文件身份摘要,不能退化成无法识别的纯编号轨。
|
||||
expect(wrapper.attributes('data-nav-mode')).toBe('sidebar');
|
||||
expect(wrapper.get('[data-testid="review-doc-nav-C-2"]').text()).toContain('f2');
|
||||
await wrapper.get('[data-testid="review-doc-nav-collapse"]').trigger('click');
|
||||
expect(wrapper.get('[data-testid="review-doc-nav-C-2"]').text()).toContain('f2.pdf');
|
||||
expect(wrapper.get('[data-testid="review-doc-nav-list"]').attributes('data-collapsed')).toBe('false');
|
||||
});
|
||||
|
||||
it('keeps the file name as the queue row title while projecting PO, lifecycle stage and status', () => {
|
||||
const rows = items(5);
|
||||
rows[1] = {
|
||||
...rows[1],
|
||||
file_name: 'purchase-order-2.pdf',
|
||||
po_number: 'PO-002',
|
||||
lifecycle_stage: 'fulfillment_prep',
|
||||
status: 'processing',
|
||||
};
|
||||
const wrapper = mount(ReviewDocumentNavigation, {
|
||||
props: {
|
||||
items: rows,
|
||||
activeCaseNo: 'C-1',
|
||||
navAriaLabel: 'nav',
|
||||
forceMode: 'sidebar',
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
|
||||
// 文件导航先展示可识别的文件名;PO/阶段/状态仍都来自后端队列 DTO。
|
||||
const queueRow = wrapper.get('[data-testid="review-doc-nav-C-2"]');
|
||||
expect(queueRow.find('.font-medium').text()).toBe('purchase-order-2.pdf');
|
||||
expect(queueRow.text()).toContain('PO-002');
|
||||
expect(queueRow.text()).toContain('通知准备');
|
||||
// 关键断言:队列行内容必须是实际 DOM 子节点,不能被原生 template 隐藏成空白框。
|
||||
expect(queueRow.find('template').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it('shows search for 20+ OTs', () => {
|
||||
@@ -94,4 +151,25 @@ describe('ReviewDocumentNavigation', () => {
|
||||
await wrapper.get('[data-testid="review-doc-nav-C-2"]').trigger('click');
|
||||
expect(wrapper.emitted('select')?.[0]).toEqual(['C-2']);
|
||||
});
|
||||
|
||||
it('keeps backend lifecycle stage visible in tabs and narrow queue', async () => {
|
||||
const rows = items(2);
|
||||
rows[1] = { ...rows[1], lifecycle_stage: 'fulfillment_prep', status: 'processing' };
|
||||
const tabs = mount(ReviewDocumentNavigation, {
|
||||
props: { items: rows, activeCaseNo: 'C-1', navAriaLabel: 'nav', forceMode: 'tabs' },
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
const narrow = mount(ReviewDocumentNavigation, {
|
||||
props: { items: rows, activeCaseNo: 'C-1', navAriaLabel: 'nav', forceMode: 'narrow' },
|
||||
global: { plugins: [i18n] },
|
||||
attachTo: document.body,
|
||||
});
|
||||
|
||||
// 关键断言:文件队列在任何响应式形态都只投影后端已裁决阶段。
|
||||
expect(tabs.get('[data-testid="review-doc-nav-C-2"]').text()).toContain('通知准备');
|
||||
await narrow.get('[data-testid="review-doc-nav-narrow-trigger"]').trigger('click');
|
||||
// 窄屏抽屉通过 Teleport 挂到 body,断言真实可见容器而非组件根节点。
|
||||
expect(document.body.querySelector('[data-testid="review-doc-nav-C-2"]')?.textContent).toContain('通知准备');
|
||||
narrow.unmount();
|
||||
});
|
||||
});
|
||||
+42
-11
@@ -1,8 +1,8 @@
|
||||
<!--
|
||||
features/chat/components/shipping-review/ReviewDocumentNavigation.vue
|
||||
用途:订单处理工作台 OT/PDF 导航(按数量响应式:隐藏 / 顶栏标签 / 左侧列表 / 窄屏抽屉)。
|
||||
用途:订单处理工作台 OT/PDF 导航(按数量响应式:隐藏 / 紧凑标签 / 左侧列表 / 窄屏抽屉)。
|
||||
依赖:vue-i18n、lucide-vue-next。
|
||||
逻辑:1 份隐藏;2–4 顶栏;≥5 左侧列表(可收起);20+ 搜索过滤;窄屏「订单 i/n」抽屉。
|
||||
逻辑:1 份隐藏;桌面端 2–4 紧凑标签、5–20 左侧列表(可收起);20+ 搜索过滤;窄屏「订单 i/n」抽屉。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue';
|
||||
@@ -26,8 +26,12 @@ export type ReviewDocumentNavItem = {
|
||||
po_number?: string | null;
|
||||
customer_name?: string | null;
|
||||
stage_label?: string | null;
|
||||
/** 队列接口下发的生命周期码;仅用于本地化展示,不参与阶段裁决。 */
|
||||
lifecycle_stage?: ReviewLifecycleStageCode | null;
|
||||
};
|
||||
|
||||
type ReviewLifecycleStageCode = 'intake_parse' | 'order_review' | 'fulfillment_prep' | 'upload_complete';
|
||||
|
||||
export type ReviewDocumentNavMode = 'hidden' | 'tabs' | 'sidebar' | 'sidebar_search' | 'narrow';
|
||||
|
||||
const props = defineProps<{
|
||||
@@ -44,6 +48,7 @@ const props = defineProps<{
|
||||
const emit = defineEmits<{
|
||||
select: [caseNo: string];
|
||||
'mode-change': [mode: ReviewDocumentNavMode];
|
||||
'collapse-change': [collapsed: boolean];
|
||||
}>();
|
||||
|
||||
const { t, te } = useI18n();
|
||||
@@ -82,12 +87,14 @@ const mode = computed<ReviewDocumentNavMode>(() => {
|
||||
const count = props.items.length;
|
||||
if (count <= 1) return 'hidden';
|
||||
if (isNarrow.value) return 'narrow';
|
||||
// 多文件先选文件、后查看阶段;2–4 用紧凑标签,5+ 才占用左侧工作列。
|
||||
if (count <= 4) return 'tabs';
|
||||
if (count <= 20) return 'sidebar';
|
||||
return 'sidebar_search';
|
||||
});
|
||||
|
||||
watch(mode, (value) => emit('mode-change', value), { immediate: true });
|
||||
watch(collapsed, (value) => emit('collapse-change', value), { immediate: true });
|
||||
|
||||
const activeIndex = computed(() => {
|
||||
const idx = props.items.findIndex((item) => item.case_no === props.activeCaseNo);
|
||||
@@ -102,6 +109,14 @@ function caseStatusLabel(status: string): string {
|
||||
return te(key) ? t(key) : t('chat.shippingOrderReview.caseStatuses.unknown');
|
||||
}
|
||||
|
||||
/** 后端阶段码只做 i18n 投影;缺失时保留空白,禁止按 Case 状态补造阶段。 */
|
||||
function lifecycleStageLabel(item: ReviewDocumentNavItem): string | null {
|
||||
const code = String(item.lifecycle_stage || '').trim() as ReviewLifecycleStageCode;
|
||||
if (!['intake_parse', 'order_review', 'fulfillment_prep', 'upload_complete'].includes(code)) return null;
|
||||
const key = `chat.shippingOrderReview.lifecycle.stages.${code}`;
|
||||
return te(key) ? t(key) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 导航状态图标语义。
|
||||
*/
|
||||
@@ -168,7 +183,7 @@ function onSelect(caseNo: string) {
|
||||
? 'rounded-xl border border-slate-200 bg-white p-2 shadow-sm dark:border-slate-800 dark:bg-slate-900'
|
||||
: mode === 'narrow'
|
||||
? ''
|
||||
: 'sticky top-3 flex max-h-[calc(100vh-6rem)] w-full shrink-0 flex-col rounded-xl border border-slate-200 bg-white shadow-sm dark:border-slate-800 dark:bg-slate-900 lg:w-64'"
|
||||
: ['sticky top-3 flex max-h-[calc(100vh-6rem)] w-full shrink-0 flex-col rounded-xl border border-slate-200 bg-white shadow-sm transition-[width] duration-200 dark:border-slate-800 dark:bg-slate-900', collapsed ? 'lg:w-20' : 'lg:w-64']"
|
||||
>
|
||||
<!-- 2–4:顶部标签 -->
|
||||
<div
|
||||
@@ -208,11 +223,15 @@ function onSelect(caseNo: string) {
|
||||
class="h-3 w-3 shrink-0 text-slate-400"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
<span class="truncate">{{ item.po_number || item.file_name || t('chat.shippingOrderReview.unnamedDocument') }}</span>
|
||||
<span class="truncate">{{ item.file_name || t('chat.shippingOrderReview.unnamedDocument') }}</span>
|
||||
</span>
|
||||
<span class="truncate text-[10px] text-slate-500 dark:text-slate-400">
|
||||
{{ item.customer_name || caseStatusLabel(item.status) }}
|
||||
<template v-if="item.stage_label"> · {{ item.stage_label }}</template>
|
||||
{{ [
|
||||
item.po_number,
|
||||
lifecycleStageLabel(item),
|
||||
item.stage_label,
|
||||
item.customer_name || caseStatusLabel(item.status),
|
||||
].filter(Boolean).join(' · ') }}
|
||||
</span>
|
||||
</button>
|
||||
</div>
|
||||
@@ -227,6 +246,7 @@ function onSelect(caseNo: string) {
|
||||
type="button"
|
||||
class="rounded p-1 text-muted hover:bg-slate-100 dark:hover:bg-slate-800"
|
||||
data-testid="review-doc-nav-collapse"
|
||||
:aria-label="collapsed ? t('chat.shippingOrderReview.documentNavigation') : t('chat.shippingOrderReview.documentNavigation')"
|
||||
@click="collapsed = !collapsed"
|
||||
>
|
||||
<ChevronLeft
|
||||
@@ -270,6 +290,7 @@ function onSelect(caseNo: string) {
|
||||
<div
|
||||
class="min-h-0 flex-1 overflow-y-auto p-1.5"
|
||||
data-testid="review-doc-nav-list"
|
||||
:data-collapsed="collapsed"
|
||||
>
|
||||
<button
|
||||
v-for="(item, index) in (collapsed ? items : filteredItems)"
|
||||
@@ -287,9 +308,13 @@ function onSelect(caseNo: string) {
|
||||
>
|
||||
<span
|
||||
v-if="collapsed"
|
||||
class="flex h-6 w-6 shrink-0 items-center justify-center rounded-md bg-slate-100 text-[10px] font-semibold dark:bg-slate-800"
|
||||
class="flex h-12 w-full min-w-0 flex-col items-center justify-center rounded-md bg-slate-100 px-1 text-[10px] dark:bg-slate-800"
|
||||
:title="`${index + 1}. ${item.file_name || item.case_no}`"
|
||||
>
|
||||
{{ index + 1 }}
|
||||
<span class="font-semibold">{{ index + 1 }}</span>
|
||||
<span class="mt-0.5 w-full truncate text-center text-[9px] font-medium text-slate-600 dark:text-slate-300">
|
||||
{{ (item.file_name || item.case_no).replace(/\.[^.]+$/, '').slice(0, 7) }}
|
||||
</span>
|
||||
</span>
|
||||
<template v-else>
|
||||
<TriangleAlert
|
||||
@@ -310,10 +335,14 @@ function onSelect(caseNo: string) {
|
||||
/>
|
||||
<span class="min-w-0 flex-1">
|
||||
<span class="block truncate font-medium text-primary">
|
||||
{{ item.po_number || item.file_name || t('chat.shippingOrderReview.unnamedDocument') }}
|
||||
{{ item.file_name || t('chat.shippingOrderReview.unnamedDocument') }}
|
||||
</span>
|
||||
<span class="block truncate text-[10px] text-muted">
|
||||
{{ item.customer_name || caseStatusLabel(item.status) }}
|
||||
{{ [
|
||||
item.po_number,
|
||||
lifecycleStageLabel(item),
|
||||
item.customer_name || caseStatusLabel(item.status),
|
||||
].filter(Boolean).join(' · ') }}
|
||||
</span>
|
||||
</span>
|
||||
</template>
|
||||
@@ -367,7 +396,9 @@ function onSelect(caseNo: string) {
|
||||
@click="onSelect(item.case_no)"
|
||||
>
|
||||
<span class="font-medium">{{ item.file_name || t('chat.shippingOrderReview.unnamedDocument') }}</span>
|
||||
<span class="text-[10px] text-muted">{{ caseStatusLabel(item.status) }}</span>
|
||||
<span class="text-[10px] text-muted">
|
||||
{{ [lifecycleStageLabel(item), caseStatusLabel(item.status)].filter(Boolean).join(' · ') }}
|
||||
</span>
|
||||
</button>
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
@@ -172,7 +172,7 @@ defineExpose({
|
||||
{{ t('chat.shippingNoticeDuplicateMatchTask', { taskNo: primaryMatch.task_no }) }}
|
||||
</div>
|
||||
<div class="mt-0.5 text-muted">
|
||||
{{ t('chat.shippingNoticeDuplicateMatchStatus', { status: primaryMatch.process_status }) }}
|
||||
{{ t('chat.shippingNoticeDuplicateMatchStatus', { status: primaryMatch.lifecycle || 'active' }) }}
|
||||
</div>
|
||||
<div v-if="primaryMatch.matched_fields?.length" class="mt-0.5 text-muted">
|
||||
{{ t('chat.shippingNoticeDuplicateMatchFields', { fields: primaryMatch.matched_fields.join(', ') }) }}
|
||||
|
||||
+87
@@ -0,0 +1,87 @@
|
||||
/**
|
||||
* features/chat/components/shipping-review/ReviewFieldConflictPanel.spec.ts
|
||||
* 用途:验证过期字段冲突卡在服务端返回 404 后会刷新,而不会保留为可再次提交的错误入口。
|
||||
* 依赖:Vitest、Vue Test Utils、Vue I18n、ReviewFieldConflictPanel。
|
||||
* 逻辑:模拟并发刷新已消耗冲突,组件必须通知父工作台重取 Case 最新投影。
|
||||
*/
|
||||
import { mount } from '@vue/test-utils';
|
||||
import { createI18n } from 'vue-i18n';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { BusinessError } from '@/shared/api/client';
|
||||
import ReviewFieldConflictPanel from './ReviewFieldConflictPanel.vue';
|
||||
|
||||
const { resolveFieldConflict } = vi.hoisted(() => ({
|
||||
resolveFieldConflict: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('@/features/chat/api/shipping.api', () => ({
|
||||
resolveWorkspaceShippingOrderReviewFieldConflict: resolveFieldConflict,
|
||||
}));
|
||||
|
||||
const i18n = createI18n({
|
||||
legacy: false,
|
||||
locale: 'zh-CN',
|
||||
messages: {
|
||||
'zh-CN': {
|
||||
chat: { shippingOrderReview: {
|
||||
fieldConflict: {
|
||||
title: '字段冲突 {count} 项', subtitle: '请选择值', focusEvidence: '定位证据',
|
||||
evidenceIssueTitle: '证据待确认({count})', evidenceIssueSubtitle: '请核对证据',
|
||||
scope: { header: '订单头', line: '订单明细' },
|
||||
customValue: '手工值', customPlaceholder: '请输入', submitCustom: '确认手工值',
|
||||
resolveReason: '人工裁决', resolveFailed: '提交失败', resolveSuccess: '已处理',
|
||||
fields: { part_number: '料号' }, reasons: { field_conflict: '字段冲突' },
|
||||
evidenceRole: {}, optionLabel: '候选 {index}', adoptOption: '采用候选值',
|
||||
},
|
||||
resume: { autoCreated: '已自动建单', waitingManualConfirm: '待人工确认' },
|
||||
} },
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
describe('ReviewFieldConflictPanel', () => {
|
||||
it('separates evidence gaps from value conflicts and does not offer a duplicate value decision', () => {
|
||||
const wrapper = mount(ReviewFieldConflictPanel, {
|
||||
props: {
|
||||
caseNo: 'SORC-1', draftVersion: 1, editable: true,
|
||||
conflicts: [],
|
||||
evidenceIssues: [{
|
||||
conflict_key: '-1:reservation_id', field_code: 'reservation_id', line_index: null, scope: 'header',
|
||||
reason: 'evidence_missing', options: [],
|
||||
}],
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
|
||||
expect(wrapper.get('[data-testid="review-evidence-issue-panel"]').text()).toContain('订单头 · reservation_id');
|
||||
expect(wrapper.find('[data-testid="review-field-conflict-custom-toggle"]').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it('refreshes the case when confirming a stale manual value returns conflict-not-found', async () => {
|
||||
resolveFieldConflict.mockRejectedValueOnce(new BusinessError({
|
||||
message: 'Field conflict not found',
|
||||
code: 'SHIPPING.REVIEW_FIELD_CONFLICT_NOT_FOUND',
|
||||
status: 404,
|
||||
}));
|
||||
const wrapper = mount(ReviewFieldConflictPanel, {
|
||||
props: {
|
||||
caseNo: 'SORC-1', draftVersion: 1, editable: true,
|
||||
conflicts: [{
|
||||
conflict_key: '-1:part_number', field_code: 'part_number', line_index: -1,
|
||||
reason: 'field_conflict', options: [],
|
||||
}],
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
|
||||
await wrapper.get('[data-testid="review-field-conflict-custom-toggle"]').trigger('click');
|
||||
await wrapper.get('[data-testid="review-field-conflict-custom-input"]').setValue('PN-001');
|
||||
await wrapper.get('[data-testid="review-field-conflict-custom-submit"]').trigger('click');
|
||||
await vi.waitFor(() => expect(wrapper.emitted('refreshed')).toHaveLength(1));
|
||||
|
||||
// 关键断言:404 代表页面投影过期,父工作台会加载最新 Case 并移除这张卡。
|
||||
expect(resolveFieldConflict).toHaveBeenCalledWith('SORC-1', '-1:part_number', expect.objectContaining({
|
||||
resolution: 'custom', custom_value: 'PN-001', expected_draft_version: 1,
|
||||
}));
|
||||
});
|
||||
});
|
||||
@@ -18,6 +18,7 @@ const props = defineProps<{
|
||||
caseNo: string;
|
||||
draftVersion: number | null | undefined;
|
||||
conflicts: ShippingOrderReviewFieldConflict[] | null | undefined;
|
||||
evidenceIssues?: ShippingOrderReviewFieldConflict[] | null | undefined;
|
||||
editable: boolean;
|
||||
}>();
|
||||
|
||||
@@ -33,6 +34,7 @@ const customOpenKey = ref<string | null>(null);
|
||||
const customValue = ref('');
|
||||
|
||||
const openConflicts = computed(() => props.conflicts || []);
|
||||
const openEvidenceIssues = computed(() => props.evidenceIssues || []);
|
||||
|
||||
/**
|
||||
* 字段编码本地化标签(无文案时回退 field_code)。
|
||||
@@ -50,6 +52,17 @@ function reasonLabel(reason: string): string {
|
||||
return te(key) ? t(key) : reason;
|
||||
}
|
||||
|
||||
/**
|
||||
* 区分订单头与明细字段;同名字段不能被误读成同一份业务值。
|
||||
*/
|
||||
function scopeLabel(scope: string | null | undefined): string {
|
||||
const code = ['header', 'line', 'line_unassigned', 'unscoped'].includes(String(scope || ''))
|
||||
? String(scope)
|
||||
: 'unscoped';
|
||||
const key = `chat.shippingOrderReview.fieldConflict.scope.${code}`;
|
||||
return t(key);
|
||||
}
|
||||
|
||||
/**
|
||||
* 证据角色本地化(主 PDF / 辅助 / 邮件正文)。
|
||||
*/
|
||||
@@ -105,6 +118,12 @@ async function adoptOption(conflict: ShippingOrderReviewFieldConflict, optionInd
|
||||
showReviewResumeOutcome(result.resume_outcome, msg, t, t('chat.shippingOrderReview.fieldConflict.resolveSuccess'));
|
||||
emit('refreshed');
|
||||
} catch (error: unknown) {
|
||||
if (error instanceof BusinessError && error.code === 'SHIPPING.REVIEW_FIELD_CONFLICT_NOT_FOUND') {
|
||||
// 冲突已被其他刷新/裁决消耗:以服务端最新 Case 为准,撤掉当前过期卡片。
|
||||
msg.info(resolveLocalizedErrorMessage(error.code, error.message));
|
||||
emit('refreshed');
|
||||
return;
|
||||
}
|
||||
const message = error instanceof BusinessError
|
||||
? resolveLocalizedErrorMessage(error.code, error.message)
|
||||
: (error instanceof Error ? error.message : t('chat.shippingOrderReview.fieldConflict.resolveFailed'));
|
||||
@@ -146,6 +165,12 @@ async function submitCustom(conflict: ShippingOrderReviewFieldConflict) {
|
||||
showReviewResumeOutcome(result.resume_outcome, msg, t, t('chat.shippingOrderReview.fieldConflict.resolveSuccess'));
|
||||
emit('refreshed');
|
||||
} catch (error: unknown) {
|
||||
if (error instanceof BusinessError && error.code === 'SHIPPING.REVIEW_FIELD_CONFLICT_NOT_FOUND') {
|
||||
// 与采用候选值保持同一 stale-data 恢复路径,禁止把已解决冲突留在页面上。
|
||||
msg.info(resolveLocalizedErrorMessage(error.code, error.message));
|
||||
emit('refreshed');
|
||||
return;
|
||||
}
|
||||
const message = error instanceof BusinessError
|
||||
? resolveLocalizedErrorMessage(error.code, error.message)
|
||||
: (error instanceof Error ? error.message : t('chat.shippingOrderReview.fieldConflict.resolveFailed'));
|
||||
@@ -158,11 +183,11 @@ async function submitCustom(conflict: ShippingOrderReviewFieldConflict) {
|
||||
|
||||
<template>
|
||||
<section
|
||||
v-if="openConflicts.length"
|
||||
v-if="openConflicts.length || openEvidenceIssues.length"
|
||||
class="rounded-xl border border-rose-200 bg-rose-50/70 p-3 shadow-sm dark:border-rose-900 dark:bg-rose-950/40"
|
||||
data-testid="review-field-conflict-panel"
|
||||
>
|
||||
<header class="flex flex-wrap items-start justify-between gap-2">
|
||||
<header v-if="openConflicts.length" class="flex flex-wrap items-start justify-between gap-2">
|
||||
<div>
|
||||
<h2 class="text-sm font-semibold text-rose-950 dark:text-rose-50">
|
||||
{{ t('chat.shippingOrderReview.fieldConflict.title', { count: openConflicts.length }) }}
|
||||
@@ -264,5 +289,38 @@ async function submitCustom(conflict: ShippingOrderReviewFieldConflict) {
|
||||
</div>
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
<div
|
||||
v-if="openEvidenceIssues.length"
|
||||
class="mt-3 rounded-lg border border-amber-200 bg-amber-50/80 p-2.5 dark:border-amber-900 dark:bg-amber-950/30"
|
||||
data-testid="review-evidence-issue-panel"
|
||||
>
|
||||
<h2 class="text-sm font-semibold text-amber-950 dark:text-amber-50">
|
||||
{{ t('chat.shippingOrderReview.fieldConflict.evidenceIssueTitle', { count: openEvidenceIssues.length }) }}
|
||||
</h2>
|
||||
<p class="mt-0.5 text-xs text-amber-800 dark:text-amber-200">
|
||||
{{ t('chat.shippingOrderReview.fieldConflict.evidenceIssueSubtitle') }}
|
||||
</p>
|
||||
<ul class="mt-2 space-y-1.5">
|
||||
<li
|
||||
v-for="issue in openEvidenceIssues"
|
||||
:key="`${issue.conflict_key}-${issue.reason}`"
|
||||
class="flex flex-wrap items-center justify-between gap-2 rounded border border-amber-200 bg-white/95 px-2.5 py-2 text-xs dark:border-amber-900 dark:bg-slate-900"
|
||||
>
|
||||
<span class="text-amber-950 dark:text-amber-50">
|
||||
<span class="text-muted">{{ scopeLabel(issue.scope) }} · </span>
|
||||
<span class="font-mono">{{ fieldLabel(issue.field_code) }}</span>
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
class="text-[11px] text-primary underline-offset-2 hover:underline"
|
||||
data-testid="review-evidence-issue-focus"
|
||||
@click="onFocus(issue)"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.fieldConflict.focusEvidence') }}
|
||||
</button>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
@@ -0,0 +1,150 @@
|
||||
/**
|
||||
* features/chat/components/shipping-review/ReviewIntakeParsePanel.spec.ts
|
||||
* 用途:锁定接收解析工作面只展示当前 Case 已授权的邮件正文与附件预览。
|
||||
* 依赖:Vitest、Vue Test Utils、vue-i18n、ReviewIntakeParsePanel。
|
||||
* 逻辑:PDF 才允许嵌入预览;非 PDF 明确降级;所有处置仅向父级发出意图。
|
||||
*/
|
||||
import { mount } from '@vue/test-utils';
|
||||
import { createI18n } from 'vue-i18n';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import ReviewIntakeParsePanel from './ReviewIntakeParsePanel.vue';
|
||||
import type { ShippingOrderReviewIntakeParseContext } from '@/features/chat/types/shipping.api.types';
|
||||
|
||||
const i18n = createI18n({
|
||||
legacy: false,
|
||||
locale: 'zh-CN',
|
||||
messages: {
|
||||
'zh-CN': {
|
||||
chat: {
|
||||
shippingOrderReview: {
|
||||
lifecycle: {
|
||||
intakeParse: {
|
||||
title: '接收解析',
|
||||
email: '邮件正文',
|
||||
noEmail: '无邮件上下文',
|
||||
attachment: '当前附件',
|
||||
fileName: '文件名',
|
||||
fileType: '文件类型',
|
||||
preview: '附件预览',
|
||||
loadPreview: '加载附件预览',
|
||||
previewUnsupported: '当前附件不支持预览',
|
||||
loadFailed: '接收解析上下文加载失败',
|
||||
retry: '重试',
|
||||
loading: '正在加载接收解析上下文',
|
||||
},
|
||||
},
|
||||
markNonOrder: '标记为非订单',
|
||||
markQualityIssue: '文件质量异常',
|
||||
reparse: '重新识别此 PDF',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const emailPdfContext: ShippingOrderReviewIntakeParseContext = {
|
||||
case_no: 'CASE-1',
|
||||
attachment: {
|
||||
document_id: 11,
|
||||
filename: 'current.pdf',
|
||||
mime_type: 'application/pdf',
|
||||
preview_kind: 'pdf',
|
||||
},
|
||||
email: {
|
||||
document_id: 7,
|
||||
filename: 'source.eml',
|
||||
render_kind: 'text',
|
||||
text: 'approved body text',
|
||||
},
|
||||
};
|
||||
|
||||
const unsupportedContext: ShippingOrderReviewIntakeParseContext = {
|
||||
...emailPdfContext,
|
||||
attachment: {
|
||||
document_id: 12,
|
||||
filename: 'source.xlsx',
|
||||
mime_type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
preview_kind: 'unsupported',
|
||||
},
|
||||
email: null,
|
||||
};
|
||||
|
||||
function mountPanel(props: Record<string, unknown>) {
|
||||
return mount(ReviewIntakeParsePanel, {
|
||||
props: {
|
||||
loading: false,
|
||||
loadFailed: false,
|
||||
previewUrl: null,
|
||||
previewLoading: false,
|
||||
...props,
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
}
|
||||
|
||||
describe('ReviewIntakeParsePanel', () => {
|
||||
it('renders EML text and only the selected attachment preview', () => {
|
||||
const wrapper = mountPanel({ context: emailPdfContext, previewUrl: 'blob:pdf' });
|
||||
|
||||
// 关键断言:邮件正文与当前附件来自同一个受控 Case context,PDF 才嵌入预览。
|
||||
expect(wrapper.get('[data-testid="intake-parse-email-body"]').text()).toContain('approved body text');
|
||||
expect(wrapper.get('[data-testid="intake-parse-attachment-preview"] iframe').attributes('src')).toBe('blob:pdf');
|
||||
});
|
||||
|
||||
it('uses a compact attachment heading without duplicate metadata', () => {
|
||||
const wrapper = mountPanel({ context: emailPdfContext, previewUrl: 'blob:pdf' });
|
||||
|
||||
// 关键断言:文件名与当前附件合并展示,MIME 类型不再占用预览空间。
|
||||
expect(wrapper.get('[data-testid="intake-parse-attachment-heading"]').text()).toContain('当前附件');
|
||||
expect(wrapper.get('[data-testid="intake-parse-attachment-heading"]').text()).toContain('current.pdf');
|
||||
expect(wrapper.text()).not.toContain('文件类型');
|
||||
});
|
||||
|
||||
it('loads isolated EML HTML from the backend preview URL inside a sandboxed iframe', () => {
|
||||
const wrapper = mountPanel({
|
||||
context: {
|
||||
...emailPdfContext,
|
||||
email: {
|
||||
...emailPdfContext.email!,
|
||||
render_kind: 'safe_html',
|
||||
preview_url: '/api/workspace/shipping-notice/order-review-cases/CASE-1/email-preview?preview_token=single-use',
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
// 关键断言:HTML 不得通过 srcdoc 注入工作台 DOM,必须由受控 URL 在无脚本 iframe 中读取。
|
||||
const frame = wrapper.get('[data-testid="intake-parse-email-html"]');
|
||||
expect(frame.attributes('sandbox')).toBeDefined();
|
||||
expect(frame.attributes('src')).toContain('preview_token=single-use');
|
||||
expect(frame.attributes('srcdoc')).toBeUndefined();
|
||||
expect(wrapper.find('[data-testid="intake-parse-email-body"]').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it('does not render a PDF frame for an unsupported attachment', () => {
|
||||
const wrapper = mountPanel({ context: unsupportedContext });
|
||||
|
||||
// 关键断言:非 PDF 不得退化为 iframe,必须明确告知不可预览。
|
||||
expect(wrapper.find('[data-testid="intake-parse-attachment-preview"]').exists()).toBe(false);
|
||||
expect(wrapper.get('[data-testid="intake-parse-preview-unsupported"]').exists()).toBe(true);
|
||||
expect(wrapper.get('[data-testid="intake-parse-no-email"]').text()).toContain('无邮件上下文');
|
||||
});
|
||||
|
||||
it('does not render parse disposition controls inside the scrolling intake panel', () => {
|
||||
const wrapper = mountPanel({
|
||||
context: emailPdfContext,
|
||||
});
|
||||
|
||||
// 关键断言:按钮由父级固定底栏统一承载,面板滚动时不得随内容离开视口。
|
||||
expect(wrapper.find('[data-testid="intake-parse-disposition-actions"]').exists()).toBe(false);
|
||||
expect(wrapper.find('[data-testid="intake-parse-mark-non-order"]').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it('does not render deprecated parse disposition controls inside the scrolling panel', () => {
|
||||
const wrapper = mountPanel({
|
||||
context: emailPdfContext,
|
||||
});
|
||||
|
||||
// 关键断言:处置由固定底栏承载,滚动内容区不得遗留重复入口。
|
||||
expect(wrapper.find('[data-testid="intake-parse-reparse"]').exists()).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,146 @@
|
||||
<!--
|
||||
features/chat/components/shipping-review/ReviewIntakeParsePanel.vue
|
||||
用途:在接收解析阶段展示当前 Case 已授权的邮件正文、当前附件及安全预览。
|
||||
依赖:vue、vue-i18n、ShippingOrderReviewIntakeParseContext。
|
||||
逻辑:只消费父级按 Case 获取的受控上下文;仅 PDF 可请求/渲染 iframe;处置操作只 emit,
|
||||
由父页沿用既有确认弹窗和 Case 命令。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { watch } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import type { ShippingOrderReviewIntakeParseContext } from '@/features/chat/types/shipping.api.types';
|
||||
|
||||
const props = defineProps<{
|
||||
context: ShippingOrderReviewIntakeParseContext | null;
|
||||
loading: boolean;
|
||||
loadFailed: boolean;
|
||||
previewUrl: string | null;
|
||||
previewLoading: boolean;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
'retry-context': [];
|
||||
'load-preview': [];
|
||||
}>();
|
||||
|
||||
const { t } = useI18n();
|
||||
|
||||
/**
|
||||
* 当前附件为 PDF 且尚无受控 Blob 时,通知父级使用当前 Case 加载预览。
|
||||
* 仅 Case context 改变时触发,禁止对不受支持文件发起预览请求。
|
||||
*/
|
||||
watch(
|
||||
() => props.context,
|
||||
(context) => {
|
||||
if (context?.attachment.preview_kind === 'pdf' && !props.previewUrl) {
|
||||
emit('load-preview');
|
||||
}
|
||||
},
|
||||
{ immediate: true },
|
||||
);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section
|
||||
class="space-y-4"
|
||||
data-testid="intake-parse-panel"
|
||||
>
|
||||
<div
|
||||
v-if="loading"
|
||||
class="rounded-xl border border-dashed border-slate-300 bg-slate-50 p-4 text-sm text-slate-600 dark:border-slate-700 dark:bg-slate-900/40 dark:text-slate-300"
|
||||
data-testid="intake-parse-loading"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.lifecycle.intakeParse.loading') }}
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-else-if="loadFailed"
|
||||
class="rounded-xl border border-rose-200 bg-rose-50 p-4 text-sm text-rose-900 dark:border-rose-900 dark:bg-rose-950/40 dark:text-rose-100"
|
||||
data-testid="intake-parse-load-failed"
|
||||
>
|
||||
<p>{{ t('chat.shippingOrderReview.lifecycle.intakeParse.loadFailed') }}</p>
|
||||
<button
|
||||
type="button"
|
||||
class="mt-3 rounded border border-rose-300 px-2.5 py-1 text-xs hover:bg-rose-100 dark:border-rose-800 dark:hover:bg-rose-950"
|
||||
data-testid="intake-parse-retry-context"
|
||||
@click="emit('retry-context')"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.lifecycle.intakeParse.retry') }}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<template v-else-if="context">
|
||||
<section class="rounded-xl border border-slate-200 bg-white p-4 shadow-sm dark:border-slate-800 dark:bg-slate-900">
|
||||
<h2 class="text-sm font-semibold">{{ t('chat.shippingOrderReview.lifecycle.intakeParse.email') }}</h2>
|
||||
<template v-if="context.email">
|
||||
<p class="mt-1 text-xs text-slate-500">{{ context.email.filename }}</p>
|
||||
<iframe
|
||||
v-if="context.email.render_kind === 'safe_html' && context.email.preview_url"
|
||||
:src="context.email.preview_url"
|
||||
sandbox=""
|
||||
referrerpolicy="no-referrer"
|
||||
:title="t('chat.shippingOrderReview.lifecycle.intakeParse.emailPreviewTitle')"
|
||||
class="mt-3 h-72 w-full rounded border border-slate-200 bg-white dark:border-slate-700 dark:bg-slate-950"
|
||||
data-testid="intake-parse-email-html"
|
||||
/>
|
||||
<pre
|
||||
v-else
|
||||
class="mt-3 max-h-72 overflow-auto whitespace-pre-wrap break-words rounded bg-slate-50 p-3 text-xs text-slate-700 dark:bg-slate-950/50 dark:text-slate-200"
|
||||
data-testid="intake-parse-email-body"
|
||||
>{{ context.email.text }}</pre>
|
||||
</template>
|
||||
<p
|
||||
v-else
|
||||
class="mt-2 text-sm text-slate-500"
|
||||
data-testid="intake-parse-no-email"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.lifecycle.intakeParse.noEmail') }}
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section class="rounded-xl border border-slate-200 bg-white p-4 shadow-sm dark:border-slate-800 dark:bg-slate-900">
|
||||
<h2 class="text-sm font-semibold" data-testid="intake-parse-attachment-heading">
|
||||
{{ t('chat.shippingOrderReview.lifecycle.intakeParse.attachment') }} ·
|
||||
<span class="font-normal text-slate-500 dark:text-slate-400">{{ context.attachment.filename }}</span>
|
||||
</h2>
|
||||
|
||||
<div
|
||||
v-if="context.attachment.preview_kind === 'pdf'"
|
||||
class="mt-3"
|
||||
data-testid="intake-parse-attachment-preview"
|
||||
>
|
||||
<p
|
||||
v-if="previewLoading"
|
||||
class="mt-2 text-sm text-slate-500"
|
||||
data-testid="intake-parse-preview-loading"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.lifecycle.intakeParse.previewLoading') }}
|
||||
</p>
|
||||
<iframe
|
||||
v-else-if="previewUrl"
|
||||
:src="previewUrl"
|
||||
:title="context.attachment.filename"
|
||||
class="mt-2 h-[32rem] w-full rounded border border-slate-200 dark:border-slate-700"
|
||||
/>
|
||||
<button
|
||||
v-else
|
||||
type="button"
|
||||
class="mt-2 rounded border border-slate-300 px-2.5 py-1 text-xs hover:bg-slate-50 dark:border-slate-700 dark:hover:bg-slate-800"
|
||||
data-testid="intake-parse-load-preview"
|
||||
@click="emit('load-preview')"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.lifecycle.intakeParse.loadPreview') }}
|
||||
</button>
|
||||
</div>
|
||||
<p
|
||||
v-else
|
||||
class="mt-4 rounded bg-slate-50 p-3 text-sm text-slate-500 dark:bg-slate-950/50"
|
||||
data-testid="intake-parse-preview-unsupported"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.lifecycle.intakeParse.previewUnsupported') }}
|
||||
</p>
|
||||
</section>
|
||||
|
||||
</template>
|
||||
</section>
|
||||
</template>
|
||||
+6
-13
@@ -1,9 +1,9 @@
|
||||
/**
|
||||
* features/chat/components/shipping-review/ReviewInventoryCandidatesPanel.spec.ts
|
||||
* 用途:验证库存路由面板在服务端刷新后重置本地表单,并展示规则码/源编码以满足可追溯。
|
||||
* 用途:验证库存路由面板展示服务端规则结果、规则码与源编码以满足可追溯。
|
||||
* 依赖:Vitest、Vue Test Utils、vue-i18n、chat 文案。
|
||||
* 逻辑:构造带技术编码的行投影;断言显示名+编码与命中规则;两列标签卡可扫描;
|
||||
* 变更候选后本地勾选被重置。
|
||||
* 自动重算意图只透传 line_key,不允许出现人工候选表单。
|
||||
*/
|
||||
import { flushPromises, mount } from '@vue/test-utils';
|
||||
import { createI18n } from 'vue-i18n';
|
||||
@@ -31,7 +31,6 @@ function line(
|
||||
rule_suggestion_source_codes: ['DSV360_AWSDU'],
|
||||
matched_rules: [{ rule_code: 'ROUTE_HINT_AWSSG', version: 1 }],
|
||||
rule_versions: [{ rule_code: 'INVENTORY_RULE_18', version: 18 }],
|
||||
manual_reason: 'initial reason',
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
@@ -82,24 +81,19 @@ describe('ReviewInventoryCandidatesPanel', () => {
|
||||
expect(wrapper.text()).toContain('新加坡仓');
|
||||
});
|
||||
|
||||
it('resets local form when server candidates change for the same line_key', async () => {
|
||||
it('renders refreshed rule candidates without exposing manual selection inputs', async () => {
|
||||
const wrapper = mount(ReviewInventoryCandidatesPanel, {
|
||||
props: {
|
||||
lines: [line({ candidate_inventory_source_codes: ['DSV360_AWSDU'], manual_reason: 'old' })],
|
||||
lines: [line({ candidate_inventory_source_codes: ['DSV360_AWSDU'] })],
|
||||
sourceLabels: { DSV360_AWSDU: '杜塞尔多夫仓', DSV360_AWSBI: '伯明翰仓' },
|
||||
editable: true,
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
|
||||
const textarea = wrapper.get('textarea');
|
||||
await textarea.setValue('user typed reason');
|
||||
expect((textarea.element as HTMLTextAreaElement).value).toBe('user typed reason');
|
||||
|
||||
await wrapper.setProps({
|
||||
lines: [line({
|
||||
candidate_inventory_source_codes: ['DSV360_AWSBI'],
|
||||
manual_reason: 'server refreshed',
|
||||
raw_rule_source_codes: ['DSV360_AWSBI'],
|
||||
unavailable_source_codes: [],
|
||||
rule_suggestion_source_codes: ['DSV360_AWSBI'],
|
||||
@@ -107,11 +101,10 @@ describe('ReviewInventoryCandidatesPanel', () => {
|
||||
})],
|
||||
});
|
||||
await flushPromises();
|
||||
|
||||
const refreshed = wrapper.get('textarea');
|
||||
expect((refreshed.element as HTMLTextAreaElement).value).toBe('server refreshed');
|
||||
expect(wrapper.text()).toContain('伯明翰仓');
|
||||
expect(wrapper.text()).toContain('DSV360_AWSBI');
|
||||
expect(wrapper.text()).toContain('ROUTE_HINT_AWSBI');
|
||||
expect(wrapper.find('textarea').exists()).toBe(false);
|
||||
expect(wrapper.find('input[type="checkbox"]').exists()).toBe(false);
|
||||
});
|
||||
});
|
||||
+3
-194
@@ -1,20 +1,16 @@
|
||||
<!--
|
||||
features/chat/components/shipping-review/ReviewInventoryCandidatesPanel.vue
|
||||
用途:库存路由恢复面板——展示规则建议/不可用源,支持 reroute、采纳建议、保留人工与多选提交。
|
||||
用途:库存路由恢复面板——展示发布规则结果、不可用源并支持自动重算。
|
||||
依赖:vue-i18n、ShippingOrderReviewBuildEligibilityLineProjection 类型。
|
||||
逻辑:接收 recovery / suggestion_pending 行;规则候选优先,零候选回退已启用源;
|
||||
服务端行指纹变化时重置本地表单;业务名与等宽 source_code 始终可见;
|
||||
原始/不可用/建议候选用两列标签卡降低密度;emit 由 composable 写 API。
|
||||
逻辑:只展示服务端规则裁决;服务端行指纹变化时刷新显示;业务名与等宽 source_code 始终可见;
|
||||
原始/不可用/有效候选用两列标签卡降低密度;仅 emit 自动重算意图。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { reactive, watch } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import type { ShippingOrderReviewBuildEligibilityLineProjection } from '@/features/chat/types/shipping.api.types';
|
||||
|
||||
const props = defineProps<{
|
||||
lines: ShippingOrderReviewBuildEligibilityLineProjection[];
|
||||
/** 已启用库存源;规则零候选时作为可选列表 */
|
||||
enabledSourceCodes?: string[];
|
||||
/** 库存源编码 → 业务显示名;提交仍使用编码 */
|
||||
sourceLabels?: Record<string, string>;
|
||||
editable?: boolean;
|
||||
@@ -22,30 +18,11 @@ const props = defineProps<{
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
(e: 'submit', payload: { lineKey: string; sourceCodes: string[]; reason: string }): void;
|
||||
(e: 'reroute', lineKey?: string): void;
|
||||
(e: 'adopt', payload: { lineKey: string; reason?: string }): void;
|
||||
(e: 'keep', payload: { lineKey: string; reason?: string }): void;
|
||||
}>();
|
||||
|
||||
const { t, te } = useI18n();
|
||||
|
||||
/** 每行本地表单状态:已选候选与原因。 */
|
||||
const formState = reactive<Record<string, { selected: string[]; reason: string }>>({});
|
||||
|
||||
/**
|
||||
* 行级可选源:规则候选优先,否则回退已启用库存源。
|
||||
*/
|
||||
function selectableCodes(line: ShippingOrderReviewBuildEligibilityLineProjection): string[] {
|
||||
const candidates = (line.candidate_inventory_source_codes || [])
|
||||
.map((code) => String(code || '').trim().toUpperCase())
|
||||
.filter(Boolean);
|
||||
if (candidates.length) return candidates;
|
||||
return (props.enabledSourceCodes || [])
|
||||
.map((code) => String(code || '').trim().toUpperCase())
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
/**
|
||||
* 规则建议可用源编码。
|
||||
*/
|
||||
@@ -56,63 +33,6 @@ function ruleSuggestionCodes(line: ShippingOrderReviewBuildEligibilityLineProjec
|
||||
|| [];
|
||||
}
|
||||
|
||||
/**
|
||||
* 服务端行投影指纹;变化时用于重置本地表单,避免提交过期候选/原因。
|
||||
*/
|
||||
function lineServerFingerprint(line: ShippingOrderReviewBuildEligibilityLineProjection): string {
|
||||
return JSON.stringify({
|
||||
line_key: String(line.line_key || line.line_index || ''),
|
||||
candidates: (line.candidate_inventory_source_codes || []).map(String),
|
||||
reason: String(line.manual_reason || ''),
|
||||
suggestion_pending: Boolean(line.suggestion_pending),
|
||||
rule: ruleSuggestionCodes(line).map(String),
|
||||
unavailable: (line.unavailable_source_codes || []).map(String),
|
||||
raw: (line.raw_rule_source_codes || []).map(String),
|
||||
block_reason: String(line.block_reason || ''),
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 清空本地表单缓存(下次 getForm 按服务端投影重新初始化)。
|
||||
*/
|
||||
function resetFormState() {
|
||||
for (const key of Object.keys(formState)) {
|
||||
delete formState[key];
|
||||
}
|
||||
}
|
||||
|
||||
watch(
|
||||
() => (props.lines || []).map(lineServerFingerprint).join('\n'),
|
||||
() => {
|
||||
resetFormState();
|
||||
},
|
||||
);
|
||||
|
||||
/**
|
||||
* 获取或初始化某行的表单状态。
|
||||
*/
|
||||
function getForm(line: ShippingOrderReviewBuildEligibilityLineProjection) {
|
||||
const key = String(line.line_key || (line.line_index ?? ''));
|
||||
if (!formState[key]) {
|
||||
const ruleCandidates = (line.candidate_inventory_source_codes || []).map(String);
|
||||
formState[key] = {
|
||||
selected: [...ruleCandidates],
|
||||
reason: String(line.manual_reason || ''),
|
||||
};
|
||||
}
|
||||
return formState[key];
|
||||
}
|
||||
|
||||
/**
|
||||
* 切换候选编码勾选状态。
|
||||
*/
|
||||
function toggleCode(line: ShippingOrderReviewBuildEligibilityLineProjection, code: string) {
|
||||
const form = getForm(line);
|
||||
const index = form.selected.indexOf(code);
|
||||
if (index >= 0) form.selected.splice(index, 1);
|
||||
else form.selected.push(code);
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析阻断原因展示文案。
|
||||
*/
|
||||
@@ -160,20 +80,6 @@ function unavailableReasonLabel(line: ShippingOrderReviewBuildEligibilityLinePro
|
||||
return te(key) ? t(key) : t('chat.shippingOrderReview.inventoryRouting.unavailableReasonUnknown');
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验并提交指定行的人工候选选择。
|
||||
*/
|
||||
function submitLine(line: ShippingOrderReviewBuildEligibilityLineProjection) {
|
||||
const lineKey = String(line.line_key || '').trim();
|
||||
if (!lineKey) return;
|
||||
const form = getForm(line);
|
||||
emit('submit', {
|
||||
lineKey,
|
||||
sourceCodes: [...form.selected],
|
||||
reason: form.reason.trim(),
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 触发行级重新匹配路由。
|
||||
*/
|
||||
@@ -182,25 +88,6 @@ function rerouteLine(line: ShippingOrderReviewBuildEligibilityLineProjection) {
|
||||
emit('reroute', lineKey || undefined);
|
||||
}
|
||||
|
||||
/**
|
||||
* 采纳待决规则建议。
|
||||
*/
|
||||
function adoptLine(line: ShippingOrderReviewBuildEligibilityLineProjection) {
|
||||
const lineKey = String(line.line_key || '').trim();
|
||||
if (!lineKey) return;
|
||||
const reason = getForm(line).reason.trim();
|
||||
emit('adopt', { lineKey, ...(reason ? { reason } : {}) });
|
||||
}
|
||||
|
||||
/**
|
||||
* 保留当前人工路由结果。
|
||||
*/
|
||||
function keepLine(line: ShippingOrderReviewBuildEligibilityLineProjection) {
|
||||
const lineKey = String(line.line_key || '').trim();
|
||||
if (!lineKey) return;
|
||||
const reason = getForm(line).reason.trim();
|
||||
emit('keep', { lineKey, ...(reason ? { reason } : {}) });
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -313,55 +200,6 @@ function keepLine(line: ShippingOrderReviewBuildEligibilityLineProjection) {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p
|
||||
v-if="line.suggestion_pending"
|
||||
class="mt-2 rounded border border-amber-200 bg-amber-50 px-2 py-1 text-xs text-amber-900 dark:border-amber-900 dark:bg-amber-950/40 dark:text-amber-100"
|
||||
data-testid="review-inventory-suggestion-pending"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.inventoryRouting.suggestionPending') }}
|
||||
</p>
|
||||
|
||||
<div v-if="selectableCodes(line).length" class="mt-3">
|
||||
<div class="text-xs font-medium text-slate-600 dark:text-slate-300">
|
||||
{{
|
||||
(line.candidate_inventory_source_codes || []).length
|
||||
? t('chat.shippingOrderReview.inventoryCandidates.selectSources')
|
||||
: t('chat.shippingOrderReview.inventoryCandidates.selectEnabledSources')
|
||||
}}
|
||||
</div>
|
||||
<div class="mt-2 flex flex-wrap gap-2">
|
||||
<label
|
||||
v-for="code in selectableCodes(line)"
|
||||
:key="code"
|
||||
class="inline-flex cursor-pointer items-center gap-1.5 rounded border border-slate-200 px-2 py-1 text-xs dark:border-slate-600"
|
||||
>
|
||||
<input
|
||||
type="checkbox"
|
||||
:checked="getForm(line).selected.includes(code)"
|
||||
:disabled="!editable || saving"
|
||||
@change="toggleCode(line, code)"
|
||||
>
|
||||
<span>{{ sourceBusinessName(code) }}</span>
|
||||
<span class="font-mono text-[11px] text-slate-500">{{ sourceCodeLabel(code) }}</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
<p v-else class="mt-2 text-xs text-rose-600 dark:text-rose-300">
|
||||
{{ t('chat.shippingOrderReview.inventoryCandidates.noEnabledSources') }}
|
||||
</p>
|
||||
|
||||
<label class="mt-3 block text-xs font-medium text-slate-600 dark:text-slate-300">
|
||||
{{ t('chat.shippingOrderReview.inventoryCandidates.reasonLabel') }}
|
||||
<textarea
|
||||
:value="getForm(line).reason"
|
||||
:disabled="!editable || saving"
|
||||
rows="2"
|
||||
class="mt-1 w-full rounded-md border border-slate-300 bg-white px-2 py-1.5 text-xs dark:border-slate-600 dark:bg-slate-950"
|
||||
:placeholder="t('chat.shippingOrderReview.inventoryCandidates.reasonPlaceholder')"
|
||||
@input="getForm(line).reason = ($event.target as HTMLTextAreaElement).value"
|
||||
/>
|
||||
</label>
|
||||
|
||||
<div class="mt-3 flex flex-wrap items-center justify-end gap-2">
|
||||
<button
|
||||
type="button"
|
||||
@@ -372,35 +210,6 @@ function keepLine(line: ShippingOrderReviewBuildEligibilityLineProjection) {
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.inventoryRouting.reroute') }}
|
||||
</button>
|
||||
<template v-if="line.suggestion_pending">
|
||||
<button
|
||||
type="button"
|
||||
class="rounded border border-amber-300 bg-amber-50 px-3 py-1.5 text-xs text-amber-900 disabled:opacity-50 dark:border-amber-800 dark:bg-amber-950/50 dark:text-amber-100"
|
||||
data-testid="review-inventory-routing-adopt"
|
||||
:disabled="!editable || saving"
|
||||
@click="adoptLine(line)"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.inventoryRouting.adoptSuggestion') }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded border border-slate-300 bg-white px-3 py-1.5 text-xs text-slate-700 disabled:opacity-50 dark:border-slate-600 dark:bg-slate-950 dark:text-slate-200"
|
||||
data-testid="review-inventory-routing-keep"
|
||||
:disabled="!editable || saving"
|
||||
@click="keepLine(line)"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.inventoryRouting.keepManual') }}
|
||||
</button>
|
||||
</template>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded bg-sky-600 px-3 py-1.5 text-xs text-white disabled:opacity-50"
|
||||
data-testid="review-inventory-candidates-submit"
|
||||
:disabled="!editable || saving || !getForm(line).selected.length || !getForm(line).reason.trim()"
|
||||
@click="submitLine(line)"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.inventoryCandidates.submit') }}
|
||||
</button>
|
||||
</div>
|
||||
</article>
|
||||
</section>
|
||||
|
||||
+2
-1
@@ -8,6 +8,7 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { inventoryActionLabelKey } from '@/features/shipping-progress/actionPresentation';
|
||||
|
||||
export interface InventoryIssueFallback {
|
||||
kind?: string | null;
|
||||
@@ -70,7 +71,7 @@ const reasonLabel = computed(() => {
|
||||
:disabled="busy"
|
||||
@click="emit('retry-preparation')"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.lineOps.retryPreparation') }}
|
||||
{{ t(inventoryActionLabelKey('retry_inventory_preparation')!) }}
|
||||
</button>
|
||||
</section>
|
||||
</template>
|
||||
+94
@@ -0,0 +1,94 @@
|
||||
/**
|
||||
* features/chat/components/shipping-review/ReviewLifecycleStageNavigation.spec.ts
|
||||
* 用途:验收订单生命周期阶段导航的只读查看与前置阻断交互。
|
||||
* 依赖:ReviewLifecycleStageNavigation;Vue Test Utils 与 Vue I18n 测试运行时。
|
||||
* 逻辑:阶段状态由父级传入;本测试只验证组件不会绕过 blocked 状态发出选择事件。
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { mount } from '@vue/test-utils';
|
||||
import { createI18n } from 'vue-i18n';
|
||||
import ReviewLifecycleStageNavigation, {
|
||||
type ReviewLifecycleStageItem,
|
||||
} from './ReviewLifecycleStageNavigation.vue';
|
||||
|
||||
const i18n = createI18n({
|
||||
legacy: false,
|
||||
locale: 'zh-CN',
|
||||
messages: {
|
||||
'zh-CN': {
|
||||
chat: {
|
||||
shippingOrderReview: {
|
||||
lifecycle: {
|
||||
navigation: '订单生命周期阶段',
|
||||
current: '当前可处理',
|
||||
completed: '已完成,可查看',
|
||||
blocked: '前置未完成',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const stages: ReviewLifecycleStageItem[] = [
|
||||
{ code: 'order_review', label: '订单复核', state: 'completed' },
|
||||
{ code: 'fulfillment_prep', label: '通知准备', state: 'current' },
|
||||
{ code: 'upload_complete', label: '通知完成', state: 'blocked', reason: '请先完成通知准备' },
|
||||
];
|
||||
|
||||
/** 挂载导航,复用真实 i18n 以覆盖状态文案渲染。 */
|
||||
function mountNavigation() {
|
||||
return mount(ReviewLifecycleStageNavigation, {
|
||||
props: { stages, activeCode: 'fulfillment_prep' },
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
}
|
||||
|
||||
describe('ReviewLifecycleStageNavigation', () => {
|
||||
it('renders intake_parse as the first lifecycle stage', () => {
|
||||
const wrapper = mount(ReviewLifecycleStageNavigation, {
|
||||
props: {
|
||||
stages: [
|
||||
{ code: 'intake_parse' as ReviewLifecycleStageItem['code'], label: '接收解析', state: 'current' },
|
||||
...stages,
|
||||
],
|
||||
activeCode: 'intake_parse' as ReviewLifecycleStageItem['code'],
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
|
||||
const nodes = wrapper.findAll('div[data-testid^="review-lifecycle-stage-"]');
|
||||
// 关键断言:接收解析必须在用户生命周期导航首位,不得回退为三阶段。
|
||||
expect(nodes.map((node) => node.attributes('data-testid'))).toEqual([
|
||||
'review-lifecycle-stage-intake_parse',
|
||||
'review-lifecycle-stage-order_review',
|
||||
'review-lifecycle-stage-fulfillment_prep',
|
||||
'review-lifecycle-stage-upload_complete',
|
||||
]);
|
||||
expect(wrapper.find('[data-testid="review-lifecycle-stage-navigation"] > div').classes()).toContain('sm:grid-cols-4');
|
||||
});
|
||||
|
||||
it('allows opening a completed stage for inspection', async () => {
|
||||
const wrapper = mountNavigation();
|
||||
await wrapper.get('[data-testid="review-lifecycle-stage-order_review"]').findAll('button')[1].trigger('click');
|
||||
// 关键断言:完成的阶段可回看,不会因已完成而被禁用。
|
||||
expect(wrapper.emitted('select')).toEqual([['order_review']]);
|
||||
});
|
||||
|
||||
it('disables a future stage and does not emit a selection', async () => {
|
||||
const wrapper = mountNavigation();
|
||||
const future = wrapper.get('[data-testid="review-lifecycle-stage-upload_complete"]');
|
||||
// 关键断言:前置未完成只展示原因,不能通过前端导航越过后端阶段。
|
||||
expect(future.text()).toContain('请先完成通知准备');
|
||||
await future.findAll('button')[1].trigger('click');
|
||||
expect(wrapper.emitted('select')).toBeUndefined();
|
||||
});
|
||||
|
||||
it('opens process details from the stage label without reserving a separate row', async () => {
|
||||
const wrapper = mountNavigation();
|
||||
const detail = wrapper.get('[data-testid="review-lifecycle-stage-detail-fulfillment_prep"]');
|
||||
// 关键断言:阶段名称本身是流程详情入口,不额外占用工作台一整行。
|
||||
await detail.trigger('click');
|
||||
expect(wrapper.emitted('open-detail')).toEqual([['fulfillment_prep']]);
|
||||
});
|
||||
});
|
||||
+87
@@ -0,0 +1,87 @@
|
||||
<!--
|
||||
features/chat/components/shipping-review/ReviewLifecycleStageNavigation.vue
|
||||
用途:订单生命周期工作台的四阶段导航,只呈现父级已裁决的阶段状态。
|
||||
依赖:父级 ShippingOrderReviewView 提供阶段、状态和阻断原因;lucide-vue-next 图标。
|
||||
逻辑:用户可打开当前或已完成阶段查看;后续阶段由父级传入 blocked 并禁用,本组件不写业务状态。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { Check, LockKeyhole } from 'lucide-vue-next';
|
||||
|
||||
export type ReviewLifecycleStageCode = 'intake_parse' | 'order_review' | 'fulfillment_prep' | 'upload_complete';
|
||||
export type ReviewLifecycleStageState = 'current' | 'completed' | 'blocked';
|
||||
|
||||
export interface ReviewLifecycleStageItem {
|
||||
code: ReviewLifecycleStageCode;
|
||||
label: string;
|
||||
state: ReviewLifecycleStageState;
|
||||
reason?: string | null;
|
||||
}
|
||||
|
||||
const props = defineProps<{
|
||||
stages: ReviewLifecycleStageItem[];
|
||||
/** 后端尚未下发入口时为空;导航只能展示加载/未授权态,不能自行指定订单复核。 */
|
||||
activeCode: ReviewLifecycleStageCode | null;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
select: [code: ReviewLifecycleStageCode];
|
||||
'open-detail': [code: ReviewLifecycleStageCode];
|
||||
}>();
|
||||
|
||||
/**
|
||||
* 阶段导航只允许进入当前或已完成阶段;blocked 仅说明前置条件,不替代后端 Gate 判定。
|
||||
*/
|
||||
function selectStage(stage: ReviewLifecycleStageItem) {
|
||||
if (stage.state === 'blocked') return;
|
||||
emit('select', stage.code);
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<nav
|
||||
class="rounded-xl border border-default bg-surface p-2"
|
||||
:aria-label="$t('chat.shippingOrderReview.lifecycle.navigation')"
|
||||
data-testid="review-lifecycle-stage-navigation"
|
||||
>
|
||||
<div class="grid gap-2 sm:grid-cols-4">
|
||||
<div
|
||||
v-for="stage in props.stages"
|
||||
:key="stage.code"
|
||||
class="min-w-0 rounded-lg border px-3 py-2 text-left transition-colors"
|
||||
:class="[
|
||||
stage.code === props.activeCode
|
||||
? 'border-brand-500 bg-brand-50 text-brand-950 dark:bg-brand-950/30 dark:text-brand-50'
|
||||
: 'border-transparent hover:bg-surface-soft',
|
||||
stage.state === 'blocked' ? 'opacity-60' : '',
|
||||
]"
|
||||
:data-testid="`review-lifecycle-stage-${stage.code}`"
|
||||
>
|
||||
<span class="flex items-center gap-2 text-sm font-semibold">
|
||||
<Check v-if="stage.state === 'completed'" class="h-4 w-4 shrink-0 text-emerald-600" />
|
||||
<LockKeyhole v-else-if="stage.state === 'blocked'" class="h-4 w-4 shrink-0 text-muted" />
|
||||
<span v-else class="h-2 w-2 shrink-0 rounded-full bg-brand-600" aria-hidden="true" />
|
||||
<button
|
||||
type="button"
|
||||
class="truncate text-left hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-500"
|
||||
:data-testid="`review-lifecycle-stage-detail-${stage.code}`"
|
||||
@click="emit('open-detail', stage.code)"
|
||||
>{{ stage.label }}</button>
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
class="mt-1 block w-full truncate text-left text-xs focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-500 disabled:cursor-not-allowed"
|
||||
:class="stage.state === 'blocked' ? 'text-muted' : 'text-secondary'"
|
||||
:title="stage.reason || undefined"
|
||||
:disabled="stage.state === 'blocked'"
|
||||
@click="selectStage(stage)"
|
||||
>
|
||||
{{ stage.state === 'current'
|
||||
? $t('chat.shippingOrderReview.lifecycle.current')
|
||||
: stage.state === 'completed'
|
||||
? $t('chat.shippingOrderReview.lifecycle.completed')
|
||||
: (stage.reason || $t('chat.shippingOrderReview.lifecycle.blocked')) }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</nav>
|
||||
</template>
|
||||
+12
-2
@@ -34,8 +34,8 @@ function mountPanel(needsReview = false) {
|
||||
needs_review: needsReview,
|
||||
selected_profile: { profile_code: 'ODP-A', display_name: '客户订单模板', version: 1 },
|
||||
candidates: [
|
||||
{ profile_code: 'ODP-A', score: 0.99 },
|
||||
{ profile_code: 'ODP-B', score: 0.98 },
|
||||
{ profile_code: 'ODP-A', display_name: '客户订单模板', score: 0.99 },
|
||||
{ profile_code: 'ODP-B', display_name: '客户订单模板(旧版)', score: 0.98 },
|
||||
],
|
||||
fallback_reason_codes: [],
|
||||
},
|
||||
@@ -59,4 +59,14 @@ describe('ReviewProfileMatchPanel', () => {
|
||||
await wrapper.get('[data-testid="review-profile-match-candidates-toggle"]').trigger('click');
|
||||
expect(wrapper.find('[data-testid="review-profile-match-candidates"]').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it('候选模板优先展示模板名称,不把内部编号作为主文案', async () => {
|
||||
const wrapper = mountPanel(true);
|
||||
|
||||
await wrapper.get('[data-testid="review-profile-match-candidates-toggle"]').trigger('click');
|
||||
|
||||
// 关键断言:业务用户辨认模板依赖 display_name,ODP 编号不应出现在候选列表主展示中。
|
||||
expect(wrapper.get('[data-testid="review-profile-match-candidates"]').text()).toContain('客户订单模板');
|
||||
expect(wrapper.get('[data-testid="review-profile-match-candidates"]').text()).not.toContain('ODP-A');
|
||||
});
|
||||
});
|
||||
@@ -57,7 +57,7 @@ const selectedLabel = computed(() => {
|
||||
if (!selected) {
|
||||
return t('chat.shippingOrderReview.profileMatch.noSelected');
|
||||
}
|
||||
const name = String(selected.display_name || selected.profile_code || '').trim();
|
||||
const name = String(selected.display_name || '').trim();
|
||||
if (!name) return t('chat.shippingOrderReview.profileMatch.noSelected');
|
||||
if (!isAdminView.value) return name;
|
||||
const version = selected.version != null ? ` v${selected.version}` : '';
|
||||
@@ -128,7 +128,7 @@ const selectedLabel = computed(() => {
|
||||
:key="`${item.profile_code}-${item.version}-${idx}`"
|
||||
class="rounded-lg border border-default bg-surface-soft px-2.5 py-1.5 text-[11px] text-secondary"
|
||||
>
|
||||
<span class="font-mono">{{ item.profile_code }}</span>
|
||||
<span>{{ item.display_name || t('chat.shippingOrderReview.profileMatch.noSelected') }}</span>
|
||||
<span v-if="item.score != null" class="ml-2 text-muted">{{ item.score }}</span>
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
/**
|
||||
* features/chat/components/shipping-review/ReviewWorkbenchFooter.spec.ts
|
||||
* 用途:验证字段冲突的 Gate 主动作只由右栏当前任务卡承载,底栏不得重复展示。
|
||||
* 依赖:Vitest、Vue Test Utils、Vue I18n、ReviewWorkbenchFooter。
|
||||
* 逻辑:订单复核底栏只保留保存校验,不展示已由当前任务卡或阶段页承载的流程动作。
|
||||
*/
|
||||
import { mount } from '@vue/test-utils';
|
||||
import { createI18n } from 'vue-i18n';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import ReviewWorkbenchFooter from './ReviewWorkbenchFooter.vue';
|
||||
|
||||
const i18n = createI18n({
|
||||
legacy: false,
|
||||
locale: 'zh-CN',
|
||||
messages: {
|
||||
'zh-CN': {
|
||||
chat: {
|
||||
shippingProcessing: { action: { resolve_field_conflicts: '处理字段冲突', view_result: '查看结果', none: '无操作' } },
|
||||
shippingOrderReview: { unsavedSwitch: { unsavedCount: '未保存 {count} 项' } },
|
||||
},
|
||||
workspace: { shippingNotice: { processGate: { actions: {} } } },
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
describe('ReviewWorkbenchFooter', () => {
|
||||
it('keeps intake parse dispositions in the sticky footer without replacement upload', () => {
|
||||
const wrapper = mount(ReviewWorkbenchFooter, {
|
||||
props: {
|
||||
availableActions: ['mark_non_order', 'mark_quality_issue', 'reparse', 'validate'],
|
||||
canConfirmBuild: false, saving: false, isReadOnly: false, hasDraft: true,
|
||||
showParseDispositions: true, showValidate: false,
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
|
||||
// 关键断言:接收解析动作与订单复核使用同一 sticky 底栏;业务不支持替代 PDF 上传。
|
||||
expect(wrapper.get('[data-testid="review-footer-actions"]').classes()).toEqual(expect.arrayContaining(['sticky', 'bottom-0']));
|
||||
expect(wrapper.text()).toContain('chat.shippingOrderReview.markNonOrder');
|
||||
expect(wrapper.text()).toContain('chat.shippingOrderReview.markQualityIssue');
|
||||
expect(wrapper.text()).toContain('chat.shippingOrderReview.reparse');
|
||||
expect(wrapper.text()).not.toContain('chat.shippingOrderReview.saveOrderAndValidate');
|
||||
});
|
||||
|
||||
it('does not duplicate current-case flow actions in the order-review footer', () => {
|
||||
const wrapper = mount(ReviewWorkbenchFooter, {
|
||||
props: {
|
||||
availableActions: [], canConfirmBuild: false, saving: false, isReadOnly: false, hasDraft: true,
|
||||
flowPresentation: {
|
||||
primary: { intent: 'resolve_field_conflicts', actionCode: 'resolve_field_conflicts', labelKey: 'chat.shippingProcessing.action.resolve_field_conflicts' },
|
||||
secondary: { intent: 'view_result', actionCode: 'view_result', labelKey: 'chat.shippingProcessing.action.view_result' },
|
||||
overflow: [],
|
||||
},
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
|
||||
// 关键断言:字段冲突、重试和查看结果各有上游上下文,复核底栏不得重复它们。
|
||||
expect(wrapper.find('[data-testid="review-footer-flow-resolve_field_conflicts"]').exists()).toBe(false);
|
||||
expect(wrapper.find('[data-testid="review-footer-flow-view_result"]').exists()).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -3,7 +3,7 @@
|
||||
用途:订单处理工作台底部唯一写操作栏(处置 / 保存 / 统一流程动作)。
|
||||
依赖:vue-i18n、lucide-vue-next、ActionPresentation。
|
||||
逻辑:ShippingOrderReviewView 传入 available_actions 与流程动作投影;sticky bottom;
|
||||
只读查看时仍可展示 view_result/view_record;写按钮受 actionsExecutable 约束;
|
||||
订单复核只保留保存校验;流程动作由所属阶段或当前任务卡承载;写按钮受 actionsExecutable 约束;
|
||||
流程写操作经 flow-action emit(与 Resolver 同链);flowBusy||saving 时禁用。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
@@ -36,6 +36,10 @@ const props = withDefaults(defineProps<{
|
||||
actionsExecutable?: boolean;
|
||||
/** 统一流程动作提交中 */
|
||||
flowBusy?: boolean;
|
||||
/** 解析处置入口由接收解析工作面承载时,订单复核底栏隐藏四项解析操作。 */
|
||||
showParseDispositions?: boolean;
|
||||
/** 保存并校验只属于订单复核表单,接收解析阶段必须隐藏。 */
|
||||
showValidate?: boolean;
|
||||
}>(), {
|
||||
unsavedCount: 0,
|
||||
flowPresentation: null,
|
||||
@@ -46,20 +50,21 @@ const props = withDefaults(defineProps<{
|
||||
autoGateHint: '',
|
||||
actionsExecutable: true,
|
||||
flowBusy: false,
|
||||
showParseDispositions: true,
|
||||
showValidate: true,
|
||||
});
|
||||
|
||||
const emit = defineEmits<{
|
||||
'mark-non-order': [];
|
||||
'mark-quality-issue': [];
|
||||
reparse: [];
|
||||
'upload-replacement': [event: Event];
|
||||
validate: [];
|
||||
confirm: [];
|
||||
'retry-stp': [];
|
||||
'flow-action': [item: ActionPresentationItem];
|
||||
}>();
|
||||
|
||||
const { t, te } = useI18n();
|
||||
const { t } = useI18n();
|
||||
|
||||
/**
|
||||
* 判断某 action 是否在当前 Case 可用。
|
||||
@@ -68,40 +73,25 @@ function hasAction(action: string): boolean {
|
||||
return props.availableActions.includes(action);
|
||||
}
|
||||
|
||||
const flowItems = computed((): ActionPresentationItem[] => {
|
||||
const presentation = props.flowPresentation;
|
||||
if (!presentation) return [];
|
||||
const items: ActionPresentationItem[] = [];
|
||||
if (presentation.primary) items.push(presentation.primary);
|
||||
if (presentation.secondary) items.push(presentation.secondary);
|
||||
items.push(...presentation.overflow);
|
||||
// 刷新留给顶部只读区;底栏不重复。
|
||||
return items.filter((item) => item.intent !== 'refresh');
|
||||
});
|
||||
/**
|
||||
* 订单复核底栏不承载流程投影动作。
|
||||
*
|
||||
* 核心逻辑:保存并校验是表单级提交,固定放在这里;字段裁决、重试、查看结果等
|
||||
* Case/阶段级动作必须留在其业务上下文中,避免同一动作在顶栏、右栏和底栏重复出现。
|
||||
*/
|
||||
const footerFlowItems = computed((): ActionPresentationItem[] => []);
|
||||
|
||||
const hasViewOnlyFlow = computed(() => flowItems.value.some((item) => (
|
||||
item.intent === 'view_result'
|
||||
|| item.intent === 'view_record'
|
||||
|| item.intent === 'open_profile_review'
|
||||
)));
|
||||
/** 保留统一动作的文案解析,供后续恢复 Footer 流程动作时复用。 */
|
||||
function flowLabel(item: ActionPresentationItem): string {
|
||||
return t(item.labelKey);
|
||||
}
|
||||
|
||||
/** 可编辑底栏,或只读但仍有导航/查看类流程动作。 */
|
||||
const showFooter = computed(() => (
|
||||
props.hasDraft && (!props.isReadOnly || hasViewOnlyFlow.value)
|
||||
));
|
||||
/** 仅可编辑草稿显示表单提交底栏;只读版本不显示无上下文的流程按钮。 */
|
||||
const showFooter = computed(() => props.hasDraft && !props.isReadOnly);
|
||||
|
||||
const controlsBusy = computed(() => props.saving || props.flowBusy);
|
||||
const canWriteCaseActions = computed(() => props.actionsExecutable && !props.isReadOnly);
|
||||
|
||||
/**
|
||||
* 流程动作文案。
|
||||
*/
|
||||
function flowLabel(item: ActionPresentationItem): string {
|
||||
if (te(item.labelKey)) return t(item.labelKey);
|
||||
const gateKey = `workspace.shippingNotice.processGate.actions.${item.actionCode}`;
|
||||
if (te(gateKey)) return t(gateKey);
|
||||
return t('chat.shippingProcessing.action.none');
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -116,7 +106,7 @@ function flowLabel(item: ActionPresentationItem): string {
|
||||
<div class="order-1 flex flex-wrap items-center gap-2 sm:order-1">
|
||||
<template v-if="!automating && canWriteCaseActions">
|
||||
<button
|
||||
v-if="hasAction('mark_non_order')"
|
||||
v-if="showParseDispositions && hasAction('mark_non_order')"
|
||||
type="button"
|
||||
:disabled="controlsBusy"
|
||||
class="rounded border border-rose-200 px-3 py-2 text-sm text-rose-700 hover:bg-rose-50 disabled:opacity-50 dark:border-rose-900 dark:text-rose-300 dark:hover:bg-rose-950/40"
|
||||
@@ -125,7 +115,7 @@ function flowLabel(item: ActionPresentationItem): string {
|
||||
{{ t('chat.shippingOrderReview.markNonOrder') }}
|
||||
</button>
|
||||
<button
|
||||
v-if="hasAction('mark_quality_issue')"
|
||||
v-if="showParseDispositions && hasAction('mark_quality_issue')"
|
||||
type="button"
|
||||
:disabled="controlsBusy"
|
||||
class="rounded border border-amber-200 px-3 py-2 text-sm text-amber-800 hover:bg-amber-50 disabled:opacity-50 dark:border-amber-900 dark:text-amber-200 dark:hover:bg-amber-950/40"
|
||||
@@ -134,7 +124,7 @@ function flowLabel(item: ActionPresentationItem): string {
|
||||
{{ t('chat.shippingOrderReview.markQualityIssue') }}
|
||||
</button>
|
||||
<button
|
||||
v-if="hasAction('reparse')"
|
||||
v-if="showParseDispositions && hasAction('reparse')"
|
||||
type="button"
|
||||
:disabled="controlsBusy"
|
||||
class="inline-flex items-center gap-1 rounded border border-slate-300 px-3 py-2 text-sm text-slate-600 hover:bg-slate-50 disabled:opacity-50 dark:border-slate-700 dark:text-slate-300 dark:hover:bg-slate-800"
|
||||
@@ -142,24 +132,10 @@ function flowLabel(item: ActionPresentationItem): string {
|
||||
>
|
||||
<RefreshCw class="h-4 w-4" />{{ t('chat.shippingOrderReview.reparse') }}
|
||||
</button>
|
||||
<label
|
||||
v-if="hasAction('mark_quality_issue')"
|
||||
class="cursor-pointer rounded border border-slate-300 px-3 py-2 text-sm text-slate-600 hover:bg-slate-50 dark:border-slate-700 dark:text-slate-300 dark:hover:bg-slate-800"
|
||||
:class="controlsBusy ? 'pointer-events-none opacity-50' : ''"
|
||||
>
|
||||
<input
|
||||
class="sr-only"
|
||||
type="file"
|
||||
accept="application/pdf,.pdf"
|
||||
:disabled="controlsBusy"
|
||||
@change="emit('upload-replacement', $event)"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.uploadReplacement') }}
|
||||
</label>
|
||||
</template>
|
||||
|
||||
<button
|
||||
v-for="item in flowItems"
|
||||
v-for="item in footerFlowItems"
|
||||
:key="`${item.intent}-${item.actionCode}`"
|
||||
type="button"
|
||||
:disabled="controlsBusy"
|
||||
@@ -196,23 +172,13 @@ function flowLabel(item: ActionPresentationItem): string {
|
||||
</p>
|
||||
<template v-if="!automating && canWriteCaseActions">
|
||||
<button
|
||||
v-if="showStpRetry || hasAction('retry_stp_auto_create')"
|
||||
type="button"
|
||||
:disabled="controlsBusy"
|
||||
class="inline-flex items-center gap-1 rounded border border-amber-400 bg-amber-50 px-3 py-2 text-sm text-amber-950 disabled:opacity-50 dark:border-amber-700 dark:bg-amber-950/40 dark:text-amber-100"
|
||||
data-testid="review-retry-stp-auto-create"
|
||||
@click="emit('retry-stp')"
|
||||
>
|
||||
<RefreshCw class="h-4 w-4" />{{ t('chat.shippingOrderReview.autoProgress.retryObject') }}
|
||||
</button>
|
||||
<button
|
||||
v-if="hasAction('validate')"
|
||||
v-if="showValidate && hasAction('validate')"
|
||||
type="button"
|
||||
:disabled="controlsBusy"
|
||||
class="inline-flex items-center gap-1 rounded bg-sky-600 px-3 py-2 text-sm text-white disabled:opacity-50"
|
||||
@click="emit('validate')"
|
||||
>
|
||||
<Save class="h-4 w-4" />{{ t('chat.shippingOrderReview.saveNow') }}
|
||||
<Save class="h-4 w-4" />{{ t('chat.shippingOrderReview.saveOrderAndValidate') }}
|
||||
</button>
|
||||
</template>
|
||||
</div>
|
||||
|
||||
@@ -1,60 +1,33 @@
|
||||
<!--
|
||||
features/chat/components/shipping-review/ReviewWorkbenchHeader.vue
|
||||
用途:订单复核工作台顶栏——对话级动作、审计/版本入口与保存状态。
|
||||
用途:订单复核工作台顶栏——审计/版本入口与保存状态。
|
||||
依赖:vue-i18n、lucide-vue-next。
|
||||
逻辑:仅当后端 conversation_allowed_actions 含 retry_auto_progress 时渲染对话级按钮;
|
||||
审计/版本为查看入口;「已保存」为状态文本;不含单个任务单写操作。
|
||||
逻辑:审计/版本为查看入口;「已保存」为状态文本;不含单个任务单写操作。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue';
|
||||
import { ArrowLeft, RefreshCw } from 'lucide-vue-next';
|
||||
import { ArrowLeft } from 'lucide-vue-next';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
|
||||
const props = defineProps<{
|
||||
runNo: string;
|
||||
itemNo?: string | null;
|
||||
versionLabel?: string;
|
||||
selectedOrderSummary?: string | null;
|
||||
saving: boolean;
|
||||
saveFailed: boolean;
|
||||
draftConflict: boolean;
|
||||
isReadOnly: boolean;
|
||||
showVersionHistory?: boolean;
|
||||
showAuditTrail?: boolean;
|
||||
/** 对话级「重试自动推进」;仅 eligible_count>0 时由父级置 true */
|
||||
showConversationRetry?: boolean;
|
||||
conversationRetryEligibleCount?: number;
|
||||
conversationRetrying?: boolean;
|
||||
conversationRetryDisabled?: boolean;
|
||||
hasConversationRetryResult?: boolean;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
back: [];
|
||||
'open-version-history': [];
|
||||
'open-audit-trail': [];
|
||||
'retry-conversation-auto-progress': [];
|
||||
'open-conversation-retry-result': [];
|
||||
}>();
|
||||
|
||||
const { t } = useI18n();
|
||||
|
||||
/**
|
||||
* 副标题:优先工作项编号与版本,否则识别批次号。
|
||||
*/
|
||||
const subtitle = computed(() => {
|
||||
if (props.itemNo) {
|
||||
return t('chat.shippingOrderReview.workItemHeader', {
|
||||
itemNo: props.itemNo,
|
||||
version: props.versionLabel || '',
|
||||
});
|
||||
}
|
||||
return t('chat.shippingOrderReview.run', { runNo: props.runNo });
|
||||
});
|
||||
|
||||
const showRetry = computed(() => (
|
||||
Boolean(props.showConversationRetry)
|
||||
&& Number(props.conversationRetryEligibleCount || 0) > 0
|
||||
));
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -69,36 +42,12 @@ const showRetry = computed(() => (
|
||||
</button>
|
||||
<div class="min-w-0 flex-1">
|
||||
<h1 class="text-base font-semibold">{{ t('chat.shippingOrderReview.title') }}</h1>
|
||||
<p class="truncate text-xs text-slate-500 dark:text-slate-400">{{ subtitle }}</p>
|
||||
<p
|
||||
v-if="selectedOrderSummary"
|
||||
class="truncate text-xs text-slate-600 dark:text-slate-300"
|
||||
data-testid="review-selected-order-summary"
|
||||
>{{ selectedOrderSummary }}</p>
|
||||
</div>
|
||||
<button
|
||||
v-if="showRetry"
|
||||
type="button"
|
||||
class="inline-flex items-center gap-1 rounded border border-amber-400 bg-amber-50 px-2.5 py-1.5 text-xs font-medium text-amber-950 hover:bg-amber-100 disabled:opacity-50 dark:border-amber-700 dark:bg-amber-950/40 dark:text-amber-100"
|
||||
data-testid="review-conversation-retry-auto-progress"
|
||||
:disabled="conversationRetrying || conversationRetryDisabled || isReadOnly"
|
||||
@click="emit('retry-conversation-auto-progress')"
|
||||
>
|
||||
<RefreshCw
|
||||
class="h-3.5 w-3.5"
|
||||
:class="conversationRetrying ? 'animate-spin' : ''"
|
||||
/>
|
||||
{{ conversationRetrying ? t('chat.shippingOrderReview.conversationRetry.retrying') : t('chat.shippingOrderReview.autoProgress.retry') }}
|
||||
<span
|
||||
v-if="conversationRetryEligibleCount"
|
||||
class="rounded bg-amber-200/80 px-1 text-[10px] dark:bg-amber-900/60"
|
||||
>{{ conversationRetryEligibleCount }}</span>
|
||||
</button>
|
||||
<button
|
||||
v-if="hasConversationRetryResult"
|
||||
type="button"
|
||||
class="relative rounded border border-slate-200 px-2.5 py-1.5 text-xs hover:bg-slate-50 dark:border-slate-700 dark:hover:bg-slate-800"
|
||||
data-testid="review-open-conversation-retry-result"
|
||||
@click="emit('open-conversation-retry-result')"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.conversationRetry.viewResult') }}
|
||||
<span class="absolute -right-1 -top-1 h-2 w-2 rounded-full bg-rose-500" />
|
||||
</button>
|
||||
<button
|
||||
v-if="showAuditTrail"
|
||||
type="button"
|
||||
|
||||
+335
-17
@@ -117,6 +117,210 @@ function buildWorkItem(
|
||||
}
|
||||
|
||||
describe('ShippingConversationProcessingCard', () => {
|
||||
it('only exposes file cancellation when the backend explicitly authorizes cancel_unit', async () => {
|
||||
const projection = buildProjection();
|
||||
projection.processing = [{
|
||||
user_task_no: 'OT-CANCEL-UNIT', group: 'processing', status_label: 'extracting',
|
||||
file_count: 1, run_no: 'RUN-CANCEL-UNIT', can_append: false,
|
||||
objects: [{ kind: 'document', object_key: 'DOC-9', label: 'cancel.pdf', filename: 'cancel.pdf',
|
||||
document_id: 9, root_document_id: 9, status_label: 'extracting' }],
|
||||
}];
|
||||
const workItem = buildWorkItem('OT-CANCEL-UNIT', {
|
||||
availableActions: ['cancel_unit'],
|
||||
sourceSummary: { ...buildWorkItem('OT-CANCEL-UNIT').sourceSummary, documentId: 9 },
|
||||
uiState: {
|
||||
status: 'running',
|
||||
stage: 'document_parsing',
|
||||
blocking_reason: null,
|
||||
primary_action: null,
|
||||
secondary_actions: [{ code: 'cancel_unit', enabled: true }],
|
||||
},
|
||||
});
|
||||
const wrapper = mount(ShippingConversationProcessingCard, {
|
||||
props: { projection, workItems: [workItem], workbenchMode: true },
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
await flushPromises();
|
||||
|
||||
await wrapper.find('summary').trigger('click');
|
||||
await wrapper.find('[data-testid="shipping-processing-file-cancel"]').trigger('click');
|
||||
expect(wrapper.emitted('fileAction')?.[0]?.[0]).toMatchObject({
|
||||
action: 'cancel_unit', projection: { workItemNo: 'OT-CANCEL-UNIT' },
|
||||
});
|
||||
});
|
||||
|
||||
it('does not fall back to legacy cancellation when ui_state revokes it', async () => {
|
||||
const projection = buildProjection();
|
||||
projection.processing = [{
|
||||
user_task_no: 'OT-CANCEL-REVOKED', group: 'processing', status_label: 'extracting',
|
||||
file_count: 1, run_no: 'RUN-CANCEL-REVOKED', can_append: false,
|
||||
objects: [{ kind: 'document', object_key: 'DOC-10', label: 'revoked.pdf', filename: 'revoked.pdf',
|
||||
document_id: 10, root_document_id: 10, status_label: 'extracting' }],
|
||||
}];
|
||||
const workItem = buildWorkItem('OT-CANCEL-REVOKED', {
|
||||
availableActions: ['cancel_unit'],
|
||||
sourceSummary: { ...buildWorkItem('OT-CANCEL-REVOKED').sourceSummary, documentId: 10 },
|
||||
uiState: {
|
||||
status: 'running',
|
||||
stage: 'document_parsing',
|
||||
blocking_reason: null,
|
||||
primary_action: null,
|
||||
secondary_actions: [],
|
||||
},
|
||||
});
|
||||
const wrapper = mount(ShippingConversationProcessingCard, {
|
||||
props: { projection, workItems: [workItem], workbenchMode: true },
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
await flushPromises();
|
||||
|
||||
// ui_state 已出现即表示后端完成了正式动作裁决;遗留 availableActions 不得重新授权。
|
||||
expect(wrapper.find('[data-testid="shipping-processing-file-cancel"]').exists()).toBe(false);
|
||||
expect(wrapper.emitted('fileAction')).toBeUndefined();
|
||||
});
|
||||
|
||||
it('does not render legacy document_names as a batch file row without a live leaf projection', async () => {
|
||||
const projection = buildProjection();
|
||||
projection.processing = [{
|
||||
user_task_no: 'OT-HISTORICAL-SNAPSHOT', group: 'processing', status_label: 'extracting',
|
||||
title: 'legacy-run.pdf', document_names: ['legacy-run.pdf'], file_count: 1,
|
||||
run_no: 'RUN-HISTORICAL-SNAPSHOT', can_append: false,
|
||||
}];
|
||||
const wrapper = mount(ShippingConversationProcessingCard, {
|
||||
props: { projection, workItems: [], workbenchMode: true },
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
await flushPromises();
|
||||
|
||||
// 批次中心没有实时叶子投影时不得由历史 Run 快照补造文件行或操作入口。
|
||||
expect(wrapper.find('[data-testid="shipping-processing-file-OT-HISTORICAL-SNAPSHOT-document-0"]').exists()).toBe(false);
|
||||
expect(wrapper.text()).not.toContain('legacy-run.pdf');
|
||||
});
|
||||
|
||||
it('uses the live leaf summary instead of a stale task object in batch mode', async () => {
|
||||
const projection = buildProjection();
|
||||
projection.processing = [{
|
||||
user_task_no: 'OT-LIVE-LEAF', group: 'processing', status_label: 'extracting',
|
||||
title: 'snapshot-old-name.pdf', file_count: 1, run_no: 'RUN-LIVE-LEAF', can_append: false,
|
||||
objects: [{
|
||||
kind: 'document', object_key: 'DOC-88', label: 'snapshot-old-name.pdf',
|
||||
filename: 'snapshot-old-name.pdf', document_id: 88, root_document_id: 88,
|
||||
status_label: 'pending_review',
|
||||
}],
|
||||
}];
|
||||
const live = buildWorkItem('OT-LIVE-LEAF', {
|
||||
runNo: 'RUN-LIVE-LEAF',
|
||||
sourceSummary: {
|
||||
emailSubject: null, filename: 'realtime-name.pdf', documentId: 88,
|
||||
documentCount: 1, parsedDocumentCount: 1, candidateCount: 1,
|
||||
customerName: null, poNumber: 'PO-REALTIME',
|
||||
},
|
||||
uiState: {
|
||||
status: 'running', stage: 'order_review', lifecycleStage: 'order_review',
|
||||
lifecycleEntries: [{ code: 'order_review', state: 'current', targetSurface: 'order_lifecycle_workbench' }],
|
||||
blocking_reason: null, primary_action: null, secondary_actions: [],
|
||||
},
|
||||
});
|
||||
const wrapper = mount(ShippingConversationProcessingCard, {
|
||||
props: { projection, workItems: [live], workbenchMode: true },
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
await flushPromises();
|
||||
|
||||
const row = wrapper.get('[data-testid="shipping-processing-file-DOC-88"]');
|
||||
expect(row.text()).toContain('realtime-name.pdf');
|
||||
expect(row.text()).toContain('PO:PO-REALTIME');
|
||||
expect(row.text()).not.toContain('snapshot-old-name.pdf');
|
||||
});
|
||||
|
||||
it('expands EML files only from the live aggregate work item', async () => {
|
||||
const projection = buildProjection();
|
||||
projection.processing = [{
|
||||
user_task_no: 'INTAKE:EML-LIVE', group: 'processing', status_label: 'extracting',
|
||||
title: 'snapshot-mail.eml', document_names: ['snapshot-attachment.pdf'],
|
||||
file_count: 1, run_no: 'RUN-EML-LIVE', can_append: false,
|
||||
aggregateChildren: [],
|
||||
}];
|
||||
const liveChild = buildWorkItem('DOCUMENT:77', {
|
||||
sourceType: 'eml', rootOrderTaskNo: 'OT-EML-LIVE', runNo: 'RUN-EML-LIVE',
|
||||
sourceSummary: {
|
||||
emailSubject: null, filename: 'live-attachment.pdf', documentId: 77,
|
||||
documentCount: 1, parsedDocumentCount: 1, candidateCount: 1,
|
||||
customerName: null, poNumber: 'PO-EML-LIVE',
|
||||
},
|
||||
uiState: {
|
||||
status: 'running', stage: 'order_review', lifecycleStage: 'order_review',
|
||||
lifecycleEntries: [{ code: 'order_review', state: 'current', targetSurface: 'order_lifecycle_workbench' }],
|
||||
blocking_reason: null, primary_action: null, secondary_actions: [],
|
||||
},
|
||||
});
|
||||
const liveEmlRoot = buildWorkItem('INTAKE:EML-LIVE', {
|
||||
sourceType: 'eml', rootOrderTaskNo: 'OT-EML-LIVE', runNo: 'RUN-EML-LIVE',
|
||||
sourceSummary: {
|
||||
emailSubject: 'Live mail', filename: 'live-mail.eml', documentId: null,
|
||||
documentCount: 1, parsedDocumentCount: 1, candidateCount: 1,
|
||||
customerName: null, poNumber: null,
|
||||
},
|
||||
aggregateChildren: [liveChild],
|
||||
});
|
||||
const wrapper = mount(ShippingConversationProcessingCard, {
|
||||
props: { projection, workItems: [liveEmlRoot], workbenchMode: true },
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
await flushPromises();
|
||||
|
||||
const row = wrapper.get('[data-testid="shipping-processing-file-DOC-77"]');
|
||||
expect(row.text()).toContain('live-attachment.pdf');
|
||||
expect(row.text()).toContain('PO:PO-EML-LIVE');
|
||||
expect(wrapper.text()).not.toContain('snapshot-attachment.pdf');
|
||||
});
|
||||
|
||||
it('keeps an EML attachment when it has a linked child order task', async () => {
|
||||
const projection = buildProjection();
|
||||
projection.processing = [{
|
||||
user_task_no: 'INTAKE:EML-WITH-CHILD-OT', group: 'processing', status_label: 'extracting',
|
||||
title: 'mail.eml', file_count: 2, run_no: 'RUN-EML-WITH-CHILD-OT', can_append: false,
|
||||
}];
|
||||
const firstAttachment = buildWorkItem('OT-EML-WITH-CHILD-OT', {
|
||||
sourceType: 'eml', rootOrderTaskNo: 'OT-EML-WITH-CHILD-OT',
|
||||
sourceSummary: {
|
||||
emailSubject: null, filename: 'first.pdf', documentId: 266,
|
||||
documentCount: 1, parsedDocumentCount: 1, candidateCount: 1,
|
||||
customerName: null, poNumber: 'PO-FIRST',
|
||||
},
|
||||
childOrderTasks: [{
|
||||
orderTaskNo: 'OT-EML-WITH-CHILD-OT-C1', status: 'blocked', stage: 'inventory_matching',
|
||||
customerName: null, poNumber: 'PO-SECOND', lastActivityAt: null,
|
||||
}],
|
||||
});
|
||||
const secondAttachment = buildWorkItem('OT-EML-WITH-CHILD-OT-C1', {
|
||||
sourceType: 'eml', rootOrderTaskNo: 'OT-EML-WITH-CHILD-OT',
|
||||
sourceSummary: {
|
||||
emailSubject: null, filename: 'second.pdf', documentId: 267,
|
||||
documentCount: 1, parsedDocumentCount: 1, candidateCount: 1,
|
||||
customerName: null, poNumber: 'PO-SECOND',
|
||||
},
|
||||
});
|
||||
const liveEmlRoot = buildWorkItem('INTAKE:EML-WITH-CHILD-OT', {
|
||||
sourceType: 'eml', rootOrderTaskNo: 'OT-EML-WITH-CHILD-OT',
|
||||
sourceSummary: {
|
||||
emailSubject: 'Mail', filename: 'mail.eml', documentId: null,
|
||||
documentCount: 2, parsedDocumentCount: 2, candidateCount: 2,
|
||||
customerName: null, poNumber: null,
|
||||
},
|
||||
aggregateChildren: [firstAttachment, secondAttachment],
|
||||
});
|
||||
const wrapper = mount(ShippingConversationProcessingCard, {
|
||||
props: { projection, workItems: [liveEmlRoot], workbenchMode: true },
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
await flushPromises();
|
||||
|
||||
expect(wrapper.find('[data-testid="shipping-processing-file-DOC-266"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="shipping-processing-file-DOC-267"]').exists()).toBe(true);
|
||||
expect(wrapper.text()).toContain('处理中 · 2 个文件');
|
||||
});
|
||||
|
||||
it('renders needs_action / processing groups and collapsible processing records with three subsections', async () => {
|
||||
const wrapper = mount(ShippingConversationProcessingCard, {
|
||||
props: { projection: buildProjection() },
|
||||
@@ -125,10 +329,11 @@ describe('ShippingConversationProcessingCard', () => {
|
||||
await flushPromises();
|
||||
|
||||
expect(wrapper.find('[data-testid="shipping-conversation-processing-card"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="shipping-processing-group-needs_action"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="shipping-processing-group-failed"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="shipping-processing-group-processing"]').exists()).toBe(true);
|
||||
expect(wrapper.text()).toContain('需要你处理 · 1 个任务');
|
||||
expect(wrapper.text()).toContain('系统处理中 · 1 个任务');
|
||||
// 批次中心统一按文件计数;旧任务数文案不再是页面统计口径。
|
||||
expect(wrapper.text()).toContain('异常 · 0 个文件');
|
||||
expect(wrapper.text()).toContain('处理中 · 0 个文件');
|
||||
expect(wrapper.text()).toContain('刚刚创建');
|
||||
|
||||
// 处理记录默认折叠;标题 count = completed + history 返回条数。
|
||||
@@ -441,20 +646,36 @@ describe('ShippingConversationProcessingCard', () => {
|
||||
expect(wrapper.findAll('[data-testid="shipping-conversation-processing-card"]')).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('renders pending order_intake work items above task groups', async () => {
|
||||
it('renders an EML order_intake in the unified failed group rather than the removed intake side path', async () => {
|
||||
const wrapper = mount(ShippingConversationProcessingCard, {
|
||||
props: {
|
||||
projection: null,
|
||||
projection: {
|
||||
summary: { total_tasks: 1, total_files: 1, processing: 0, needs_action: 1, completed: 0, history: 0 },
|
||||
needs_action: [{
|
||||
user_task_no: 'SNI-1',
|
||||
group: 'needs_action',
|
||||
userGroup: 'failed',
|
||||
status_label: 'failed',
|
||||
title: 'mail.eml',
|
||||
file_count: 1,
|
||||
run_no: null,
|
||||
can_append: false,
|
||||
}],
|
||||
processing: [],
|
||||
completed: [],
|
||||
history: [],
|
||||
},
|
||||
workItems: [{
|
||||
workItemType: 'order_intake',
|
||||
workItemNo: 'SNI-1',
|
||||
sourceType: 'direct_pdf',
|
||||
sourceType: 'eml',
|
||||
rootOrderTaskNo: null,
|
||||
shippingNoticeNo: null,
|
||||
conversationId: 'conv-1',
|
||||
submissionNo: 'SOS-1',
|
||||
intakeNo: 'SNI-1',
|
||||
status: 'failed',
|
||||
userGroup: 'failed',
|
||||
stage: 'document_parsing',
|
||||
progressVersion: 1,
|
||||
lastActivityAt: '2026-08-04T12:00:00Z',
|
||||
@@ -484,16 +705,10 @@ describe('ShippingConversationProcessingCard', () => {
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
await flushPromises();
|
||||
expect(wrapper.find('[data-testid="shipping-processing-group-order-intake"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="shipping-processing-intake-SNI-1"]').exists()).toBe(true);
|
||||
expect(wrapper.text()).toContain('po.pdf');
|
||||
expect(wrapper.find('[data-testid="shipping-processing-intake-recovery"]').exists()).toBe(true);
|
||||
expect(wrapper.text()).toContain('SHIPPING_NOTICE.INTAKE_PARSE_FAILED');
|
||||
await wrapper.find('[data-testid="shipping-processing-intake-action-retry_parse"]').trigger('click');
|
||||
expect(wrapper.emitted('intakeAction')?.[0]?.[0]).toMatchObject({
|
||||
action: 'retry_parse',
|
||||
item: { workItemNo: 'SNI-1' },
|
||||
});
|
||||
expect(wrapper.find('[data-testid="shipping-processing-group-failed"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="shipping-processing-task-SNI-1"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="shipping-processing-group-order-intake"]').exists()).toBe(false);
|
||||
expect(wrapper.text()).toContain('重试解析');
|
||||
});
|
||||
|
||||
it('keeps a human Gate action visible before and after selecting its task', async () => {
|
||||
@@ -549,7 +764,110 @@ describe('ShippingConversationProcessingCard', () => {
|
||||
});
|
||||
await flushPromises();
|
||||
|
||||
expect(wrapper.text()).toContain('待复核');
|
||||
// 旧聚合卡不再显示内部 Case 状态;工作台文件行才展示后端 ui_state。
|
||||
expect(wrapper.text()).not.toContain('review_case_draft');
|
||||
expect(wrapper.text()).not.toContain('review_case_draft');
|
||||
});
|
||||
|
||||
it('renders a compact V3 file row with named lifecycle entries', async () => {
|
||||
const projection = buildProjection();
|
||||
projection.processing = [{
|
||||
...projection.processing[0],
|
||||
user_task_no: 'OT-LIFECYCLE',
|
||||
run_no: 'RUN-LIFECYCLE',
|
||||
file_count: 1,
|
||||
}];
|
||||
const wrapper = mount(ShippingConversationProcessingCard, {
|
||||
props: {
|
||||
projection,
|
||||
workbenchMode: true,
|
||||
workItems: [buildWorkItem('OT-LIFECYCLE', {
|
||||
runNo: 'RUN-LIFECYCLE',
|
||||
caseNo: 'CASE-LIFECYCLE',
|
||||
sourceSummary: {
|
||||
emailSubject: null,
|
||||
filename: 'lifecycle.pdf',
|
||||
documentId: 9,
|
||||
documentCount: 1,
|
||||
parsedDocumentCount: 1,
|
||||
candidateCount: 1,
|
||||
customerName: null,
|
||||
poNumber: 'PO-LIFECYCLE',
|
||||
},
|
||||
uiState: {
|
||||
status: 'running',
|
||||
stage: 'inventory_match',
|
||||
lifecycleStage: 'fulfillment_prep',
|
||||
lifecycleEntries: [
|
||||
{ code: 'order_review', state: 'available', targetSurface: 'order_lifecycle_workbench' },
|
||||
{ code: 'fulfillment_prep', state: 'current', targetSurface: 'order_lifecycle_workbench' },
|
||||
{ code: 'upload_complete', state: 'unavailable', targetSurface: 'order_lifecycle_workbench' },
|
||||
],
|
||||
blocking_reason: null,
|
||||
primary_action: null,
|
||||
secondary_actions: [],
|
||||
},
|
||||
})],
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
await flushPromises();
|
||||
|
||||
const row = wrapper.find('[data-testid="shipping-processing-file-DOC-9"]');
|
||||
expect(row.exists()).toBe(true);
|
||||
expect(row.text()).toContain('lifecycle.pdf');
|
||||
expect(row.text()).toContain('PO:PO-LIFECYCLE');
|
||||
expect(row.text()).toContain('通知准备');
|
||||
expect(row.text()).toContain('订单复核 · 可进入');
|
||||
expect(row.text()).toContain('通知准备 · 当前可处理');
|
||||
expect(row.text()).toContain('通知完成 · 前置未完成');
|
||||
});
|
||||
|
||||
it('fails closed when a lifecycle entry has an unknown backend state', async () => {
|
||||
const projection = buildProjection();
|
||||
projection.processing = [{
|
||||
...projection.processing[0],
|
||||
user_task_no: 'OT-LIFECYCLE-UNKNOWN',
|
||||
run_no: 'RUN-LIFECYCLE-UNKNOWN',
|
||||
file_count: 1,
|
||||
}];
|
||||
const wrapper = mount(ShippingConversationProcessingCard, {
|
||||
props: {
|
||||
projection,
|
||||
workbenchMode: true,
|
||||
workItems: [buildWorkItem('OT-LIFECYCLE-UNKNOWN', {
|
||||
runNo: 'RUN-LIFECYCLE-UNKNOWN',
|
||||
sourceSummary: {
|
||||
emailSubject: null,
|
||||
filename: 'unknown-entry.pdf',
|
||||
documentId: 10,
|
||||
documentCount: 1,
|
||||
parsedDocumentCount: 1,
|
||||
candidateCount: 1,
|
||||
customerName: null,
|
||||
poNumber: 'PO-UNKNOWN',
|
||||
},
|
||||
uiState: {
|
||||
status: 'running',
|
||||
stage: 'inventory_match',
|
||||
lifecycleStage: 'fulfillment_prep',
|
||||
lifecycleEntries: [
|
||||
{ code: 'order_review', state: 'paused', targetSurface: 'order_lifecycle_workbench' },
|
||||
] as unknown as ShippingProcessingProjection['uiState']['lifecycleEntries'],
|
||||
blocking_reason: null,
|
||||
primary_action: null,
|
||||
secondary_actions: [],
|
||||
},
|
||||
})],
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
await flushPromises();
|
||||
|
||||
const row = wrapper.find('[data-testid="shipping-processing-file-DOC-10"]');
|
||||
const orderReview = row.findAll('button').find((button) => button.text().includes('订单复核'));
|
||||
expect(orderReview?.attributes('disabled')).toBeDefined();
|
||||
await orderReview?.trigger('click');
|
||||
expect(wrapper.emitted('openLifecycleStage')).toBeUndefined();
|
||||
});
|
||||
});
|
||||
+528
-199
@@ -1,6 +1,6 @@
|
||||
/**
|
||||
* features/chat/components/shipping/ShippingConversationProcessingCard.vue
|
||||
* 用途:右侧「本次处理中」顶层任务卡——needs_action / processing / 处理记录。
|
||||
* 用途:右侧「批次进度中心」顶层任务卡——needs_action / processing / 处理记录。
|
||||
* 依赖:vue-i18n、ConversationProcessingProjection、conversationProcessingState、
|
||||
* conversationProcessingDisplay、actionPresentation、shippingProcessingLabels、SidebarProgressInline。
|
||||
* 逻辑:由 ShippingWorkflowTimeline 嵌入;只消费统一 projection / workItems;
|
||||
@@ -13,10 +13,11 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, ref, watch } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { ChevronDown, ChevronRight } from 'lucide-vue-next';
|
||||
import { ChevronDown, ChevronRight, MoreHorizontal } from 'lucide-vue-next';
|
||||
import type {
|
||||
ConversationProcessingProjection,
|
||||
ConversationProcessingUserTask,
|
||||
ShippingProcessingLifecycleEntry,
|
||||
ShippingProcessingProjection,
|
||||
} from '@/features/chat/types/shipping.api.types';
|
||||
import { getPrimaryDocumentName } from '@/features/chat/shipping/conversationProcessingDisplay';
|
||||
@@ -30,11 +31,12 @@ import {
|
||||
} from '@/features/chat/shipping/conversationProcessingState';
|
||||
import {
|
||||
resolveShippingProcessingMessage,
|
||||
resolveShippingProcessingReasonLabel,
|
||||
resolveShippingProcessingStageLabel,
|
||||
resolveShippingProcessingStatusLabel,
|
||||
shippingProcessingSourceTypeKey,
|
||||
shippingProcessingStageKey,
|
||||
} from '@/features/chat/shipping/shippingProcessingLabels';
|
||||
import { resolveConversationTaskActionPresentation } from '@/features/shipping-progress/actionPresentation';
|
||||
import { flattenBusinessFileProjections } from '@/features/chat/shipping/conversationProcessingProjection';
|
||||
import { resolveConversationTaskActionPresentation, resolveProcessingActionPresentation } from '@/features/shipping-progress/actionPresentation';
|
||||
import SidebarProgressInline from '@/features/shipping-progress/components/SidebarProgressInline.vue';
|
||||
import type { ActionPresentation, ActionPresentationItem } from '@/features/shipping-progress/types';
|
||||
|
||||
@@ -46,6 +48,15 @@ const props = defineProps<{
|
||||
conversationId?: string | null;
|
||||
/** 后端截断提示:history 还有未返回内容时在处理记录底部展示 */
|
||||
hasMoreHistory?: boolean;
|
||||
/** 批次中心按状态 → EML → 文件展示,不再嵌入任务级 15 节点进度。 */
|
||||
workbenchMode?: boolean;
|
||||
/** 批次四阶段筛选;保留状态/EML 分组,仅隐藏不属于当前阶段的任务。 */
|
||||
lifecycleFilter?: 'all' | 'intake_parse' | 'order_review' | 'fulfillment_prep' | 'upload_complete';
|
||||
/** 批次中心本地搜索:只筛叶子文件,父 EML 卡仍保留。 */
|
||||
fileSearchQuery?: string;
|
||||
/** 后端已授权下载的正式 Excel 对应 OT。 */
|
||||
downloadableTaskNos?: string[];
|
||||
selectedDownloadTaskNos?: string[];
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
@@ -59,6 +70,12 @@ const emit = defineEmits<{
|
||||
intakeAction: [payload: { item: ShippingProcessingProjection; action: string }];
|
||||
/** OT 卡内统一进度动作。 */
|
||||
projectionAction: [payload: { projection: ShippingProcessingProjection; item: ActionPresentationItem }];
|
||||
downloadArtifact: [taskNo: string];
|
||||
toggleDownloadSelection: [taskNo: string];
|
||||
/** 文件级生命周期入口;父级只切换工作台展示,不在导航时写入业务状态。 */
|
||||
openLifecycleStage: [payload: { projection: ShippingProcessingProjection; entry: ShippingProcessingLifecycleEntry }];
|
||||
/** 单文件低频操作;仅当后端明确授权该动作时才发出。 */
|
||||
fileAction: [payload: { projection: ShippingProcessingProjection; action: string }];
|
||||
}>();
|
||||
|
||||
const { t, te } = useI18n();
|
||||
@@ -66,27 +83,63 @@ const uiState = createConversationProcessingUiState();
|
||||
/** 处理记录整组默认折叠。 */
|
||||
const historySectionExpanded = ref(false);
|
||||
|
||||
/** 批次中心文件叶子行;EML 仅是聚合容器,文件状态、原因与动作必须取叶子自身投影。 */
|
||||
type WorkbenchFileRow = {
|
||||
kind: 'document';
|
||||
object_key: string;
|
||||
label: string;
|
||||
filename?: string | null;
|
||||
document_id?: number | null;
|
||||
status_label?: string | null;
|
||||
po_number?: string | null;
|
||||
projection?: ShippingProcessingProjection;
|
||||
};
|
||||
const LIFECYCLE_STAGE_CODES = ['intake_parse', 'order_review', 'fulfillment_prep', 'upload_complete'] as const;
|
||||
type LifecycleStageCode = typeof LIFECYCLE_STAGE_CODES[number];
|
||||
const LIFECYCLE_STAGE_LABEL_KEYS: Record<string, string> = {
|
||||
intake_parse: 'intakeParse',
|
||||
order_review: 'orderReview',
|
||||
fulfillment_prep: 'fulfillmentPrep',
|
||||
upload_complete: 'uploadComplete',
|
||||
};
|
||||
|
||||
/** 唯一进度源:统一 conversation_processing / work_items 合成投影。 */
|
||||
const activeProjection = computed((): ConversationProcessingProjection | null => (
|
||||
props.projection || null
|
||||
));
|
||||
|
||||
/** 尚未建 OT、仍应展示在「待处理材料」的 Intake 工作项。 */
|
||||
const pendingIntakeItems = computed((): ShippingProcessingProjection[] => {
|
||||
const items = Array.isArray(props.workItems) ? props.workItems : [];
|
||||
return items.filter((item) => {
|
||||
if (item.workItemType !== 'order_intake') return false;
|
||||
return !['completed', 'cancelled'].includes(String(item.status || ''));
|
||||
});
|
||||
});
|
||||
|
||||
const hasContent = computed(() => Boolean(
|
||||
activeProjection.value
|
||||
|| pendingIntakeItems.value.length,
|
||||
activeProjection.value,
|
||||
));
|
||||
|
||||
const completedTasks = computed(() => activeProjection.value?.completed || []);
|
||||
const historyTasks = computed(() => activeProjection.value?.history || []);
|
||||
const statusGroups = computed(() => activeProjection.value?.status_groups || null);
|
||||
const completedTasks = computed(() => statusGroups.value?.completed || activeProjection.value?.completed || []);
|
||||
const historyTasks = computed(() => statusGroups.value
|
||||
? [...statusGroups.value.cancelled, ...statusGroups.value.archived]
|
||||
: (activeProjection.value?.history || []));
|
||||
/** EML 卡必须由后端 userGroup 分入独立用户区;旧任务保留 needs_action 兼容归属。 */
|
||||
const failedTasks = computed(() => statusGroups.value?.failed
|
||||
|| (activeProjection.value?.needs_action || []).filter((task) => task.userGroup === 'failed' || !task.userGroup));
|
||||
const waitingHumanTasks = computed(() => statusGroups.value?.waiting_human
|
||||
|| (activeProjection.value?.needs_action || []).filter((task) => task.userGroup === 'waiting_human'));
|
||||
const processingTasks = computed(() => statusGroups.value?.processing || activeProjection.value?.processing || []);
|
||||
|
||||
/** 任务只要含一个命中附件即保留,避免筛选后打散同一封 EML 的上下文。 */
|
||||
function taskMatchesLifecycleFilter(task: ConversationProcessingUserTask): boolean {
|
||||
const filter = props.lifecycleFilter || 'all';
|
||||
const query = String(props.fileSearchQuery || '').trim().toLowerCase();
|
||||
// 非批次中心保留历史任务卡兼容展示;只有批次中心才按叶子文件筛选。
|
||||
if (!props.workbenchMode && filter === 'all' && !query) return true;
|
||||
return workbenchFileRows(task).some((file) => {
|
||||
if (filter !== 'all' && String(file.projection?.uiState?.lifecycleStage || '') !== filter) return false;
|
||||
return !query || [file.filename, file.label, file.po_number]
|
||||
.some((value) => String(value || '').toLowerCase().includes(query));
|
||||
});
|
||||
}
|
||||
const visibleFailedTasks = computed(() => failedTasks.value.filter(taskMatchesLifecycleFilter));
|
||||
const visibleWaitingHumanTasks = computed(() => waitingHumanTasks.value.filter(taskMatchesLifecycleFilter));
|
||||
const visibleProcessingTasks = computed(() => processingTasks.value.filter(taskMatchesLifecycleFilter));
|
||||
const visibleCompletedTasks = computed(() => completedTasks.value.filter(taskMatchesLifecycleFilter));
|
||||
|
||||
/** history 中非取消 →「历史版本」。 */
|
||||
const historyVersionTasks = computed(() => historyTasks.value.filter(
|
||||
@@ -97,6 +150,8 @@ const historyVersionTasks = computed(() => historyTasks.value.filter(
|
||||
const cancelledHistoryTasks = computed(() => historyTasks.value.filter(
|
||||
(task) => String(task.status_label || '').trim().toLowerCase() === 'cancelled',
|
||||
));
|
||||
const visibleHistoryVersionTasks = computed(() => historyVersionTasks.value.filter(taskMatchesLifecycleFilter));
|
||||
const visibleCancelledHistoryTasks = computed(() => cancelledHistoryTasks.value.filter(taskMatchesLifecycleFilter));
|
||||
|
||||
/** 处理记录标题计数:当前返回的 completed + history。 */
|
||||
const recordTaskCount = computed(() => (
|
||||
@@ -123,7 +178,7 @@ function projectionForTask(task: ConversationProcessingUserTask): ShippingProces
|
||||
if (!taskNo) return null;
|
||||
const items = Array.isArray(props.workItems) ? props.workItems : [];
|
||||
return items.find((item) => (
|
||||
item.workItemType === 'order_task'
|
||||
(item.workItemType === 'order_task' || item.workItemType === 'order_intake')
|
||||
&& String(item.workItemNo || '').trim() === taskNo
|
||||
)) || null;
|
||||
}
|
||||
@@ -187,6 +242,7 @@ function canExpandFileDetails(task: ConversationProcessingUserTask): boolean {
|
||||
* 处理记录(completed/history)永不展实时进度。
|
||||
*/
|
||||
function progressModeForTask(task: ConversationProcessingUserTask): 'full' | 'compact' | 'hidden' {
|
||||
if (props.workbenchMode) return 'hidden';
|
||||
if (!projectionForTask(task)) return 'hidden';
|
||||
const group = String(task.group || '').trim();
|
||||
if (group === 'completed' || group === 'history') return 'hidden';
|
||||
@@ -204,6 +260,249 @@ function taskLabel(_task: ConversationProcessingUserTask): string {
|
||||
return t('chat.shippingProcessing.multiPdfTaskTitle');
|
||||
}
|
||||
|
||||
/** EML 聚合标题优先使用后端邮件文件名,普通文件则显示主文件名。 */
|
||||
function groupTitle(task: ConversationProcessingUserTask): string {
|
||||
const projection = projectionForTask(task);
|
||||
const children = task.aggregateChildren || [];
|
||||
const projectionFilename = String(projection?.sourceSummary?.filename || '').trim();
|
||||
const emlChild = children.find((child) => (
|
||||
String(child.sourceSummary?.filename || '').trim().toLowerCase().endsWith('.eml')
|
||||
));
|
||||
const emailChild = children.find((child) => Boolean(child.sourceSummary?.emailSubject));
|
||||
const isEml = projection?.sourceType === 'eml'
|
||||
&& Boolean(
|
||||
emlChild
|
||||
|| emailChild
|
||||
|| projection?.sourceSummary?.emailSubject
|
||||
|| projectionFilename.toLowerCase().endsWith('.eml'),
|
||||
);
|
||||
if (!isEml) return projection?.sourceSummary?.filename || task.title || taskLabel(task);
|
||||
// 后端在 EML 聚合根 sourceSummary 写入 Intake 原始邮件资产名;子附件列表不含
|
||||
// 邮件本体时仍必须显示该 .eml,不能回退成 Intake 编号或任一 PDF 文件名。
|
||||
if (projectionFilename.toLowerCase().endsWith('.eml')) return projectionFilename;
|
||||
if (emlChild?.sourceSummary?.filename) return emlChild.sourceSummary.filename;
|
||||
if (projection?.sourceSummary?.emailSubject) return `EML · ${projection.sourceSummary.emailSubject}`;
|
||||
if (emailChild?.sourceSummary?.emailSubject) return `EML · ${emailChild.sourceSummary.emailSubject}`;
|
||||
if (task.aggregateSummary?.intakeNo) {
|
||||
return `EML · ${task.aggregateSummary?.intakeNo || task.user_task_no}`;
|
||||
}
|
||||
return task.title || taskLabel(task);
|
||||
}
|
||||
|
||||
/** 工作台文件行:只展示后端 document objects,避免用任务标题冒充文件。 */
|
||||
function workbenchFileRows(task: ConversationProcessingUserTask): WorkbenchFileRow[] {
|
||||
const children = task.aggregateChildren || [];
|
||||
// [AUTHORITY] 批次模式只以实时 work_items 作为文件行真相。Conversation task 的
|
||||
// children / objects / document_names 是 Run 级兼容快照,可用于非批次卡历史展示,
|
||||
// 但不得重建批次中的文件名、状态、阶段或操作。
|
||||
if (props.workbenchMode) {
|
||||
const taskNo = String(task.user_task_no || '').trim();
|
||||
const liveLeaves = (props.workItems || []).flatMap((item) => {
|
||||
const isTaskRoot = String(item.rootOrderTaskNo || '').trim() === taskNo
|
||||
|| String(item.workItemNo || '').trim() === taskNo;
|
||||
if (!isTaskRoot) return [];
|
||||
// EML 父项的实时附件只存在于 aggregateChildren;展开同一份后端 work_item,
|
||||
// 不读取 conversation task 兼容快照。
|
||||
return item.sourceType === 'eml'
|
||||
? flattenBusinessFileProjections([item])
|
||||
: [item];
|
||||
}).filter((item) => (
|
||||
Number(item.sourceSummary?.documentId || 0) > 0
|
||||
));
|
||||
const seenLiveDocumentIds = new Set<number>();
|
||||
const uniqueLiveLeaves = liveLeaves.filter((item) => {
|
||||
const documentId = Number(item.sourceSummary?.documentId || 0);
|
||||
if (seenLiveDocumentIds.has(documentId)) return false;
|
||||
seenLiveDocumentIds.add(documentId);
|
||||
return true;
|
||||
});
|
||||
return uniqueLiveLeaves.map((item, index) => {
|
||||
const documentId = Number(item.sourceSummary?.documentId || 0);
|
||||
const filename = String(item.sourceSummary?.filename || '').trim();
|
||||
return {
|
||||
kind: 'document' as const,
|
||||
object_key: documentId ? `DOC-${documentId}` : `${taskNo}-live-${item.workItemNo || index}`,
|
||||
label: filename || item.workItemNo || `文件 ${index + 1}`,
|
||||
filename: filename || item.workItemNo || `文件 ${index + 1}`,
|
||||
document_id: documentId || null,
|
||||
status_label: String(item.uiState?.status || item.userStatus || item.status || ''),
|
||||
po_number: item.sourceSummary?.poNumber || null,
|
||||
projection: item,
|
||||
};
|
||||
});
|
||||
}
|
||||
if (children.length) {
|
||||
return flattenBusinessFileProjections(children).map((child, index) => {
|
||||
const filename = String(child.sourceSummary?.filename || '').trim();
|
||||
const documentId = Number(child.sourceSummary?.documentId || 0) || 0;
|
||||
return {
|
||||
kind: 'document' as const,
|
||||
object_key: documentId ? `DOC-${documentId}` : `${task.user_task_no}-aggregate-${child.workItemNo || index}`,
|
||||
label: filename || child.workItemNo || `文件 ${index + 1}`,
|
||||
filename: filename || child.workItemNo || `文件 ${index + 1}`,
|
||||
status_label: String(child.uiState?.status || child.userStatus || child.status || ''),
|
||||
po_number: child.sourceSummary?.poNumber || null,
|
||||
projection: child,
|
||||
};
|
||||
});
|
||||
}
|
||||
const documents = (task.objects || []).filter((item) => (
|
||||
item.kind === 'document'
|
||||
&& !String(item.filename || item.label || '').trim().toLowerCase().endsWith('.eml')
|
||||
));
|
||||
if (documents.length) {
|
||||
// direct_pdf 没有 EML aggregate_children;将唯一根 work_item 绑定到其文件行,
|
||||
// 使状态、原因和操作仍然来自同一份后端 ui_state,而不是丢失操作或回退 legacy 字段。
|
||||
const directFileProjection = projectionForTask(task);
|
||||
return documents.map((item) => ({
|
||||
kind: 'document' as const,
|
||||
object_key: item.object_key,
|
||||
label: item.label,
|
||||
filename: item.filename,
|
||||
document_id: item.document_id,
|
||||
status_label: item.status_label,
|
||||
po_number: directFileProjection?.sourceSummary?.poNumber || null,
|
||||
projection: directFileProjection?.sourceType === 'direct_pdf'
|
||||
? directFileProjection
|
||||
: undefined,
|
||||
}));
|
||||
}
|
||||
const taskName = String(task.title || '').trim().toLowerCase();
|
||||
if (taskName.endsWith('.eml') || task.aggregateSummary?.intakeNo) return [];
|
||||
// 新版实时投影可只返回 work_items,不重复旧 task.objects;此时以同一 OT 的叶子
|
||||
// document 投影生成行,确保文件状态、阶段和按钮仍完全来自后端。
|
||||
const taskNo = String(task.user_task_no || '').trim();
|
||||
const liveLeaves = (props.workItems || []).filter((item) => (
|
||||
String(item.rootOrderTaskNo || '').trim() === taskNo
|
||||
&& Number(item.sourceSummary?.documentId || 0) > 0
|
||||
&& !item.childOrderTasks?.length
|
||||
));
|
||||
if (liveLeaves.length) {
|
||||
return liveLeaves.map((item, index) => {
|
||||
const documentId = Number(item.sourceSummary?.documentId || 0);
|
||||
const filename = String(item.sourceSummary?.filename || '').trim();
|
||||
return {
|
||||
kind: 'document' as const,
|
||||
object_key: documentId ? `DOC-${documentId}` : `${taskNo}-live-${item.workItemNo || index}`,
|
||||
label: filename || item.workItemNo || `文件 ${index + 1}`,
|
||||
filename: filename || item.workItemNo || `文件 ${index + 1}`,
|
||||
document_id: documentId || null,
|
||||
status_label: String(item.uiState?.status || item.userStatus || item.status || ''),
|
||||
po_number: item.sourceSummary?.poNumber || null,
|
||||
projection: item,
|
||||
};
|
||||
});
|
||||
}
|
||||
return (task.document_names || []).map((filename, index) => ({
|
||||
kind: 'document' as const,
|
||||
object_key: `${task.user_task_no}-document-${index}`,
|
||||
label: filename,
|
||||
filename,
|
||||
status_label: task.status_label,
|
||||
po_number: null,
|
||||
}));
|
||||
}
|
||||
|
||||
/** 阶段筛选只收窄附件行,EML 卡本身仍保留以便用户识别邮件来源。 */
|
||||
function visibleWorkbenchFileRows(task: ConversationProcessingUserTask): WorkbenchFileRow[] {
|
||||
const filter = props.lifecycleFilter || 'all';
|
||||
const rows = workbenchFileRows(task);
|
||||
const query = String(props.fileSearchQuery || '').trim().toLowerCase();
|
||||
return rows.filter((file) => {
|
||||
if (filter !== 'all' && String(file.projection?.uiState?.lifecycleStage || '') !== filter) return false;
|
||||
if (!query) return true;
|
||||
return [file.filename, file.label, file.po_number].some((value) => String(value || '').toLowerCase().includes(query));
|
||||
});
|
||||
}
|
||||
|
||||
function fileDownloadTaskNo(file: WorkbenchFileRow): string | null {
|
||||
const taskNo = String(file.projection?.rootOrderTaskNo || '').trim();
|
||||
return taskNo && (props.downloadableTaskNos || []).includes(taskNo) ? taskNo : null;
|
||||
}
|
||||
function isDownloadSelected(taskNo: string): boolean {
|
||||
return (props.selectedDownloadTaskNos || []).includes(taskNo);
|
||||
}
|
||||
|
||||
/** 状态组标题按文件计数,与批次总览保持同一口径。 */
|
||||
function groupFileCount(tasks: ConversationProcessingUserTask[]): number {
|
||||
const seen = new Set<string>();
|
||||
return tasks.reduce((total, task) => total + workbenchFileRows(task).reduce((count, file) => {
|
||||
const filename = String(file.filename || file.label || '').trim().toLowerCase();
|
||||
if (filename.endsWith('.eml')) return count;
|
||||
const key = String(('document_id' in file ? file.document_id : undefined)
|
||||
|| file.object_key || file.filename || file.label || '').trim();
|
||||
if (!key || seen.has(key)) return count;
|
||||
seen.add(key);
|
||||
return count + 1;
|
||||
}, 0), 0);
|
||||
}
|
||||
|
||||
function workbenchFileStatus(file: WorkbenchFileRow, task: ConversationProcessingUserTask): string {
|
||||
const status = file.projection
|
||||
? (file.projection.uiState?.status || file.projection.userStatus || file.projection.status)
|
||||
: (file.status_label || task.status_label || '');
|
||||
return resolveShippingProcessingStatusLabel(String(status), te, t);
|
||||
}
|
||||
|
||||
function workbenchFileReason(file: WorkbenchFileRow, task: ConversationProcessingUserTask): string {
|
||||
if (file.projection) {
|
||||
const reason = file.projection.uiState
|
||||
? file.projection.uiState.blocking_reason
|
||||
: file.projection.blockingReason;
|
||||
return resolveShippingProcessingReasonLabel(reason, te, t);
|
||||
}
|
||||
return taskReasonLabel(task);
|
||||
}
|
||||
|
||||
/** 文件工作面显示四阶段业务语义;技术 stage 仍保留给进度诊断,不用于入口可达性。 */
|
||||
function workbenchFileLifecycleStage(file: WorkbenchFileRow): string {
|
||||
const code = String(file.projection?.uiState?.lifecycleStage || '').trim();
|
||||
const key = LIFECYCLE_STAGE_LABEL_KEYS[code];
|
||||
return key
|
||||
? t(`chat.shippingNoticeUi.stage.${key}`)
|
||||
: t('chat.shippingProcessing.stageLabel.waiting_system_start');
|
||||
}
|
||||
|
||||
/** 生命周期入口仅消费后端投影;禁止按候选、Case 或阶段顺序二次裁决。 */
|
||||
function lifecycleEntries(file: WorkbenchFileRow): ShippingProcessingLifecycleEntry[] {
|
||||
return file.projection?.uiState?.lifecycleEntries || [];
|
||||
}
|
||||
|
||||
function lifecycleEntry(file: WorkbenchFileRow, target: LifecycleStageCode): ShippingProcessingLifecycleEntry | null {
|
||||
return lifecycleEntries(file).find((entry) => entry.code === target) || null;
|
||||
}
|
||||
|
||||
function lifecycleEntryState(file: WorkbenchFileRow, target: LifecycleStageCode): 'available' | 'current' | 'unavailable' {
|
||||
const state = lifecycleEntry(file, target)?.state;
|
||||
// [FAIL-CLOSED] 服务端新增或异常状态不得被 UI 当作可进入工作台。
|
||||
return state === 'available' || state === 'current' ? state : 'unavailable';
|
||||
}
|
||||
|
||||
function lifecycleEntryLabel(file: WorkbenchFileRow, target: LifecycleStageCode): string {
|
||||
void file;
|
||||
// 阶段状态由按钮颜色和 disabled 表达,避免重复的“当前可处理/前置未完成”文案挤占文件行。
|
||||
return t(`chat.shippingNoticeUi.stage.${LIFECYCLE_STAGE_LABEL_KEYS[target]}`);
|
||||
}
|
||||
|
||||
function onOpenLifecycleStage(file: WorkbenchFileRow, lifecycleStage: LifecycleStageCode) {
|
||||
const entry = lifecycleEntry(file, lifecycleStage);
|
||||
if (!file.projection || !entry) return;
|
||||
if (lifecycleEntryState(file, lifecycleStage) === 'unavailable') return;
|
||||
emit('openLifecycleStage', { projection: file.projection, entry });
|
||||
}
|
||||
|
||||
/** 叶子文件动作由自身 ui_state 裁决;没有叶子投影时不伪造可操作按钮。 */
|
||||
function filePrimaryActionItem(file: WorkbenchFileRow): ActionPresentationItem | null {
|
||||
return file.projection
|
||||
? resolveProcessingActionPresentation(file.projection, { surface: 'right' }).primary
|
||||
: null;
|
||||
}
|
||||
|
||||
function onFileProjectionAction(file: WorkbenchFileRow) {
|
||||
const action = filePrimaryActionItem(file);
|
||||
if (file.projection && action) emit('projectionAction', { projection: file.projection, item: action });
|
||||
}
|
||||
|
||||
/**
|
||||
* 主文件副标题:有主文件名时渲染「主文件:{name}」。
|
||||
*/
|
||||
@@ -229,7 +528,38 @@ function fileCountLabel(task: ConversationProcessingUserTask): string {
|
||||
* 任务状态文案:优先统一 shippingProcessing,回退 shippingWorkflow。
|
||||
*/
|
||||
function statusLabel(task: ConversationProcessingUserTask): string {
|
||||
return resolveShippingProcessingStatusLabel(String(task.status_label || ''), te, t);
|
||||
return resolveShippingProcessingStatusLabel(
|
||||
String(task.uiState?.status || task.userStatus || task.status_label || ''),
|
||||
te,
|
||||
t,
|
||||
);
|
||||
}
|
||||
|
||||
/** 展示统一投影的真实履约阶段;识别候选不再冒充最终完成。 */
|
||||
function stageLabel(task: ConversationProcessingUserTask): string {
|
||||
const projection = projectionForTask(task);
|
||||
if (!projection) return '';
|
||||
return intakeStageLabel(projection);
|
||||
}
|
||||
|
||||
/** 展示后端 ui_state 已裁决的阻断原因;i18n 仅负责翻译,不映射或猜测业务原因。 */
|
||||
function taskReasonLabel(task: ConversationProcessingUserTask): string {
|
||||
const reason = task.uiState
|
||||
? task.uiState.blocking_reason
|
||||
: task.blockingReason;
|
||||
return resolveShippingProcessingReasonLabel(reason, te, t);
|
||||
}
|
||||
|
||||
/** 同一 EML 聚合卡状态计数;仅用后端下发的 aggregateSummary,不从 UI 状态推导。 */
|
||||
function aggregateStatusLabel(task: ConversationProcessingUserTask): string {
|
||||
const summary = task.aggregateSummary;
|
||||
if (!summary) return '';
|
||||
const parts: string[] = [];
|
||||
if (summary.completed) parts.push(t('chat.shippingProcessing.aggregate.completed', { count: summary.completed }));
|
||||
if (summary.processing) parts.push(t('chat.shippingProcessing.aggregate.processing', { count: summary.processing }));
|
||||
if (summary.needsAction) parts.push(t('chat.shippingProcessing.aggregate.needsAction', { count: summary.needsAction }));
|
||||
if (summary.failed) parts.push(t('chat.shippingProcessing.aggregate.failed', { count: summary.failed }));
|
||||
return parts.join(' · ');
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -256,6 +586,16 @@ function taskActionPresentation(task: ConversationProcessingUserTask): ActionPre
|
||||
return resolveConversationTaskActionPresentation(task, { surface: 'right' });
|
||||
}
|
||||
|
||||
/**
|
||||
* 待确认分组的批次重解析入口:仅消费该分组任务的后端授权,避免按钮脱离业务上下文。
|
||||
*/
|
||||
function waitingHumanBatchReparseTask(): ConversationProcessingUserTask | null {
|
||||
return visibleWaitingHumanTasks.value.find((task) => (
|
||||
task.available_actions?.includes('reparse_batch')
|
||||
&& String(task.run_no || '').trim()
|
||||
)) || null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 唯一主 CTA(实心按钮);处理记录只读卡不调用。
|
||||
*/
|
||||
@@ -270,10 +610,14 @@ function currentNeedLabel(task: ConversationProcessingUserTask): string {
|
||||
primaryAction?: { code?: string } | null;
|
||||
};
|
||||
const action = String(
|
||||
typedTask.primaryAction?.code
|
||||
?? task.primary_action
|
||||
?? task.available_actions?.[0]
|
||||
?? '',
|
||||
task.uiState
|
||||
? (task.uiState.primary_action?.code
|
||||
?? task.uiState.secondary_actions.find((item) => item.enabled)?.code
|
||||
?? '')
|
||||
: (typedTask.primaryAction?.code
|
||||
?? task.primary_action
|
||||
?? task.available_actions?.[0]
|
||||
?? ''),
|
||||
).trim().toLowerCase();
|
||||
const labels: Record<string, string> = {
|
||||
confirm_customer: 'chat.shippingProcessing.currentNeed.confirmCustomer',
|
||||
@@ -326,6 +670,7 @@ function shouldShowOverflowActions(_task: ConversationProcessingUserTask): boole
|
||||
* 是否渲染任务级主/次动作区(不含「展开文件详情」文件控制)。
|
||||
*/
|
||||
function shouldShowTaskLevelActions(task: ConversationProcessingUserTask): boolean {
|
||||
if (props.workbenchMode) return Boolean(primaryActionItem(task));
|
||||
if (projectionForTask(task)) return false;
|
||||
return Boolean(primaryActionItem(task) || secondaryActionItem(task));
|
||||
}
|
||||
@@ -364,7 +709,27 @@ function presentationActionLabel(task: ConversationProcessingUserTask, item: Act
|
||||
if (key && te(key)) return t(key);
|
||||
const extractionKey = `chat.shippingOrderExtractionAction.${code}`;
|
||||
if (te(extractionKey)) return t(extractionKey);
|
||||
return code;
|
||||
return t('chat.shippingProcessing.action.unknown');
|
||||
}
|
||||
|
||||
/**
|
||||
* 文件低频操作优先读取正式 ui_state;旧 availableActions 仅兼容未下发 ui_state 的旧投影。
|
||||
* 一旦后端提供 ui_state,遗留字段绝不能重新授予已撤销的操作。
|
||||
*/
|
||||
function canCancelFile(file: WorkbenchFileRow): boolean {
|
||||
const projection = file.projection;
|
||||
if (!projection) return false;
|
||||
if (projection.uiState) {
|
||||
return projection.uiState.secondary_actions.some(
|
||||
(action) => action.enabled && action.code === 'cancel_unit',
|
||||
);
|
||||
}
|
||||
return projection.availableActions.includes('cancel_unit');
|
||||
}
|
||||
|
||||
function onFileAction(file: WorkbenchFileRow, action: string) {
|
||||
if (!file.projection || action !== 'cancel_unit' || !canCancelFile(file)) return;
|
||||
emit('fileAction', { projection: file.projection, action });
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -391,93 +756,11 @@ function toggleHistorySection() {
|
||||
historySectionExpanded.value = !historySectionExpanded.value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Intake 材料标题:文件名 / 邮件主题 / Intake 编号。
|
||||
*/
|
||||
function intakeTitle(item: ShippingProcessingProjection): string {
|
||||
return String(
|
||||
item.sourceSummary?.filename
|
||||
|| item.sourceSummary?.emailSubject
|
||||
|| item.workItemNo
|
||||
|| '',
|
||||
).trim() || item.workItemNo;
|
||||
}
|
||||
|
||||
/**
|
||||
* Intake 状态文案。
|
||||
*/
|
||||
function intakeStatusLabel(item: ShippingProcessingProjection): string {
|
||||
return resolveShippingProcessingStatusLabel(item.status, te, t);
|
||||
}
|
||||
|
||||
/**
|
||||
* Intake 阶段文案。
|
||||
*/
|
||||
function intakeStageLabel(item: ShippingProcessingProjection): string {
|
||||
const key = shippingProcessingStageKey(item.stage);
|
||||
return te(key) ? t(key) : String(item.stage || '');
|
||||
}
|
||||
|
||||
/**
|
||||
* Intake 来源类型文案。
|
||||
*/
|
||||
function intakeSourceLabel(item: ShippingProcessingProjection): string {
|
||||
const key = shippingProcessingSourceTypeKey(item.sourceType);
|
||||
return te(key) ? t(key) : String(item.sourceType || '');
|
||||
}
|
||||
|
||||
/**
|
||||
* Intake / OT 门禁与失败恢复元信息(Gate / Attempt / 资产状态)。
|
||||
*/
|
||||
function intakeRecoveryMeta(item: ShippingProcessingProjection): string[] {
|
||||
const parts: string[] = [];
|
||||
const gate = item.currentGate;
|
||||
const reason = String(
|
||||
gate?.blockingReasonCode
|
||||
|| item.sourceSummary?.failureReasonCode
|
||||
|| '',
|
||||
).trim();
|
||||
if (reason) {
|
||||
parts.push(t('chat.shippingProcessing.failureReason', { code: reason }));
|
||||
}
|
||||
const attempt = gate?.attemptNo ?? item.sourceSummary?.parseAttemptCount;
|
||||
if (attempt != null && Number(attempt) > 0) {
|
||||
parts.push(t('chat.shippingProcessing.parseAttempt', { count: Number(attempt) }));
|
||||
}
|
||||
const assetStatus = String(item.sourceSummary?.assetStatus || '').trim();
|
||||
if (assetStatus) {
|
||||
const key = `chat.shippingProcessing.assetStatus.${assetStatus}`;
|
||||
parts.push(te(key) ? t(key) : t('chat.shippingProcessing.assetStatusLabel', { status: assetStatus }));
|
||||
}
|
||||
if (gate?.gateCode) {
|
||||
parts.push(t('chat.shippingProcessing.gateCode', { code: gate.gateCode }));
|
||||
}
|
||||
return parts;
|
||||
}
|
||||
|
||||
/**
|
||||
* Intake 可见动作(仅展示 retry_parse)。
|
||||
*/
|
||||
function visibleIntakeActions(item: ShippingProcessingProjection): string[] {
|
||||
const actions = Array.isArray(item.availableActions) ? item.availableActions : [];
|
||||
return actions.filter((code) => code === 'retry_parse');
|
||||
}
|
||||
|
||||
/**
|
||||
* Intake 动作文案。
|
||||
*/
|
||||
function intakeActionLabel(action: string): string {
|
||||
if (action === 'retry_parse') return t('chat.shippingProcessing.retryFromFailure');
|
||||
return action;
|
||||
}
|
||||
|
||||
/**
|
||||
* 触发 Intake 级动作。
|
||||
*/
|
||||
function onIntakeAction(item: ShippingProcessingProjection, action: string) {
|
||||
const code = String(action || '').trim();
|
||||
if (!code) return;
|
||||
emit('intakeAction', { item, action: code });
|
||||
return resolveShippingProcessingStageLabel(item.stage, te, t);
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -488,70 +771,15 @@ function onIntakeAction(item: ShippingProcessingProjection, action: string) {
|
||||
data-testid="shipping-conversation-processing-card"
|
||||
>
|
||||
<section
|
||||
v-if="pendingIntakeItems.length"
|
||||
data-testid="shipping-processing-group-order-intake"
|
||||
>
|
||||
<div class="mb-1.5 text-[11px] font-semibold uppercase tracking-wide text-violet-700 dark:text-violet-300">
|
||||
{{ t('chat.shippingProcessing.pendingMaterials') }}
|
||||
· {{ pendingIntakeItems.length }}
|
||||
</div>
|
||||
<div class="space-y-2">
|
||||
<article
|
||||
v-for="item in pendingIntakeItems"
|
||||
:key="item.workItemNo"
|
||||
class="rounded-lg border border-default bg-surface px-2.5 py-2"
|
||||
:data-testid="`shipping-processing-intake-${item.workItemNo}`"
|
||||
:data-source-type="item.sourceType"
|
||||
:data-status="item.status"
|
||||
>
|
||||
<div class="text-sm font-semibold text-primary">
|
||||
{{ intakeTitle(item) }}
|
||||
</div>
|
||||
<div class="mt-0.5 flex flex-wrap gap-x-2 gap-y-0.5 text-[11px] text-secondary">
|
||||
<span>{{ intakeSourceLabel(item) }}</span>
|
||||
<span>{{ intakeStatusLabel(item) }}</span>
|
||||
<span v-if="intakeStageLabel(item)">{{ intakeStageLabel(item) }}</span>
|
||||
</div>
|
||||
<div
|
||||
v-if="intakeRecoveryMeta(item).length"
|
||||
class="mt-1 flex flex-wrap gap-x-2 gap-y-0.5 text-[11px] text-rose-700 dark:text-rose-300"
|
||||
data-testid="shipping-processing-intake-recovery"
|
||||
>
|
||||
<span
|
||||
v-for="(meta, idx) in intakeRecoveryMeta(item)"
|
||||
:key="`${item.workItemNo}-meta-${idx}`"
|
||||
>{{ meta }}</span>
|
||||
</div>
|
||||
<div
|
||||
v-if="visibleIntakeActions(item).length"
|
||||
class="mt-1.5 flex flex-wrap gap-1.5"
|
||||
data-testid="shipping-processing-intake-actions"
|
||||
>
|
||||
<button
|
||||
v-for="action in visibleIntakeActions(item)"
|
||||
:key="`${item.workItemNo}-${action}`"
|
||||
type="button"
|
||||
class="rounded-md border border-default bg-surface px-2 py-0.5 text-[11px] text-secondary hover:text-primary"
|
||||
:data-testid="`shipping-processing-intake-action-${action}`"
|
||||
@click="onIntakeAction(item, action)"
|
||||
>
|
||||
{{ intakeActionLabel(action) }}
|
||||
</button>
|
||||
</div>
|
||||
</article>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section
|
||||
v-if="activeProjection?.needs_action.length"
|
||||
data-testid="shipping-processing-group-needs_action"
|
||||
v-if="visibleFailedTasks.length"
|
||||
data-testid="shipping-processing-group-failed"
|
||||
>
|
||||
<div class="mb-1.5 text-[11px] font-semibold uppercase tracking-wide text-amber-700 dark:text-amber-300">
|
||||
{{ resolveShippingProcessingMessage('groupNeedsAction', te, t, { count: activeProjection.needs_action.length }) }}
|
||||
{{ t('chat.shippingProcessing.batchWorkbench.groups.failed', { count: groupFileCount(visibleFailedTasks) }) }}
|
||||
</div>
|
||||
<div class="space-y-2">
|
||||
<article
|
||||
v-for="task in activeProjection.needs_action"
|
||||
v-for="task in visibleFailedTasks"
|
||||
:key="task.user_task_no"
|
||||
class="rounded-lg border px-2.5 py-2 transition"
|
||||
:class="[
|
||||
@@ -569,19 +797,24 @@ function onIntakeAction(item: ShippingProcessingProjection, action: string) {
|
||||
@click="onSelectTask(task)"
|
||||
>
|
||||
<div class="text-sm font-semibold text-primary">
|
||||
{{ resolveShippingProcessingMessage('taskTitle', te, t, { label: taskLabel(task) }) }}
|
||||
{{ workbenchMode ? groupTitle(task) : resolveShippingProcessingMessage('taskTitle', te, t, { label: taskLabel(task) }) }}
|
||||
</div>
|
||||
<div class="mt-0.5 flex flex-wrap gap-x-2 gap-y-0.5 text-[11px] text-secondary">
|
||||
<div v-if="!workbenchMode" class="mt-0.5 flex flex-wrap gap-x-2 gap-y-0.5 text-[11px] text-secondary">
|
||||
<span v-if="fileCountLabel(task)">{{ fileCountLabel(task) }}</span>
|
||||
<span>{{ statusLabel(task) }}</span>
|
||||
</div>
|
||||
<div
|
||||
v-if="primaryFileLabel(task)"
|
||||
v-if="!workbenchMode && primaryFileLabel(task)"
|
||||
class="mt-0.5 truncate text-[11px] text-muted"
|
||||
data-testid="shipping-processing-task-primary-file"
|
||||
>
|
||||
{{ primaryFileLabel(task) }}
|
||||
</div>
|
||||
<div v-if="taskReasonLabel(task)" class="mt-1 text-[11px] text-rose-600 dark:text-rose-300">
|
||||
{{ taskReasonLabel(task) }}
|
||||
</div>
|
||||
<div v-if="aggregateStatusLabel(task)" class="mt-1 text-[11px] text-secondary">
|
||||
{{ aggregateStatusLabel(task) }}
|
||||
</div>
|
||||
<div
|
||||
v-if="task.recent_append_count"
|
||||
class="mt-1 text-[11px] font-medium text-brand-700 dark:text-brand-300"
|
||||
@@ -595,27 +828,41 @@ function onIntakeAction(item: ShippingProcessingProjection, action: string) {
|
||||
{{ resolveShippingProcessingMessage('justCreated', te, t) }}
|
||||
</div>
|
||||
</button>
|
||||
<div
|
||||
v-if="task.group === 'needs_action' && currentNeedLabel(task)"
|
||||
class="mt-1 text-[11px] text-secondary"
|
||||
data-testid="shipping-processing-current-need"
|
||||
>
|
||||
{{ t('chat.shippingProcessing.progress.currentNeedLabel') }}{{ currentNeedLabel(task) }}
|
||||
<div v-if="workbenchMode" class="mt-3 space-y-2 border-t border-rose-200/70 pt-2">
|
||||
<div v-for="file in visibleWorkbenchFileRows(task)" :key="file.object_key" class="grid gap-x-3 gap-y-1 rounded-md bg-white/70 px-2 py-1.5 text-[11px] sm:grid-cols-[minmax(10rem,1fr)_auto_auto] sm:items-center dark:bg-slate-950/30" :data-testid="`shipping-processing-file-${file.object_key}`">
|
||||
<div class="min-w-0"><span class="truncate font-medium text-primary">{{ file.filename || file.label }}</span><span class="ml-1 text-secondary">· {{ t('chat.shippingProcessing.batchWorkbench.fileEntries.po', { value: file.po_number || '-' }) }}</span></div>
|
||||
<div class="flex min-w-0 flex-wrap items-center gap-1">
|
||||
<span class="w-fit shrink-0 rounded-full bg-rose-100 px-2 py-0.5 font-medium text-rose-700">{{ workbenchFileStatus(file, task) || t('chat.shippingProcessing.batchWorkbench.groups.failedFallback') }}</span>
|
||||
<button v-if="filePrimaryActionItem(file)" type="button" class="rounded-md border border-rose-300 px-2 py-0.5 font-medium text-rose-700 hover:bg-rose-50" @click="onFileProjectionAction(file)">{{ presentationActionLabel(task, filePrimaryActionItem(file)!) }}</button>
|
||||
<label v-if="fileDownloadTaskNo(file)" class="inline-flex items-center gap-1 text-secondary"><input type="checkbox" :checked="isDownloadSelected(fileDownloadTaskNo(file)!)" @change="emit('toggleDownloadSelection', fileDownloadTaskNo(file)!)"><span class="sr-only">{{ t('chat.shippingProcessing.batchWorkbench.artifacts.select') }}</span></label>
|
||||
<button v-if="fileDownloadTaskNo(file)" type="button" class="rounded-md border border-emerald-300 px-2 py-0.5 font-medium text-emerald-700 hover:bg-emerald-50" @click="emit('downloadArtifact', fileDownloadTaskNo(file)!)">{{ t('chat.shippingProcessing.batchWorkbench.artifacts.download') }}</button>
|
||||
</div>
|
||||
<div class="col-span-full flex min-h-7 items-center justify-between gap-3 border-t border-default pt-1.5">
|
||||
<div class="min-w-0 truncate text-secondary"><span>{{ t('chat.shippingProcessing.batchWorkbench.fileEntries.stage', { value: workbenchFileLifecycleStage(file) }) }}</span><span v-if="workbenchFileReason(file, task)" class="text-rose-600 dark:text-rose-300" :title="workbenchFileReason(file, task)"> · {{ t('chat.shippingProcessing.batchWorkbench.fileEntries.blocker', { value: workbenchFileReason(file, task) }) }}</span></div>
|
||||
<div v-if="lifecycleEntries(file).length" class="flex shrink-0 flex-wrap justify-end gap-1">
|
||||
<button v-for="stage in LIFECYCLE_STAGE_CODES" :key="stage" type="button" class="rounded border px-1.5 py-1 text-[11px] font-medium disabled:cursor-not-allowed" :class="lifecycleEntryState(file, stage) === 'current' ? 'border-brand-600 bg-brand-600 text-white hover:bg-brand-700' : lifecycleEntryState(file, stage) === 'available' ? 'border-emerald-300 bg-emerald-50 text-emerald-800 hover:bg-emerald-100' : 'border-default bg-surface-muted text-muted'" :disabled="lifecycleEntryState(file, stage) === 'unavailable'" :title="lifecycleEntryState(file, stage) === 'unavailable' ? t('chat.shippingProcessing.batchWorkbench.fileEntries.unavailable') : undefined" @click="onOpenLifecycleStage(file, stage)">{{ lifecycleEntryLabel(file, stage) }}</button>
|
||||
</div>
|
||||
<details v-if="canCancelFile(file)" class="relative shrink-0">
|
||||
<summary class="list-none rounded border border-default p-1 text-secondary hover:bg-surface-muted" :aria-label="t('chat.shippingProcessing.action.more')"><MoreHorizontal class="h-3.5 w-3.5" /></summary>
|
||||
<button type="button" class="absolute right-0 top-7 z-10 whitespace-nowrap rounded border border-rose-200 bg-surface px-2 py-1 text-[11px] text-rose-700 shadow-sm hover:bg-rose-50" data-testid="shipping-processing-file-cancel" @click="onFileAction(file, 'cancel_unit')">{{ t('chat.shippingProcessing.actions.cancelFile') }}</button>
|
||||
</details>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<SidebarProgressInline
|
||||
v-if="progressModeForTask(task) !== 'hidden' && projectionForTask(task)"
|
||||
v-if="!workbenchMode && progressModeForTask(task) !== 'hidden' && projectionForTask(task)"
|
||||
class="mt-1.5 border-t border-current/10 pt-1.5"
|
||||
:projection="projectionForTask(task)!"
|
||||
:compact="progressModeForTask(task) === 'compact'"
|
||||
@action="(item) => emit('projectionAction', { projection: projectionForTask(task)!, item })"
|
||||
/>
|
||||
<div
|
||||
v-if="shouldShowTaskLevelActions(task) || (!projectionForTask(task) && canExpandFileDetails(task))"
|
||||
v-if="shouldShowTaskLevelActions(task) || (!workbenchMode && !projectionForTask(task) && canExpandFileDetails(task))"
|
||||
class="mt-1.5 flex flex-wrap items-center gap-x-3 gap-y-1"
|
||||
data-testid="shipping-processing-task-actions"
|
||||
>
|
||||
<button
|
||||
v-if="!projectionForTask(task) && primaryActionItem(task)"
|
||||
v-if="(!workbenchMode && !projectionForTask(task)) && primaryActionItem(task)"
|
||||
type="button"
|
||||
class="rounded-md border border-brand-300 bg-brand-600 px-2.5 py-1 text-[11px] font-medium text-white hover:bg-brand-700 dark:border-brand-700 dark:bg-brand-700 dark:hover:bg-brand-600"
|
||||
:data-testid="`shipping-processing-action-${primaryActionItem(task)!.actionCode}`"
|
||||
@@ -630,15 +877,75 @@ function onIntakeAction(item: ShippingProcessingProjection, action: string) {
|
||||
</section>
|
||||
|
||||
<section
|
||||
v-if="activeProjection?.processing.length"
|
||||
data-testid="shipping-processing-group-processing"
|
||||
v-if="visibleWaitingHumanTasks.length"
|
||||
data-testid="shipping-processing-group-waiting_human"
|
||||
>
|
||||
<div class="mb-1.5 text-[11px] font-semibold uppercase tracking-wide text-sky-700 dark:text-sky-300">
|
||||
{{ resolveShippingProcessingMessage('groupProcessing', te, t, { count: activeProjection.processing.length }) }}
|
||||
<div class="mb-1.5 flex items-center justify-between gap-2 text-[11px] font-semibold uppercase tracking-wide text-amber-700 dark:text-amber-300">
|
||||
{{ t('chat.shippingProcessing.batchWorkbench.groups.waitingHuman', { count: groupFileCount(visibleWaitingHumanTasks) }) }}
|
||||
<button
|
||||
v-if="workbenchMode && waitingHumanBatchReparseTask()"
|
||||
type="button"
|
||||
class="inline-flex items-center gap-1 rounded-md border border-amber-300 bg-amber-50 px-2.5 py-1 text-[11px] font-medium normal-case text-amber-800 hover:bg-amber-100 dark:border-amber-700 dark:bg-amber-950/30 dark:text-amber-200"
|
||||
data-testid="shipping-processing-batch-reparse"
|
||||
@click="onTaskAction(waitingHumanBatchReparseTask()!, 'reparse_batch')"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.lineOps.reparse_batch') }}
|
||||
</button>
|
||||
</div>
|
||||
<div class="space-y-2">
|
||||
<article
|
||||
v-for="task in activeProjection.processing"
|
||||
v-for="task in visibleWaitingHumanTasks"
|
||||
:key="task.user_task_no"
|
||||
class="rounded-lg border border-amber-400 bg-amber-50/80 px-2.5 py-2 transition dark:border-amber-700 dark:bg-amber-950/30"
|
||||
:data-testid="`shipping-processing-task-${task.user_task_no}`"
|
||||
:data-focused="focusedTaskNo === task.user_task_no ? '1' : '0'"
|
||||
>
|
||||
<button type="button" class="w-full text-left" @click="onSelectTask(task)">
|
||||
<div class="text-sm font-semibold text-primary">{{ workbenchMode ? groupTitle(task) : resolveShippingProcessingMessage('taskTitle', te, t, { label: taskLabel(task) }) }}</div>
|
||||
<div v-if="!workbenchMode" class="mt-0.5 flex flex-wrap gap-x-2 gap-y-0.5 text-[11px] text-secondary">
|
||||
<span v-if="fileCountLabel(task)">{{ fileCountLabel(task) }}</span>
|
||||
</div>
|
||||
<div v-if="taskReasonLabel(task)" class="mt-1 text-[11px] text-rose-600 dark:text-rose-300">{{ taskReasonLabel(task) }}</div>
|
||||
<div v-if="aggregateStatusLabel(task)" class="mt-1 text-[11px] text-secondary">{{ aggregateStatusLabel(task) }}</div>
|
||||
</button>
|
||||
<div v-if="workbenchMode" class="mt-3 space-y-2 border-t border-amber-200/70 pt-2">
|
||||
<div v-for="file in visibleWorkbenchFileRows(task)" :key="file.object_key" class="grid gap-x-3 gap-y-1 rounded-md bg-white/70 px-2 py-1.5 text-[11px] sm:grid-cols-[minmax(10rem,1fr)_auto_auto] sm:items-center dark:bg-slate-950/30" :data-testid="`shipping-processing-file-${file.object_key}`">
|
||||
<div class="min-w-0"><span class="truncate font-medium text-primary">{{ file.filename || file.label }}</span><span class="ml-1 text-secondary">· {{ t('chat.shippingProcessing.batchWorkbench.fileEntries.po', { value: file.po_number || '-' }) }}</span></div>
|
||||
<div class="flex min-w-0 flex-wrap items-center gap-1"><span class="w-fit shrink-0 rounded-full bg-amber-100 px-2 py-0.5 font-medium text-amber-800">{{ workbenchFileStatus(file, task) || t('chat.shippingProcessing.batchWorkbench.groups.waitingFallback') }}</span><button v-if="filePrimaryActionItem(file)" type="button" class="rounded-md bg-brand-600 px-2 py-0.5 font-medium text-white hover:bg-brand-700" @click="onFileProjectionAction(file)">{{ presentationActionLabel(task, filePrimaryActionItem(file)!) }}</button><label v-if="fileDownloadTaskNo(file)" class="inline-flex items-center gap-1 text-secondary"><input type="checkbox" :checked="isDownloadSelected(fileDownloadTaskNo(file)!)" @change="emit('toggleDownloadSelection', fileDownloadTaskNo(file)!)"><span class="sr-only">{{ t('chat.shippingProcessing.batchWorkbench.artifacts.select') }}</span></label><button v-if="fileDownloadTaskNo(file)" type="button" class="rounded-md border border-emerald-300 px-2 py-0.5 font-medium text-emerald-700 hover:bg-emerald-50" @click="emit('downloadArtifact', fileDownloadTaskNo(file)!)">{{ t('chat.shippingProcessing.batchWorkbench.artifacts.download') }}</button></div>
|
||||
<div class="col-span-full flex min-h-7 items-center justify-between gap-3 border-t border-default pt-1.5"><div class="min-w-0 truncate text-secondary"><span>{{ t('chat.shippingProcessing.batchWorkbench.fileEntries.stage', { value: workbenchFileLifecycleStage(file) }) }}</span><span v-if="workbenchFileReason(file, task)" class="text-rose-600 dark:text-rose-300" :title="workbenchFileReason(file, task)"> · {{ t('chat.shippingProcessing.batchWorkbench.fileEntries.blocker', { value: workbenchFileReason(file, task) }) }}</span></div><div v-if="lifecycleEntries(file).length" class="flex shrink-0 flex-wrap justify-end gap-1">
|
||||
<button v-for="stage in LIFECYCLE_STAGE_CODES" :key="stage" type="button" class="rounded border px-1.5 py-1 text-[11px] font-medium disabled:cursor-not-allowed" :class="lifecycleEntryState(file, stage) === 'current' ? 'border-brand-600 bg-brand-600 text-white hover:bg-brand-700' : lifecycleEntryState(file, stage) === 'available' ? 'border-emerald-300 bg-emerald-50 text-emerald-800 hover:bg-emerald-100' : 'border-default bg-surface-muted text-muted'" :disabled="lifecycleEntryState(file, stage) === 'unavailable'" :title="lifecycleEntryState(file, stage) === 'unavailable' ? t('chat.shippingProcessing.batchWorkbench.fileEntries.unavailable') : undefined" @click="onOpenLifecycleStage(file, stage)">{{ lifecycleEntryLabel(file, stage) }}</button>
|
||||
</div><details v-if="canCancelFile(file)" class="relative shrink-0"><summary class="list-none rounded border border-default p-1 text-secondary hover:bg-surface-muted" :aria-label="t('chat.shippingProcessing.action.more')"><MoreHorizontal class="h-3.5 w-3.5" /></summary><button type="button" class="absolute right-0 top-7 z-10 whitespace-nowrap rounded border border-rose-200 bg-surface px-2 py-1 text-[11px] text-rose-700 shadow-sm hover:bg-rose-50" data-testid="shipping-processing-file-cancel" @click="onFileAction(file, 'cancel_unit')">{{ t('chat.shippingProcessing.actions.cancelFile') }}</button></details></div>
|
||||
</div>
|
||||
</div>
|
||||
<SidebarProgressInline
|
||||
v-if="!workbenchMode && projectionForTask(task)"
|
||||
class="mt-1.5 border-t border-current/10 pt-1.5"
|
||||
:projection="projectionForTask(task)!"
|
||||
:compact="false"
|
||||
@action="(item) => emit('projectionAction', { projection: projectionForTask(task)!, item })"
|
||||
/>
|
||||
<button
|
||||
v-if="!workbenchMode && primaryActionItem(task)"
|
||||
type="button"
|
||||
class="mt-2 rounded-md bg-brand-600 px-2.5 py-1.5 text-[11px] font-medium text-white hover:bg-brand-700"
|
||||
@click="onTaskAction(task, primaryActionItem(task)!.actionCode)"
|
||||
>
|
||||
{{ presentationActionLabel(task, primaryActionItem(task)!) }}
|
||||
</button>
|
||||
</article>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section
|
||||
v-if="visibleProcessingTasks.length"
|
||||
data-testid="shipping-processing-group-processing"
|
||||
>
|
||||
<div class="mb-1.5 text-[11px] font-semibold uppercase tracking-wide text-sky-700 dark:text-sky-300">
|
||||
{{ t('chat.shippingProcessing.batchWorkbench.groups.processing', { count: groupFileCount(visibleProcessingTasks) }) }}
|
||||
</div>
|
||||
<div class="space-y-2">
|
||||
<article
|
||||
v-for="task in visibleProcessingTasks"
|
||||
:key="task.user_task_no"
|
||||
class="rounded-lg border border-default bg-surface px-2.5 py-2"
|
||||
:class="focusedTaskNo === task.user_task_no
|
||||
@@ -653,19 +960,21 @@ function onIntakeAction(item: ShippingProcessingProjection, action: string) {
|
||||
@click="onSelectTask(task)"
|
||||
>
|
||||
<div class="text-sm font-semibold text-primary">
|
||||
{{ resolveShippingProcessingMessage('taskTitle', te, t, { label: taskLabel(task) }) }}
|
||||
{{ workbenchMode ? groupTitle(task) : resolveShippingProcessingMessage('taskTitle', te, t, { label: taskLabel(task) }) }}
|
||||
</div>
|
||||
<div class="mt-0.5 flex flex-wrap gap-x-2 gap-y-0.5 text-[11px] text-secondary">
|
||||
<div v-if="!workbenchMode" class="mt-0.5 flex flex-wrap gap-x-2 gap-y-0.5 text-[11px] text-secondary">
|
||||
<span v-if="fileCountLabel(task)">{{ fileCountLabel(task) }}</span>
|
||||
<span>{{ statusLabel(task) }}</span>
|
||||
</div>
|
||||
<div
|
||||
v-if="primaryFileLabel(task)"
|
||||
v-if="!workbenchMode && primaryFileLabel(task)"
|
||||
class="mt-0.5 truncate text-[11px] text-muted"
|
||||
data-testid="shipping-processing-task-primary-file"
|
||||
>
|
||||
{{ primaryFileLabel(task) }}
|
||||
</div>
|
||||
<div v-if="aggregateStatusLabel(task)" class="mt-1 text-[11px] text-secondary">
|
||||
{{ aggregateStatusLabel(task) }}
|
||||
</div>
|
||||
<div
|
||||
v-if="task.recent_append_count"
|
||||
class="mt-1 text-[11px] font-medium text-brand-700 dark:text-brand-300"
|
||||
@@ -679,8 +988,16 @@ function onIntakeAction(item: ShippingProcessingProjection, action: string) {
|
||||
{{ resolveShippingProcessingMessage('justCreated', te, t) }}
|
||||
</div>
|
||||
</button>
|
||||
<div v-if="workbenchMode" class="mt-3 space-y-2 border-t border-sky-200/70 pt-2">
|
||||
<div v-for="file in visibleWorkbenchFileRows(task)" :key="file.object_key" class="grid gap-x-3 gap-y-1 rounded-md bg-surface-muted/40 px-2 py-1.5 text-[11px] sm:grid-cols-[minmax(10rem,1fr)_auto_auto] sm:items-center" :data-testid="`shipping-processing-file-${file.object_key}`">
|
||||
<div class="min-w-0"><span class="truncate font-medium text-primary">{{ file.filename || file.label }}</span><span class="ml-1 text-secondary">· {{ t('chat.shippingProcessing.batchWorkbench.fileEntries.po', { value: file.po_number || '-' }) }}</span></div><div class="flex min-w-0 flex-wrap items-center gap-1"><span class="w-fit shrink-0 rounded-full bg-sky-100 px-2 py-0.5 font-medium text-sky-700">{{ workbenchFileStatus(file, task) || t('chat.shippingProcessing.batchWorkbench.groups.processingFallback') }}</span><button v-if="filePrimaryActionItem(file)" type="button" class="rounded-md border border-brand-300 px-2 py-0.5 font-medium text-brand-700 hover:bg-brand-50" @click="onFileProjectionAction(file)">{{ presentationActionLabel(task, filePrimaryActionItem(file)!) }}</button><label v-if="fileDownloadTaskNo(file)" class="inline-flex items-center gap-1 text-secondary"><input type="checkbox" :checked="isDownloadSelected(fileDownloadTaskNo(file)!)" @change="emit('toggleDownloadSelection', fileDownloadTaskNo(file)!)"><span class="sr-only">{{ t('chat.shippingProcessing.batchWorkbench.artifacts.select') }}</span></label><button v-if="fileDownloadTaskNo(file)" type="button" class="rounded-md border border-emerald-300 px-2 py-0.5 font-medium text-emerald-700 hover:bg-emerald-50" @click="emit('downloadArtifact', fileDownloadTaskNo(file)!)">{{ t('chat.shippingProcessing.batchWorkbench.artifacts.download') }}</button></div>
|
||||
<div class="col-span-full flex min-h-7 items-center justify-between gap-3 border-t border-default pt-1.5"><div class="min-w-0 truncate text-secondary"><span>{{ t('chat.shippingProcessing.batchWorkbench.fileEntries.stage', { value: workbenchFileLifecycleStage(file) }) }}</span><span v-if="workbenchFileReason(file, task)" class="text-rose-600" :title="workbenchFileReason(file, task)"> · {{ t('chat.shippingProcessing.batchWorkbench.fileEntries.blocker', { value: workbenchFileReason(file, task) }) }}</span></div><div v-if="lifecycleEntries(file).length" class="flex shrink-0 flex-wrap justify-end gap-1">
|
||||
<button v-for="stage in LIFECYCLE_STAGE_CODES" :key="stage" type="button" class="rounded border px-1.5 py-1 text-[11px] font-medium disabled:cursor-not-allowed" :class="lifecycleEntryState(file, stage) === 'current' ? 'border-brand-600 bg-brand-600 text-white hover:bg-brand-700' : lifecycleEntryState(file, stage) === 'available' ? 'border-emerald-300 bg-emerald-50 text-emerald-800 hover:bg-emerald-100' : 'border-default bg-surface-muted text-muted'" :disabled="lifecycleEntryState(file, stage) === 'unavailable'" :title="lifecycleEntryState(file, stage) === 'unavailable' ? t('chat.shippingProcessing.batchWorkbench.fileEntries.unavailable') : undefined" @click="onOpenLifecycleStage(file, stage)">{{ lifecycleEntryLabel(file, stage) }}</button>
|
||||
</div><details v-if="canCancelFile(file)" class="relative shrink-0"><summary class="list-none rounded border border-default p-1 text-secondary hover:bg-surface-muted" :aria-label="t('chat.shippingProcessing.action.more')"><MoreHorizontal class="h-3.5 w-3.5" /></summary><button type="button" class="absolute right-0 top-7 z-10 whitespace-nowrap rounded border border-rose-200 bg-surface px-2 py-1 text-[11px] text-rose-700 shadow-sm hover:bg-rose-50" data-testid="shipping-processing-file-cancel" @click="onFileAction(file, 'cancel_unit')">{{ t('chat.shippingProcessing.actions.cancelFile') }}</button></details></div>
|
||||
</div>
|
||||
</div>
|
||||
<SidebarProgressInline
|
||||
v-if="progressModeForTask(task) !== 'hidden' && projectionForTask(task)"
|
||||
v-if="!workbenchMode && progressModeForTask(task) !== 'hidden' && projectionForTask(task)"
|
||||
class="mt-1.5 border-t border-current/10 pt-1.5"
|
||||
:projection="projectionForTask(task)!"
|
||||
:compact="progressModeForTask(task) === 'compact'"
|
||||
@@ -692,7 +1009,7 @@ function onIntakeAction(item: ShippingProcessingProjection, action: string) {
|
||||
data-testid="shipping-processing-task-actions"
|
||||
>
|
||||
<button
|
||||
v-if="!projectionForTask(task) && primaryActionItem(task)"
|
||||
v-if="!workbenchMode && !projectionForTask(task) && primaryActionItem(task)"
|
||||
type="button"
|
||||
class="rounded-md border border-brand-300 bg-brand-600 px-2.5 py-1 text-[11px] font-medium text-white hover:bg-brand-700 dark:border-brand-700 dark:bg-brand-700 dark:hover:bg-brand-600"
|
||||
:data-testid="`shipping-processing-action-${primaryActionItem(task)!.actionCode}`"
|
||||
@@ -701,7 +1018,7 @@ function onIntakeAction(item: ShippingProcessingProjection, action: string) {
|
||||
{{ presentationActionLabel(task, primaryActionItem(task)!) }}
|
||||
</button>
|
||||
<button
|
||||
v-if="canExpandFileDetails(task)"
|
||||
v-if="!workbenchMode && canExpandFileDetails(task)"
|
||||
type="button"
|
||||
class="inline-flex items-center gap-1 text-[11px] text-secondary underline-offset-2 hover:text-primary hover:underline"
|
||||
data-testid="shipping-processing-expand-files"
|
||||
@@ -724,7 +1041,7 @@ function onIntakeAction(item: ShippingProcessingProjection, action: string) {
|
||||
</button>
|
||||
</div>
|
||||
<button
|
||||
v-else-if="canExpandFileDetails(task)"
|
||||
v-else-if="!workbenchMode && canExpandFileDetails(task)"
|
||||
type="button"
|
||||
class="mt-1.5 inline-flex items-center gap-1 text-[11px] text-secondary underline-offset-2 hover:text-primary hover:underline"
|
||||
data-testid="shipping-processing-expand-files"
|
||||
@@ -785,7 +1102,7 @@ function onIntakeAction(item: ShippingProcessingProjection, action: string) {
|
||||
data-testid="shipping-processing-history-body"
|
||||
>
|
||||
<div
|
||||
v-if="completedTasks.length"
|
||||
v-if="visibleCompletedTasks.length"
|
||||
data-testid="shipping-processing-history-completed"
|
||||
>
|
||||
<div class="mb-1 text-[11px] font-medium text-emerald-700 dark:text-emerald-300">
|
||||
@@ -793,7 +1110,7 @@ function onIntakeAction(item: ShippingProcessingProjection, action: string) {
|
||||
</div>
|
||||
<div class="space-y-2">
|
||||
<article
|
||||
v-for="task in completedTasks"
|
||||
v-for="task in visibleCompletedTasks"
|
||||
:key="task.user_task_no"
|
||||
class="rounded-lg border border-default bg-surface/80 px-2.5 py-2"
|
||||
:data-testid="`shipping-processing-task-${task.user_task_no}`"
|
||||
@@ -805,6 +1122,7 @@ function onIntakeAction(item: ShippingProcessingProjection, action: string) {
|
||||
<div class="mt-0.5 flex flex-wrap gap-x-2 gap-y-0.5 text-[11px] text-secondary">
|
||||
<span v-if="fileCountLabel(task)">{{ fileCountLabel(task) }}</span>
|
||||
<span>{{ statusLabel(task) }}</span>
|
||||
<span v-if="stageLabel(task)">· {{ stageLabel(task) }}</span>
|
||||
</div>
|
||||
<div
|
||||
v-if="primaryFileLabel(task)"
|
||||
@@ -813,6 +1131,17 @@ function onIntakeAction(item: ShippingProcessingProjection, action: string) {
|
||||
>
|
||||
{{ primaryFileLabel(task) }}
|
||||
</div>
|
||||
<div v-if="taskReasonLabel(task)" class="mt-1 text-[11px] text-rose-600 dark:text-rose-300">
|
||||
{{ taskReasonLabel(task) }}
|
||||
</div>
|
||||
<div v-if="workbenchMode" class="mt-3 space-y-2 border-t border-emerald-200/70 pt-2">
|
||||
<div v-for="file in visibleWorkbenchFileRows(task)" :key="file.object_key" class="grid gap-x-3 gap-y-1 rounded-md bg-emerald-50/40 px-2 py-1.5 text-[11px] sm:grid-cols-[minmax(10rem,1fr)_auto_auto] sm:items-center" :data-testid="`shipping-processing-file-${file.object_key}`">
|
||||
<div class="min-w-0"><span class="truncate font-medium text-primary">{{ file.filename || file.label }}</span><span class="ml-1 text-secondary">· {{ t('chat.shippingProcessing.batchWorkbench.fileEntries.po', { value: file.po_number || '-' }) }}</span></div><div class="flex min-w-0 flex-wrap items-center gap-1"><span class="w-fit shrink-0 rounded-full bg-emerald-100 px-2 py-0.5 font-medium text-emerald-700">{{ workbenchFileStatus(file, task) }}</span><label v-if="fileDownloadTaskNo(file)" class="inline-flex items-center gap-1 text-secondary"><input type="checkbox" :checked="isDownloadSelected(fileDownloadTaskNo(file)!)" @change="emit('toggleDownloadSelection', fileDownloadTaskNo(file)!)"><span class="sr-only">{{ t('chat.shippingProcessing.batchWorkbench.artifacts.select') }}</span></label><button v-if="fileDownloadTaskNo(file)" type="button" class="rounded-md border border-emerald-300 px-2 py-0.5 font-medium text-emerald-700 hover:bg-emerald-50" @click="emit('downloadArtifact', fileDownloadTaskNo(file)!)">{{ t('chat.shippingProcessing.batchWorkbench.artifacts.download') }}</button></div>
|
||||
<div class="col-span-full flex min-h-7 items-center justify-between gap-3 border-t border-default pt-1.5"><div class="min-w-0 truncate text-secondary"><span>{{ t('chat.shippingProcessing.batchWorkbench.fileEntries.stage', { value: workbenchFileLifecycleStage(file) }) }}</span><span v-if="workbenchFileReason(file, task)" class="text-rose-600" :title="workbenchFileReason(file, task)"> · {{ t('chat.shippingProcessing.batchWorkbench.fileEntries.blocker', { value: workbenchFileReason(file, task) }) }}</span></div><div v-if="lifecycleEntries(file).length" class="flex shrink-0 flex-wrap justify-end gap-1">
|
||||
<button v-for="stage in LIFECYCLE_STAGE_CODES" :key="stage" type="button" class="rounded border px-1.5 py-1 text-[11px] font-medium disabled:cursor-not-allowed" :class="lifecycleEntryState(file, stage) === 'current' ? 'border-brand-600 bg-brand-600 text-white hover:bg-brand-700' : lifecycleEntryState(file, stage) === 'available' ? 'border-emerald-300 bg-emerald-50 text-emerald-800 hover:bg-emerald-100' : 'border-default bg-surface-muted text-muted'" :disabled="lifecycleEntryState(file, stage) === 'unavailable'" :title="lifecycleEntryState(file, stage) === 'unavailable' ? t('chat.shippingProcessing.batchWorkbench.fileEntries.unavailable') : undefined" @click="onOpenLifecycleStage(file, stage)">{{ lifecycleEntryLabel(file, stage) }}</button>
|
||||
</div></div>
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
v-if="recordViewDetailsItem(task)"
|
||||
type="button"
|
||||
@@ -827,7 +1156,7 @@ function onIntakeAction(item: ShippingProcessingProjection, action: string) {
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="historyVersionTasks.length"
|
||||
v-if="visibleHistoryVersionTasks.length"
|
||||
data-testid="shipping-processing-history-versions"
|
||||
>
|
||||
<div class="mb-1 text-[11px] font-medium text-slate-600 dark:text-slate-300">
|
||||
@@ -835,7 +1164,7 @@ function onIntakeAction(item: ShippingProcessingProjection, action: string) {
|
||||
</div>
|
||||
<div class="space-y-2">
|
||||
<article
|
||||
v-for="task in historyVersionTasks"
|
||||
v-for="task in visibleHistoryVersionTasks"
|
||||
:key="task.user_task_no"
|
||||
class="rounded-lg border border-default bg-surface/80 px-2.5 py-2"
|
||||
:data-testid="`shipping-processing-task-${task.user_task_no}`"
|
||||
@@ -869,7 +1198,7 @@ function onIntakeAction(item: ShippingProcessingProjection, action: string) {
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="cancelledHistoryTasks.length"
|
||||
v-if="visibleCancelledHistoryTasks.length"
|
||||
data-testid="shipping-processing-history-cancelled"
|
||||
>
|
||||
<div class="mb-1 text-[11px] font-medium text-slate-500 dark:text-slate-400">
|
||||
@@ -877,7 +1206,7 @@ function onIntakeAction(item: ShippingProcessingProjection, action: string) {
|
||||
</div>
|
||||
<div class="space-y-2">
|
||||
<article
|
||||
v-for="task in cancelledHistoryTasks"
|
||||
v-for="task in visibleCancelledHistoryTasks"
|
||||
:key="task.user_task_no"
|
||||
class="rounded-lg border border-dashed border-default bg-surface/60 px-2.5 py-2 opacity-90"
|
||||
:data-testid="`shipping-processing-task-${task.user_task_no}`"
|
||||
|
||||
+487
-16
@@ -5,11 +5,13 @@
|
||||
* 逻辑:断言不再渲染进度列表/刷新取消/完整 handling 卡片;失败重试与需处理继续处理互斥。
|
||||
*/
|
||||
import { mount } from '@vue/test-utils';
|
||||
import { ref } from 'vue';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { createI18n } from 'vue-i18n';
|
||||
import chatZhCn from '@/locales/zh-CN/chat.json';
|
||||
import ShippingOrderExtractionCard from './ShippingOrderExtractionCard.vue';
|
||||
import type { ShippingOrderExtractionState } from '../../types/chat.types';
|
||||
import { SHIPPING_WORKFLOW_KEY } from '../../shipping/useShippingNoticeWorkflow';
|
||||
|
||||
const i18n = createI18n({
|
||||
legacy: false,
|
||||
@@ -51,6 +53,477 @@ const buildState = (patch: Partial<ShippingOrderExtractionState> = {}): Shipping
|
||||
});
|
||||
|
||||
describe('ShippingOrderExtractionCard', () => {
|
||||
it('opens the authoritative conversation batch even when no single run number is available', () => {
|
||||
const wrapper = mount(ShippingOrderExtractionCard, {
|
||||
props: { state: buildState() },
|
||||
global: {
|
||||
plugins: [i18n],
|
||||
provide: {
|
||||
[SHIPPING_WORKFLOW_KEY as symbol]: {
|
||||
processing: ref({
|
||||
status_groups: {
|
||||
failed: [], waiting_human: [], processing: [{
|
||||
user_task_no: 'INTAKE:SNI-BATCH', title: 'batch.eml', file_count: 1,
|
||||
userGroup: 'processing', group: 'processing', aggregateChildren: [],
|
||||
}], completed: [], cancelled: [], archived: [],
|
||||
},
|
||||
}),
|
||||
processingWorkItems: ref([]),
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
expect(wrapper.get('[data-testid="shipping-order-extraction-open-batch-workbench"]').exists()).toBe(true);
|
||||
});
|
||||
|
||||
it('does not present historical handling items or CTA as current work when the live projection exists', () => {
|
||||
const wrapper = mount(ShippingOrderExtractionCard, {
|
||||
props: {
|
||||
state: buildState({
|
||||
status: 'review_required',
|
||||
availableActions: ['review_candidate'],
|
||||
primaryNotice: 'candidate_confirmation',
|
||||
handlingItems: [{
|
||||
category: 'candidate_confirmation', count: 2, reasonCodes: [],
|
||||
affectedRefs: [], primaryAction: 'review_candidate',
|
||||
}],
|
||||
}),
|
||||
},
|
||||
global: {
|
||||
plugins: [i18n],
|
||||
provide: {
|
||||
[SHIPPING_WORKFLOW_KEY as symbol]: {
|
||||
processing: ref({
|
||||
ui_state: { status: 'running' },
|
||||
summary: { total_files: 1, completed_files: 0, waiting_human_files: 0, failed_files: 0 },
|
||||
status_groups: {
|
||||
failed: [], waiting_human: [], processing: [{
|
||||
user_task_no: 'OT-LIVE', title: 'live.pdf', file_count: 1,
|
||||
userGroup: 'processing', group: 'processing', aggregateChildren: [],
|
||||
}], completed: [], cancelled: [], archived: [],
|
||||
},
|
||||
}),
|
||||
processingWorkItems: ref([]),
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
expect(wrapper.text()).not.toContain('候选待人工确认');
|
||||
expect(wrapper.find('[data-testid="shipping-order-extraction-handling-summary"]').exists()).toBe(false);
|
||||
expect(wrapper.find('[data-testid="shipping-order-extraction-primary-action"]').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it('collapses file-level progress when the batch workbench is open', () => {
|
||||
const wrapper = mount(ShippingOrderExtractionCard, {
|
||||
props: { state: buildState(), runNo: 'SNER-COMPACT', compactProgress: true },
|
||||
global: { plugins: [i18n], provide: { [SHIPPING_WORKFLOW_KEY as symbol]: { processingWorkItems: ref([]) } } },
|
||||
});
|
||||
|
||||
expect(wrapper.find('[data-testid="shipping-order-extraction-status-groups"]').exists()).toBe(false);
|
||||
expect(wrapper.find('[data-testid="shipping-order-extraction-open-batch-workbench"]').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it('uses unified EML aggregation and keeps candidate creation out of completed', async () => {
|
||||
const aggregate = {
|
||||
workItemType: 'order_task', workItemNo: 'INTAKE:SNI-1', sourceType: 'eml', rootOrderTaskNo: 'OT-1',
|
||||
shippingNoticeNo: null, runNo: 'SNER-EML', caseNo: null, conversationId: 'conv-1', submissionNo: 'SOS-1', intakeNo: 'SNI-1',
|
||||
status: 'processing', stage: 'candidate_creating', progressVersion: 1, lastActivityAt: '', currentGate: null, availableActions: [],
|
||||
sourceSummary: { emailSubject: null, filename: 'forwarder.eml', documentCount: 3, parsedDocumentCount: 3, candidateCount: 2, customerName: null, poNumber: null }, childOrderTasks: [],
|
||||
userStatus: 'running', userStage: 'candidate_creating', facts: { uploadState: 'not_created' },
|
||||
aggregateSummary: { intakeNo: 'SNI-1', total: 3, completed: 1, processing: 1, needsAction: 0, failed: 1, stages: ['completed', 'candidate_creating'], reasonCodes: ['upload_rpa_failed'] },
|
||||
aggregateChildren: [
|
||||
{ workItemType: 'order_task', workItemNo: 'OT-1', sourceType: 'eml', rootOrderTaskNo: 'OT-1', shippingNoticeNo: null, runNo: 'SNER-EML', caseNo: null, conversationId: 'conv-1', submissionNo: 'SOS-1', intakeNo: 'SNI-1', status: 'completed', stage: 'completed', progressVersion: 1, lastActivityAt: '', currentGate: null, availableActions: [], sourceSummary: { emailSubject: null, filename: 'done.pdf', documentCount: 1, parsedDocumentCount: 1, candidateCount: 1, customerName: null, poNumber: null }, childOrderTasks: [], userStatus: 'completed', userStage: 'completed', facts: { uploadState: 'succeeded' } },
|
||||
{ workItemType: 'order_task', workItemNo: 'OT-2', sourceType: 'eml', rootOrderTaskNo: 'OT-1', shippingNoticeNo: null, runNo: 'SNER-EML', caseNo: null, conversationId: 'conv-1', submissionNo: 'SOS-1', intakeNo: 'SNI-1', status: 'processing', stage: 'candidate_creating', progressVersion: 1, lastActivityAt: '', currentGate: null, availableActions: [], sourceSummary: { emailSubject: null, filename: 'candidate.pdf', documentCount: 1, parsedDocumentCount: 1, candidateCount: 1, customerName: null, poNumber: null }, childOrderTasks: [], userStatus: 'running', userStage: 'candidate_creating', facts: { uploadState: 'not_created' } },
|
||||
],
|
||||
} as any;
|
||||
const wrapper = mount(ShippingOrderExtractionCard, {
|
||||
props: { state: buildState(), runNo: 'SNER-EML' },
|
||||
global: { plugins: [i18n], provide: { [SHIPPING_WORKFLOW_KEY as symbol]: { processingWorkItems: ref([aggregate]) } } },
|
||||
});
|
||||
expect(wrapper.get('[data-testid="shipping-order-extraction-eml-aggregate"]').text()).toContain('已上传完成 1 · 处理中 1 · 异常 1');
|
||||
expect(wrapper.text()).not.toContain('已生成候选 3 个文件');
|
||||
await wrapper.get('[data-testid="shipping-order-extraction-eml-aggregate"] button').trigger('click');
|
||||
expect(wrapper.text()).toContain('candidate.pdf');
|
||||
expect(wrapper.text()).toContain('处理中 1');
|
||||
});
|
||||
|
||||
it('uses the current three PDF rows instead of stale Run review totals', () => {
|
||||
const currentPdfRows = ['4210020274.pdf', '4210020272.pdf', '4210020273.pdf'].map((fileName, index) => ({
|
||||
unitId: index + 1,
|
||||
documentId: index + 101,
|
||||
intakeId: 1,
|
||||
documentType: 'attachment',
|
||||
fileName,
|
||||
status: 'candidate_ready' as const,
|
||||
userVisibleStage: 'candidate_ready',
|
||||
reasonCode: null,
|
||||
}));
|
||||
const wrapper = mount(ShippingOrderExtractionCard, {
|
||||
props: {
|
||||
runNo: 'SNER-STALE-COUNTS',
|
||||
state: buildState({
|
||||
// 历史 Run/Case 累计不能污染当前邮件的三份有效 PDF 统计。
|
||||
summary: {
|
||||
totalDocuments: 20,
|
||||
pendingDocuments: 0,
|
||||
processingDocuments: 0,
|
||||
completedDocuments: 2,
|
||||
reviewRequiredDocuments: 21,
|
||||
failedDocuments: 0,
|
||||
cancelledDocuments: 0,
|
||||
candidateCount: 3,
|
||||
},
|
||||
documents: currentPdfRows,
|
||||
}),
|
||||
},
|
||||
global: { plugins: [i18n], provide: { [SHIPPING_WORKFLOW_KEY as symbol]: { processingWorkItems: ref([]) } } },
|
||||
});
|
||||
|
||||
// 当前卡片的总数、完成率和候选列表必须来自同一份有效 PDF 清单。
|
||||
expect(wrapper.text()).toContain('共 3 个文件');
|
||||
expect(wrapper.text()).toContain('0/3 已处理');
|
||||
expect(wrapper.text()).toContain('已生成候选 3 个文件');
|
||||
expect(wrapper.text()).not.toContain('23/20 已处理');
|
||||
expect(wrapper.text()).not.toContain('100% 完成');
|
||||
});
|
||||
|
||||
it('keeps its matched EML card when the side-panel poll temporarily omits the intake', async () => {
|
||||
const workItems = ref<any[]>([{
|
||||
workItemType: 'order_task', workItemNo: 'INTAKE:SNI-STABLE', sourceType: 'eml', rootOrderTaskNo: 'OT-STABLE',
|
||||
shippingNoticeNo: null, runNo: 'SNER-STABLE', caseNo: null, conversationId: 'conv-1', submissionNo: 'SOS-1', intakeNo: 'SNI-STABLE',
|
||||
status: 'processing', stage: 'candidate_creating', progressVersion: 1, lastActivityAt: '', currentGate: null, availableActions: [],
|
||||
sourceSummary: { emailSubject: null, filename: 'stable.eml', documentCount: 2, parsedDocumentCount: 2, candidateCount: 0, customerName: null, poNumber: null },
|
||||
childOrderTasks: [], userStatus: 'running', userStage: 'candidate_creating', facts: { uploadState: 'not_created' },
|
||||
aggregateSummary: { intakeNo: 'SNI-STABLE', total: 2, completed: 0, processing: 2, needsAction: 0, failed: 0, stages: ['candidate_creating'], reasonCodes: [] },
|
||||
aggregateChildren: [],
|
||||
}]);
|
||||
const wrapper = mount(ShippingOrderExtractionCard, {
|
||||
props: { state: buildState(), runNo: 'SNER-STABLE' },
|
||||
global: { plugins: [i18n], provide: { [SHIPPING_WORKFLOW_KEY as symbol]: { processingWorkItems: workItems } } },
|
||||
});
|
||||
|
||||
expect(wrapper.get('[data-testid="shipping-order-extraction-eml-aggregate"]').text()).toContain('stable.eml');
|
||||
// 关键断言:右侧轮询暂时省略本 Intake 时,中间消息卡仍保留其自身的 EML 形态。
|
||||
workItems.value = [];
|
||||
await wrapper.vm.$nextTick();
|
||||
expect(wrapper.get('[data-testid="shipping-order-extraction-eml-aggregate"]').text()).toContain('stable.eml');
|
||||
});
|
||||
|
||||
it('does not render a historical EML snapshot while the authoritative conversation projection is loading', () => {
|
||||
const historicalAggregate = {
|
||||
workItemType: 'order_task', workItemNo: 'INTAKE:SNI-HISTORY', sourceType: 'eml', intakeNo: 'SNI-HISTORY',
|
||||
sourceSummary: { filename: 'historical.eml', documentCount: 3 },
|
||||
aggregateSummary: { intakeNo: 'SNI-HISTORY', total: 3, completed: 0, processing: 3, needsAction: 0, failed: 0, stages: [], reasonCodes: [] },
|
||||
aggregateChildren: [],
|
||||
} as any;
|
||||
const wrapper = mount(ShippingOrderExtractionCard, {
|
||||
props: { state: buildState(), runNo: 'SNER-HISTORY' },
|
||||
global: { plugins: [i18n], provide: { [SHIPPING_WORKFLOW_KEY as symbol]: {
|
||||
processing: ref(null),
|
||||
processingWorkItems: ref([historicalAggregate]),
|
||||
initialLoading: ref(true),
|
||||
loading: ref(true),
|
||||
} } },
|
||||
});
|
||||
|
||||
expect(wrapper.find('[data-testid="shipping-order-extraction-eml-aggregate"]').exists()).toBe(false);
|
||||
expect(wrapper.find('[data-testid="shipping-order-extraction-projection-loading"]').exists()).toBe(true);
|
||||
expect(wrapper.text()).not.toContain('historical.eml');
|
||||
expect(wrapper.text()).not.toContain('系统处理中');
|
||||
});
|
||||
|
||||
it('does not render message document rows while the authoritative projection is loading', () => {
|
||||
const wrapper = mount(ShippingOrderExtractionCard, {
|
||||
props: { state: buildState({
|
||||
documents: [{
|
||||
unitId: 91,
|
||||
documentId: 191,
|
||||
documentType: 'attachment',
|
||||
fileName: 'message-snapshot.pdf',
|
||||
status: 'review_required',
|
||||
}],
|
||||
}) },
|
||||
global: { plugins: [i18n], provide: { [SHIPPING_WORKFLOW_KEY as symbol]: {
|
||||
processing: ref(null),
|
||||
processingWorkItems: ref([]),
|
||||
initialLoading: ref(true),
|
||||
loading: ref(true),
|
||||
} } },
|
||||
});
|
||||
|
||||
expect(wrapper.text()).not.toContain('message-snapshot.pdf');
|
||||
expect(wrapper.text()).not.toContain('系统处理中');
|
||||
});
|
||||
|
||||
it('expands an EML inside its status group and shows every child attachment state', async () => {
|
||||
const child = {
|
||||
workItemType: 'order_task', workItemNo: 'OT-CHILD-1', sourceType: 'eml', rootOrderTaskNo: 'OT-ROOT',
|
||||
shippingNoticeNo: null, runNo: 'SNER-DETAIL', caseNo: null, conversationId: 'conv-1', submissionNo: 'SOS-1', intakeNo: 'SNI-DETAIL',
|
||||
status: 'failed', stage: 'document_parsing', progressVersion: 1, lastActivityAt: '', currentGate: null, availableActions: [],
|
||||
sourceSummary: { emailSubject: null, filename: 'failed.pdf', documentCount: 1, parsedDocumentCount: 0, candidateCount: 0, customerName: null, poNumber: null },
|
||||
childOrderTasks: [], userStatus: 'running', userStage: 'document_parsing', facts: { uploadState: 'not_created' },
|
||||
// 后端新裁决与旧 userStatus 冲突时,摘要卡必须使用 ui_state,不能显示成“处理中”。
|
||||
uiState: { status: 'failed', stage: 'document_parsing', blocking_reason: { code: 'PARSE_FAILED' }, primary_action: null, secondary_actions: [] },
|
||||
blockingReason: { code: 'PARSE_FAILED' },
|
||||
} as any;
|
||||
const task = { user_task_no: 'INTAKE:SNI-DETAIL', title: 'mail.eml', file_count: 1, userGroup: 'failed', group: 'needs_action', aggregateChildren: [child], aggregateSummary: { intakeNo: 'SNI-DETAIL', total: 1, completed: 0, processing: 0, needsAction: 0, failed: 1, stages: ['document_parsing'], reasonCodes: ['PARSE_FAILED'] } } as any;
|
||||
const wrapper = mount(ShippingOrderExtractionCard, {
|
||||
props: { state: buildState(), runNo: 'SNER-DETAIL' },
|
||||
global: {
|
||||
plugins: [i18n],
|
||||
provide: {
|
||||
[SHIPPING_WORKFLOW_KEY as symbol]: {
|
||||
processing: ref({ status_groups: { failed: [task], waiting_human: [], processing: [], completed: [], cancelled: [], archived: [] } }),
|
||||
processingWorkItems: ref([]),
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
await wrapper.get('[data-testid="shipping-order-extraction-eml-failed-INTAKE:SNI-DETAIL"] button').trigger('click');
|
||||
expect(wrapper.get('[data-testid="shipping-order-extraction-eml-children"]').text()).toContain('failed.pdf');
|
||||
expect(wrapper.text()).toContain('异常 1');
|
||||
expect(wrapper.text()).toContain('当前步骤需要人工处理');
|
||||
expect(wrapper.text()).not.toContain('PARSE_FAILED');
|
||||
expect(wrapper.get('[data-testid="shipping-order-extraction-child-status-OT-CHILD-1"]')
|
||||
.classes()).toContain('text-rose-600');
|
||||
});
|
||||
|
||||
it('does not supplement an authoritative EML group from a second work-item snapshot', async () => {
|
||||
const child = {
|
||||
workItemType: 'order_task', workItemNo: 'OT-FALLBACK-1', sourceType: 'eml', rootOrderTaskNo: 'OT-FALLBACK',
|
||||
shippingNoticeNo: null, runNo: 'SNER-FALLBACK', caseNo: null, conversationId: 'conv-1', submissionNo: 'SOS-1', intakeNo: 'SNI-FALLBACK',
|
||||
status: 'processing', stage: 'document_parsing', progressVersion: 1, lastActivityAt: '', currentGate: null, availableActions: [],
|
||||
sourceSummary: { emailSubject: null, filename: 'inside.eml.pdf', documentCount: 1, parsedDocumentCount: 1, candidateCount: 0, customerName: null, poNumber: null },
|
||||
childOrderTasks: [], userStatus: 'running', userStage: 'document_parsing', facts: { uploadState: 'not_created' },
|
||||
} as any;
|
||||
const task = { user_task_no: 'INTAKE:SNI-FALLBACK', title: 'inside.eml', file_count: 1, userGroup: 'processing', group: 'processing', aggregateChildren: [], aggregateSummary: { intakeNo: 'SNI-FALLBACK', total: 1, completed: 0, processing: 1, needsAction: 0, failed: 0, stages: ['document_parsing'], reasonCodes: [] } } as any;
|
||||
const wrapper = mount(ShippingOrderExtractionCard, {
|
||||
props: { state: buildState(), runNo: 'SNER-FALLBACK' },
|
||||
global: { plugins: [i18n], provide: { [SHIPPING_WORKFLOW_KEY as symbol]: {
|
||||
processing: ref({ status_groups: { failed: [], waiting_human: [], processing: [task], completed: [], cancelled: [], archived: [] } }),
|
||||
processingWorkItems: ref([{ workItemType: 'order_intake', workItemNo: 'INTAKE:SNI-FALLBACK', sourceType: 'eml', intakeNo: 'SNI-FALLBACK', aggregateChildren: [child] } as any]),
|
||||
} } },
|
||||
});
|
||||
await wrapper.get('[data-testid="shipping-order-extraction-eml-processing-INTAKE:SNI-FALLBACK"] button').trigger('click');
|
||||
// 状态组出现后,子文件必须完全来自该组;不能用另一份 work_items 补数。
|
||||
expect(wrapper.find('[data-testid="shipping-order-extraction-eml-children"]').exists()).toBe(false);
|
||||
expect(wrapper.text()).not.toContain('inside.eml.pdf');
|
||||
});
|
||||
|
||||
it('uses the conversation projection total instead of the message Run snapshot total', () => {
|
||||
const task = {
|
||||
user_task_no: 'INTAKE:SNI-TOTAL', title: 'mail-total.eml', file_count: 2,
|
||||
userGroup: 'waiting_human', group: 'needs_action', aggregateChildren: [],
|
||||
aggregateSummary: { intakeNo: 'SNI-TOTAL', total: 2, completed: 0, processing: 0, needsAction: 2, failed: 0, stages: ['order_review'], reasonCodes: [] },
|
||||
} as any;
|
||||
const wrapper = mount(ShippingOrderExtractionCard, {
|
||||
props: { state: buildState({ summary: { ...buildState().summary, totalDocuments: 6 } }), runNo: 'SNER-TOTAL' },
|
||||
global: { plugins: [i18n], provide: { [SHIPPING_WORKFLOW_KEY as symbol]: {
|
||||
processing: ref({
|
||||
summary: { total_files: 2, completed_files: 0, waiting_human_files: 2, failed_files: 0 },
|
||||
ui_state: { status: 'waiting_human' },
|
||||
status_groups: { failed: [], waiting_human: [task], processing: [], completed: [], cancelled: [], archived: [] },
|
||||
}),
|
||||
processingWorkItems: ref([{ sourceType: 'eml', intakeNo: 'SNI-TOTAL', aggregateChildren: [{ sourceSummary: { filename: 'stale.pdf' } }] }]),
|
||||
} } },
|
||||
});
|
||||
|
||||
expect(wrapper.text()).toContain('共 2 个文件');
|
||||
// 关键断言:待人工处理不是完成,聊天摘要必须与批次中心 completed_files 同口径。
|
||||
expect(wrapper.text()).toContain('0/2 已处理');
|
||||
expect(wrapper.text()).not.toContain('共 6 个文件');
|
||||
expect(wrapper.text()).not.toContain('stale.pdf');
|
||||
});
|
||||
|
||||
it('counts unique EML attachment children instead of task rows', async () => {
|
||||
const childA = { workItemType: 'order_task', workItemNo: 'OT-A', sourceType: 'eml', intakeNo: 'SNI-COUNT', sourceSummary: { filename: 'a.pdf', documentId: 101, documentCount: 1 }, status: 'processing', stage: 'document_parsing', userStatus: 'running', facts: { uploadState: 'not_created' } } as any;
|
||||
const childB = { ...childA, workItemNo: 'OT-B', sourceSummary: { filename: 'b.pdf', documentId: 102, documentCount: 1 } } as any;
|
||||
const task = { user_task_no: 'INTAKE:SNI-COUNT', title: 'count.eml', file_count: 2, userGroup: 'processing', group: 'processing', aggregateChildren: [childA, childB], aggregateSummary: { intakeNo: 'SNI-COUNT', total: 2, completed: 0, processing: 2, needsAction: 0, failed: 0, stages: [], reasonCodes: [] } } as any;
|
||||
const wrapper = mount(ShippingOrderExtractionCard, {
|
||||
props: { state: buildState(), runNo: 'SNER-COUNT' },
|
||||
global: { plugins: [i18n], provide: { [SHIPPING_WORKFLOW_KEY as symbol]: { processing: ref({ status_groups: { failed: [], waiting_human: [], processing: [task], completed: [], cancelled: [], archived: [] } }), processingWorkItems: ref([]) } } },
|
||||
});
|
||||
expect(wrapper.text()).toContain('2 个文件');
|
||||
});
|
||||
|
||||
it('renders every projected file when the batch has two documents', () => {
|
||||
const wrapper = mount(ShippingOrderExtractionCard, {
|
||||
props: {
|
||||
state: buildState({
|
||||
summary: {
|
||||
totalDocuments: 2,
|
||||
pendingDocuments: 0,
|
||||
processingDocuments: 0,
|
||||
completedDocuments: 0,
|
||||
reviewRequiredDocuments: 2,
|
||||
failedDocuments: 0,
|
||||
candidateCount: 0,
|
||||
},
|
||||
documents: [
|
||||
{ unitId: 1, documentId: 11, fileName: '4518838154.pdf', status: 'review_required' },
|
||||
{ unitId: 2, documentId: 12, fileName: '4518838152.pdf', status: 'review_required' },
|
||||
],
|
||||
availableActions: ['enter_manual_review'],
|
||||
healthTips: [],
|
||||
}),
|
||||
runNo: 'SNER-2',
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
expect(wrapper.text()).toContain('4518838154.pdf');
|
||||
expect(wrapper.text()).toContain('4518838152.pdf');
|
||||
});
|
||||
|
||||
it('groups completed attachments under their EML intake instead of mixing unrelated files', async () => {
|
||||
const wrapper = mount(ShippingOrderExtractionCard, {
|
||||
props: {
|
||||
state: buildState({
|
||||
documents: [
|
||||
{ unitId: 1, documentId: 11, intakeId: 7, documentType: 'email_body', fileName: 'Forwarder_A.eml', status: 'processing' },
|
||||
{ unitId: 2, documentId: 12, intakeId: 7, documentType: 'attachment', fileName: 'Packing_List.pdf', status: 'candidate_ready' },
|
||||
{ unitId: 3, documentId: 13, intakeId: 8, documentType: 'attachment', fileName: 'Customs_Form.pdf', status: 'processing' },
|
||||
],
|
||||
healthTips: [],
|
||||
}),
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
await wrapper.find('button').trigger('click');
|
||||
const text = wrapper.text();
|
||||
expect(text.indexOf('Forwarder_A.eml')).toBeLessThan(text.indexOf('Packing_List.pdf'));
|
||||
expect(text).toContain('Customs_Form.pdf');
|
||||
expect(text.match(/Packing_List\.pdf/g)?.length).toBe(1);
|
||||
});
|
||||
|
||||
it('groups by email_body document type and renders parse failure as failed', () => {
|
||||
const wrapper = mount(ShippingOrderExtractionCard, {
|
||||
props: {
|
||||
state: buildState({
|
||||
status: 'failed',
|
||||
summary: {
|
||||
totalDocuments: 2,
|
||||
pendingDocuments: 0,
|
||||
processingDocuments: 0,
|
||||
completedDocuments: 0,
|
||||
reviewRequiredDocuments: 0,
|
||||
failedDocuments: 1,
|
||||
candidateCount: 0,
|
||||
},
|
||||
documents: [
|
||||
{ unitId: -7, documentId: 7, intakeId: 7, documentType: 'email_body', fileName: 'forwarder-message', status: 'failed', reasonCode: 'intake_parse_failed' },
|
||||
{ unitId: 8, documentId: 8, intakeId: 7, documentType: 'attachment', fileName: 'po.pdf', status: 'failed', reasonCode: 'intake_parse_failed' },
|
||||
],
|
||||
healthTips: [],
|
||||
currentActivity: null,
|
||||
}),
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
const text = wrapper.text();
|
||||
expect(text).toContain('forwarder-message');
|
||||
expect(text).toContain('po.pdf');
|
||||
expect(text).toContain('异常');
|
||||
expect(wrapper.findAll('.animate-spin').length).toBe(0);
|
||||
});
|
||||
|
||||
it('does not render completed files again as standalone cards', async () => {
|
||||
const wrapper = mount(ShippingOrderExtractionCard, {
|
||||
props: {
|
||||
state: buildState({
|
||||
summary: {
|
||||
totalDocuments: 2,
|
||||
pendingDocuments: 0,
|
||||
processingDocuments: 0,
|
||||
completedDocuments: 2,
|
||||
reviewRequiredDocuments: 0,
|
||||
failedDocuments: 0,
|
||||
candidateCount: 2,
|
||||
},
|
||||
documents: [
|
||||
{ unitId: 1, documentId: 11, fileName: '4518838152.pdf', status: 'candidate_ready' },
|
||||
{ unitId: 2, documentId: 12, fileName: '4518838154.pdf', status: 'candidate_ready' },
|
||||
],
|
||||
healthTips: [],
|
||||
}),
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
const accordion = wrapper.find('button');
|
||||
await accordion.trigger('click');
|
||||
expect(wrapper.text().match(/4518838152\.pdf/g)?.length).toBe(1);
|
||||
});
|
||||
|
||||
it('aggregates a fully completed EML intake only inside the completed section', async () => {
|
||||
const wrapper = mount(ShippingOrderExtractionCard, {
|
||||
props: {
|
||||
state: buildState({
|
||||
summary: {
|
||||
totalDocuments: 2,
|
||||
pendingDocuments: 0,
|
||||
processingDocuments: 0,
|
||||
completedDocuments: 2,
|
||||
reviewRequiredDocuments: 0,
|
||||
failedDocuments: 0,
|
||||
candidateCount: 2,
|
||||
},
|
||||
documents: [
|
||||
{ unitId: -7, documentId: 7, intakeId: 7, documentType: 'email_body', fileName: 'forwarder.eml', status: 'processing' },
|
||||
{ unitId: 8, documentId: 8, intakeId: 7, documentType: 'attachment', fileName: 'packing.pdf', status: 'candidate_ready' },
|
||||
],
|
||||
healthTips: [],
|
||||
}),
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
expect(wrapper.text()).not.toContain('forwarder.eml');
|
||||
expect(wrapper.text()).not.toContain('packing.pdf');
|
||||
await wrapper.find('button').trigger('click');
|
||||
expect(wrapper.text()).toContain('forwarder.eml');
|
||||
expect(wrapper.text()).toContain('packing.pdf');
|
||||
expect(wrapper.text().match(/forwarder\.eml/g)?.length).toBe(1);
|
||||
expect(wrapper.text().match(/packing\.pdf/g)?.length).toBe(1);
|
||||
expect(wrapper.text()).toContain('已提取');
|
||||
});
|
||||
|
||||
it('keeps a partially completed EML intake outside the completed section', async () => {
|
||||
const wrapper = mount(ShippingOrderExtractionCard, {
|
||||
props: {
|
||||
state: buildState({
|
||||
documents: [
|
||||
{ unitId: -7, documentId: 7, intakeId: 7, documentType: 'email_body', fileName: 'forwarder.eml', status: 'processing' },
|
||||
{ unitId: 8, documentId: 8, intakeId: 7, documentType: 'attachment', fileName: 'packing.pdf', status: 'candidate_ready' },
|
||||
{ unitId: 9, documentId: 9, intakeId: 7, documentType: 'attachment', fileName: 'invoice.pdf', status: 'processing' },
|
||||
],
|
||||
healthTips: [],
|
||||
}),
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
await wrapper.find('button').trigger('click');
|
||||
expect(wrapper.text()).toContain('forwarder.eml');
|
||||
expect(wrapper.text()).toContain('invoice.pdf');
|
||||
expect(wrapper.text().match(/packing\.pdf/g)?.length).toBe(1);
|
||||
});
|
||||
|
||||
it('shows an EML as exception when a child failed even if the parent status is processing', () => {
|
||||
const wrapper = mount(ShippingOrderExtractionCard, {
|
||||
props: {
|
||||
state: buildState({
|
||||
documents: [
|
||||
{ unitId: -7, documentId: 7, intakeId: 7, documentType: 'email_body', fileName: 'forwarder.eml', status: 'processing' },
|
||||
{ unitId: 8, documentId: 8, intakeId: 7, documentType: 'attachment', fileName: 'packing.pdf', status: 'failed', reasonCode: 'intake_parse_failed' },
|
||||
],
|
||||
healthTips: [],
|
||||
}),
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
expect(wrapper.text()).toContain('异常');
|
||||
expect(wrapper.text()).not.toContain('解析附件中');
|
||||
});
|
||||
|
||||
it('renders summary title, file count, system processing and no progress/refresh/cancel', () => {
|
||||
const wrapper = mount(ShippingOrderExtractionCard, {
|
||||
props: { state: buildState(), runNo: 'SNER-1' },
|
||||
@@ -61,7 +534,7 @@ describe('ShippingOrderExtractionCard', () => {
|
||||
expect(wrapper.text()).toContain('3 个文件');
|
||||
expect(wrapper.text()).toContain('系统处理中');
|
||||
expect(wrapper.text()).toContain('处理时间偏长');
|
||||
expect(wrapper.text()).toContain('查看详情');
|
||||
expect(wrapper.text()).toContain('打开批次进度中心');
|
||||
expect(wrapper.text()).not.toContain('刷新状态');
|
||||
expect(wrapper.text()).not.toContain('取消本次识别');
|
||||
expect(wrapper.text()).not.toContain('PO-450003.pdf');
|
||||
@@ -134,7 +607,7 @@ describe('ShippingOrderExtractionCard', () => {
|
||||
});
|
||||
expect(wrapper.text()).toContain('订单候选已生成');
|
||||
expect(wrapper.text()).toContain('候选待人工确认 · 2 项');
|
||||
expect(wrapper.text()).toContain('继续处理');
|
||||
expect(wrapper.text()).toContain('打开批次进度中心');
|
||||
expect(wrapper.text()).not.toContain('部分附件需人工处理');
|
||||
expect(wrapper.findAll('[data-testid="shipping-order-extraction-handling-item"]').length).toBe(0);
|
||||
});
|
||||
@@ -193,11 +666,11 @@ describe('ShippingOrderExtractionCard', () => {
|
||||
expect(wrapper.text()).not.toContain('ST-88');
|
||||
expect(wrapper.findAll('[data-testid="shipping-order-extraction-handling-item"]').length).toBe(0);
|
||||
expect(wrapper.findAll('[data-testid="shipping-order-extraction-handling-primary-action"]').length).toBe(0);
|
||||
// 失败优先:唯一主 CTA 为重试解析。
|
||||
expect(wrapper.find('[data-testid="shipping-order-extraction-primary-action"]').text()).toContain('重试解析');
|
||||
// 当前原型将执行入口统一收敛到批次进度中心,旧消息卡不再保留重试 CTA。
|
||||
expect(wrapper.find('[data-testid="shipping-order-extraction-primary-action"]').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it('shows continue CTA for review-required without retry', () => {
|
||||
it('keeps only the batch workbench CTA for review-required without retry', () => {
|
||||
const wrapper = mount(ShippingOrderExtractionCard, {
|
||||
props: {
|
||||
state: buildState({
|
||||
@@ -227,8 +700,9 @@ describe('ShippingOrderExtractionCard', () => {
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
expect(wrapper.find('[data-testid="shipping-order-extraction-primary-action"]').text()).toContain('继续处理');
|
||||
expect(wrapper.text()).not.toContain('重试解析');
|
||||
expect(wrapper.find('[data-testid="shipping-order-extraction-primary-action"]').exists()).toBe(false);
|
||||
expect(wrapper.find('[data-testid="shipping-order-extraction-view-details"]').exists()).toBe(false);
|
||||
expect(wrapper.get('[data-testid="shipping-order-extraction-open-batch-workbench"]').exists()).toBe(true);
|
||||
});
|
||||
|
||||
it('does not render multi-OT ChatProgressSummary list', () => {
|
||||
@@ -292,10 +766,10 @@ describe('ShippingOrderExtractionCard', () => {
|
||||
});
|
||||
expect(wrapper.findAll('[data-testid="chat-progress-summary-list"]').length).toBe(0);
|
||||
expect(wrapper.text()).not.toContain('PO.pdf');
|
||||
expect(wrapper.find('[data-testid="shipping-order-extraction-primary-action"]').text()).toContain('继续处理');
|
||||
expect(wrapper.find('[data-testid="shipping-order-extraction-primary-action"]').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it('emits retry for failed attachments via primary CTA', async () => {
|
||||
it('keeps retry actions out of the bottom action bar', async () => {
|
||||
const wrapper = mount(ShippingOrderExtractionCard, {
|
||||
props: {
|
||||
state: buildState({
|
||||
@@ -315,13 +789,11 @@ describe('ShippingOrderExtractionCard', () => {
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
const retryBtn = wrapper.find('[data-testid="shipping-order-extraction-primary-action"]');
|
||||
expect(retryBtn.text()).toContain('重试解析');
|
||||
await retryBtn.trigger('click');
|
||||
expect(wrapper.emitted('retry')?.length).toBe(1);
|
||||
expect(wrapper.find('[data-testid="shipping-order-extraction-primary-action"]').exists()).toBe(false);
|
||||
expect(wrapper.get('[data-testid="shipping-order-extraction-open-batch-workbench"]').exists()).toBe(true);
|
||||
});
|
||||
|
||||
it('keeps view details as secondary text link only', () => {
|
||||
it('does not render the removed view details link', () => {
|
||||
const wrapper = mount(ShippingOrderExtractionCard, {
|
||||
props: {
|
||||
state: buildState({
|
||||
@@ -333,8 +805,7 @@ describe('ShippingOrderExtractionCard', () => {
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
const details = wrapper.find('[data-testid="shipping-order-extraction-view-details"]');
|
||||
expect(details.exists()).toBe(true);
|
||||
expect(details.classes().join(' ')).toContain('underline-offset-2');
|
||||
expect(details.exists()).toBe(false);
|
||||
expect(wrapper.findAll('[data-testid="shipping-order-extraction-primary-action"]').length).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -2,15 +2,16 @@
|
||||
* features/chat/components/shipping/ShippingOrderExtractionCard.vue
|
||||
* 用途:聊天主区「订单识别任务」摘要卡——标题、文件数+状态、一行 handling 摘要、唯一主 CTA、查看详情。
|
||||
* 依赖:订单抽取 Run 状态卡 DTO、shipping.api 文档/进度接口、ShippingOrderExtractionDetailsDrawer、vue-router、vue-i18n。
|
||||
* 逻辑:对话区只做任务摘要;长进度/Gate/刷新取消由右侧栏承接;详情抽屉仅由次要「查看详情」打开。
|
||||
* 逻辑:对话区默认展示状态-EML 聚合;批次工作台打开后切换为紧凑摘要,长进度/Gate/刷新取消由工作台承接。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import { computed, ref } from 'vue';
|
||||
import { computed, inject, ref, watch } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { useRoute, useRouter } from 'vue-router';
|
||||
import { CircleCheck, CircleX, LoaderCircle, TriangleAlert } from 'lucide-vue-next';
|
||||
import { AlertCircle, ArrowRight, CheckCircle2, ChevronDown, CircleX, FileText, LoaderCircle, Mail, RefreshCw, TriangleAlert } from 'lucide-vue-next';
|
||||
import type {
|
||||
ShippingOrderExtractionHandlingItemState,
|
||||
ShippingOrderExtractionFileState,
|
||||
ShippingOrderExtractionState,
|
||||
} from '../../types/chat.types';
|
||||
import type {
|
||||
@@ -18,6 +19,11 @@ import type {
|
||||
ShippingOrderExtractionProgressEvent,
|
||||
} from '../../types/shipping.api.types';
|
||||
import type { ShippingProcessingProjection } from '../../types/shipping.api.types';
|
||||
import { SHIPPING_WORKFLOW_KEY } from '../../shipping/useShippingNoticeWorkflow';
|
||||
import {
|
||||
resolveShippingProcessingReasonLabel,
|
||||
resolveShippingProcessingStageLabel,
|
||||
} from '../../shipping/shippingProcessingLabels';
|
||||
import {
|
||||
listWorkspaceShippingOrderExtractionDocuments,
|
||||
listWorkspaceShippingOrderExtractionProgressEvents,
|
||||
@@ -35,17 +41,199 @@ const props = defineProps<{
|
||||
readonlyReason?: string | null;
|
||||
/** 可选统一投影;摘要卡不再渲染进度,仅保留 prop 兼容宿主。 */
|
||||
processingProjection?: ShippingProcessingProjection | null;
|
||||
/** 批次工作台打开时,左侧只保留摘要,避免与工作台重复展示文件明细。 */
|
||||
compactProgress?: boolean;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
retry: [];
|
||||
refresh: [];
|
||||
cancel: [reason?: string];
|
||||
'open-batch-workbench': [];
|
||||
}>();
|
||||
|
||||
const { t, te } = useI18n();
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
const shippingWorkflow = inject(SHIPPING_WORKFLOW_KEY, null);
|
||||
|
||||
type ConversationStatusGroups = NonNullable<import('../../types/shipping.api.types').ConversationProcessingProjection['status_groups']>;
|
||||
type ConversationProcessing = import('../../types/shipping.api.types').ConversationProcessingProjection;
|
||||
const conversationProcessing = computed<ConversationProcessing | null>(() => (
|
||||
(shippingWorkflow as { processing?: { value?: ConversationProcessing | null } | null } | null)?.processing?.value || null
|
||||
));
|
||||
const conversationProjectionLoading = computed(() => Boolean(
|
||||
(shippingWorkflow as { initialLoading?: { value?: boolean } | null } | null)?.initialLoading?.value,
|
||||
));
|
||||
const conversationStatusGroups = computed<ConversationStatusGroups | null>(() => conversationProcessing.value?.status_groups || null);
|
||||
const hasConversationStatusGroups = computed(() => Boolean(conversationStatusGroups.value));
|
||||
const statusGroupDefs = [
|
||||
{ key: 'failed', label: 'chat.shippingProcessing.groupFailed' },
|
||||
{ key: 'waiting_human', label: 'chat.shippingProcessing.groupWaitingHuman' },
|
||||
{ key: 'processing', label: 'chat.shippingProcessing.groupProcessing' },
|
||||
{ key: 'completed', label: 'chat.shippingProcessing.groupCompleted' },
|
||||
{ key: 'cancelled', label: 'chat.shippingProcessing.groupCancelled' },
|
||||
{ key: 'archived', label: 'chat.shippingProcessing.groupHistoryRecords' },
|
||||
] as const;
|
||||
const expandedStatusGroups = ref(new Set<string>(['failed', 'waiting_human', 'processing']));
|
||||
const expandedEmlTasks = ref(new Set<string>());
|
||||
function statusGroupTasks(key: typeof statusGroupDefs[number]['key']) {
|
||||
return conversationStatusGroups.value?.[key] || [];
|
||||
}
|
||||
function statusGroupLabel(key: typeof statusGroupDefs[number]['key']) {
|
||||
const count = statusGroupTasks(key).length;
|
||||
return t(statusGroupDefs.find((item) => item.key === key)!.label, { count });
|
||||
}
|
||||
function toggleStatusGroup(key: string) {
|
||||
const next = new Set(expandedStatusGroups.value);
|
||||
if (next.has(key)) next.delete(key); else next.add(key);
|
||||
expandedStatusGroups.value = next;
|
||||
}
|
||||
function toggleEmlTask(taskNo: string) {
|
||||
const next = new Set(expandedEmlTasks.value);
|
||||
if (next.has(taskNo)) next.delete(taskNo); else next.add(taskNo);
|
||||
expandedEmlTasks.value = next;
|
||||
}
|
||||
function taskChildren(task: { aggregateChildren?: ShippingProcessingProjection[]; user_task_no?: string | null; aggregateSummary?: { intakeNo?: string | null } | null }) {
|
||||
if (task.aggregateChildren?.length) return task.aggregateChildren;
|
||||
// [AUTHORITY] 新会话投影必须自带 EML 子文件;不能从 Run 快照或另一份 work_items 补齐,
|
||||
// 否则左右面板会出现不同文件数、不同状态的同一封邮件。
|
||||
if (hasConversationStatusGroups.value) return [];
|
||||
const projection = statusTaskProjection(task);
|
||||
if (!projection) return [];
|
||||
if (projection?.aggregateChildren?.length) return projection.aggregateChildren;
|
||||
// 后端未返回 aggregate_children 时只展示聚合摘要。禁止用 childOrderTasks 或
|
||||
// 历史聊天 Run 快照重新推导附件、Candidate、阶段或按钮。
|
||||
return [];
|
||||
}
|
||||
function taskFileCount(task: { aggregateChildren?: ShippingProcessingProjection[]; file_count?: number | null; aggregateSummary?: { intakeNo?: string | null } | null }) {
|
||||
// EML 是来源容器;统一只计其附件,避免聊天卡与批次中心相差一份 EML 本体。
|
||||
const children = taskChildren(task).filter((child) => !String(
|
||||
child.sourceSummary?.filename || '',
|
||||
).trim().toLowerCase().endsWith('.eml'));
|
||||
if (children.length) {
|
||||
const ids = new Set(children.map((child) => String(child.sourceSummary?.documentId || child.workItemNo || '').trim()).filter(Boolean));
|
||||
return ids.size || children.length;
|
||||
}
|
||||
if (hasConversationStatusGroups.value) return Math.max(0, Number(task.file_count || 0));
|
||||
const projection = statusTaskProjection(task);
|
||||
const sourceCount = Number(projection?.sourceSummary?.documentCount || 0);
|
||||
return sourceCount > 0 ? sourceCount : Math.max(0, Number(task.file_count || 0));
|
||||
}
|
||||
function childStatusLabel(child: ShippingProcessingProjection) {
|
||||
const status = displayProjectionStatus(child);
|
||||
if (status === 'completed' && child.facts?.uploadState === 'succeeded') return t('chat.shippingProcessing.aggregate.completed', { count: 1 });
|
||||
if (status === 'failed' || status === 'retryable') return t('chat.shippingProcessing.aggregate.failed', { count: 1 });
|
||||
if (status === 'waiting_human') return t('chat.shippingProcessing.aggregate.needsAction', { count: 1 });
|
||||
return t('chat.shippingProcessing.aggregate.processing', { count: 1 });
|
||||
}
|
||||
function displayReason(
|
||||
reason?: import('../../types/shipping.api.types').ShippingProcessingBlockingReason | null,
|
||||
) {
|
||||
return resolveShippingProcessingReasonLabel(reason, te, t);
|
||||
}
|
||||
/** 新投影有 ui_state 时严格消费其状态;旧响应才回退 userStatus / status。 */
|
||||
function displayProjectionStatus(item: ShippingProcessingProjection): string {
|
||||
return String(item.uiState
|
||||
? item.uiState.status
|
||||
: (item.userStatus || item.status || '')).trim().toLowerCase();
|
||||
}
|
||||
function isFailedProjection(item: ShippingProcessingProjection): boolean {
|
||||
const status = displayProjectionStatus(item);
|
||||
return status === 'failed' || status === 'retryable';
|
||||
}
|
||||
function isWaitingProjection(item: ShippingProcessingProjection): boolean {
|
||||
return displayProjectionStatus(item) === 'waiting_human';
|
||||
}
|
||||
function isCompletedProjection(item: ShippingProcessingProjection): boolean {
|
||||
return displayProjectionStatus(item) === 'completed' && item.facts?.uploadState === 'succeeded';
|
||||
}
|
||||
function taskReason(task: { uiState?: { blocking_reason: import('../../types/shipping.api.types').ShippingProcessingBlockingReason | null }; blockingReason?: import('../../types/shipping.api.types').ShippingProcessingBlockingReason | null }) {
|
||||
return task.uiState ? task.uiState.blocking_reason : task.blockingReason;
|
||||
}
|
||||
function childStageLabel(child: ShippingProcessingProjection) {
|
||||
const stage = String(child.uiState?.stage || child.userStage || child.stage || '').trim();
|
||||
return resolveShippingProcessingStageLabel(stage, te, t);
|
||||
}
|
||||
function statusTaskProjection(task: { user_task_no?: string | null; aggregateSummary?: { intakeNo?: string | null } | null }) {
|
||||
const items = shippingWorkflow?.processingWorkItems.value || [];
|
||||
const intakeNo = String(task.aggregateSummary?.intakeNo || '').trim();
|
||||
if (intakeNo) {
|
||||
const intakeMatch = items.find((item) => (
|
||||
item.sourceType === 'eml'
|
||||
&& String(item.intakeNo || '').trim() === intakeNo
|
||||
));
|
||||
if (intakeMatch) return intakeMatch;
|
||||
}
|
||||
return items.find((item) => (
|
||||
(item.workItemType === 'order_task' || item.workItemType === 'order_intake')
|
||||
&& String(item.workItemNo || '').trim() === String((task as any).user_task_no || '').trim()
|
||||
)) || null;
|
||||
}
|
||||
function aggregateStatusLabelFromSummary(summary: NonNullable<import('../../types/shipping.api.types').ConversationProcessingUserTask['aggregateSummary']>) {
|
||||
const parts: string[] = [];
|
||||
if (summary.completed) parts.push(t('chat.shippingProcessing.aggregate.completed', { count: summary.completed }));
|
||||
if (summary.processing) parts.push(t('chat.shippingProcessing.aggregate.processing', { count: summary.processing }));
|
||||
if (summary.needsAction) parts.push(t('chat.shippingProcessing.aggregate.needsAction', { count: summary.needsAction }));
|
||||
if (summary.failed) parts.push(t('chat.shippingProcessing.aggregate.failed', { count: summary.failed }));
|
||||
return parts.join(' · ');
|
||||
}
|
||||
|
||||
/**
|
||||
* 当前 Run 对应的 EML Intake 聚合项。
|
||||
*
|
||||
* 右侧投影轮询是增量可见的:一次响应暂未带回该 Intake 不能让聊天消息卡
|
||||
* 降级为旧 Run 卡。消息卡保留最后一次同 Run/用户任务命中的聚合快照,只有
|
||||
* 同一绑定再次命中时才更新;右侧面板仍直接消费实时投影。
|
||||
*/
|
||||
const matchedEmlAggregate = computed(() => {
|
||||
const runNo = String(props.runNo || props.state.runNo || '').trim();
|
||||
const userTaskNo = String(props.state.userTaskNo || '').trim();
|
||||
const items = shippingWorkflow?.processingWorkItems.value || [];
|
||||
return items.find((item) => (
|
||||
item.workItemType === 'order_task'
|
||||
&& item.sourceType === 'eml'
|
||||
&& Boolean(item.aggregateSummary)
|
||||
&& (
|
||||
String(item.runNo || '').trim() === runNo
|
||||
|| (Boolean(userTaskNo) && String(item.rootOrderTaskNo || '').trim() === userTaskNo)
|
||||
)
|
||||
)) || null;
|
||||
});
|
||||
const lastMatchedEmlAggregate = ref<ShippingProcessingProjection | null>(null);
|
||||
watch(matchedEmlAggregate, (item) => {
|
||||
if (item) lastMatchedEmlAggregate.value = item;
|
||||
}, { immediate: true });
|
||||
const emlAggregate = computed(() => (
|
||||
// [AUTHORITY] 切换会话时先等待该会话的统一投影,禁止旧聊天消息 Run 快照抢占首屏;
|
||||
// 请求完成后仍只消费后端 Projection,失败则保留既有兼容摘要。
|
||||
hasConversationStatusGroups.value || conversationProjectionLoading.value
|
||||
? null
|
||||
: (matchedEmlAggregate.value || lastMatchedEmlAggregate.value)
|
||||
));
|
||||
const emlAggregateChildren = computed(() => emlAggregate.value?.aggregateChildren || []);
|
||||
const emlAggregateExpanded = ref(false);
|
||||
function aggregateStageLabel(item: ShippingProcessingProjection): string {
|
||||
const stage = String(item.uiState ? item.uiState.stage : (item.userStage || item.stage || '')).trim();
|
||||
return resolveShippingProcessingStageLabel(stage, te, t);
|
||||
}
|
||||
function aggregateChildStatusLabel(item: ShippingProcessingProjection): string {
|
||||
const status = displayProjectionStatus(item);
|
||||
if (status === 'completed' && item.facts?.uploadState === 'succeeded') return t('chat.shippingProcessing.aggregate.completed', { count: 1 });
|
||||
if (status === 'failed' || status === 'retryable') return t('chat.shippingProcessing.aggregate.failed', { count: 1 });
|
||||
if (status === 'waiting_human') return t('chat.shippingProcessing.aggregate.needsAction', { count: 1 });
|
||||
return t('chat.shippingProcessing.aggregate.processing', { count: 1 });
|
||||
}
|
||||
function aggregateSummaryLabel(item: ShippingProcessingProjection): string {
|
||||
const summary = item.aggregateSummary;
|
||||
if (!summary) return '';
|
||||
const parts: string[] = [];
|
||||
if (summary.completed) parts.push(t('chat.shippingProcessing.aggregate.completed', { count: summary.completed }));
|
||||
if (summary.processing) parts.push(t('chat.shippingProcessing.aggregate.processing', { count: summary.processing }));
|
||||
if (summary.needsAction) parts.push(t('chat.shippingProcessing.aggregate.needsAction', { count: summary.needsAction }));
|
||||
if (summary.failed) parts.push(t('chat.shippingProcessing.aggregate.failed', { count: summary.failed }));
|
||||
return parts.join(' · ');
|
||||
}
|
||||
|
||||
const detailsOpen = ref(false);
|
||||
const detailsLoading = ref(false);
|
||||
@@ -57,7 +245,110 @@ const progressEvents = ref<ShippingOrderExtractionProgressEvent[]>([]);
|
||||
|
||||
const displaySummary = computed(() => props.state.summary);
|
||||
|
||||
const handlingItems = computed(() => props.state.handlingItems || []);
|
||||
/**
|
||||
* 旧聊天消息中的 handlingItems 是当时的 Run 快照;实时会话投影已返回时,
|
||||
* 绝不能把它重新展示成当前待办或用它决定 CTA。当前待办仅由后端 work_items
|
||||
* 与其 ui_state 裁决,旧卡在此模式下只保留历史消息本身。
|
||||
*/
|
||||
const handlingItems = computed(() => (
|
||||
hasConversationStatusGroups.value ? [] : (props.state.handlingItems || [])
|
||||
));
|
||||
const fileRows = computed(() => props.state.documents || []);
|
||||
const isEmailRow = (row: ShippingOrderExtractionFileState) => (
|
||||
row.documentType === 'email_body' || row.fileName?.toLowerCase().endsWith('.eml')
|
||||
);
|
||||
/**
|
||||
* 返回当前 Run 快照中的唯一业务 PDF,隔离历史 Unit/Review Case 汇总。
|
||||
* 核心逻辑:优先用稳定 documentId 去重;旧快照缺失时才回退 unitId 或文件名。
|
||||
*/
|
||||
const currentBusinessFileRows = computed(() => {
|
||||
const seen = new Set<string>();
|
||||
return fileRows.value.filter((row) => {
|
||||
if (isEmailRow(row)) return false;
|
||||
const key = row.documentId > 0
|
||||
? `document:${row.documentId}`
|
||||
: row.unitId > 0
|
||||
? `unit:${row.unitId}`
|
||||
: `filename:${String(row.fileName || '').trim().toLowerCase()}`;
|
||||
if (seen.has(key)) return false;
|
||||
seen.add(key);
|
||||
return true;
|
||||
});
|
||||
});
|
||||
const hasCurrentBusinessFileRows = computed(() => currentBusinessFileRows.value.length > 0);
|
||||
const emailRows = computed(() => fileRows.value.filter(isEmailRow));
|
||||
const isFailedParseRow = (row: ShippingOrderExtractionFileState) => (
|
||||
row.status === 'failed'
|
||||
|| row.reasonCode === 'intake_parse_failed'
|
||||
|| row.userVisibleStage === 'parse_failed'
|
||||
);
|
||||
const childRows = (email: ShippingOrderExtractionFileState) => fileRows.value.filter((row) => (
|
||||
row.unitId !== email.unitId
|
||||
&& row.intakeId != null
|
||||
&& row.intakeId === email.intakeId
|
||||
&& !isEmailRow(row)
|
||||
));
|
||||
const candidateEmailGroups = computed(() => emailRows.value
|
||||
.map((parent) => ({ parent, children: childRows(parent) }))
|
||||
.filter((group) => group.children.length > 0 && group.children.every((child) => child.status === 'candidate_ready')));
|
||||
const emailHasFailedChild = (email: ShippingOrderExtractionFileState) => childRows(email).some(isFailedParseRow);
|
||||
const emailIsCompleted = (email: ShippingOrderExtractionFileState) => {
|
||||
const children = childRows(email);
|
||||
return children.length > 0 && children.every((child) => child.status === 'candidate_ready');
|
||||
};
|
||||
const candidateEmailUnitIds = computed(() => new Set(
|
||||
candidateEmailGroups.value.flatMap((group) => [group.parent.unitId, ...group.children.map((child) => child.unitId)]),
|
||||
));
|
||||
const candidateStandaloneRows = computed(() => fileRows.value.filter((row) => (
|
||||
!isEmailRow(row)
|
||||
&& row.status === 'candidate_ready'
|
||||
&& !emailRows.value.some((email) => childRows(email).some((child) => child.unitId === row.unitId))
|
||||
)));
|
||||
const candidateFileCount = computed(() => (
|
||||
candidateEmailGroups.value.reduce((count, group) => count + group.children.length, 0)
|
||||
+ candidateStandaloneRows.value.length
|
||||
));
|
||||
const activeEmailRows = computed(() => emailRows.value.filter((row) => !candidateEmailUnitIds.value.has(row.unitId)));
|
||||
const standaloneRows = computed(() => fileRows.value.filter((row) => (
|
||||
!isEmailRow(row)
|
||||
&& row.status !== 'candidate_ready'
|
||||
&& !isFailedParseRow(row)
|
||||
&& !candidateEmailUnitIds.value.has(row.unitId)
|
||||
&& !emailRows.value.some((email) => childRows(email).some((child) => child.unitId === row.unitId))
|
||||
)));
|
||||
const failedRows = computed(() => fileRows.value.filter((row) => (
|
||||
isFailedParseRow(row)
|
||||
&& !candidateEmailUnitIds.value.has(row.unitId)
|
||||
&& !emailRows.value.some((email) => childRows(email).some((child) => child.unitId === row.unitId))
|
||||
)));
|
||||
const processedCount = computed(() => {
|
||||
if (hasConversationStatusGroups.value) {
|
||||
const summary = conversationProcessing.value?.summary;
|
||||
// [AUTHORITY] “已处理/完成率”只表示已经完成通知生命周期的业务文件。
|
||||
// waiting_human / failed 只是后端裁决出的待处理事项,不能借用历史 Run 的
|
||||
// “处理过”口径累计为完成,否则会与批次进度中心的 completed_files 冲突。
|
||||
return Math.max(0, Number(summary?.completed_files || 0));
|
||||
}
|
||||
// 当前 Run 仅表达抽取/候选状态,不能把 candidate_ready 或历史复核 Case 伪装成
|
||||
// 已完成通知生命周期;生命周期完成数只由会话权威投影下发。
|
||||
if (hasCurrentBusinessFileRows.value) return 0;
|
||||
return emlAggregate.value?.aggregateSummary?.completed
|
||||
?? (props.state.summary.completedDocuments + props.state.summary.reviewRequiredDocuments);
|
||||
});
|
||||
const progressPercent = computed(() => {
|
||||
const total = batchFileCount.value;
|
||||
return total > 0 ? Math.min(100, Math.round((processedCount.value / total) * 100)) : 0;
|
||||
});
|
||||
const completedExpanded = ref(false);
|
||||
|
||||
/** 新版会话批次的业务文件数由后端汇总;旧 Run 卡仍保留历史兼容计数。 */
|
||||
const batchFileCount = computed(() => {
|
||||
if (hasConversationStatusGroups.value) {
|
||||
return Math.max(0, Number(conversationProcessing.value?.summary?.total_files || 0));
|
||||
}
|
||||
if (hasCurrentBusinessFileRows.value) return currentBusinessFileRows.value.length;
|
||||
return Math.max(0, Number(emlAggregate.value?.sourceSummary.documentCount ?? props.state.summary.totalDocuments));
|
||||
});
|
||||
|
||||
/**
|
||||
* 是否为「仅重复关联已有任务、无需人工复核」终态通知。
|
||||
@@ -83,26 +374,20 @@ const isCandidateConfirmationNotice = computed(() => (
|
||||
)
|
||||
));
|
||||
|
||||
const toneClass = computed(() => {
|
||||
if (isDuplicateOnlyNotice.value) {
|
||||
return 'border-violet-200 bg-violet-50/80 text-violet-950 dark:border-violet-800 dark:bg-violet-950/35 dark:text-violet-100';
|
||||
}
|
||||
if (isCandidateConfirmationNotice.value) {
|
||||
return 'border-teal-200 bg-teal-50/80 text-teal-950 dark:border-teal-800 dark:bg-teal-950/35 dark:text-teal-100';
|
||||
}
|
||||
switch (props.state.status) {
|
||||
case 'completed':
|
||||
return 'border-emerald-200 bg-emerald-50/80 text-emerald-950 dark:border-emerald-800 dark:bg-emerald-950/35 dark:text-emerald-100';
|
||||
case 'partially_completed':
|
||||
case 'review_required':
|
||||
return 'border-amber-200 bg-amber-50/80 text-amber-950 dark:border-amber-800 dark:bg-amber-950/35 dark:text-amber-100';
|
||||
case 'failed':
|
||||
case 'cancelled':
|
||||
return 'border-rose-200 bg-rose-50/80 text-rose-900 dark:border-rose-800 dark:bg-rose-950/35 dark:text-rose-100';
|
||||
default:
|
||||
return 'border-sky-200 bg-sky-50/80 text-sky-900 dark:border-sky-800 dark:bg-sky-950/35 dark:text-sky-100';
|
||||
}
|
||||
});
|
||||
function rowStatusLabel(row: ShippingOrderExtractionFileState): string {
|
||||
if (row.status === 'candidate_ready') return t('chat.shippingProcessing.candidateReady');
|
||||
if (isFailedParseRow(row)) return t('chat.shippingProcessing.batchException');
|
||||
if (row.status === 'review_required') return t('chat.shippingProcessing.waitingReview');
|
||||
const stageKey = `chat.shippingOrderExtractionUserStage.${String(row.userVisibleStage || '').trim()}`;
|
||||
if (row.userVisibleStage && te(stageKey)) return t(stageKey);
|
||||
return t('chat.shippingProcessing.batchProcessing');
|
||||
}
|
||||
|
||||
function rowStatusClass(row: ShippingOrderExtractionFileState): string {
|
||||
if (row.status === 'candidate_ready') return 'text-emerald-500';
|
||||
if (isFailedParseRow(row)) return 'text-rose-500';
|
||||
return 'text-blue-500';
|
||||
}
|
||||
|
||||
/**
|
||||
* 将处理事项类别映射为一句过程通知文案。
|
||||
@@ -126,6 +411,20 @@ function handlingTitle(item: ShippingOrderExtractionHandlingItemState): string {
|
||||
* 状态短句:排队/处理中仅「系统处理中」;其余用过程通知,不含文件阶段耗时。
|
||||
*/
|
||||
const statusNotice = computed(() => {
|
||||
if (hasConversationStatusGroups.value) {
|
||||
const status = String(conversationProcessing.value?.ui_state?.status || '').trim().toLowerCase();
|
||||
if (status === 'completed') return t('chat.shippingSessionSummary.processNoticeCompleted');
|
||||
if (status === 'failed' || status === 'retryable') return t('chat.shippingSessionSummary.processNoticeFailed');
|
||||
if (status === 'waiting_human') return t('chat.shippingSessionSummary.processNoticeNeedsAction');
|
||||
return t('chat.shippingProcessing.systemProcessing');
|
||||
}
|
||||
if (emlAggregate.value) {
|
||||
const status = String(emlAggregate.value.userStatus || '').trim().toLowerCase();
|
||||
if (status === 'completed') return t('chat.shippingSessionSummary.processNoticeCompleted');
|
||||
if (status === 'failed' || status === 'retryable') return t('chat.shippingSessionSummary.processNoticeFailed');
|
||||
if (status === 'waiting_human') return t('chat.shippingSessionSummary.processNoticeNeedsAction');
|
||||
return t('chat.shippingProcessing.systemProcessing');
|
||||
}
|
||||
if (props.state.cancellation?.requested && !props.state.cancellation?.completedAt && !props.state.terminal) {
|
||||
return t('chat.shippingOrderExtractionUserStage.cancellation_requested');
|
||||
}
|
||||
@@ -177,6 +476,9 @@ const handlingSummaryLine = computed(() => {
|
||||
if (!first) return '';
|
||||
const totalCount = items.reduce((sum, item) => sum + Math.max(0, Number(item.count || 0)), 0);
|
||||
const count = totalCount > 0 ? totalCount : items.length;
|
||||
// 旧 Run 的 Case 是跨版本历史记录。当前卡片已有 PDF 快照时,数目不一致即说明
|
||||
// handling 来自另一集合,不能在“本批文件”标题下误导为当前待复核文件。
|
||||
if (hasCurrentBusinessFileRows.value && count !== currentBusinessFileRows.value.length) return '';
|
||||
return t('chat.shippingOrderExtractionHandling.summaryLine', {
|
||||
title: handlingTitle(first),
|
||||
count,
|
||||
@@ -187,7 +489,7 @@ const handlingSummaryLine = computed(() => {
|
||||
* 唯一主 CTA:失败→重试解析;需处理→继续处理;否则不展示。
|
||||
*/
|
||||
const primaryChatAction = computed((): { kind: 'retry' | 'continue'; label: string } | null => {
|
||||
if (props.readonly) return null;
|
||||
if (props.readonly || hasConversationStatusGroups.value) return null;
|
||||
const actions = props.state.availableActions || [];
|
||||
const canRetry = actions.includes('retry_failed_attachments')
|
||||
|| actions.includes('retry_failed_documents')
|
||||
@@ -261,7 +563,7 @@ async function loadDetailsDocuments() {
|
||||
detailsLoading.value = true;
|
||||
detailsLoadFailed.value = false;
|
||||
try {
|
||||
const docsRes = await listWorkspaceShippingOrderExtractionDocuments(runNo).catch(() => null);
|
||||
const docsRes = await listWorkspaceShippingOrderExtractionDocuments(runNo, props.state.uploadBatchId).catch(() => null);
|
||||
if (docsRes) {
|
||||
detailsDocuments.value = Array.isArray(docsRes.items) ? docsRes.items : [];
|
||||
} else {
|
||||
@@ -286,7 +588,7 @@ async function loadDetailsProgress() {
|
||||
progressLoading.value = true;
|
||||
progressLoadFailed.value = false;
|
||||
try {
|
||||
const eventsRes = await listWorkspaceShippingOrderExtractionProgressEvents(runNo).catch(() => null);
|
||||
const eventsRes = await listWorkspaceShippingOrderExtractionProgressEvents(runNo, props.state.uploadBatchId).catch(() => null);
|
||||
if (eventsRes) {
|
||||
progressEvents.value = Array.isArray(eventsRes.items) ? eventsRes.items : [];
|
||||
} else {
|
||||
@@ -347,25 +649,151 @@ async function onPrimaryChatAction() {
|
||||
|
||||
<template>
|
||||
<div
|
||||
class="mb-3 rounded-lg border px-3.5 py-2.5"
|
||||
:class="toneClass"
|
||||
v-if="conversationProjectionLoading"
|
||||
class="mb-3 animate-pulse overflow-hidden rounded-xl border border-slate-200 bg-white/90 shadow-md dark:border-slate-700 dark:bg-slate-900/90"
|
||||
data-testid="shipping-order-extraction-projection-loading"
|
||||
>
|
||||
<!-- 读取权威 Projection 不是业务状态;只显示结构骨架,避免伪造“系统处理中”。 -->
|
||||
<div class="border-b border-slate-200 bg-indigo-50/70 px-5 py-4 dark:border-slate-700 dark:bg-indigo-950/30">
|
||||
<div class="h-6 w-36 rounded bg-slate-200 dark:bg-slate-700" />
|
||||
<div class="mt-3 h-4 w-2/3 rounded bg-slate-200 dark:bg-slate-700" />
|
||||
<div class="mt-5 h-2 w-full rounded bg-slate-200 dark:bg-slate-700" />
|
||||
</div>
|
||||
<div class="space-y-3 p-4">
|
||||
<div class="h-12 rounded-lg bg-slate-100 dark:bg-slate-800" />
|
||||
<div class="h-12 rounded-lg bg-slate-100 dark:bg-slate-800" />
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
v-else
|
||||
class="mb-3 overflow-hidden rounded-xl border border-slate-200 bg-white/90 text-slate-900 shadow-md backdrop-blur-sm dark:border-slate-700 dark:bg-slate-900/90 dark:text-slate-100"
|
||||
data-testid="shipping-order-extraction-card"
|
||||
>
|
||||
<div class="flex items-start gap-3">
|
||||
<LoaderCircle
|
||||
v-if="state.status === 'queued' || state.status === 'processing'"
|
||||
class="mt-0.5 h-4 w-4 shrink-0 animate-spin"
|
||||
/>
|
||||
<CircleCheck
|
||||
v-else-if="state.status === 'completed' || isDuplicateOnlyNotice || isCandidateConfirmationNotice"
|
||||
class="mt-0.5 h-4 w-4 shrink-0"
|
||||
/>
|
||||
<TriangleAlert
|
||||
v-else-if="state.status === 'partially_completed' || state.status === 'review_required'"
|
||||
class="mt-0.5 h-4 w-4 shrink-0"
|
||||
/>
|
||||
<CircleX v-else class="mt-0.5 h-4 w-4 shrink-0" />
|
||||
<div class="border-b border-slate-200 bg-indigo-50/70 px-5 py-4 dark:border-slate-700 dark:bg-indigo-950/30">
|
||||
<div class="flex items-center justify-between gap-3">
|
||||
<div class="flex items-center gap-2 text-lg font-semibold">
|
||||
<LoaderCircle v-if="hasConversationStatusGroups ? conversationProcessing?.ui_state?.status === 'running' : emlAggregate ? emlAggregate.userStatus === 'running' : state.status === 'queued' || state.status === 'processing'" class="h-5 w-5 animate-spin text-blue-600" />
|
||||
<CheckCircle2 v-else-if="hasConversationStatusGroups ? conversationProcessing?.ui_state?.status === 'completed' : emlAggregate ? emlAggregate.userStatus === 'completed' && emlAggregate.facts?.uploadState === 'succeeded' : state.status === 'completed'" class="h-5 w-5 text-emerald-500" />
|
||||
<TriangleAlert v-else class="h-5 w-5 text-amber-500" />
|
||||
<span>{{ t('chat.shippingProcessing.multiPdfTaskTitle') }}</span>
|
||||
</div>
|
||||
<span class="rounded-full bg-slate-200 px-3 py-1 text-xs font-medium text-slate-600 dark:bg-slate-700 dark:text-slate-200">
|
||||
{{ t('chat.shippingProcessing.batchFilesTotal', { count: batchFileCount }) }}
|
||||
</span>
|
||||
</div>
|
||||
<p class="mt-1 text-sm text-slate-600 dark:text-slate-300">{{ t('chat.shippingProcessing.batchStatusTitle') }} · {{ statusNotice }}</p>
|
||||
<div v-for="tip in healthTips" :key="tip.code" class="mt-1 text-sm font-medium text-amber-600">{{ t(`chat.shippingOrderExtractionHealthTip.${tip.code}`) }}</div>
|
||||
<div v-if="handlingSummaryLine" class="mt-1 text-sm text-slate-600 dark:text-slate-300">{{ handlingSummaryLine }}</div>
|
||||
<div class="mt-4 flex items-end justify-between">
|
||||
<span class="text-lg font-medium text-blue-600">{{ progressPercent }}% {{ t('chat.shippingProcessing.batchComplete') }}</span>
|
||||
<span class="text-sm text-slate-600 dark:text-slate-300">{{ processedCount }}/{{ batchFileCount }} {{ t('chat.shippingProcessing.batchProcessed') }}</span>
|
||||
</div>
|
||||
<div class="mt-3 h-2 overflow-hidden rounded-full bg-slate-200 dark:bg-slate-700">
|
||||
<div class="h-full rounded-full bg-blue-600 transition-all" :style="{ width: `${progressPercent}%` }" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="hasConversationStatusGroups && !compactProgress" class="flex flex-col gap-2 bg-slate-50 p-2 dark:bg-slate-950/30" data-testid="shipping-order-extraction-status-groups">
|
||||
<template v-for="group in statusGroupDefs" :key="group.key">
|
||||
<section v-if="statusGroupTasks(group.key).length" class="overflow-hidden rounded-lg border border-slate-200 bg-white dark:border-slate-700 dark:bg-slate-900">
|
||||
<button type="button" class="flex w-full items-center justify-between px-3 py-3 text-left" @click="toggleStatusGroup(group.key)">
|
||||
<span class="text-sm font-semibold" :class="group.key === 'failed' ? 'text-rose-600' : group.key === 'waiting_human' ? 'text-amber-700' : group.key === 'completed' ? 'text-emerald-600' : 'text-slate-700 dark:text-slate-200'">{{ statusGroupLabel(group.key) }}</span>
|
||||
<ChevronDown class="h-4 w-4 transition-transform" :class="expandedStatusGroups.has(group.key) ? 'rotate-180' : ''" />
|
||||
</button>
|
||||
<div v-if="expandedStatusGroups.has(group.key)" class="space-y-2 border-t border-slate-200 p-2 dark:border-slate-700">
|
||||
<article v-for="task in statusGroupTasks(group.key)" :key="task.user_task_no" class="rounded-lg border border-slate-200 bg-slate-50 dark:border-slate-700 dark:bg-slate-950/30" :data-testid="`shipping-order-extraction-eml-${group.key}-${task.user_task_no}`">
|
||||
<div class="flex items-start gap-2">
|
||||
<Mail class="mt-0.5 h-4 w-4 text-blue-600" />
|
||||
<div class="min-w-0 flex-1">
|
||||
<button type="button" class="flex w-full items-center justify-between gap-2 text-left" @click="toggleEmlTask(task.user_task_no)">
|
||||
<span class="truncate text-sm font-medium">{{ task.title || task.user_task_no }}</span>
|
||||
<ChevronDown class="h-4 w-4 shrink-0 transition-transform" :class="expandedEmlTasks.has(task.user_task_no) ? 'rotate-180' : ''" />
|
||||
</button>
|
||||
<div class="mt-1 text-xs text-slate-500">{{ t('chat.shippingProcessing.taskFiles', { count: taskFileCount(task) }) }}<span v-if="task.aggregateSummary"> · {{ aggregateStatusLabelFromSummary(task.aggregateSummary) }}</span></div>
|
||||
<div v-if="taskReason(task)" class="mt-1 text-xs text-rose-600">{{ displayReason(taskReason(task)) }}</div>
|
||||
<div v-if="expandedEmlTasks.has(task.user_task_no) && taskChildren(task).length" class="mt-2 space-y-1 border-t border-slate-200 pt-2 dark:border-slate-700" data-testid="shipping-order-extraction-eml-children">
|
||||
<div v-for="child in taskChildren(task).filter((item) => !String(item.sourceSummary?.filename || '').toLowerCase().endsWith('.eml'))" :key="child.workItemNo" class="flex items-start justify-between gap-3 rounded-md bg-white px-2 py-1.5 text-xs dark:bg-slate-900">
|
||||
<div class="min-w-0">
|
||||
<div class="truncate font-medium">{{ child.sourceSummary.filename || child.workItemNo }}</div>
|
||||
<div class="text-[11px] text-slate-500">{{ childStageLabel(child) }}</div>
|
||||
<div v-if="taskReason(child)" class="text-[11px] text-rose-600">{{ displayReason(taskReason(child)) }}</div>
|
||||
</div>
|
||||
<span :data-testid="`shipping-order-extraction-child-status-${child.workItemNo}`" class="shrink-0" :class="isFailedProjection(child) ? 'text-rose-600' : isWaitingProjection(child) ? 'text-amber-700' : isCompletedProjection(child) ? 'text-emerald-600' : 'text-blue-600'">{{ childStatusLabel(child) }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</article>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
</div>
|
||||
<div v-else-if="!compactProgress && emlAggregate" class="flex flex-col gap-2 bg-slate-50 p-2 dark:bg-slate-950/30" data-testid="shipping-order-extraction-eml-aggregate">
|
||||
<article class="overflow-hidden rounded-lg border border-slate-300 bg-white shadow-sm dark:border-slate-700 dark:bg-slate-900">
|
||||
<div class="flex items-start gap-3 border-b border-slate-200 bg-blue-50/50 p-3 dark:border-slate-700 dark:bg-blue-950/20">
|
||||
<Mail class="mt-0.5 h-5 w-5 text-blue-600" />
|
||||
<div class="min-w-0 flex-1">
|
||||
<div class="flex items-center justify-between gap-3">
|
||||
<span class="truncate font-medium">{{ t('chat.shippingProcessing.emailPrefix') }}{{ emlAggregate.sourceSummary.filename || emlAggregate.intakeNo }}</span>
|
||||
<span class="rounded border px-2 py-0.5 text-xs" :class="emlAggregate.userStatus === 'failed' || emlAggregate.userStatus === 'retryable' ? 'border-rose-200 bg-rose-100/70 text-rose-600' : emlAggregate.userStatus === 'waiting_human' ? 'border-amber-200 bg-amber-100/70 text-amber-700' : emlAggregate.userStatus === 'completed' ? 'border-emerald-200 bg-emerald-100/70 text-emerald-600' : 'border-blue-200 bg-blue-100/70 text-blue-600'">
|
||||
{{ emlAggregate.userStatus === 'completed' ? t('chat.shippingProcessing.aggregate.completed', { count: emlAggregate.aggregateSummary?.completed || 0 }) : emlAggregate.userStatus === 'failed' || emlAggregate.userStatus === 'retryable' ? t('chat.shippingProcessing.batchException') : emlAggregate.userStatus === 'waiting_human' ? t('chat.shippingProcessing.waitingReview') : t('chat.shippingProcessing.systemProcessing') }}
|
||||
</span>
|
||||
</div>
|
||||
<div class="mt-1 text-xs text-slate-600 dark:text-slate-300">{{ aggregateSummaryLabel(emlAggregate) }}</div>
|
||||
<div v-if="taskReason(emlAggregate)" class="mt-1 text-xs text-rose-600">{{ displayReason(taskReason(emlAggregate)) }}</div>
|
||||
</div>
|
||||
</div>
|
||||
<button type="button" class="flex w-full items-center justify-between px-3 py-2 text-left text-sm" @click="emlAggregateExpanded = !emlAggregateExpanded">
|
||||
<span>{{ t('chat.shippingProcessing.taskFiles', { count: emlAggregate.sourceSummary.documentCount || 0 }) }}</span>
|
||||
<ChevronDown class="h-4 w-4 transition-transform" :class="emlAggregateExpanded ? 'rotate-180' : ''" />
|
||||
</button>
|
||||
<div v-if="emlAggregateExpanded" class="space-y-1 border-t border-slate-200 px-3 py-2 dark:border-slate-700">
|
||||
<div v-for="child in emlAggregateChildren" :key="child.workItemNo" class="flex items-center justify-between gap-3 py-1 text-sm">
|
||||
<span class="min-w-0 truncate">{{ child.sourceSummary.filename || child.workItemNo }}</span>
|
||||
<span class="shrink-0 text-xs" :class="isFailedProjection(child) ? 'text-rose-600' : isWaitingProjection(child) ? 'text-amber-700' : isCompletedProjection(child) ? 'text-emerald-600' : 'text-blue-600'">{{ aggregateChildStatusLabel(child) }} · {{ aggregateStageLabel(child) }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</article>
|
||||
</div>
|
||||
<div v-else-if="!compactProgress" class="flex flex-col gap-2 bg-slate-50 p-2 dark:bg-slate-950/30">
|
||||
<button type="button" class="flex items-center justify-between rounded-lg border border-slate-200 bg-white px-3 py-3 text-left dark:border-slate-700 dark:bg-slate-900" @click="completedExpanded = !completedExpanded">
|
||||
<span class="flex items-center gap-3 text-base font-medium"><span class="flex h-7 w-7 items-center justify-center rounded-full bg-blue-100 text-blue-600"><CheckCircle2 class="h-4 w-4" /></span>{{ t('chat.shippingProcessing.candidateFiles', { count: candidateFileCount }) }}</span>
|
||||
<ChevronDown class="h-5 w-5 transition-transform" :class="completedExpanded ? 'rotate-180' : ''" />
|
||||
</button>
|
||||
<div v-if="completedExpanded && candidateFileCount" class="space-y-2 rounded-lg border border-slate-200 bg-white px-4 py-2 text-sm dark:border-slate-700 dark:bg-slate-900">
|
||||
<div v-for="group in candidateEmailGroups" :key="`candidate-email-${group.parent.unitId}`" class="rounded-md border border-blue-100 bg-blue-50/50 px-3 py-2 dark:border-blue-900 dark:bg-blue-950/20">
|
||||
<div class="flex items-center gap-2 font-medium text-slate-700 dark:text-slate-200"><Mail class="h-4 w-4 text-blue-600" />{{ t('chat.shippingProcessing.emailPrefix') }}{{ group.parent.fileName }}<span class="ml-auto text-emerald-500">{{ t('chat.shippingProcessing.batchExtracted') }}</span></div>
|
||||
<div class="mt-1 space-y-1 border-l-2 border-blue-200 pl-3 dark:border-blue-800">
|
||||
<div v-for="row in group.children" :key="`candidate-child-${row.unitId}`" class="flex items-center gap-2 py-1 text-slate-600 dark:text-slate-300"><CheckCircle2 class="h-4 w-4 text-blue-500" />{{ row.fileName }}<span class="ml-auto text-blue-500">{{ rowStatusLabel(row) }}</span></div>
|
||||
</div>
|
||||
</div>
|
||||
<div v-for="row in candidateStandaloneRows" :key="`candidate-${row.unitId}`" class="flex items-center gap-2 py-1 text-slate-600 dark:text-slate-300"><CheckCircle2 class="h-4 w-4 text-blue-500" />{{ row.fileName }}<span class="ml-auto text-blue-500">{{ rowStatusLabel(row) }}</span></div>
|
||||
</div>
|
||||
<div v-for="row in activeEmailRows" :key="row.unitId" class="overflow-hidden rounded-lg border border-slate-300 bg-white shadow-sm dark:border-slate-700 dark:bg-slate-900">
|
||||
<div class="flex items-start gap-3 border-b border-slate-200 bg-blue-50/50 p-3 dark:border-slate-700 dark:bg-blue-950/20"><Mail class="mt-0.5 h-5 w-5 text-blue-600" /><div class="min-w-0 flex-1"><div class="flex items-center justify-between gap-3"><span class="font-medium">{{ t('chat.shippingProcessing.emailPrefix') }}{{ row.fileName }}</span><span class="rounded border px-2 py-0.5 text-xs" :class="isFailedParseRow(row) || emailHasFailedChild(row) ? 'border-rose-200 bg-rose-100/70 text-rose-600' : emailIsCompleted(row) ? 'border-emerald-200 bg-emerald-100/70 text-emerald-600' : 'border-blue-200 bg-blue-100/70 text-blue-600'">{{ isFailedParseRow(row) || emailHasFailedChild(row) ? t('chat.shippingProcessing.batchException') : emailIsCompleted(row) ? t('chat.shippingProcessing.batchExtracted') : t('chat.shippingProcessing.parsingAttachments') }}</span></div><span class="mt-1 block font-mono text-xs text-slate-500">{{ t('chat.shippingProcessing.emailMeta') }}</span></div></div>
|
||||
<div class="mx-4 my-2 flex flex-col gap-2 border-l-2 border-blue-200 bg-slate-50 p-3 pl-4 dark:border-blue-800 dark:bg-blue-950/30"><div v-for="child in childRows(row)" :key="`child-${child.unitId}`" class="flex items-center justify-between gap-3 text-sm"><span class="flex min-w-0 items-center gap-2"><CheckCircle2 v-if="child.status === 'candidate_ready'" class="h-4 w-4 text-emerald-500" /><LoaderCircle v-else-if="!isFailedParseRow(child)" class="h-4 w-4 animate-spin text-blue-500" /><AlertCircle v-else class="h-4 w-4 text-rose-500" /><span class="truncate">{{ child.fileName }}</span></span><span :class="rowStatusClass(child)">{{ rowStatusLabel(child) }}</span></div></div>
|
||||
</div>
|
||||
<div v-for="row in standaloneRows" :key="row.unitId" class="flex items-center justify-between gap-3 rounded-lg border border-slate-200 bg-white p-3 transition-colors hover:bg-slate-50 dark:border-slate-700 dark:bg-slate-900"><span class="flex min-w-0 items-center gap-3"><FileText class="h-5 w-5 text-slate-500" /><span class="truncate">{{ row.fileName }}</span></span><span class="flex items-center gap-2" :class="rowStatusClass(row)">{{ rowStatusLabel(row) }}<RefreshCw v-if="!isFailedParseRow(row)" class="h-4 w-4 animate-spin" /></span></div>
|
||||
<div v-if="!fileRows.length" class="rounded-lg border border-slate-200 bg-white p-3 text-sm text-slate-500 dark:border-slate-700 dark:bg-slate-900">{{ t('chat.shippingProcessing.batchFilesUnavailable') }}</div>
|
||||
<div v-for="row in failedRows" :key="`failed-${row.unitId}`" class="rounded-lg border border-rose-200 bg-rose-50 p-3 dark:border-rose-800 dark:bg-rose-950/30"><div class="flex items-center justify-between text-rose-600"><span class="flex items-center gap-2 font-medium"><AlertCircle class="h-5 w-5" />{{ row.fileName }}</span><span class="rounded bg-rose-100 px-2 py-0.5 text-xs">{{ t('chat.shippingProcessing.batchException') }}</span></div><p class="mt-2 pl-7 text-sm">{{ row.explainability?.message || t('chat.shippingProcessing.batchManualVerify') }}</p></div>
|
||||
</div>
|
||||
|
||||
<div class="flex justify-end border-t border-slate-200 bg-indigo-50/60 p-3 dark:border-slate-700 dark:bg-indigo-950/20">
|
||||
<div class="flex items-center gap-3">
|
||||
<button
|
||||
v-if="!compactProgress && (hasConversationStatusGroups || String(props.runNo || '').trim())"
|
||||
type="button"
|
||||
class="inline-flex items-center gap-2 rounded-lg bg-blue-600 px-5 py-2.5 text-sm font-medium text-white shadow-sm hover:bg-blue-700"
|
||||
data-testid="shipping-order-extraction-open-batch-workbench"
|
||||
@click="emit('open-batch-workbench')"
|
||||
>
|
||||
{{ t('chat.shippingProcessing.openBatchWorkbench') }}
|
||||
<ArrowRight class="h-4 w-4" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="false" class="flex items-start gap-3">
|
||||
<CircleX class="mt-0.5 h-4 w-4 shrink-0" />
|
||||
<div class="min-w-0 flex-1">
|
||||
<div
|
||||
v-if="readonly"
|
||||
@@ -394,7 +822,7 @@ async function onPrimaryChatAction() {
|
||||
class="mt-1 text-[11px] opacity-80"
|
||||
data-testid="shipping-order-extraction-error-request-id"
|
||||
>
|
||||
{{ t('chat.shippingOrderExtractionErrorRequestId', { id: state.errorExplainability.request_id }) }}
|
||||
{{ t('chat.shippingOrderExtractionErrorRequestId', { id: state.errorExplainability?.request_id }) }}
|
||||
</p>
|
||||
|
||||
<div
|
||||
@@ -424,12 +852,12 @@ async function onPrimaryChatAction() {
|
||||
type="button"
|
||||
class="inline-flex items-center rounded-md border border-current/20 px-2.5 py-1 text-xs font-medium hover:bg-black/5 dark:hover:bg-white/5"
|
||||
data-testid="shipping-order-extraction-primary-action"
|
||||
:disabled="primaryChatAction.kind === 'retry' && retrying"
|
||||
:disabled="primaryChatAction?.kind === 'retry' && retrying"
|
||||
@click="onPrimaryChatAction"
|
||||
>
|
||||
{{ primaryChatAction.kind === 'retry' && retrying
|
||||
{{ primaryChatAction?.kind === 'retry' && retrying
|
||||
? t('chat.shippingOrderExtractionRetrying')
|
||||
: primaryChatAction.label }}
|
||||
: primaryChatAction?.label }}
|
||||
</button>
|
||||
<button
|
||||
v-if="String(props.runNo || '').trim()"
|
||||
|
||||
+26
-23
@@ -7,7 +7,7 @@
|
||||
* 以模态对话框语义呈现(初始焦点、Tab 陷阱、Escape/关闭后焦点恢复);
|
||||
* 文档与时间线加载失败分别提供就地重试;内部错误码不向普通用户展示。
|
||||
*/
|
||||
import { nextTick, onBeforeUnmount, ref, watch } from 'vue';
|
||||
import { computed, nextTick, onBeforeUnmount, ref, watch } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { X } from 'lucide-vue-next';
|
||||
import type { ShippingOrderExtractionState } from '../../types/chat.types';
|
||||
@@ -42,6 +42,19 @@ const closeButtonRef = ref<HTMLButtonElement | null>(null);
|
||||
let previouslyFocused: HTMLElement | null = null;
|
||||
const timelineOpen = ref(false);
|
||||
|
||||
const timelineGroups = computed(() => {
|
||||
const groups = new Map<string, { documentId: number | null; fileName: string; events: ShippingOrderExtractionProgressEvent[] }>();
|
||||
for (const event of props.progressEvents) {
|
||||
const documentId = event.document_id != null ? Number(event.document_id) : null;
|
||||
const document = documentId == null ? null : props.documents.find((item) => Number(item.document_id) === documentId);
|
||||
const key = documentId == null ? 'run' : `document-${documentId}`;
|
||||
const group = groups.get(key) || { documentId, fileName: document?.file_name || (documentId == null ? t('chat.shippingOrderExtractionTimelineRunScope') : `Document ${documentId}`), events: [] };
|
||||
group.events.push(event);
|
||||
groups.set(key, group);
|
||||
}
|
||||
return [...groups.values()];
|
||||
});
|
||||
|
||||
const FOCUSABLE_SELECTOR = [
|
||||
'a[href]',
|
||||
'button:not([disabled])',
|
||||
@@ -314,28 +327,18 @@ onBeforeUnmount(() => {
|
||||
>
|
||||
{{ t('chat.shippingOrderExtractionTimelineEmpty') }}
|
||||
</div>
|
||||
<ol v-else class="mt-3 space-y-3">
|
||||
<li
|
||||
v-for="event in progressEvents"
|
||||
:key="`${event.event_code}-${event.unit_id || 0}-${event.document_id || 0}-${event.occurred_at}`"
|
||||
class="border-l-2 border-slate-200 pl-3 text-xs text-slate-700 dark:border-slate-700 dark:text-slate-200"
|
||||
>
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<span class="rounded-full bg-slate-100 px-2 py-0.5 text-[11px] font-medium text-slate-700 dark:bg-slate-800 dark:text-slate-200">
|
||||
{{ t(eventCategoryKey(event)) }}
|
||||
</span>
|
||||
<div class="font-medium text-slate-900 dark:text-slate-100">
|
||||
{{ eventActivityLabel(event) }}
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="eventContextLabel(event)" class="mt-1 opacity-85">
|
||||
{{ eventContextLabel(event) }}
|
||||
</div>
|
||||
<div class="mt-1 opacity-70">
|
||||
{{ eventOccurredAtLabel(event.occurred_at) }}
|
||||
</div>
|
||||
</li>
|
||||
</ol>
|
||||
<div v-else class="mt-3 space-y-3">
|
||||
<section v-for="group in timelineGroups" :key="group.documentId == null ? 'run' : group.documentId" class="rounded-md border border-slate-200 px-3 py-2 dark:border-slate-700">
|
||||
<h4 class="text-xs font-semibold text-slate-900 dark:text-slate-100">{{ group.fileName }}</h4>
|
||||
<ol class="mt-2 space-y-3">
|
||||
<li v-for="event in group.events" :key="`${event.event_code}-${event.unit_id || 0}-${event.document_id || 0}-${event.occurred_at}`" class="border-l-2 border-slate-200 pl-3 text-xs text-slate-700 dark:border-slate-700 dark:text-slate-200">
|
||||
<div class="flex flex-wrap items-center gap-2"><span class="rounded-full bg-slate-100 px-2 py-0.5 text-[11px] font-medium text-slate-700 dark:bg-slate-800 dark:text-slate-200">{{ t(eventCategoryKey(event)) }}</span><div class="font-medium text-slate-900 dark:text-slate-100">{{ eventActivityLabel(event) }}</div></div>
|
||||
<div v-if="eventContextLabel(event)" class="mt-1 opacity-85">{{ eventContextLabel(event) }}</div>
|
||||
<div class="mt-1 opacity-70">{{ eventOccurredAtLabel(event.occurred_at) }}</div>
|
||||
</li>
|
||||
</ol>
|
||||
</section>
|
||||
</div>
|
||||
</details>
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
+26
-1
@@ -30,6 +30,7 @@ function buildItem(patch: Partial<ShippingWorkflowItem> = {}): ShippingWorkflowI
|
||||
current_run_no: 'SNER-9',
|
||||
lifecycle_status: 'extracting',
|
||||
current_stage: 'extracting',
|
||||
available_actions: ['cancel'],
|
||||
lock_version: 1,
|
||||
events: [
|
||||
{
|
||||
@@ -113,11 +114,35 @@ describe('ShippingWorkflowItemDetailDrawer', () => {
|
||||
wrapper.unmount();
|
||||
});
|
||||
|
||||
it('does not infer any write or lifecycle entry from a local file status', () => {
|
||||
const wrapper = mount(ShippingWorkflowItemDetailDrawer, {
|
||||
props: {
|
||||
open: true,
|
||||
item: buildItem({
|
||||
lifecycle_status: 'pending_review',
|
||||
available_actions: [],
|
||||
}),
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
attachTo: document.body,
|
||||
});
|
||||
|
||||
// 空动作契约表示后端没有授予操作;状态名不得让前端补造入口。
|
||||
expect(drawerRoot()?.querySelector('[data-testid="shipping-workflow-action-open-review"]')).toBeNull();
|
||||
expect(drawerRoot()?.querySelector('[data-testid="shipping-workflow-item-drawer-reparse"]')).toBeNull();
|
||||
expect(drawerRoot()?.querySelector('[data-testid="shipping-workflow-item-drawer-cancel"]')).toBeNull();
|
||||
wrapper.unmount();
|
||||
});
|
||||
|
||||
it('hides cancel for closed items and emits close', async () => {
|
||||
const wrapper = mount(ShippingWorkflowItemDetailDrawer, {
|
||||
props: {
|
||||
open: true,
|
||||
item: buildItem({ lifecycle_status: 'closed', closed_reason: 'user_cancelled' }),
|
||||
item: buildItem({
|
||||
lifecycle_status: 'closed',
|
||||
closed_reason: 'user_cancelled',
|
||||
available_actions: [],
|
||||
}),
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
attachTo: document.body,
|
||||
|
||||
+5
-14
@@ -52,17 +52,13 @@ const events = computed((): ShippingWorkflowEvent[] => (
|
||||
|
||||
const canCancel = computed(() => {
|
||||
const actions = props.item?.available_actions;
|
||||
if (Array.isArray(actions)) return actions.includes('cancel') || Boolean(props.item);
|
||||
const status = String(props.item?.lifecycle_status || '').trim();
|
||||
return Boolean(props.item) && !['closed', 'cancelled'].includes(status);
|
||||
// [AUTHORITY] 文件动作只能由文档级 available_actions 授权;空数组就是明确无权限。
|
||||
return Array.isArray(actions) && actions.includes('cancel');
|
||||
});
|
||||
|
||||
const canReparse = computed(() => {
|
||||
const actions = props.item?.available_actions;
|
||||
if (Array.isArray(actions)) return actions.includes('reparse')
|
||||
|| ['failed', 'reparse_failed'].includes(String(props.item?.lifecycle_status || '').trim());
|
||||
// 无契约时 fail-closed,禁止仅凭 pending_review 展示。
|
||||
return false;
|
||||
return Array.isArray(actions) && actions.includes('reparse');
|
||||
});
|
||||
|
||||
const reparseActionLabel = computed(() => {
|
||||
@@ -75,13 +71,8 @@ const reparseActionLabel = computed(() => {
|
||||
const canOpenReview = computed(() => {
|
||||
if (!props.item) return false;
|
||||
const actions = props.item.available_actions;
|
||||
const status = String(props.item.lifecycle_status || '').trim();
|
||||
if (Array.isArray(actions)) {
|
||||
return actions.includes('view_details')
|
||||
|| actions.includes('enter_manual_review')
|
||||
|| status === 'pending_review';
|
||||
}
|
||||
return status === 'pending_review';
|
||||
// 生命周期工作台是独立授权,详情/人工复核动作不得隐式升级为生命周期入口。
|
||||
return Array.isArray(actions) && actions.includes('open_order_review');
|
||||
});
|
||||
|
||||
const filename = computed(() => {
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
import { computed, nextTick, onBeforeUnmount, ref, watch } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
|
||||
export type ShippingWorkflowReasonAction = 'cancel' | 'reparse';
|
||||
export type ShippingWorkflowReasonAction = 'cancel' | 'reparse' | 'reparse_batch';
|
||||
|
||||
const props = withDefaults(defineProps<{
|
||||
modelValue: boolean;
|
||||
@@ -31,13 +31,17 @@ const reasonMissing = ref(false);
|
||||
const reasonInputRef = ref<HTMLTextAreaElement | null>(null);
|
||||
|
||||
const title = computed(() => (
|
||||
props.action === 'reparse'
|
||||
props.action === 'reparse_batch'
|
||||
? t('chat.shippingProcessing.reasonDialog.reparseBatchTitle')
|
||||
: props.action === 'reparse'
|
||||
? t('chat.shippingProcessing.reasonDialog.reparseTitle')
|
||||
: t('chat.shippingProcessing.reasonDialog.cancelTitle')
|
||||
));
|
||||
|
||||
const confirmLabel = computed(() => (
|
||||
props.action === 'reparse'
|
||||
props.action === 'reparse_batch'
|
||||
? t('chat.shippingProcessing.reasonDialog.reparseBatchConfirm')
|
||||
: props.action === 'reparse'
|
||||
? t('chat.shippingProcessing.reasonDialog.reparseConfirm')
|
||||
: t('chat.shippingProcessing.reasonDialog.cancelConfirm')
|
||||
));
|
||||
@@ -149,7 +153,7 @@ onBeforeUnmount(() => {
|
||||
</p>
|
||||
|
||||
<label
|
||||
v-if="action === 'reparse'"
|
||||
v-if="action === 'reparse' || action === 'reparse_batch'"
|
||||
class="mt-2 block text-xs text-secondary"
|
||||
>
|
||||
{{ t('chat.shippingProcessing.reasonDialog.commentOptional') }}
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -53,7 +53,7 @@ const buildBatchUiStateEvent = (
|
||||
task_no: taskNo,
|
||||
batch_no: batchNo,
|
||||
checkpoint,
|
||||
process_status: 'matched',
|
||||
match_status: 'matched',
|
||||
review_status: null,
|
||||
pending_human_reason: null,
|
||||
match_status: 'fulfillable',
|
||||
@@ -92,7 +92,7 @@ describe('useChat shipping_ui_state SSE', () => {
|
||||
|
||||
expect(message.shipping_ui_state?.task_no).toBe('SN-UNIT-001');
|
||||
expect(message.shipping_actions).toBeUndefined();
|
||||
expect((message.payload as { action_buttons?: unknown[] }).action_buttons).toEqual([]);
|
||||
expect((message.payload as { action_buttons?: unknown[] }).action_buttons).toBeUndefined();
|
||||
expect((message.payload as { shipping_batch_ui_state?: { batch_no?: string } }).shipping_batch_ui_state?.batch_no).toBe('SB-UNIT-001');
|
||||
});
|
||||
|
||||
|
||||
@@ -151,7 +151,7 @@ export const applyShippingUiStateToMessage = (msg: ChatMessage, data: Record<str
|
||||
msg.shipping_ui_state = uiState;
|
||||
msg.shipping_actions = undefined;
|
||||
if (msg.type === 'shipping-match-result' && msg.payload && typeof msg.payload === 'object') {
|
||||
(msg.payload as { action_buttons?: ChatMessage['shipping_actions'] }).action_buttons = [];
|
||||
delete (msg.payload as { action_buttons?: ChatMessage['shipping_actions'] }).action_buttons;
|
||||
}
|
||||
msg.payload = {
|
||||
...(msg.payload && typeof msg.payload === 'object' ? msg.payload as Record<string, unknown> : {}),
|
||||
@@ -185,6 +185,7 @@ const normalizeShippingOrderExtractionState = (
|
||||
: null;
|
||||
return {
|
||||
status: status as ShippingOrderExtractionState['status'],
|
||||
uploadBatchId: String(data.uploadBatchId || '').trim() || null,
|
||||
summary: {
|
||||
totalDocuments: Math.max(0, Number(rawSummary.totalDocuments || 0)),
|
||||
pendingDocuments: Math.max(0, Number(rawSummary.pendingDocuments || 0)),
|
||||
@@ -207,6 +208,27 @@ const normalizeShippingOrderExtractionState = (
|
||||
: [],
|
||||
}
|
||||
: null,
|
||||
documents: Array.isArray(data.documents)
|
||||
? data.documents.map((item) => {
|
||||
const row = item && typeof item === 'object' ? item as Record<string, unknown> : {};
|
||||
return {
|
||||
unitId: Math.max(0, Number(row.unitId || 0)),
|
||||
documentId: Math.max(0, Number(row.documentId || 0)),
|
||||
intakeId: row.intakeId != null ? Math.max(0, Number(row.intakeId || 0)) || null : null,
|
||||
documentType: String(row.documentType || '').trim() || null,
|
||||
fileName: String(row.fileName || '').trim() || null,
|
||||
status: String(row.status || '').trim(),
|
||||
userVisibleStage: String(row.userVisibleStage || '').trim() || null,
|
||||
reasonCode: String(row.reasonCode || '').trim() || null,
|
||||
explainability: row.explainability && typeof row.explainability === 'object'
|
||||
? row.explainability as { message?: string | null }
|
||||
: null,
|
||||
emailSupplement: row.emailSupplement && typeof row.emailSupplement === 'object'
|
||||
? row.emailSupplement as { status?: string | null }
|
||||
: null,
|
||||
};
|
||||
})
|
||||
: [],
|
||||
selectionPlan: rawSelectionPlan
|
||||
? {
|
||||
selectionVersion: String(rawSelectionPlan.selectionVersion || '').trim() || null,
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
/**
|
||||
* features/chat/composables/useChatRouteSync.spec.ts
|
||||
* 用途:验证聊天路由初始化的关键首屏请求调度。
|
||||
* 依赖:vitest、useChatRouteSync。
|
||||
* 逻辑:历史会话列表属于后台辅助数据,不能阻塞指定 conversation 的消息与进度加载。
|
||||
*/
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
|
||||
vi.mock('vue', () => ({
|
||||
onBeforeUnmount: vi.fn(),
|
||||
onMounted: vi.fn(),
|
||||
watch: vi.fn(),
|
||||
}));
|
||||
|
||||
import { useChatRouteSync } from './useChatRouteSync';
|
||||
|
||||
describe('useChatRouteSync', () => {
|
||||
it('starts the requested conversation before the history list resolves', async () => {
|
||||
let resolveHistory!: () => void;
|
||||
const loadHistory = vi.fn(() => new Promise<void>((resolve) => {
|
||||
resolveHistory = resolve;
|
||||
}));
|
||||
const loadConversation = vi.fn(async () => undefined);
|
||||
const routeSync = useChatRouteSync({
|
||||
deps: {
|
||||
route: {
|
||||
params: { agentId: '24' },
|
||||
query: { conversation_id: 'conversation-b' },
|
||||
},
|
||||
router: { push: vi.fn() },
|
||||
} as never,
|
||||
currentAgentId: { value: 24 } as never,
|
||||
presetQuestion: { value: '' } as never,
|
||||
shippingTaskIdFromQuery: { value: null } as never,
|
||||
isShippingNoticeAgent: { value: true } as never,
|
||||
resetChatStateForAgentChange: vi.fn(),
|
||||
cancelVoiceInput: vi.fn(),
|
||||
syncCurrentUserProfile: vi.fn(async () => undefined),
|
||||
loadAgent: vi.fn(async () => undefined),
|
||||
loadUserAgents: vi.fn(async () => undefined),
|
||||
loadHistory,
|
||||
loadConversation,
|
||||
resumeShippingTaskFromQuery: vi.fn(async () => undefined),
|
||||
handleSend: vi.fn(async () => undefined),
|
||||
createNewChatView: vi.fn(),
|
||||
onAuthLogout: vi.fn(),
|
||||
onViewportResize: vi.fn(),
|
||||
disposePeripherals: vi.fn(),
|
||||
scheduleScrollToBottom: vi.fn(),
|
||||
input: { value: '' } as never,
|
||||
});
|
||||
|
||||
const pending = routeSync.syncChatStateForRoute();
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(loadHistory).toHaveBeenCalledTimes(1);
|
||||
expect(loadConversation).toHaveBeenCalledWith('conversation-b', { force: true });
|
||||
});
|
||||
|
||||
resolveHistory();
|
||||
await pending;
|
||||
});
|
||||
});
|
||||
@@ -94,16 +94,23 @@ export function useChatRouteSync(options: UseChatRouteSyncOptions) {
|
||||
await loadUserAgents();
|
||||
if (syncToken !== routeSyncToken) return;
|
||||
|
||||
await loadHistory();
|
||||
if (syncToken !== routeSyncToken) return;
|
||||
|
||||
const convId = route.query.conversation_id as string;
|
||||
// 历史列表是辅助内容;直达会话时不能阻塞消息/货代 Projection 的首屏读取。
|
||||
const historyPromise = loadHistory();
|
||||
if (convId) {
|
||||
await loadConversation(convId, { force: true });
|
||||
await Promise.all([
|
||||
historyPromise,
|
||||
loadConversation(convId, { force: true }),
|
||||
]);
|
||||
if (syncToken !== routeSyncToken) return;
|
||||
} else if (shippingTaskIdFromQuery.value || shippingBatchNoFromQuery?.value) {
|
||||
await historyPromise;
|
||||
if (syncToken !== routeSyncToken) return;
|
||||
await resumeShippingTaskFromQuery();
|
||||
if (syncToken !== routeSyncToken) return;
|
||||
} else {
|
||||
await historyPromise;
|
||||
if (syncToken !== routeSyncToken) return;
|
||||
}
|
||||
|
||||
if (presetQuestion.value) {
|
||||
|
||||
@@ -103,7 +103,7 @@ describe('useChatShipping persisted batch snapshot', () => {
|
||||
shipping_batch_ui_state: {
|
||||
batch_no: 'SB-EXISTING',
|
||||
current_focus_task_no: 'SN-EXISTING',
|
||||
tasks: [{ task_no: 'SN-EXISTING', source_type: 'email', process_status: 'pending_review' }],
|
||||
tasks: [{ task_no: 'SN-EXISTING', source_type: 'email', review_status: 'parse_review' }],
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -133,7 +133,7 @@ describe('useChatShipping message recovery payload', () => {
|
||||
shipping_ui_state: {
|
||||
task_no: 'SN-OPEN-EXISTING',
|
||||
batch_no: 'SB-OPEN-EXISTING',
|
||||
process_status: 'waiting_inventory',
|
||||
inventory_lines_json: [{ reservation_id: 'R-1' }],
|
||||
steps: [],
|
||||
summary: {},
|
||||
action_buttons: [],
|
||||
|
||||
@@ -554,7 +554,7 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
|
||||
const hasRunningShippingBatchTasks = () =>
|
||||
shippingBatchTasks.value.some(
|
||||
(task) => !['uploaded', 'completed', 'closed', 'rejected'].includes(String(task.process_status || '').trim()),
|
||||
(task) => String(task.ui_state?.stage?.code || '').trim() !== 'upload_complete',
|
||||
);
|
||||
|
||||
/**
|
||||
@@ -591,10 +591,10 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
const normalizedTaskId = String(taskId || getActiveShippingTaskId() || '').trim().toUpperCase();
|
||||
if (!conversationKey || !normalizedTaskId || !isShippingNoticeAgent.value || isShippingActionBusy.value) return;
|
||||
const detail = activeShippingTaskDetail.value;
|
||||
// 任务详情接口当前不返回顶层 checkpoint,parse_review 需从详情状态字段回推。
|
||||
// 复核同步只消费后端统一 ui_state.checkpoint,不读取 review_status 等领域事实推导。
|
||||
const checkpoint = String(
|
||||
(detail?.step_payload as Record<string, unknown> | undefined)?.checkpoint
|
||||
|| detail?.review_status
|
||||
detail?.ui_state?.checkpoint?.code
|
||||
|| detail?.ui_state?.checkpoint_code
|
||||
|| '',
|
||||
).trim();
|
||||
if (checkpoint !== 'parse_review') return;
|
||||
@@ -722,18 +722,10 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
});
|
||||
|
||||
const { executeShippingDecision, executeShippingManualUpload } = createShippingDecisionHandlers({
|
||||
messages,
|
||||
conversationId,
|
||||
history,
|
||||
isShippingNoticeAgent,
|
||||
currentAgentId,
|
||||
getActiveShippingTaskId,
|
||||
getActiveShippingBatchNo: () => resolvedShippingBatchNo.value || shippingBatchNoFromQuery.value || '',
|
||||
loadHistory,
|
||||
refreshShippingActions,
|
||||
startChatTurn,
|
||||
msg,
|
||||
t,
|
||||
refreshShippingActions,
|
||||
msg,
|
||||
t,
|
||||
});
|
||||
|
||||
const {
|
||||
@@ -970,7 +962,6 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
const {
|
||||
handleShippingAutoUploadFile,
|
||||
handleShippingAutoUploadNoticeBatch,
|
||||
openShippingInventoryPicker,
|
||||
openShippingNoticePicker,
|
||||
selectShippingInventoryUploadTask,
|
||||
cancelShippingInventoryTaskSelection,
|
||||
@@ -1019,20 +1010,16 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
|
||||
const { handleShippingMenuAction, handleShippingActionClick } = createShippingMenuHandlers({
|
||||
isThinking,
|
||||
currentAgentId,
|
||||
getActiveShippingTaskId,
|
||||
getActiveShippingBatchNo: () => resolvedShippingBatchNo.value || shippingBatchNoFromQuery.value || '',
|
||||
messages,
|
||||
sendShippingMenuMessage,
|
||||
openShippingInventoryPicker,
|
||||
openShippingNoticePicker,
|
||||
openShippingCustomerDialog,
|
||||
executeShippingDecision,
|
||||
executeShippingManualUpload,
|
||||
refreshShippingActions,
|
||||
startChatTurn,
|
||||
msg,
|
||||
t,
|
||||
msg,
|
||||
t,
|
||||
});
|
||||
|
||||
const { tryHandleShippingSend, tryHandleShippingAttachmentAutoFlow } = createShippingSendHandlers({
|
||||
@@ -1058,7 +1045,6 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
loadHistory,
|
||||
sendShippingMenuMessage,
|
||||
startChatTurn,
|
||||
openShippingInventoryPicker,
|
||||
executeShippingDecision,
|
||||
executeShippingManualUpload,
|
||||
handleShippingMenuAction,
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
/**
|
||||
* features/chat/composables/useProcurementContractChat.spec.ts
|
||||
* 用途:验证采购合同双文件选择后的即时可见状态。
|
||||
* 依赖:Vitest、Vue refs、useProcurementContractChat。
|
||||
* 逻辑:我方原合同选择后即展示本地文件名,FileAsset 上传仅补充可提交的资产编号。
|
||||
*/
|
||||
import { computed, ref } from 'vue';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { useProcurementContractChat } from './useProcurementContractChat';
|
||||
|
||||
const { uploadFileAsset } = vi.hoisted(() => ({ uploadFileAsset: vi.fn() }));
|
||||
|
||||
vi.mock('@/shared/api/file-assets.api', () => ({ uploadFileAsset }));
|
||||
|
||||
/** 构建只覆盖原合同选择流程的最小上下文。 */
|
||||
function createProcurementChat() {
|
||||
return useProcurementContractChat({
|
||||
currentAgent: ref({ agent_code: 'procurement_contract_review' }),
|
||||
currentAgentId: computed(() => 1),
|
||||
attachments: ref([]),
|
||||
messages: ref([]),
|
||||
isThinking: ref(false),
|
||||
isUploadingAttachments: ref(false),
|
||||
input: ref(''),
|
||||
clearAttachments: vi.fn(),
|
||||
saveLocalMessageToBackend: vi.fn(async () => undefined),
|
||||
loadHistory: vi.fn(async () => undefined),
|
||||
msg: { warning: vi.fn(), success: vi.fn(), info: vi.fn() },
|
||||
t: (key: string) => key,
|
||||
});
|
||||
}
|
||||
|
||||
describe('useProcurementContractChat original contract selection', () => {
|
||||
it('shows the selected original contract before its FileAsset upload finishes', async () => {
|
||||
let resolveUpload: ((value: { asset_no: string; original_filename: string }) => void) | undefined;
|
||||
uploadFileAsset.mockImplementation(() => new Promise((resolve) => { resolveUpload = resolve; }));
|
||||
const chat = createProcurementChat();
|
||||
const file = new File(['original'], '我方原合同.md', { type: 'text/markdown' });
|
||||
|
||||
const selecting = chat.handleOriginalContractSelected({ target: { files: [file], value: 'selected' } } as unknown as Event);
|
||||
|
||||
// 断言上传尚未完成时 UI 仍能立刻渲染已选择的我方原合同。
|
||||
expect(chat.originalContractName.value).toBe('我方原合同.md');
|
||||
expect(chat.originalContractAssetNo.value).toBeNull();
|
||||
|
||||
resolveUpload?.({ asset_no: 'FA-ORIGINAL-1', original_filename: '我方原合同.md' });
|
||||
await selecting;
|
||||
expect(chat.originalContractAssetNo.value).toBe('FA-ORIGINAL-1');
|
||||
});
|
||||
});
|
||||
@@ -131,12 +131,18 @@ export function useProcurementContractChat(options: ProcurementContractChatOptio
|
||||
const file = input.files?.[0];
|
||||
input.value = '';
|
||||
if (!file) return;
|
||||
// [STEP 1] 选择即展示,避免 FileAsset 网络上传期间输入栏看起来没有响应。
|
||||
originalContractAssetNo.value = null;
|
||||
originalContractName.value = file.name;
|
||||
options.isUploadingAttachments.value = true;
|
||||
try {
|
||||
const asset = await uploadFileAsset(file);
|
||||
// [STEP 2] 上传完成后才允许作为正式比对基准提交。
|
||||
originalContractAssetNo.value = asset.asset_no;
|
||||
originalContractName.value = asset.original_filename || file.name;
|
||||
} catch (e: unknown) {
|
||||
// 上传失败的临时卡片不可作为基准,必须移除,避免显示与提交状态不一致。
|
||||
clearOriginalContract();
|
||||
options.msg.warning(e instanceof Error ? e.message : options.t('chat.procurementContract.uploadFailed'));
|
||||
} finally {
|
||||
options.isUploadingAttachments.value = false;
|
||||
|
||||
@@ -15,7 +15,6 @@ export const SHIPPING_MENU_ACTION_SPECS: Record<
|
||||
ShippingMenuAction,
|
||||
{ id: string; label: string; message: string; variant: 'primary' | 'secondary' | 'danger' }
|
||||
> = {
|
||||
upload: { id: 'upload_inventory_file', label: '选择库存文件', message: '我要上传库存 Excel', variant: 'primary' },
|
||||
retry_rpa: { id: 'retry_rpa', label: '重新获取库存', message: '重新获取库存', variant: 'secondary' },
|
||||
confirm: { id: 'confirm', label: '确认', message: '确认', variant: 'primary' },
|
||||
reparse: { id: 'reparse', label: '重新解析', message: '重新解析', variant: 'secondary' },
|
||||
|
||||
@@ -5,6 +5,8 @@
|
||||
* 逻辑:断言 1920/1440/1366 下主滚动唯一、底栏 sticky;默认浮窗不进网格;固定侧栏才用双栏 token。
|
||||
*/
|
||||
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { resolve } from 'node:path';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
/** 方案冻结的三档验收视口。 */
|
||||
@@ -26,6 +28,12 @@ const PRIMARY_SCROLL_CLASS = 'overflow-y-auto';
|
||||
/** 浮动证据面板默认锚点(避开 sticky 底栏)。 */
|
||||
const FLOAT_ANCHOR = { bottomClass: 'bottom-20', zIndexClass: 'z-30' };
|
||||
|
||||
const lifecycleNavigationPath = resolve(
|
||||
__dirname,
|
||||
'../components/shipping-review/ReviewLifecycleStageNavigation.vue',
|
||||
);
|
||||
const reviewWorkbenchPath = resolve(__dirname, '../views/ShippingOrderReviewView.vue');
|
||||
|
||||
describe('shipping order review workbench viewport layout contract', () => {
|
||||
it('freezes three desktop acceptance viewports from the layout plan', () => {
|
||||
// 关键断言:验收矩阵不得悄悄缩减档位。
|
||||
@@ -56,4 +64,16 @@ describe('shipping order review workbench viewport layout contract', () => {
|
||||
expect(share1920).toBeGreaterThanOrEqual(0.65);
|
||||
expect(share1440).toBeGreaterThanOrEqual(0.62);
|
||||
});
|
||||
|
||||
it('keeps four lifecycle columns while reserving 16rem only for the desktop sidebar', () => {
|
||||
const lifecycleNavigation = readFileSync(lifecycleNavigationPath, 'utf8');
|
||||
const reviewWorkbench = readFileSync(reviewWorkbenchPath, 'utf8');
|
||||
|
||||
// 关键断言:接收解析为第四阶段;必须断言真实导航组件,不能只验证 spec 内常量。
|
||||
expect(lifecycleNavigation).toContain('class="grid gap-2 sm:grid-cols-4"');
|
||||
// sidebar/sidebar_search 是唯一允许预留 16rem 的模式;tabs/hidden/narrow 均落入 contents。
|
||||
expect(reviewWorkbench).toMatch(/reviewDocumentNavigationMode\.value === 'sidebar'\s*\|\|\s*reviewDocumentNavigationMode\.value === 'sidebar_search'/);
|
||||
expect(reviewWorkbench).toMatch(/:class="reviewDocumentNavigationUsesSidebar\s*\? 'grid gap-2 lg:grid-cols-\[16rem_minmax\(0,1fr\)\] lg:items-start lg:gap-3'\s*:\s*'contents'"/);
|
||||
expect(reviewWorkbench).not.toMatch(/reviewDocumentNavigationMode\.value === '(?:tabs|hidden|narrow)'\s*\?\s*'[^']*16rem/);
|
||||
});
|
||||
});
|
||||
@@ -24,7 +24,7 @@ vi.mock('../api/chat.api', () => ({
|
||||
|
||||
const createConversationContext = () => {
|
||||
const conversationId = ref<string | null>('conv-a');
|
||||
const messages = ref([]);
|
||||
const messages = ref<any[]>([{ role: 'assistant', content: 'old-a' }]);
|
||||
const createNewChatView = vi.fn(() => {
|
||||
conversationId.value = null;
|
||||
messages.value = [];
|
||||
@@ -44,7 +44,10 @@ const createConversationContext = () => {
|
||||
activeRunId: ref(null),
|
||||
messages,
|
||||
isThinking: ref(false),
|
||||
loadConversationState: vi.fn(),
|
||||
loadConversationState: (id, loaded) => {
|
||||
conversationId.value = id;
|
||||
messages.value = loaded;
|
||||
},
|
||||
createNewChatView,
|
||||
clearPendingNoticeBatchRetry,
|
||||
onConversationIdChanging: vi.fn(),
|
||||
@@ -152,4 +155,62 @@ describe('useChatPageConversation', () => {
|
||||
await handleShippingAutoUploadNoticeBatch([file]);
|
||||
expect(enqueueNoticeFiles).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('clears the previous conversation messages before an uncached history request resolves', async () => {
|
||||
let resolveMessages!: (value: any[]) => void;
|
||||
listChatMessages.mockImplementation(() => new Promise((resolve) => { resolveMessages = resolve; }));
|
||||
const { api, messages, conversationId } = createConversationContext();
|
||||
|
||||
const pending = api.loadConversation('conv-b', { force: true });
|
||||
|
||||
// 会话已切换但 B 尚无本地快照时,绝不能继续显示 A 的消息/订单卡。
|
||||
expect(conversationId.value).toBe('conv-b');
|
||||
expect(messages.value).toEqual([]);
|
||||
|
||||
resolveMessages([{ role: 'assistant', content: 'loaded-b' }]);
|
||||
await pending;
|
||||
expect(messages.value[0]?.content).toBe('loaded-b');
|
||||
});
|
||||
|
||||
it('restores cached messages immediately and discards a late response from an older selection', async () => {
|
||||
const pending = new Map<string, { resolve: (value: any[]) => void }>();
|
||||
listChatMessages.mockImplementation((id: string) => new Promise((resolve) => {
|
||||
pending.set(id, { resolve });
|
||||
}));
|
||||
const { api, messages, conversationId } = createConversationContext();
|
||||
|
||||
const firstB = api.loadConversation('conv-b', { force: true });
|
||||
pending.get('conv-b')!.resolve([{ role: 'assistant', content: 'cached-b' }]);
|
||||
await firstB;
|
||||
|
||||
const selectA = api.loadConversation('conv-a', { force: true });
|
||||
const returnB = api.loadConversation('conv-b', { force: true });
|
||||
expect(messages.value[0]?.content).toBe('cached-b');
|
||||
|
||||
pending.get('conv-a')!.resolve([{ role: 'assistant', content: 'late-a' }]);
|
||||
pending.get('conv-b')!.resolve([{ role: 'assistant', content: 'cached-b' }]);
|
||||
await Promise.all([selectA, returnB]);
|
||||
|
||||
expect(conversationId.value).toBe('conv-b');
|
||||
expect(messages.value[0]?.content).toBe('cached-b');
|
||||
});
|
||||
|
||||
it('keeps the rendered cached message array when revalidation is semantically unchanged', async () => {
|
||||
const pending = new Map<string, { resolve: (value: any[]) => void }>();
|
||||
listChatMessages.mockImplementation((id: string) => new Promise((resolve) => {
|
||||
pending.set(id, { resolve });
|
||||
}));
|
||||
const { api, messages } = createConversationContext();
|
||||
|
||||
const initial = api.loadConversation('conv-b', { force: true });
|
||||
pending.get('conv-b')!.resolve([{ chat_log_id: 91, role: 'assistant', content: 'stable-b' }]);
|
||||
await initial;
|
||||
|
||||
const revalidate = api.loadConversation('conv-b', { force: true });
|
||||
const renderedCache = messages.value;
|
||||
pending.get('conv-b')!.resolve([{ chat_log_id: 91, role: 'assistant', content: 'stable-b' }]);
|
||||
await revalidate;
|
||||
|
||||
expect(messages.value).toBe(renderedCache);
|
||||
});
|
||||
});
|
||||
@@ -37,6 +37,30 @@ export interface ChatPageConversationContext {
|
||||
}
|
||||
|
||||
export function createChatPageConversationApi(ctx: ChatPageConversationContext) {
|
||||
// 会话消息与发货 Projection 使用相同的 SWR 原则:仅在内存保留最近成功快照;
|
||||
// 路由切换先原子显示目标会话快照(或空白),再后台读取,不能让旧会话占据新会话首帧。
|
||||
const messageSnapshots = new Map<string, ChatMessage[]>();
|
||||
let messageRequestGeneration = 0;
|
||||
|
||||
const touchMessageSnapshot = (id: string, messages: ChatMessage[]) => {
|
||||
messageSnapshots.delete(id);
|
||||
messageSnapshots.set(id, messages);
|
||||
while (messageSnapshots.size > 20) {
|
||||
const oldestId = messageSnapshots.keys().next().value as string | undefined;
|
||||
if (!oldestId) break;
|
||||
messageSnapshots.delete(oldestId);
|
||||
}
|
||||
};
|
||||
|
||||
const messageSemanticKey = (items: ChatMessage[]) => JSON.stringify(items.map((item) => ({
|
||||
id: item.chat_log_id ?? item.local_id ?? null,
|
||||
role: item.role,
|
||||
type: item.type,
|
||||
content: item.content,
|
||||
payload: item.payload ?? null,
|
||||
attachments: item.attachments ?? [],
|
||||
})));
|
||||
|
||||
const loadConversation = async (id: string, options?: { force?: boolean }) => {
|
||||
const force = options?.force ?? false;
|
||||
if (!force && ctx.conversationId.value === id && !ctx.activeRunId.value && ctx.messages.value.length > 0) {
|
||||
@@ -44,6 +68,8 @@ export function createChatPageConversationApi(ctx: ChatPageConversationContext)
|
||||
}
|
||||
|
||||
const prevConversationId = ctx.conversationId.value;
|
||||
const generation = ++messageRequestGeneration;
|
||||
const cachedMessages = messageSnapshots.get(id);
|
||||
try {
|
||||
/**
|
||||
* 切换会话前先清空输入框草稿,避免 textarea DOM 里残留上一会话的可见文本,
|
||||
@@ -51,9 +77,19 @@ export function createChatPageConversationApi(ctx: ChatPageConversationContext)
|
||||
*/
|
||||
ctx.input.value = '';
|
||||
ctx.onConversationIdChanging(id, prevConversationId);
|
||||
// [STEP 1] 先切换消息容器:未访问会话渲染空白而非上一会话;
|
||||
// 已访问会话复用自身快照,避免“缓存卡先出现后整页闪一下”。
|
||||
ctx.loadConversationState(id, cachedMessages ? [...cachedMessages] : []);
|
||||
const loaded = await listChatMessages(id, ctx.currentAgentId.value);
|
||||
ctx.loadConversationState(id, Array.isArray(loaded) ? loaded : []);
|
||||
if (!loaded?.length) {
|
||||
if (generation !== messageRequestGeneration || ctx.conversationId.value !== id) return;
|
||||
const nextMessages = Array.isArray(loaded) ? loaded : [];
|
||||
const currentMessages = ctx.messages.value;
|
||||
touchMessageSnapshot(id, nextMessages);
|
||||
// 同一会话后台重验没有业务变化时,保留消息数组和子卡实例,避免缓存首帧后闪一下。
|
||||
if (messageSemanticKey(currentMessages) !== messageSemanticKey(nextMessages)) {
|
||||
ctx.loadConversationState(id, nextMessages);
|
||||
}
|
||||
if (!nextMessages.length) {
|
||||
await ctx.onConversationLoadedEmpty();
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -82,7 +82,6 @@ export function buildReviewWorkbenchDisplayCase(
|
||||
build_eligibility: shellSource?.draft?.build_eligibility ?? undefined,
|
||||
},
|
||||
available_actions: [],
|
||||
conversation_allowed_actions: [],
|
||||
formal_editable_field_ids: [],
|
||||
order_data_version: null,
|
||||
llm_suggestions: [],
|
||||
|
||||
@@ -2,8 +2,7 @@
|
||||
* features/chat/shipping-review/useShippingOrderReview.spec.ts
|
||||
* 用途:阶段 3 复核页历史版本只读、草稿版本冲突、建单资格门禁、库存候选与路由恢复写入冒烟。
|
||||
* 依赖:isReviewCaseHistorical / isDraftVersionMismatchError / summarizeDraftConflictDiff /
|
||||
* isBuildConfirmBlocked / lineNeedsManualInventorySelection /
|
||||
* lineHasPendingRoutingSuggestion / lineNeedsInventoryRoutingRecovery、useShippingOrderReview。
|
||||
* isBuildConfirmBlocked / lineNeedsInventoryRoutingRecovery、useShippingOrderReview。
|
||||
* 逻辑:断言 superseded 只读、版本冲突码识别、差异摘要、confirm 门禁、inventory PUT、
|
||||
* reroute/adopt/keep 与 suggestion_pending 行筛选。
|
||||
*/
|
||||
@@ -18,8 +17,6 @@ import {
|
||||
isReviewCaseHistorical,
|
||||
isReviewReadOnly,
|
||||
isReviewWorkItemClosed,
|
||||
lineNeedsManualInventorySelection,
|
||||
lineHasPendingRoutingSuggestion,
|
||||
lineNeedsInventoryRoutingRecovery,
|
||||
mapReviewContextLifecycleStatus,
|
||||
REVIEW_BUILD_ELIGIBILITY_BLOCKED,
|
||||
@@ -42,22 +39,25 @@ const api = vi.hoisted(() => ({
|
||||
|
||||
getRun: vi.fn(),
|
||||
|
||||
getQueue: vi.fn(),
|
||||
|
||||
getEvidence: vi.fn(),
|
||||
|
||||
getPreview: vi.fn(),
|
||||
|
||||
getIntakeParseContext: vi.fn(),
|
||||
|
||||
getExtractionRun: vi.fn(),
|
||||
getProcessingWorkItem: vi.fn(),
|
||||
|
||||
reparseDocument: vi.fn(),
|
||||
|
||||
putInventoryCandidates: vi.fn(),
|
||||
rerouteInventoryRouting: vi.fn(),
|
||||
adoptInventoryRoutingSuggestion: vi.fn(),
|
||||
keepManualInventoryRouting: vi.fn(),
|
||||
|
||||
confirmCase: vi.fn(),
|
||||
|
||||
validateDraft: vi.fn(),
|
||||
|
||||
}));
|
||||
|
||||
|
||||
@@ -72,17 +72,18 @@ vi.mock('../api/shipping.api', () => ({
|
||||
|
||||
getWorkspaceShippingOrderReviewRun: api.getRun,
|
||||
|
||||
getWorkspaceShippingOrderReviewQueue: api.getQueue,
|
||||
|
||||
getWorkspaceShippingOrderReviewEvidence: api.getEvidence,
|
||||
|
||||
getWorkspaceShippingOrderReviewPreview: api.getPreview,
|
||||
|
||||
getWorkspaceShippingOrderReviewIntakeParseContext: api.getIntakeParseContext,
|
||||
|
||||
getWorkspaceShippingOrderExtractionRun: api.getExtractionRun,
|
||||
getWorkspaceShippingProcessingWorkItem: api.getProcessingWorkItem,
|
||||
|
||||
putWorkspaceShippingOrderReviewInventoryCandidates: api.putInventoryCandidates,
|
||||
postWorkspaceShippingOrderReviewInventoryRoutingReroute: api.rerouteInventoryRouting,
|
||||
postWorkspaceShippingOrderReviewInventoryRoutingAdoptSuggestion: api.adoptInventoryRoutingSuggestion,
|
||||
postWorkspaceShippingOrderReviewInventoryRoutingKeepManual: api.keepManualInventoryRouting,
|
||||
|
||||
confirmWorkspaceShippingOrderReviewCase: api.confirmCase,
|
||||
|
||||
@@ -96,7 +97,7 @@ vi.mock('../api/shipping.api', () => ({
|
||||
|
||||
deleteWorkspaceShippingOrderReviewLine: vi.fn(),
|
||||
|
||||
validateWorkspaceShippingOrderReviewDraft: vi.fn(),
|
||||
validateWorkspaceShippingOrderReviewDraft: api.validateDraft,
|
||||
|
||||
createWorkspaceShippingOrderReviewManualDraft: vi.fn(),
|
||||
|
||||
@@ -335,36 +336,6 @@ describe('build eligibility helpers', () => {
|
||||
|
||||
|
||||
|
||||
it('detects lines needing manual inventory selection', () => {
|
||||
|
||||
expect(lineNeedsManualInventorySelection({ can_build: true })).toBe(false);
|
||||
|
||||
expect(lineNeedsManualInventorySelection({
|
||||
|
||||
can_build: false,
|
||||
|
||||
candidate_inventory_source_codes: ['DSV360_AWSDU'],
|
||||
|
||||
})).toBe(true);
|
||||
|
||||
expect(lineNeedsManualInventorySelection({
|
||||
|
||||
can_build: false,
|
||||
|
||||
block_reason: 'require_manual_review',
|
||||
|
||||
})).toBe(true);
|
||||
|
||||
expect(lineNeedsManualInventorySelection({
|
||||
|
||||
can_build: false,
|
||||
|
||||
block_reason: 'customer_unresolved',
|
||||
|
||||
})).toBe(false);
|
||||
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
|
||||
@@ -381,10 +352,26 @@ describe('useShippingOrderReview build eligibility writes', () => {
|
||||
|
||||
});
|
||||
|
||||
api.getQueue.mockResolvedValue({
|
||||
summary: { total: 1, needs_action: 1, processing: 0, completed: 0 },
|
||||
items: [{ case_no: 'CASE-1', document_id: 1, status: 'draft', issue_count: 0, available_actions: [] }],
|
||||
});
|
||||
|
||||
api.getEvidence.mockResolvedValue({ items: [] });
|
||||
|
||||
api.getPreview.mockRejectedValue(new Error('preview unavailable'));
|
||||
|
||||
api.getIntakeParseContext.mockImplementation(async (caseNo: string) => ({
|
||||
case_no: caseNo,
|
||||
attachment: {
|
||||
document_id: caseNo === 'CASE-2' ? 2 : 1,
|
||||
filename: caseNo === 'CASE-2' ? 'second.pdf' : 'order.pdf',
|
||||
mime_type: 'application/pdf',
|
||||
preview_kind: 'pdf',
|
||||
},
|
||||
email: null,
|
||||
}));
|
||||
|
||||
api.getProcessingWorkItem.mockRejectedValue(
|
||||
Object.assign(new Error('not found'), { name: 'BusinessError', status: 404, code: 'NOT_FOUND' }),
|
||||
);
|
||||
@@ -403,7 +390,7 @@ describe('useShippingOrderReview build eligibility writes', () => {
|
||||
|
||||
|
||||
|
||||
it('exposes buildEligibility and manualInventoryLines from active case draft', async () => {
|
||||
it('exposes buildEligibility and automatic routing recovery lines from active case draft', async () => {
|
||||
|
||||
const review = useShippingOrderReview();
|
||||
|
||||
@@ -413,9 +400,8 @@ describe('useShippingOrderReview build eligibility writes', () => {
|
||||
|
||||
expect(review.canConfirmBuild.value).toBe(false);
|
||||
|
||||
expect(review.manualInventoryLines.value).toHaveLength(1);
|
||||
|
||||
expect(review.manualInventoryLines.value[0]?.line_key).toBe('line-1');
|
||||
expect(review.routingRecoveryLines.value).toHaveLength(1);
|
||||
expect(review.routingRecoveryLines.value[0]?.line_key).toBe('line-1');
|
||||
|
||||
});
|
||||
|
||||
@@ -436,6 +422,180 @@ describe('useShippingOrderReview build eligibility writes', () => {
|
||||
expect(review.previewUrl.value).toMatch(/^blob:/);
|
||||
});
|
||||
|
||||
it('applies the latest Case returned by save and validate', async () => {
|
||||
const review = useShippingOrderReview();
|
||||
await review.load('RUN-1', 'CASE-1');
|
||||
api.validateDraft.mockResolvedValue({
|
||||
case: buildCase({
|
||||
draft: { ...buildCase().draft!, draft_version: 3 },
|
||||
}),
|
||||
resume_outcome: { outcome: 'auto_create_enqueued' },
|
||||
});
|
||||
|
||||
await review.validate();
|
||||
|
||||
expect(api.validateDraft).toHaveBeenCalledWith('CASE-1', 2);
|
||||
expect(review.activeCase.value?.draft?.draft_version).toBe(3);
|
||||
});
|
||||
|
||||
it('refreshes the current Case silently without entering the PDF-switch loading state', async () => {
|
||||
const review = useShippingOrderReview();
|
||||
await review.load('RUN-1', 'CASE-1');
|
||||
const blob = new Blob(['%PDF'], { type: 'application/pdf' });
|
||||
api.getPreview.mockResolvedValue(blob);
|
||||
await review.ensurePreviewLoaded('CASE-1');
|
||||
|
||||
api.getCase.mockResolvedValue(buildCase({
|
||||
draft: { ...buildCase().draft!, draft_version: 3 },
|
||||
}));
|
||||
await review.reloadLatestDraft();
|
||||
|
||||
// Gate 操作后的同步不能冒充 PDF 切换:保留工作面和已加载预览,不展示大骨架。
|
||||
expect(review.caseSwitchLoading.value).toBe(false);
|
||||
expect(review.caseSwitchFailed.value).toBe(false);
|
||||
expect(review.activeCase.value?.draft?.draft_version).toBe(3);
|
||||
expect(review.previewCaseNo.value).toBe('CASE-1');
|
||||
expect(review.previewUrl.value).toMatch(/^blob:/);
|
||||
});
|
||||
|
||||
it('discards a stale preview success after Case A switches to Case B', async () => {
|
||||
const review = useShippingOrderReview();
|
||||
await review.load('RUN-1', 'CASE-1');
|
||||
let resolveA: ((value: Blob) => void) | null = null;
|
||||
let resolveB: ((value: Blob) => void) | null = null;
|
||||
api.getPreview.mockImplementation((caseNo: string) => new Promise<Blob>((resolve) => {
|
||||
if (caseNo === 'CASE-1') resolveA = resolve;
|
||||
if (caseNo === 'CASE-2') resolveB = resolve;
|
||||
}));
|
||||
|
||||
const previewA = review.ensurePreviewLoaded('CASE-1');
|
||||
api.getCase.mockResolvedValue(buildCase({ case_no: 'CASE-2', document: { id: 2, file_name: 'second.pdf' } }));
|
||||
await review.selectCase('CASE-2');
|
||||
// 关键断言:切换立即清除旧 URL;B 必须启动独立预览请求,不能复用 A in-flight。
|
||||
expect(review.previewUrl.value).toBe('');
|
||||
const previewB = review.ensurePreviewLoaded('CASE-2');
|
||||
expect(api.getPreview).toHaveBeenNthCalledWith(1, 'CASE-1');
|
||||
expect(api.getPreview).toHaveBeenNthCalledWith(2, 'CASE-2');
|
||||
|
||||
resolveA?.(new Blob(['A'], { type: 'application/pdf' }));
|
||||
await expect(previewA).resolves.toBe(false);
|
||||
expect(review.previewUrl.value).toBe('');
|
||||
resolveB?.(new Blob(['B'], { type: 'application/pdf' }));
|
||||
await expect(previewB).resolves.toBe(true);
|
||||
expect(review.previewCaseNo.value).toBe('CASE-2');
|
||||
expect(review.previewUrl.value).toMatch(/^blob:/);
|
||||
});
|
||||
|
||||
it('discards a stale preview failure after Case A switches to Case B', async () => {
|
||||
const review = useShippingOrderReview();
|
||||
await review.load('RUN-1', 'CASE-1');
|
||||
let rejectA: ((reason?: unknown) => void) | null = null;
|
||||
let resolveB: ((value: Blob) => void) | null = null;
|
||||
api.getPreview.mockImplementation((caseNo: string) => new Promise<Blob>((resolve, reject) => {
|
||||
if (caseNo === 'CASE-1') rejectA = reject;
|
||||
if (caseNo === 'CASE-2') resolveB = resolve;
|
||||
}));
|
||||
|
||||
const previewA = review.ensurePreviewLoaded('CASE-1');
|
||||
api.getCase.mockResolvedValue(buildCase({ case_no: 'CASE-2', document: { id: 2, file_name: 'second.pdf' } }));
|
||||
await review.selectCase('CASE-2');
|
||||
const previewB = review.ensurePreviewLoaded('CASE-2');
|
||||
rejectA?.(new Error('stale preview failure'));
|
||||
await expect(previewA).resolves.toBe(false);
|
||||
// 关键断言:A 的失败不能把 B 标为预览失败或清空 B 的进行态。
|
||||
expect(review.previewLoadFailed.value).toBe(false);
|
||||
expect(review.previewLoading.value).toBe(true);
|
||||
resolveB?.(new Blob(['B'], { type: 'application/pdf' }));
|
||||
await expect(previewB).resolves.toBe(true);
|
||||
expect(review.previewCaseNo.value).toBe('CASE-2');
|
||||
expect(review.previewLoadFailed.value).toBe(false);
|
||||
});
|
||||
|
||||
it('loads intake parse context on demand for the active Case and clears it before a new Case resolves', async () => {
|
||||
const review = useShippingOrderReview();
|
||||
await review.load('RUN-1', 'CASE-1');
|
||||
|
||||
expect(api.getIntakeParseContext).not.toHaveBeenCalled();
|
||||
await review.ensureIntakeParseContextLoaded('CASE-1');
|
||||
expect(api.getIntakeParseContext).toHaveBeenCalledWith('CASE-1');
|
||||
expect(review.intakeParseContext.value?.case_no).toBe('CASE-1');
|
||||
|
||||
let resolveCase: ((value: ShippingOrderReviewCase) => void) | null = null;
|
||||
api.getCase.mockImplementation((caseNo: string) => caseNo === 'CASE-2'
|
||||
? new Promise<ShippingOrderReviewCase>((resolve) => { resolveCase = resolve; })
|
||||
: Promise.resolve(buildCase({ case_no: caseNo })));
|
||||
const pending = review.selectCase('CASE-2');
|
||||
|
||||
// 关键断言:切换附件期间不得展示 CASE-1 的 EML/附件上下文。
|
||||
expect(review.intakeParseContext.value).toBeNull();
|
||||
expect(review.intakeParseLoading.value).toBe(false);
|
||||
resolveCase?.(buildCase({ case_no: 'CASE-2', document: { id: 2, file_name: 'second.pdf' } }));
|
||||
await pending;
|
||||
await review.ensureIntakeParseContextLoaded('CASE-2');
|
||||
|
||||
expect(api.getIntakeParseContext).toHaveBeenLastCalledWith('CASE-2');
|
||||
expect(review.intakeParseContext.value?.case_no).toBe('CASE-2');
|
||||
});
|
||||
|
||||
it('does not retain an older intake context when the next Case context request fails', async () => {
|
||||
const review = useShippingOrderReview();
|
||||
await review.load('RUN-1', 'CASE-1');
|
||||
await review.ensureIntakeParseContextLoaded('CASE-1');
|
||||
expect(review.intakeParseContext.value?.case_no).toBe('CASE-1');
|
||||
|
||||
api.getCase.mockResolvedValue(buildCase({ case_no: 'CASE-2', document: { id: 2, file_name: 'second.pdf' } }));
|
||||
await review.selectCase('CASE-2');
|
||||
api.getIntakeParseContext.mockRejectedValueOnce(new Error('context unavailable'));
|
||||
|
||||
await expect(review.ensureIntakeParseContextLoaded('CASE-2')).resolves.toBe(false);
|
||||
// 关键断言:失败只显示本次错误,不得回退为上一附件的邮件正文。
|
||||
expect(review.intakeParseContext.value).toBeNull();
|
||||
expect(review.intakeParseLoadFailed.value).toBe(true);
|
||||
});
|
||||
|
||||
it('keeps the latest same-Case intake context when an older success resolves last', async () => {
|
||||
const review = useShippingOrderReview();
|
||||
await review.load('RUN-1', 'CASE-1');
|
||||
let resolveFirst: ((value: Record<string, unknown>) => void) | null = null;
|
||||
let resolveSecond: ((value: Record<string, unknown>) => void) | null = null;
|
||||
api.getIntakeParseContext
|
||||
.mockImplementationOnce(() => new Promise((resolve) => { resolveFirst = resolve; }))
|
||||
.mockImplementationOnce(() => new Promise((resolve) => { resolveSecond = resolve; }));
|
||||
|
||||
const first = review.ensureIntakeParseContextLoaded('CASE-1');
|
||||
const second = review.ensureIntakeParseContextLoaded('CASE-1');
|
||||
resolveSecond?.({ case_no: 'CASE-1', attachment: { document_id: 2, filename: 'latest.pdf', mime_type: 'application/pdf', preview_kind: 'pdf' }, email: null });
|
||||
await second;
|
||||
resolveFirst?.({ case_no: 'CASE-1', attachment: { document_id: 1, filename: 'stale.pdf', mime_type: 'application/pdf', preview_kind: 'pdf' }, email: null });
|
||||
await first;
|
||||
|
||||
// 关键断言:同一 Case 的旧成功响应不可覆盖后发请求的附件/EML。
|
||||
expect(review.intakeParseContext.value?.attachment.filename).toBe('latest.pdf');
|
||||
expect(review.intakeParseLoadFailed.value).toBe(false);
|
||||
});
|
||||
|
||||
it('keeps the latest same-Case success when an older request fails last', async () => {
|
||||
const review = useShippingOrderReview();
|
||||
await review.load('RUN-1', 'CASE-1');
|
||||
let rejectFirst: ((reason?: unknown) => void) | null = null;
|
||||
let resolveSecond: ((value: Record<string, unknown>) => void) | null = null;
|
||||
api.getIntakeParseContext
|
||||
.mockImplementationOnce(() => new Promise((_, reject) => { rejectFirst = reject; }))
|
||||
.mockImplementationOnce(() => new Promise((resolve) => { resolveSecond = resolve; }));
|
||||
|
||||
const first = review.ensureIntakeParseContextLoaded('CASE-1');
|
||||
const second = review.ensureIntakeParseContextLoaded('CASE-1');
|
||||
resolveSecond?.({ case_no: 'CASE-1', attachment: { document_id: 2, filename: 'latest.pdf', mime_type: 'application/pdf', preview_kind: 'pdf' }, email: null });
|
||||
await second;
|
||||
rejectFirst?.(new Error('stale failure'));
|
||||
await first;
|
||||
|
||||
// 关键断言:旧失败不得清空新成功结果或重新标记本次加载失败。
|
||||
expect(review.intakeParseContext.value?.attachment.filename).toBe('latest.pdf');
|
||||
expect(review.intakeParseLoadFailed.value).toBe(false);
|
||||
expect(review.intakeParseLoading.value).toBe(false);
|
||||
});
|
||||
|
||||
it('clears activeCase immediately while switching and keeps empty shell on failure (UI-01)', async () => {
|
||||
// 关键断言:loading 期间不得保留旧 Case 业务对象;失败后也不得回显旧值。
|
||||
let resolveCase: ((value: ShippingOrderReviewCase) => void) | null = null;
|
||||
@@ -509,76 +669,6 @@ describe('useShippingOrderReview build eligibility writes', () => {
|
||||
expect(review.activeCase.value?.case_no).toBe('CASE-B');
|
||||
});
|
||||
|
||||
it('submits inventory candidates via PUT and refreshes case', async () => {
|
||||
|
||||
const updated = buildCase({
|
||||
|
||||
draft: {
|
||||
|
||||
...buildCase().draft!,
|
||||
|
||||
draft_version: 3,
|
||||
|
||||
build_eligibility: {
|
||||
|
||||
can_build: true,
|
||||
|
||||
status: 'ready',
|
||||
|
||||
line_projections: [{
|
||||
|
||||
line_key: 'line-1',
|
||||
|
||||
line_index: 0,
|
||||
|
||||
can_build: true,
|
||||
|
||||
selection_mode: 'manual',
|
||||
|
||||
manual_reason: 'Confirmed with planner',
|
||||
|
||||
candidate_inventory_source_codes: ['DSV360_AWSDU'],
|
||||
|
||||
}],
|
||||
|
||||
},
|
||||
|
||||
},
|
||||
|
||||
});
|
||||
|
||||
api.putInventoryCandidates.mockResolvedValue(updated);
|
||||
|
||||
|
||||
|
||||
const review = useShippingOrderReview();
|
||||
|
||||
await review.load('RUN-1', 'CASE-1');
|
||||
|
||||
await review.setLineInventoryCandidates('line-1', ['DSV360_AWSDU'], 'Confirmed with planner');
|
||||
|
||||
|
||||
|
||||
expect(api.putInventoryCandidates).toHaveBeenCalledWith('CASE-1', 'line-1', {
|
||||
|
||||
expected_draft_version: 2,
|
||||
|
||||
source_codes: ['DSV360_AWSDU'],
|
||||
|
||||
reason: 'Confirmed with planner',
|
||||
|
||||
});
|
||||
|
||||
expect(review.activeCase.value?.draft?.draft_version).toBe(3);
|
||||
|
||||
expect(review.buildEligibility.value?.can_build).toBe(true);
|
||||
|
||||
expect(review.canConfirmBuild.value).toBe(true);
|
||||
|
||||
});
|
||||
|
||||
|
||||
|
||||
it('blocks confirm when build eligibility cannot build', async () => {
|
||||
|
||||
const review = useShippingOrderReview();
|
||||
@@ -666,7 +756,7 @@ describe('useShippingOrderReview build eligibility writes', () => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it('notifies the conversation workflow when auto progress reaches a retryable terminal state', async () => {
|
||||
it('keeps polling after a recoverable RPA failure so a later callback can refresh the workflow', async () => {
|
||||
vi.useFakeTimers();
|
||||
const onWorkflowRefresh = vi.fn();
|
||||
const readyCase: ShippingOrderReviewCase = {
|
||||
@@ -681,7 +771,8 @@ describe('useShippingOrderReview build eligibility writes', () => {
|
||||
api.getPreview.mockResolvedValue({ preview_url: '' });
|
||||
api.getProcessingWorkItem
|
||||
.mockResolvedValueOnce({ work_item_no: 'OT-1', status: 'building_order' })
|
||||
.mockResolvedValueOnce({ work_item_no: 'OT-1', status: 'retryable', retryable: true });
|
||||
.mockResolvedValueOnce({ work_item_no: 'OT-1', status: 'retryable', retryable: true })
|
||||
.mockResolvedValueOnce({ work_item_no: 'OT-1', status: 'completed' });
|
||||
api.confirmCase.mockResolvedValue({
|
||||
task_no: 'SN-1', order_task_no: 'OT-1', shipping_notice_no: 'SN-1', idempotent_replay: false,
|
||||
workflow_id: 'WF-1', case: { ...readyCase, status: 'confirmed', order_task_no: 'OT-1' }, auto_progress_started: true,
|
||||
@@ -694,6 +785,10 @@ describe('useShippingOrderReview build eligibility writes', () => {
|
||||
await Promise.resolve();
|
||||
|
||||
expect(onWorkflowRefresh).toHaveBeenCalled();
|
||||
// RPA 可重试失败不是工作流关闭;必须继续读取后续成功回调的 Projection。
|
||||
expect(review.workflowProgressPolling.value).toBe(true);
|
||||
await vi.advanceTimersByTimeAsync(2600);
|
||||
await Promise.resolve();
|
||||
expect(review.workflowProgressPolling.value).toBe(false);
|
||||
review.stopWorkflowProgressPolling();
|
||||
vi.useRealTimers();
|
||||
@@ -719,7 +814,7 @@ describe('useShippingOrderReview build eligibility writes', () => {
|
||||
expect(review.reviewProgressContext.value?.user_task_authoritative).toBe(true);
|
||||
});
|
||||
|
||||
it('leaves OT unset during reparse polling when candidate-bound case lacks order_task_no', async () => {
|
||||
it('leaves OT unset while waiting for a reparse Case when candidate-bound case lacks order_task_no', async () => {
|
||||
vi.useFakeTimers();
|
||||
api.getCase.mockResolvedValue(buildCase({
|
||||
candidate_id: 42,
|
||||
@@ -752,11 +847,11 @@ describe('useShippingOrderReview build eligibility writes', () => {
|
||||
expect(review.reviewProgressContext.value?.user_task_no).toBeNull();
|
||||
expect(review.reviewProgressContext.value?.user_task_authoritative).toBe(false);
|
||||
|
||||
review.stopReparseProgressPolling();
|
||||
review.stopReparseCaseRefreshPolling();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it('polls reparse progress and loads the new review version when ready', async () => {
|
||||
it('loads the new review version when completed reparse has activated its Stream Case', async () => {
|
||||
vi.useFakeTimers();
|
||||
let reparsePollCount = 0;
|
||||
api.reparseDocument.mockImplementation(async () => ({
|
||||
@@ -765,17 +860,26 @@ describe('useShippingOrderReview build eligibility writes', () => {
|
||||
}));
|
||||
api.getRun.mockImplementation(async (runNo: string) => ({
|
||||
run_no: runNo,
|
||||
status: runNo === 'RUN-2' ? 'review_required' : 'review_required',
|
||||
status: runNo === 'RUN-2' ? 'completed' : 'review_required',
|
||||
summary: {},
|
||||
items: [{ case_no: runNo === 'RUN-2' ? 'CASE-2' : 'CASE-1', status: 'draft', issue_count: 0 }],
|
||||
}));
|
||||
api.getQueue.mockImplementation(async (runNo: string) => ({
|
||||
summary: { total: 1, needs_action: 1, processing: 0, completed: 0 },
|
||||
items: [{
|
||||
case_no: runNo === 'RUN-2' ? 'CASE-2' : 'CASE-1',
|
||||
document_id: 1,
|
||||
source_run_no: runNo,
|
||||
status: 'draft', issue_count: 0, available_actions: [],
|
||||
}],
|
||||
}));
|
||||
api.getExtractionRun.mockImplementation(async (runNo: string) => {
|
||||
reparsePollCount += 1;
|
||||
const ready = runNo === 'RUN-2' && reparsePollCount >= 2;
|
||||
return {
|
||||
run_no: runNo,
|
||||
status: ready ? 'review_required' : 'extracting',
|
||||
current_activity: { user_visible_stage: ready ? 'review_required' : 'extracting' },
|
||||
status: ready ? 'completed' : 'extracting',
|
||||
current_activity: { user_visible_stage: ready ? 'completed' : 'extracting' },
|
||||
};
|
||||
});
|
||||
api.getCase.mockImplementation(async (caseNo: string) => buildCase({
|
||||
@@ -787,19 +891,16 @@ describe('useShippingOrderReview build eligibility writes', () => {
|
||||
await review.load('RUN-1', 'CASE-1', { conversationId: 'conv-1', itemNo: 'SWI-1' });
|
||||
await review.reparseDocument('document_quality');
|
||||
|
||||
expect(review.reparseProgressActive.value).toBe(true);
|
||||
await vi.advanceTimersByTimeAsync(2600);
|
||||
await Promise.resolve();
|
||||
|
||||
expect(review.reparseProgressStage.value).toBe('draft_ready');
|
||||
expect(review.reparseProgressPolling.value).toBe(false);
|
||||
expect(review.reviewRun.value?.run_no).toBe('RUN-2');
|
||||
expect(review.activeCase.value?.case_no).toBe('CASE-2');
|
||||
review.stopReparseProgressPolling();
|
||||
review.stopReparseCaseRefreshPolling();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it('loads a partially completed reparse result and clears the read-only progress state', async () => {
|
||||
it('loads a partially completed reparse result without a legacy read-only progress state', async () => {
|
||||
vi.useFakeTimers();
|
||||
api.reparseDocument.mockImplementation(async () => ({
|
||||
run: { run_no: 'RUN-PARTIAL', items: [], summary: {} },
|
||||
@@ -816,6 +917,15 @@ describe('useShippingOrderReview build eligibility writes', () => {
|
||||
status: runNo === 'RUN-PARTIAL' ? 'partially_completed' : 'review_required',
|
||||
current_activity: { user_visible_stage: 'review_required' },
|
||||
}));
|
||||
api.getQueue.mockImplementation(async (runNo: string) => ({
|
||||
summary: { total: 1, needs_action: 1, processing: 0, completed: 0 },
|
||||
items: [{
|
||||
case_no: runNo === 'RUN-PARTIAL' ? 'CASE-PARTIAL' : 'CASE-1',
|
||||
document_id: 1,
|
||||
source_run_no: runNo,
|
||||
status: 'draft', issue_count: 0, available_actions: [],
|
||||
}],
|
||||
}));
|
||||
api.getCase.mockImplementation(async (caseNo: string) => buildCase({
|
||||
case_no: caseNo,
|
||||
run_no: caseNo === 'CASE-PARTIAL' ? 'RUN-PARTIAL' : 'RUN-1',
|
||||
@@ -829,59 +939,69 @@ describe('useShippingOrderReview build eligibility writes', () => {
|
||||
|
||||
expect(review.reviewRun.value?.run_no).toBe('RUN-PARTIAL');
|
||||
expect(review.activeCase.value?.case_no).toBe('CASE-PARTIAL');
|
||||
expect(review.reparseProgressStage.value).toBe('draft_ready');
|
||||
expect(review.reparseProgressPolling.value).toBe(false);
|
||||
expect(review.reparseProgressActive.value).toBe(false);
|
||||
expect(review.isReadOnly.value).toBe(false);
|
||||
expect(review.statusMessage.value).not.toBe('reparse_in_progress');
|
||||
review.stopReparseProgressPolling();
|
||||
review.stopReparseCaseRefreshPolling();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it('resolves the replacement run when superseded_by_run_no is set', async () => {
|
||||
it('opens the Stream current version instead of retaining a historical Case', async () => {
|
||||
api.getQueue.mockResolvedValue({
|
||||
summary: { total: 1, needs_action: 1, processing: 0, completed: 0 },
|
||||
items: [{ case_no: 'CASE-2', document_id: 1, source_run_no: 'RUN-2', status: 'draft', issue_count: 0, available_actions: [] }],
|
||||
});
|
||||
api.getRun.mockImplementation(async (runNo: string) => ({
|
||||
run_no: runNo, summary: {},
|
||||
items: [{ case_no: runNo === 'RUN-2' ? 'CASE-2' : 'CASE-1', document_id: 1, status: 'draft', issue_count: 0 }],
|
||||
}));
|
||||
api.getCase.mockImplementation(async (caseNo: string) => buildCase({
|
||||
case_no: caseNo, run_no: caseNo === 'CASE-2' ? 'RUN-2' : 'RUN-1',
|
||||
}));
|
||||
const review = useShippingOrderReview();
|
||||
await review.load('RUN-1', 'CASE-1', { conversationId: 'conv-1', itemNo: 'SWI-1' });
|
||||
review.reviewRun.value!.superseded_by_run_no = 'RUN-2';
|
||||
api.getRun.mockResolvedValue({
|
||||
run_no: 'RUN-2', summary: {}, items: [{ case_no: 'CASE-2', status: 'draft', issue_count: 0 }],
|
||||
});
|
||||
api.getCase.mockResolvedValue(buildCase({ case_no: 'CASE-2', run_no: 'RUN-2' }));
|
||||
|
||||
const target = await review.openCurrentVersion();
|
||||
|
||||
expect(target).toEqual({ runNo: 'RUN-2', caseNo: 'CASE-2' });
|
||||
expect(review.activeCase.value?.case_no).toBe('CASE-2');
|
||||
});
|
||||
|
||||
it('resolves the replacement run when the historical item still points at the open case', async () => {
|
||||
it('does not jump to a different PDF when the Stream contains multiple documents', async () => {
|
||||
api.getRun.mockImplementation(async (runNo: string) => runNo === 'RUN-1'
|
||||
? {
|
||||
run_no: 'RUN-1',
|
||||
run_no: runNo,
|
||||
summary: {},
|
||||
items: [{ case_no: 'CASE-1', status: 'superseded', issue_count: 0 }],
|
||||
}
|
||||
: {
|
||||
run_no: 'RUN-2',
|
||||
run_no: runNo,
|
||||
summary: {},
|
||||
items: [{ case_no: 'CASE-2', status: 'draft', issue_count: 0 }],
|
||||
items: [{ case_no: runNo === 'RUN-3' ? 'CASE-1-NEW' : 'CASE-2', status: 'draft', issue_count: 0 }],
|
||||
});
|
||||
api.getCase.mockImplementation(async (caseNo: string) => buildCase({
|
||||
case_no: caseNo,
|
||||
run_no: caseNo === 'CASE-2' ? 'RUN-2' : 'RUN-1',
|
||||
status: caseNo === 'CASE-2' ? 'draft' : 'superseded',
|
||||
run_no: caseNo === 'CASE-1-NEW' ? 'RUN-3' : caseNo === 'CASE-2' ? 'RUN-2' : 'RUN-1',
|
||||
status: caseNo === 'CASE-1-NEW' || caseNo === 'CASE-2' ? 'draft' : 'superseded',
|
||||
}));
|
||||
api.getQueue.mockResolvedValue({
|
||||
summary: { total: 2, needs_action: 2, processing: 0, completed: 0 },
|
||||
items: [
|
||||
{ case_no: 'CASE-1-NEW', document_id: 1, source_run_no: 'RUN-3', status: 'draft', issue_count: 0, available_actions: [] },
|
||||
{ case_no: 'CASE-2', document_id: 2, source_run_no: 'RUN-2', status: 'draft', issue_count: 0, available_actions: [] },
|
||||
],
|
||||
});
|
||||
|
||||
const review = useShippingOrderReview();
|
||||
await review.load('RUN-1', 'CASE-1', { conversationId: 'conv-1', itemNo: 'SWI-1' });
|
||||
review.reviewRun.value!.superseded_by_run_no = 'RUN-2';
|
||||
const target = await review.openCurrentVersion();
|
||||
|
||||
expect(target).toEqual({ runNo: 'RUN-2', caseNo: 'CASE-2' });
|
||||
expect(review.reviewRun.value?.run_no).toBe('RUN-2');
|
||||
expect(review.activeCase.value?.case_no).toBe('CASE-2');
|
||||
expect(target).toEqual({ runNo: 'RUN-3', caseNo: 'CASE-1-NEW' });
|
||||
expect(review.reviewRun.value?.run_no).toBe('RUN-3');
|
||||
expect(review.activeCase.value?.case_no).toBe('CASE-1-NEW');
|
||||
});
|
||||
|
||||
it('shows a terminal failed stage when reparse fails', async () => {
|
||||
it('stops waiting when reparse fails without exposing a synthetic stage', async () => {
|
||||
vi.useFakeTimers();
|
||||
api.reparseDocument.mockResolvedValue({
|
||||
run: { run_no: 'RUN-FAILED', items: [], summary: {} }, reused: false,
|
||||
@@ -896,9 +1016,8 @@ describe('useShippingOrderReview build eligibility writes', () => {
|
||||
await vi.advanceTimersByTimeAsync(2600);
|
||||
await Promise.resolve();
|
||||
|
||||
expect(review.reparseProgressStage.value).toBe('failed');
|
||||
expect(review.reparseProgressPolling.value).toBe(false);
|
||||
review.stopReparseProgressPolling();
|
||||
expect(review.reviewRun.value?.run_no).toBe('RUN-1');
|
||||
review.stopReparseCaseRefreshPolling();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
@@ -932,24 +1051,14 @@ describe('inventory routing recovery', () => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it('detects pending suggestion and recovery lines beyond manual selection', () => {
|
||||
// 关键断言:suggestion_pending 即使 can_build true 也应进入恢复集合。
|
||||
expect(lineHasPendingRoutingSuggestion({ suggestion_pending: true })).toBe(true);
|
||||
expect(lineNeedsInventoryRoutingRecovery({
|
||||
can_build: true,
|
||||
suggestion_pending: true,
|
||||
})).toBe(true);
|
||||
it('detects automatic routing recovery lines', () => {
|
||||
expect(lineNeedsInventoryRoutingRecovery({
|
||||
can_build: true,
|
||||
unavailable_source_codes: ['OFFLINE_SRC'],
|
||||
})).toBe(true);
|
||||
expect(lineNeedsManualInventorySelection({
|
||||
can_build: true,
|
||||
suggestion_pending: true,
|
||||
})).toBe(false);
|
||||
});
|
||||
|
||||
it('exposes routingRecoveryLines for suggestion_pending rows', async () => {
|
||||
it('exposes routingRecoveryLines for blocked rule rows', async () => {
|
||||
api.getCase.mockResolvedValue(buildCase({
|
||||
draft: {
|
||||
...buildCase().draft!,
|
||||
@@ -959,8 +1068,8 @@ describe('inventory routing recovery', () => {
|
||||
line_projections: [{
|
||||
line_key: 'line-pending',
|
||||
line_index: 0,
|
||||
can_build: true,
|
||||
suggestion_pending: true,
|
||||
can_build: false,
|
||||
block_reason: 'inventory_source_unavailable',
|
||||
rule_suggestion_source_codes: ['DSV360_AWSDU'],
|
||||
candidate_inventory_source_codes: ['DSV360_AWSHK'],
|
||||
selection_mode: 'manual',
|
||||
@@ -970,7 +1079,6 @@ describe('inventory routing recovery', () => {
|
||||
}));
|
||||
const review = useShippingOrderReview();
|
||||
await review.load('RUN-1', 'CASE-1');
|
||||
expect(review.manualInventoryLines.value).toHaveLength(0);
|
||||
expect(review.routingRecoveryLines.value).toHaveLength(1);
|
||||
expect(review.routingRecoveryLines.value[0]?.line_key).toBe('line-pending');
|
||||
});
|
||||
@@ -993,32 +1101,6 @@ describe('inventory routing recovery', () => {
|
||||
uuidSpy.mockRestore();
|
||||
});
|
||||
|
||||
it('adopts and keeps inventory routing suggestions via POST APIs', async () => {
|
||||
const updated = buildCase({ draft: { ...buildCase().draft!, draft_version: 4 } });
|
||||
api.adoptInventoryRoutingSuggestion.mockResolvedValue(updated);
|
||||
api.keepManualInventoryRouting.mockResolvedValue(updated);
|
||||
const uuidSpy = vi.spyOn(crypto, 'randomUUID')
|
||||
.mockReturnValueOnce('idem-adopt-1')
|
||||
.mockReturnValueOnce('idem-keep-1');
|
||||
|
||||
const review = useShippingOrderReview();
|
||||
await review.load('RUN-1', 'CASE-1');
|
||||
await review.adoptInventoryRoutingSuggestion('line-1', 'use rule');
|
||||
await review.keepManualInventoryRouting('line-1', 'keep manual');
|
||||
|
||||
expect(api.adoptInventoryRoutingSuggestion).toHaveBeenCalledWith('CASE-1', 'line-1', {
|
||||
expected_draft_version: 2,
|
||||
idempotency_key: 'idem-adopt-1',
|
||||
reason: 'use rule',
|
||||
});
|
||||
expect(api.keepManualInventoryRouting).toHaveBeenCalledWith('CASE-1', 'line-1', {
|
||||
expected_draft_version: 4,
|
||||
idempotency_key: 'idem-keep-1',
|
||||
reason: 'keep manual',
|
||||
});
|
||||
uuidSpy.mockRestore();
|
||||
});
|
||||
|
||||
it('sets draftConflict on 409 VERSION_MISMATCH during reroute', async () => {
|
||||
api.rerouteInventoryRouting.mockRejectedValue(
|
||||
new BusinessError({ message: 'stale', code: REVIEW_DRAFT_VERSION_MISMATCH }),
|
||||
|
||||
@@ -5,23 +5,23 @@
|
||||
* 逻辑:按 runNo 加载 Review Run/Case;合成 ShippingReviewProgressContext;
|
||||
* OT 绑定 Case.order_task_no / Candidate;切换 Case 时清空 activeCase(纯 skeleton,禁止旧值 DOM);
|
||||
* 409 REVIEW_DRAFT_VERSION_MISMATCH 冲突处理;build_eligibility 驱动 confirm/reroute;
|
||||
* 重识别轮询 extraction-run;PDF Blob 由 ensurePreviewLoaded 按需加载。
|
||||
* 重识别后刷新正式 Run/Case/Gate 投影;PDF Blob 由 ensurePreviewLoaded 按需加载。
|
||||
*/
|
||||
import { computed, getCurrentInstance, onBeforeUnmount, ref } from 'vue';
|
||||
import { BusinessError } from '@/shared/api/client';
|
||||
import {
|
||||
addWorkspaceShippingOrderReviewLine,
|
||||
createWorkspaceShippingOrderReviewManualDraft,
|
||||
createWorkspaceShippingOrderReviewReplacementIntake,
|
||||
createWorkspaceShippingOrderReviewReplacementRun,
|
||||
copyWorkspaceShippingOrderReviewLine,
|
||||
confirmWorkspaceShippingOrderReviewCase,
|
||||
deleteWorkspaceShippingOrderReviewLine,
|
||||
getWorkspaceShippingOrderReviewCase,
|
||||
getWorkspaceShippingOrderReviewEvidence,
|
||||
getWorkspaceShippingOrderReviewIntakeParseContext,
|
||||
getWorkspaceShippingOrderReviewPreview,
|
||||
getShippingNoticeIntake,
|
||||
getWorkspaceShippingOrderReviewEmailEvidencePreview,
|
||||
getWorkspaceShippingOrderReviewRun,
|
||||
getWorkspaceShippingOrderReviewQueue,
|
||||
getWorkspaceShippingOrderExtractionRun,
|
||||
patchWorkspaceShippingOrderReviewHeaderField,
|
||||
patchWorkspaceShippingOrderReviewLineField,
|
||||
@@ -29,9 +29,6 @@ import {
|
||||
updateWorkspaceShippingNoticeLine,
|
||||
markWorkspaceShippingOrderReviewNonOrder,
|
||||
markWorkspaceShippingOrderReviewQualityIssue,
|
||||
putWorkspaceShippingOrderReviewInventoryCandidates,
|
||||
postWorkspaceShippingOrderReviewInventoryRoutingAdoptSuggestion,
|
||||
postWorkspaceShippingOrderReviewInventoryRoutingKeepManual,
|
||||
postWorkspaceShippingOrderReviewInventoryRoutingReroute,
|
||||
reparseWorkspaceShippingOrderReviewDocument,
|
||||
validateWorkspaceShippingOrderReviewDraft,
|
||||
@@ -46,15 +43,17 @@ import type {
|
||||
ShippingOrderReviewCaseLoadingContext,
|
||||
ShippingOrderReviewCaseSnapshot,
|
||||
ShippingOrderReviewEvidence,
|
||||
ShippingOrderReviewIntakeParseContext,
|
||||
ShippingOrderReviewLlmAdjudicationPayload,
|
||||
ShippingOrderReviewLlmSuggestion,
|
||||
ShippingOrderExtractionRun,
|
||||
ShippingOrderReviewRun,
|
||||
ShippingOrderReviewQueue,
|
||||
ShippingOrderReviewEmailEvidencePreview,
|
||||
ShippingReviewProgressContext,
|
||||
ShippingReviewProgressVersion,
|
||||
ShippingWorkflowItemLifecycleStatus,
|
||||
} from '../types/shipping.api.types';
|
||||
import { uploadFileAsset } from '@/shared/api/file-assets.api';
|
||||
import { useShippingProcessingWorkItem } from '../shipping/useShippingProcessingWorkItem';
|
||||
|
||||
/** ???????????? */
|
||||
@@ -72,15 +71,6 @@ export const REVIEW_DRAFT_VERSION_MISMATCH = 'SHIPPING.REVIEW_DRAFT_VERSION_MISM
|
||||
/** ?????????? confirm ????? */
|
||||
export const REVIEW_BUILD_ELIGIBILITY_BLOCKED = 'SHIPPING.REVIEW_BUILD_ELIGIBILITY_BLOCKED';
|
||||
|
||||
/** ????????????????????????? */
|
||||
const INVENTORY_BLOCK_REASONS = new Set([
|
||||
'require_manual_review',
|
||||
'no_inventory_source_candidates',
|
||||
'manual_inventory_source_reason_required',
|
||||
'manual_inventory_source_invalid',
|
||||
'inventory_source_unresolved',
|
||||
]);
|
||||
|
||||
/** ????????????/??????????? Case ??? */
|
||||
export type DraftVersionConflict = {
|
||||
localVersion: number;
|
||||
@@ -179,25 +169,6 @@ export function isBuildConfirmBlocked(eligibility?: ShippingOrderReviewBuildElig
|
||||
* ????????????????????
|
||||
* ??????? can_build ? false ????????????????
|
||||
*/
|
||||
export function lineNeedsManualInventorySelection(
|
||||
line: ShippingOrderReviewBuildEligibilityLineProjection,
|
||||
): boolean {
|
||||
if (line.can_build !== false) return false;
|
||||
const codes = line.candidate_inventory_source_codes || [];
|
||||
if (codes.length > 0) return true;
|
||||
return INVENTORY_BLOCK_REASONS.has(String(line.block_reason || '').trim());
|
||||
}
|
||||
|
||||
/**
|
||||
* ?????????????????????????????
|
||||
* @param line - build_eligibility ???
|
||||
*/
|
||||
export function lineHasPendingRoutingSuggestion(
|
||||
line: ShippingOrderReviewBuildEligibilityLineProjection,
|
||||
): boolean {
|
||||
return line.suggestion_pending === true;
|
||||
}
|
||||
|
||||
/**
|
||||
* ??????????????????? / ???? / ??????
|
||||
* ?????suggestion_pending?unavailable_source_codes ??????????????
|
||||
@@ -206,9 +177,8 @@ export function lineHasPendingRoutingSuggestion(
|
||||
export function lineNeedsInventoryRoutingRecovery(
|
||||
line: ShippingOrderReviewBuildEligibilityLineProjection,
|
||||
): boolean {
|
||||
if (lineHasPendingRoutingSuggestion(line)) return true;
|
||||
if ((line.unavailable_source_codes || []).length > 0) return true;
|
||||
return lineNeedsManualInventorySelection(line);
|
||||
return line.can_build === false && Boolean(String(line.block_reason || '').trim());
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -329,6 +299,7 @@ function synthesizeWorkItemFromReviewContext(params: {
|
||||
|
||||
export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void } = {}) {
|
||||
const reviewRun = ref<ShippingOrderReviewRun | null>(null);
|
||||
const reviewQueue = ref<ShippingOrderReviewQueue | null>(null);
|
||||
const activeCase = ref<ShippingOrderReviewCase | null>(null);
|
||||
const caseProjectionVersion = ref<number | null>(null);
|
||||
const caseLoadingContext = ref<ShippingOrderReviewCaseLoadingContext | null>(null);
|
||||
@@ -386,7 +357,16 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
|
||||
const previewCaseNo = ref<string | null>(null);
|
||||
const previewLoading = ref(false);
|
||||
const previewLoadFailed = ref(false);
|
||||
let previewInflight: Promise<boolean> | null = null;
|
||||
const emailPreview = ref<ShippingOrderReviewEmailEvidencePreview | null>(null);
|
||||
/** 接收解析工作面专用上下文;切换 Case 或重新加载时必须立即清空,禁止串附件/EML。 */
|
||||
const intakeParseContext = ref<ShippingOrderReviewIntakeParseContext | null>(null);
|
||||
const intakeParseLoading = ref(false);
|
||||
const intakeParseLoadFailed = ref(false);
|
||||
/** 接收解析上下文请求代次:同一 Case 的后发请求必须覆盖并作废前发请求。 */
|
||||
let intakeParseRequestGeneration = 0;
|
||||
/** PDF 预览请求代次:切换 Case 后旧 Blob/失败都不得写回当前附件。 */
|
||||
let previewRequestGeneration = 0;
|
||||
let previewInflight: { caseNo: string; promise: Promise<boolean> } | null = null;
|
||||
/** Case 切换请求代次:快速切换时丢弃过期响应,禁止旧 Case 覆盖新 Case。 */
|
||||
let caseLoadGeneration = 0;
|
||||
/** 当前正在请求或已选定的 Case 编号(与 generation 双校验)。 */
|
||||
@@ -398,34 +378,11 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
|
||||
/** ?????????? Workflow ????? */
|
||||
const showWorkflowProgress = ref(false);
|
||||
const workflowProgressPolling = ref(false);
|
||||
/** ??????? WorkflowItem ???????????????? */
|
||||
const reparseProgressActive = ref(false);
|
||||
const reparseProgressPolling = ref(false);
|
||||
const reparseProgressRefreshFailed = ref(false);
|
||||
const reparseProgressStage = ref<'submitted' | 'layout_parsing' | 'routing' | 'extracting' | 'validating' | 'draft_ready' | 'auto_confirming' | 'building_order' | 'inventory_matching' | 'generating_excel' | 'awaiting_manual_action' | 'completed' | 'failed' | 'interrupted'>('submitted');
|
||||
/** ?????????????????/????????????????? */
|
||||
const reparseLastStableStage = ref<'submitted' | 'layout_parsing' | 'routing' | 'extracting' | 'validating' | 'draft_ready' | 'auto_confirming' | 'building_order' | 'inventory_matching' | 'generating_excel' | 'awaiting_manual_action' | 'completed'>('submitted');
|
||||
const reparseRunStatus = ref<string>('queued');
|
||||
const reparseLastActivityAt = ref<string | null>(null);
|
||||
/** ????????????????????????????????? */
|
||||
const reparseLastRefreshedAt = ref<string | null>(null);
|
||||
const reparseStalePolls = ref(0);
|
||||
const reparsePendingReviewPolls = ref(0);
|
||||
let contextConversationId = '';
|
||||
let contextItemNo = '';
|
||||
let progressPollTimer: ReturnType<typeof window.setInterval> | null = null;
|
||||
let reparsePollTimer: ReturnType<typeof window.setInterval> | null = null;
|
||||
let reparsePollTick: (() => Promise<void>) | null = null;
|
||||
let reparseCaseRefreshTimer: ReturnType<typeof window.setInterval> | null = null;
|
||||
const PROGRESS_POLL_MS = 2500;
|
||||
/** ??????????????????reparse_kind ????????? */
|
||||
const REPARSE_RUNNING_LIFECYCLES = new Set([
|
||||
'layout_parsing', 'waiting_layout', 'routing', 'matching_profile',
|
||||
'extracting', 'merging_supplement',
|
||||
]);
|
||||
/** ??????????? Run ?????????????????? Case? */
|
||||
const REPARSE_REVIEW_READY_STATUSES = new Set([
|
||||
'review_required', 'partially_completed',
|
||||
]);
|
||||
|
||||
/**
|
||||
* 应用后端返回的完整 Case 快照。
|
||||
@@ -449,39 +406,26 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
|
||||
workflowProgressPolling.value = false;
|
||||
};
|
||||
|
||||
/** ?? PDF ?????????????????????? */
|
||||
const stopReparseProgressPolling = () => {
|
||||
if (reparsePollTimer != null) {
|
||||
window.clearInterval(reparsePollTimer);
|
||||
reparsePollTimer = null;
|
||||
}
|
||||
reparseProgressPolling.value = false;
|
||||
reparsePollTick = null;
|
||||
};
|
||||
|
||||
/**
|
||||
* ? Extraction Run ?????????????? Case ????????
|
||||
* @param runNo - reparse API ???? Run ???????? pending_review ??????
|
||||
* 等待后端明确产出新复核 Case 后切换工作台,不将 Run 技术状态推断成另一条用户进度。
|
||||
*
|
||||
* AI 触发时机:用户发起“重新识别此 PDF”后调用。
|
||||
* 核心逻辑:以会话级 Review Stream 队列中同一 document_id 的 source_run_no + case_no
|
||||
* 触发 Case 加载;completed 也可能已生成可复核 Case,不能仅按 Run 技术终态停止。
|
||||
* failed/cancelled 仅刷新正式投影并停止,失败原因由正式状态卡与 Gate 表达。
|
||||
*
|
||||
* Args:
|
||||
* runNo: 重识别请求返回的后继 Run 编号。
|
||||
*/
|
||||
const startReparseProgressPolling = (runNo: string, restoreExisting = false) => {
|
||||
stopReparseProgressPolling();
|
||||
const startReparseCaseRefreshPolling = (runNo: string) => {
|
||||
stopReparseCaseRefreshPolling();
|
||||
const targetRunNo = String(runNo || '').trim();
|
||||
const targetDocumentId = currentStreamDocumentId();
|
||||
if (!targetRunNo) return;
|
||||
reparseProgressActive.value = true;
|
||||
reparseProgressPolling.value = true;
|
||||
reparseProgressRefreshFailed.value = false;
|
||||
if (!restoreExisting) {
|
||||
reparseProgressStage.value = 'submitted';
|
||||
reparseLastStableStage.value = 'submitted';
|
||||
reparseRunStatus.value = 'queued';
|
||||
reparseLastActivityAt.value = null;
|
||||
reparseLastRefreshedAt.value = null;
|
||||
reparseStalePolls.value = 0;
|
||||
reparsePendingReviewPolls.value = 0;
|
||||
}
|
||||
const tick = async () => {
|
||||
try {
|
||||
const run = await getWorkspaceShippingOrderExtractionRun(targetRunNo);
|
||||
const normalizedStatus = String(run.status || '').trim();
|
||||
const synthesized = synthesizeWorkItemFromReviewContext({
|
||||
reviewRun: reviewRun.value,
|
||||
activeCase: activeCase.value,
|
||||
@@ -490,112 +434,37 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
|
||||
extractionRun: run,
|
||||
});
|
||||
if (synthesized) reviewProgressContext.value = synthesized;
|
||||
|
||||
reparseProgressRefreshFailed.value = false;
|
||||
reparseStalePolls.value = 0;
|
||||
reparseLastRefreshedAt.value = new Date().toISOString();
|
||||
reparseRunStatus.value = String(run.status || '').trim() || 'queued';
|
||||
reparseLastActivityAt.value = run.current_activity?.last_activity_at || run.last_activity_at || null;
|
||||
|
||||
const normalizedRunStatus = String(run.status || '').trim();
|
||||
const runStage = String(run.current_activity?.user_visible_stage || run.user_visible_stage || '').trim();
|
||||
const lifecycle = String(synthesized?.lifecycle_status || '').trim();
|
||||
|
||||
if (['review_required', 'partially_completed'].includes(normalizedRunStatus)) {
|
||||
reparsePendingReviewPolls.value += 1;
|
||||
} else {
|
||||
reparsePendingReviewPolls.value = 0;
|
||||
}
|
||||
|
||||
if (['queued', 'layout_parsing', 'waiting_layout'].includes(normalizedRunStatus)
|
||||
|| ['queued', 'layout_parsing', 'waiting_layout'].includes(runStage)) {
|
||||
reparseLastStableStage.value = 'layout_parsing';
|
||||
} else if (['routing', 'matching_profile'].includes(normalizedRunStatus)
|
||||
|| ['routing', 'matching_profile'].includes(runStage)) {
|
||||
reparseLastStableStage.value = 'routing';
|
||||
} else if (['extracting', 'merging_supplement'].includes(normalizedRunStatus)
|
||||
|| ['extracting', 'merging_supplement'].includes(runStage)) {
|
||||
reparseLastStableStage.value = 'extracting';
|
||||
} else if (['review_required', 'partially_completed'].includes(normalizedRunStatus)) {
|
||||
reparseLastStableStage.value = 'draft_ready';
|
||||
} else if (['candidate_ready'].includes(normalizedRunStatus) || runStage === 'candidate_ready') {
|
||||
reparseLastStableStage.value = 'validating';
|
||||
} else if (['confirming', 'auto_confirming'].includes(normalizedRunStatus)
|
||||
|| ['confirming', 'auto_confirming'].includes(runStage)) {
|
||||
reparseLastStableStage.value = 'auto_confirming';
|
||||
} else if (normalizedRunStatus === 'building_order' || runStage === 'building_order') {
|
||||
reparseLastStableStage.value = 'building_order';
|
||||
} else if (normalizedRunStatus === 'inventory_matching' || runStage === 'inventory_matching') {
|
||||
reparseLastStableStage.value = 'inventory_matching';
|
||||
} else if (normalizedRunStatus === 'generating_excel' || runStage === 'generating_excel') {
|
||||
reparseLastStableStage.value = 'generating_excel';
|
||||
} else if (['manual_upload_pending', 'upload_rpa_pending', 'upload_rpa_running'].includes(normalizedRunStatus)) {
|
||||
reparseLastStableStage.value = 'awaiting_manual_action';
|
||||
} else if (['completed', 'partially_completed'].includes(normalizedRunStatus)) {
|
||||
reparseLastStableStage.value = 'completed';
|
||||
}
|
||||
reparseProgressStage.value = reparseLastStableStage.value;
|
||||
|
||||
if (['failed', 'cancelled'].includes(normalizedRunStatus) || lifecycle === 'reparse_failed') {
|
||||
reparseProgressStage.value = 'failed';
|
||||
stopReparseProgressPolling();
|
||||
reparseProgressActive.value = false;
|
||||
refreshStatusMessage();
|
||||
return;
|
||||
}
|
||||
|
||||
if (REPARSE_REVIEW_READY_STATUSES.has(normalizedRunStatus)) {
|
||||
let currentCaseNo = '';
|
||||
try {
|
||||
const reviewRunDetail = await getWorkspaceShippingOrderReviewRun(targetRunNo);
|
||||
currentCaseNo = String(
|
||||
reviewRunDetail.items.find((item) => String(item.case_no || '').trim())?.case_no
|
||||
|| reviewRunDetail.items[0]?.case_no
|
||||
|| '',
|
||||
).trim();
|
||||
} catch {
|
||||
/* Review Run ?????????? */
|
||||
}
|
||||
if (currentCaseNo) {
|
||||
reparseProgressStage.value = 'draft_ready';
|
||||
stopReparseProgressPolling();
|
||||
await load(targetRunNo, currentCaseNo, {
|
||||
if (['review_required', 'partially_completed', 'completed'].includes(normalizedStatus)) {
|
||||
const target = await resolveCurrentStreamTarget(targetDocumentId, targetRunNo);
|
||||
if (target) {
|
||||
window.clearInterval(reparseCaseRefreshTimer!);
|
||||
reparseCaseRefreshTimer = null;
|
||||
await load(target.runNo, target.caseNo, {
|
||||
conversationId: contextConversationId,
|
||||
itemNo: contextItemNo || undefined,
|
||||
restoreProgress: false,
|
||||
});
|
||||
reparseProgressActive.value = false;
|
||||
refreshStatusMessage();
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (['manual_upload_pending', 'upload_rpa_pending', 'upload_rpa_running', 'closed', 'cancelled'].includes(lifecycle)) {
|
||||
stopReparseProgressPolling();
|
||||
return;
|
||||
}
|
||||
|
||||
reparseStalePolls.value = reparseStalePolls.value + 1;
|
||||
if (reparseStalePolls.value >= 24) {
|
||||
reparseProgressRefreshFailed.value = true;
|
||||
}
|
||||
} catch {
|
||||
reparseProgressRefreshFailed.value = true;
|
||||
reparseStalePolls.value = reparseStalePolls.value + 1;
|
||||
if (reparseStalePolls.value >= 8) {
|
||||
if (['failed', 'cancelled'].includes(normalizedStatus)) {
|
||||
window.clearInterval(reparseCaseRefreshTimer!);
|
||||
reparseCaseRefreshTimer = null;
|
||||
refreshStatusMessage();
|
||||
}
|
||||
} catch {
|
||||
// 轮询只承担恢复导航;临时网络失败由后续 tick 重试,禁止伪造业务进度。
|
||||
}
|
||||
};
|
||||
reparsePollTick = tick;
|
||||
void reparsePollTick();
|
||||
reparsePollTimer = window.setInterval(() => { void tick(); }, PROGRESS_POLL_MS);
|
||||
void tick();
|
||||
reparseCaseRefreshTimer = window.setInterval(() => { void tick(); }, PROGRESS_POLL_MS);
|
||||
};
|
||||
|
||||
/** ???????????????????????? tick ??? */
|
||||
const refreshReparseProgress = async () => {
|
||||
if (!reparsePollTick) return;
|
||||
await reparsePollTick();
|
||||
const stopReparseCaseRefreshPolling = () => {
|
||||
if (reparseCaseRefreshTimer != null) {
|
||||
window.clearInterval(reparseCaseRefreshTimer);
|
||||
reparseCaseRefreshTimer = null;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -612,7 +481,8 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
|
||||
if (!authoritativeOrderTaskNo.value && !targetRunNo) return;
|
||||
showWorkflowProgress.value = true;
|
||||
workflowProgressPolling.value = true;
|
||||
const UNIFIED_TERMINAL = new Set(['completed', 'failed', 'cancelled', 'retryable', 'needs_review', 'waiting_human']);
|
||||
// RPA 超时、可重试失败和人工复核都可能被后续回调推进,页面留存期间持续读取 Projection。
|
||||
const UNIFIED_TERMINAL = new Set(['completed', 'cancelled']);
|
||||
let lastUnifiedStatus = '';
|
||||
const RUN_TERMINAL = new Set(['completed', 'partially_completed', 'failed', 'cancelled']);
|
||||
const tick = async () => {
|
||||
@@ -628,7 +498,7 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
|
||||
lastUnifiedStatus = unifiedStatus;
|
||||
options.onWorkflowRefresh?.();
|
||||
}
|
||||
if (UNIFIED_TERMINAL.has(unifiedStatus) || unifiedStatus === 'waiting_review') {
|
||||
if (UNIFIED_TERMINAL.has(unifiedStatus)) {
|
||||
stopWorkflowProgressPolling();
|
||||
}
|
||||
return;
|
||||
@@ -660,7 +530,7 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
|
||||
if (getCurrentInstance()) {
|
||||
onBeforeUnmount(() => {
|
||||
stopWorkflowProgressPolling();
|
||||
stopReparseProgressPolling();
|
||||
stopReparseCaseRefreshPolling();
|
||||
stopShippingProcessing();
|
||||
clearPreview();
|
||||
});
|
||||
@@ -677,10 +547,7 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
|
||||
const isWorkItemClosed = computed(() => isReviewWorkItemClosed(reviewProgressContext.value));
|
||||
|
||||
/** ??/????????????????????????? */
|
||||
const isReadOnly = computed(() => (
|
||||
reparseProgressActive.value
|
||||
|| isReviewReadOnly(activeCase.value, reviewProgressContext.value)
|
||||
));
|
||||
const isReadOnly = computed(() => isReviewReadOnly(activeCase.value, reviewProgressContext.value));
|
||||
|
||||
/**
|
||||
* Draft ?????edit_draft ???????
|
||||
@@ -732,10 +599,6 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
|
||||
statusMessage.value = 'reparse_in_progress';
|
||||
return;
|
||||
}
|
||||
if (reparseProgressActive.value) {
|
||||
statusMessage.value = 'reparse_in_progress';
|
||||
return;
|
||||
}
|
||||
if (isViewingHistoricalVersion.value || activeCase.value?.status === 'superseded') {
|
||||
statusMessage.value = 'superseded';
|
||||
return;
|
||||
@@ -766,11 +629,6 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
|
||||
&& !isBuildConfirmBlocked(buildEligibility.value)
|
||||
));
|
||||
|
||||
/** ????????????????? */
|
||||
const manualInventoryLines = computed(() =>
|
||||
(buildEligibility.value?.line_projections || []).filter(lineNeedsManualInventorySelection),
|
||||
);
|
||||
|
||||
/** ??????????????????????????? */
|
||||
const routingRecoveryLines = computed(() =>
|
||||
(buildEligibility.value?.line_projections || []).filter(lineNeedsInventoryRoutingRecovery),
|
||||
@@ -816,14 +674,53 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
|
||||
}
|
||||
};
|
||||
|
||||
/** 当前工作台所对应的物理 PDF;版本切换必须固定此 ID,不能由 Run 中的首个 Case 推断。 */
|
||||
const currentStreamDocumentId = (): number | null => {
|
||||
const activeDocumentId = Number(activeCase.value?.document?.id || 0);
|
||||
if (activeDocumentId > 0) return activeDocumentId;
|
||||
const activeCaseNo = String(activeCase.value?.case_no || '').trim();
|
||||
const summary = reviewRun.value?.items.find((item) => item.case_no === activeCaseNo);
|
||||
const summaryDocumentId = Number(summary?.document_id || 0);
|
||||
return summaryDocumentId > 0 ? summaryDocumentId : null;
|
||||
};
|
||||
|
||||
/**
|
||||
* 从会话级 Review Stream 队列解析当前 PDF 的权威版本。
|
||||
*
|
||||
* Queue 是跨 Run 的文件主线读模型;仅接受同 document_id 且有 source_run_no 的记录,
|
||||
* 避免多 PDF 会话把另一个文件的首个 Case 当作当前版本。
|
||||
*/
|
||||
const resolveCurrentStreamTarget = async (
|
||||
documentId: number | null,
|
||||
anchorRunNo?: string | null,
|
||||
): Promise<{ runNo: string; caseNo: string } | null> => {
|
||||
const anchor = String(anchorRunNo || reviewRun.value?.run_no || activeCase.value?.run_no || '').trim();
|
||||
if (!documentId || !anchor) return null;
|
||||
const queue = await getWorkspaceShippingOrderReviewQueue(anchor);
|
||||
reviewQueue.value = queue;
|
||||
const item = queue.items.find((candidate) => (
|
||||
Number(candidate.document_id || 0) === documentId
|
||||
&& String(candidate.case_no || '').trim()
|
||||
&& String(candidate.source_run_no || '').trim()
|
||||
));
|
||||
if (!item) return null;
|
||||
return {
|
||||
runNo: String(item.source_run_no).trim(),
|
||||
caseNo: String(item.case_no).trim(),
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* ???? PDF ?? URL?????????
|
||||
*/
|
||||
const clearPreview = () => {
|
||||
++previewRequestGeneration;
|
||||
if (previewUrl.value) URL.revokeObjectURL(previewUrl.value);
|
||||
previewUrl.value = '';
|
||||
previewCaseNo.value = null;
|
||||
previewLoading.value = false;
|
||||
previewLoadFailed.value = false;
|
||||
previewInflight = null;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -834,32 +731,115 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
|
||||
*/
|
||||
const ensurePreviewLoaded = async (caseNo?: string | null): Promise<boolean> => {
|
||||
const target = String(caseNo || activeCase.value?.case_no || '').trim();
|
||||
if (!target) return false;
|
||||
if (!target || activeCase.value?.case_no !== target) return false;
|
||||
if (previewCaseNo.value === target && previewUrl.value) return true;
|
||||
if (previewInflight) return previewInflight;
|
||||
if (previewInflight?.caseNo === target) return previewInflight.promise;
|
||||
|
||||
const generation = caseLoadGeneration;
|
||||
const requestGeneration = ++previewRequestGeneration;
|
||||
previewLoading.value = true;
|
||||
previewLoadFailed.value = false;
|
||||
previewInflight = (async () => {
|
||||
const promise = (async () => {
|
||||
try {
|
||||
if (previewUrl.value) URL.revokeObjectURL(previewUrl.value);
|
||||
previewUrl.value = '';
|
||||
const blob = await getWorkspaceShippingOrderReviewPreview(target);
|
||||
previewUrl.value = URL.createObjectURL(blob);
|
||||
const url = URL.createObjectURL(blob);
|
||||
if (
|
||||
requestGeneration !== previewRequestGeneration
|
||||
|| generation !== caseLoadGeneration
|
||||
|| activeCase.value?.case_no !== target
|
||||
) {
|
||||
URL.revokeObjectURL(url);
|
||||
return false;
|
||||
}
|
||||
if (previewUrl.value) URL.revokeObjectURL(previewUrl.value);
|
||||
previewUrl.value = url;
|
||||
previewCaseNo.value = target;
|
||||
previewLoadFailed.value = false;
|
||||
return true;
|
||||
} catch {
|
||||
previewLoadFailed.value = true;
|
||||
previewUrl.value = '';
|
||||
previewCaseNo.value = null;
|
||||
if (
|
||||
requestGeneration === previewRequestGeneration
|
||||
&& generation === caseLoadGeneration
|
||||
&& activeCase.value?.case_no === target
|
||||
) {
|
||||
previewLoadFailed.value = true;
|
||||
previewUrl.value = '';
|
||||
previewCaseNo.value = null;
|
||||
}
|
||||
return false;
|
||||
} finally {
|
||||
previewLoading.value = false;
|
||||
previewInflight = null;
|
||||
if (
|
||||
requestGeneration === previewRequestGeneration
|
||||
&& generation === caseLoadGeneration
|
||||
&& activeCase.value?.case_no === target
|
||||
) {
|
||||
previewLoading.value = false;
|
||||
previewInflight = null;
|
||||
}
|
||||
}
|
||||
})();
|
||||
return previewInflight;
|
||||
previewInflight = { caseNo: target, promise };
|
||||
return promise;
|
||||
};
|
||||
|
||||
/** 按当前证据 Document 读取邮件正文;PDF 证据仍使用受控 PDF Blob。 */
|
||||
const ensureEmailEvidenceLoaded = async (caseNo: string, documentId: number, evidenceId?: string): Promise<boolean> => {
|
||||
try {
|
||||
emailPreview.value = await getWorkspaceShippingOrderReviewEmailEvidencePreview(caseNo, documentId, evidenceId);
|
||||
return true;
|
||||
} catch {
|
||||
emailPreview.value = null;
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 仅在用户打开接收解析工作面时按需读取当前 Case 的附件与邮件正文。
|
||||
* Case/代次双校验避免迟到响应把旧附件或 EML 写回当前工作面;失败保持空上下文。
|
||||
*/
|
||||
const ensureIntakeParseContextLoaded = async (caseNo: string): Promise<boolean> => {
|
||||
const target = String(caseNo || '').trim();
|
||||
if (!target || activeCase.value?.case_no !== target) {
|
||||
++intakeParseRequestGeneration;
|
||||
intakeParseContext.value = null;
|
||||
intakeParseLoading.value = false;
|
||||
intakeParseLoadFailed.value = false;
|
||||
return false;
|
||||
}
|
||||
|
||||
const generation = caseLoadGeneration;
|
||||
const requestGeneration = ++intakeParseRequestGeneration;
|
||||
intakeParseContext.value = null;
|
||||
intakeParseLoading.value = true;
|
||||
intakeParseLoadFailed.value = false;
|
||||
try {
|
||||
const context = await getWorkspaceShippingOrderReviewIntakeParseContext(target);
|
||||
if (
|
||||
requestGeneration !== intakeParseRequestGeneration
|
||||
|| generation !== caseLoadGeneration
|
||||
|| activeCase.value?.case_no !== target
|
||||
) return false;
|
||||
intakeParseContext.value = context;
|
||||
return true;
|
||||
} catch {
|
||||
if (
|
||||
requestGeneration === intakeParseRequestGeneration
|
||||
&& generation === caseLoadGeneration
|
||||
&& activeCase.value?.case_no === target
|
||||
) {
|
||||
intakeParseContext.value = null;
|
||||
intakeParseLoadFailed.value = true;
|
||||
}
|
||||
return false;
|
||||
} finally {
|
||||
if (
|
||||
requestGeneration === intakeParseRequestGeneration
|
||||
&& generation === caseLoadGeneration
|
||||
&& activeCase.value?.case_no === target
|
||||
) {
|
||||
intakeParseLoading.value = false;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/** ?? Run ??????? URL ?? Case??????? PDF? */
|
||||
@@ -868,6 +848,8 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
|
||||
preferredCaseNo?: string,
|
||||
options?: { conversationId?: string; itemNo?: string; restoreProgress?: boolean },
|
||||
) => {
|
||||
++caseLoadGeneration;
|
||||
++intakeParseRequestGeneration;
|
||||
loading.value = true;
|
||||
loadFailed.value = false;
|
||||
draftConflict.value = null;
|
||||
@@ -883,16 +865,19 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
|
||||
versions.value = [];
|
||||
evidence.value = [];
|
||||
llmSuggestions.value = [];
|
||||
intakeParseContext.value = null;
|
||||
intakeParseLoading.value = false;
|
||||
intakeParseLoadFailed.value = false;
|
||||
clearPreview();
|
||||
try {
|
||||
const run = await getWorkspaceShippingOrderReviewRun(runNo);
|
||||
const [run, queue] = await Promise.all([
|
||||
getWorkspaceShippingOrderReviewRun(runNo),
|
||||
getWorkspaceShippingOrderReviewQueue(runNo),
|
||||
]);
|
||||
reviewRun.value = run;
|
||||
// ? Run ???????????????? Case??????????????
|
||||
if (run.superseded_by_run_no) {
|
||||
await load(run.superseded_by_run_no, preferredCaseNo, options);
|
||||
return;
|
||||
}
|
||||
const caseNo = preferredCaseNo || run.items[0]?.case_no;
|
||||
reviewQueue.value = queue;
|
||||
// [STREAM] Run 替代不等于其内全部 PDF 替代;当前文件只由队列 Stream 裁决。
|
||||
const caseNo = preferredCaseNo || queue.items[0]?.case_no || run.items[0]?.case_no;
|
||||
const caseSnapshot = caseNo ? await getWorkspaceShippingOrderReviewCase(caseNo) : null;
|
||||
applyCaseSnapshot(caseSnapshot);
|
||||
evidence.value = caseNo ? (await getWorkspaceShippingOrderReviewEvidence(caseNo)).items : [];
|
||||
@@ -900,21 +885,12 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
|
||||
clearPreview();
|
||||
await refreshWorkItemContext(contextConversationId, contextItemNo);
|
||||
// refreshWorkItemContext ????? ref???????? ref????? load ???????????
|
||||
const restoredItem = (reviewProgressContext as { readonly value: ShippingReviewProgressContext | null }).value;
|
||||
const restoredRunNo = String(restoredItem?.current_run_no || '').trim();
|
||||
const restoredLifecycle = String(restoredItem?.lifecycle_status || '').trim();
|
||||
const activeCaseStatus = String(caseSnapshot?.case?.status || '').trim();
|
||||
const isReparseRunning = REPARSE_RUNNING_LIFECYCLES.has(restoredLifecycle)
|
||||
|| activeCaseStatus === 'reparse_pending';
|
||||
const isReparseFailed = ['reparse_failed', 'failed'].includes(restoredLifecycle);
|
||||
if (options?.restoreProgress !== false && restoredRunNo && (isReparseRunning || isReparseFailed)) {
|
||||
startReparseProgressPolling(restoredRunNo, true);
|
||||
}
|
||||
} catch {
|
||||
loadFailed.value = true;
|
||||
reviewRun.value = null;
|
||||
activeCase.value = null;
|
||||
reviewProgressContext.value = null;
|
||||
reviewQueue.value = null;
|
||||
versions.value = [];
|
||||
statusMessage.value = null;
|
||||
} finally {
|
||||
@@ -928,6 +904,7 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
|
||||
* 保留 reviewProgressContext(Run 级进度条按契约绑定整 Run,不随 PDF 跳变)。
|
||||
*/
|
||||
const resetCaseTransientState = () => {
|
||||
++intakeParseRequestGeneration;
|
||||
activeCase.value = null;
|
||||
caseProjectionVersion.value = null;
|
||||
caseLoadingContext.value = null;
|
||||
@@ -940,6 +917,9 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
|
||||
saveFailed.value = false;
|
||||
loadFailed.value = false;
|
||||
statusMessage.value = null;
|
||||
intakeParseContext.value = null;
|
||||
intakeParseLoading.value = false;
|
||||
intakeParseLoadFailed.value = false;
|
||||
clearPreview();
|
||||
};
|
||||
|
||||
@@ -953,9 +933,15 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
|
||||
const target = String(caseNo || '').trim();
|
||||
if (!target) return;
|
||||
const generation = ++caseLoadGeneration;
|
||||
++intakeParseRequestGeneration;
|
||||
requestedCaseNo.value = target;
|
||||
caseSwitchLoading.value = true;
|
||||
caseSwitchFailed.value = false;
|
||||
// 切换请求一开始即撤销旧 Blob 并作废旧预览响应,禁止 A 的 PDF 留在 B 的工作面。
|
||||
clearPreview();
|
||||
intakeParseContext.value = null;
|
||||
intakeParseLoading.value = false;
|
||||
intakeParseLoadFailed.value = false;
|
||||
try {
|
||||
const [detail, result] = await Promise.all([
|
||||
getWorkspaceShippingOrderReviewCase(target),
|
||||
@@ -1108,21 +1094,21 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
|
||||
};
|
||||
|
||||
/**
|
||||
* ?????? Case ?????????????????????
|
||||
* 门禁动作完成后静默同步当前 Case。
|
||||
* 核心逻辑:这不是用户切换 PDF,故不能复用 selectCase;保留已加载预览、字段/证据焦点与 intake
|
||||
* 上下文,仅在当前 Case 的快照和证据都返回后替换数据,再同步 Run 与 WorkflowItem 状态。
|
||||
*/
|
||||
const reloadLatestDraft = async () => {
|
||||
if (!activeCase.value) return;
|
||||
const caseNo = activeCase.value.case_no;
|
||||
saving.value = true;
|
||||
try {
|
||||
if (draftConflict.value?.serverCase) {
|
||||
activeCase.value = draftConflict.value.serverCase;
|
||||
caseProjectionVersion.value = Date.now();
|
||||
caseLoadingContext.value = null;
|
||||
evidence.value = (await getWorkspaceShippingOrderReviewEvidence(caseNo)).items;
|
||||
} else {
|
||||
await selectCase(caseNo);
|
||||
}
|
||||
const [detail, result] = await Promise.all([
|
||||
getWorkspaceShippingOrderReviewCase(caseNo),
|
||||
getWorkspaceShippingOrderReviewEvidence(caseNo),
|
||||
]);
|
||||
applyCaseSnapshot(detail);
|
||||
evidence.value = result.items;
|
||||
if (reviewRun.value && activeCase.value) {
|
||||
const item = reviewRun.value.items.find((row) => row.case_no === caseNo);
|
||||
if (item) {
|
||||
@@ -1209,27 +1195,14 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
|
||||
if (!activeCase.value) return;
|
||||
validationInProgress.value = true;
|
||||
try {
|
||||
await save(() => validateWorkspaceShippingOrderReviewDraft(activeCase.value!.case_no, version()));
|
||||
await save(async () => (
|
||||
await validateWorkspaceShippingOrderReviewDraft(activeCase.value!.case_no, version())
|
||||
).case);
|
||||
} finally {
|
||||
validationInProgress.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* ????????????????? Case?
|
||||
* @param lineKey - Draft ? line_key
|
||||
* @param sourceCodes - ?????????????
|
||||
* @param reason - ??????
|
||||
*/
|
||||
const setLineInventoryCandidates = (lineKey: string, sourceCodes: string[], reason: string) => {
|
||||
if (!activeCase.value) return Promise.resolve();
|
||||
return save(() => putWorkspaceShippingOrderReviewInventoryCandidates(activeCase.value!.case_no, lineKey, {
|
||||
expected_draft_version: version(),
|
||||
source_codes: sourceCodes,
|
||||
reason,
|
||||
}));
|
||||
};
|
||||
|
||||
/**
|
||||
* ?????????????????409 ????? markWriteFailure?
|
||||
* @param lineKey - ???????? reroute
|
||||
@@ -1244,44 +1217,6 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
|
||||
}));
|
||||
};
|
||||
|
||||
/**
|
||||
* ???????????????
|
||||
* @param lineKey - Draft ? line_key
|
||||
* @param reason - ????
|
||||
*/
|
||||
const adoptInventoryRoutingSuggestion = (lineKey: string, reason?: string) => {
|
||||
if (!activeCase.value) return Promise.resolve();
|
||||
const trimmedReason = String(reason || '').trim();
|
||||
return save(() => postWorkspaceShippingOrderReviewInventoryRoutingAdoptSuggestion(
|
||||
activeCase.value!.case_no,
|
||||
lineKey,
|
||||
{
|
||||
expected_draft_version: version(),
|
||||
idempotency_key: crypto.randomUUID(),
|
||||
...(trimmedReason ? { reason: trimmedReason } : {}),
|
||||
},
|
||||
));
|
||||
};
|
||||
|
||||
/**
|
||||
* ????????????????????
|
||||
* @param lineKey - Draft ? line_key
|
||||
* @param reason - ????
|
||||
*/
|
||||
const keepManualInventoryRouting = (lineKey: string, reason?: string) => {
|
||||
if (!activeCase.value) return Promise.resolve();
|
||||
const trimmedReason = String(reason || '').trim();
|
||||
return save(() => postWorkspaceShippingOrderReviewInventoryRoutingKeepManual(
|
||||
activeCase.value!.case_no,
|
||||
lineKey,
|
||||
{
|
||||
expected_draft_version: version(),
|
||||
idempotency_key: crypto.randomUUID(),
|
||||
...(trimmedReason ? { reason: trimmedReason } : {}),
|
||||
},
|
||||
));
|
||||
};
|
||||
|
||||
/** ????????????????? Task ??? Case??????? DTO? */
|
||||
const confirm = async () => {
|
||||
if (!activeCase.value) return null;
|
||||
@@ -1367,7 +1302,7 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
|
||||
applyCaseSnapshot(await getWorkspaceShippingOrderReviewCase(activeCase.value.case_no));
|
||||
if (reviewRun.value) reviewRun.value = await getWorkspaceShippingOrderReviewRun(reviewRun.value.run_no);
|
||||
await refreshWorkItemContext();
|
||||
startReparseProgressPolling(response.run.run_no);
|
||||
startReparseCaseRefreshPolling(response.run.run_no);
|
||||
return response;
|
||||
} catch (error) {
|
||||
saveFailed.value = true;
|
||||
@@ -1376,30 +1311,6 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
|
||||
saving.value = false;
|
||||
}
|
||||
};
|
||||
/** ???? PDF ????? Intake ?????????? Document ????? Run? */
|
||||
const uploadReplacement = async (file: File) => {
|
||||
if (!activeCase.value) return null;
|
||||
const asset = await uploadFileAsset(file);
|
||||
const intake = await createWorkspaceShippingOrderReviewReplacementIntake(activeCase.value.case_no, asset.asset_no);
|
||||
for (let attempt = 0; attempt < 60; attempt += 1) {
|
||||
const current = await getShippingNoticeIntake(intake.intake_no);
|
||||
if (current.parse_status === 'parsed') return startReplacementRun(current.intake_no);
|
||||
if (['parse_failed', 'cancelled', 'expired'].includes(current.parse_status)) {
|
||||
throw new Error('Replacement PDF parsing failed');
|
||||
}
|
||||
await new Promise<void>((resolve) => window.setTimeout(resolve, 1000));
|
||||
}
|
||||
throw new Error('Replacement PDF parsing is still pending');
|
||||
};
|
||||
const startReplacementRun = async (intakeNo: string) => {
|
||||
if (!activeCase.value) return null;
|
||||
const response = await createWorkspaceShippingOrderReviewReplacementRun(activeCase.value.case_no, intakeNo);
|
||||
applyCaseSnapshot(await getWorkspaceShippingOrderReviewCase(activeCase.value.case_no));
|
||||
if (reviewRun.value) reviewRun.value = await getWorkspaceShippingOrderReviewRun(reviewRun.value.run_no);
|
||||
await refreshWorkItemContext();
|
||||
return response;
|
||||
};
|
||||
|
||||
/**
|
||||
* ?????????? LLM ?????????
|
||||
*/
|
||||
@@ -1495,47 +1406,12 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
|
||||
return { runNo, caseNo };
|
||||
};
|
||||
|
||||
/**
|
||||
* ????????????????? Run ? Case?
|
||||
* ??????? reviewRun.superseded_by_run_no ??? WorkItem ??????? Workflow API?
|
||||
*/
|
||||
/** 由 Workflow 当前 Case 打开文件级 Stream 当前版本;不再以批次 Run 后继关系跳转。 */
|
||||
const openCurrentVersion = async (): Promise<{ runNo: string; caseNo: string } | null> => {
|
||||
reviewProgressContext.value = synthesizeWorkItemFromReviewContext({
|
||||
reviewRun: reviewRun.value,
|
||||
activeCase: activeCase.value,
|
||||
conversationId: contextConversationId,
|
||||
itemNo: contextItemNo,
|
||||
});
|
||||
versions.value = [];
|
||||
refreshStatusMessage();
|
||||
|
||||
const target = currentVersionTarget();
|
||||
const activeRunNo = String(reviewRun.value?.run_no || '').trim();
|
||||
const activeCaseNo = String(activeCase.value?.case_no || '').trim();
|
||||
const targetIsCurrentView = Boolean(
|
||||
target
|
||||
&& target.runNo === activeRunNo
|
||||
&& target.caseNo === activeCaseNo,
|
||||
);
|
||||
if (reviewRun.value?.superseded_by_run_no && (!target || targetIsCurrentView || activeCase.value?.status === 'superseded')) {
|
||||
try {
|
||||
const replacement = await getWorkspaceShippingOrderReviewRun(reviewRun.value.superseded_by_run_no);
|
||||
const preferredCaseNo = String(reviewProgressContext.value?.current_case_no || '').trim();
|
||||
const replacementCase = replacement.items.find((item) => String(item.case_no || '').trim() === preferredCaseNo)
|
||||
|| replacement.items.find((item) => String(item.case_no || '').trim());
|
||||
const replacementRunNo = String(replacement.run_no || '').trim();
|
||||
const replacementCaseNo = String(replacementCase?.case_no || '').trim();
|
||||
if (replacementRunNo && replacementCaseNo) {
|
||||
await load(replacementRunNo, replacementCaseNo, {
|
||||
conversationId: contextConversationId,
|
||||
itemNo: contextItemNo || undefined,
|
||||
});
|
||||
return { runNo: replacementRunNo, caseNo: replacementCaseNo };
|
||||
}
|
||||
} catch {
|
||||
/* ???????????????????????? */
|
||||
}
|
||||
}
|
||||
const target = await resolveCurrentStreamTarget(currentStreamDocumentId());
|
||||
if (!target) return null;
|
||||
await load(target.runNo, target.caseNo, {
|
||||
conversationId: contextConversationId,
|
||||
@@ -1546,6 +1422,7 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
|
||||
|
||||
return {
|
||||
reviewRun,
|
||||
reviewQueue,
|
||||
activeCase,
|
||||
caseProjectionVersion,
|
||||
caseLoadingContext,
|
||||
@@ -1561,7 +1438,6 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
|
||||
draftConflictDiffLines,
|
||||
buildEligibility,
|
||||
canConfirmBuild,
|
||||
manualInventoryLines,
|
||||
routingRecoveryLines,
|
||||
isViewingHistoricalVersion,
|
||||
isWorkItemClosed,
|
||||
@@ -1577,22 +1453,19 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
|
||||
focusedLineKey,
|
||||
evidenceDrawerFocus,
|
||||
previewUrl,
|
||||
previewCaseNo,
|
||||
previewLoading,
|
||||
previewLoadFailed,
|
||||
ensurePreviewLoaded,
|
||||
ensureEmailEvidenceLoaded,
|
||||
emailPreview,
|
||||
intakeParseContext,
|
||||
intakeParseLoading,
|
||||
intakeParseLoadFailed,
|
||||
ensureIntakeParseContextLoaded,
|
||||
clearPreview,
|
||||
showWorkflowProgress,
|
||||
workflowProgressPolling,
|
||||
reparseProgressActive,
|
||||
reparseProgressPolling,
|
||||
reparseProgressRefreshFailed,
|
||||
reparseProgressStage,
|
||||
reparseLastStableStage,
|
||||
reparseRunStatus,
|
||||
reparseLastActivityAt,
|
||||
reparseLastRefreshedAt,
|
||||
reparseStalePolls,
|
||||
refreshReparseProgress,
|
||||
loading,
|
||||
loadFailed,
|
||||
caseSwitchLoading,
|
||||
@@ -1616,21 +1489,16 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
|
||||
copyLine,
|
||||
deleteLine,
|
||||
validate,
|
||||
setLineInventoryCandidates,
|
||||
rerouteInventoryRouting,
|
||||
adoptInventoryRoutingSuggestion,
|
||||
keepManualInventoryRouting,
|
||||
confirm,
|
||||
startWorkflowProgressPolling,
|
||||
stopWorkflowProgressPolling,
|
||||
startReparseProgressPolling,
|
||||
stopReparseProgressPolling,
|
||||
startReparseCaseRefreshPolling,
|
||||
stopReparseCaseRefreshPolling,
|
||||
createManualDraft,
|
||||
markNonOrder,
|
||||
markQualityIssue,
|
||||
reparseDocument,
|
||||
uploadReplacement,
|
||||
startReplacementRun,
|
||||
focusSuggestionField,
|
||||
setEvidenceDrawerFocus,
|
||||
clearEvidenceDrawerFocus,
|
||||
|
||||
@@ -22,13 +22,38 @@ import {
|
||||
buildTaskSemanticKey,
|
||||
buildProcessingSemanticKey,
|
||||
stabilizeTaskObjects,
|
||||
flattenBusinessFileProjections,
|
||||
businessFileKeys,
|
||||
} from './conversationProcessingProjection';
|
||||
import { normalizeShippingProcessingProjection } from './normalizeShippingProcessing';
|
||||
import type {
|
||||
ConversationProcessingProjection,
|
||||
ShippingProcessingProjection,
|
||||
ShippingWorkflowItem,
|
||||
} from '@/features/chat/types/shipping.api.types';
|
||||
|
||||
describe('EML business-file projection', () => {
|
||||
it('excludes the EML container and keeps its PDF/XLSX leaf attachments', () => {
|
||||
const eml = {
|
||||
workItemType: 'order_task', workItemNo: 'INTAKE:SNI-1', sourceType: 'eml',
|
||||
sourceSummary: { filename: 'mail.eml', documentCount: 2 },
|
||||
aggregateChildren: [
|
||||
{ workItemType: 'order_task', workItemNo: 'OT-1', sourceType: 'eml', sourceSummary: { filename: 'notice-a.pdf', documentId: 101, documentCount: 1 } },
|
||||
{ workItemType: 'order_task', workItemNo: 'OT-2', sourceType: 'eml', sourceSummary: { filename: 'items.xlsx', documentId: 102, documentCount: 1 } },
|
||||
],
|
||||
} as ShippingProcessingProjection;
|
||||
const directPdf = {
|
||||
workItemType: 'order_task', workItemNo: 'OT-3', sourceType: 'direct_pdf',
|
||||
sourceSummary: { filename: 'direct.pdf', documentId: 103, documentCount: 1 },
|
||||
} as ShippingProcessingProjection;
|
||||
|
||||
// EML 仅为来源分组,3 个业务附件才是唯一文件集合。
|
||||
expect(flattenBusinessFileProjections([eml, directPdf]).map((row) => row.sourceSummary.filename))
|
||||
.toEqual(['notice-a.pdf', 'items.xlsx', 'direct.pdf']);
|
||||
expect(businessFileKeys([eml, directPdf])).toEqual(['document:101', 'document:102', 'document:103']);
|
||||
});
|
||||
});
|
||||
|
||||
function item(partial: Partial<ShippingWorkflowItem>): ShippingWorkflowItem {
|
||||
return {
|
||||
item_no: 'WI-1',
|
||||
@@ -613,6 +638,94 @@ describe('conversationProcessingProjection', () => {
|
||||
expect(projection?.summary.total_files).toBe(1);
|
||||
});
|
||||
|
||||
it('aggregates mixed order tasks from one EML intake into one card', () => {
|
||||
const base = {
|
||||
sourceType: 'eml' as const,
|
||||
rootOrderTaskNo: null,
|
||||
shippingNoticeNo: null,
|
||||
conversationId: 'conv-eml',
|
||||
submissionNo: 'SOS-EML',
|
||||
intakeNo: 'INTAKE-EML-1',
|
||||
progressVersion: 1,
|
||||
currentGate: null,
|
||||
childOrderTasks: [],
|
||||
};
|
||||
const items: ShippingProcessingProjection[] = [
|
||||
{
|
||||
...base, workItemType: 'order_task', workItemNo: 'OT-DONE', status: 'completed', stage: 'completed',
|
||||
userStatus: 'completed', userStage: 'completed', lastActivityAt: '2026-08-06T00:00:00Z', availableActions: [],
|
||||
sourceSummary: { emailSubject: 'Shipment', filename: 'a.pdf', documentCount: 1, parsedDocumentCount: 1, candidateCount: 1, customerName: null, poNumber: null },
|
||||
},
|
||||
{
|
||||
...base, workItemType: 'order_task', workItemNo: 'OT-RUN', status: 'processing', stage: 'inventory_matching',
|
||||
userStatus: 'running', userStage: 'inventory_match', lastActivityAt: '2026-08-06T00:00:01Z', availableActions: [],
|
||||
sourceSummary: { emailSubject: 'Shipment', filename: 'b.pdf', documentCount: 1, parsedDocumentCount: 1, candidateCount: 1, customerName: null, poNumber: null },
|
||||
},
|
||||
{
|
||||
...base, workItemType: 'order_task', workItemNo: 'OT-FAIL', status: 'failed', stage: 'freight_uploading',
|
||||
userStatus: 'failed', userStage: 'freight_upload', lastActivityAt: '2026-08-06T00:00:02Z', availableActions: [],
|
||||
blockingReason: { code: 'upload_rpa_failed' },
|
||||
sourceSummary: { emailSubject: 'Shipment', filename: 'c.pdf', documentCount: 1, parsedDocumentCount: 1, candidateCount: 1, customerName: null, poNumber: null },
|
||||
},
|
||||
];
|
||||
const projection = projectConversationProcessingFromWorkItems(items);
|
||||
expect(projection?.needs_action).toHaveLength(1);
|
||||
expect(projection?.processing).toHaveLength(0);
|
||||
expect(projection?.completed).toHaveLength(0);
|
||||
expect(projection?.needs_action[0]?.aggregateSummary).toEqual(expect.objectContaining({
|
||||
intakeNo: 'INTAKE-EML-1', total: 3, completed: 1, processing: 1, needsAction: 1, failed: 1,
|
||||
}));
|
||||
expect(projection?.needs_action[0]?.file_count).toBe(3);
|
||||
expect(projection?.needs_action[0]?.aggregateSummary?.reasonCodes).toContain('upload_rpa_failed');
|
||||
});
|
||||
|
||||
it('does not reuse an empty EML task when a later poll returns aggregate children', () => {
|
||||
const base = {
|
||||
workItemType: 'order_task' as const, sourceType: 'eml' as const, rootOrderTaskNo: 'OT-ROOT',
|
||||
shippingNoticeNo: null, conversationId: 'conv-stable', submissionNo: 'SOS-1', intakeNo: 'SNI-STABLE',
|
||||
progressVersion: 1, currentGate: null, availableActions: [], status: 'processing' as const,
|
||||
stage: 'document_parsing' as const, userStatus: 'running' as const, userStage: 'document_parsing' as const,
|
||||
lastActivityAt: '2026-08-06T00:00:00Z',
|
||||
sourceSummary: { emailSubject: 'mail', filename: 'stable.eml', documentCount: 1, parsedDocumentCount: 1, candidateCount: 0, customerName: null, poNumber: null },
|
||||
};
|
||||
const first = projectConversationProcessingFromWorkItems([{ ...base, workItemNo: 'INTAKE:SNI-STABLE', aggregateSummary: { intakeNo: 'SNI-STABLE', total: 1, completed: 0, processing: 1, needsAction: 0, failed: 0, stages: [], reasonCodes: [] }, aggregateChildren: [] }]);
|
||||
const child = { ...base, workItemNo: 'OT-CHILD', sourceSummary: { ...base.sourceSummary, filename: 'attachment.pdf' } };
|
||||
const second = projectConversationProcessingFromWorkItems([{ ...base, workItemNo: 'INTAKE:SNI-STABLE', aggregateSummary: { intakeNo: 'SNI-STABLE', total: 1, completed: 0, processing: 1, needsAction: 0, failed: 0, stages: [], reasonCodes: [] }, aggregateChildren: [child] }], first);
|
||||
expect(second?.processing[0]?.aggregateChildren?.map((item) => item.sourceSummary.filename)).toEqual(['attachment.pdf']);
|
||||
expect(second?.processing[0]).not.toBe(first?.processing[0]);
|
||||
});
|
||||
|
||||
it('puts an EML with review-required children into needs_action even when parent says processing', () => {
|
||||
const parent = {
|
||||
workItemType: 'order_task' as const, workItemNo: 'INTAKE:SNI-STATUS', sourceType: 'eml' as const,
|
||||
rootOrderTaskNo: null, shippingNoticeNo: null, conversationId: 'conv-status', submissionNo: 'SOS-1', intakeNo: 'SNI-STATUS',
|
||||
status: 'processing' as const, stage: 'document_parsing' as const, userStatus: 'running' as const, userGroup: 'processing' as const,
|
||||
userStage: 'document_parsing' as const, progressVersion: 1, lastActivityAt: '', currentGate: null, availableActions: [],
|
||||
sourceSummary: { emailSubject: null, filename: 'mail.eml', documentCount: 2, parsedDocumentCount: 2, candidateCount: 0, customerName: null, poNumber: null },
|
||||
aggregateChildren: [
|
||||
{ workItemType: 'order_task', workItemNo: 'OT-1', sourceType: 'eml', rootOrderTaskNo: null, shippingNoticeNo: null, conversationId: 'conv-status', submissionNo: 'SOS-1', intakeNo: 'SNI-STATUS', status: 'review_required', stage: 'review_required', userStatus: 'waiting_human', userStage: 'review_required', progressVersion: 1, lastActivityAt: '', currentGate: null, availableActions: [], sourceSummary: { emailSubject: null, filename: 'a.pdf', documentCount: 1, parsedDocumentCount: 1, candidateCount: 0, customerName: null, poNumber: null }, childOrderTasks: [], facts: { uploadState: 'not_created' } },
|
||||
{ workItemType: 'order_task', workItemNo: 'OT-2', sourceType: 'eml', rootOrderTaskNo: null, shippingNoticeNo: null, conversationId: 'conv-status', submissionNo: 'SOS-1', intakeNo: 'SNI-STATUS', status: 'processing', stage: 'document_parsing', userStatus: 'running', userStage: 'document_parsing', progressVersion: 1, lastActivityAt: '', currentGate: null, availableActions: [], sourceSummary: { emailSubject: null, filename: 'b.pdf', documentCount: 1, parsedDocumentCount: 1, candidateCount: 0, customerName: null, poNumber: null }, childOrderTasks: [], facts: { uploadState: 'not_created' } },
|
||||
],
|
||||
} as any;
|
||||
const projection = projectConversationProcessingFromWorkItems([parent]);
|
||||
expect(projection?.needs_action).toHaveLength(1);
|
||||
expect(projection?.processing).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('does not aggregate direct PDFs with matching intake numbers', () => {
|
||||
const common = {
|
||||
workItemType: 'order_task' as const, rootOrderTaskNo: null, shippingNoticeNo: null,
|
||||
conversationId: 'conv-pdf', submissionNo: 'SOS-PDF', intakeNo: 'INTAKE-SAME', progressVersion: 1,
|
||||
currentGate: null, childOrderTasks: [], status: 'processing' as const, stage: 'document_parsing' as const,
|
||||
userStatus: 'running' as const, userStage: 'document_parsing' as const, lastActivityAt: '2026-08-06T00:00:00Z', availableActions: [],
|
||||
};
|
||||
const projection = projectConversationProcessingFromWorkItems([
|
||||
{ ...common, workItemNo: 'OT-1', sourceType: 'direct_pdf', sourceSummary: { emailSubject: null, filename: 'a.pdf', documentCount: 1, parsedDocumentCount: 0, candidateCount: 0, customerName: null, poNumber: null } },
|
||||
{ ...common, workItemNo: 'OT-2', sourceType: 'direct_pdf', sourceSummary: { emailSubject: null, filename: 'b.pdf', documentCount: 1, parsedDocumentCount: 0, candidateCount: 0, customerName: null, poNumber: null } },
|
||||
]);
|
||||
expect(projection?.processing).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('prefers work_items task lists over embedded conversation_processing when both exist', () => {
|
||||
const workItems: ShippingProcessingProjection[] = [
|
||||
{
|
||||
@@ -693,11 +806,43 @@ describe('conversationProcessingProjection', () => {
|
||||
const projection = resolveConversationProcessingFromUnified(workItems, embedded);
|
||||
// 关键断言:兄弟 OT 仅出现在 work_items;embedded 缺 sibling 时不得覆盖任务列表。
|
||||
expect(projection?.needs_action.map((t) => t.user_task_no)).toEqual(['OT-ROOT']);
|
||||
expect(projection?.processing.map((t) => t.user_task_no)).toEqual(['OT-SIBLING']);
|
||||
expect(projection?.processing).toEqual([]);
|
||||
expect(projection?.needs_action[0]?.aggregateSummary).toEqual(expect.objectContaining({
|
||||
intakeNo: 'SNI-1', total: 2, completed: 0, processing: 1, needsAction: 1,
|
||||
}));
|
||||
expect(projection?.focused_task_no).toBe('OT-ROOT');
|
||||
expect(projection?.recent_task_no).toBe('OT-SIBLING');
|
||||
});
|
||||
|
||||
it('uses backend status_groups instead of rebuilding a file list from work_items', () => {
|
||||
const workItems: ShippingProcessingProjection[] = [{
|
||||
workItemType: 'order_task', workItemNo: 'OT-LIVE', sourceType: 'direct_pdf',
|
||||
rootOrderTaskNo: 'OT-LIVE', shippingNoticeNo: null, conversationId: 'conv-live',
|
||||
submissionNo: 'SOS-LIVE', intakeNo: 'SNI-LIVE', status: 'waiting_review',
|
||||
stage: 'order_review', progressVersion: 9, lastActivityAt: '2026-08-16T00:00:00Z',
|
||||
currentGate: null, availableActions: ['open_order_review'], childOrderTasks: [],
|
||||
sourceSummary: { emailSubject: null, filename: 'live.pdf', documentCount: 1,
|
||||
parsedDocumentCount: 1, candidateCount: 1, customerName: null, poNumber: 'PO-LIVE' },
|
||||
}];
|
||||
const backendProjection = {
|
||||
summary: { total_tasks: 1, total_files: 1, processing: 1, needs_action: 0, completed: 0, history: 0 },
|
||||
status_groups: {
|
||||
failed: [], waiting_human: [{
|
||||
user_task_no: 'OT-LIVE', group: 'needs_action', status_label: 'waiting_human',
|
||||
file_count: 1, can_append: false,
|
||||
}], processing: [], completed: [], cancelled: [], archived: [],
|
||||
},
|
||||
needs_action: [], processing: [{ user_task_no: 'OT-HISTORY', status_label: 'extracting' }],
|
||||
completed: [], history: [], focused_task_no: null, recent_task_no: null,
|
||||
};
|
||||
|
||||
const projection = resolveConversationProcessingFromUnified(workItems, backendProjection);
|
||||
|
||||
// 后端已排除的历史条目不允许被前端 work_items 重建回页面。
|
||||
expect(projection?.needs_action.map((task) => task.user_task_no)).toEqual(['OT-LIVE']);
|
||||
expect(projection?.processing).toEqual([]);
|
||||
});
|
||||
|
||||
it('merges focus metadata from embedded onto work_items-derived projection', () => {
|
||||
const derived = projectConversationProcessingFromWorkItems([{
|
||||
workItemType: 'order_task',
|
||||
@@ -800,6 +945,93 @@ describe('conversationProcessingProjection — normalize & semantic & stabilize'
|
||||
expect(t2.available_actions).toEqual(['open_order_review', 'view_details']);
|
||||
});
|
||||
|
||||
it('buildTaskSemanticKey: ui_state 动作变化必须改变签名', () => {
|
||||
const shared = {
|
||||
user_task_no: 'INTAKE:SNI-UI', group: 'needs_action' as const,
|
||||
status_label: 'waiting_human', file_count: 1, can_append: false,
|
||||
available_actions: ['retry_parse'],
|
||||
};
|
||||
const before = {
|
||||
...shared,
|
||||
uiState: {
|
||||
status: 'waiting_human', stage: 'order_review', blocking_reason: null,
|
||||
primary_action: { code: 'open_order_review', i18nKey: 'action.open_order_review', parameters: {} },
|
||||
secondary_actions: [],
|
||||
},
|
||||
};
|
||||
const after = {
|
||||
...before,
|
||||
uiState: {
|
||||
...before.uiState,
|
||||
primary_action: { code: 'retry_parse', i18nKey: 'action.retry_parse', parameters: {} },
|
||||
},
|
||||
};
|
||||
expect(buildTaskSemanticKey(before)).not.toBe(buildTaskSemanticKey(after));
|
||||
});
|
||||
|
||||
it('buildTaskSemanticKey: 后端撤销生命周期入口时必须改变签名', () => {
|
||||
const shared = {
|
||||
user_task_no: 'INTAKE:SNI-LIFECYCLE', group: 'needs_action' as const,
|
||||
status_label: 'waiting_human', file_count: 1, can_append: false,
|
||||
uiState: {
|
||||
status: 'waiting_human', stage: 'waiting_review', blocking_reason: null,
|
||||
primary_action: null, secondary_actions: [],
|
||||
lifecycleEntries: [{ code: 'order_review' as const, state: 'current' as const, targetSurface: 'order_lifecycle_workbench' as const }],
|
||||
},
|
||||
};
|
||||
const revoked = {
|
||||
...shared,
|
||||
uiState: { ...shared.uiState, lifecycleEntries: [] },
|
||||
};
|
||||
expect(buildTaskSemanticKey(shared)).not.toBe(buildTaskSemanticKey(revoked));
|
||||
});
|
||||
|
||||
it('buildTaskSemanticKey: EML 子文件入口被撤销时必须替换聚合卡', () => {
|
||||
const child = {
|
||||
workItemNo: 'OT-LEAF-1',
|
||||
intakeNo: 'SNI-LEAF',
|
||||
status: 'waiting_human',
|
||||
stage: 'order_review',
|
||||
sourceSummary: { filename: 'leaf.pdf', documentId: 801 },
|
||||
uiState: {
|
||||
status: 'waiting_human', stage: 'order_review', blocking_reason: null,
|
||||
primary_action: null, secondary_actions: [],
|
||||
lifecycleEntries: [{
|
||||
code: 'order_review' as const, state: 'current' as const,
|
||||
targetSurface: 'order_lifecycle_workbench' as const,
|
||||
}],
|
||||
},
|
||||
} as any;
|
||||
const task = {
|
||||
user_task_no: 'INTAKE:SNI-LEAF', group: 'needs_action' as const,
|
||||
status_label: 'waiting_human', file_count: 1, can_append: false,
|
||||
uiState: { status: 'waiting_human', stage: 'order_review', blocking_reason: null, primary_action: null, secondary_actions: [] },
|
||||
aggregateChildren: [child],
|
||||
} as any;
|
||||
const revoked = {
|
||||
...task,
|
||||
aggregateChildren: [{
|
||||
...child,
|
||||
uiState: { ...child.uiState, lifecycleEntries: [] },
|
||||
}],
|
||||
};
|
||||
|
||||
expect(buildTaskSemanticKey(task)).not.toBe(buildTaskSemanticKey(revoked));
|
||||
});
|
||||
|
||||
it('buildTaskSemanticKey: authoritative ui_state without a primary action ignores stale legacy action', () => {
|
||||
const shared = {
|
||||
user_task_no: 'INTAKE:SNI-NO-ACTION', group: 'processing' as const,
|
||||
status_label: 'processing', file_count: 1, can_append: false,
|
||||
primary_action: 'retry_parse', available_actions: ['retry_parse'],
|
||||
uiState: { status: 'processing', stage: 'document_parsing', blocking_reason: null, primary_action: null, secondary_actions: [] },
|
||||
};
|
||||
const withoutLegacy = { ...shared, primary_action: null, available_actions: [] };
|
||||
|
||||
// 后端 ui_state 已明确“无动作”时,旧字段变动不能让状态卡语义闪烁或伪造 CTA。
|
||||
expect(buildTaskSemanticKey(shared)).toBe(buildTaskSemanticKey(withoutLegacy));
|
||||
});
|
||||
|
||||
it('stabilizeTaskObjects: 同一 user_task_no 且语义相同,优先复用旧对象引用(避免 DOM 重建)', () => {
|
||||
const baseTask = (no: string, updatedAt: string) => ({
|
||||
user_task_no: no,
|
||||
@@ -972,6 +1204,210 @@ describe('conversationProcessingProjection — normalize & semantic & stabilize'
|
||||
expect(normalized.processing.length).toBe(0);
|
||||
});
|
||||
|
||||
it('normalizes backend status-group task UI state and EML children without recalculating batch facts', () => {
|
||||
const backendProjection = {
|
||||
// 统计是后端按完整批次裁决的事实,不能由当前返回的局部 EML/附件数组替代。
|
||||
summary: { total_tasks: 1, total_files: 7, processing: 0, needs_action: 1, completed: 0, history: 0 },
|
||||
focused_task_no: 'INTAKE:SNI-API',
|
||||
recent_task_no: 'INTAKE:SNI-API',
|
||||
needs_action: [], processing: [], completed: [], history: [],
|
||||
status_groups: {
|
||||
failed: [{
|
||||
user_task_no: 'INTAKE:SNI-API', title: 'source.eml', display_kind: 'multi_document_task',
|
||||
document_names: ['a.pdf', 'b.pdf'], group: 'needs_action', status_label: 'failed', file_count: 2,
|
||||
can_append: false, available_actions: [], primary_action: null,
|
||||
ui_state: {
|
||||
status: 'failed', stage: 'document_parsing',
|
||||
blocking_reason: { code: 'PARSE_FAILED', i18n_key: 'shipping.parse_failed', details: {} },
|
||||
primary_action: { code: 'retry', i18n_key: 'shipping.retry', parameters: {} }, secondary_actions: [],
|
||||
},
|
||||
aggregate_children: [{
|
||||
work_item_type: 'order_task', work_item_no: 'OT-API-1', source_type: 'direct_pdf',
|
||||
root_order_task_no: 'OT-API-1', shipping_notice_no: null, conversation_id: 'conv-api',
|
||||
submission_no: 'SUB-1', intake_no: 'SNI-API', status: 'failed', stage: 'document_parsing',
|
||||
progress_version: 1, last_activity_at: '2026-08-14T00:00:00Z', current_gate: null, available_actions: [],
|
||||
source_summary: { email_subject: 'Subject', filename: 'a.pdf', document_count: 1, parsed_document_count: 0, candidate_count: 0 },
|
||||
child_order_tasks: [], ui_state: {
|
||||
status: 'failed', stage: 'document_parsing', blocking_reason: { code: 'PARSE_FAILED', details: {} },
|
||||
primary_action: { code: 'retry', parameters: {} }, secondary_actions: [],
|
||||
},
|
||||
}],
|
||||
}],
|
||||
waiting_human: [], processing: [], completed: [], cancelled: [], archived: [],
|
||||
},
|
||||
four_stage_nodes: [{ code: 'intake_parse', label_key: 'shipping.stage.intake', status: 'blocked' }],
|
||||
output_artifacts: [{ order_task_no: 'OT-API-1', filename: 'shipping.xlsx', type: 'excel', status: 'ready', action: { code: 'download_excel', enabled: true } }],
|
||||
} as unknown as ConversationProcessingProjection;
|
||||
|
||||
const normalized = normalizeConversationProcessingProjection(backendProjection);
|
||||
const eml = normalized.status_groups!.failed[0]!;
|
||||
|
||||
// 后端裁决的状态/按钮必须在 EML 与附件层均可直接消费,前端不重新推导。
|
||||
expect(eml.uiState?.primary_action?.code).toBe('retry');
|
||||
expect(eml.uiState?.primary_action?.i18nKey).toBe('shipping.retry');
|
||||
expect(eml.aggregateChildren?.[0]?.uiState?.primary_action?.code).toBe('retry');
|
||||
expect(eml.aggregateChildren?.[0]?.sourceSummary.filename).toBe('a.pdf');
|
||||
// 批次统计、四阶段与产物均是后端事实,适配时不得从附件重算或丢失。
|
||||
expect(normalized.summary.total_files).toBe(7);
|
||||
expect(normalized.four_stage_nodes).toEqual([{ code: 'intake_parse', label_key: 'shipping.stage.intake', status: 'blocked' }]);
|
||||
expect(normalized.output_artifacts?.[0]?.action.enabled).toBe(true);
|
||||
});
|
||||
|
||||
it('normalizes backend lifecycle_entries in status groups without recreating entries', () => {
|
||||
const backendProjection = {
|
||||
summary: { total_tasks: 1, total_files: 1, processing: 0, needs_action: 1, completed: 0, history: 0 },
|
||||
focused_task_no: null,
|
||||
recent_task_no: null,
|
||||
needs_action: [], processing: [], completed: [], history: [],
|
||||
status_groups: {
|
||||
failed: [],
|
||||
waiting_human: [{
|
||||
user_task_no: 'OT-LIFECYCLE-SNAKE', title: 'order.pdf', display_kind: 'single_document_task',
|
||||
document_names: ['order.pdf'], group: 'needs_action', status_label: 'waiting_human', file_count: 1,
|
||||
can_append: false, available_actions: [],
|
||||
ui_state: {
|
||||
status: 'waiting_human', stage: 'field_completeness', lifecycle_stage: 'order_review',
|
||||
lifecycle_entries: [{ code: 'intake_parse', state: 'available', target_surface: 'order_lifecycle_workbench' }, {
|
||||
code: 'order_review', state: 'current', target_surface: 'order_lifecycle_workbench',
|
||||
}],
|
||||
blocking_reason: null, primary_action: null, secondary_actions: [],
|
||||
},
|
||||
}],
|
||||
processing: [], completed: [], cancelled: [], archived: [],
|
||||
},
|
||||
} as unknown as ConversationProcessingProjection;
|
||||
|
||||
const normalized = normalizeConversationProcessingProjection(backendProjection);
|
||||
const task = normalized.status_groups!.waiting_human[0]!;
|
||||
|
||||
expect(task.uiState?.lifecycleStage).toBe('order_review');
|
||||
expect(task.uiState?.lifecycleEntries).toEqual([
|
||||
{ code: 'intake_parse', state: 'available', targetSurface: 'order_lifecycle_workbench' },
|
||||
{ code: 'order_review', state: 'current', targetSurface: 'order_lifecycle_workbench' },
|
||||
]);
|
||||
});
|
||||
|
||||
it('normalizes embedded primary-action lifecycle navigation fields from backend snake_case', () => {
|
||||
const embedded = {
|
||||
summary: { total_tasks: 1, total_files: 1, processing: 0, needs_action: 1, completed: 0, history: 0 },
|
||||
focused_task_no: null, recent_task_no: null,
|
||||
needs_action: [], processing: [], completed: [], history: [],
|
||||
status_groups: {
|
||||
failed: [],
|
||||
waiting_human: [{
|
||||
user_task_no: 'OT-FULFILLMENT-NAV', title: 'order.pdf', display_kind: 'single_document_task',
|
||||
document_names: ['order.pdf'], group: 'needs_action', status_label: 'waiting_human', file_count: 1,
|
||||
can_append: false, available_actions: [],
|
||||
ui_state: {
|
||||
status: 'waiting_human', stage: 'inventory_matching', lifecycle_stage: 'fulfillment_prep',
|
||||
lifecycle_entries: [], blocking_reason: null,
|
||||
primary_action: {
|
||||
code: 'open_inventory_match_review', execution_mode: 'navigate',
|
||||
target_surface: 'order_lifecycle_workbench', target_lifecycle_stage: 'fulfillment_prep',
|
||||
}, secondary_actions: [],
|
||||
},
|
||||
}],
|
||||
processing: [], completed: [], cancelled: [], archived: [],
|
||||
},
|
||||
} as unknown as ConversationProcessingProjection;
|
||||
|
||||
const action = normalizeConversationProcessingProjection(embedded)
|
||||
.status_groups!.waiting_human[0]!.uiState!.primary_action!;
|
||||
|
||||
expect(action.executionMode).toBe('navigate');
|
||||
expect(action.targetSurface).toBe('order_lifecycle_workbench');
|
||||
expect(action.targetLifecycleStage).toBe('fulfillment_prep');
|
||||
});
|
||||
|
||||
it('normalizes embedded secondary-action lifecycle navigation fields from backend snake_case', () => {
|
||||
const embedded = {
|
||||
summary: { total_tasks: 1, total_files: 1, processing: 0, needs_action: 1, completed: 0, history: 0 },
|
||||
focused_task_no: null, recent_task_no: null,
|
||||
needs_action: [], processing: [], completed: [], history: [],
|
||||
status_groups: {
|
||||
failed: [],
|
||||
waiting_human: [{
|
||||
user_task_no: 'OT-VIEW-NAV', title: 'order.pdf', display_kind: 'single_document_task',
|
||||
document_names: ['order.pdf'], group: 'needs_action', status_label: 'waiting_human', file_count: 1,
|
||||
can_append: false, available_actions: [],
|
||||
ui_state: {
|
||||
status: 'waiting_human', stage: 'inventory_matching', lifecycle_stage: 'fulfillment_prep',
|
||||
lifecycle_entries: [], blocking_reason: null, primary_action: null,
|
||||
secondary_actions: [{
|
||||
code: 'view_result', enabled: true, execution_mode: 'navigate',
|
||||
target_surface: 'order_lifecycle_workbench', target_lifecycle_stage: 'fulfillment_prep',
|
||||
}],
|
||||
},
|
||||
}],
|
||||
processing: [], completed: [], cancelled: [], archived: [],
|
||||
},
|
||||
} as unknown as ConversationProcessingProjection;
|
||||
|
||||
const action = normalizeConversationProcessingProjection(embedded)
|
||||
.status_groups!.waiting_human[0]!.uiState!.secondary_actions[0]!;
|
||||
|
||||
// 次动作与主动作一样来自后端授权;缺失导航字段会使文件级查看结果静默失效。
|
||||
expect(action.executionMode).toBe('navigate');
|
||||
expect(action.targetSurface).toBe('order_lifecycle_workbench');
|
||||
expect(action.targetLifecycleStage).toBe('fulfillment_prep');
|
||||
});
|
||||
|
||||
it('fails closed for unsupported embedded primary-action navigation targets', () => {
|
||||
const embedded = {
|
||||
summary: { total_tasks: 1, total_files: 1, processing: 0, needs_action: 1, completed: 0, history: 0 },
|
||||
focused_task_no: null, recent_task_no: null,
|
||||
needs_action: [], processing: [], completed: [], history: [],
|
||||
status_groups: {
|
||||
failed: [],
|
||||
waiting_human: [{
|
||||
user_task_no: 'OT-INVALID-NAV', title: 'order.pdf', display_kind: 'single_document_task',
|
||||
document_names: ['order.pdf'], group: 'needs_action', status_label: 'waiting_human', file_count: 1,
|
||||
can_append: false, available_actions: [],
|
||||
ui_state: {
|
||||
status: 'waiting_human', stage: 'inventory_matching', lifecycle_stage: 'fulfillment_prep',
|
||||
lifecycle_entries: [], blocking_reason: null,
|
||||
primary_action: {
|
||||
code: 'open_inventory_match_review', execution_mode: 'unknown',
|
||||
target_surface: 'unsupported_surface', target_lifecycle_stage: 'unsupported_stage',
|
||||
}, secondary_actions: [],
|
||||
},
|
||||
}],
|
||||
processing: [], completed: [], cancelled: [], archived: [],
|
||||
},
|
||||
} as unknown as ConversationProcessingProjection;
|
||||
|
||||
const action = normalizeConversationProcessingProjection(embedded)
|
||||
.status_groups!.waiting_human[0]!.uiState!.primary_action!;
|
||||
|
||||
expect(action.executionMode).toBeUndefined();
|
||||
expect(action.targetSurface).toBeNull();
|
||||
expect(action.targetLifecycleStage).toBeNull();
|
||||
});
|
||||
|
||||
it('keeps backend intake_parse primary-action target instead of dropping it', () => {
|
||||
const normalized = normalizeShippingProcessingProjection({
|
||||
work_item_no: 'OT-INTAKE-ACTION', source_type: 'direct_pdf', status: 'waiting_human',
|
||||
stage: 'intake_parse', progress_version: 1, last_activity_at: '2026-08-16T00:00:00Z',
|
||||
source_summary: {}, available_actions: [], child_order_tasks: [],
|
||||
ui_state: {
|
||||
status: 'waiting_human', stage: 'intake_parse', lifecycle_stage: 'intake_parse',
|
||||
lifecycle_entries: [{ code: 'intake_parse', state: 'current', target_surface: 'order_lifecycle_workbench' }],
|
||||
blocking_reason: null,
|
||||
primary_action: {
|
||||
code: 'open_intake_parse', parameters: {}, execution_mode: 'navigate',
|
||||
target_surface: 'order_lifecycle_workbench', target_lifecycle_stage: 'intake_parse',
|
||||
},
|
||||
secondary_actions: [],
|
||||
},
|
||||
});
|
||||
|
||||
// 后端指定接收解析时,前端仅透传该目标,不得由现有三阶段白名单裁决或改写。
|
||||
expect(normalized?.uiState?.primary_action?.targetLifecycleStage).toBe('intake_parse');
|
||||
expect(normalized?.uiState?.lifecycleEntries).toEqual([
|
||||
{ code: 'intake_parse', state: 'current', targetSurface: 'order_lifecycle_workbench', disabledReasonKey: null },
|
||||
]);
|
||||
});
|
||||
|
||||
it('resolveConversationProcessingFromUnified: work_items 为空时,embedded waiting_human 任务迁入 needs_action 且统一文案', () => {
|
||||
const embedded: ConversationProcessingProjection = {
|
||||
summary: { total_tasks: 1, total_files: 1, processing: 1, needs_action: 0, completed: 0, history: 0 },
|
||||
@@ -1006,7 +1442,7 @@ describe('conversationProcessingProjection — normalize & semantic & stabilize'
|
||||
expect(result!.needs_action[0]!.title).toBe('b.pdf');
|
||||
});
|
||||
|
||||
it('resolveConversationProcessingFromUnified: work_items 仅含 order_intake 时,仍走 embedded normalize 路径(过渡窗口不跳状态)', () => {
|
||||
it('resolveConversationProcessingFromUnified: 仅含 EML order_intake 时,派生统一 processing 投影而非回退 embedded', () => {
|
||||
const embedded: ConversationProcessingProjection = {
|
||||
summary: { total_tasks: 1, total_files: 1, processing: 1, needs_action: 0, completed: 0, history: 0 },
|
||||
focused_task_no: 'OT-LEG3',
|
||||
@@ -1035,7 +1471,7 @@ describe('conversationProcessingProjection — normalize & semantic & stabilize'
|
||||
{
|
||||
workItemType: 'order_intake',
|
||||
workItemNo: 'SNI-1',
|
||||
sourceType: 'direct_pdf',
|
||||
sourceType: 'eml',
|
||||
rootOrderTaskNo: null,
|
||||
shippingNoticeNo: null,
|
||||
conversationId: 'conv-1',
|
||||
@@ -1061,13 +1497,16 @@ describe('conversationProcessingProjection — normalize & semantic & stabilize'
|
||||
];
|
||||
const result = resolveConversationProcessingFromUnified(workItems, embedded);
|
||||
expect(result).not.toBeNull();
|
||||
// 过渡阶段:order_intake 不触发统一投影派生;embedded waiting_human 必须 normalize 成 waiting_review/needs_action
|
||||
// EML 尚未创建 OT 时,也必须作为一张 EML 卡进入统一“系统处理中”区。
|
||||
expect(result!.focused_task_no).toBe('OT-LEG3');
|
||||
expect(result!.processing.length).toBe(0);
|
||||
expect(result!.needs_action.length).toBe(1);
|
||||
expect(result!.needs_action[0]!.status_label).toBe('waiting_review');
|
||||
expect(result!.needs_action[0]!.title).toBe('c.pdf');
|
||||
expect(result!.needs_action[0]!.group).toBe('needs_action');
|
||||
expect(result!.needs_action).toHaveLength(0);
|
||||
expect(result!.processing).toHaveLength(1);
|
||||
expect(result!.processing[0]).toMatchObject({
|
||||
user_task_no: 'SNI-1',
|
||||
title: 'c.pdf',
|
||||
group: 'processing',
|
||||
status_label: 'processing',
|
||||
});
|
||||
});
|
||||
|
||||
it('resolveConversationProcessingFromUnified + IntakeOtStabilizer: 看到 order_task 后 2s 内暂缺 OT 保持 previousProjection(避免轮询抖动)', () => {
|
||||
|
||||
Loaded 100 of 606 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user