feat(shipping-notice,receipt-report): 新增收料报表功能并优化发货通知流程
清理废弃的shipping xfa ocr automark相关代码和job配置 新增收料报表管理的前端页面、路由和侧边栏入口 新增后端收料报表配置接口、数据库模型和RPA脚本 优化发货通知流程的重试策略,将shipping相关job默认不自动重试 移除废弃的库存源确认相关逻辑,更新流程门禁规则 重构订单模板的值适配器模块,新增坐标OCR值适配器 清理前端shipping菜单和action的废弃选项 更新相关文档和测试用例,调整.gitignore忽略规则
This commit is contained in:
1 parent
260465b72d
commit
1b6483a4ea
466 files changed
+32115
-33796
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,34 +285,10 @@ 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}`;
|
||||
|
||||
/** 入队统一 PDF 自动标记;服务端按 Profile 能力选择坐标或 XFA 多源证据。 */
|
||||
export const enqueueOrderProfilePdfAutomark = (
|
||||
profileId: number,
|
||||
@@ -329,7 +303,7 @@ export const getOrderProfilePdfAutomarkJob = (profileId: number, jobId: number)
|
||||
requestJson<{
|
||||
job_id: number;
|
||||
status: string;
|
||||
kind?: 'coordinate_regions' | 'visual_binding' | null;
|
||||
kind?: 'field_binding_candidates' | null;
|
||||
candidates?: Array<Record<string, unknown>>;
|
||||
diagnostics?: Record<string, unknown>;
|
||||
preview_render_checksum?: string | null;
|
||||
@@ -341,60 +315,12 @@ export const getOrderProfilePdfAutomarkJob = (profileId: number, jobId: number)
|
||||
auth(),
|
||||
);
|
||||
|
||||
/** 入队 XFA OCR 自动标记 Job(须合成预览 ready)。 */
|
||||
export const enqueueOrderProfileXfaOcrAutomark = (
|
||||
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`,
|
||||
{ method: 'POST', body: JSON.stringify(payload), ...jsonAuth() },
|
||||
);
|
||||
|
||||
/** 轮询 OCR 自动标记 Job 状态与建议。 */
|
||||
export const getOrderProfileXfaOcrAutomarkJob = (profileId: number, jobId: number) =>
|
||||
requestJson<{
|
||||
job_id: number;
|
||||
status: string;
|
||||
suggestions?: Array<Record<string, unknown>>;
|
||||
error_code?: string | null;
|
||||
preview_render_checksum?: string | null;
|
||||
}>(
|
||||
`/api/admin/shipping-notice/order-document-profiles/${profileId}/xfa/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() },
|
||||
);
|
||||
|
||||
@@ -403,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() },
|
||||
);
|
||||
|
||||
@@ -412,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() },
|
||||
);
|
||||
|
||||
@@ -587,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() },
|
||||
);
|
||||
|
||||
@@ -680,7 +544,6 @@ export const authorizeOrderProfilePdfPreview = (profileId: number, documentId: n
|
||||
);
|
||||
|
||||
/** @deprecated 旧 XFA 调用方兼容别名;新代码使用 authorizeOrderProfilePdfPreview。 */
|
||||
export const authorizeOrderProfileXfaPdfPreview = authorizeOrderProfilePdfPreview;
|
||||
|
||||
/** 为冻结样本绑定申请只读详情页逐页预览授权,禁止回退到当前 document layout。 */
|
||||
export const authorizeOrderProfileFrozenSamplePreviewPages = (profileId: number, sampleBindingId: number) =>
|
||||
|
||||
@@ -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>
|
||||
|
||||
|
||||
+818
-708
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>
|
||||
|
||||
-714
@@ -1,714 +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 { authorizePreviewPagesMock, authorizePdfPreviewMock, saveDraftMock, splitPreviewMock, enqueueAutomarkMock, getAutomarkJobMock, suggestUnifiedMappingMock, messageErrorMock, detailDefinition } = vi.hoisted(() => ({
|
||||
authorizePreviewPagesMock: vi.fn(),
|
||||
authorizePdfPreviewMock: vi.fn(),
|
||||
saveDraftMock: vi.fn(),
|
||||
splitPreviewMock: vi.fn(),
|
||||
enqueueAutomarkMock: vi.fn(),
|
||||
getAutomarkJobMock: vi.fn(),
|
||||
suggestUnifiedMappingMock: vi.fn(),
|
||||
messageErrorMock: 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: messageErrorMock, 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: (...args: unknown[]) => authorizePreviewPagesMock(...args),
|
||||
authorizeOrderProfilePdfPreview: (...args: unknown[]) => authorizePdfPreviewMock(...args),
|
||||
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(),
|
||||
enqueueOrderProfilePdfAutomark: (...args: unknown[]) => enqueueAutomarkMock(...args),
|
||||
getOrderProfilePdfAutomarkJob: (...args: unknown[]) => getAutomarkJobMock(...args),
|
||||
acceptOrderProfileXfaOcrAutomarkSuggestion: vi.fn(),
|
||||
rejectOrderProfileXfaOcrAutomarkSuggestion: vi.fn(),
|
||||
suggestOrderProfileXfaUnifiedMapping: (...args: unknown[]) => suggestUnifiedMappingMock(...args),
|
||||
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);
|
||||
enqueueAutomarkMock.mockReset();
|
||||
enqueueAutomarkMock.mockResolvedValue({ job_id: 9, status: 'queued' });
|
||||
getAutomarkJobMock.mockReset();
|
||||
getAutomarkJobMock.mockResolvedValue({
|
||||
job_id: 9,
|
||||
status: 'succeeded',
|
||||
kind: 'visual_binding',
|
||||
candidates: [],
|
||||
preview_render_checksum: 'r'.repeat(64),
|
||||
});
|
||||
messageErrorMock.mockReset();
|
||||
suggestUnifiedMappingMock.mockReset();
|
||||
authorizePreviewPagesMock.mockReset();
|
||||
authorizePreviewPagesMock.mockResolvedValue({
|
||||
document_id: 85,
|
||||
page_count: 1,
|
||||
pages: [{ page_no: 1, preview_token: 'token' }],
|
||||
expires_in_seconds: 60,
|
||||
});
|
||||
authorizePdfPreviewMock.mockReset();
|
||||
authorizePdfPreviewMock.mockResolvedValue({
|
||||
document_id: 85,
|
||||
preview_token: 'xfa-pdf-token',
|
||||
expires_in_seconds: 120,
|
||||
});
|
||||
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);
|
||||
enqueueAutomarkMock.mockReset();
|
||||
enqueueAutomarkMock.mockResolvedValue({ job_id: 9, status: 'queued' });
|
||||
getAutomarkJobMock.mockReset();
|
||||
getAutomarkJobMock.mockResolvedValue({
|
||||
job_id: 9,
|
||||
status: 'succeeded',
|
||||
kind: 'visual_binding',
|
||||
candidates: [],
|
||||
preview_render_checksum: 'r'.repeat(64),
|
||||
});
|
||||
messageErrorMock.mockReset();
|
||||
suggestUnifiedMappingMock.mockReset();
|
||||
authorizePreviewPagesMock.mockReset();
|
||||
authorizePreviewPagesMock.mockResolvedValue({
|
||||
document_id: 85,
|
||||
page_count: 1,
|
||||
pages: [{ page_no: 1, preview_token: 'token' }],
|
||||
expires_in_seconds: 60,
|
||||
});
|
||||
authorizePdfPreviewMock.mockReset();
|
||||
authorizePdfPreviewMock.mockResolvedValue({
|
||||
document_id: 85,
|
||||
preview_token: 'xfa-pdf-token',
|
||||
expires_in_seconds: 120,
|
||||
});
|
||||
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;
|
||||
}
|
||||
// 原 PDF 授权就绪后,合成预览失败不应禁标注。
|
||||
desk.xfaPdfGrant.value = { document_id: 85, preview_token: 'token', expires_in_seconds: 120 };
|
||||
desk.pageLoadError.value = null;
|
||||
desk.syntheticPreviewStatus.value = 'unavailable';
|
||||
expect(desk.annotationDisabled.value).toBe(false);
|
||||
|
||||
desk.xfaPdfGrant.value = null;
|
||||
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);
|
||||
|
||||
it('keeps XFA mapping ready but reports a native PDF page authorization failure', async () => {
|
||||
// 该 suite 保留多个 mounted desk;持续拒绝确保本用例的异步 loadPages 不会被旧实例抢先消费。
|
||||
authorizePdfPreviewMock.mockRejectedValue(new Error('PDF preview unavailable'));
|
||||
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', pageUnavailable: 'native page unavailable' },
|
||||
xfaAutoMark: { enqueueFailed: 'e', jobFailed: 'j' },
|
||||
} } } } })],
|
||||
},
|
||||
});
|
||||
for (let i = 0; i < 40; i += 1) {
|
||||
await flushPromises();
|
||||
if (!desk.loading.value) break;
|
||||
}
|
||||
|
||||
// 断言:XFA 字段建模不依赖 synthetic preview;仅原生 PDF 页进入可重试失败态。
|
||||
expect(desk.definition.value).toBeTruthy();
|
||||
expect(desk.loadError.value).toBe(false);
|
||||
expect(desk.pageUnavailable.value).toBe(true);
|
||||
expect(desk.pageLoadError.value).toBe('native page unavailable');
|
||||
}, 15000);
|
||||
|
||||
it('uses the single-use XFA PDF grant instead of PDFium page grants', async () => {
|
||||
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', pageUnavailable: 'native page unavailable' },
|
||||
xfaAutoMark: { enqueueFailed: 'e', jobFailed: 'j' },
|
||||
workbench: { regionLabels: { order_field: '字段 {count}' } },
|
||||
} } } } })] },
|
||||
});
|
||||
for (let i = 0; i < 40; i += 1) {
|
||||
await flushPromises();
|
||||
if (!desk.loading.value) break;
|
||||
}
|
||||
|
||||
expect(authorizePdfPreviewMock).toHaveBeenCalledWith(52, 85);
|
||||
expect(authorizePreviewPagesMock).not.toHaveBeenCalled();
|
||||
expect(desk.activeXfaPdfGrant.value?.preview_token).toBe('xfa-pdf-token');
|
||||
}, 15000);
|
||||
|
||||
it('creates a local XFA visual box immediately without requesting mapping suggestions', async () => {
|
||||
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', pageUnavailable: 'native page unavailable' },
|
||||
xfaAutoMark: { enqueueFailed: 'e', jobFailed: 'j' },
|
||||
workbench: { regionLabels: { order_field: '字段 {count}' } },
|
||||
} } } } })] },
|
||||
});
|
||||
for (let i = 0; i < 40; i += 1) {
|
||||
await flushPromises();
|
||||
if (!desk.loading.value) break;
|
||||
}
|
||||
|
||||
await desk.onCanvasCreate({ x0: 0.1, y0: 0.2, x1: 0.3, y1: 0.4 });
|
||||
|
||||
expect(suggestUnifiedMappingMock).not.toHaveBeenCalled();
|
||||
expect(desk.selectedBindingId.value).toBeTruthy();
|
||||
expect(desk.creationKind.value).toBeNull();
|
||||
expect(desk.canvasRegions.value).toEqual(expect.arrayContaining([expect.objectContaining({
|
||||
id: desk.selectedBindingId.value,
|
||||
kind: 'xfa_visual',
|
||||
pageNo: 1,
|
||||
region: { x0: 0.1, y0: 0.2, x1: 0.3, y1: 0.4 },
|
||||
visualBindingStatus: 'suggested',
|
||||
})]));
|
||||
}, 15000);
|
||||
|
||||
it('blocks saving a drawn XFA box until Schema and datasets bindings are completed', async () => {
|
||||
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', pageUnavailable: 'native page unavailable',
|
||||
blocker: { incomplete_visual_binding: '请先完成每个手工视觉框的 Schema 字段和 datasets 路径绑定' },
|
||||
},
|
||||
xfaAutoMark: { enqueueFailed: 'e', jobFailed: 'j' },
|
||||
workbench: { regionLabels: { order_field: '字段 {count}' } },
|
||||
} } } } })] },
|
||||
});
|
||||
for (let i = 0; i < 40; i += 1) {
|
||||
await flushPromises();
|
||||
if (!desk.loading.value) break;
|
||||
}
|
||||
await desk.onCanvasCreate({ x0: 0.1, y0: 0.2, x1: 0.3, y1: 0.4 });
|
||||
|
||||
await expect(desk.saveDraft()).resolves.toBe(false);
|
||||
expect(saveDraftMock).not.toHaveBeenCalled();
|
||||
expect(messageErrorMock).toHaveBeenCalledWith('请先完成每个手工视觉框的 Schema 字段和 datasets 路径绑定');
|
||||
}, 15000);
|
||||
|
||||
it('shows the OCR worker error code when an automark job fails', async () => {
|
||||
getAutomarkJobMock.mockResolvedValueOnce({
|
||||
job_id: 9,
|
||||
status: 'failed',
|
||||
error_code: 'SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_OCR_UNAVAILABLE',
|
||||
message: 'XFA native PDF OCR is unavailable',
|
||||
suggestions: [],
|
||||
});
|
||||
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', pageUnavailable: 'native page unavailable' },
|
||||
xfaAutoMark: { enqueueFailed: '入队失败', jobFailed: '任务失败', jobFailedWithCode: '自动标记不可用({code}):{message}' },
|
||||
} } } } })] },
|
||||
});
|
||||
for (let i = 0; i < 40; i += 1) {
|
||||
await flushPromises();
|
||||
if (!desk.loading.value) break;
|
||||
}
|
||||
|
||||
await expect(desk.startAutomarkJob()).rejects.toThrow('SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_OCR_UNAVAILABLE');
|
||||
expect(messageErrorMock).toHaveBeenCalledWith(
|
||||
'自动标记不可用(SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_OCR_UNAVAILABLE):XFA native PDF OCR is unavailable',
|
||||
);
|
||||
}, 15000);
|
||||
|
||||
it('projects XFA automark suggestions onto the shared canvas without persisting bindings', async () => {
|
||||
getAutomarkJobMock.mockResolvedValueOnce({
|
||||
job_id: 9,
|
||||
status: 'success',
|
||||
kind: 'visual_binding',
|
||||
candidates: [{
|
||||
suggestion_id: 'sugg-1',
|
||||
field_key: 'invoiced-to-path',
|
||||
field_code: 'customer_po_no',
|
||||
page_no: 1,
|
||||
normalized_bbox: { x0: 0.1, y0: 0.2, x1: 0.3, y1: 0.4 },
|
||||
match_class: 'medium',
|
||||
suggestion_origin: 'ocr',
|
||||
confidence: 0.95,
|
||||
needs_review: false,
|
||||
}],
|
||||
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: { loadFailed: 'fail', pageUnavailable: 'native page unavailable' },
|
||||
xfaAutoMark: { enqueueFailed: '入队失败', jobFailed: '任务失败' },
|
||||
} } } } })] },
|
||||
});
|
||||
for (let i = 0; i < 40; i += 1) {
|
||||
await flushPromises();
|
||||
if (!desk.loading.value) break;
|
||||
}
|
||||
|
||||
expect(desk.activeXfaPdfGrant.value?.preview_token).toBe('xfa-pdf-token');
|
||||
await desk.startAutomarkJob();
|
||||
|
||||
// XFA 自动标注必须以 XFA desk 选定的 annotation sample 为输入,
|
||||
// 不允许退回到普通 PDF 表单的 documentId。
|
||||
expect(enqueueAutomarkMock).toHaveBeenCalledWith(52, expect.objectContaining({
|
||||
document_id: 85,
|
||||
page_no: 1,
|
||||
}));
|
||||
expect(desk.definition.value?.bindings).toHaveLength(0);
|
||||
expect(desk.canvasRegions.value).toEqual(expect.arrayContaining([expect.objectContaining({
|
||||
id: 'automark:sugg-1',
|
||||
kind: 'xfa_visual',
|
||||
pageNo: 1,
|
||||
region: { x0: 0.1, y0: 0.2, x1: 0.3, y1: 0.4 },
|
||||
visualBindingStatus: 'suggested',
|
||||
})]));
|
||||
}, 15000);
|
||||
|
||||
it('restores only unresolved persisted automark suggestions for the annotation document', async () => {
|
||||
detailDefinition.value = {
|
||||
...structuredClone(baseDefinition),
|
||||
xfa_ocr_automark: {
|
||||
job_id: 11,
|
||||
document_id: 85,
|
||||
preview_render_checksum: 'r'.repeat(64),
|
||||
render_mode: 'native_pdf',
|
||||
suggestions: [
|
||||
{
|
||||
suggestion_id: 'open-suggestion',
|
||||
field_key: 'invoiced-to-path',
|
||||
field_code: 'customer_po_no',
|
||||
page_no: 1,
|
||||
normalized_bbox: { x0: 0.1, y0: 0.2, x1: 0.3, y1: 0.4 },
|
||||
match_class: 'medium',
|
||||
},
|
||||
{
|
||||
suggestion_id: 'resolved-suggestion',
|
||||
field_key: 'invoiced-to-path',
|
||||
field_code: 'customer_po_no',
|
||||
page_no: 1,
|
||||
normalized_bbox: { x0: 0.5, y0: 0.6, x1: 0.7, y1: 0.8 },
|
||||
decision: 'rejected',
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
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', pageUnavailable: 'native page unavailable' },
|
||||
xfaAutoMark: { enqueueFailed: '入队失败', jobFailed: '任务失败' },
|
||||
} } } } })] },
|
||||
});
|
||||
for (let i = 0; i < 40; i += 1) {
|
||||
await flushPromises();
|
||||
if (!desk.loading.value) break;
|
||||
}
|
||||
|
||||
expect(desk.autoMarkSuggestions.value.map((item) => item.suggestion_id)).toEqual(['open-suggestion']);
|
||||
expect(desk.canvasRegions.value.map((item) => item.id)).toContain('automark:open-suggestion');
|
||||
expect(desk.canvasRegions.value.map((item) => item.id)).not.toContain('automark:resolved-suggestion');
|
||||
expect(desk.definition.value?.bindings).toHaveLength(0);
|
||||
}, 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_"];
|
||||
|
||||
/**
|
||||
* 判断是否为统一视觉 / 拆分 / 迁移审计事件。
|
||||
|
||||
+1
-1
@@ -63,7 +63,7 @@ describe('OrderProfileDocumentCanvas PDF preview', () => {
|
||||
profileId: 71,
|
||||
pdfPreview: { preview_token: 'single-use-token' },
|
||||
regions: [{
|
||||
id: 'automark:sugg-1', kind: 'xfa_visual', label: '自动标注', pageNo: 1,
|
||||
id: 'automark:sugg-1', kind: 'order_field', label: '自动标注', pageNo: 1,
|
||||
region: { x0: .5, y0: .5, x1: .75, y1: .75 },
|
||||
}],
|
||||
pageNo: 1,
|
||||
|
||||
-14
@@ -55,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);优先于空态提示。 */
|
||||
@@ -64,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];
|
||||
@@ -278,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';
|
||||
@@ -365,10 +358,6 @@ onBeforeUnmount(() => { endMove(); endPan(); endCreation(); URL.revokeObjectURL(
|
||||
<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>
|
||||
@@ -377,7 +366,6 @@ 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">
|
||||
@@ -508,8 +496,6 @@ 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-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); }
|
||||
|
||||
+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
-1720
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[];
|
||||
@@ -829,71 +825,6 @@ export interface OrderProfilePdfPreviewGrant { document_id: number; preview_toke
|
||||
/** @deprecated 使用 OrderProfilePdfPreviewGrant;保留给旧 XFA 调用方。 */
|
||||
export type OrderProfileXfaPdfPreviewGrant = OrderProfilePdfPreviewGrant;
|
||||
|
||||
/** 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';
|
||||
|
||||
export interface OrderProfileBoundSample {
|
||||
id: number;
|
||||
document_id: number;
|
||||
@@ -988,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;
|
||||
@@ -1006,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;
|
||||
}
|
||||
|
||||
@@ -1024,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;
|
||||
@@ -1185,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;
|
||||
@@ -1209,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,7 +9,6 @@
|
||||
*/
|
||||
import { BusinessError, requestJson } from '@/shared/api/client';
|
||||
import { getAuthHeaders } from '@/shared/utils/auth';
|
||||
import { reportShippingDebugEvent } from '../shipping/shippingDebugReporter';
|
||||
import {
|
||||
normalizeShippingProcessingProjection,
|
||||
normalizeShippingProcessingWorkItems,
|
||||
@@ -32,6 +31,7 @@ import type {
|
||||
ShippingOrderExtractionProgressEvent,
|
||||
ShippingOrderExtractionRunCreateResponse,
|
||||
ShippingOrderReviewQueue,
|
||||
ShippingOrderReviewEmailEvidencePreview,
|
||||
ShippingOrderReviewIntakeParseContext,
|
||||
OrderExtractionSubmissionRequest,
|
||||
OrderExtractionSubmissionResponse,
|
||||
@@ -51,8 +51,6 @@ import type {
|
||||
ShippingDuplicateAction,
|
||||
ShippingOrderReviewDraftWrite,
|
||||
ShippingOrderReviewEvidence,
|
||||
ShippingOrderReviewInventoryCandidatesWrite,
|
||||
ShippingOrderReviewInventoryRoutingDecisionWrite,
|
||||
ShippingOrderReviewInventoryRoutingRerouteWrite,
|
||||
ShippingOrderReviewLlmAdjudicationPayload,
|
||||
ShippingOrderReviewLlmSuggestion,
|
||||
@@ -94,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({
|
||||
@@ -128,11 +104,6 @@ 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?: {
|
||||
lifecycle_status?: string;
|
||||
page?: number;
|
||||
@@ -182,6 +153,10 @@ export const workspaceShippingExportUrl = (taskNo: string) =>
|
||||
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', {
|
||||
@@ -379,6 +354,20 @@ 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, uploadBatchId?: string | null) =>
|
||||
requestJson<ShippingOrderExtractionDocumentsResponse>(
|
||||
@@ -455,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 后重跑资格校验。
|
||||
@@ -497,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 当前库存候选版本与历史摘要。
|
||||
*/
|
||||
@@ -536,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)。
|
||||
*/
|
||||
@@ -721,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 二进制继续由受控同源预览接口提供;坐标缺失不影响字段值。
|
||||
@@ -857,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<{
|
||||
@@ -943,10 +843,10 @@ export async function getWorkspaceShippingOrderReviewPreview(caseNo: string): Pr
|
||||
return response.blob();
|
||||
}
|
||||
|
||||
/** 读取当前 Case 同 Intake 的已解析邮件正文证据;不暴露原始 EML 或附件。 */
|
||||
export const getWorkspaceShippingOrderReviewEmailEvidencePreview = (caseNo: string, documentId: number) =>
|
||||
requestJson<{ document_id: number; document_type: 'email_body'; filename: string; text: string }>(
|
||||
`/api/workspace/shipping-notice/order-review-cases/${encodeURIComponent(caseNo)}/email-evidence-preview/${documentId}`,
|
||||
/** 读取当前 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 邮件正文;仅在接收解析工作面打开时调用。 */
|
||||
@@ -1030,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' });
|
||||
@@ -1139,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 }
|
||||
@@ -1202,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 - 发货任务编号
|
||||
@@ -1391,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"
|
||||
|
||||
@@ -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 = {
|
||||
|
||||
-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>
|
||||
+31
-3
@@ -18,6 +18,13 @@ const i18n = createI18n({
|
||||
workspace: {
|
||||
shippingNotice: {
|
||||
processGate: {
|
||||
actionCodes: {
|
||||
retry_inventory_preparation: '重新获取库存',
|
||||
},
|
||||
inventoryActions: {
|
||||
retryInventoryMatching: '重新库存匹配',
|
||||
retryInventoryPreparation: '重新获取库存',
|
||||
},
|
||||
reasons: {
|
||||
inventory_shortage_review_required: '存在库存缺口,需要人工处理',
|
||||
},
|
||||
@@ -171,7 +178,7 @@ describe('ReviewCurrentProcessingCard', () => {
|
||||
expect(nextStep).not.toContain('inventory_shortage_review_required');
|
||||
});
|
||||
|
||||
it('renders server-provided recovery actions without duplicating the primary action', async () => {
|
||||
it('hides internal inventory recovery targets while retaining the stable primary action', async () => {
|
||||
const wrapper = mount(ReviewCurrentProcessingCard, {
|
||||
props: {
|
||||
stageCode: 'inventory_matching',
|
||||
@@ -185,7 +192,28 @@ describe('ReviewCurrentProcessingCard', () => {
|
||||
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', {}],
|
||||
]);
|
||||
});
|
||||
});
|
||||
+13
-18
@@ -8,7 +8,7 @@
|
||||
-->
|
||||
<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,
|
||||
@@ -17,6 +17,7 @@ import type {
|
||||
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;
|
||||
@@ -51,8 +52,6 @@ const props = defineProps<{
|
||||
showAdminDiagnosis?: boolean;
|
||||
retrying?: boolean;
|
||||
locating?: boolean;
|
||||
/** 题7A:自动次数已耗尽但允许人工继续的源;不为空时按钮语义提示「人工继续」+ tooltip 列名。 */
|
||||
retryExhaustedSources?: string[] | null;
|
||||
/** 仅 UI 展示的 running 文案(如 inventory_preparation 正在跑时主卡按钮 loading 附加信息)。 */
|
||||
automation?: {
|
||||
status?: string | null;
|
||||
@@ -231,6 +230,7 @@ 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;
|
||||
@@ -240,12 +240,10 @@ const showBusinessAction = computed(() => {
|
||||
});
|
||||
|
||||
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 '';
|
||||
@@ -268,14 +266,7 @@ const businessActionLabel = computed(() => {
|
||||
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');
|
||||
@@ -284,9 +275,10 @@ 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();
|
||||
if (!code || isNonTaskCapabilityAction(code)) return false;
|
||||
if (!code || isNonTaskCapabilityAction(code) || isInternalInventoryAction(code)) return false;
|
||||
if (code === String(props.primaryAction?.code || '').trim()) return false;
|
||||
const key = String(
|
||||
action.i18nKey
|
||||
@@ -297,6 +289,8 @@ const recoveryActions = computed(() => (props.recoveryActions || []).filter((act
|
||||
}));
|
||||
|
||||
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
|
||||
@@ -445,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);
|
||||
|
||||
+11
-2
@@ -44,7 +44,7 @@ const props = defineProps<{
|
||||
docked: boolean;
|
||||
floatSide: 'right' | 'left';
|
||||
src: string;
|
||||
emailPreview?: { document_id: number; filename: string; text: string } | null;
|
||||
emailPreview?: { document_id: number; filename: string; text: string; render_kind: 'safe_html' | 'text'; preview_url?: string } | null;
|
||||
evidence: ShippingOrderReviewEvidence | null;
|
||||
evidenceList: ShippingOrderReviewEvidence[];
|
||||
fieldLabel?: string;
|
||||
@@ -730,7 +730,16 @@ onBeforeUnmount(() => {
|
||||
</div>
|
||||
|
||||
<div class="grid min-h-0 flex-1 grid-rows-[minmax(0,1fr)_auto]">
|
||||
<div v-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">
|
||||
<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
|
||||
|
||||
+3
-2
@@ -104,11 +104,12 @@ describe('ReviewDocumentNavigation', () => {
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
|
||||
// 关键断言:生命周期四阶段兼容不能改变既有的强制侧栏与编号折叠轨交互。
|
||||
// 关键断言:收起后仍保留文件身份摘要,不能退化成无法识别的纯编号轨。
|
||||
expect(wrapper.attributes('data-nav-mode')).toBe('sidebar');
|
||||
expect(wrapper.get('[data-testid="review-doc-nav-C-2"]').text()).toContain('2');
|
||||
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', () => {
|
||||
|
||||
@@ -48,6 +48,7 @@ const props = defineProps<{
|
||||
const emit = defineEmits<{
|
||||
select: [caseNo: string];
|
||||
'mode-change': [mode: ReviewDocumentNavMode];
|
||||
'collapse-change': [collapsed: boolean];
|
||||
}>();
|
||||
|
||||
const { t, te } = useI18n();
|
||||
@@ -93,6 +94,7 @@ const mode = computed<ReviewDocumentNavMode>(() => {
|
||||
});
|
||||
|
||||
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);
|
||||
@@ -181,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
|
||||
@@ -244,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
|
||||
@@ -287,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)"
|
||||
@@ -304,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
|
||||
|
||||
+19
@@ -26,6 +26,8 @@ const i18n = createI18n({
|
||||
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: '字段冲突' },
|
||||
@@ -38,6 +40,23 @@ const i18n = createI18n({
|
||||
});
|
||||
|
||||
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',
|
||||
|
||||
@@ -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 / 辅助 / 邮件正文)。
|
||||
*/
|
||||
@@ -170,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 }) }}
|
||||
@@ -276,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>
|
||||
+37
-26
@@ -36,7 +36,6 @@ const i18n = createI18n({
|
||||
markNonOrder: '标记为非订单',
|
||||
markQualityIssue: '文件质量异常',
|
||||
reparse: '重新识别此 PDF',
|
||||
uploadReplacement: '上传替代 PDF',
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -54,6 +53,7 @@ const emailPdfContext: ShippingOrderReviewIntakeParseContext = {
|
||||
email: {
|
||||
document_id: 7,
|
||||
filename: 'source.eml',
|
||||
render_kind: 'text',
|
||||
text: 'approved body text',
|
||||
},
|
||||
};
|
||||
@@ -76,11 +76,6 @@ function mountPanel(props: Record<string, unknown>) {
|
||||
loadFailed: false,
|
||||
previewUrl: null,
|
||||
previewLoading: false,
|
||||
saving: false,
|
||||
canMarkNonOrder: false,
|
||||
canMarkQualityIssue: false,
|
||||
canReparse: false,
|
||||
canUploadReplacement: false,
|
||||
...props,
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
@@ -96,6 +91,35 @@ describe('ReviewIntakeParsePanel', () => {
|
||||
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 });
|
||||
|
||||
@@ -105,35 +129,22 @@ describe('ReviewIntakeParsePanel', () => {
|
||||
expect(wrapper.get('[data-testid="intake-parse-no-email"]').text()).toContain('无邮件上下文');
|
||||
});
|
||||
|
||||
it('emits parse disposition intent without executing Case commands', async () => {
|
||||
it('does not render parse disposition controls inside the scrolling intake panel', () => {
|
||||
const wrapper = mountPanel({
|
||||
context: emailPdfContext,
|
||||
canMarkNonOrder: true,
|
||||
canMarkQualityIssue: true,
|
||||
canReparse: true,
|
||||
canUploadReplacement: true,
|
||||
});
|
||||
|
||||
await wrapper.get('[data-testid="intake-parse-mark-non-order"]').trigger('click');
|
||||
await wrapper.get('[data-testid="intake-parse-mark-quality-issue"]').trigger('click');
|
||||
await wrapper.get('[data-testid="intake-parse-reparse"]').trigger('click');
|
||||
await wrapper.get('[data-testid="intake-parse-upload-replacement"] input').trigger('change');
|
||||
|
||||
expect(wrapper.emitted('mark-non-order')).toHaveLength(1);
|
||||
expect(wrapper.emitted('mark-quality-issue')).toHaveLength(1);
|
||||
expect(wrapper.emitted('reparse')).toHaveLength(1);
|
||||
expect(wrapper.emitted('upload-replacement')).toHaveLength(1);
|
||||
// 关键断言:按钮由父级固定底栏统一承载,面板滚动时不得随内容离开视口。
|
||||
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 infer replacement permission from another disposition permission', () => {
|
||||
it('does not render deprecated parse disposition controls inside the scrolling panel', () => {
|
||||
const wrapper = mountPanel({
|
||||
context: emailPdfContext,
|
||||
canMarkQualityIssue: true,
|
||||
canUploadReplacement: false,
|
||||
});
|
||||
|
||||
// 关键断言:父级必须显式授予替代上传,不能因质量异常动作可用而显示上传入口。
|
||||
expect(wrapper.get('[data-testid="intake-parse-mark-quality-issue"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="intake-parse-upload-replacement"]').exists()).toBe(false);
|
||||
// 关键断言:处置由固定底栏承载,滚动内容区不得遗留重复入口。
|
||||
expect(wrapper.find('[data-testid="intake-parse-reparse"]').exists()).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -16,20 +16,11 @@ const props = defineProps<{
|
||||
loadFailed: boolean;
|
||||
previewUrl: string | null;
|
||||
previewLoading: boolean;
|
||||
saving: boolean;
|
||||
canMarkNonOrder: boolean;
|
||||
canMarkQualityIssue: boolean;
|
||||
canReparse: boolean;
|
||||
canUploadReplacement: boolean;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
'retry-context': [];
|
||||
'load-preview': [];
|
||||
'mark-non-order': [];
|
||||
'mark-quality-issue': [];
|
||||
reparse: [];
|
||||
'upload-replacement': [event: Event];
|
||||
}>();
|
||||
|
||||
const { t } = useI18n();
|
||||
@@ -83,7 +74,17 @@ watch(
|
||||
<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>
|
||||
@@ -98,24 +99,16 @@ watch(
|
||||
</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">{{ t('chat.shippingOrderReview.lifecycle.intakeParse.attachment') }}</h2>
|
||||
<dl class="mt-3 grid gap-2 text-sm sm:grid-cols-2">
|
||||
<div>
|
||||
<dt class="text-xs text-slate-500">{{ t('chat.shippingOrderReview.lifecycle.intakeParse.fileName') }}</dt>
|
||||
<dd class="mt-0.5 break-all">{{ context.attachment.filename }}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt class="text-xs text-slate-500">{{ t('chat.shippingOrderReview.lifecycle.intakeParse.fileType') }}</dt>
|
||||
<dd class="mt-0.5 break-all">{{ context.attachment.mime_type || '-' }}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
<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-4"
|
||||
class="mt-3"
|
||||
data-testid="intake-parse-attachment-preview"
|
||||
>
|
||||
<h3 class="text-xs font-medium text-slate-600 dark:text-slate-300">{{ t('chat.shippingOrderReview.lifecycle.intakeParse.preview') }}</h3>
|
||||
<p
|
||||
v-if="previewLoading"
|
||||
class="mt-2 text-sm text-slate-500"
|
||||
@@ -148,53 +141,6 @@ watch(
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<div class="flex flex-wrap gap-2" data-testid="intake-parse-disposition-actions">
|
||||
<button
|
||||
v-if="canMarkNonOrder"
|
||||
type="button"
|
||||
:disabled="saving"
|
||||
class="rounded border border-rose-200 px-3 py-2 text-sm text-rose-700 disabled:opacity-50 dark:border-rose-900 dark:text-rose-300"
|
||||
data-testid="intake-parse-mark-non-order"
|
||||
@click="emit('mark-non-order')"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.markNonOrder') }}
|
||||
</button>
|
||||
<button
|
||||
v-if="canMarkQualityIssue"
|
||||
type="button"
|
||||
:disabled="saving"
|
||||
class="rounded border border-amber-200 px-3 py-2 text-sm text-amber-800 disabled:opacity-50 dark:border-amber-900 dark:text-amber-200"
|
||||
data-testid="intake-parse-mark-quality-issue"
|
||||
@click="emit('mark-quality-issue')"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.markQualityIssue') }}
|
||||
</button>
|
||||
<button
|
||||
v-if="canReparse"
|
||||
type="button"
|
||||
:disabled="saving"
|
||||
class="rounded border border-slate-300 px-3 py-2 text-sm text-slate-600 disabled:opacity-50 dark:border-slate-700 dark:text-slate-300"
|
||||
data-testid="intake-parse-reparse"
|
||||
@click="emit('reparse')"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.reparse') }}
|
||||
</button>
|
||||
<label
|
||||
v-if="canUploadReplacement"
|
||||
class="cursor-pointer rounded border border-slate-300 px-3 py-2 text-sm text-slate-600 dark:border-slate-700 dark:text-slate-300"
|
||||
:class="saving ? 'pointer-events-none opacity-50' : ''"
|
||||
data-testid="intake-parse-upload-replacement"
|
||||
>
|
||||
<input
|
||||
class="sr-only"
|
||||
type="file"
|
||||
accept="application/pdf,.pdf"
|
||||
:disabled="saving"
|
||||
@change="emit('upload-replacement', $event)"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.uploadReplacement') }}
|
||||
</label>
|
||||
</div>
|
||||
</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>
|
||||
+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>
|
||||
|
||||
@@ -24,6 +24,24 @@ const i18n = createI18n({
|
||||
});
|
||||
|
||||
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: {
|
||||
|
||||
@@ -38,6 +38,8 @@ const props = withDefaults(defineProps<{
|
||||
flowBusy?: boolean;
|
||||
/** 解析处置入口由接收解析工作面承载时,订单复核底栏隐藏四项解析操作。 */
|
||||
showParseDispositions?: boolean;
|
||||
/** 保存并校验只属于订单复核表单,接收解析阶段必须隐藏。 */
|
||||
showValidate?: boolean;
|
||||
}>(), {
|
||||
unsavedCount: 0,
|
||||
flowPresentation: null,
|
||||
@@ -49,13 +51,13 @@ const props = withDefaults(defineProps<{
|
||||
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': [];
|
||||
@@ -130,20 +132,6 @@ const canWriteCaseActions = computed(() => props.actionsExecutable && !props.isR
|
||||
>
|
||||
<RefreshCw class="h-4 w-4" />{{ t('chat.shippingOrderReview.reparse') }}
|
||||
</button>
|
||||
<label
|
||||
v-if="showParseDispositions && 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
|
||||
@@ -184,7 +172,7 @@ const canWriteCaseActions = computed(() => props.actionsExecutable && !props.isR
|
||||
</p>
|
||||
<template v-if="!automating && canWriteCaseActions">
|
||||
<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"
|
||||
|
||||
@@ -1,13 +1,11 @@
|
||||
<!--
|
||||
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<{
|
||||
@@ -21,28 +19,15 @@ const props = defineProps<{
|
||||
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 showRetry = computed(() => (
|
||||
Boolean(props.showConversationRetry)
|
||||
&& Number(props.conversationRetryEligibleCount || 0) > 0
|
||||
));
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -63,34 +48,6 @@ const showRetry = computed(() => (
|
||||
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"
|
||||
|
||||
+24
-10
@@ -94,7 +94,7 @@ type WorkbenchFileRow = {
|
||||
po_number?: string | null;
|
||||
projection?: ShippingProcessingProjection;
|
||||
};
|
||||
const LIFECYCLE_STAGE_CODES = ['order_review', 'fulfillment_prep', 'upload_complete'] as const;
|
||||
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',
|
||||
@@ -479,14 +479,9 @@ function lifecycleEntryState(file: WorkbenchFileRow, target: LifecycleStageCode)
|
||||
}
|
||||
|
||||
function lifecycleEntryLabel(file: WorkbenchFileRow, target: LifecycleStageCode): string {
|
||||
const stage = t(`chat.shippingNoticeUi.stage.${LIFECYCLE_STAGE_LABEL_KEYS[target]}`);
|
||||
const state = lifecycleEntryState(file, target);
|
||||
const stateKey = state === 'current'
|
||||
? 'chat.shippingOrderReview.lifecycle.current'
|
||||
: state === 'available'
|
||||
? 'chat.shippingOrderReview.lifecycle.available'
|
||||
: 'chat.shippingOrderReview.lifecycle.blocked';
|
||||
return `${stage} · ${t(stateKey)}`;
|
||||
void file;
|
||||
// 阶段状态由按钮颜色和 disabled 表达,避免重复的“当前可处理/前置未完成”文案挤占文件行。
|
||||
return t(`chat.shippingNoticeUi.stage.${LIFECYCLE_STAGE_LABEL_KEYS[target]}`);
|
||||
}
|
||||
|
||||
function onOpenLifecycleStage(file: WorkbenchFileRow, lifecycleStage: LifecycleStageCode) {
|
||||
@@ -591,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(实心按钮);处理记录只读卡不调用。
|
||||
*/
|
||||
@@ -875,8 +880,17 @@ function intakeStageLabel(item: ShippingProcessingProjection): string {
|
||||
v-if="visibleWaitingHumanTasks.length"
|
||||
data-testid="shipping-processing-group-waiting_human"
|
||||
>
|
||||
<div class="mb-1.5 text-[11px] font-semibold uppercase tracking-wide text-amber-700 dark:text-amber-300">
|
||||
<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
|
||||
|
||||
@@ -149,6 +149,46 @@ describe('ShippingOrderExtractionCard', () => {
|
||||
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',
|
||||
|
||||
@@ -257,6 +257,25 @@ 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'
|
||||
@@ -310,6 +329,9 @@ const processedCount = computed(() => {
|
||||
// “处理过”口径累计为完成,否则会与批次进度中心的 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);
|
||||
});
|
||||
@@ -324,6 +346,7 @@ 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));
|
||||
});
|
||||
|
||||
@@ -453,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,
|
||||
|
||||
@@ -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') }}
|
||||
|
||||
@@ -25,14 +25,18 @@ vi.mock('vue-router', () => ({
|
||||
const api = vi.hoisted(() => ({
|
||||
cancelRun: vi.fn(async () => ({})),
|
||||
cancelDocument: vi.fn(async () => ({})),
|
||||
reparseCase: vi.fn(async () => ({})),
|
||||
reparseRun: vi.fn(async () => ({})),
|
||||
reparseBatch: vi.fn(async () => ({ created: [], excluded: [] })),
|
||||
retryRun: vi.fn(async () => ({})),
|
||||
retryIntake: vi.fn(async () => ({})),
|
||||
}));
|
||||
vi.mock('@/features/chat/api/shipping.api', () => ({
|
||||
cancelWorkspaceShippingOrderExtractionRun: api.cancelRun,
|
||||
cancelWorkspaceShippingOrderExtractionDocument: api.cancelDocument,
|
||||
reparseWorkspaceShippingOrderReviewDocument: api.reparseCase,
|
||||
reparseWorkspaceShippingOrderExtractionRun: api.reparseRun,
|
||||
reparseWorkspaceShippingOrderExtractionBatch: api.reparseBatch,
|
||||
retryWorkspaceShippingOrderExtractionRun: api.retryRun,
|
||||
retryShippingNoticeIntake: api.retryIntake,
|
||||
}));
|
||||
@@ -107,6 +111,9 @@ describe('ShippingWorkflowTimeline', () => {
|
||||
document.body.innerHTML = '';
|
||||
routerPush.mockClear();
|
||||
api.cancelDocument.mockClear();
|
||||
api.reparseCase.mockClear();
|
||||
api.reparseRun.mockClear();
|
||||
api.reparseBatch.mockClear();
|
||||
});
|
||||
|
||||
it('renders backend-owned four-stage summaries and the authorized download toolbar', async () => {
|
||||
@@ -266,7 +273,7 @@ describe('ShippingWorkflowTimeline', () => {
|
||||
}));
|
||||
});
|
||||
|
||||
it('opens the reparse confirmation for a file action without requiring a parent task-number match', async () => {
|
||||
it('executes a file reparse only through the backend-projected Case', async () => {
|
||||
const file = fileProjection({
|
||||
uiState: {
|
||||
status: 'failed', stage: 'document_parsing', lifecycleStage: 'intake_parse',
|
||||
@@ -283,8 +290,139 @@ describe('ShippingWorkflowTimeline', () => {
|
||||
});
|
||||
await flushPromises();
|
||||
|
||||
// DOCUMENT:<id> 不会匹配 OT 父任务号;已授权的叶子 Run 仍必须能打开重识别确认。
|
||||
// DOCUMENT:<id> 不会匹配 OT 父任务号;已授权叶子只能使用其后端投影 Case。
|
||||
expect(document.querySelector('[data-testid="shipping-workflow-reason-dialog"]')).not.toBeNull();
|
||||
const input = document.querySelector<HTMLTextAreaElement>('[data-testid="shipping-workflow-reason-input"]');
|
||||
if (input) {
|
||||
input.value = 'field_mapping_error';
|
||||
input.dispatchEvent(new Event('input', { bubbles: true }));
|
||||
}
|
||||
document.querySelector<HTMLElement>('[data-testid="shipping-workflow-reason-confirm"]')?.click();
|
||||
await flushPromises();
|
||||
expect(api.reparseCase).toHaveBeenCalledWith('CASE-1', 'field_mapping_error', undefined);
|
||||
expect(api.reparseRun).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('uses the backend-projected Run only when a failed file has no Review Case', async () => {
|
||||
const file = fileProjection({
|
||||
caseNo: null,
|
||||
uiState: {
|
||||
status: 'failed', stage: 'document_parsing', lifecycleStage: 'intake_parse',
|
||||
lifecycleEntries: [], blocking_reason: null,
|
||||
primary_action: { code: 'reparse', i18nKey: null, parameters: {} }, secondary_actions: [],
|
||||
},
|
||||
});
|
||||
const wrapper = mountTimeline(processingProjection(), [file]);
|
||||
await flushPromises();
|
||||
|
||||
await wrapper.findComponent({ name: 'ShippingConversationProcessingCard' }).vm.$emit('projection-action', {
|
||||
projection: file,
|
||||
item: { intent: 'retry', actionCode: 'reparse', labelKey: 'chat.shippingProcessing.action.retry_parse' },
|
||||
});
|
||||
await flushPromises();
|
||||
const input = document.querySelector<HTMLTextAreaElement>('[data-testid="shipping-workflow-reason-input"]');
|
||||
if (input) {
|
||||
input.value = 'document_quality';
|
||||
input.dispatchEvent(new Event('input', { bubbles: true }));
|
||||
}
|
||||
document.querySelector<HTMLElement>('[data-testid="shipping-workflow-reason-confirm"]')?.click();
|
||||
await flushPromises();
|
||||
|
||||
expect(api.reparseRun).toHaveBeenCalledWith('RUN-1', {
|
||||
reason: 'document_quality', comment: undefined,
|
||||
});
|
||||
expect(api.reparseCase).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('keeps batch reparse available in order review and submits the dedicated batch command', async () => {
|
||||
const file = fileProjection({
|
||||
uiState: {
|
||||
status: 'waiting_human', stage: 'waiting_review', lifecycleStage: 'order_review',
|
||||
lifecycleEntries: [], blocking_reason: null,
|
||||
primary_action: { code: 'reparse_batch', i18nKey: null, parameters: {} }, secondary_actions: [],
|
||||
},
|
||||
});
|
||||
const wrapper = mountTimeline(processingProjection(), [file]);
|
||||
await flushPromises();
|
||||
|
||||
await wrapper.findComponent({ name: 'ShippingConversationProcessingCard' }).vm.$emit('projection-action', {
|
||||
projection: file,
|
||||
item: { intent: 'reparse_batch', actionCode: 'reparse_batch', labelKey: 'chat.shippingProcessing.action.reparse_batch' },
|
||||
});
|
||||
const input = document.querySelector<HTMLTextAreaElement>('[data-testid="shipping-workflow-reason-input"]');
|
||||
if (input) {
|
||||
input.value = 'rule_updated';
|
||||
input.dispatchEvent(new Event('input', { bubbles: true }));
|
||||
}
|
||||
document.querySelector<HTMLElement>('[data-testid="shipping-workflow-reason-confirm"]')?.click();
|
||||
await flushPromises();
|
||||
|
||||
expect(api.reparseBatch).toHaveBeenCalledWith('RUN-1', {
|
||||
reason: 'rule_updated', comment: undefined,
|
||||
});
|
||||
expect(api.reparseCase).not.toHaveBeenCalled();
|
||||
expect(api.reparseRun).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('renders the authorized batch reparse button beside waiting-human files and submits its Run', async () => {
|
||||
const task = {
|
||||
...processingProjection().processing[0],
|
||||
group: 'needs_action',
|
||||
userStatus: 'waiting_human',
|
||||
available_actions: ['reparse_batch'],
|
||||
primary_action: 'reparse_batch',
|
||||
};
|
||||
const processing = processingProjection({
|
||||
needs_action: [task],
|
||||
processing: [],
|
||||
status_groups: { failed: [], waiting_human: [task], processing: [], completed: [], cancelled: [], archived: [] },
|
||||
} as Partial<ConversationProcessingProjection>);
|
||||
const wrapper = mountTimeline(processing, [fileProjection({
|
||||
uiState: {
|
||||
status: 'waiting_human', stage: 'waiting_review', lifecycleStage: 'order_review',
|
||||
lifecycleEntries: [], blocking_reason: null, primary_action: null, secondary_actions: [],
|
||||
},
|
||||
})]);
|
||||
await flushPromises();
|
||||
|
||||
const batchButton = wrapper.get('[data-testid="shipping-processing-batch-reparse"]');
|
||||
expect(batchButton.text()).toBe('重新解析本批次');
|
||||
await batchButton.trigger('click');
|
||||
const input = document.querySelector<HTMLTextAreaElement>('[data-testid="shipping-workflow-reason-input"]');
|
||||
if (input) {
|
||||
input.value = 'rule_updated';
|
||||
input.dispatchEvent(new Event('input', { bubbles: true }));
|
||||
}
|
||||
document.querySelector<HTMLElement>('[data-testid="shipping-workflow-reason-confirm"]')?.click();
|
||||
await flushPromises();
|
||||
|
||||
expect(api.reparseBatch).toHaveBeenCalledWith('RUN-1', {
|
||||
reason: 'rule_updated', comment: undefined,
|
||||
});
|
||||
});
|
||||
|
||||
it('does not render batch reparse when authorization exists outside waiting-human files', async () => {
|
||||
const task = {
|
||||
...processingProjection().processing[0],
|
||||
group: 'processing',
|
||||
userStatus: 'processing',
|
||||
available_actions: ['reparse_batch'],
|
||||
primary_action: 'reparse_batch',
|
||||
};
|
||||
const processing = processingProjection({
|
||||
needs_action: [],
|
||||
processing: [task],
|
||||
status_groups: { failed: [], waiting_human: [], processing: [task], completed: [], cancelled: [], archived: [] },
|
||||
} as Partial<ConversationProcessingProjection>);
|
||||
const wrapper = mountTimeline(processing, [fileProjection({
|
||||
uiState: {
|
||||
status: 'processing', stage: 'document_parsing', lifecycleStage: 'intake_parse',
|
||||
lifecycleEntries: [], blocking_reason: null, primary_action: null, secondary_actions: [],
|
||||
},
|
||||
})]);
|
||||
await flushPromises();
|
||||
|
||||
expect(wrapper.find('[data-testid="shipping-processing-batch-reparse"]').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it('retries a file generic-retry action by its backend run instead of silently treating it as intake retry', async () => {
|
||||
|
||||
@@ -26,7 +26,9 @@ import { useShippingProcessGateRecovery } from '@/features/shipping-process-gate
|
||||
import {
|
||||
cancelWorkspaceShippingOrderExtractionRun,
|
||||
cancelWorkspaceShippingOrderExtractionDocument,
|
||||
reparseWorkspaceShippingOrderReviewDocument,
|
||||
reparseWorkspaceShippingOrderExtractionRun,
|
||||
reparseWorkspaceShippingOrderExtractionBatch,
|
||||
retryWorkspaceShippingOrderExtractionRun,
|
||||
retryShippingNoticeIntake,
|
||||
} from '@/features/chat/api/shipping.api';
|
||||
@@ -100,6 +102,8 @@ const reasonDialogOpen = ref(false);
|
||||
const reasonDialogAction = ref<ShippingWorkflowReasonAction>('cancel');
|
||||
/** 任务级取消:走 Run API,不绑单个 WorkflowItem。 */
|
||||
const reasonDialogRunNo = ref<string | null>(null);
|
||||
/** 文件叶子重解析只能绑定后端已裁决的 Review Case;不得由前端按状态推导。 */
|
||||
const reasonDialogCaseNo = ref<string | null>(null);
|
||||
/** 单文件取消:仅由后端 cancel_unit 授权的 document_id 赋值。 */
|
||||
const reasonDialogDocumentId = ref<number | null>(null);
|
||||
const processingWorkItems = computed((): ShippingProcessingProjection[] => (
|
||||
@@ -477,6 +481,14 @@ async function onProcessingTaskAction(payload: {
|
||||
openReparseRunDialog(runNo);
|
||||
return;
|
||||
}
|
||||
if (action === 'reparse_batch') {
|
||||
if (!runNo) {
|
||||
msg.warning(t('chat.shippingProcessing.retryTaskMissingRun'));
|
||||
return;
|
||||
}
|
||||
openReparseBatchDialog(runNo);
|
||||
return;
|
||||
}
|
||||
if (action === 'retry_parse' || action === 'retry') {
|
||||
const intakeNo = String(task.user_task_no || '').replace(/^INTAKE:/i, '').trim();
|
||||
if (intakeNo.startsWith('SNI-')) {
|
||||
@@ -550,10 +562,29 @@ function openCancelRunDialog(runNo: string) {
|
||||
}
|
||||
|
||||
/**
|
||||
* 打开重识别原因弹窗:走 Run 级 reparse API。
|
||||
* 打开批次重解析原因弹窗:服务端按 PDF 预检并创建独立子 Run。
|
||||
*/
|
||||
function openReparseBatchDialog(runNo: string) {
|
||||
reasonDialogRunNo.value = String(runNo || '').trim() || null;
|
||||
reasonDialogCaseNo.value = null;
|
||||
reasonDialogDocumentId.value = null;
|
||||
reasonDialogAction.value = 'reparse_batch';
|
||||
reasonDialogOpen.value = true;
|
||||
}
|
||||
|
||||
/** 打开 Run 级重解析原因弹窗:仅重建当前 Run 的一个后继版本,不展开批次。 */
|
||||
function openReparseRunDialog(runNo: string) {
|
||||
reasonDialogRunNo.value = String(runNo || '').trim() || null;
|
||||
reasonDialogCaseNo.value = null;
|
||||
reasonDialogDocumentId.value = null;
|
||||
reasonDialogAction.value = 'reparse';
|
||||
reasonDialogOpen.value = true;
|
||||
}
|
||||
|
||||
/** 打开 Case 级重解析原因弹窗;该 Case 必须来自文件叶子的后端 Projection。 */
|
||||
function openReparseCaseDialog(caseNo: string) {
|
||||
reasonDialogCaseNo.value = String(caseNo || '').trim() || null;
|
||||
reasonDialogRunNo.value = null;
|
||||
reasonDialogDocumentId.value = null;
|
||||
reasonDialogAction.value = 'reparse';
|
||||
reasonDialogOpen.value = true;
|
||||
@@ -614,11 +645,12 @@ function reparseErrorMessage(error: unknown): { title: string; message: string }
|
||||
*/
|
||||
async function onReasonConfirm(payload: { reason: string; comment?: string }) {
|
||||
const runNo = String(reasonDialogRunNo.value || '').trim();
|
||||
const caseNo = String(reasonDialogCaseNo.value || '').trim();
|
||||
const documentId = reasonDialogDocumentId.value;
|
||||
if (!runNo || actionBusyItemNo.value) return;
|
||||
actionBusyItemNo.value = runNo;
|
||||
if ((!runNo && !caseNo) || actionBusyItemNo.value) return;
|
||||
actionBusyItemNo.value = caseNo || runNo;
|
||||
try {
|
||||
if (reasonDialogAction.value === 'reparse') {
|
||||
if (reasonDialogAction.value === 'reparse' || reasonDialogAction.value === 'reparse_batch') {
|
||||
const allowed = new Set(['rule_updated', 'field_mapping_error', 'document_quality', 'other']);
|
||||
const normalizedReason = allowed.has(payload.reason)
|
||||
? payload.reason as 'rule_updated' | 'field_mapping_error' | 'document_quality' | 'other'
|
||||
@@ -626,10 +658,19 @@ async function onReasonConfirm(payload: { reason: string; comment?: string }) {
|
||||
const comment = normalizedReason === 'other'
|
||||
? [payload.reason, payload.comment].filter(Boolean).join(' — ') || undefined
|
||||
: payload.comment;
|
||||
await reparseWorkspaceShippingOrderExtractionRun(runNo, {
|
||||
reason: normalizedReason,
|
||||
comment,
|
||||
});
|
||||
if (caseNo) {
|
||||
await reparseWorkspaceShippingOrderReviewDocument(caseNo, normalizedReason, comment);
|
||||
} else if (reasonDialogAction.value === 'reparse_batch') {
|
||||
await reparseWorkspaceShippingOrderExtractionBatch(runNo, {
|
||||
reason: normalizedReason,
|
||||
comment,
|
||||
});
|
||||
} else {
|
||||
await reparseWorkspaceShippingOrderExtractionRun(runNo, {
|
||||
reason: normalizedReason,
|
||||
comment,
|
||||
});
|
||||
}
|
||||
} else {
|
||||
if (documentId && documentId > 0) {
|
||||
await cancelWorkspaceShippingOrderExtractionDocument(runNo, documentId, { reason: payload.reason });
|
||||
@@ -640,11 +681,13 @@ async function onReasonConfirm(payload: { reason: string; comment?: string }) {
|
||||
await ctl.value.refresh();
|
||||
reasonDialogOpen.value = false;
|
||||
reasonDialogRunNo.value = null;
|
||||
reasonDialogCaseNo.value = null;
|
||||
reasonDialogDocumentId.value = null;
|
||||
} catch (err) {
|
||||
// 失败时关闭原因确认框,避免与错误提示双遮罩。
|
||||
reasonDialogOpen.value = false;
|
||||
reasonDialogRunNo.value = null;
|
||||
reasonDialogCaseNo.value = null;
|
||||
reasonDialogDocumentId.value = null;
|
||||
msg.error(reparseErrorMessage(err));
|
||||
} finally {
|
||||
@@ -706,7 +749,13 @@ async function onTaskProjectionAction(payload: {
|
||||
void onProcessingTaskAction({ task, action: 'reparse' });
|
||||
return;
|
||||
}
|
||||
// 文件叶子没有父任务同名 workItemNo;仅使用后端下发的当前 Run,不反推任务或阶段。
|
||||
// 文件叶子的重解析目标由后端投影明确给出:有 Case 走 Case API;无 Case 的
|
||||
// 失败文件只能使用该叶子下发的 Run API。禁止从状态、文件名或阶段反推目标。
|
||||
const caseNo = String(projection.caseNo || '').trim();
|
||||
if (caseNo) {
|
||||
openReparseCaseDialog(caseNo);
|
||||
return;
|
||||
}
|
||||
const runNo = String(projection.runNo || '').trim();
|
||||
if (!runNo) {
|
||||
msg.warning(t('chat.shippingProcessing.retryTaskMissingRun'));
|
||||
@@ -715,6 +764,15 @@ async function onTaskProjectionAction(payload: {
|
||||
openReparseRunDialog(runNo);
|
||||
return;
|
||||
}
|
||||
if (code === 'reparse_batch') {
|
||||
const runNo = String(projection.runNo || '').trim();
|
||||
if (!runNo) {
|
||||
msg.warning(t('chat.shippingProcessing.retryTaskMissingRun'));
|
||||
return;
|
||||
}
|
||||
openReparseBatchDialog(runNo);
|
||||
return;
|
||||
}
|
||||
if (code === 'retry_inventory_preparation') {
|
||||
const gateSummary = projection.processGate;
|
||||
if (!gateSummary) {
|
||||
|
||||
@@ -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' },
|
||||
|
||||
@@ -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,
|
||||
@@ -55,10 +52,7 @@ const api = vi.hoisted(() => ({
|
||||
|
||||
reparseDocument: vi.fn(),
|
||||
|
||||
putInventoryCandidates: vi.fn(),
|
||||
rerouteInventoryRouting: vi.fn(),
|
||||
adoptInventoryRoutingSuggestion: vi.fn(),
|
||||
keepManualInventoryRouting: vi.fn(),
|
||||
|
||||
confirmCase: vi.fn(),
|
||||
|
||||
@@ -89,10 +83,7 @@ vi.mock('../api/shipping.api', () => ({
|
||||
getWorkspaceShippingOrderExtractionRun: api.getExtractionRun,
|
||||
getWorkspaceShippingProcessingWorkItem: api.getProcessingWorkItem,
|
||||
|
||||
putWorkspaceShippingOrderReviewInventoryCandidates: api.putInventoryCandidates,
|
||||
postWorkspaceShippingOrderReviewInventoryRoutingReroute: api.rerouteInventoryRouting,
|
||||
postWorkspaceShippingOrderReviewInventoryRoutingAdoptSuggestion: api.adoptInventoryRoutingSuggestion,
|
||||
postWorkspaceShippingOrderReviewInventoryRoutingKeepManual: api.keepManualInventoryRouting,
|
||||
|
||||
confirmWorkspaceShippingOrderReviewCase: api.confirmCase,
|
||||
|
||||
@@ -345,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);
|
||||
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
|
||||
@@ -429,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();
|
||||
|
||||
@@ -439,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');
|
||||
|
||||
});
|
||||
|
||||
@@ -709,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();
|
||||
@@ -866,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 = {
|
||||
@@ -881,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,
|
||||
@@ -894,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();
|
||||
@@ -919,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,
|
||||
@@ -952,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 () => ({
|
||||
@@ -965,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({
|
||||
@@ -987,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: {} },
|
||||
@@ -1016,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',
|
||||
@@ -1029,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,
|
||||
@@ -1096,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();
|
||||
});
|
||||
|
||||
@@ -1132,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!,
|
||||
@@ -1159,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',
|
||||
@@ -1170,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');
|
||||
});
|
||||
@@ -1193,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,15 +5,13 @@
|
||||
* 逻辑:按 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,
|
||||
@@ -22,7 +20,6 @@ import {
|
||||
getWorkspaceShippingOrderReviewIntakeParseContext,
|
||||
getWorkspaceShippingOrderReviewPreview,
|
||||
getWorkspaceShippingOrderReviewEmailEvidencePreview,
|
||||
getShippingNoticeIntake,
|
||||
getWorkspaceShippingOrderReviewRun,
|
||||
getWorkspaceShippingOrderReviewQueue,
|
||||
getWorkspaceShippingOrderExtractionRun,
|
||||
@@ -32,9 +29,6 @@ import {
|
||||
updateWorkspaceShippingNoticeLine,
|
||||
markWorkspaceShippingOrderReviewNonOrder,
|
||||
markWorkspaceShippingOrderReviewQualityIssue,
|
||||
putWorkspaceShippingOrderReviewInventoryCandidates,
|
||||
postWorkspaceShippingOrderReviewInventoryRoutingAdoptSuggestion,
|
||||
postWorkspaceShippingOrderReviewInventoryRoutingKeepManual,
|
||||
postWorkspaceShippingOrderReviewInventoryRoutingReroute,
|
||||
reparseWorkspaceShippingOrderReviewDocument,
|
||||
validateWorkspaceShippingOrderReviewDraft,
|
||||
@@ -55,11 +49,11 @@ import type {
|
||||
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';
|
||||
|
||||
/** ???????????? */
|
||||
@@ -77,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;
|
||||
@@ -184,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 ??????????????
|
||||
@@ -211,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());
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -392,7 +357,7 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
|
||||
const previewCaseNo = ref<string | null>(null);
|
||||
const previewLoading = ref(false);
|
||||
const previewLoadFailed = ref(false);
|
||||
const emailPreview = ref<{ document_id: number; document_type: 'email_body'; filename: string; text: string } | null>(null);
|
||||
const emailPreview = ref<ShippingOrderReviewEmailEvidencePreview | null>(null);
|
||||
/** 接收解析工作面专用上下文;切换 Case 或重新加载时必须立即清空,禁止串附件/EML。 */
|
||||
const intakeParseContext = ref<ShippingOrderReviewIntakeParseContext | null>(null);
|
||||
const intakeParseLoading = ref(false);
|
||||
@@ -413,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 快照。
|
||||
@@ -464,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,
|
||||
@@ -505,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;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -627,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 () => {
|
||||
@@ -643,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;
|
||||
@@ -675,7 +530,7 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
|
||||
if (getCurrentInstance()) {
|
||||
onBeforeUnmount(() => {
|
||||
stopWorkflowProgressPolling();
|
||||
stopReparseProgressPolling();
|
||||
stopReparseCaseRefreshPolling();
|
||||
stopShippingProcessing();
|
||||
clearPreview();
|
||||
});
|
||||
@@ -692,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 ???????
|
||||
@@ -747,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;
|
||||
@@ -781,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),
|
||||
@@ -831,6 +674,42 @@ 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?????????
|
||||
*/
|
||||
@@ -904,9 +783,9 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
|
||||
};
|
||||
|
||||
/** 按当前证据 Document 读取邮件正文;PDF 证据仍使用受控 PDF Blob。 */
|
||||
const ensureEmailEvidenceLoaded = async (caseNo: string, documentId: number): Promise<boolean> => {
|
||||
const ensureEmailEvidenceLoaded = async (caseNo: string, documentId: number, evidenceId?: string): Promise<boolean> => {
|
||||
try {
|
||||
emailPreview.value = await getWorkspaceShippingOrderReviewEmailEvidencePreview(caseNo, documentId);
|
||||
emailPreview.value = await getWorkspaceShippingOrderReviewEmailEvidencePreview(caseNo, documentId, evidenceId);
|
||||
return true;
|
||||
} catch {
|
||||
emailPreview.value = null;
|
||||
@@ -997,12 +876,8 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
|
||||
]);
|
||||
reviewRun.value = run;
|
||||
reviewQueue.value = queue;
|
||||
// ? 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;
|
||||
// [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 : [];
|
||||
@@ -1010,16 +885,6 @@ 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;
|
||||
@@ -1338,21 +1203,6 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* ????????????????? 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
|
||||
@@ -1367,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;
|
||||
@@ -1490,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;
|
||||
@@ -1499,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 ?????????
|
||||
*/
|
||||
@@ -1618,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,
|
||||
@@ -1685,7 +1438,6 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
|
||||
draftConflictDiffLines,
|
||||
buildEligibility,
|
||||
canConfirmBuild,
|
||||
manualInventoryLines,
|
||||
routingRecoveryLines,
|
||||
isViewingHistoricalVersion,
|
||||
isWorkItemClosed,
|
||||
@@ -1714,16 +1466,6 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
|
||||
clearPreview,
|
||||
showWorkflowProgress,
|
||||
workflowProgressPolling,
|
||||
reparseProgressActive,
|
||||
reparseProgressPolling,
|
||||
reparseProgressRefreshFailed,
|
||||
reparseProgressStage,
|
||||
reparseLastStableStage,
|
||||
reparseRunStatus,
|
||||
reparseLastActivityAt,
|
||||
reparseLastRefreshedAt,
|
||||
reparseStalePolls,
|
||||
refreshReparseProgress,
|
||||
loading,
|
||||
loadFailed,
|
||||
caseSwitchLoading,
|
||||
@@ -1747,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,
|
||||
|
||||
@@ -299,7 +299,6 @@ export function normalizeLifecycleStatus(
|
||||
const HUMAN_ACTION_CODES = new Set([
|
||||
'confirm_customer', 'resolve_field_conflicts', 'adjudicate_duplicate',
|
||||
'open_order_review', 'open_order_processing', 'enter_manual_review',
|
||||
'open_inventory_source_review', 'confirm_inventory_source',
|
||||
'open_inventory_match_review', 'rematch', 'match_inventory',
|
||||
'open_shortage_review', 'upload_inventory_file', 'open_manual_upload',
|
||||
'wait_manual_upload', 'retry', 'retry_parse', 'retry_failed_documents',
|
||||
@@ -1318,7 +1317,6 @@ export function projectConversationProcessingFromWorkItems(
|
||||
primaryAction: userPrimaryAction,
|
||||
facts: userFacts,
|
||||
userGroup: item.userGroup ?? null,
|
||||
retryable: typeof item.retryable === 'boolean' ? item.retryable : false,
|
||||
userCurrentGateCode: item.userCurrentGateCode ?? null,
|
||||
legacyStatus: item.legacyStatus ?? null,
|
||||
legacyStage: item.legacyStage ?? null,
|
||||
|
||||
@@ -83,7 +83,7 @@ describe('normalizeShippingProcessingProjection', () => {
|
||||
expect(normalized!.sourceSummary.documentId).toBe(17);
|
||||
expect(normalized!.sourceSummary.assetStatus).toBe('ready');
|
||||
expect(normalized!.availableActions).toEqual(['open_review']);
|
||||
expect(normalized!.uiState).toEqual({
|
||||
expect(normalized!.uiState).toMatchObject({
|
||||
status: 'waiting_human',
|
||||
stage: 'order_review',
|
||||
blocking_reason: { code: 'pdf_preferred_critical_conflict', i18nKey: null, details: {} },
|
||||
|
||||
@@ -291,7 +291,7 @@ function normalizeAggregateSummary(
|
||||
|
||||
/**
|
||||
* 题4A:规范 inventory_preparation 结构化字段(snake_case → camelCase)。
|
||||
* 注意:failed_sources 会进一步透传到 exhausted_sources 分开(二者互斥;仅 max_attempts 耗尽的源进 exhausted)。
|
||||
* 注意:只投影当前准备结果;失败后由具体 Gate 动作决定下一步。
|
||||
*/
|
||||
function normalizeInventoryPreparation(raw: unknown): ShippingInventoryPreparationSummary | null {
|
||||
if (!raw || typeof raw !== 'object') return null;
|
||||
@@ -308,7 +308,6 @@ function normalizeInventoryPreparation(raw: unknown): ShippingInventoryPreparati
|
||||
const preparedSources = toStrArr(item.prepared_sources ?? item.preparedSources);
|
||||
const pendingSources = toStrArr(item.pending_sources ?? item.pendingSources);
|
||||
const failedSources = toStrArr(item.failed_sources ?? item.failedSources);
|
||||
const exhaustedSources = toStrArr(item.exhausted_sources ?? item.exhaustedSources);
|
||||
const activeAttemptCount = Number(item.active_attempt_count ?? item.activeAttemptCount ?? 0) || 0;
|
||||
const gateAttemptActive = Boolean(item.gate_attempt_active ?? item.gateAttemptActive ?? false);
|
||||
const latestRaw = (item.latest_attempts ?? item.latestAttempts) as Record<string, unknown> | undefined;
|
||||
@@ -348,7 +347,6 @@ function normalizeInventoryPreparation(raw: unknown): ShippingInventoryPreparati
|
||||
preparedSources,
|
||||
pendingSources,
|
||||
failedSources,
|
||||
exhaustedSources,
|
||||
activeAttemptCount,
|
||||
gateAttemptActive,
|
||||
latestAttempts: Object.keys(latestAttempts).length ? latestAttempts : undefined,
|
||||
@@ -424,14 +422,12 @@ export function normalizeShippingProcessingProjection(
|
||||
assetStatus: readNullableString(summaryRaw, 'asset_status', 'assetStatus'),
|
||||
},
|
||||
childOrderTasks: children,
|
||||
// [T9 用户态 Projection 7 字段] 优先读后端 user_* / blocking_reason / retryable / primary_action / facts;
|
||||
// [T9 用户态 Projection 6 字段] 优先读后端 user_* / blocking_reason / primary_action / facts;
|
||||
// 缺省为 null(旧后端不会下发,旧前端不读取,完全兼容)。
|
||||
userStatus: readNullableString(item, 'user_status', 'userStatus') as ShippingProcessingProjection['userStatus'],
|
||||
userStage: readNullableString(item, 'user_stage', 'userStage') as ShippingProcessingProjection['userStage'],
|
||||
userCurrentGateCode: readNullableString(item, 'user_current_gate_code', 'userCurrentGateCode'),
|
||||
blockingReason: normalizeBlockingReason(item.blocking_reason ?? item.blockingReason),
|
||||
retryable:
|
||||
(item.retryable as boolean | undefined) == null ? false : Boolean(item.retryable),
|
||||
primaryAction: normalizePrimaryAction(item.primary_action ?? item.primaryAction),
|
||||
uiState: normalizeProcessingUiState(item.ui_state ?? item.uiState),
|
||||
facts: normalizeFacts(item.facts),
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
downloadWorkspaceShippingExportArchive as requestShippingExportArchive,
|
||||
workspaceShippingExportUrl,
|
||||
workspaceShippingInventoryFileUrl,
|
||||
workspaceShippingLineInventoryFileUrl,
|
||||
} from '@/features/chat/api/shipping.api';
|
||||
import { getAuthHeaders } from '@/shared/utils/auth';
|
||||
|
||||
@@ -25,6 +26,17 @@ export async function downloadWorkspaceShippingInventoryFile(taskId: string): Pr
|
||||
await downloadWorkspaceShippingFile(workspaceShippingInventoryFileUrl(taskId), `${taskId}-inventory.xlsx`);
|
||||
}
|
||||
|
||||
/** 下载某订单行实际匹配的库存快照;后端复核该文件号是否为当前行事实。 */
|
||||
export async function downloadWorkspaceShippingLineInventoryFile(
|
||||
taskId: string,
|
||||
inventoryFileNo: string,
|
||||
): Promise<void> {
|
||||
await downloadWorkspaceShippingFile(
|
||||
workspaceShippingLineInventoryFileUrl(taskId, inventoryFileNo),
|
||||
`${inventoryFileNo}.xlsx`,
|
||||
);
|
||||
}
|
||||
|
||||
async function downloadWorkspaceShippingFile(url: string, fallbackName: string): Promise<void> {
|
||||
const res = await fetch(url, { headers: getAuthHeaders() });
|
||||
if (!res.ok) {
|
||||
|
||||
@@ -4,7 +4,6 @@
|
||||
* 依赖:shippingMenu.resolveShippingNumericChoice、types/shipping.types。
|
||||
* 逻辑:useChatShippingSendHandler 调用;覆盖手工上传、库存上传、Excel 生成/下载与切票。
|
||||
*/
|
||||
import { resolveShippingNumericChoice } from './shippingMenu';
|
||||
import type { ShippingMenuAction } from '../types/shipping.types';
|
||||
|
||||
export interface ShippingTaskSwitchIntent {
|
||||
@@ -27,20 +26,6 @@ export function isShippingManualUploadIntent(text: string): boolean {
|
||||
].some((pattern) => pattern.test(normalized));
|
||||
}
|
||||
|
||||
export function isShippingInventoryUploadIntent(text: string, assistantContext: string): boolean {
|
||||
const normalized = text.trim();
|
||||
if (!normalized) return false;
|
||||
const choice = resolveShippingNumericChoice(normalized, assistantContext);
|
||||
if (choice === 'upload') return true;
|
||||
return [
|
||||
/^上传库存$/,
|
||||
/上传库存文件/,
|
||||
/手工上传/,
|
||||
/选择库存/,
|
||||
/upload.*inventory/i,
|
||||
].some((pattern) => pattern.test(normalized));
|
||||
}
|
||||
|
||||
export function isShippingGenerateExcelIntent(text: string): boolean {
|
||||
const normalized = text.trim();
|
||||
if (!normalized) return false;
|
||||
|
||||
@@ -29,7 +29,6 @@ export function classifyShippingMenuLine(desc: string): ShippingMenuAction | nul
|
||||
const normalized = String(desc || '').trim();
|
||||
if (!normalized) return null;
|
||||
if (/已确认/.test(normalized)) return null;
|
||||
if (/(?:选择|上传).*(?:库存|excel|xlsx|xls|csv)/i.test(normalized)) return 'upload';
|
||||
if (/(?:重试|重新)\s*RPA|重试.*(?:导出|获取|拉取)|RPA.*(?:导出|获取|拉取).*重试/i.test(desc)) return 'retry_rpa';
|
||||
if (/重新解析|重解析|reparse/i.test(desc)) return 'reparse';
|
||||
if (/驳回|取消|reject/i.test(desc)) return 'reject';
|
||||
|
||||
@@ -1,24 +1,21 @@
|
||||
/**
|
||||
* features/chat/shipping/shippingTurnActions.spec.ts
|
||||
* 用途:验证决策/冻结等 Chat Turn 映射(不含已下线的 create_batch)。
|
||||
* 用途:验证聊天仅构造仍允许的非履约 Chat Turn。
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { resolveShippingChatTurn } from './shippingTurnActions';
|
||||
|
||||
describe('shippingTurnActions', () => {
|
||||
it('maps freeze_order only with the version shown to the user', () => {
|
||||
// 关键断言:缺版本不得构造 freeze Turn,避免乐观锁盲写。
|
||||
it('does not map legacy fulfillment writes to Chat Turns', () => {
|
||||
// 关键断言:冻结、库存源、匹配、Excel 与上传写入必须由正式 OT Gate 裁决。
|
||||
expect(resolveShippingChatTurn('freeze_order', 'sn-freeze-001')).toBeNull();
|
||||
expect(resolveShippingChatTurn('freeze_order', 'sn-freeze-001', { expectedOrderDataVersion: 7 })).toEqual({
|
||||
actionType: 'shipping.freeze_order',
|
||||
payload: { task_no: 'SN-FREEZE-001', expected_order_data_version: 7 },
|
||||
});
|
||||
expect(resolveShippingChatTurn('confirm_inventory_source', 'sn-source-001', { sourceCode: 'WH-A' })).toBeNull();
|
||||
expect(resolveShippingChatTurn('match_inventory', 'sn-match-001')).toBeNull();
|
||||
expect(resolveShippingChatTurn('generate_excel', 'sn-excel-001')).toBeNull();
|
||||
expect(resolveShippingChatTurn('retry_upload', 'sn-upload-001')).toBeNull();
|
||||
});
|
||||
|
||||
it('maps confirm decision to submit_decision', () => {
|
||||
expect(resolveShippingChatTurn('confirm', 'sn-1')).toEqual({
|
||||
actionType: 'shipping.submit_decision',
|
||||
payload: { task_no: 'SN-1', decision: 'confirm' },
|
||||
});
|
||||
it('does not map a legacy confirm decision to a Chat Turn', () => {
|
||||
expect(resolveShippingChatTurn('confirm', 'sn-1')).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -1,11 +1,9 @@
|
||||
/**
|
||||
* features/chat/shipping/shippingTurnActions.ts
|
||||
* 用途:将发货通知菜单/决策 action.id 映射为 Chat Turn action_type + payload。
|
||||
* 依赖:constants/shipping。
|
||||
* 逻辑:useChatShippingDecision 与 useChatShippingMenuHandler 调用本模块,不再直调 workspace API 插消息;
|
||||
* co8 后已移除 create_batch / switch_batch_focus Turn 构造器,上传改走 Intake + order extraction。
|
||||
* 用途:仅构造仍允许的发货通知 Chat Turn。
|
||||
* 依赖:无。
|
||||
* 逻辑:履约写操作已统一迁入正式 OT Gate,本模块只保留非履约的聊天辅助 Turn。
|
||||
*/
|
||||
import { SHIPPING_DECISION_ACTIONS } from '../constants/shipping';
|
||||
|
||||
export interface ShippingChatTurnSpec {
|
||||
actionType: string;
|
||||
@@ -13,10 +11,10 @@ export interface ShippingChatTurnSpec {
|
||||
}
|
||||
|
||||
/**
|
||||
* 将发货 UI 动作 id 解析为平台 Chat Turn 规格。
|
||||
* 将仍允许的 Chat 动作解析为平台 Turn 规格。
|
||||
* @param actionId - 状态机 action_buttons.id
|
||||
* @param taskNo - 任务编号
|
||||
* @param extra - 额外参数,如 confirm_inventory_source 的 source_code
|
||||
* @param extra - 保留参数,供调用方类型兼容;履约写不再使用。
|
||||
* @returns Chat Turn 规格;无法映射时返回 null
|
||||
*/
|
||||
export function resolveShippingChatTurn(
|
||||
@@ -29,59 +27,9 @@ export function resolveShippingChatTurn(
|
||||
const id = String(actionId || '').trim();
|
||||
if (!id) return null;
|
||||
|
||||
if (SHIPPING_DECISION_ACTIONS.has(id)) {
|
||||
return {
|
||||
actionType: 'shipping.submit_decision',
|
||||
payload: { task_no: normalizedTaskNo, decision: id },
|
||||
};
|
||||
}
|
||||
|
||||
switch (id) {
|
||||
case 'freeze_order':
|
||||
const expectedOrderDataVersion = extra?.expectedOrderDataVersion;
|
||||
if (!Number.isInteger(expectedOrderDataVersion) || !expectedOrderDataVersion || expectedOrderDataVersion < 1) return null;
|
||||
return {
|
||||
actionType: 'shipping.freeze_order',
|
||||
payload: {
|
||||
task_no: normalizedTaskNo,
|
||||
expected_order_data_version: expectedOrderDataVersion,
|
||||
},
|
||||
};
|
||||
case 'generate_excel':
|
||||
return { actionType: 'shipping.generate_excel', payload: { task_no: normalizedTaskNo } };
|
||||
case 'retry_upload':
|
||||
return { actionType: 'shipping.retry_upload', payload: { task_no: normalizedTaskNo } };
|
||||
case 'match_inventory':
|
||||
return { actionType: 'shipping.match_inventory', payload: { task_no: normalizedTaskNo } };
|
||||
case 'mark_manual_uploaded':
|
||||
return { actionType: 'shipping.mark_manual_uploaded', payload: { task_no: normalizedTaskNo } };
|
||||
case 'confirm_inventory_source': {
|
||||
const sourceCode = String(extra?.sourceCode || '').trim().toUpperCase();
|
||||
if (!sourceCode) return null;
|
||||
return {
|
||||
actionType: 'shipping.confirm_inventory_source',
|
||||
payload: { task_no: normalizedTaskNo, source_code: sourceCode },
|
||||
};
|
||||
}
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 构造 submit_decision Chat Turn(文本/菜单决策共用)。
|
||||
*/
|
||||
export function buildShippingSubmitDecisionTurn(
|
||||
taskNo: string,
|
||||
decision: string,
|
||||
): ShippingChatTurnSpec {
|
||||
return {
|
||||
actionType: 'shipping.submit_decision',
|
||||
payload: {
|
||||
task_no: String(taskNo || '').trim().toUpperCase(),
|
||||
decision: String(decision || '').trim(),
|
||||
},
|
||||
};
|
||||
void id;
|
||||
void extra;
|
||||
return null;
|
||||
}
|
||||
/**
|
||||
* 构造货代领域 refs,键名与 agent_runtime_context.refs 对齐。
|
||||
|
||||
@@ -1,102 +1,57 @@
|
||||
/**
|
||||
* features/chat/shipping/useChatShippingDecision.spec.ts
|
||||
* 用途:验证发货通知决策处理器经 Chat Turn 发起,silent 模式不追加用户气泡。
|
||||
* 用途:验证发货 Chat 不再承载履约写,操作只刷新权威 OT 投影。
|
||||
* 依赖:vitest、vue refs、useChatShippingDecision。
|
||||
* 逻辑:mock startChatTurn,覆盖 silent/普通决策与显式 taskId 分支。
|
||||
*/
|
||||
import { computed, ref } from 'vue';
|
||||
import { describe, expect, it, vi, beforeEach } from 'vitest';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { createShippingDecisionHandlers, type ShippingDecisionContext } from './useChatShippingDecision';
|
||||
import type { ChatMessage } from '../types/chat.types';
|
||||
|
||||
const defaultStartChatTurn = vi.fn(async (options: {
|
||||
hooks?: { onAssistantMessageFinished?: (msg: ChatMessage) => Promise<void> };
|
||||
}) => {
|
||||
await options?.hooks?.onAssistantMessageFinished?.(
|
||||
{ role: 'assistant', content: 'mock assistant' },
|
||||
);
|
||||
return true;
|
||||
});
|
||||
|
||||
const createContext = (
|
||||
overrides: Partial<ShippingDecisionContext> = {},
|
||||
): ShippingDecisionContext => ({
|
||||
messages: ref([]),
|
||||
conversationId: ref('conv-001'),
|
||||
history: ref([{ conversation_id: 'conv-001' }]),
|
||||
isShippingNoticeAgent: computed(() => true),
|
||||
currentAgentId: computed(() => 42),
|
||||
getActiveShippingTaskId: () => 'SN-FOCUS-001',
|
||||
getActiveShippingBatchNo: () => 'BATCH-001',
|
||||
loadHistory: vi.fn(async () => undefined),
|
||||
refreshShippingActions: vi.fn(async () => undefined),
|
||||
startChatTurn: defaultStartChatTurn,
|
||||
msg: {
|
||||
warning: vi.fn(),
|
||||
success: vi.fn(),
|
||||
},
|
||||
t: (key: string) => key,
|
||||
...overrides,
|
||||
});
|
||||
|
||||
describe('useChatShippingDecision', () => {
|
||||
beforeEach(() => {
|
||||
defaultStartChatTurn.mockClear();
|
||||
});
|
||||
|
||||
it('does not append local chat messages when decision runs in silent mode', async () => {
|
||||
it('does not dispatch a Chat Turn for a legacy decision', async () => {
|
||||
const ctx = createContext();
|
||||
const { executeShippingDecision } = createShippingDecisionHandlers(ctx);
|
||||
|
||||
const ok = await executeShippingDecision('reparse_inventory', '重新上传库存', { silent: true });
|
||||
|
||||
expect(ok).toBe(true);
|
||||
expect(ctx.startChatTurn).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
inputType: 'action',
|
||||
actionType: 'shipping.submit_decision',
|
||||
payload: { task_no: 'SN-FOCUS-001', decision: 'reparse_inventory' },
|
||||
silent: true,
|
||||
}),
|
||||
);
|
||||
expect(ctx.messages.value).toEqual([]);
|
||||
expect(ok).toBe(false);
|
||||
expect(ctx.refreshShippingActions).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('delegates normal decisions to startChatTurn with display text', async () => {
|
||||
it('does not dispatch a Chat Turn for a normal legacy decision', async () => {
|
||||
const ctx = createContext();
|
||||
const { executeShippingDecision } = createShippingDecisionHandlers(ctx);
|
||||
|
||||
const ok = await executeShippingDecision('confirm', '确认');
|
||||
|
||||
expect(ok).toBe(true);
|
||||
expect(ctx.startChatTurn).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
actionType: 'shipping.submit_decision',
|
||||
displayText: expect.stringContaining('SN-FOCUS-001'),
|
||||
payload: { task_no: 'SN-FOCUS-001', decision: 'confirm' },
|
||||
}),
|
||||
);
|
||||
expect(ok).toBe(false);
|
||||
expect(ctx.refreshShippingActions).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('does not show success toast for retry_rpa inside shipping agent workspace', async () => {
|
||||
it('refreshes authoritative actions when Chat decision is rejected', async () => {
|
||||
const ctx = createContext();
|
||||
const { executeShippingDecision } = createShippingDecisionHandlers(ctx);
|
||||
|
||||
const ok = await executeShippingDecision('retry_rpa', '重新获取库存');
|
||||
|
||||
expect(ok).toBe(true);
|
||||
expect(ctx.startChatTurn).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
payload: { task_no: 'SN-FOCUS-001', decision: 'retry_rpa' },
|
||||
}),
|
||||
);
|
||||
expect(ctx.msg.success).not.toHaveBeenCalled();
|
||||
expect(ok).toBe(false);
|
||||
expect(ctx.refreshShippingActions).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('prefers explicit taskId for workspace retry decisions', async () => {
|
||||
it('does not dispatch even when a legacy decision supplies an explicit taskId', async () => {
|
||||
const ctx = createContext({
|
||||
getActiveShippingTaskId: () => '',
|
||||
});
|
||||
@@ -104,22 +59,14 @@ describe('useChatShippingDecision', () => {
|
||||
|
||||
const ok = await executeShippingDecision('retry_rpa', '重新获取库存', { taskId: 'sn-target-009' });
|
||||
|
||||
expect(ok).toBe(true);
|
||||
expect(ctx.startChatTurn).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
payload: { task_no: 'SN-TARGET-009', decision: 'retry_rpa' },
|
||||
}),
|
||||
);
|
||||
expect(ctx.msg.warning).not.toHaveBeenCalled();
|
||||
expect(ok).toBe(false);
|
||||
});
|
||||
|
||||
it('returns false when startChatTurn reports failure', async () => {
|
||||
const ctx = createContext({
|
||||
startChatTurn: vi.fn(async () => false),
|
||||
});
|
||||
const { executeShippingDecision } = createShippingDecisionHandlers(ctx);
|
||||
it('does not dispatch manual upload through Chat', async () => {
|
||||
const ctx = createContext();
|
||||
const { executeShippingManualUpload } = createShippingDecisionHandlers(ctx);
|
||||
|
||||
const ok = await executeShippingDecision('confirm', '确认');
|
||||
const ok = await executeShippingManualUpload('SN-FOCUS-001');
|
||||
|
||||
expect(ok).toBe(false);
|
||||
});
|
||||
|
||||
@@ -1,28 +1,13 @@
|
||||
/**
|
||||
* features/chat/shipping/useChatShippingDecision.ts
|
||||
* 用途:封装人工决策提交与手工上传标记逻辑,统一走 Chat Turn SSE。
|
||||
* 依赖:shippingTurnActions、chat-turn.types、chat.types。
|
||||
* 逻辑:由 useChatShipping 调用;所有决策/手工上传经 startChatTurn,不再 push 本地消息或直调 workspace API。
|
||||
* 用途:阻止 Chat 提交已迁入正式 OT Gate 的履约写操作。
|
||||
* 依赖:chat.types。
|
||||
* 逻辑:历史聊天指令只刷新权威投影并提示进入任务处理页;不再构造 Chat Turn 或上传凭据。
|
||||
*/
|
||||
import { buildShippingSubmitDecisionTurn, buildShippingTurnRefs } from './shippingTurnActions';
|
||||
import { reportShippingDebugEvent } from './shippingDebugReporter';
|
||||
import { uploadFileAsset } from '@/shared/api/file-assets.api';
|
||||
import type { StartChatTurnOptions } from '../types/chat-turn.types';
|
||||
import type { ChatMessage, ChatSessionItem } from '../types/chat.types';
|
||||
import type { ComputedRef, Ref } from 'vue';
|
||||
|
||||
export interface ShippingDecisionContext {
|
||||
messages: Ref<ChatMessage[]>;
|
||||
conversationId: Ref<string | null>;
|
||||
history: Ref<ChatSessionItem[]>;
|
||||
isShippingNoticeAgent: ComputedRef<boolean>;
|
||||
currentAgentId: ComputedRef<number>;
|
||||
getActiveShippingTaskId: () => string;
|
||||
getActiveShippingBatchNo: () => string;
|
||||
loadHistory: () => Promise<void>;
|
||||
refreshShippingActions: () => Promise<void>;
|
||||
startChatTurn: (options: StartChatTurnOptions) => Promise<boolean>;
|
||||
msg: { warning: (text: string) => void; success: (text: string) => void };
|
||||
msg: { warning: (text: string) => void };
|
||||
t: (key: string, params?: Record<string, unknown>) => string;
|
||||
}
|
||||
|
||||
@@ -34,139 +19,36 @@ export interface ExecuteShippingDecisionOptions {
|
||||
/**
|
||||
* 创建发货通知决策处理器。
|
||||
*
|
||||
* 核心逻辑:构造 shipping.submit_decision Chat Turn,由平台 SSE 统一渲染 user/assistant 与 ChatLog。
|
||||
* 核心逻辑:Chat 不再有履约写执行权,只刷新后端 Gate 投影。
|
||||
* @param ctx - 决策处理上下文
|
||||
* @returns 人工决策与手工上传确认处理函数
|
||||
*/
|
||||
export function createShippingDecisionHandlers(ctx: ShippingDecisionContext) {
|
||||
const manualUploadInFlightTaskIds = new Set<string>();
|
||||
|
||||
const reportRetryRpaDebug = (hypothesisId: string, msg: string, data: Record<string, unknown>) =>
|
||||
reportShippingDebugEvent('useChatShippingDecision.ts', hypothesisId, msg, data);
|
||||
|
||||
const syncHistoryIfNeeded = async () => {
|
||||
if (!ctx.conversationId.value && ctx.history.value.length === 0) {
|
||||
await ctx.loadHistory();
|
||||
} else if (ctx.conversationId.value) {
|
||||
const exists = ctx.history.value.some((h) => h.conversation_id === ctx.conversationId.value);
|
||||
if (!exists) await ctx.loadHistory();
|
||||
}
|
||||
};
|
||||
|
||||
const afterDecisionTurn = async () => {
|
||||
await syncHistoryIfNeeded();
|
||||
void ctx.refreshShippingActions();
|
||||
};
|
||||
|
||||
/**
|
||||
* 在 Chat 操作中选择并上传人工货代回执,返回当前用户私有的 FileAsset 编号。
|
||||
* 取消选择不会提交“已手工上传”动作,确保后端的证据门禁没有绕过路径。
|
||||
*/
|
||||
const selectManualUploadEvidence = () => new Promise<File | null>((resolve) => {
|
||||
const picker = document.createElement('input');
|
||||
picker.type = 'file';
|
||||
picker.accept = 'image/*,.pdf';
|
||||
picker.style.display = 'none';
|
||||
document.body.appendChild(picker);
|
||||
let settled = false;
|
||||
const finish = (file: File | null) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
picker.remove();
|
||||
resolve(file);
|
||||
};
|
||||
picker.addEventListener('change', () => finish(picker.files?.[0] || null), { once: true });
|
||||
picker.addEventListener('cancel', () => finish(null), { once: true });
|
||||
// 部分浏览器不会触发 cancel;窗口重新获得焦点后仍未选择文件即视为取消。
|
||||
window.addEventListener('focus', () => setTimeout(() => finish(picker.files?.[0] || null), 0), { once: true });
|
||||
picker.click();
|
||||
});
|
||||
|
||||
/**
|
||||
* 提交发货人工决策,经 Chat Turn 统一 SSE 返回。
|
||||
*/
|
||||
/** 历史 Chat 决策只刷新 Gate 投影,禁止绕过正式 OT。 */
|
||||
const executeShippingDecision = async (
|
||||
decision: string,
|
||||
displayText?: string,
|
||||
options?: ExecuteShippingDecisionOptions,
|
||||
) => {
|
||||
const taskId = String(options?.taskId || ctx.getActiveShippingTaskId() || '').trim().toUpperCase();
|
||||
void reportRetryRpaDebug('D', 'executeShippingDecision entry', {
|
||||
decision,
|
||||
taskId,
|
||||
conversationId: ctx.conversationId.value,
|
||||
silent: Boolean(options?.silent),
|
||||
});
|
||||
void decision;
|
||||
void displayText;
|
||||
void options;
|
||||
if (!taskId) {
|
||||
ctx.msg.warning(ctx.t('chat.shippingNoticeMissingTaskId'));
|
||||
return false;
|
||||
}
|
||||
const userText = (displayText || decision).trim();
|
||||
const turnSpec = buildShippingSubmitDecisionTurn(taskId, decision);
|
||||
try {
|
||||
const ok = await ctx.startChatTurn({
|
||||
agentId: ctx.currentAgentId.value,
|
||||
inputType: 'action',
|
||||
displayText: options?.silent ? userText : `${userText}\n任务编号:${taskId}`,
|
||||
actionType: turnSpec.actionType,
|
||||
payload: turnSpec.payload,
|
||||
refs: buildShippingTurnRefs(taskId, ctx.getActiveShippingBatchNo()),
|
||||
silent: options?.silent,
|
||||
hooks: {
|
||||
onAssistantMessageFinished: async (assistantMsg) => {
|
||||
void assistantMsg;
|
||||
await afterDecisionTurn();
|
||||
},
|
||||
},
|
||||
});
|
||||
return ok;
|
||||
} catch (e: unknown) {
|
||||
const errorMessage = e instanceof Error ? e.message : ctx.t('chat.streamError.generic');
|
||||
ctx.msg.warning(errorMessage);
|
||||
return false;
|
||||
}
|
||||
await ctx.refreshShippingActions();
|
||||
ctx.msg.warning(ctx.t('chat.shippingNoticeUi.manualUpload.openTaskWorkbench'));
|
||||
return false;
|
||||
};
|
||||
|
||||
const executeShippingManualUpload = async (taskId: string, displayText?: string) => {
|
||||
const normalizedTaskId = String(taskId || '').trim().toUpperCase();
|
||||
if (!normalizedTaskId || manualUploadInFlightTaskIds.has(normalizedTaskId)) return false;
|
||||
manualUploadInFlightTaskIds.add(normalizedTaskId);
|
||||
const userText = (displayText || '我已在货代系统完成上传').trim();
|
||||
try {
|
||||
const evidenceFile = await selectManualUploadEvidence();
|
||||
if (!evidenceFile) {
|
||||
ctx.msg.warning('请先选择货代上传截图或回执文件');
|
||||
return false;
|
||||
}
|
||||
const evidence = await uploadFileAsset(evidenceFile);
|
||||
const ok = await ctx.startChatTurn({
|
||||
agentId: ctx.currentAgentId.value,
|
||||
inputType: 'action',
|
||||
displayText: userText,
|
||||
actionType: 'shipping.mark_manual_uploaded',
|
||||
payload: { task_no: normalizedTaskId, evidence_asset_no: evidence.asset_no },
|
||||
refs: buildShippingTurnRefs(normalizedTaskId, ctx.getActiveShippingBatchNo()),
|
||||
hooks: {
|
||||
onAssistantMessageFinished: async (assistantMsg) => {
|
||||
assistantMsg.shipping_actions_used = true;
|
||||
assistantMsg.shipping_actions = undefined;
|
||||
ctx.messages.value.forEach((rawMsg) => {
|
||||
if (rawMsg.role === 'assistant') {
|
||||
rawMsg.shipping_actions = undefined;
|
||||
}
|
||||
});
|
||||
void ctx.refreshShippingActions();
|
||||
},
|
||||
},
|
||||
});
|
||||
return ok;
|
||||
} catch (e: unknown) {
|
||||
const errorMessage = e instanceof Error ? e.message : '标记手工上传失败';
|
||||
ctx.msg.warning(errorMessage);
|
||||
return false;
|
||||
} finally {
|
||||
manualUploadInFlightTaskIds.delete(normalizedTaskId);
|
||||
}
|
||||
void taskId;
|
||||
void displayText;
|
||||
await ctx.refreshShippingActions();
|
||||
ctx.msg.warning(ctx.t('chat.shippingNoticeUi.manualUpload.openTaskWorkbench'));
|
||||
return false;
|
||||
};
|
||||
|
||||
return { executeShippingDecision, executeShippingManualUpload };
|
||||
|
||||
@@ -8,23 +8,10 @@ import { computed, ref } from 'vue';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { createShippingMenuHandlers, type ShippingMenuHandlerContext } from './useChatShippingMenuHandler';
|
||||
|
||||
const {
|
||||
confirmWorkspaceShippingInventorySource,
|
||||
getWorkspaceShippingTask,
|
||||
} = vi.hoisted(() => ({
|
||||
confirmWorkspaceShippingInventorySource: vi.fn(),
|
||||
getWorkspaceShippingTask: vi.fn(),
|
||||
}));
|
||||
|
||||
const { downloadWorkspaceShippingExcelFile } = vi.hoisted(() => ({
|
||||
downloadWorkspaceShippingExcelFile: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('@/features/chat/api/shipping.api', () => ({
|
||||
confirmWorkspaceShippingInventorySource,
|
||||
getWorkspaceShippingTask,
|
||||
}));
|
||||
|
||||
vi.mock('./shippingDownload', () => ({
|
||||
downloadWorkspaceShippingExcelFile,
|
||||
}));
|
||||
@@ -54,12 +41,10 @@ const createContext = (
|
||||
|
||||
describe('useChatShippingMenuHandler', () => {
|
||||
beforeEach(() => {
|
||||
confirmWorkspaceShippingInventorySource.mockReset();
|
||||
getWorkspaceShippingTask.mockReset();
|
||||
downloadWorkspaceShippingExcelFile.mockReset();
|
||||
});
|
||||
|
||||
it('uses explicit taskId for retry_rpa workspace actions', async () => {
|
||||
it('does not execute retry_rpa from a Chat menu', async () => {
|
||||
const ctx = createContext();
|
||||
const { handleShippingMenuAction } = createShippingMenuHandlers(ctx);
|
||||
|
||||
@@ -69,16 +54,8 @@ describe('useChatShippingMenuHandler', () => {
|
||||
{ taskId: 'sn-target-009' },
|
||||
);
|
||||
|
||||
expect(ctx.executeShippingDecision).toHaveBeenCalledWith(
|
||||
'retry_rpa',
|
||||
'重新获取库存',
|
||||
{ taskId: 'SN-TARGET-009' },
|
||||
);
|
||||
expect(ctx.executeShippingDecision).not.toHaveBeenCalledWith(
|
||||
'retry_rpa',
|
||||
'重新获取库存',
|
||||
{ taskId: 'SN-ACTIVE-001' },
|
||||
);
|
||||
expect(ctx.executeShippingDecision).not.toHaveBeenCalled();
|
||||
expect(ctx.refreshShippingActions).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('does not dispatch legacy generate_excel Chat Turn', async () => {
|
||||
@@ -109,8 +86,7 @@ describe('useChatShippingMenuHandler', () => {
|
||||
expect(ctx.refreshShippingActions).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('reads the displayed order version before freezing through Chat Turn', async () => {
|
||||
getWorkspaceShippingTask.mockResolvedValue({ order_data_version: 9 });
|
||||
it('does not dispatch a legacy freeze action through Chat Turn', async () => {
|
||||
const ctx = createContext();
|
||||
const { handleShippingMenuAction } = createShippingMenuHandlers(ctx);
|
||||
|
||||
@@ -120,10 +96,7 @@ describe('useChatShippingMenuHandler', () => {
|
||||
{ taskId: 'sn-freeze-901' },
|
||||
);
|
||||
|
||||
expect(ctx.startChatTurn).toHaveBeenCalledWith(expect.objectContaining({
|
||||
actionType: 'shipping.freeze_order',
|
||||
payload: { task_no: 'SN-FREEZE-901', expected_order_data_version: 9 },
|
||||
}));
|
||||
expect(ctx.startChatTurn).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('passes explicit taskId into inventory picker actions', async () => {
|
||||
|
||||
@@ -1,26 +1,19 @@
|
||||
/**
|
||||
* features/chat/shipping/useChatShippingMenuHandler.ts
|
||||
* 用途:分发聊天气泡动作按钮点击;业务动作统一走 Chat Turn SSE。
|
||||
* 依赖:shippingTurnActions、shipping.api(只读 task 详情)、shippingDownload、chat.types。
|
||||
* 逻辑:可映射为 action_type 的按钮走 startChatTurn;纯 UI(下载/选文件/表单)仍走本地行为。
|
||||
* 用途:分发聊天气泡的只读与导航辅助操作。
|
||||
* 依赖:shippingDownload、chat.types。
|
||||
* 逻辑:履约写只由正式 OT Gate 执行;历史聊天写动作仅刷新,不再创建 Chat Turn。
|
||||
*/
|
||||
import { getWorkspaceShippingTask } from '@/features/chat/api/shipping.api';
|
||||
import { SHIPPING_DECISION_ACTIONS } from '../constants/shipping';
|
||||
import { downloadWorkspaceShippingExcelFile } from './shippingDownload';
|
||||
import { buildShippingTurnRefs, resolveShippingChatTurn } from './shippingTurnActions';
|
||||
import type { StartChatTurnOptions } from '../types/chat-turn.types';
|
||||
import type { ChatMessage } from '../types/chat.types';
|
||||
import type { ShippingActionButton } from '../types/shipping.types';
|
||||
import type { ComputedRef, Ref } from 'vue';
|
||||
import type { Ref } from 'vue';
|
||||
|
||||
export interface ShippingMenuHandlerContext {
|
||||
isThinking: Ref<boolean>;
|
||||
currentAgentId: ComputedRef<number>;
|
||||
getActiveShippingTaskId: () => string;
|
||||
getActiveShippingBatchNo: () => string;
|
||||
messages: Ref<ChatMessage[]>;
|
||||
sendShippingMenuMessage: (message: string) => Promise<void>;
|
||||
openShippingInventoryPicker: (taskId?: string) => boolean;
|
||||
openShippingNoticePicker: (taskId?: string) => boolean;
|
||||
openShippingCustomerDialog: (taskId: string) => Promise<void>;
|
||||
executeShippingDecision: (
|
||||
@@ -30,7 +23,6 @@ export interface ShippingMenuHandlerContext {
|
||||
) => Promise<boolean>;
|
||||
executeShippingManualUpload: (taskId: string, displayText?: string) => Promise<boolean>;
|
||||
refreshShippingActions: () => Promise<void>;
|
||||
startChatTurn: (options: StartChatTurnOptions) => Promise<boolean>;
|
||||
msg: { warning: (text: string) => void; info: (text: string) => void };
|
||||
t: (key: string, ...args: unknown[]) => string;
|
||||
}
|
||||
@@ -43,78 +35,6 @@ export interface HandleShippingMenuActionOptions {
|
||||
* 创建发货通知动作菜单处理器。
|
||||
*/
|
||||
export function createShippingMenuHandlers(ctx: ShippingMenuHandlerContext) {
|
||||
const normalizeInventorySourceText = (value: string) =>
|
||||
String(value || '')
|
||||
.toUpperCase()
|
||||
.replace(/[^A-Z0-9]+/g, '');
|
||||
|
||||
const recentInventorySourceHint = () => {
|
||||
const parts: string[] = [];
|
||||
for (let i = ctx.messages.value.length - 1; i >= 0 && parts.length < 6; i -= 1) {
|
||||
const content = String(ctx.messages.value[i]?.content || '').trim();
|
||||
if (content) parts.push(content);
|
||||
}
|
||||
return parts.join('\n');
|
||||
};
|
||||
|
||||
const resolveInventorySourceCodeFromContext = async (taskId: string): Promise<string> => {
|
||||
const detail = await getWorkspaceShippingTask(taskId);
|
||||
const resolution = detail.inventory_source_resolution;
|
||||
const candidates = resolution && typeof resolution === 'object'
|
||||
? (resolution as { candidates?: unknown }).candidates
|
||||
: null;
|
||||
if (!Array.isArray(candidates) || candidates.length === 0) return '';
|
||||
if (candidates.length === 1) {
|
||||
const only = candidates[0];
|
||||
return only && typeof only === 'object'
|
||||
? String((only as { source_code?: unknown }).source_code || '').trim().toUpperCase()
|
||||
: '';
|
||||
}
|
||||
const hint = normalizeInventorySourceText(recentInventorySourceHint());
|
||||
if (!hint) return '';
|
||||
const matches = candidates.filter((item) => {
|
||||
if (!item || typeof item !== 'object') return false;
|
||||
const source = item as { source_code?: unknown; display_name?: unknown; warehouse_code?: unknown; program_name?: unknown };
|
||||
const values = [
|
||||
source.source_code,
|
||||
source.display_name,
|
||||
source.warehouse_code,
|
||||
source.program_name,
|
||||
].map((value) => normalizeInventorySourceText(String(value || ''))).filter(Boolean);
|
||||
return values.some((value) => hint.includes(value) || value.includes(hint));
|
||||
});
|
||||
if (matches.length !== 1) return '';
|
||||
return String((matches[0] as { source_code?: unknown }).source_code || '').trim().toUpperCase();
|
||||
};
|
||||
|
||||
const runShippingActionTurn = async (
|
||||
action: ShippingActionButton | { id?: string; message: string; label?: string },
|
||||
taskId: string,
|
||||
extra?: { sourceCode?: string; expectedOrderDataVersion?: number },
|
||||
) => {
|
||||
const actionId = String(action.id || '').trim();
|
||||
const turnSpec = resolveShippingChatTurn(actionId, taskId, extra);
|
||||
if (!turnSpec) return false;
|
||||
const displayBase = String(action.message || actionId || '操作').trim();
|
||||
const displayText = actionId === 'confirm_inventory_source'
|
||||
? ctx.t('chat.shippingNoticeUi.inventorySource.confirmWithTask', { taskId })
|
||||
: ctx.t('chat.shippingNoticeUi.inventorySource.actionWithTask', { message: displayBase, taskId });
|
||||
await ctx.startChatTurn({
|
||||
agentId: ctx.currentAgentId.value,
|
||||
inputType: 'action',
|
||||
displayText,
|
||||
actionType: turnSpec.actionType,
|
||||
payload: turnSpec.payload,
|
||||
refs: buildShippingTurnRefs(taskId, ctx.getActiveShippingBatchNo()),
|
||||
hooks: {
|
||||
onAssistantMessageFinished: async () => {
|
||||
void ctx.refreshShippingActions();
|
||||
},
|
||||
},
|
||||
});
|
||||
return true;
|
||||
};
|
||||
|
||||
const handleShippingMenuAction = async (
|
||||
action: ShippingActionButton | { id?: string; message: string },
|
||||
chatMsg?: ChatMessage & { shipping_actions_used?: boolean },
|
||||
@@ -152,105 +72,17 @@ export function createShippingMenuHandlers(ctx: ShippingMenuHandlerContext) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 旧匹配/Excel 动作仅保留历史文案兼容;业务执行必须由 Projection
|
||||
// 下发的正式 Gate Action 驱动,Chat 不得再创建 legacy Turn。
|
||||
if (action.id === 'match_inventory' || action.id === 'generate_excel') {
|
||||
await ctx.refreshShippingActions();
|
||||
ctx.msg.info(ctx.t('chat.shippingNoticeRefreshDone'));
|
||||
return;
|
||||
}
|
||||
|
||||
const chatTurnActionIds = new Set([
|
||||
'freeze_order',
|
||||
'generate_excel',
|
||||
'retry_upload',
|
||||
'match_inventory',
|
||||
'mark_manual_uploaded',
|
||||
'confirm_inventory_source',
|
||||
]);
|
||||
|
||||
if (action.id && chatTurnActionIds.has(action.id)) {
|
||||
if (chatMsg?.shipping_actions_used) return;
|
||||
if (chatMsg) chatMsg.shipping_actions_used = true;
|
||||
const taskId = resolveTaskId();
|
||||
if (!taskId) {
|
||||
ctx.msg.warning(ctx.t('chat.shippingNoticeMissingTaskId'));
|
||||
if (chatMsg) chatMsg.shipping_actions_used = false;
|
||||
return;
|
||||
}
|
||||
try {
|
||||
let sourceCode = '';
|
||||
let expectedOrderDataVersion: number | undefined;
|
||||
if (action.id === 'freeze_order') {
|
||||
const detail = await getWorkspaceShippingTask(taskId);
|
||||
const version = Number(detail.order_data_version);
|
||||
if (!Number.isInteger(version) || version < 1) {
|
||||
ctx.msg.warning(ctx.t('chat.shippingNoticeRefreshRequired'));
|
||||
if (chatMsg) chatMsg.shipping_actions_used = false;
|
||||
return;
|
||||
}
|
||||
expectedOrderDataVersion = version;
|
||||
}
|
||||
if (action.id === 'confirm_inventory_source') {
|
||||
sourceCode = String((action as { source_code?: unknown }).source_code || '').trim().toUpperCase();
|
||||
if (!sourceCode) {
|
||||
sourceCode = await resolveInventorySourceCodeFromContext(taskId);
|
||||
}
|
||||
if (!sourceCode) {
|
||||
ctx.msg.warning(ctx.t('chat.shippingNoticeUi.inventorySource.inputHint'));
|
||||
if (chatMsg) chatMsg.shipping_actions_used = false;
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (action.id === 'mark_manual_uploaded') {
|
||||
await ctx.executeShippingManualUpload(taskId, '我已在货代系统完成上传');
|
||||
return;
|
||||
}
|
||||
const label = String(('label' in action ? action.label : '') || sourceCode).trim();
|
||||
const displayMessage = action.id === 'confirm_inventory_source'
|
||||
? ctx.t('chat.shippingNoticeUi.inventorySource.confirmDisplay', { label: label || sourceCode })
|
||||
: action.message;
|
||||
await runShippingActionTurn(
|
||||
{ ...action, message: displayMessage },
|
||||
taskId,
|
||||
sourceCode ? { sourceCode } : { expectedOrderDataVersion },
|
||||
);
|
||||
} catch (e: unknown) {
|
||||
ctx.msg.warning(e instanceof Error ? e.message : '操作失败');
|
||||
if (chatMsg) chatMsg.shipping_actions_used = false;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (action.id === 'retry_resolve_inventory_source') {
|
||||
await ctx.refreshShippingActions();
|
||||
ctx.msg.info(ctx.t('chat.shippingNoticeUi.inventorySource.retryResolveDone'));
|
||||
return;
|
||||
}
|
||||
if (action.id === 'upload_inventory_file') {
|
||||
ctx.openShippingInventoryPicker(resolveTaskId());
|
||||
return;
|
||||
}
|
||||
if (action.id === 'replace_notice_file') {
|
||||
ctx.openShippingNoticePicker(resolveTaskId());
|
||||
return;
|
||||
}
|
||||
if (action.id === 'reparse_inventory') {
|
||||
if (chatMsg?.shipping_actions_used) return;
|
||||
const taskId = resolveTaskId();
|
||||
if (!taskId) {
|
||||
ctx.msg.warning(ctx.t('chat.shippingNoticeMissingTaskId'));
|
||||
return;
|
||||
}
|
||||
if (chatMsg) chatMsg.shipping_actions_used = true;
|
||||
const ok = await ctx.executeShippingDecision('reparse_inventory', action.message, { silent: true, taskId });
|
||||
if (ok) ctx.openShippingInventoryPicker(taskId);
|
||||
return;
|
||||
}
|
||||
if (action.id && SHIPPING_DECISION_ACTIONS.has(action.id)) {
|
||||
if (chatMsg?.shipping_actions_used) return;
|
||||
if (chatMsg) chatMsg.shipping_actions_used = true;
|
||||
await ctx.executeShippingDecision(action.id, action.message, { taskId: resolveTaskId() });
|
||||
if (action.id && [
|
||||
'freeze_order', 'match_inventory', 'rematch',
|
||||
'generate_excel', 'retry_upload', 'mark_manual_uploaded', 'reparse_inventory',
|
||||
'confirm', 'retry_rpa', 'reject', 'reparse',
|
||||
].includes(action.id)) {
|
||||
await ctx.refreshShippingActions();
|
||||
ctx.msg.info(ctx.t('chat.shippingNoticeUi.manualUpload.openTaskWorkbench'));
|
||||
return;
|
||||
}
|
||||
if (chatMsg?.shipping_actions_used) return;
|
||||
|
||||
@@ -4,15 +4,11 @@
|
||||
* 依赖:shipping.api(任务详情)、shippingIntents、shippingMenu、shippingDownload、chat.types。
|
||||
* 逻辑:已预处理 Intake 创建独立订单抽取 Run;co8 后切票不再调用 shipping_batches API,改提示用户使用 processing 工作台。
|
||||
*/
|
||||
import {
|
||||
getWorkspaceShippingTask,
|
||||
} from '@/features/chat/api/shipping.api';
|
||||
import { SHIPPING_DECISION_ACTIONS, SHIPPING_MENU_ACTION_SPECS } from '../constants/shipping';
|
||||
import { downloadWorkspaceShippingExcelFile } from './shippingDownload';
|
||||
import {
|
||||
isShippingDownloadExcelIntent,
|
||||
isShippingGenerateExcelIntent,
|
||||
isShippingInventoryUploadIntent,
|
||||
isShippingManualUploadIntent,
|
||||
parseShippingTaskSwitchIntent,
|
||||
} from './shippingIntents';
|
||||
@@ -56,7 +52,6 @@ export interface ShippingSendHandlerContext {
|
||||
loadHistory: () => Promise<void>;
|
||||
sendShippingMenuMessage: (message: string) => Promise<void>;
|
||||
startChatTurn: (options: StartChatTurnOptions) => Promise<boolean>;
|
||||
openShippingInventoryPicker: () => boolean;
|
||||
executeShippingDecision: (decision: string, displayText?: string) => Promise<boolean>;
|
||||
executeShippingManualUpload: (taskId: string, displayText?: string) => Promise<boolean>;
|
||||
handleShippingMenuAction: (action: ShippingActionButton | { id?: string; message: string; label?: string; source_code?: string }) => Promise<void>;
|
||||
@@ -95,55 +90,6 @@ export interface ShippingSendHandlerContext {
|
||||
* @returns 发送前文本与附件自动流程处理函数;返回 true 表示已消费本次发送
|
||||
*/
|
||||
export function createShippingSendHandlers(ctx: ShippingSendHandlerContext) {
|
||||
const normalizeInventorySourceText = (value: string) =>
|
||||
String(value || '')
|
||||
.toUpperCase()
|
||||
.replace(/[^A-Z0-9]+/g, '');
|
||||
|
||||
const tryConfirmInventorySourceFromText = async (content: string): Promise<boolean> => {
|
||||
const taskId = ctx.getActiveShippingTaskId();
|
||||
if (!taskId) return false;
|
||||
const normalized = normalizeInventorySourceText(content);
|
||||
if (!normalized) return false;
|
||||
try {
|
||||
const detail = await getWorkspaceShippingTask(taskId);
|
||||
if (detail.pending_human_reason !== 'inventory_source_unresolved') return false;
|
||||
const resolution = detail.inventory_source_resolution;
|
||||
const candidates = resolution && typeof resolution === 'object'
|
||||
? (resolution as { candidates?: unknown }).candidates
|
||||
: null;
|
||||
if (!Array.isArray(candidates) || candidates.length === 0) return false;
|
||||
const hit = candidates.find((item) => {
|
||||
if (!item || typeof item !== 'object') return false;
|
||||
const source = item as { source_code?: unknown; display_name?: unknown; warehouse_code?: unknown; program_name?: unknown };
|
||||
const values = [
|
||||
source.source_code,
|
||||
source.display_name,
|
||||
source.warehouse_code,
|
||||
source.program_name,
|
||||
].map((value) => normalizeInventorySourceText(String(value || ''))).filter(Boolean);
|
||||
return values.some((value) => normalized === value || normalized.includes(value) || value.includes(normalized));
|
||||
}) as { source_code?: unknown; display_name?: unknown } | undefined;
|
||||
const sourceCode = String(hit?.source_code || '').trim().toUpperCase();
|
||||
if (!sourceCode) return false;
|
||||
if (typeof content !== 'string') return false;
|
||||
ctx.input.value = '';
|
||||
ctx.attachments.value = [];
|
||||
const label = String(hit?.display_name || sourceCode).trim();
|
||||
await ctx.handleShippingMenuAction({
|
||||
id: 'confirm_inventory_source',
|
||||
message: ctx.t('chat.shippingNoticeUi.inventorySource.confirmDisplay', { label }),
|
||||
label,
|
||||
source_code: sourceCode,
|
||||
});
|
||||
return true;
|
||||
} catch (e: unknown) {
|
||||
const errorMessage = e instanceof Error ? e.message : ctx.t('chat.shippingNoticeUi.inventorySource.confirmFailed');
|
||||
ctx.msg.warning(errorMessage);
|
||||
return true;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 拦截切票/切任务意图(co8 已下线批次 API)。
|
||||
*
|
||||
@@ -280,11 +226,6 @@ export function createShippingSendHandlers(ctx: ShippingSendHandlerContext) {
|
||||
ctx.attachments.value = [];
|
||||
return true;
|
||||
}
|
||||
if (await tryConfirmInventorySourceFromText(content)) {
|
||||
if (typeof textOrEvent !== 'string') ctx.input.value = '';
|
||||
ctx.attachments.value = [];
|
||||
return true;
|
||||
}
|
||||
const assistantCtx = ctx.lastAssistantMessageContent();
|
||||
const numericText = content.trim();
|
||||
if (/^[1-91-9](?:[\.\、\)::]?)$/.test(numericText)) {
|
||||
@@ -303,9 +244,7 @@ export function createShippingSendHandlers(ctx: ShippingSendHandlerContext) {
|
||||
const menuChoice = resolveShippingNumericChoice(content, assistantCtx);
|
||||
if (menuChoice) {
|
||||
if (typeof textOrEvent !== 'string') ctx.input.value = '';
|
||||
if (menuChoice === 'upload') {
|
||||
if (ctx.openShippingInventoryPicker()) return true;
|
||||
} else if (SHIPPING_DECISION_ACTIONS.has(menuChoice)) {
|
||||
if (SHIPPING_DECISION_ACTIONS.has(menuChoice)) {
|
||||
const spec = SHIPPING_MENU_ACTION_SPECS[menuChoice];
|
||||
await ctx.executeShippingDecision(menuChoice, spec?.label || spec?.message || menuChoice);
|
||||
return true;
|
||||
@@ -320,32 +259,11 @@ export function createShippingSendHandlers(ctx: ShippingSendHandlerContext) {
|
||||
if (await ctx.executeShippingDecision(shippingDecision, content.trim())) return true;
|
||||
}
|
||||
if (isShippingManualUploadIntent(content)) {
|
||||
const taskId = ctx.getActiveShippingTaskId();
|
||||
if (!taskId) {
|
||||
ctx.msg.warning('未找到任务编号,请先完成前面的步骤');
|
||||
return true;
|
||||
}
|
||||
ctx.resolvedShippingTaskId.value = taskId;
|
||||
if (typeof textOrEvent !== 'string') ctx.input.value = '';
|
||||
ctx.attachments.value = [];
|
||||
await ctx.executeShippingManualUpload(taskId, content.trim());
|
||||
return true;
|
||||
}
|
||||
if (isShippingInventoryUploadIntent(content, assistantCtx)) {
|
||||
if (typeof textOrEvent !== 'string') ctx.input.value = '';
|
||||
if (ctx.openShippingInventoryPicker()) return true;
|
||||
ctx.msg.info(ctx.t('chat.shippingNoticeUi.manualUpload.openTaskWorkbench'));
|
||||
return true;
|
||||
}
|
||||
if (isShippingGenerateExcelIntent(content)) {
|
||||
const taskId = ctx.getActiveShippingTaskId();
|
||||
if (!taskId) {
|
||||
ctx.msg.warning('未找到任务编号,请先完成解析与库存匹配');
|
||||
return true;
|
||||
}
|
||||
ctx.resolvedShippingTaskId.value = taskId;
|
||||
if (typeof textOrEvent !== 'string') ctx.input.value = '';
|
||||
ctx.attachments.value = [];
|
||||
await ctx.handleShippingMenuAction({ id: 'generate_excel', message: content.trim() });
|
||||
ctx.msg.info(ctx.t('chat.shippingNoticeUi.manualUpload.openTaskWorkbench'));
|
||||
return true;
|
||||
}
|
||||
if (isShippingDownloadExcelIntent(content)) {
|
||||
|
||||
@@ -23,7 +23,6 @@ import { normalizeShippingProcessingProjection } from './normalizeShippingProces
|
||||
const DEFAULT_POLL_MS = 3000;
|
||||
const TERMINAL_STATUSES = new Set([
|
||||
'completed',
|
||||
'failed',
|
||||
'cancelled',
|
||||
]);
|
||||
|
||||
|
||||
@@ -87,11 +87,11 @@ export type ShippingProcessingActionIntent =
|
||||
| 'confirm_customer'
|
||||
| 'resolve_field_conflicts'
|
||||
| 'adjudicate_duplicate'
|
||||
| 'open_inventory_source_review'
|
||||
| 'open_inventory_match_review'
|
||||
| 'open_shortage_review'
|
||||
| 'upload_inventory_file'
|
||||
| 'retry'
|
||||
| 'reparse_batch'
|
||||
| 'refresh'
|
||||
| 'regenerate_excel'
|
||||
| 'download_excel'
|
||||
@@ -341,7 +341,7 @@ export interface ShippingProcessingProjection {
|
||||
assetStatus?: string | null;
|
||||
};
|
||||
childOrderTasks: ShippingOrderTaskSummary[];
|
||||
// ============== [T8 用户态 Projection 7 字段] ==============
|
||||
// ============== [T8 用户态 Projection 6 字段] ==============
|
||||
// 后端 apply_user_projection_fields 下发;旧客户端不识别会直接忽略(安全);
|
||||
// 新前端优先用本字段停止本地推导。
|
||||
/** 用户态 status(6 枚举:running / waiting_human / retryable / failed / completed / cancelled)。 */
|
||||
@@ -352,8 +352,6 @@ export interface ShippingProcessingProjection {
|
||||
userCurrentGateCode?: string | null;
|
||||
/** 阻断原因:{code, i18nKey, details};status=waiting_human / retryable / failed 时非空。 */
|
||||
blockingReason?: ShippingProcessingBlockingReason | null;
|
||||
/** 技术失败是否可重试;业务阻断(waiting_human)通常 false。 */
|
||||
retryable?: boolean;
|
||||
/** 唯一主入口按钮建议:{code, i18nKey, parameters};前端只渲染不新建动作码。 */
|
||||
primaryAction?: ShippingProcessingPrimaryAction | null;
|
||||
/**
|
||||
@@ -387,7 +385,7 @@ export interface ShippingProcessingProjection {
|
||||
|
||||
/**
|
||||
* 题4A & 7A:逐源 inventory 准备状态(ShippingProcessingProjection.inventoryPreparation)。
|
||||
* 按实际冻结源 required_sources 为基准分类,failed/exhausted 拆分暴露。
|
||||
* 按实际冻结源 required_sources 为基准分类并暴露当前成功、等待和失败事实。
|
||||
*/
|
||||
export interface ShippingInventoryPreparationSummary {
|
||||
/** 实际任务级冻结源(task.task_frozen_inventory_source_codes),顺序以冻结记录为准。 */
|
||||
@@ -396,17 +394,15 @@ export interface ShippingInventoryPreparationSummary {
|
||||
preparedSources: string[];
|
||||
/** RPA 正在跑或入队中(queued / running);active_attempt_count > 0 的对应源集合。 */
|
||||
pendingSources: string[];
|
||||
/** 最近一次失败状态(attempt.status == failed)但未耗尽自动次数的源。 */
|
||||
/** 最近一次失败状态(attempt.status == failed)的源。 */
|
||||
failedSources: string[];
|
||||
/** 题7A:自动重试 max_attempts 已耗尽但允许人工 user_retry 继续的源;独立于 failed,便于 UI 提示。 */
|
||||
exhaustedSources: string[];
|
||||
/** 全表当前 queued+running Attempt 总数(>= pendingSources.length,存在 Gate 活动 Attempt 时会更高)。 */
|
||||
activeAttemptCount: number;
|
||||
/** 题2B:Process Gate 是否有 queued/running 状态的 inventory 批次;作为全局 running 额外保护。 */
|
||||
gateAttemptActive?: boolean;
|
||||
/**
|
||||
* 按冻结源逐源最近 Attempt 摘要(source_code → 结构化记录)。
|
||||
* 用于 UI tooltip/详情;按钮禁用不直接读本字典,读上面的 required/prepared/pending/failed/exhausted 集合。
|
||||
* 用于 UI tooltip/详情;按钮禁用不直接读本字典,读上面的 required/prepared/pending/failed 集合。
|
||||
*/
|
||||
latestAttempts?: Record<string, ShippingInventoryPerSourceAttempt>;
|
||||
}
|
||||
@@ -418,9 +414,9 @@ export interface ShippingInventoryPreparationSummary {
|
||||
export interface ShippingInventoryPerSourceAttempt {
|
||||
sourceCode: string;
|
||||
attemptNo: number;
|
||||
/** queued | running | consumed | failed | exhausted | skipped */
|
||||
/** queued | running | consumed | failed | skipped */
|
||||
status: string;
|
||||
/** 失败/耗尽:人工可继续;running/queued:false */
|
||||
/** 失败:用户可选择明确恢复动作;running/queued:false */
|
||||
manualRetryable?: boolean;
|
||||
/** attempt.error_message 或 业务错误摘要,供 tooltip。 */
|
||||
message?: string | null;
|
||||
@@ -606,7 +602,6 @@ export interface ConversationProcessingUserTask {
|
||||
userStage?: ShippingUserProcessingStage | null;
|
||||
userCurrentGateCode?: string | null;
|
||||
blockingReason?: ShippingProcessingBlockingReason | null;
|
||||
retryable?: boolean;
|
||||
primaryAction?: ShippingProcessingPrimaryAction | null;
|
||||
facts?: ShippingProcessingFacts;
|
||||
/** EML Intake 的用户可见全局分组;前端只消费,不从附件状态自行推导。 */
|
||||
@@ -763,14 +758,14 @@ export type InventorySourceStatus =
|
||||
| 'unresolved'
|
||||
| 'ambiguous'
|
||||
| 'resolved'
|
||||
| 'user_confirmed'
|
||||
| 'candidates_frozen'
|
||||
| 'invalid'
|
||||
| 'conflicted';
|
||||
|
||||
export type InventorySourceMethod =
|
||||
| 'rule_exact'
|
||||
| 'rule_combined'
|
||||
| 'user_confirmed'
|
||||
| 'rule_evaluation_freeze'
|
||||
| 'legacy_migrated';
|
||||
|
||||
export interface ShippingInventorySourceCandidate {
|
||||
@@ -786,6 +781,7 @@ export interface ShippingInventorySourceResolution {
|
||||
status?: InventorySourceStatus | null;
|
||||
method?: InventorySourceMethod | null;
|
||||
reason?: string | null;
|
||||
release_field_values?: Record<string, string>;
|
||||
candidates?: ShippingInventorySourceCandidate[];
|
||||
destination_candidates?: string[];
|
||||
evidence?: Record<string, unknown>[];
|
||||
@@ -869,8 +865,6 @@ export interface ShippingTaskSummary {
|
||||
inventory_source_method?: InventorySourceMethod | null;
|
||||
inventory_source_config_version?: string | null;
|
||||
inventory_routing_fingerprint?: string | null;
|
||||
inventory_source_confirmed_at?: string | null;
|
||||
inventory_source_confirmed_by?: number | null;
|
||||
inventory_snapshot?: ShippingInventorySnapshot | null;
|
||||
created_at?: string | null;
|
||||
updated_at?: string | null;
|
||||
@@ -1042,16 +1036,12 @@ export type ShippingProcessGateActionCode =
|
||||
| 'adjudicate_duplicate'
|
||||
| 'resolve_field_conflicts'
|
||||
| 'retry_with_latest_rules'
|
||||
| 'open_inventory_source_review'
|
||||
| 'adopt_rule_suggestion'
|
||||
| 'keep_manual_inventory_decision'
|
||||
| 'recheck_freeze_readiness'
|
||||
| 'retry_task_creation'
|
||||
| 'retry_inventory_preparation'
|
||||
| 'poll_inventory_preparation'
|
||||
| 'upload_inventory_file'
|
||||
| 'retry_inventory_field_mapping'
|
||||
| 'confirm_inventory_field_mapping'
|
||||
| 'retry_inventory_matching'
|
||||
| 'retry_inventory_from_preparation'
|
||||
| 'retry_inventory_from_field_mapping'
|
||||
@@ -1103,7 +1093,10 @@ export interface ShippingProcessGateActionPresentation {
|
||||
code: string;
|
||||
label_key: string;
|
||||
kind: 'current_gate' | 'recovery' | 'view' | string;
|
||||
dispatch: 'navigation' | 'mutation' | 'refresh' | string;
|
||||
dispatch: 'navigation' | 'mutation' | 'refresh' | 'view' | 'dialog' | string;
|
||||
ui_handler?: string | null;
|
||||
target_surface?: ShippingActionTargetSurface | null;
|
||||
target_anchor?: ShippingActionTargetAnchor | null;
|
||||
}
|
||||
|
||||
/** 服务端 RecoveryPlan 只读目标;target_gate 由后端合同推导,客户端不得提交覆盖。 */
|
||||
@@ -1541,13 +1534,33 @@ export interface ShippingTaskUiState {
|
||||
updated_at?: string | null;
|
||||
}
|
||||
|
||||
/** 后端 Gate / Artifact 声明的生命周期工作面;未知值不得由前端猜测归属。 */
|
||||
export type ShippingActionTargetSurface =
|
||||
| 'intake_parse'
|
||||
| 'order_review'
|
||||
| 'fulfillment_prep'
|
||||
| 'upload_complete'
|
||||
| string;
|
||||
|
||||
/** 后端 Gate / Artifact 声明的页面内动作槽位。 */
|
||||
export type ShippingActionTargetAnchor =
|
||||
| 'excel_artifact'
|
||||
| 'freight_upload'
|
||||
| 'manual_upload'
|
||||
| string;
|
||||
|
||||
export interface ShippingUnifiedAction {
|
||||
code: string;
|
||||
label?: string | null;
|
||||
kind: ShippingActionKind | string;
|
||||
/** 后端 Gate 裁决的执行分派,客户端只负责调用对应宿主能力。 */
|
||||
dispatch: 'navigation' | 'mutation' | 'refresh' | 'view' | 'dialog' | string;
|
||||
/** 后端声明的既有页面宿主能力;不用于动作展示或授权。 */
|
||||
ui_handler?: string | null;
|
||||
enabled: boolean;
|
||||
requires_confirmation: boolean;
|
||||
target_surface?: string | null;
|
||||
target_surface?: ShippingActionTargetSurface | null;
|
||||
target_anchor?: ShippingActionTargetAnchor | null;
|
||||
disabled_reason?: string | null;
|
||||
expected_gate_version?: number | null;
|
||||
}
|
||||
@@ -2163,6 +2176,8 @@ export interface ReviewWorkbenchAuditContext {
|
||||
document_id?: number | null;
|
||||
field_id?: string | null;
|
||||
line_key?: string | null;
|
||||
/** header | line | line_unassigned | unscoped;相同 field_code 在订单头和明细行是不同业务字段。 */
|
||||
scope?: 'header' | 'line' | 'line_unassigned' | 'unscoped' | string | null;
|
||||
page_no?: number | null;
|
||||
evidence_ref?: string | null;
|
||||
draft_version?: number | null;
|
||||
@@ -2223,6 +2238,10 @@ export interface ShippingOrderReviewDraftLine {
|
||||
|
||||
export interface ShippingOrderReviewCaseSummary {
|
||||
case_no: string;
|
||||
/** 文件级复核主线;主队列以此而非 Run/Case 历史去重。 */
|
||||
stream_id?: number | null;
|
||||
revision_no?: number | null;
|
||||
stream_state?: 'active' | 'reparsing' | 'confirmed' | 'closed' | 'conflict' | string | null;
|
||||
document_id: number;
|
||||
file_name?: string | null;
|
||||
status: string;
|
||||
@@ -2269,10 +2288,25 @@ export interface ShippingOrderReviewIntakeParseContext {
|
||||
email: {
|
||||
document_id: number;
|
||||
filename: string;
|
||||
/** 安全 HTML 命中快照时为 safe_html;其它情况降级为 text。 */
|
||||
render_kind: 'safe_html' | 'text';
|
||||
/** 后端签发的短时单用途 HTML 预览地址;只能放进 sandbox iframe。 */
|
||||
preview_url?: string;
|
||||
text: string;
|
||||
} | null;
|
||||
}
|
||||
|
||||
/** 当前字段的同 Intake EML 证据预览;HTML 必须在无权限 sandbox iframe 中渲染。 */
|
||||
export interface ShippingOrderReviewEmailEvidencePreview {
|
||||
document_id: number;
|
||||
document_type: 'email_body';
|
||||
filename: string;
|
||||
text: string;
|
||||
render_kind: 'safe_html' | 'text';
|
||||
preview_url?: string;
|
||||
highlighted?: boolean;
|
||||
}
|
||||
|
||||
/** 库存路由规则版本摘要(行级投影 / 规则建议内复用)。 */
|
||||
export interface ShippingOrderReviewInventoryRuleVersion {
|
||||
rule_id?: number;
|
||||
@@ -2423,12 +2457,6 @@ export interface ShippingOrderReviewBuildEligibility {
|
||||
auto_create_failure_reasons?: Array<{ code: string; message: string }>;
|
||||
}
|
||||
|
||||
export interface ShippingOrderReviewInventoryCandidatesWrite {
|
||||
expected_draft_version: number;
|
||||
source_codes: string[];
|
||||
reason: string;
|
||||
}
|
||||
|
||||
/** 整单或行级重新匹配库存路由写请求。 */
|
||||
export interface ShippingOrderReviewInventoryRoutingRerouteWrite {
|
||||
expected_draft_version: number;
|
||||
@@ -2436,13 +2464,6 @@ export interface ShippingOrderReviewInventoryRoutingRerouteWrite {
|
||||
line_key?: string;
|
||||
}
|
||||
|
||||
/** 采纳规则建议 / 保留人工路由写请求。 */
|
||||
export interface ShippingOrderReviewInventoryRoutingDecisionWrite {
|
||||
expected_draft_version: number;
|
||||
idempotency_key?: string;
|
||||
reason?: string;
|
||||
}
|
||||
|
||||
/** 建单前客户识别投影(复核工作台固定客户区)。 */
|
||||
export interface ShippingOrderReviewCustomerResolution {
|
||||
resolved: boolean;
|
||||
@@ -2490,6 +2511,8 @@ export interface ShippingOrderReviewFieldConflict {
|
||||
field_code: string;
|
||||
line_index?: number | null;
|
||||
line_key?: string | null;
|
||||
/** header | line | line_unassigned | unscoped;相同 field_code 在订单头和明细行是不同业务字段。 */
|
||||
scope?: 'header' | 'line' | 'line_unassigned' | 'unscoped' | string | null;
|
||||
severity?: string;
|
||||
reason: string;
|
||||
options: ShippingOrderReviewFieldConflictOption[];
|
||||
@@ -2520,6 +2543,8 @@ export interface ShippingOrderReviewCase {
|
||||
customer_resolution?: ShippingOrderReviewCustomerResolution | null;
|
||||
/** 建单前字段冲突;有开放项时工作台侧栏展示裁决区 */
|
||||
field_conflicts?: ShippingOrderReviewFieldConflict[] | null;
|
||||
/** 关键字段证据缺失;与多来源取值冲突分区展示,不提供重复填值入口。 */
|
||||
evidence_issues?: ShippingOrderReviewFieldConflict[] | null;
|
||||
/** 建单前重复检测;needs_adjudication 时侧栏展示裁决区 */
|
||||
duplicate?: ShippingOrderReviewDuplicate | null;
|
||||
/** 建单前文档模板匹配只读摘要 */
|
||||
@@ -2607,11 +2632,6 @@ export interface ShippingOrderReviewCase {
|
||||
build_eligibility?: ShippingOrderReviewBuildEligibility;
|
||||
} | null;
|
||||
available_actions: string[];
|
||||
/** 对话级可执行动作(与对话处理 GET 同源);仅 retryable 对象计入。 */
|
||||
conversation_allowed_actions?: Array<{
|
||||
code: string;
|
||||
eligible_count: number;
|
||||
}>;
|
||||
/** 正式任务 Schema 放行可写字段 field_id;confirmed + edit_formal_task 时由后端投影。 */
|
||||
formal_editable_field_ids?: string[];
|
||||
/** 关联 Notice 的 order_data_version;formal patch 乐观锁。 */
|
||||
@@ -3017,6 +3037,7 @@ export interface ShippingOrderReviewLineFulfillmentDecision {
|
||||
line_status?: string;
|
||||
is_active?: boolean;
|
||||
reason?: string | null;
|
||||
release_field_values?: Record<string, string>;
|
||||
required_qty?: string | null;
|
||||
available_qty?: string | null;
|
||||
reservation_id?: string | null;
|
||||
@@ -3033,7 +3054,8 @@ export type ShippingOrderReviewLineFulfillmentDecisionCode =
|
||||
| 'close_unfulfillable'
|
||||
| 'reopen'
|
||||
| 'use_new_inventory_file'
|
||||
| 'change_inventory_source';
|
||||
| 'change_inventory_source'
|
||||
| 'release_inventory_shortage';
|
||||
|
||||
/** 行级履约与库存缺口投影行(含 OT 匹配事实与 allowed_actions)。 */
|
||||
export interface ShippingOrderReviewLineFulfillmentLine {
|
||||
@@ -3079,6 +3101,18 @@ export interface ShippingOrderReviewLineFulfillmentLine {
|
||||
inventory_allowed_actions?: string[];
|
||||
line_allowed_actions?: string[];
|
||||
auto_fulfill_error_message?: string | null;
|
||||
/** 短缺放行前必须人工确认的模板实际消费字段(含 Header/Line 库存字段与系统事实)。 */
|
||||
release_required_fields?: Array<{ field_id: string; display_name: string }>;
|
||||
/** 发货模板实际消费字段;唯一受控快照或任务事实只读,其他项要求人工补录。 */
|
||||
release_template_fields?: Array<{
|
||||
field_id: string;
|
||||
display_name: string;
|
||||
value?: string | null;
|
||||
value_source?: 'inventory_snapshot' | 'manual_required' | string;
|
||||
requires_manual?: boolean;
|
||||
}>;
|
||||
/** 字段无法受控解析时的稳定错误码;UI 必须隐藏放行入口。 */
|
||||
release_field_resolution_error?: string | null;
|
||||
decision?: ShippingOrderReviewLineFulfillmentDecision | null;
|
||||
block_reason?: string | null;
|
||||
}
|
||||
|
||||
@@ -9,7 +9,7 @@ import type { ShippingFieldAdjudication, ShippingOrderCustomerMatch } from './sh
|
||||
|
||||
export type ShippingActionVariant = 'primary' | 'secondary' | 'danger';
|
||||
|
||||
export type ShippingMenuAction = 'upload' | 'retry_rpa' | 'confirm' | 'reparse' | 'reject';
|
||||
export type ShippingMenuAction = 'retry_rpa' | 'confirm' | 'reparse' | 'reject';
|
||||
|
||||
export type ChatUploadFileType = 'image' | 'document' | 'audio' | 'video' | 'custom';
|
||||
|
||||
|
||||
@@ -17,16 +17,24 @@ import {
|
||||
auditWorkspaceShippingOrderReviewEligibilityDetails,
|
||||
auditWorkspaceShippingOrderReviewVersionHistory,
|
||||
getWorkspaceShippingTask,
|
||||
decideWorkspaceShippingOrderReviewLineFulfillment,
|
||||
retryWorkspaceShippingOrderStpAutoCreate,
|
||||
retryWorkspaceShippingTask,
|
||||
retryWorkspaceShippingTaskLine,
|
||||
} from '@/features/chat/api/shipping.api';
|
||||
|
||||
const { downloadWorkspaceShippingInventoryFileMock } = vi.hoisted(() => ({
|
||||
downloadWorkspaceShippingInventoryFileMock: vi.fn().mockResolvedValue(undefined),
|
||||
const { downloadWorkspaceShippingLineInventoryFileMock } = vi.hoisted(() => ({
|
||||
downloadWorkspaceShippingLineInventoryFileMock: vi.fn().mockResolvedValue(undefined),
|
||||
}));
|
||||
const { downloadWorkspaceShippingExcelFileMock } = vi.hoisted(() => ({
|
||||
downloadWorkspaceShippingExcelFileMock: vi.fn().mockResolvedValue(undefined),
|
||||
}));
|
||||
|
||||
vi.mock('@/features/chat/shipping/shippingDownload', () => ({
|
||||
downloadWorkspaceShippingInventoryFile: downloadWorkspaceShippingInventoryFileMock,
|
||||
downloadWorkspaceShippingLineInventoryFile: downloadWorkspaceShippingLineInventoryFileMock,
|
||||
}));
|
||||
vi.mock('@/features/workspace/api/shipping-tasks.api', () => ({
|
||||
downloadWorkspaceShippingExcelFile: downloadWorkspaceShippingExcelFileMock,
|
||||
}));
|
||||
|
||||
const focusSuggestionField = vi.fn();
|
||||
@@ -38,6 +46,12 @@ const confirmMock = vi.fn();
|
||||
const reloadLatestDraftMock = vi.fn().mockResolvedValue(undefined);
|
||||
const refreshShippingProcessingMock = vi.fn().mockResolvedValue(undefined);
|
||||
const patchLineMock = vi.fn().mockResolvedValue(undefined);
|
||||
const { submitProcessGatePrimaryActionMock } = vi.hoisted(() => ({
|
||||
submitProcessGatePrimaryActionMock: vi.fn().mockResolvedValue({ outcome: 'submitted' }),
|
||||
}));
|
||||
const { postFormalGateActionMock } = vi.hoisted(() => ({
|
||||
postFormalGateActionMock: vi.fn().mockResolvedValue({}),
|
||||
}));
|
||||
|
||||
const messageMocks = vi.hoisted(() => ({
|
||||
info: vi.fn(),
|
||||
@@ -94,9 +108,13 @@ const workItem = ref<Record<string, any> | null>(null);
|
||||
const reviewProgressContext = ref<Record<string, any> | null>(null);
|
||||
/** 与 activeCase 同源共享,供断言 Progress 优先阶段源。 */
|
||||
const shippingProcessingProjection = ref<Record<string, any> | null>(null);
|
||||
/** 正式任务投影的请求中状态;用于覆盖 Case 先到、Projection 后到的过渡窗口。 */
|
||||
const shippingProcessingLoading = ref(false);
|
||||
const intakeParseContext = ref<Record<string, any> | null>(null);
|
||||
|
||||
const activeCase = ref({
|
||||
/** 每个用例必须从独立的 Case 图快照开始,避免嵌套 schema/draft 被浅拷贝污染。 */
|
||||
function createActiveCaseFixture() {
|
||||
return {
|
||||
case_no: 'CASE-1',
|
||||
document_id: 1,
|
||||
status: 'draft',
|
||||
@@ -140,7 +158,10 @@ const activeCase = ref({
|
||||
process_gate: null,
|
||||
profile_match: { available: false, visibility: 'admin_only', candidates: [] },
|
||||
automation: { status: 'idle', can_auto_create: false, can_build: true },
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
const activeCase = ref<Record<string, any>>(createActiveCaseFixture());
|
||||
|
||||
vi.mock('@/features/chat/api/shipping.api', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('@/features/chat/api/shipping.api')>();
|
||||
@@ -149,6 +170,8 @@ vi.mock('@/features/chat/api/shipping.api', async (importOriginal) => {
|
||||
auditWorkspaceShippingOrderReviewVersionHistory: vi.fn().mockResolvedValue({ audited: true, case_no: 'CASE-1' }),
|
||||
auditWorkspaceShippingOrderReviewEligibilityDetails: vi.fn().mockResolvedValue({ audited: true, case_no: 'CASE-1' }),
|
||||
retryWorkspaceShippingTask: vi.fn().mockResolvedValue({ status: 'ok' }),
|
||||
retryWorkspaceShippingTaskLine: vi.fn().mockResolvedValue({ status: 'ok' }),
|
||||
decideWorkspaceShippingOrderReviewLineFulfillment: vi.fn().mockResolvedValue({ status: 'ok' }),
|
||||
retryWorkspaceShippingOrderStpAutoCreate: vi.fn().mockResolvedValue({
|
||||
status: 'queued',
|
||||
job_id: 901,
|
||||
@@ -254,7 +277,6 @@ function createReviewComposableMock() {
|
||||
markNonOrder: vi.fn(),
|
||||
markQualityIssue: vi.fn(),
|
||||
reparseDocument: vi.fn(),
|
||||
uploadReplacement: vi.fn(),
|
||||
focusSuggestionField,
|
||||
setEvidenceDrawerFocus: vi.fn(),
|
||||
clearEvidenceDrawerFocus: vi.fn(),
|
||||
@@ -268,19 +290,9 @@ function createReviewComposableMock() {
|
||||
showWorkflowProgress: computed(() => false),
|
||||
workflowProgressPolling: computed(() => false),
|
||||
shippingProcessingProjection,
|
||||
shippingProcessingLoading: ref(false),
|
||||
shippingProcessingLoading,
|
||||
shippingProcessingError: ref(null),
|
||||
refreshShippingProcessing: refreshShippingProcessingMock,
|
||||
reparseProgressActive: computed(() => false),
|
||||
reparseProgressPolling: computed(() => false),
|
||||
reparseProgressRefreshFailed: computed(() => false),
|
||||
reparseProgressStage: computed(() => 'submitted'),
|
||||
reparseLastStableStage: computed(() => 'submitted'),
|
||||
reparseRunStatus: computed(() => 'queued'),
|
||||
reparseLastActivityAt: computed(() => null),
|
||||
reparseLastRefreshedAt: computed(() => null),
|
||||
reparseStalePolls: computed(() => 0),
|
||||
refreshReparseProgress: vi.fn(),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -290,6 +302,17 @@ vi.mock('@/shared/composables/useMessage', () => ({
|
||||
useMessage: () => messageMocks,
|
||||
}));
|
||||
|
||||
vi.mock('@/features/shipping-process-gates/composables/useShippingProcessGateRecovery', () => ({
|
||||
useShippingProcessGateRecovery: () => ({
|
||||
busy: ref(false),
|
||||
submitPrimaryAction: submitProcessGatePrimaryActionMock,
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock('@/features/shipping-process-gates/api/process-gates.api', () => ({
|
||||
postWorkspaceProcessGateAction: (...args: unknown[]) => postFormalGateActionMock(...args),
|
||||
}));
|
||||
|
||||
vi.mock('../components/shipping-review/ReviewDocumentPreview.vue', () => ({
|
||||
default: {
|
||||
name: 'ReviewDocumentPreview',
|
||||
@@ -422,7 +445,6 @@ async function mountView(query: Record<string, string> = {}) {
|
||||
markNonOrder: '非订单',
|
||||
markQualityIssue: '质量异常',
|
||||
reparse: '重新识别',
|
||||
uploadReplacement: '替换 PDF',
|
||||
saveNow: '保存并校验',
|
||||
saveOrderAndValidate: '保存订单并校验',
|
||||
confirmCreate: '确认并建单',
|
||||
@@ -491,25 +513,6 @@ async function mountView(query: Record<string, string> = {}) {
|
||||
saveFailed: '失败',
|
||||
versionConflict: { badge: '冲突' },
|
||||
statusBanner: { unknown: '未知' },
|
||||
reparseFailedVersion: {
|
||||
notice: 'V{failedVersion} 重新识别失败,失败阶段:{stage}。当前展示并可继续复核:V{displayedVersion}。',
|
||||
unknownStage: '未知阶段',
|
||||
stages: { layout_parsing: '解析 PDF 页面与表格' },
|
||||
},
|
||||
reparseProgress: {
|
||||
title: '重识别',
|
||||
subtitle: '',
|
||||
polling: '',
|
||||
refreshFailed: '',
|
||||
failed: '',
|
||||
retry: '',
|
||||
stages: {
|
||||
submitted: '1',
|
||||
layout_parsing: '2',
|
||||
extracting: '3',
|
||||
draft_ready: '4',
|
||||
},
|
||||
},
|
||||
autoProgress: {
|
||||
status: { unknown: '', needs_retry: '待重试', needs_human: '需要人工处理' },
|
||||
result: '{status}',
|
||||
@@ -592,6 +595,9 @@ async function mountView(query: Record<string, string> = {}) {
|
||||
frozenOrder: '冻结订单',
|
||||
inventorySource: '库存源',
|
||||
downloadInventory: '下载库存文件',
|
||||
retryInventory: '重新获取库存',
|
||||
releaseShortage: '库存缺口放行',
|
||||
shortage: '库存不足',
|
||||
pending: '库存匹配或通知文件尚未生成。',
|
||||
},
|
||||
},
|
||||
@@ -658,26 +664,10 @@ async function mountView(query: Record<string, string> = {}) {
|
||||
|
||||
/** 将共享 Case fixture 恢复为可编辑草稿,避免跨用例污染确认恢复态。 */
|
||||
function resetActiveCaseFixture() {
|
||||
activeCase.value = {
|
||||
...activeCase.value,
|
||||
case_no: 'CASE-1',
|
||||
document_id: 1,
|
||||
status: 'draft',
|
||||
confirmed_task_no: null,
|
||||
confirmed_task_id: null,
|
||||
has_formal_ot: false,
|
||||
task_missing: false,
|
||||
recovery_available: null,
|
||||
post_confirm_auto_progress: null,
|
||||
process_gate: null,
|
||||
current_stage: null,
|
||||
technical_progress: null,
|
||||
automation: { status: 'idle', can_auto_create: false, can_build: true },
|
||||
available_actions: ['validate', 'confirm', 'mark_non_order', 'reparse'],
|
||||
profile_match: { available: false, visibility: 'admin_only', candidates: [] },
|
||||
};
|
||||
shippingProcessingProjection.value = null;
|
||||
intakeParseContext.value = null;
|
||||
activeCase.value = createActiveCaseFixture();
|
||||
shippingProcessingProjection.value = null;
|
||||
shippingProcessingLoading.value = false;
|
||||
intakeParseContext.value = null;
|
||||
}
|
||||
|
||||
describe('ShippingOrderReviewView layout phase 1', () => {
|
||||
@@ -712,6 +702,21 @@ describe('ShippingOrderReviewView layout phase 1', () => {
|
||||
},
|
||||
automation: { status: 'manual_fallback', can_auto_create: false, can_build: true },
|
||||
};
|
||||
const taskApi = await import('@/features/chat/api/shipping.api');
|
||||
vi.mocked(taskApi.getWorkspaceShippingTask).mockResolvedValue({
|
||||
task_no: 'SN-GATE-1', status: 'processing', lines: [], events: [],
|
||||
ui_state: {
|
||||
actions: {
|
||||
primary: {
|
||||
code: 'confirm_customer', kind: 'current_gate', enabled: true,
|
||||
dispatch: 'navigation', ui_handler: 'customer_resolution',
|
||||
requires_confirmation: false,
|
||||
},
|
||||
secondary: [],
|
||||
},
|
||||
process_gate: { execution_no: 'EXEC-GATE-1' }, summary: {}, steps: [],
|
||||
},
|
||||
} as any);
|
||||
|
||||
const wrapper = await mountView();
|
||||
await flushPromises();
|
||||
@@ -721,6 +726,114 @@ describe('ShippingOrderReviewView layout phase 1', () => {
|
||||
expect(wrapper.find('[data-testid="mock-process-gate"]').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it('submits a server-authorized Gate action from the current-task card without an action-code alias', async () => {
|
||||
activeCase.value = {
|
||||
...activeCase.value,
|
||||
status: 'confirmed', has_formal_ot: true, task_missing: false,
|
||||
confirmed_task_id: 98, confirmed_task_no: 'SN-EXCEL-1',
|
||||
};
|
||||
shippingProcessingProjection.value = {
|
||||
workItemType: 'order_task', workItemNo: 'SN-EXCEL-1', sourceType: 'direct_pdf',
|
||||
rootOrderTaskNo: 'SN-EXCEL-1', shippingNoticeNo: 'SN-EXCEL-1', conversationId: 'conv-1',
|
||||
submissionNo: 'SUB-EXCEL-1', intakeNo: 'SNI-EXCEL-1', status: 'blocked', stage: 'excel_generating',
|
||||
progressVersion: 1, lastActivityAt: '2026-08-18T12:13:30Z', currentGate: {
|
||||
gateCode: 'artifact_generation', status: 'blocked_retryable', nextActionCode: 'regenerate_excel_artifact',
|
||||
},
|
||||
processGate: {
|
||||
execution_no: 'EXEC-EXCEL-1', status: 'blocked_retryable', current_gate_code: 'artifact_generation',
|
||||
next_action_code: 'regenerate_excel_artifact', allowed_actions: ['regenerate_excel_artifact'],
|
||||
current_blocking_gate: { gate_code: 'artifact_generation', status: 'blocked_retryable', evaluation_version: 8 },
|
||||
},
|
||||
availableActions: ['regenerate_excel_artifact'],
|
||||
sourceSummary: { emailSubject: null, filename: 'po.xlsx', documentCount: 1, parsedDocumentCount: 1, candidateCount: 1, customerName: null, poNumber: null },
|
||||
childOrderTasks: [],
|
||||
uiState: {
|
||||
status: 'retryable', stage: 'excel_generating', blocking_reason: null,
|
||||
primary_action: { code: 'regenerate_excel_artifact', i18nKey: 'chat.shippingProcessing.action.regenerate_excel' },
|
||||
secondary_actions: [],
|
||||
},
|
||||
};
|
||||
const taskApi = await import('@/features/chat/api/shipping.api');
|
||||
vi.mocked(taskApi.getWorkspaceShippingTask).mockResolvedValue({
|
||||
task_no: 'SN-EXCEL-1', status: 'processing', lines: [], events: [],
|
||||
ui_state: {
|
||||
actions: {
|
||||
primary: {
|
||||
code: 'regenerate_excel_artifact', kind: 'recovery', enabled: true,
|
||||
dispatch: 'mutation',
|
||||
target_surface: 'fulfillment_prep', target_anchor: 'excel_artifact',
|
||||
requires_confirmation: false,
|
||||
},
|
||||
secondary: [],
|
||||
},
|
||||
process_gate: {
|
||||
execution_no: 'EXEC-EXCEL-1',
|
||||
current_blocking_gate: {
|
||||
gate_code: 'artifact_generation', evaluation_version: 8,
|
||||
},
|
||||
},
|
||||
summary: {}, steps: [],
|
||||
},
|
||||
} as any);
|
||||
|
||||
const wrapper = await mountView();
|
||||
await flushPromises();
|
||||
await wrapper.get('[data-testid="review-current-task-primary-action"]').trigger('click');
|
||||
await flushPromises();
|
||||
|
||||
// 关键断言:旧 Projection 的 regenerate_excel 不可执行;正式任务的原始动作码
|
||||
// 只委托统一 Gate 执行器,由其按后端版本与授权再次校验。
|
||||
expect(submitProcessGatePrimaryActionMock).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
execution_no: 'EXEC-EXCEL-1',
|
||||
current_blocking_gate: expect.objectContaining({ gate_code: 'artifact_generation' }),
|
||||
}),
|
||||
{ actionCode: 'regenerate_excel_artifact' },
|
||||
);
|
||||
expect(postFormalGateActionMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('does not submit an action merely because its code has a Gate-like prefix', async () => {
|
||||
activeCase.value = {
|
||||
...activeCase.value,
|
||||
status: 'confirmed', has_formal_ot: true, task_missing: false,
|
||||
confirmed_task_id: 99, confirmed_task_no: 'SN-UNAUTHORIZED-1',
|
||||
// 旧 Case 投影仍可能带上 Gate;不能让它以动作码前缀绕过实时 Projection。
|
||||
process_gate: {
|
||||
execution_no: 'EXEC-STALE-CASE-1', status: 'blocked_retryable', owner_type: 'human', technical_auto_only: false,
|
||||
current_blocking_gate: { gate_code: 'artifact_generation', status: 'blocked_retryable' },
|
||||
},
|
||||
};
|
||||
shippingProcessingProjection.value = {
|
||||
workItemType: 'order_task', workItemNo: 'SN-UNAUTHORIZED-1', sourceType: 'direct_pdf',
|
||||
rootOrderTaskNo: 'SN-UNAUTHORIZED-1', shippingNoticeNo: 'SN-UNAUTHORIZED-1', conversationId: 'conv-1',
|
||||
submissionNo: 'SUB-UNAUTHORIZED-1', intakeNo: 'SNI-UNAUTHORIZED-1', status: 'blocked', stage: 'excel_generating',
|
||||
progressVersion: 1, lastActivityAt: '2026-08-18T12:13:30Z', currentGate: {
|
||||
gateCode: 'artifact_generation', status: 'blocked_retryable', nextActionCode: 'confirm_customer',
|
||||
},
|
||||
processGate: {
|
||||
execution_no: 'EXEC-UNAUTHORIZED-1', status: 'blocked_retryable', current_gate_code: 'artifact_generation',
|
||||
next_action_code: 'confirm_customer', allowed_actions: ['confirm_customer'],
|
||||
current_blocking_gate: { gate_code: 'artifact_generation', status: 'blocked_retryable', evaluation_version: 9 },
|
||||
},
|
||||
availableActions: ['confirm_customer'],
|
||||
sourceSummary: { emailSubject: null, filename: 'po.xlsx', documentCount: 1, parsedDocumentCount: 1, candidateCount: 1, customerName: null, poNumber: null },
|
||||
childOrderTasks: [],
|
||||
uiState: {
|
||||
status: 'retryable', stage: 'excel_generating', blocking_reason: null,
|
||||
primary_action: { code: 'regenerate_excel_artifact', i18nKey: 'chat.shippingProcessing.action.regenerate_excel' },
|
||||
secondary_actions: [],
|
||||
},
|
||||
};
|
||||
|
||||
const wrapper = await mountView();
|
||||
await flushPromises();
|
||||
|
||||
// 旧 Projection 的 action 不可替代正式任务动作;详情无同码授权时右侧不展示写按钮。
|
||||
expect(wrapper.find('[data-testid="review-current-task-primary-action"]').exists()).toBe(false);
|
||||
expect(submitProcessGatePrimaryActionMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('routes the right-rail field-conflict action through the registered focus executor', async () => {
|
||||
activeCase.value = {
|
||||
...activeCase.value,
|
||||
@@ -816,7 +929,33 @@ describe('ShippingOrderReviewView layout phase 1', () => {
|
||||
expect(wrapper.find('[data-testid="review-current-task-primary-action"]').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it('shows restored version as current and latest version only as failed attempt', async () => {
|
||||
it('keeps a formal task action loading until its authoritative processing projection arrives', async () => {
|
||||
// Case 快照先返回时可能携带历史/降级 Gate;正式 OT 的动作必须等待统一 Projection 裁决。
|
||||
activeCase.value = {
|
||||
...activeCase.value,
|
||||
status: 'confirmed',
|
||||
has_formal_ot: true,
|
||||
confirmed_task_id: 90,
|
||||
confirmed_task_no: 'SN-PROJECTION-PENDING',
|
||||
process_gate: {
|
||||
execution_no: 'EXEC-PROJECTION-PENDING', status: 'blocked_retryable', owner_type: 'human', technical_auto_only: false,
|
||||
current_blocking_gate: { gate_code: 'inventory_preparation', status: 'blocked_retryable' },
|
||||
primary_action: { code: 'retry', label_key: 'chat.shippingOrderReview.currentTask.actionRetry' },
|
||||
},
|
||||
automation: { status: 'failed', retryable: true, can_auto_create: false, can_build: true },
|
||||
};
|
||||
shippingProcessingProjection.value = null;
|
||||
shippingProcessingLoading.value = true;
|
||||
|
||||
const wrapper = await mountView();
|
||||
await flushPromises();
|
||||
|
||||
// 关键断言:不得先显示 Case 的通用“重试”,避免 Projection 到达后按钮语义跳变。
|
||||
expect(wrapper.find('[data-testid="review-current-processing-retry"]').exists()).toBe(false);
|
||||
expect(wrapper.find('[data-testid="review-current-task-primary-action"]').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it('does not render legacy reparse failure stage as a separate progress source', async () => {
|
||||
reviewProgressContext.value = {
|
||||
item_no: 'WFI-1',
|
||||
current_version_no: 4,
|
||||
@@ -832,21 +971,20 @@ describe('ShippingOrderReviewView layout phase 1', () => {
|
||||
};
|
||||
const wrapper = await mountView();
|
||||
|
||||
const notice = wrapper.find('[data-testid="review-reparse-failed-version-notice"]');
|
||||
expect(notice.text()).toContain('V4 重新识别失败');
|
||||
expect(notice.text()).toContain('解析 PDF 页面与表格');
|
||||
expect(notice.text()).toContain('V3');
|
||||
// 关键断言:顶栏当前版本跟随旧成功结果 V3,禁止把旧字段标成失败尝试 V4。
|
||||
expect(wrapper.find('[data-testid="review-reparse-failed-version-notice"]').exists()).toBe(false);
|
||||
expect(wrapper.find('[data-testid="review-reparse-progress"]').exists()).toBe(false);
|
||||
expect(wrapper.find('[data-testid="review-reparse-progress-rail"]').exists()).toBe(false);
|
||||
// 关键断言:页面只消费统一生命周期/处理投影,禁止用旧失败阶段重建另一条进度轨道。
|
||||
expect(wrapper.find('[data-testid="review-workbench-execution-summary"]').exists()).toBe(false);
|
||||
expect(wrapper.text()).toContain('V3');
|
||||
});
|
||||
|
||||
it('does not show reparse-failure version notice for normal review', async () => {
|
||||
it('does not render a legacy reparse progress rail for normal review', async () => {
|
||||
reviewProgressContext.value = {
|
||||
item_no: 'WFI-1', current_version_no: 3, lifecycle_status: 'pending_review',
|
||||
};
|
||||
const wrapper = await mountView();
|
||||
expect(wrapper.find('[data-testid="review-reparse-failed-version-notice"]').exists()).toBe(false);
|
||||
expect(wrapper.find('[data-testid="review-reparse-progress"]').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it('renders main editor + summary rail without chat context toggle', async () => {
|
||||
@@ -1210,7 +1348,7 @@ describe('ShippingOrderReviewView layout phase 1', () => {
|
||||
intakeParseContext.value = {
|
||||
case_no: 'CASE-1',
|
||||
attachment: { document_id: 1, filename: 'current.pdf', mime_type: 'application/pdf', preview_kind: 'pdf' },
|
||||
email: { document_id: 2, filename: 'source.eml', text: 'current CASE-1 EML body' },
|
||||
email: { document_id: 2, filename: 'source.eml', render_kind: 'text', text: 'current CASE-1 EML body' },
|
||||
};
|
||||
|
||||
const intakeWrapper = await mountView({ lifecycle_stage: 'intake_parse' });
|
||||
@@ -1218,6 +1356,11 @@ describe('ShippingOrderReviewView layout phase 1', () => {
|
||||
// 关键断言:接收解析面板只显示当前 Case context 的邮件正文和附件。
|
||||
expect(intakeWrapper.get('[data-testid="intake-parse-email-body"]').text()).toContain('current CASE-1 EML body');
|
||||
expect(intakeWrapper.get('[data-testid="intake-parse-attachment-preview"] iframe').attributes('src')).toBe('blob:mock-pdf');
|
||||
const intakeFooter = intakeWrapper.get('[data-testid="review-footer-actions"]');
|
||||
// 关键断言:接收解析处置复用订单复核的固定底栏,滚动邮件/附件时仍可操作。
|
||||
expect(intakeFooter.classes()).toEqual(expect.arrayContaining(['sticky', 'bottom-0']));
|
||||
expect(intakeFooter.text()).toContain('非订单');
|
||||
expect(intakeWrapper.find('[data-testid="intake-parse-disposition-actions"]').exists()).toBe(false);
|
||||
|
||||
const orderWrapper = await mountView({ lifecycle_stage: 'order_review' });
|
||||
// 关键断言:订单复核底栏保留 validate,但不再承载四个接收解析处置入口。
|
||||
@@ -1449,11 +1592,24 @@ describe('ShippingOrderReviewView layout phase 1', () => {
|
||||
.toBeLessThan(wrapper.html().indexOf('review-fulfillment-prep-workspace'));
|
||||
});
|
||||
|
||||
it('keeps frozen order lines visible when the inventory file and match result are not ready', async () => {
|
||||
it('renders one row-level inventory workspace with each line source and authorized retry', async () => {
|
||||
const taskApi = await import('@/features/chat/api/shipping.api');
|
||||
activeCase.value = {
|
||||
...activeCase.value,
|
||||
status: 'confirmed', confirmed_task_id: 903, confirmed_task_no: 'SN-FROZEN', has_formal_ot: true,
|
||||
line_fulfillment: {
|
||||
lines: [{
|
||||
line_key: 'line-frozen',
|
||||
inventory_source: { code: 'DBS', label: 'DBS', status: 'resolved' },
|
||||
inventory_allowed_actions: ['retry_inventory_preparation', 'retry_inventory_matching'],
|
||||
line_allowed_actions: ['release_inventory_shortage'],
|
||||
release_template_fields: [
|
||||
{ field_id: '101', display_name: 'ODM ID', value: 'ODM-001', value_source: 'inventory_snapshot', requires_manual: false },
|
||||
{ field_id: '102', display_name: '库位', value: null, value_source: 'manual_required', requires_manual: true },
|
||||
],
|
||||
release_required_fields: [{ field_id: '102', display_name: '库位' }],
|
||||
}],
|
||||
},
|
||||
};
|
||||
shippingProcessingProjection.value = {
|
||||
uiState: {
|
||||
@@ -1469,11 +1625,15 @@ describe('ShippingOrderReviewView layout phase 1', () => {
|
||||
lifecycle_stage: 'fulfillment_prep', lifecycle_entries: [{ code: 'fulfillment_prep', state: 'current' }],
|
||||
stage_context: {
|
||||
preparation: {
|
||||
status: 'blocked', has_match_result: false,
|
||||
status: 'blocked', has_match_result: true,
|
||||
frozen_order_lines: [{
|
||||
line_key: 'line-frozen', reservation_id: 'RSV-FROZEN', part_number: 'PN-FROZEN', required_qty: '6',
|
||||
}],
|
||||
lines: [], inventory_sources: [{ source_code: 'CRANE', status: 'waiting', inventory_file_id: null }],
|
||||
lines: [{
|
||||
line_key: 'line-frozen', reservation_id: 'RSV-FROZEN', part_number: 'PN-FROZEN',
|
||||
required_qty: '6', available_qty: null, shortage_qty: null, source_code: 'DBS',
|
||||
inventory_file_no: 'SIF-LINE-DBS', status: 'shortage',
|
||||
}],
|
||||
artifact: { file_name: null, status: 'not_generated' },
|
||||
},
|
||||
},
|
||||
@@ -1483,78 +1643,63 @@ describe('ShippingOrderReviewView layout phase 1', () => {
|
||||
const wrapper = await mountView({ lifecycle_stage: 'fulfillment_prep' });
|
||||
await flushPromises();
|
||||
|
||||
// 关键断言:无库存文件时仍展示冻结订单;库存匹配空态不能吞掉订单明细。
|
||||
expect(wrapper.get('[data-testid="review-fulfillment-frozen-order"]').text()).toContain('RSV-FROZEN');
|
||||
expect(wrapper.get('[data-testid="review-fulfillment-frozen-order"]').text()).toContain('PN-FROZEN');
|
||||
expect(wrapper.get('[data-testid="review-fulfillment-prep-pending"]').exists()).toBe(true);
|
||||
// 关键断言:订单基线列和库存事实合为唯一行级工作表,库存源不得退化为任务级 CRANE。
|
||||
const workspace = wrapper.get('[data-testid="review-fulfillment-prep-workspace"]');
|
||||
expect(workspace.text()).toContain('RSV-FROZEN');
|
||||
expect(workspace.text()).toContain('PN-FROZEN');
|
||||
expect(workspace.text()).toContain('DBS');
|
||||
expect(wrapper.find('[data-testid="review-fulfillment-frozen-order"]').exists()).toBe(false);
|
||||
expect(wrapper.get('[data-testid="review-fulfillment-line-download-line-frozen"]').attributes('title'))
|
||||
.toBeTruthy();
|
||||
expect(wrapper.get('[data-testid="review-fulfillment-line-retry-preparation-line-frozen"]').attributes('title'))
|
||||
.toBeTruthy();
|
||||
expect(wrapper.get('[data-testid="review-fulfillment-line-retry-matching-line-frozen"]').exists()).toBe(true);
|
||||
expect(wrapper.get('[data-testid="review-fulfillment-line-release-line-frozen"]').exists()).toBe(true);
|
||||
expect(workspace.text()).toContain('库存不足');
|
||||
await wrapper.get('[data-testid="review-fulfillment-line-download-line-frozen"]').trigger('click');
|
||||
expect(downloadWorkspaceShippingLineInventoryFileMock).toHaveBeenCalledWith('SN-FROZEN', 'SIF-LINE-DBS');
|
||||
await wrapper.get('[data-testid="review-fulfillment-line-retry-preparation-line-frozen"]').trigger('click');
|
||||
expect(retryWorkspaceShippingTaskLine).toHaveBeenCalledWith('SN-FROZEN', 'line-frozen');
|
||||
await wrapper.get('[data-testid="review-fulfillment-line-release-line-frozen"]').trigger('click');
|
||||
expect(wrapper.get('[data-testid="review-release-inventory-dialog"]').text()).toContain('ODM ID');
|
||||
expect(wrapper.get('[data-testid="review-release-inventory-dialog"]').text()).toContain('ODM-001');
|
||||
const dialog = wrapper.get('[data-testid="review-release-inventory-dialog"]');
|
||||
await dialog.find('textarea').setValue('客户确认分批发货');
|
||||
await dialog.find('input').setValue('A-01');
|
||||
await dialog.get('button.bg-amber-600').trigger('click');
|
||||
expect(vi.mocked(decideWorkspaceShippingOrderReviewLineFulfillment)).toHaveBeenCalledWith('CASE-1', expect.objectContaining({
|
||||
line_key: 'line-frozen',
|
||||
reason: '客户确认分批发货',
|
||||
release_field_values: { '102': 'A-01' },
|
||||
}));
|
||||
});
|
||||
|
||||
it('only exposes inventory download for the current task when the backend confirms its active file', async () => {
|
||||
const taskApi = await import('@/features/chat/api/shipping.api');
|
||||
activeCase.value = {
|
||||
...activeCase.value,
|
||||
status: 'confirmed', confirmed_task_id: 905, confirmed_task_no: 'SN-INVENTORY-FILE', has_formal_ot: true,
|
||||
};
|
||||
shippingProcessingProjection.value = {
|
||||
uiState: {
|
||||
lifecycleStage: 'fulfillment_prep',
|
||||
lifecycleEntries: [{ code: 'fulfillment_prep', state: 'current', targetSurface: 'order_lifecycle_workbench' }],
|
||||
primary_action: null,
|
||||
secondary_actions: [],
|
||||
},
|
||||
};
|
||||
vi.mocked(taskApi.getWorkspaceShippingTask).mockResolvedValue({
|
||||
task_no: 'SN-INVENTORY-FILE', status: 'processing', lines: [], events: [],
|
||||
ui_state: {
|
||||
lifecycle_stage: 'fulfillment_prep', lifecycle_entries: [{ code: 'fulfillment_prep', state: 'current' }],
|
||||
stage_context: {
|
||||
preparation: {
|
||||
frozen_order_lines: [], lines: [], has_match_result: false,
|
||||
inventory_file: { available: true, file_name: 'confirmed-inventory.xlsx' },
|
||||
},
|
||||
},
|
||||
},
|
||||
} as any);
|
||||
it('keeps intake parse on the standard workbench and removes the inventory return row', async () => {
|
||||
const originalQueue = reviewQueue.value;
|
||||
try {
|
||||
reviewQueue.value = {
|
||||
...reviewQueue.value,
|
||||
items: [{
|
||||
...reviewQueue.value.items[0],
|
||||
lifecycle_stage: 'intake_parse',
|
||||
lifecycle_entries: [],
|
||||
intake_parse_authorized: true,
|
||||
}],
|
||||
};
|
||||
const intakeWrapper = await mountView({ lifecycle_stage: 'intake_parse' });
|
||||
await flushPromises();
|
||||
|
||||
const wrapper = await mountView({ lifecycle_stage: 'fulfillment_prep' });
|
||||
await flushPromises();
|
||||
|
||||
// 关键断言:只有服务端声明当前任务 active link 文件可用时才出现入口,避免跨订单猜测下载。
|
||||
const download = wrapper.get('[data-testid="review-fulfillment-inventory-download"]');
|
||||
expect(download.text()).toContain('下载库存文件');
|
||||
await download.trigger('click');
|
||||
expect(downloadWorkspaceShippingInventoryFileMock).toHaveBeenCalledWith('SN-INVENTORY-FILE');
|
||||
// 关键断言:接收解析不是库存工作面,避免用户看不到重解析入口。
|
||||
expect(intakeWrapper.find('[data-testid="shipping-order-review-view"]').attributes('data-workbench-mode'))
|
||||
.toBe('standard');
|
||||
expect(intakeWrapper.find('[data-testid="review-enter-inventory-mode"]').exists()).toBe(false);
|
||||
expect(intakeWrapper.find('[data-testid="review-return-standard-mode"]').exists()).toBe(false);
|
||||
} finally {
|
||||
reviewQueue.value = originalQueue;
|
||||
}
|
||||
});
|
||||
|
||||
it('does not expose inventory download when the current task has no active inventory file', async () => {
|
||||
const taskApi = await import('@/features/chat/api/shipping.api');
|
||||
activeCase.value = {
|
||||
...activeCase.value,
|
||||
status: 'confirmed', confirmed_task_id: 906, confirmed_task_no: 'SN-NO-INVENTORY-FILE', has_formal_ot: true,
|
||||
};
|
||||
shippingProcessingProjection.value = {
|
||||
uiState: {
|
||||
lifecycleStage: 'fulfillment_prep',
|
||||
lifecycleEntries: [{ code: 'fulfillment_prep', state: 'current', targetSurface: 'order_lifecycle_workbench' }],
|
||||
primary_action: null,
|
||||
secondary_actions: [],
|
||||
},
|
||||
};
|
||||
vi.mocked(taskApi.getWorkspaceShippingTask).mockResolvedValue({
|
||||
task_no: 'SN-NO-INVENTORY-FILE', status: 'processing', lines: [], events: [],
|
||||
ui_state: {
|
||||
lifecycle_stage: 'fulfillment_prep', lifecycle_entries: [{ code: 'fulfillment_prep', state: 'current' }],
|
||||
stage_context: { preparation: { frozen_order_lines: [], lines: [], has_match_result: false, inventory_file: { available: false } } },
|
||||
},
|
||||
} as any);
|
||||
|
||||
const wrapper = await mountView({ lifecycle_stage: 'fulfillment_prep' });
|
||||
await flushPromises();
|
||||
|
||||
expect(wrapper.find('[data-testid="review-fulfillment-inventory-download"]').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it('prefers the formal Gate over a stale processing projection in the current-task card', async () => {
|
||||
it('uses the current processing projection instead of a stale formal-task Gate in the current-task card', async () => {
|
||||
const taskApi = await import('@/features/chat/api/shipping.api');
|
||||
activeCase.value = {
|
||||
...activeCase.value,
|
||||
@@ -1582,9 +1727,9 @@ describe('ShippingOrderReviewView layout phase 1', () => {
|
||||
const wrapper = await mountView({ lifecycle_stage: 'fulfillment_prep' });
|
||||
await flushPromises();
|
||||
|
||||
// 关键断言:正式 Gate 阻断时,右栏不得继续写成“系统正在处理”。
|
||||
// 关键断言:正式任务详情是附件/明细快照;当前 Gate 必须由实时 Projection 裁决。
|
||||
expect(wrapper.get('[data-testid="review-build-gate-rail"] [data-testid="review-current-processing-card"]')
|
||||
.attributes('data-user-status')).toBe('retryable');
|
||||
.attributes('data-user-status')).toBe('running');
|
||||
});
|
||||
|
||||
it('ignores a late formal-task response after switching to another PDF', async () => {
|
||||
@@ -1657,7 +1802,7 @@ describe('ShippingOrderReviewView layout phase 1', () => {
|
||||
expect(wrapper.get('[data-testid="review-footer-actions"]').text()).toContain('保存订单并校验');
|
||||
});
|
||||
|
||||
it('keeps manual upload registration out of the upload main area because the current-task card owns it', async () => {
|
||||
it('keeps backend-authorized manual upload registration out of the upload main area', async () => {
|
||||
const originalQueue = reviewQueue.value;
|
||||
try {
|
||||
activeCase.value = {
|
||||
@@ -1691,6 +1836,8 @@ describe('ShippingOrderReviewView layout phase 1', () => {
|
||||
actions: {
|
||||
primary: {
|
||||
code: 'mark_manual_uploaded', kind: 'forward', enabled: true,
|
||||
target_surface: 'upload_complete',
|
||||
target_anchor: 'manual_upload',
|
||||
requires_confirmation: false,
|
||||
},
|
||||
secondary: [],
|
||||
@@ -1700,14 +1847,205 @@ describe('ShippingOrderReviewView layout phase 1', () => {
|
||||
} as any);
|
||||
const withAuthorization = await mountView({ lifecycle_stage: 'upload_complete' });
|
||||
await flushPromises();
|
||||
// Gate 写操作只在右侧“当前任务”显示;主区只保留上传事实与审计摘要。
|
||||
expect(withAuthorization.find('[data-testid="review-lifecycle-upload-manual"]').exists()).toBe(false);
|
||||
// 无界面 TaskTodoPanel 仍须挂载执行器,供右栏 Gate 动作统一调度。
|
||||
expect((withAuthorization.vm as { formalTodoPanelRef?: unknown }).formalTodoPanelRef).toBeTruthy();
|
||||
// 正式动作直接提交当前 Gate,不允许无界面 TaskTodoPanel 作为隐藏执行器。
|
||||
expect((withAuthorization.vm as { formalTodoPanelRef?: unknown }).formalTodoPanelRef).toBeUndefined();
|
||||
} finally {
|
||||
reviewQueue.value = originalQueue;
|
||||
}
|
||||
});
|
||||
|
||||
it('opens the page-level evidence dialog when the authorized current-task action is manual upload', async () => {
|
||||
activeCase.value = {
|
||||
...activeCase.value,
|
||||
status: 'confirmed', confirmed_task_no: 'SN-UPLOAD-DIALOG', confirmed_task_id: 19, has_formal_ot: true,
|
||||
};
|
||||
const taskApi = await import('@/features/chat/api/shipping.api');
|
||||
vi.mocked(taskApi.getWorkspaceShippingTask).mockResolvedValue({
|
||||
task_no: 'SN-UPLOAD-DIALOG', status: 'processing', lines: [], events: [],
|
||||
ui_state: {
|
||||
actions: {
|
||||
primary: {
|
||||
code: 'mark_manual_uploaded', kind: 'forward', enabled: true,
|
||||
dispatch: 'dialog', ui_handler: 'manual_upload_evidence',
|
||||
target_surface: 'upload_complete', target_anchor: 'manual_upload',
|
||||
requires_confirmation: false,
|
||||
},
|
||||
secondary: [],
|
||||
},
|
||||
summary: {}, steps: [],
|
||||
},
|
||||
} as any);
|
||||
|
||||
const wrapper = await mountView({ lifecycle_stage: 'upload_complete' });
|
||||
await flushPromises();
|
||||
await wrapper.get('[data-testid="review-current-task-primary-action"]').trigger('click');
|
||||
await flushPromises();
|
||||
|
||||
expect(wrapper.find('[data-testid="manual-upload-evidence-dialog"]').exists()).toBe(true);
|
||||
});
|
||||
|
||||
it('renders the authorized Excel download in every upload-complete order line instead of the task rail', async () => {
|
||||
activeCase.value = {
|
||||
...activeCase.value,
|
||||
status: 'confirmed', confirmed_task_no: 'SN-DOWNLOAD-DISPATCH', confirmed_task_id: 20, has_formal_ot: true,
|
||||
schema: {
|
||||
...activeCase.value.schema,
|
||||
fields: [
|
||||
...activeCase.value.schema.fields,
|
||||
{ field_id: 'fld-line-no', field_code: 'line_no', display_name: '项次', scope: 'line', value_type: 'string', required: true, options: [] },
|
||||
{ field_id: 'fld-part-number', field_code: 'part_number', display_name: '料号', scope: 'line', value_type: 'string', required: true, options: [] },
|
||||
{ field_id: 'fld-quantity', field_code: 'quantity', display_name: '数量', scope: 'line', value_type: 'number', required: true, options: [] },
|
||||
],
|
||||
},
|
||||
draft: {
|
||||
...activeCase.value.draft,
|
||||
lines: [
|
||||
{ line_key: 'LINE-1', values: { 'fld-line-no': { value: '10' }, 'fld-part-number': { value: 'PN-ONE' }, 'fld-quantity': { value: '4' } }, machine_fields: [] },
|
||||
{ line_key: 'LINE-2', values: { 'fld-line-no': { value: '20' }, 'fld-part-number': { value: 'PN-TWO' }, 'fld-quantity': { value: '7' } }, machine_fields: [] },
|
||||
],
|
||||
},
|
||||
line_fulfillment: {
|
||||
lines: [
|
||||
{ line_key: 'LINE-1', reservation_id: 'RSV-1', line_status: 'fulfilled' },
|
||||
{ line_key: 'LINE-2', reservation_id: 'RSV-2', line_status: 'fulfilled' },
|
||||
],
|
||||
},
|
||||
};
|
||||
const taskApi = await import('@/features/chat/api/shipping.api');
|
||||
vi.mocked(taskApi.getWorkspaceShippingTask).mockResolvedValue({
|
||||
task_no: 'SN-DOWNLOAD-DISPATCH', status: 'completed', lines: [], events: [],
|
||||
ui_state: {
|
||||
actions: {
|
||||
primary: {
|
||||
code: 'mark_manual_uploaded', kind: 'forward', enabled: true,
|
||||
dispatch: 'dialog', ui_handler: 'manual_upload_evidence',
|
||||
requires_confirmation: false,
|
||||
},
|
||||
secondary: [{
|
||||
code: 'download_excel', label: '下载 Excel', kind: 'view', enabled: true,
|
||||
dispatch: 'view', ui_handler: 'excel_download',
|
||||
target_surface: 'upload_complete', target_anchor: 'excel_artifact',
|
||||
requires_confirmation: false,
|
||||
}],
|
||||
},
|
||||
lifecycle_stage: 'upload_complete',
|
||||
lifecycle_entries: [{ code: 'upload_complete', state: 'current' }],
|
||||
process_gate: { execution_no: 'EXEC-DOWNLOAD-DISPATCH' }, summary: {}, steps: [],
|
||||
},
|
||||
} as any);
|
||||
|
||||
const wrapper = await mountView({ lifecycle_stage: 'upload_complete' });
|
||||
await flushPromises();
|
||||
|
||||
const rows = wrapper.findAll('[data-testid="review-upload-complete-line"]');
|
||||
expect(rows).toHaveLength(2);
|
||||
expect(rows[0].text()).toContain('PN-ONE');
|
||||
expect(rows[1].text()).toContain('PN-TWO');
|
||||
expect(wrapper.find('[data-testid="review-current-task-recovery-download_excel"]').exists()).toBe(false);
|
||||
|
||||
await wrapper.get('[data-testid="review-upload-complete-download-LINE-1"]').trigger('click');
|
||||
await flushPromises();
|
||||
|
||||
// 下载是 Artifact 只读操作;订单行不按 PO 聚合,且不得伪装成 Gate mutation。
|
||||
expect(downloadWorkspaceShippingExcelFileMock).toHaveBeenCalledWith('SN-DOWNLOAD-DISPATCH');
|
||||
expect(messageMocks.success).not.toHaveBeenCalled();
|
||||
expect(submitProcessGatePrimaryActionMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('keeps backend-authorized Excel regeneration out of fulfillment preparation main area', async () => {
|
||||
const originalQueue = reviewQueue.value;
|
||||
try {
|
||||
activeCase.value = {
|
||||
...activeCase.value,
|
||||
status: 'confirmed', confirmed_task_no: 'SN-EXCEL-RETRY', confirmed_task_id: 12, has_formal_ot: true,
|
||||
};
|
||||
reviewQueue.value = {
|
||||
...reviewQueue.value,
|
||||
items: [{
|
||||
...reviewQueue.value.items[0], lifecycle_stage: 'fulfillment_prep',
|
||||
lifecycle_entries: [
|
||||
{ code: 'intake_parse', state: 'available', targetSurface: 'order_lifecycle_workbench' },
|
||||
{ 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' },
|
||||
],
|
||||
}],
|
||||
};
|
||||
const taskApi = await import('@/features/chat/api/shipping.api');
|
||||
vi.mocked(taskApi.getWorkspaceShippingTask).mockResolvedValue({
|
||||
task_no: 'SN-EXCEL-RETRY', status: 'processing', lines: [], events: [],
|
||||
ui_state: {
|
||||
actions: {
|
||||
primary: {
|
||||
code: 'regenerate_excel_artifact', kind: 'recovery', enabled: true,
|
||||
dispatch: 'mutation',
|
||||
target_surface: 'fulfillment_prep',
|
||||
target_anchor: 'excel_artifact',
|
||||
requires_confirmation: false,
|
||||
},
|
||||
secondary: [],
|
||||
},
|
||||
stage_context: { preparation: { status: 'blocked', has_match_result: false, lines: [] } },
|
||||
summary: {}, steps: [],
|
||||
},
|
||||
} as any);
|
||||
|
||||
const wrapper = await mountView({ lifecycle_stage: 'fulfillment_prep' });
|
||||
await flushPromises();
|
||||
|
||||
// Gate 18 的写入口只属于右侧“当前任务”;准备区仅展示库存与产物事实。
|
||||
expect(wrapper.find('[data-testid="review-lifecycle-preparation-regenerate_excel_artifact"]').exists()).toBe(false);
|
||||
} finally {
|
||||
reviewQueue.value = originalQueue;
|
||||
}
|
||||
});
|
||||
|
||||
it('does not place a backend action in a lifecycle area when its anchor differs', async () => {
|
||||
const originalQueue = reviewQueue.value;
|
||||
try {
|
||||
activeCase.value = {
|
||||
...activeCase.value,
|
||||
status: 'confirmed', confirmed_task_no: 'SN-ANCHOR-1', confirmed_task_id: 13, has_formal_ot: true,
|
||||
};
|
||||
reviewQueue.value = {
|
||||
...reviewQueue.value,
|
||||
items: [{
|
||||
...reviewQueue.value.items[0], lifecycle_stage: 'fulfillment_prep',
|
||||
lifecycle_entries: [
|
||||
{ code: 'fulfillment_prep', state: 'current', targetSurface: 'order_lifecycle_workbench' },
|
||||
],
|
||||
}],
|
||||
};
|
||||
const taskApi = await import('@/features/chat/api/shipping.api');
|
||||
vi.mocked(taskApi.getWorkspaceShippingTask).mockResolvedValue({
|
||||
task_no: 'SN-ANCHOR-1', status: 'processing', lines: [], events: [],
|
||||
ui_state: {
|
||||
actions: {
|
||||
primary: {
|
||||
code: 'regenerate_excel_artifact', kind: 'recovery', enabled: true,
|
||||
dispatch: 'mutation',
|
||||
target_surface: 'fulfillment_prep', target_anchor: 'inventory_matching',
|
||||
requires_confirmation: false,
|
||||
},
|
||||
secondary: [],
|
||||
},
|
||||
stage_context: { preparation: { status: 'blocked', has_match_result: false, lines: [] } },
|
||||
summary: {}, steps: [],
|
||||
},
|
||||
} as any);
|
||||
|
||||
const wrapper = await mountView({ lifecycle_stage: 'fulfillment_prep' });
|
||||
await flushPromises();
|
||||
|
||||
// 位置必须同时由后端 surface 与 anchor 授权;前端不能仅凭动作码或阶段补放。
|
||||
expect(wrapper.find('[data-testid="review-lifecycle-preparation-regenerate_excel_artifact"]').exists()).toBe(false);
|
||||
} finally {
|
||||
reviewQueue.value = originalQueue;
|
||||
}
|
||||
}, 15000);
|
||||
|
||||
it('renders a persistent result panel for a completed formal task', async () => {
|
||||
activeCase.value = {
|
||||
...activeCase.value,
|
||||
@@ -1914,7 +2252,7 @@ describe('ShippingOrderReviewView audit and progress recovery', () => {
|
||||
expect(messageMocks.warning).toHaveBeenCalledWith('审计记录失败,敏感面板未打开,请重试');
|
||||
});
|
||||
|
||||
it('restores object-level retry from post_confirm_auto_progress after reload', async () => {
|
||||
it('waits for the authoritative Gate projection instead of restoring Case retry after reload', async () => {
|
||||
activeCase.value = {
|
||||
...activeCase.value,
|
||||
status: 'confirmed',
|
||||
@@ -1938,15 +2276,15 @@ describe('ShippingOrderReviewView audit and progress recovery', () => {
|
||||
};
|
||||
const wrapper = await mountView();
|
||||
await flushPromises();
|
||||
// 关键断言:琥珀色确认条已移除;刷新后对象级重试挂在当前处理卡。
|
||||
// 关键断言:正式 OT 的旧 Case 快照不是写授权;实时 Gate 未返回时只能等待。
|
||||
expect(wrapper.find('[data-testid="review-confirm-outcome"]').exists()).toBe(false);
|
||||
expect(wrapper.find('[data-testid="retry-auto-progress-after-confirm"]').exists()).toBe(false);
|
||||
expect(wrapper.find('[data-testid="review-current-processing-retry"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="review-current-processing-retry"]').exists()).toBe(false);
|
||||
expect(wrapper.find('[data-testid="review-current-processing-ot"]').text()).toContain('SN-RECOVER-1');
|
||||
}, 15000);
|
||||
|
||||
it('retries formal OT via unified /retry from main card after refresh without confirmSuccess (UI-01)', async () => {
|
||||
// 关键断言:刷新后无 confirmSuccess 时,主卡仍用 confirmed_task_no 调统一 /retry(禁止 auto-progress)。
|
||||
it('does not call legacy retry before the formal OT Gate projection arrives (UI-01)', async () => {
|
||||
// 关键断言:刷新后无实时 Gate 时,不能用 confirmed_task_no 调旧 /retry。
|
||||
vi.mocked(retryWorkspaceShippingTask).mockClear();
|
||||
activeCase.value = {
|
||||
...activeCase.value,
|
||||
@@ -1972,10 +2310,8 @@ describe('ShippingOrderReviewView audit and progress recovery', () => {
|
||||
const wrapper = await mountView();
|
||||
await flushPromises();
|
||||
const retryBtn = wrapper.find('[data-testid="review-current-processing-retry"]');
|
||||
expect(retryBtn.exists()).toBe(true);
|
||||
await retryBtn.trigger('click');
|
||||
await flushPromises();
|
||||
expect(retryWorkspaceShippingTask).toHaveBeenCalledWith('SN-OT-FAIL-1');
|
||||
expect(retryBtn.exists()).toBe(false);
|
||||
expect(retryWorkspaceShippingTask).not.toHaveBeenCalled();
|
||||
}, 15000);
|
||||
|
||||
it('disables the formal Gate retry while inventory preparation is waiting for RPA callback', async () => {
|
||||
@@ -2005,6 +2341,25 @@ describe('ShippingOrderReviewView audit and progress recovery', () => {
|
||||
secondary_actions: [],
|
||||
},
|
||||
};
|
||||
vi.mocked(getWorkspaceShippingTask).mockResolvedValue({
|
||||
task_no: 'SN-OT-WAITING-INVENTORY', status: 'processing', lines: [], events: [],
|
||||
ui_state: {
|
||||
actions: {
|
||||
primary: {
|
||||
code: 'retry_inventory_preparation', kind: 'recovery', enabled: true,
|
||||
dispatch: 'mutation', requires_confirmation: false,
|
||||
},
|
||||
secondary: [],
|
||||
},
|
||||
process_gate: {
|
||||
execution_no: 'EXEC-INVENTORY-WAITING',
|
||||
current_blocking_gate: {
|
||||
gate_code: 'inventory_preparation', evaluation_version: 1,
|
||||
},
|
||||
},
|
||||
summary: {}, steps: [],
|
||||
},
|
||||
} as any);
|
||||
|
||||
const wrapper = await mountView();
|
||||
await flushPromises();
|
||||
@@ -2147,8 +2502,8 @@ describe('ShippingOrderReviewView audit and progress recovery', () => {
|
||||
expect(wrapper.find('[data-testid="review-profile-match-panel"]').exists()).toBe(true);
|
||||
}, 15000);
|
||||
|
||||
it('hydrates progress-failed retry state from Case projection without confirm UI', async () => {
|
||||
// 关键断言:无确认建单按钮时,仍可从 post_confirm_auto_progress 恢复对象级重试入口。
|
||||
it('does not hydrate a write retry from Case projection without formal Gate data', async () => {
|
||||
// 关键断言:无确认建单按钮时,Case 的失败状态只能作为历史摘要,不能恢复写入口。
|
||||
activeCase.value = {
|
||||
...activeCase.value,
|
||||
status: 'confirmed',
|
||||
@@ -2173,7 +2528,7 @@ describe('ShippingOrderReviewView audit and progress recovery', () => {
|
||||
const wrapper = await mountView();
|
||||
await flushPromises();
|
||||
expect(wrapper.find('[data-testid="review-confirm-create"]').exists()).toBe(false);
|
||||
expect(wrapper.find('[data-testid="review-current-processing-retry"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="review-current-processing-retry"]').exists()).toBe(false);
|
||||
expect(wrapper.find('[data-testid="review-current-processing-ot"]').text()).toContain('SN-CONFIRM-PROGRESS-FAIL');
|
||||
}, 15000);
|
||||
});
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
+18
-16
@@ -179,7 +179,7 @@ describe('ProcessGateRecoveryCard', () => {
|
||||
expect(wrapper.find('[data-testid="process-gate-readonly-hint"]').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it('shows inventory upload as a secondary entry beside retrying inventory retrieval', async () => {
|
||||
it('does not expose inventory file upload beside retrying inventory retrieval', () => {
|
||||
const wrapper = mount(ProcessGateRecoveryCard, {
|
||||
props: {
|
||||
summary: baseSummary({
|
||||
@@ -189,42 +189,37 @@ describe('ProcessGateRecoveryCard', () => {
|
||||
next_action_code: 'retry_inventory_preparation',
|
||||
},
|
||||
next_action_code: 'retry_inventory_preparation',
|
||||
allowed_actions: ['retry_inventory_preparation', 'upload_inventory_file'],
|
||||
allowed_actions: ['retry_inventory_preparation'],
|
||||
task_no: 'SN-TEST-001',
|
||||
navigation: { target: 'task_workspace', task_no: 'SN-TEST-001' },
|
||||
}),
|
||||
canHandle: true,
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
|
||||
const upload = wrapper.get('[data-testid="process-gate-inventory-upload"]');
|
||||
expect(upload.text()).toContain('上传库存文件');
|
||||
await upload.trigger('click');
|
||||
expect(wrapper.emitted('navigate')).toHaveLength(1);
|
||||
expect(wrapper.get('[data-testid="process-gate-recovery-primary"]').text())
|
||||
.toContain('重新获取库存(RPA)');
|
||||
expect(wrapper.find('[data-testid="process-gate-inventory-upload"]').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it('opens local upload registration when requested by the order review workbench', async () => {
|
||||
it('does not expose an obsolete inventory recovery target as a user action', () => {
|
||||
const wrapper = mount(ProcessGateRecoveryCard, {
|
||||
props: {
|
||||
summary: baseSummary({
|
||||
current_blocking_gate: {
|
||||
...baseSummary().current_blocking_gate!,
|
||||
gate_code: 'inventory_preparation',
|
||||
next_action_code: 'retry_inventory_preparation',
|
||||
gate_code: 'inventory_matching',
|
||||
next_action_code: 'retry_inventory_from_preparation',
|
||||
},
|
||||
next_action_code: 'retry_inventory_preparation',
|
||||
allowed_actions: ['retry_inventory_preparation', 'upload_inventory_file'],
|
||||
task_no: 'SN-TEST-001',
|
||||
next_action_code: 'retry_inventory_from_preparation',
|
||||
}),
|
||||
canHandle: true,
|
||||
inventoryUploadMode: 'local',
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
|
||||
await wrapper.get('[data-testid="process-gate-inventory-upload"]').trigger('click');
|
||||
expect(wrapper.emitted('manualUpload')).toHaveLength(1);
|
||||
expect(wrapper.emitted('navigate')).toBeUndefined();
|
||||
expect(wrapper.find('[data-testid="process-gate-recovery-primary"]').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it('opens evidence registration for the manual-upload confirmation primary action', async () => {
|
||||
@@ -238,6 +233,13 @@ describe('ProcessGateRecoveryCard', () => {
|
||||
},
|
||||
next_action_code: 'mark_manual_uploaded',
|
||||
allowed_actions: ['mark_manual_uploaded'],
|
||||
primary_action: {
|
||||
code: 'mark_manual_uploaded',
|
||||
label_key: 'workspace.shippingNotice.processGate.actionCodes.mark_manual_uploaded',
|
||||
kind: 'current_gate',
|
||||
dispatch: 'dialog',
|
||||
ui_handler: 'manual_upload_evidence',
|
||||
},
|
||||
task_no: 'SN-TEST-001',
|
||||
} as ShippingProcessGateUserSummary),
|
||||
canHandle: true,
|
||||
|
||||
+11
-37
@@ -4,7 +4,7 @@
|
||||
* 依赖:useShippingProcessGateRecovery、processGateNavigation、process-gates.api、
|
||||
* ShippingProcessGateUserSummary / ShippingExplainabilityReason。
|
||||
* 逻辑:仅 owner_type=human(且非 technical_auto_only)时渲染;系统 Worker 等待整卡隐藏;
|
||||
* 导航类动作 router.push;confirm_customer / mark_manual_uploaded 发射本地事件由父级开弹窗;
|
||||
* 导航类动作 router.push;dialog + ui_handler 发射本地事件由父级打开既有宿主;
|
||||
* POST 类动作调 Workspace API;409 触发 refreshed;
|
||||
* 下一步文案独立于按钮;canHandle=false 时不渲染恢复主按钮,提示用 Footer;
|
||||
* 禁止堆栈/路径/SQL。
|
||||
@@ -13,6 +13,7 @@
|
||||
import { computed } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { useShippingProcessGateRecovery } from '../composables/useShippingProcessGateRecovery';
|
||||
import { inventoryActionLabelKey, isInternalInventoryAction } from '@/features/shipping-progress/actionPresentation';
|
||||
import type { ProcessGateNavigationContext } from '../composables/processGateNavigation';
|
||||
import type { ShippingProcessGateUserSummary } from '../types/process-gate.types';
|
||||
|
||||
@@ -24,8 +25,6 @@ const props = withDefaults(defineProps<{
|
||||
/** 复核工作台仅展示待处理说明;唯一可执行入口由“当前任务”承担。 */
|
||||
showActions?: boolean;
|
||||
navigationContext?: ProcessGateNavigationContext;
|
||||
/** 复核工作台直接打开人工上传登记;任务中心默认仍导航到任务详情。 */
|
||||
inventoryUploadMode?: 'navigate' | 'local';
|
||||
/** 复核 Schema 的 field_code/field_id 到业务字段名映射。 */
|
||||
fieldLabels?: Record<string, string>;
|
||||
}>(), {
|
||||
@@ -48,11 +47,8 @@ const blockingGate = computed(() => props.summary?.current_blocking_gate || null
|
||||
const nextActionCode = computed(() =>
|
||||
String(props.summary?.next_action_code || blockingGate.value?.next_action_code || '').trim(),
|
||||
);
|
||||
const hasRecoveryAction = computed(() => Boolean(blockingGate.value && nextActionCode.value));
|
||||
const showInventoryUploadAction = computed(() => (
|
||||
String(blockingGate.value?.gate_code || '').trim().toLowerCase() === 'inventory_preparation'
|
||||
&& nextActionCode.value === 'retry_inventory_preparation'
|
||||
&& (props.summary?.allowed_actions || []).includes('upload_inventory_file')
|
||||
const hasRecoveryAction = computed(() => Boolean(
|
||||
blockingGate.value && nextActionCode.value && !isInternalInventoryAction(nextActionCode.value),
|
||||
));
|
||||
|
||||
/**
|
||||
@@ -94,6 +90,8 @@ const gateLabel = computed(() =>
|
||||
const actionLabel = computed(() => {
|
||||
const code = nextActionCode.value;
|
||||
if (!code) return '';
|
||||
const inventoryKey = inventoryActionLabelKey(code);
|
||||
if (inventoryKey && te(inventoryKey)) return t(inventoryKey);
|
||||
const key = `workspace.shippingNotice.processGate.actionCodes.${code}`;
|
||||
return te(key) ? t(key) : t('workspace.shippingNotice.processGate.continueAction');
|
||||
});
|
||||
@@ -128,19 +126,17 @@ const failureDetail = computed(() => safeBusinessText(props.summary?.failure_det
|
||||
*/
|
||||
async function runPrimaryAction() {
|
||||
if (!props.summary || !props.canHandle || busy.value) return;
|
||||
// Gate 20 的“确认已人工上传”必须先收集截图/PDF 与货代回执号;
|
||||
// 该动作只打开既有凭据弹窗,禁止普通 Gate POST 绕过证据门槛。
|
||||
if (nextActionCode.value === 'mark_manual_uploaded') {
|
||||
emit('manualUpload');
|
||||
return;
|
||||
}
|
||||
const result = await submitPrimaryAction(props.summary, {
|
||||
navigationContext: props.navigationContext,
|
||||
});
|
||||
if (result.outcome === 'confirm_customer' && result.taskNo) {
|
||||
if (result.outcome === 'dialog' && result.uiHandler === 'customer_resolution' && result.taskNo) {
|
||||
emit('confirmCustomer', result.taskNo);
|
||||
return;
|
||||
}
|
||||
if (result.outcome === 'dialog' && result.uiHandler === 'manual_upload_evidence') {
|
||||
emit('manualUpload');
|
||||
return;
|
||||
}
|
||||
if (result.outcome === 'navigated') {
|
||||
emit('navigate');
|
||||
return;
|
||||
@@ -155,19 +151,6 @@ async function runPrimaryAction() {
|
||||
}
|
||||
}
|
||||
|
||||
async function runInventoryUpload() {
|
||||
if (!props.summary || !props.canHandle || busy.value) return;
|
||||
if (props.inventoryUploadMode === 'local') {
|
||||
emit('manualUpload');
|
||||
return;
|
||||
}
|
||||
const result = await submitPrimaryAction(props.summary, {
|
||||
actionCode: 'upload_inventory_file',
|
||||
navigationContext: props.navigationContext,
|
||||
});
|
||||
if (result.outcome === 'navigated') emit('navigate');
|
||||
}
|
||||
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -208,15 +191,6 @@ async function runInventoryUpload() {
|
||||
>
|
||||
{{ busy ? $t('workspace.shippingNotice.processGate.submitting') : actionLabel }}
|
||||
</button>
|
||||
<button
|
||||
v-if="showInventoryUploadAction && canHandle"
|
||||
type="button"
|
||||
class="inline-flex min-h-8 items-center rounded-md border border-default bg-surface px-3 py-1.5 text-xs font-semibold text-secondary shadow-sm transition hover:bg-surface-soft focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-500 focus-visible:ring-offset-2"
|
||||
data-testid="process-gate-inventory-upload"
|
||||
@click="runInventoryUpload"
|
||||
>
|
||||
{{ $t('workspace.shippingNotice.processGate.actionCodes.upload_inventory_file') }}
|
||||
</button>
|
||||
<span
|
||||
v-if="!canHandle && hasRecoveryAction"
|
||||
class="text-xs text-muted"
|
||||
|
||||
@@ -2,53 +2,14 @@
|
||||
* features/shipping-process-gates/composables/processGateNavigation.ts
|
||||
* 用途:将服务端下发的门禁恢复动作映射为 Vue Router 深链(复核台 / 任务工作台)。
|
||||
* 依赖:process-gate.types、vue-router RouteLocationRaw。
|
||||
* 逻辑:与 process_gate_projection.navigation 对齐;禁止本地发明 action_code。
|
||||
* confirm_customer 不属于复核导航:由本地客户选择弹窗完成(建单后 customer_review)。
|
||||
* 逻辑:与 process_gate_projection.navigation 及后端下发的 dispatch 对齐;
|
||||
* 禁止根据 action_code 判断跳转或弹窗。
|
||||
*/
|
||||
import type { RouteLocationRaw } from 'vue-router';
|
||||
import type { ShippingProcessGateUserSummary } from '../types/process-gate.types';
|
||||
|
||||
/**
|
||||
* 前端本地 UX 动作:不 router.push、不 POST Gate API,由挂载方打开专用弹窗/面板。
|
||||
* 与「复核页不做客户重识别」的产品边界一致。
|
||||
*/
|
||||
export const PROCESS_GATE_LOCAL_UX_ACTIONS = new Set<string>([
|
||||
'confirm_customer',
|
||||
]);
|
||||
|
||||
/** 点击后仅导航、不 POST 的人工入口动作(regenerate_manual_upload_todo 除外)。 */
|
||||
export const PROCESS_GATE_NAVIGATION_ACTIONS = new Set<string>([
|
||||
'open_order_review',
|
||||
'open_inventory_source_review',
|
||||
'open_profile_review',
|
||||
'edit_order_fields',
|
||||
'edit_reservation',
|
||||
'adjudicate_duplicate',
|
||||
'resolve_field_conflicts',
|
||||
'open_inventory_match_review',
|
||||
'open_shortage_review',
|
||||
'upload_inventory_file',
|
||||
'confirm_inventory_field_mapping',
|
||||
]);
|
||||
|
||||
/**
|
||||
* 判断动作码是否为前端本地 UX(弹窗)恢复动作。
|
||||
*/
|
||||
export function isProcessGateLocalUxAction(actionCode: string): boolean {
|
||||
return PROCESS_GATE_LOCAL_UX_ACTIONS.has(String(actionCode || '').trim());
|
||||
}
|
||||
|
||||
/**
|
||||
* 从 Gate 摘要解析任务编号(客户确认 API 锚点)。
|
||||
* @returns 大写 task_no;缺失时空串
|
||||
*/
|
||||
export function resolveProcessGateTaskNo(summary: ShippingProcessGateUserSummary): string {
|
||||
return String(
|
||||
summary.navigation?.task_no
|
||||
|| summary.task_no
|
||||
|| '',
|
||||
).trim().toUpperCase();
|
||||
}
|
||||
import type {
|
||||
ShippingProcessGateActionPresentation,
|
||||
ShippingProcessGateUserSummary,
|
||||
} from '../types/process-gate.types';
|
||||
|
||||
export interface ProcessGateNavigationContext {
|
||||
agentId?: string;
|
||||
@@ -57,24 +18,23 @@ export interface ProcessGateNavigationContext {
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断动作码是否属于前端导航类恢复动作。
|
||||
* 判断后端是否将动作裁决为导航。
|
||||
*/
|
||||
export function isProcessGateNavigationAction(actionCode: string): boolean {
|
||||
return PROCESS_GATE_NAVIGATION_ACTIONS.has(String(actionCode || '').trim());
|
||||
export function isProcessGateNavigationAction(action: ShippingProcessGateActionPresentation | null): boolean {
|
||||
return String(action?.dispatch || '').trim() === 'navigation';
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据 Gate 摘要与动作码构建 router 目标。
|
||||
* 根据 Gate 摘要与后端动作展示元数据构建 router 目标。
|
||||
* 核心逻辑:优先 summary.navigation;缺省时回退 review_run_no / case_no / task_no。
|
||||
* @returns 可 push 的路由;缺关键编号时 null
|
||||
*/
|
||||
export function buildProcessGateNavigationRoute(
|
||||
summary: ShippingProcessGateUserSummary,
|
||||
actionCode: string,
|
||||
action: ShippingProcessGateActionPresentation | null,
|
||||
context: ProcessGateNavigationContext = {},
|
||||
): RouteLocationRaw | null {
|
||||
const code = String(actionCode || '').trim();
|
||||
if (!isProcessGateNavigationAction(code)) return null;
|
||||
if (!isProcessGateNavigationAction(action)) return null;
|
||||
|
||||
const nav = summary.navigation;
|
||||
const runNo = String(nav?.run_no || summary.review_run_no || '').trim();
|
||||
@@ -82,7 +42,7 @@ export function buildProcessGateNavigationRoute(
|
||||
const taskNo = String(nav?.task_no || summary.task_no || '').trim();
|
||||
const focus = String(nav?.focus || 'draft').trim();
|
||||
|
||||
if (nav?.target === 'task_workspace' || code === 'upload_inventory_file') {
|
||||
if (nav?.target === 'task_workspace') {
|
||||
if (!taskNo) return null;
|
||||
return { name: 'workspace-shipping-tasks', params: { taskNo } };
|
||||
}
|
||||
|
||||
+44
-18
@@ -2,8 +2,8 @@
|
||||
* features/shipping-process-gates/composables/useShippingProcessGateRecovery.ts
|
||||
* 用途:任务工作台门禁恢复动作编排(导航、本地 UX 弹窗、幂等键、版本锁、409 刷新)。
|
||||
* 依赖:process-gates.api、processGateNavigation、process-gate.types、useMessage。
|
||||
* 逻辑:ProcessGateRecoveryCard 调用 submitPrimaryAction;禁止本地发明 action_code;
|
||||
* confirm_customer 打开客户选择弹窗,不跳转订单复核。
|
||||
* 逻辑:ProcessGateRecoveryCard 调用 submitPrimaryAction;动作行为只由后端的
|
||||
* dispatch + ui_handler 裁决,action_code 仅作为后端执行标识。
|
||||
*/
|
||||
import { ref } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
@@ -20,26 +20,43 @@ import type {
|
||||
} from '../types/process-gate.types';
|
||||
import {
|
||||
buildProcessGateNavigationRoute,
|
||||
isProcessGateLocalUxAction,
|
||||
isProcessGateNavigationAction,
|
||||
resolveProcessGateTaskNo,
|
||||
type ProcessGateNavigationContext,
|
||||
} from './processGateNavigation';
|
||||
|
||||
export type ProcessGateActionOutcome =
|
||||
| 'submitted'
|
||||
| 'navigated'
|
||||
| 'confirm_customer'
|
||||
| 'dialog'
|
||||
| 'refresh_needed'
|
||||
| 'failed'
|
||||
| 'noop';
|
||||
|
||||
export interface ProcessGateActionResult {
|
||||
outcome: ProcessGateActionOutcome;
|
||||
/** confirm_customer 时带回的任务编号 */
|
||||
/** dialog 时由后端声明的既有页面宿主能力。 */
|
||||
uiHandler?: string;
|
||||
/** dialog 宿主可能需要的任务编号。 */
|
||||
taskNo?: string;
|
||||
}
|
||||
|
||||
/** 从当前 Gate 的后端展示契约解析动作;缺元数据时 fail-closed。 */
|
||||
function resolveActionPresentation(
|
||||
summary: ShippingProcessGateUserSummary,
|
||||
actionCode: string,
|
||||
) {
|
||||
const gate = summary.current_blocking_gate;
|
||||
const actions = [
|
||||
...(summary.action_presentation || []),
|
||||
...(gate?.action_presentation || []),
|
||||
];
|
||||
const primary = summary.primary_action;
|
||||
if (primary && String(primary.code || '').trim() === actionCode) return primary;
|
||||
const exact = actions.find((item) => String(item?.code || '').trim() === actionCode);
|
||||
if (exact) return exact;
|
||||
return null;
|
||||
}
|
||||
|
||||
function newIdempotencyKey(): string {
|
||||
if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {
|
||||
return crypto.randomUUID();
|
||||
@@ -99,9 +116,9 @@ export function useShippingProcessGateRecovery() {
|
||||
const busy = ref(false);
|
||||
|
||||
/**
|
||||
* 提交、导航或打开本地 UX(客户弹窗)以恢复当前阻断 Gate。
|
||||
* 提交、导航或打开后端声明的既有页面宿主以恢复当前阻断 Gate。
|
||||
* 核心逻辑:evaluation_version 来自 current_blocking_gate;409 返回 refresh_needed;
|
||||
* confirm_customer 需 task_no,不走复核深链。
|
||||
* dialog 必须携带 ui_handler,缺失时 fail-closed。
|
||||
*/
|
||||
async function submitPrimaryAction(
|
||||
summary: ShippingProcessGateUserSummary,
|
||||
@@ -128,20 +145,29 @@ export function useShippingProcessGateRecovery() {
|
||||
return { outcome: 'noop' };
|
||||
}
|
||||
|
||||
// [STEP] 客户确认:建单后 customer_review,打开选择弹窗,禁止跳转复核页。
|
||||
if (isProcessGateLocalUxAction(actionCode) && actionCode === 'confirm_customer') {
|
||||
const taskNo = resolveProcessGateTaskNo(summary);
|
||||
if (!taskNo) {
|
||||
msg.warning(t('workspace.shippingNotice.processGate.customerTaskMissing'));
|
||||
return { outcome: 'failed' };
|
||||
}
|
||||
return { outcome: 'confirm_customer', taskNo };
|
||||
const action = resolveActionPresentation(summary, String(actionCode));
|
||||
if (!action) {
|
||||
msg.warning(t('workspace.shippingNotice.processGate.noAction'));
|
||||
return { outcome: 'noop' };
|
||||
}
|
||||
|
||||
if (isProcessGateNavigationAction(actionCode)) {
|
||||
if (String(action.dispatch || '').trim() === 'dialog') {
|
||||
const uiHandler = String(action.ui_handler || '').trim();
|
||||
if (!uiHandler) {
|
||||
msg.warning(t('workspace.shippingNotice.processGate.noAction'));
|
||||
return { outcome: 'failed' };
|
||||
}
|
||||
return {
|
||||
outcome: 'dialog',
|
||||
uiHandler,
|
||||
taskNo: String(summary.navigation?.task_no || summary.task_no || '').trim().toUpperCase(),
|
||||
};
|
||||
}
|
||||
|
||||
if (isProcessGateNavigationAction(action)) {
|
||||
const route = buildProcessGateNavigationRoute(
|
||||
summary,
|
||||
actionCode,
|
||||
action,
|
||||
options?.navigationContext || {},
|
||||
);
|
||||
if (!route) {
|
||||
|
||||
@@ -11,6 +11,7 @@ import type {
|
||||
ShippingInventorySourceLineBlockReasonCode,
|
||||
ShippingInventorySourceUnavailableReasonCode,
|
||||
ShippingProcessGateActionCode,
|
||||
ShippingProcessGateActionPresentation,
|
||||
ShippingProcessGateCode,
|
||||
ShippingProcessGateProjection,
|
||||
ShippingProcessGateStatus,
|
||||
@@ -23,6 +24,7 @@ export type {
|
||||
ShippingInventorySourceLineBlockReasonCode,
|
||||
ShippingInventorySourceUnavailableReasonCode,
|
||||
ShippingProcessGateActionCode,
|
||||
ShippingProcessGateActionPresentation,
|
||||
ShippingProcessGateCode,
|
||||
ShippingProcessGateProjection,
|
||||
ShippingProcessGateStatus,
|
||||
|
||||
@@ -87,18 +87,35 @@ describe('resolveProcessingActionPresentation', () => {
|
||||
availableActions: ['retry_parse', 'view_result'],
|
||||
uiState: {
|
||||
status: 'waiting_human', stage: 'fulfillment_prep', blocking_reason: null,
|
||||
primary_action: { code: 'open_inventory_source_review', i18nKey: 'action.open_inventory_source_review', parameters: {} },
|
||||
primary_action: { code: 'retry_inventory_preparation', i18nKey: 'action.retry_inventory_preparation', parameters: {} },
|
||||
secondary_actions: [
|
||||
{ code: 'view_details', enabled: true },
|
||||
{ code: 'retry_parse', enabled: false },
|
||||
],
|
||||
},
|
||||
}));
|
||||
expect(result.primary?.actionCode).toBe('open_inventory_source_review');
|
||||
expect(result.primary?.actionCode).toBe('retry_inventory_preparation');
|
||||
expect(result.secondary?.actionCode).toBe('view_details');
|
||||
expect(result.overflow).toEqual([]);
|
||||
});
|
||||
|
||||
it('renders the backend-authorized extraction retry without consulting legacy actions', () => {
|
||||
const result = resolveProcessingActionPresentation(projection({
|
||||
availableActions: ['open_order_review'],
|
||||
uiState: {
|
||||
status: 'failed', stage: 'document_parsing', blocking_reason: {
|
||||
code: 'SHIPPING_NOTICE.ORDER_EXTRACTION_RUN_SNAPSHOT_OBSOLETE', details: {},
|
||||
},
|
||||
primary_action: { code: 'retry_order_extraction', i18nKey: null, parameters: {} },
|
||||
secondary_actions: [],
|
||||
},
|
||||
}), { surface: 'right' });
|
||||
|
||||
expect(result.primary).toMatchObject({
|
||||
intent: 'retry', actionCode: 'retry_order_extraction',
|
||||
});
|
||||
});
|
||||
|
||||
it('uses the backend intake parse target for the navigation label', () => {
|
||||
const result = resolveProcessingActionPresentation(projection({
|
||||
uiState: {
|
||||
@@ -167,11 +184,22 @@ describe('resolveProcessingActionPresentation', () => {
|
||||
|
||||
expect(result.primary).toMatchObject({
|
||||
actionCode: 'retry_inventory_preparation',
|
||||
labelKey: 'workspace.shippingNotice.processGate.actionCodes.retry_inventory_preparation',
|
||||
labelKey: 'workspace.shippingNotice.processGate.inventoryActions.retryInventoryPreparation',
|
||||
});
|
||||
expect(result.secondary).toBeNull();
|
||||
});
|
||||
|
||||
it('uses the shared inventory presentation for a rematch action', () => {
|
||||
const result = resolveProcessingActionPresentation(projection({
|
||||
availableActions: ['retry_inventory_matching'],
|
||||
}), { surface: 'right' });
|
||||
|
||||
expect(result.primary).toMatchObject({
|
||||
actionCode: 'retry_inventory_matching',
|
||||
labelKey: 'workspace.shippingNotice.processGate.inventoryActions.retryInventoryMatching',
|
||||
});
|
||||
});
|
||||
|
||||
it('filters open_order_review and refresh on review surface', () => {
|
||||
const result = resolveProcessingActionPresentation(projection({
|
||||
availableActions: ['open_order_review', 'refresh', 'view_result'],
|
||||
|
||||
Loaded 100 of 466 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user