feat(shipping-notice): 落地 XFA 拆分、版面签名、统一进度与处理域履约
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
3a9fbac2fc
commit
d2b3d74def
571 files changed
+78064
-24681
No files matched your search
@@ -44,14 +44,25 @@ export type ShippingAuditDiffRow = {
|
||||
after: unknown;
|
||||
};
|
||||
|
||||
export type ShippingAuditXfaSnapshotRef = {
|
||||
purpose: string;
|
||||
snapshot_ref: string;
|
||||
plaintext_sha256?: string | null;
|
||||
};
|
||||
|
||||
export type ShippingAuditEventDetail = ShippingAuditEventSummary & {
|
||||
before_snapshot?: Record<string, unknown> | null;
|
||||
after_snapshot?: Record<string, unknown> | null;
|
||||
before_hash?: string | null;
|
||||
after_hash?: string | null;
|
||||
diff?: ShippingAuditDiffRow[];
|
||||
diff_json?: Record<string, unknown> | null;
|
||||
metadata?: Record<string, unknown>;
|
||||
evidence_refs?: Array<Record<string, unknown>>;
|
||||
artifact_refs?: Array<Record<string, unknown>>;
|
||||
context_refs?: Record<string, unknown>;
|
||||
has_xfa_full_snapshots?: boolean;
|
||||
xfa_snapshot_refs?: ShippingAuditXfaSnapshotRef[];
|
||||
};
|
||||
|
||||
export type ShippingAuditFilters = {
|
||||
@@ -129,6 +140,22 @@ export function getShippingAuditEvent(eventId: number) {
|
||||
);
|
||||
}
|
||||
|
||||
export type ShippingAuditXfaSnapshotDetail = {
|
||||
summary: Record<string, unknown>;
|
||||
payload: Record<string, unknown> | null;
|
||||
sensitive_redacted: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* 按需读取 XFA 加密完整快照;后端按 audit_sensitive_read 裁剪并再写访问审计。
|
||||
*/
|
||||
export function getShippingXfaAuditSnapshot(snapshotRef: string) {
|
||||
return requestJson<ShippingAuditXfaSnapshotDetail>(
|
||||
`/api/admin/shipping-notice/audit-snapshots/${encodeURIComponent(snapshotRef)}`,
|
||||
auth(),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 按 Workflow / Item / Run / PDF / Case / Task 关联键追溯全链。
|
||||
*/
|
||||
|
||||
@@ -13,7 +13,6 @@ import type {
|
||||
CoordinateReconstructionSuggestion,
|
||||
OrderFieldLayoutSuggestionResponse,
|
||||
OrderFieldValuePreviewResponse,
|
||||
CoordinateReconstructionSettings,
|
||||
OrderProfileSampleIntake,
|
||||
OrderProfileSamplePreview,
|
||||
OrderProfilePreviewPages,
|
||||
@@ -197,16 +196,6 @@ export const getOrderProfileSampleTables = (documentId: number) =>
|
||||
);
|
||||
|
||||
/** 以管理员确认的相对列边界生成坐标重建候选;结果始终待人工审核。 */
|
||||
export const previewOrderProfileCoordinateReconstruction = (
|
||||
documentId: number, tableId: string, coordinateReconstruction: CoordinateReconstructionSettings,
|
||||
) => requestJson<CoordinateReconstructionPreview>(
|
||||
'/api/admin/shipping-notice/order-document-profile-samples/coordinate-reconstruction-preview', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ document_id: documentId, table_id: tableId, coordinate_reconstruction: coordinateReconstruction }),
|
||||
...jsonAuth(),
|
||||
},
|
||||
);
|
||||
|
||||
/** 从冻结字符坐标建议全部或指定物理行;rowOffset 省略时保持原有全量识别。 */
|
||||
export const suggestOrderProfileCoordinateReconstruction = (
|
||||
documentId: number, tableId: string, rowOffset?: number, schemaVersionId?: number,
|
||||
@@ -255,7 +244,9 @@ export const completeOrderDocumentProfileWizard = (payload: {
|
||||
display_name: string;
|
||||
schema_version_id: number;
|
||||
document_id: number;
|
||||
main_table_id: string;
|
||||
main_table_id?: string;
|
||||
authoritative_collection_path_id?: string;
|
||||
mirror_collection_path_ids?: string[];
|
||||
browser_session_id: string;
|
||||
operation_id: string;
|
||||
}) => requestJson<ShippingOrderDocumentProfile & {
|
||||
@@ -265,6 +256,45 @@ export const completeOrderDocumentProfileWizard = (payload: {
|
||||
{ method: 'POST', body: JSON.stringify(payload), ...jsonAuth() },
|
||||
);
|
||||
|
||||
/** 读取样本文档 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`,
|
||||
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`,
|
||||
auth(),
|
||||
);
|
||||
|
||||
/** 按 path_id 读取分级样本值;reveal=true 要求敏感读权限并产生完整访问审计。 */
|
||||
export const previewOrderProfileSampleXfaValue = (documentId: number, pathId: string, reveal = false) =>
|
||||
requestJson<import('../types/shipping-order-document-profile.types').XfaValuePreviewResponse>(
|
||||
`/api/admin/shipping-notice/order-document-profile-samples/${documentId}/xfa/value-preview`,
|
||||
{ method: 'POST', body: JSON.stringify({ path_id: pathId, reveal }), ...jsonAuth() },
|
||||
);
|
||||
|
||||
/** 预览拆分规则执行结果;reveal=true 需 audit_sensitive_read,返回完整值并写访问审计。 */
|
||||
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`,
|
||||
{ method: 'POST', body: JSON.stringify(payload), ...jsonAuth() },
|
||||
);
|
||||
|
||||
/** 校验 Profile 拆分规则契约与 Schema 映射;不持久化。 */
|
||||
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`,
|
||||
{ method: 'POST', body: JSON.stringify(payload), ...jsonAuth() },
|
||||
);
|
||||
|
||||
/** 冻结建议决定;接受后的实际区域修改仍由当前草稿保存接口统一写入 Revision。 */
|
||||
export const decideOrderDocumentProfileSuggestion = (profileId: number, payload: {
|
||||
suggestion_id: string;
|
||||
@@ -296,15 +326,36 @@ export const runOrderProfileInstantCheck = (profileId: number, payload: {
|
||||
|
||||
/** 在绑定 annotation/training 样本上试运行;接口不会接受或回显盲测真值。 */
|
||||
export const runOrderProfileCurrentSample = (profileId: number, payload: {
|
||||
sample_binding_id: number; browser_session_id: string; lease_token: string; operation_id: string;
|
||||
sample_binding_id?: number; 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/current-sample`,
|
||||
{ method: 'POST', body: JSON.stringify(payload), ...jsonAuth() },
|
||||
);
|
||||
|
||||
/** 生成当前草稿版面签名;服务端更新 Profile 轻量引用,不接收前端 matcher 分数。 */
|
||||
export const runOrderProfileLayoutSignature = (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`,
|
||||
{ method: 'POST', body: JSON.stringify(payload), ...jsonAuth() },
|
||||
);
|
||||
|
||||
/** 执行跨模板唯一性验证;可附带 auto_generate_signature 请求体字段。 */
|
||||
export const runOrderProfileCrossTemplateOverlap = (profileId: number, payload: {
|
||||
browser_session_id: string; lease_token: string; operation_id: string; auto_generate_signature?: boolean;
|
||||
}) => requestJson<import('@/features/admin/types/shipping-order-document-profile.types').OrderProfileValidationRun>(
|
||||
`/api/admin/shipping-notice/order-document-profiles/${profileId}/validation-runs/cross-template-overlap`,
|
||||
{ method: 'POST', body: JSON.stringify(payload), ...jsonAuth() },
|
||||
);
|
||||
|
||||
/** 创建不可变发布检查报告;必须指定与当前草稿 checksum 一致的通过验证运行。 */
|
||||
export const createOrderProfilePublishCheck = (profileId: number, payload: {
|
||||
validation_run_id: number; browser_session_id: string; lease_token: string; operation_id: string;
|
||||
validation_run_id: number;
|
||||
matching_signature_run_id?: number;
|
||||
overlap_validation_run_id?: number;
|
||||
browser_session_id: string;
|
||||
lease_token: string;
|
||||
operation_id: string;
|
||||
}) => requestJson<import('@/features/admin/types/shipping-order-document-profile.types').OrderProfilePublishCheckReport>(
|
||||
`/api/admin/shipping-notice/order-document-profiles/${profileId}/publish-checks`,
|
||||
{ method: 'POST', body: JSON.stringify(payload), ...jsonAuth() },
|
||||
@@ -452,7 +503,7 @@ export const previewOrderProfileBlindTestCandidate = (suiteId: number, payload:
|
||||
`/api/admin/shipping-notice/order-document-profile-test-suites/${suiteId}/candidate-preview`, { method: 'POST', body: JSON.stringify(payload), ...jsonAuth() },
|
||||
);
|
||||
/** 将逐项勾选和必要更正值转为既有盲测真值。 */
|
||||
export const confirmOrderProfileBlindTestReviews = (suiteId: number, payload: { document_id: number; table_id: string; row_reviews: unknown[]; order_field_reviews: Record<string, unknown> }) => requestJson<OrderProfileTestSuite>(
|
||||
export const confirmOrderProfileBlindTestReviews = (suiteId: number, payload: { document_id: number; table_id: string; layout_version_id: number; layout_payload_checksum: string; row_reviews: unknown[]; order_field_reviews: Record<string, unknown> }) => requestJson<OrderProfileTestSuite>(
|
||||
`/api/admin/shipping-notice/order-document-profile-test-suites/${suiteId}/reviewed-samples`, { method: 'POST', body: JSON.stringify(payload), ...jsonAuth() },
|
||||
);
|
||||
|
||||
|
||||
@@ -365,6 +365,7 @@ onMounted(() => {
|
||||
>
|
||||
<option value="">{{ t('admin.shippingAudit.filters.all') }}</option>
|
||||
<option value="review_workbench">{{ t('admin.shippingAudit.filters.eventTypeGroupReviewWorkbench') }}</option>
|
||||
<option value="formal_task_edit">{{ t('admin.shippingAudit.filters.eventTypeGroupFormalTaskEdit') }}</option>
|
||||
<option value="chat_workbench">{{ t('admin.shippingAudit.filters.eventTypeGroupChatWorkbench') }}</option>
|
||||
<option value="process_gate">{{ t('admin.shippingAudit.filters.eventTypeGroupProcessGate') }}</option>
|
||||
<option value="candidate_qualification">{{ t('admin.shippingAudit.filters.eventTypeGroupQualification') }}</option>
|
||||
|
||||
+4
@@ -36,6 +36,10 @@ const messages = {
|
||||
copyId: '复制编号',
|
||||
techRefsHint: '技术编号默认折叠展示,点击即可复制。',
|
||||
hashSection: '哈希摘要(排障用)',
|
||||
beforeHash: '变更前 checksum',
|
||||
afterHash: '变更后 checksum',
|
||||
xfaSnapshots: 'XFA 完整快照引用',
|
||||
xfaSnapshotsHint: '完整密文需敏感读权限按需打开;此处仅展示引用与用途。',
|
||||
columns: {
|
||||
event: '事件',
|
||||
actor: '操作者',
|
||||
|
||||
+38
-2
@@ -1,9 +1,10 @@
|
||||
<!--
|
||||
features/admin/modules/shipping-audit/ShippingAuditEventDetailDrawer.vue
|
||||
用途:审计事件详情抽屉——业务化元数据、敏感脱敏提示、白名单 Diff、哈希摘要。
|
||||
用途:审计事件详情抽屉——业务化元数据、敏感脱敏提示、白名单 Diff、XFA 快照引用、哈希摘要。
|
||||
依赖:shipping-audit.api 类型、shippingAuditDisplay、Vue I18n、useMessage。
|
||||
逻辑:由 ShippingAuditCenterPage 传入 detail;事件/动作/结果与列表同源业务标签;
|
||||
技术编号以复制芯片展示;关闭时 emit close;不自行拉接口。
|
||||
展示 before/after checksum 与 XFA snapshot_ref;技术编号以复制芯片展示;
|
||||
关闭时 emit close;不自行拉接口。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue';
|
||||
@@ -164,9 +165,44 @@ function onClose() {
|
||||
<dt class="text-muted">{{ t('admin.shippingAudit.previousEventHash') }}</dt>
|
||||
<dd class="break-all font-mono text-[10px]">{{ detail.previous_event_hash || '—' }}</dd>
|
||||
</div>
|
||||
<div v-if="detail.before_hash">
|
||||
<dt class="text-muted">{{ t('admin.shippingAudit.beforeHash') }}</dt>
|
||||
<dd class="break-all font-mono text-[10px]" data-testid="shipping-audit-before-hash">{{ detail.before_hash }}</dd>
|
||||
</div>
|
||||
<div v-if="detail.after_hash">
|
||||
<dt class="text-muted">{{ t('admin.shippingAudit.afterHash') }}</dt>
|
||||
<dd class="break-all font-mono text-[10px]" data-testid="shipping-audit-after-hash">{{ detail.after_hash }}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
</details>
|
||||
|
||||
<section
|
||||
v-if="detail.xfa_snapshot_refs?.length"
|
||||
class="mt-5"
|
||||
data-testid="shipping-audit-xfa-snapshots"
|
||||
>
|
||||
<h3 class="text-sm font-semibold">{{ t('admin.shippingAudit.xfaSnapshots') }}</h3>
|
||||
<p class="mt-1 text-[11px] text-muted">{{ t('admin.shippingAudit.xfaSnapshotsHint') }}</p>
|
||||
<ul class="mt-2 space-y-2">
|
||||
<li
|
||||
v-for="ref in detail.xfa_snapshot_refs"
|
||||
:key="ref.snapshot_ref"
|
||||
class="rounded-lg border border-default px-3 py-2 text-xs"
|
||||
>
|
||||
<div class="font-medium">{{ ref.purpose }}</div>
|
||||
<button
|
||||
type="button"
|
||||
class="mt-1 rounded border border-default px-2 py-0.5 font-mono text-[11px] text-muted"
|
||||
:title="ref.snapshot_ref"
|
||||
data-testid="shipping-audit-xfa-snapshot-ref"
|
||||
@click="copyTechId(ref.snapshot_ref)"
|
||||
>
|
||||
{{ t('admin.shippingAudit.copyId') }} · {{ ref.snapshot_ref.slice(0, 12) }}…
|
||||
</button>
|
||||
</li>
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
<h3 class="mt-6 font-semibold">{{ t('admin.shippingAudit.diff') }}</h3>
|
||||
<div v-if="detail.diff?.length" class="mt-2 space-y-2" data-testid="shipping-audit-diff-rows">
|
||||
<div
|
||||
|
||||
+80
-32
@@ -1,8 +1,9 @@
|
||||
<!--
|
||||
features/admin/modules/shipping-order-document-profiles/OrderProfileBlindTestPage.vue
|
||||
用途:维护订单模板草稿的独立盲测证据,并完成执行和批准。
|
||||
依赖:盲测 API、Vue Router、统一业务错误提示和四语言文案。
|
||||
逻辑:验证页进入本页;管理员选择未参与建模的样本、复核候选后写入真值,再执行并批准,最后回到发布检查。
|
||||
依赖:盲测 API、Profile 详情、Vue Router、统一业务错误提示和四语言文案。
|
||||
逻辑:验证页进入本页;coordinate 走表格候选,xfa_dataset 走文档级结构分析候选;
|
||||
管理员复核候选后写入真值,再执行并批准,最后回到发布检查。不回显盲测真值。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, onBeforeUnmount, onMounted, ref } from 'vue';
|
||||
@@ -16,10 +17,10 @@ import {
|
||||
createOrderProfileTestSuite,
|
||||
executeOrderProfileTestSuite,
|
||||
createOrderProfileSample,
|
||||
getOrderDocumentProfileDetail,
|
||||
getOrderProfileSampleStatus,
|
||||
listOrderProfileBlindTestAvailableSamples,
|
||||
listOrderProfileBoundSamples,
|
||||
listOrderProfileSamples,
|
||||
previewOrderProfileBlindTestCandidate,
|
||||
removeOrderProfileTestSample,
|
||||
} from '@/features/admin/api/shipping-order-document-profile.api';
|
||||
@@ -28,7 +29,9 @@ 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();
|
||||
@@ -37,9 +40,12 @@ 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);
|
||||
@@ -48,7 +54,7 @@ const hasTrainingSample = ref(false);
|
||||
const availableSamplesLoaded = ref(false);
|
||||
const availableSamplesLoading = ref(false);
|
||||
const uploadingSample = ref(false);
|
||||
const pendingUpload = ref<{ intakeNo: string; filename: string; state: 'parsing' | 'failed'; errorCode?: string | null } | null>(null);
|
||||
const pendingUpload = ref<{ intakeNo: string; filename: string; state: 'materializing' | 'failed'; errorCode?: string | null } | null>(null);
|
||||
let uploadPollingTimer: number | null = null;
|
||||
let availableSamplesController: AbortController | null = null;
|
||||
let availableSamplesTimeout: number | null = null;
|
||||
@@ -57,6 +63,17 @@ let availableSamplesTimeout: number | null = null;
|
||||
const selectedSample = computed(() => availableSamples.value.find((item) => `${item.document_id}:${item.table_id}` === selectedSampleKey.value) || null);
|
||||
/** 用安全表格摘要区分同页多表;内部 table_id 仅作为请求身份,绝不展示给管理员。 */
|
||||
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,
|
||||
@@ -80,6 +97,12 @@ const failureDetails = computed(() => (suite.value?.latest_run?.failure_codes ||
|
||||
if (parts[2] === 'coordinate_evidence_missing') {
|
||||
return { code, message: t('admin.shippingOrderProfiles.blindTest.failure.coordinateEvidenceMissing', { sample: sampleName }) };
|
||||
}
|
||||
if (parts[2] === 'xfa_evidence_missing') {
|
||||
return { code, message: t('admin.shippingOrderProfiles.blindTest.failure.xfaEvidenceMissing', { sample: sampleName }) };
|
||||
}
|
||||
if (parts[2] === 'line_count') {
|
||||
return { code, message: t('admin.shippingOrderProfiles.blindTest.failure.rowsMismatch', { sample: sampleName }) };
|
||||
}
|
||||
if (parts[2] === 'mismatch') {
|
||||
return { code, message: t('admin.shippingOrderProfiles.blindTest.failure.rowsMismatch', { sample: sampleName }) };
|
||||
}
|
||||
@@ -103,24 +126,24 @@ function report(error: unknown): void {
|
||||
const code = error instanceof BusinessError ? error.code : '';
|
||||
message.error(code ? t(`errors.${code}`, code) : t('admin.orderProfileValidation.failed'));
|
||||
}
|
||||
/** 将模板布局失败码转成盲测页可执行的提示,不向管理员回显内部快照数据。 */
|
||||
function sampleFailureMessage(errorCode?: string | null): string {
|
||||
const key = errorCode === 'mineru_cell_coordinates_missing'
|
||||
? 'sampleLayoutCoordinatesMissing'
|
||||
: errorCode === 'shipping_document_layout_snapshot_size_exceeded'
|
||||
? 'sampleLayoutSnapshotTooLarge'
|
||||
: 'sampleParseFailed';
|
||||
return t(`admin.shippingOrderProfiles.wizard.${key}`);
|
||||
/** 将文件物化失败转成安全提示;版面错误只允许在预览复核阶段出现。 */
|
||||
function sampleFailureMessage(): string {
|
||||
return t('admin.shippingOrderProfiles.blindTest.sampleMaterializationFailed');
|
||||
}
|
||||
|
||||
/** 创建或读取当前草稿 checksum 对应的盲测集;候选样本按需加载,避免进入页面时扫描全部历史样本。 */
|
||||
async function loadSuite(): Promise<void> {
|
||||
loading.value = true;
|
||||
try {
|
||||
const [nextSuite, boundSamples] = await Promise.all([
|
||||
const [nextSuite, boundSamples, profile] = 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) {
|
||||
@@ -130,9 +153,10 @@ async function loadSuite(): Promise<void> {
|
||||
}
|
||||
}
|
||||
|
||||
/** 按需读取独立样本摘要;上传解析完成时可强制刷新并定位刚上传的文档。 */
|
||||
/** 按需读取独立样本摘要;强制刷新会替换旧请求,确保定位刚物化的文档。 */
|
||||
async function loadAvailableSamples(force = false): Promise<void> {
|
||||
if (!suite.value || suite.value.status !== 'draft' || (!force && availableSamplesLoaded.value) || availableSamplesLoading.value) return;
|
||||
if (!suite.value || suite.value.status !== 'draft') return;
|
||||
if (!force && (availableSamplesLoaded.value || availableSamplesLoading.value)) return;
|
||||
availableSamplesController?.abort();
|
||||
if (availableSamplesTimeout) window.clearTimeout(availableSamplesTimeout);
|
||||
const controller = new AbortController();
|
||||
@@ -156,9 +180,9 @@ async function loadAvailableSamples(force = false): Promise<void> {
|
||||
if (availableSamplesController === controller) {
|
||||
availableSamplesController = null;
|
||||
availableSamplesLoading.value = false;
|
||||
if (availableSamplesTimeout) window.clearTimeout(availableSamplesTimeout);
|
||||
availableSamplesTimeout = null;
|
||||
}
|
||||
if (availableSamplesTimeout) window.clearTimeout(availableSamplesTimeout);
|
||||
availableSamplesTimeout = null;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -168,28 +192,36 @@ function stopUploadPolling(): void {
|
||||
uploadPollingTimer = null;
|
||||
}
|
||||
|
||||
/** 上传完成后精确选中同一 Intake 的首个可盲测表格,仍必须经过管理员预览和复核。 */
|
||||
/** 文件物化后精确选中同一 Intake 的候选;后台版面预热不参与上传成功判定。 */
|
||||
async function pollUploadedSample(intakeNo: string): Promise<void> {
|
||||
try {
|
||||
const result = await getOrderProfileSampleStatus(intakeNo);
|
||||
if (result.parse_status === 'parsed' && result.document_count > 0) {
|
||||
const uploaded = (await listOrderProfileSamples()).find((item) => item.intake_no === intakeNo);
|
||||
await loadAvailableSamples(true);
|
||||
const selected = uploaded && availableSamples.value.find((item) => item.document_id === uploaded.document_id);
|
||||
const selected = availableSamples.value.find((item) => (result.document_ids || []).includes(item.document_id));
|
||||
if (selected) {
|
||||
selectedSampleKey.value = `${selected.document_id}:${selected.table_id}`;
|
||||
pendingUpload.value = null;
|
||||
message.success(t('admin.shippingOrderProfiles.wizard.sampleReady'));
|
||||
message.success(t('admin.shippingOrderProfiles.blindTest.sampleUploaded'));
|
||||
} else {
|
||||
pendingUpload.value = { intakeNo, filename: pendingUpload.value?.filename || '', state: 'failed' };
|
||||
pendingUpload.value = null;
|
||||
message.success(t('admin.shippingOrderProfiles.blindTest.sampleUploaded'));
|
||||
message.error(t('admin.shippingOrderProfiles.blindTest.noIndependentSamples'));
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (['failed', 'error'].includes(result.parse_status)) {
|
||||
pendingUpload.value = {
|
||||
intakeNo, filename: pendingUpload.value?.filename || '', state: 'failed', errorCode: result.error_code,
|
||||
};
|
||||
await loadAvailableSamples(true);
|
||||
const selected = availableSamples.value.find((item) => (result.document_ids || []).includes(item.document_id));
|
||||
if (selected) {
|
||||
selectedSampleKey.value = `${selected.document_id}:${selected.table_id}`;
|
||||
pendingUpload.value = null;
|
||||
message.success(t('admin.shippingOrderProfiles.blindTest.sampleAcceptedForReview'));
|
||||
} else {
|
||||
pendingUpload.value = {
|
||||
intakeNo, filename: pendingUpload.value?.filename || '', state: 'failed', errorCode: result.error_code,
|
||||
};
|
||||
}
|
||||
return;
|
||||
}
|
||||
uploadPollingTimer = window.setTimeout(() => void pollUploadedSample(intakeNo), 1500);
|
||||
@@ -213,7 +245,7 @@ async function uploadIndependentSample(event: Event): Promise<void> {
|
||||
try {
|
||||
const asset = await uploadFileAsset(file);
|
||||
const intake = await createOrderProfileSample(asset.asset_no);
|
||||
pendingUpload.value = { intakeNo: intake.intake_no, filename: file.name, state: 'parsing' };
|
||||
pendingUpload.value = { intakeNo: intake.intake_no, filename: file.name, state: 'materializing' };
|
||||
void pollUploadedSample(intake.intake_no);
|
||||
} catch (error) {
|
||||
report(error);
|
||||
@@ -225,6 +257,10 @@ async function uploadIndependentSample(event: Event): Promise<void> {
|
||||
/** 运行选中独立样本并初始化逐行、逐订单字段的人工复核表单。 */
|
||||
async function previewSample(): Promise<void> {
|
||||
if (!suite.value || !selectedSample.value) return;
|
||||
if (selectedSample.value.review_mode === 'preparing') {
|
||||
message.error(t('admin.shippingOrderProfiles.blindTest.reviewPreparing'));
|
||||
return;
|
||||
}
|
||||
working.value = true;
|
||||
try {
|
||||
candidate.value = await previewOrderProfileBlindTestCandidate(suite.value.id, selectedSample.value);
|
||||
@@ -262,7 +298,8 @@ function reviewedRows(): Array<Record<string, unknown>> | null {
|
||||
|
||||
/** 提交全量人工复核,将候选结果或管理员更正转换为服务端受保护的盲测真值。 */
|
||||
async function confirmReview(): Promise<void> {
|
||||
if (!suite.value || !candidate.value) return;
|
||||
if (!suite.value || !candidate.value || !candidate.value.confirmable
|
||||
|| !candidate.value.layout_version_id || !candidate.value.layout_payload_checksum) return;
|
||||
const reviews = reviewedRows();
|
||||
if (!reviews) return;
|
||||
working.value = true;
|
||||
@@ -270,6 +307,8 @@ async function confirmReview(): Promise<void> {
|
||||
suite.value = await confirmOrderProfileBlindTestReviews(suite.value.id, {
|
||||
document_id: candidate.value.document_id,
|
||||
table_id: candidate.value.table_id,
|
||||
layout_version_id: candidate.value.layout_version_id,
|
||||
layout_payload_checksum: candidate.value.layout_payload_checksum,
|
||||
row_reviews: reviews,
|
||||
order_field_reviews: Object.fromEntries(Object.entries(orderFieldReviews.value).map(([fieldKey, review]) => [
|
||||
fieldKey,
|
||||
@@ -282,6 +321,11 @@ async function confirmReview(): Promise<void> {
|
||||
availableSamples.value = [];
|
||||
message.success(t('admin.shippingOrderProfiles.blindTest.addedSamples'));
|
||||
} catch (error) {
|
||||
if (error instanceof BusinessError && error.code === 'SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_PREVIEW_STALE') {
|
||||
candidate.value = null;
|
||||
selectedSampleKey.value = '';
|
||||
await loadAvailableSamples(true);
|
||||
}
|
||||
report(error);
|
||||
} finally {
|
||||
working.value = false;
|
||||
@@ -357,13 +401,16 @@ onBeforeUnmount(() => {
|
||||
<template>
|
||||
<section class="blind-test-page">
|
||||
<header>
|
||||
<div><h1 class="section-title">{{ t('admin.shippingOrderProfiles.blindTest.title') }}</h1><p class="section-desc mt-1">{{ t('admin.shippingOrderProfiles.blindTest.reviewHint') }}</p></div>
|
||||
<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>
|
||||
</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>
|
||||
|
||||
<p v-if="loading">{{ t('admin.orderProfileValidation.loading') }}</p>
|
||||
<template v-else-if="suite">
|
||||
<section class="card suite-summary"><div><h2>{{ t('admin.shippingOrderProfiles.blindTest.samples', { count: suite.sample_count, status: t(`admin.shippingOrderProfiles.versionCenter.testStatus.${suite.status}`) }) }}</h2><p v-if="suite.latest_run">{{ t('admin.shippingOrderProfiles.blindTest.latestResult', { status: suite.latest_run.status, passed: suite.latest_run.passed_sample_count, count: suite.latest_run.sample_count }) }}</p><p v-else>{{ t('admin.shippingOrderProfiles.blindTest.notRun') }}</p></div><span :class="`status ${suite.status}`">{{ t(`admin.shippingOrderProfiles.versionCenter.testStatus.${suite.status}`) }}</span></section>
|
||||
<section class="card suite-summary"><div><h2>{{ t('admin.shippingOrderProfiles.blindTest.samples', { count: suite.sample_count, required: 1, status: t(`admin.shippingOrderProfiles.versionCenter.testStatus.${suite.status}`) }) }}</h2><p v-if="suite.latest_run">{{ t('admin.shippingOrderProfiles.blindTest.latestResult', { status: suite.latest_run.status, passed: suite.latest_run.passed_sample_count, count: suite.latest_run.sample_count }) }}</p><p v-else>{{ t('admin.shippingOrderProfiles.blindTest.notRun') }}</p></div><span :class="`status ${suite.status}`">{{ t(`admin.shippingOrderProfiles.versionCenter.testStatus.${suite.status}`) }}</span></section>
|
||||
|
||||
<section v-if="failureDetails.length" class="card failure-details">
|
||||
<div><h2>{{ t('admin.shippingOrderProfiles.blindTest.failure.title') }}</h2><p>{{ t('admin.shippingOrderProfiles.blindTest.failure.hint') }}</p></div>
|
||||
@@ -373,12 +420,13 @@ onBeforeUnmount(() => {
|
||||
<section v-if="suite.status === 'draft'" class="card">
|
||||
<div class="sample-heading"><h2>{{ t('admin.shippingOrderProfiles.blindTest.selectIndependentSample') }}</h2><label class="btn-secondary upload-sample"><input type="file" accept=".pdf,.eml,application/pdf,message/rfc822" :disabled="uploadingSample" @change="uploadIndependentSample"><span>{{ uploadingSample ? t('admin.shippingOrderProfiles.wizard.uploading') : t('admin.shippingOrderProfiles.blindTest.uploadSample') }}</span></label></div>
|
||||
<p v-if="availableSamplesLoaded && !availableSamples.length">{{ t('admin.shippingOrderProfiles.blindTest.noIndependentSamples') }}</p>
|
||||
<div class="sample-picker"><button v-if="!availableSamplesLoaded" type="button" class="btn-secondary" :disabled="availableSamplesLoading" @click="() => void loadAvailableSamples()">{{ availableSamplesLoading ? t('admin.shippingOrderProfiles.blindTest.loadingIndependentSamples') : t('admin.shippingOrderProfiles.blindTest.loadIndependentSamples') }}</button><template v-else-if="availableSamples.length"><select v-model="selectedSampleKey" class="select-field"><option value="">{{ t('admin.shippingOrderProfiles.blindTest.selectSamplePlaceholder') }}</option><option v-for="sample in availableSamples" :key="`${sample.document_id}:${sample.table_id}`" :value="`${sample.document_id}:${sample.table_id}`">{{ sampleLabel(sample) }}</option></select><button type="button" class="btn-primary" :disabled="!selectedSample || working" @click="previewSample">{{ t('admin.shippingOrderProfiles.blindTest.previewAndReview') }}</button></template></div>
|
||||
<p v-if="pendingUpload" class="upload-status" :class="{ failed: pendingUpload.state === 'failed' }">{{ pendingUpload.filename }} · {{ pendingUpload.state === 'parsing' ? t('admin.shippingOrderProfiles.wizard.sampleParsing') : sampleFailureMessage(pendingUpload.errorCode) }}</p>
|
||||
<div class="sample-picker"><button v-if="!availableSamplesLoaded" type="button" class="btn-secondary" :disabled="availableSamplesLoading" @click="() => void loadAvailableSamples()">{{ availableSamplesLoading ? t('admin.shippingOrderProfiles.blindTest.loadingIndependentSamples') : t('admin.shippingOrderProfiles.blindTest.loadIndependentSamples') }}</button><template v-else-if="availableSamples.length"><select v-model="selectedSampleKey" class="select-field"><option value="">{{ t('admin.shippingOrderProfiles.blindTest.selectSamplePlaceholder') }}</option><option v-for="sample in availableSamples" :key="`${sample.document_id}:${sample.table_id}`" :value="`${sample.document_id}:${sample.table_id}`">{{ sampleLabel(sample) }}</option></select><button type="button" class="btn-primary" :disabled="!selectedSample || selectedSample.review_mode === 'preparing' || working" @click="previewSample">{{ selectedSample?.review_mode === 'preparing' ? t('admin.shippingOrderProfiles.blindTest.reviewPreparing') : selectedSample?.review_mode === 'diagnostic' ? t('admin.shippingOrderProfiles.blindTest.viewDiagnostic') : t('admin.shippingOrderProfiles.blindTest.previewAndReview') }}</button><button type="button" class="btn-secondary" :disabled="availableSamplesLoading" @click="() => void loadAvailableSamples(true)">{{ t('admin.shippingOrderProfiles.blindTest.refreshSamples') }}</button></template></div>
|
||||
<p v-if="pendingUpload" class="upload-status" :class="{ failed: pendingUpload.state === 'failed' }">{{ pendingUpload.filename }} · {{ pendingUpload.state === 'materializing' ? t('admin.shippingOrderProfiles.blindTest.sampleMaterializing') : sampleFailureMessage() }}</p>
|
||||
</section>
|
||||
|
||||
<section v-if="candidate" class="card candidate-card">
|
||||
<h2>{{ t('admin.shippingOrderProfiles.blindTest.reviewHint') }}</h2>
|
||||
<p v-if="!candidate.confirmable" class="training-required">{{ t('admin.shippingOrderProfiles.blindTest.diagnosticOnly') }}</p>
|
||||
<p v-if="!candidate.rows.length">{{ t('admin.shippingOrderProfiles.blindTest.candidateRowsEmpty') }}</p>
|
||||
<article v-for="(row, index) in candidate.rows" :key="index" class="review-item">
|
||||
<template v-if="rowReviews[index]">
|
||||
@@ -392,7 +440,7 @@ onBeforeUnmount(() => {
|
||||
<label><input :checked="orderFieldReview(orderFieldKey(field)).correct" type="checkbox" @change="updateOrderFieldReview(orderFieldKey(field), { correct: ($event.target as HTMLInputElement).checked })">{{ t('admin.shippingOrderProfiles.blindTest.correct') }}</label>
|
||||
<input v-if="!orderFieldReview(orderFieldKey(field)).correct" class="input-field" :value="orderFieldReview(orderFieldKey(field)).value" :placeholder="t('admin.shippingOrderProfiles.blindTest.correctedValue')" @input="updateOrderFieldReview(orderFieldKey(field), { value: ($event.target as HTMLInputElement).value })">
|
||||
</article>
|
||||
<button type="button" class="btn-primary" :disabled="working || !candidate.rows.length" @click="confirmReview">{{ t('admin.shippingOrderProfiles.blindTest.confirmReview') }}</button>
|
||||
<button v-if="candidate.confirmable" type="button" class="btn-primary" :disabled="working || !candidate.rows.length" @click="confirmReview">{{ t('admin.shippingOrderProfiles.blindTest.confirmReview') }}</button>
|
||||
</section>
|
||||
|
||||
<section class="card"><h2>{{ t('admin.shippingOrderProfiles.blindTest.addedSamples') }}</h2><p>{{ t('admin.shippingOrderProfiles.blindTest.addedSamplesHint') }}</p><ul v-if="suite.samples.length"><li v-for="sample in suite.samples" :key="sample.id"><span>{{ sample.filename }} · P{{ sample.page_no }}</span><button v-if="suite.status === 'draft'" type="button" class="btn-secondary btn-sm" :disabled="working" @click="removeSample(sample.id)">{{ t('admin.shippingOrderProfiles.blindTest.removeSample') }}</button></li></ul><p v-else>{{ t('admin.shippingOrderProfiles.blindTest.noIndependentSamples') }}</p></section>
|
||||
|
||||
+74
-16
@@ -1,8 +1,8 @@
|
||||
<!--
|
||||
features/admin/modules/shipping-order-document-profiles/OrderProfileCreateWizardPage.vue
|
||||
用途:以三步向导创建订单文档模板草稿。
|
||||
依赖:Schema/样本/表格 API、步骤组件和 Vue Router。
|
||||
逻辑:首步仅收集业务名称和 Schema;最后一步由服务端生成系统编码并原子创建草稿、样本绑定、Revision 与 Lease。
|
||||
用途:以三步向导创建订单文档模板草稿(坐标或 XFA 自动分流)。
|
||||
依赖:Schema/样本/表格/XFA API、步骤组件和 Vue Router。
|
||||
逻辑:样本 xfa_analysis_ready 时第三步改为集合确认;否则保持表格选择;原子创建草稿与 Lease。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, onBeforeUnmount, onMounted, reactive, ref, watch } from 'vue';
|
||||
@@ -13,10 +13,12 @@ import { BusinessError } from '@/shared/api/client';
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
import { getShippingOrderSchemaState } from '@/features/admin/api/shipping-order-schema.api';
|
||||
import { completeOrderDocumentProfileWizard, getOrderProfileSampleTables, listOrderProfileSamples } from '@/features/admin/api/shipping-order-document-profile.api';
|
||||
import type { OrderProfileSampleDocument } from '@/features/admin/types/shipping-order-document-profile.types';
|
||||
import type { ShippingOrderSchemaVersion } from '@/features/admin/types/shipping-order-schema.types';
|
||||
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 };
|
||||
|
||||
@@ -27,21 +29,34 @@ const step = ref(1);
|
||||
const saving = ref(false);
|
||||
const schemas = ref<ShippingOrderSchemaVersion[]>([]);
|
||||
const schemasResolved = ref(false);
|
||||
const samples = ref<Array<{ document_id: number; intake_no: string; filename?: string | null; table_count: number }>>([]);
|
||||
const samples = ref<OrderProfileSampleDocument[]>([]);
|
||||
const tables = ref<Array<{ table_id: string; page_no: number; row_count: number; column_count: number; rows: string[][] }>>([]);
|
||||
const identity = reactive<Identity>({ displayName: '', schemaId: 0 });
|
||||
const documentId = ref(0);
|
||||
const tableId = ref('');
|
||||
const authoritativePathId = ref('');
|
||||
const mirrorPathIds = ref<string[]>([]);
|
||||
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 canNext = computed(() => step.value === 1
|
||||
? Boolean(identity.displayName.trim() && identity.schemaId)
|
||||
: step.value === 2 ? Boolean(documentId.value) : Boolean(tableId.value));
|
||||
const stepThreeLabel = computed(() => (
|
||||
isXfaSample.value
|
||||
? t('admin.shippingOrderProfiles.wizard.xfa.stepTitle')
|
||||
: 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(authoritativePathId.value);
|
||||
return Boolean(tableId.value);
|
||||
});
|
||||
const steps = computed(() => [
|
||||
{ number: 1, label: t('admin.shippingOrderProfiles.wizard.identityStep'), icon: FileText },
|
||||
{ number: 2, label: t('admin.shippingOrderProfiles.wizard.sampleStep'), icon: Layers3 },
|
||||
{ number: 3, label: t('admin.shippingOrderProfiles.wizard.tableStep'), icon: Sparkles },
|
||||
{ number: 3, label: stepThreeLabel.value, icon: Sparkles },
|
||||
]);
|
||||
|
||||
/** 接收首步身份快照;父级单一状态驱动下一步校验,避免子组件对象替换造成状态不同步。 */
|
||||
@@ -49,6 +64,7 @@ function updateIdentity(next: Identity): void {
|
||||
identity.displayName = next.displayName;
|
||||
identity.schemaId = next.schemaId;
|
||||
}
|
||||
|
||||
/** 加载可用 Schema 与已解析样本;失败不创建或缓存任何 Profile。 */
|
||||
async function loadContext(): Promise<void> {
|
||||
try {
|
||||
@@ -60,16 +76,19 @@ async function loadContext(): Promise<void> {
|
||||
message.error(error instanceof BusinessError ? error.message : t('admin.shippingOrderProfiles.wizard.loadFailed'));
|
||||
}
|
||||
}
|
||||
|
||||
/** 刷新上传后的样本库;轮询失败静默处理,避免短暂网络异常持续弹出提示。 */
|
||||
async function refreshSamples(showError = true): Promise<void> {
|
||||
try { samples.value = await listOrderProfileSamples(); }
|
||||
catch { if (showError) message.error(t('admin.shippingOrderProfiles.wizard.loadFailed')); }
|
||||
}
|
||||
|
||||
/** 仅在第二步保持已解析文档列表为最新,离开步骤后立即停止。 */
|
||||
function stopSampleRefresh(): void {
|
||||
if (sampleRefreshTimer !== null) clearTimeout(sampleRefreshTimer);
|
||||
sampleRefreshTimer = null;
|
||||
}
|
||||
|
||||
function scheduleSampleRefresh(): void {
|
||||
stopSampleRefresh();
|
||||
if (step.value !== 2) return;
|
||||
@@ -77,22 +96,32 @@ function scheduleSampleRefresh(): void {
|
||||
if (step.value === 2) sampleRefreshTimer = setTimeout(scheduleSampleRefresh, 2000);
|
||||
});
|
||||
}
|
||||
/** 加载选定样本的可用表格;单表场景由下一步直接作为订单明细表。 */
|
||||
|
||||
/** 加载选定样本的可用表格;XFA 样本跳过表格加载。 */
|
||||
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 = [];
|
||||
tables.value = [];
|
||||
if (!id) return;
|
||||
await loadTables(id);
|
||||
});
|
||||
|
||||
watch(step, (currentStep) => {
|
||||
if (currentStep === 2) scheduleSampleRefresh();
|
||||
else stopSampleRefresh();
|
||||
});
|
||||
/** 前进仅校验当前步骤;单表直接创建,多表才要求管理员确认订单明细表。 */
|
||||
|
||||
/** 前进仅校验当前步骤;XFA 样本进入集合确认,单表坐标样本可直接创建。 */
|
||||
async function next(): Promise<void> {
|
||||
if (!canNext.value) {
|
||||
message.error(step.value === 1 && !publishedSchemas.value.length
|
||||
@@ -101,6 +130,10 @@ 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) {
|
||||
@@ -115,16 +148,31 @@ async function next(): Promise<void> {
|
||||
}
|
||||
if (step.value < 3) step.value += 1;
|
||||
}
|
||||
/** 单事务完成后进入草稿编辑路由;创建草稿和创建并进入标注共享同一审计动作。 */
|
||||
|
||||
/** 单事务完成后进入草稿编辑路由;XFA 与坐标共享同一审计动作入口。 */
|
||||
async function finish(enterEditor: boolean): Promise<void> {
|
||||
if (!canNext.value) return;
|
||||
saving.value = true;
|
||||
try {
|
||||
const profile = await completeOrderDocumentProfileWizard({
|
||||
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 = 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 profile = await completeOrderDocumentProfileWizard(payload);
|
||||
message.success(t('admin.shippingOrderProfiles.created'));
|
||||
await router.push(enterEditor
|
||||
? { name: 'AdminShippingOrderDocumentProfileEdit', params: { profileCode: profile.profile_code, profileId: profile.id }, query: { editorSessionId: browserSessionId } }
|
||||
@@ -133,6 +181,7 @@ async function finish(enterEditor: boolean): Promise<void> {
|
||||
message.error(error instanceof BusinessError ? error.message : t('admin.shippingOrderProfiles.wizard.createFailed'));
|
||||
} finally { saving.value = false; }
|
||||
}
|
||||
|
||||
onMounted(loadContext);
|
||||
onBeforeUnmount(stopSampleRefresh);
|
||||
</script>
|
||||
@@ -165,6 +214,15 @@ 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"
|
||||
/>
|
||||
<OrderProfileModelStartStep v-else v-model="tableId" :tables="tables" />
|
||||
</main>
|
||||
|
||||
|
||||
+14
-12
@@ -1,6 +1,6 @@
|
||||
<!--
|
||||
features/admin/modules/shipping-order-document-profiles/OrderProfileEditorPage.vue
|
||||
用途:订单坐标 Profile v2 的独立草稿标注编辑页。
|
||||
用途:订单坐标 Profile 的独立草稿标注编辑页。
|
||||
依赖:受控预览 API、Schema API、DocumentCanvas、IssuePanel、shippingOrderField.utils。
|
||||
逻辑:仅编辑由向导创建的草稿;起行锚点默认 customer_po_line_no(内部项次 line_no 亦可绑定);
|
||||
撤销/重做、自动保存和建议决定均受当前标签租约保护。
|
||||
@@ -51,6 +51,7 @@ import type {
|
||||
OrderProfileRowReconstructionMode,
|
||||
ShippingOrderDocumentProfile,
|
||||
} from "@/features/admin/types/shipping-order-document-profile.types";
|
||||
import { asCoordinateProfileDefinition } from "@/features/admin/types/shipping-order-document-profile.types";
|
||||
import type {
|
||||
ShippingOrderFieldConfig,
|
||||
ShippingOrderSchemaVersion,
|
||||
@@ -896,7 +897,6 @@ const definition = () => {
|
||||
};
|
||||
});
|
||||
return {
|
||||
contract_version: "order_coordinate_profile.v2" as const,
|
||||
document_match: {
|
||||
document_type: "purchase_order" as const,
|
||||
page_pattern: "one_or_more" as const,
|
||||
@@ -1528,8 +1528,9 @@ const mergeEquivalentOrderAnchors = (items: OrderProfileCanvasRegion[]) => {
|
||||
|
||||
/** 从 v2 定义恢复区域,供草稿重开后继续在画布上编辑。 */
|
||||
const restoreRegions = (profile: ShippingOrderDocumentProfile) => {
|
||||
const definition = asCoordinateProfileDefinition(profile.definition);
|
||||
for (const key of Object.keys(tableRegionSettings)) delete tableRegionSettings[Number(key)];
|
||||
for (const table of profile.definition.table_regions) {
|
||||
for (const table of definition.table_regions) {
|
||||
const regionPageNo = restoreOrderProfileRegionPageNo(table);
|
||||
tableRegionSettings[regionPageNo] = {
|
||||
rowReconstructionMode: table.row_reconstruction_mode || 'fixed_subrows',
|
||||
@@ -1537,7 +1538,7 @@ const restoreRegions = (profile: ShippingOrderDocumentProfile) => {
|
||||
};
|
||||
}
|
||||
const restored: OrderProfileCanvasRegion[] = [
|
||||
...(profile.definition.document_match.required_anchors || []).flatMap<OrderProfileCanvasRegion>((anchor) => {
|
||||
...(definition.document_match.required_anchors || []).flatMap<OrderProfileCanvasRegion>((anchor) => {
|
||||
if (!anchor.label_region || !anchor.value_region || !anchor.page_no) return [];
|
||||
return [{
|
||||
id: `${anchor.anchor_id}_label`, kind: 'document_anchor_label', label: anchor.label,
|
||||
@@ -1547,7 +1548,7 @@ const restoreRegions = (profile: ShippingOrderDocumentProfile) => {
|
||||
region: anchor.value_region, parentId: anchor.anchor_id, pageNo: anchor.page_no,
|
||||
}];
|
||||
}),
|
||||
...(profile.definition.draft_unbound_order_field_layouts || []).flatMap<OrderProfileCanvasRegion>((item) => {
|
||||
...(definition.draft_unbound_order_field_layouts || []).flatMap<OrderProfileCanvasRegion>((item) => {
|
||||
const pageNo = item.page_scope === "exact_page" ? item.page_no || 1 : 1;
|
||||
if (!item.anchor?.region || !item.absolute_value_region) {
|
||||
return [{
|
||||
@@ -1580,7 +1581,7 @@ const restoreRegions = (profile: ShippingOrderDocumentProfile) => {
|
||||
pageNo,
|
||||
}];
|
||||
}),
|
||||
...(profile.definition.order_field_layouts || []).filter((item) => !item.anchor).map((item) => ({
|
||||
...(definition.order_field_layouts || []).filter((item) => !item.anchor).map((item) => ({
|
||||
id: item.layout_id,
|
||||
kind: "order_field" as const,
|
||||
label: schemaFieldLabel(item.field_code),
|
||||
@@ -1588,7 +1589,7 @@ const restoreRegions = (profile: ShippingOrderDocumentProfile) => {
|
||||
fieldCode: item.field_code,
|
||||
pageNo: item.page_scope === "exact_page" ? item.page_no || 1 : 1,
|
||||
})),
|
||||
...(profile.definition.order_field_layouts || []).flatMap((item) => {
|
||||
...(definition.order_field_layouts || []).flatMap((item) => {
|
||||
if (!item.anchor?.region || !item.absolute_value_region) return [];
|
||||
const anchor = item.anchor.region;
|
||||
return [{
|
||||
@@ -1612,7 +1613,7 @@ const restoreRegions = (profile: ShippingOrderDocumentProfile) => {
|
||||
pageNo: item.page_scope === "exact_page" ? item.page_no || 1 : 1,
|
||||
}];
|
||||
}),
|
||||
...profile.definition.table_regions.flatMap((table) => {
|
||||
...definition.table_regions.flatMap((table) => {
|
||||
const regionPageNo = restoreOrderProfileRegionPageNo(table);
|
||||
const headerLayoutIds = new Set(
|
||||
table.header_layouts.map((item) => item.layout_id),
|
||||
@@ -1733,10 +1734,11 @@ const edit = async (profile: ShippingOrderDocumentProfile) => {
|
||||
form.displayName = profile.display_name;
|
||||
form.schemaId = profile.schema_version_id;
|
||||
form.changeNote = profile.change_note || "";
|
||||
documentMatch.requiredAnchors = (profile.definition.document_match.required_anchors || []).map((item) => ({ ...item }));
|
||||
documentMatch.optionalAnchors = (profile.definition.document_match.optional_anchors || []).map((item) => ({ ...item }));
|
||||
documentMatch.minimumScore = profile.definition.document_match.minimum_score;
|
||||
documentMatch.minimumMargin = profile.definition.document_match.minimum_margin;
|
||||
const definition = asCoordinateProfileDefinition(profile.definition);
|
||||
documentMatch.requiredAnchors = (definition.document_match.required_anchors || []).map((item) => ({ ...item }));
|
||||
documentMatch.optionalAnchors = (definition.document_match.optional_anchors || []).map((item) => ({ ...item }));
|
||||
documentMatch.minimumScore = definition.document_match.minimum_score;
|
||||
documentMatch.minimumMargin = definition.document_match.minimum_margin;
|
||||
documentMatchDirty.value = false;
|
||||
regions.value = restoreRegions(profile);
|
||||
history.value = [];
|
||||
|
||||
+28
-10
@@ -1,26 +1,44 @@
|
||||
<!--
|
||||
features/admin/modules/shipping-order-document-profiles/OrderProfileEditorRoutePage.vue
|
||||
用途:承接草稿编辑深链并挂载独立编辑页。
|
||||
依赖:Vue Router、OrderProfileEditorPage。
|
||||
逻辑:将路径草稿身份传递给独立编辑页;query 仅传递标签会话,不得改变目标草稿。
|
||||
用途:按 template_mode 路由 Coordinate 编辑器或 XFA 映射工作台。
|
||||
依赖:Vue Router、Profile 详情 API、OrderProfileEditorPage、XfaProfileMappingPage。
|
||||
逻辑:加载草稿后鉴别联合;coordinate 保持原编辑器,xfa_dataset 进入映射页。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { ref } from 'vue';
|
||||
import { onMounted, ref } from 'vue';
|
||||
import { useRoute } from 'vue-router';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { BusinessError } from '@/shared/api/client';
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
import { getOrderDocumentProfileDetail } from '@/features/admin/api/shipping-order-document-profile.api';
|
||||
import { isXfaDatasetProfileDefinition } from '@/features/admin/types/shipping-order-document-profile.types';
|
||||
import OrderProfileEditorPage from './OrderProfileEditorPage.vue';
|
||||
import XfaProfileMappingPage from './XfaProfileMappingPage.vue';
|
||||
|
||||
const { t } = useI18n();
|
||||
const route = useRoute();
|
||||
const message = useMessage();
|
||||
const ready = ref(false);
|
||||
const isXfa = ref(false);
|
||||
|
||||
/**
|
||||
* 路由参数由编辑页直接读取;本页只在挂载前准备渲染,避免旧 query 身份适配。
|
||||
* @returns 设置完成后显示编辑页。
|
||||
* 读取草稿 template_mode 后选择编辑器。
|
||||
*/
|
||||
function prepareEditor(): void {
|
||||
ready.value = true;
|
||||
async function prepareEditor(): Promise<void> {
|
||||
try {
|
||||
const profileId = Number(route.params.profileId);
|
||||
const profile = await getOrderDocumentProfileDetail(profileId);
|
||||
isXfa.value = isXfaDatasetProfileDefinition(profile.definition) || profile.template_mode === 'xfa_dataset';
|
||||
ready.value = true;
|
||||
} catch (error) {
|
||||
message.error(error instanceof BusinessError ? error.message : t('admin.shippingOrderProfiles.xfaWorkbench.loadFailed'));
|
||||
}
|
||||
}
|
||||
|
||||
prepareEditor();
|
||||
onMounted(prepareEditor);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<OrderProfileEditorPage v-if="ready" />
|
||||
<XfaProfileMappingPage v-if="ready && isXfa" />
|
||||
<OrderProfileEditorPage v-else-if="ready" />
|
||||
</template>
|
||||
+272
-24
@@ -1,8 +1,8 @@
|
||||
<!--
|
||||
features/admin/modules/shipping-order-document-profiles/OrderProfilePublishCheckPage.vue
|
||||
用途:以当前已验证草稿生成可读的发布检查,并在门禁通过后发布模板。
|
||||
用途:展示版面签名、跨模板唯一性与发布阻断项,并在门禁通过后发布模板。
|
||||
依赖:发布检查 API、验证运行 API、Vue Router 和统一消息提示。
|
||||
逻辑:自动选择当前样本试读的通过运行;阻断项不可绕过,语义差异必须逐项确认。
|
||||
逻辑:自动选择当前样本试读通过运行;服务端生成签名/重叠验证;阻断项不可绕过,语义差异须逐项确认。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref } from 'vue';
|
||||
@@ -10,37 +10,264 @@ import { useRoute, useRouter } from 'vue-router';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { BusinessError } from '@/shared/api/client';
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
import { acquireOrderDocumentProfileEditLease, confirmOrderProfilePublishCheck, createOrderProfilePublishCheck, listOrderProfileValidationRuns } from '@/features/admin/api/shipping-order-document-profile.api';
|
||||
import type { OrderProfilePublishCheckReport, OrderProfileValidationRun } from '@/features/admin/types/shipping-order-document-profile.types';
|
||||
import {
|
||||
acquireOrderDocumentProfileEditLease,
|
||||
confirmOrderProfilePublishCheck,
|
||||
createOrderProfilePublishCheck,
|
||||
listOrderProfileValidationRuns,
|
||||
} from '@/features/admin/api/shipping-order-document-profile.api';
|
||||
import type {
|
||||
OrderProfileOverlapConflictProfile,
|
||||
OrderProfilePublishCheckReport,
|
||||
OrderProfileValidationRun,
|
||||
} from '@/features/admin/types/shipping-order-document-profile.types';
|
||||
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
const message = useMessage();
|
||||
const { t } = useI18n();
|
||||
const profileId = Number(route.params.profileId);
|
||||
const runs = ref<OrderProfileValidationRun[]>([]);
|
||||
const report = ref<OrderProfilePublishCheckReport | null>(null);
|
||||
const confirmed = ref<string[]>([]);
|
||||
const busy = ref(false);
|
||||
const sessionId = String(route.query.editorSessionId || '').trim() || crypto.randomUUID();
|
||||
const leaseToken = ref('');
|
||||
|
||||
const route = useRoute(); const router = useRouter(); const message = useMessage(); const { t } = useI18n();
|
||||
const profileId = Number(route.params.profileId); const runs = ref<OrderProfileValidationRun[]>([]); const report = ref<OrderProfilePublishCheckReport | null>(null); const confirmed = ref<string[]>([]); const busy = ref(false);
|
||||
const sessionId = String(route.query.editorSessionId || '').trim() || crypto.randomUUID(); const leaseToken = ref('');
|
||||
const validationRun = computed(() => runs.value.find((item) => item.run_type === 'current_sample' && item.status === 'passed') || null);
|
||||
const publishable = computed(() => report.value?.status === 'valid' && !report.value.blocking_items.length && confirmed.value.length === report.value.warning_items.length);
|
||||
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);
|
||||
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 || []);
|
||||
const gateStatus = computed<'pass' | 'blocked' | 'pending'>(() => {
|
||||
if (!report.value) return 'pending';
|
||||
return report.value.blocking_items.length ? 'blocked' : 'pass';
|
||||
});
|
||||
|
||||
/** 显示统一业务错误,避免发布页暴露服务端实现细节。 */
|
||||
function fail(error: unknown): void { message.error(error instanceof BusinessError ? error.message : t('admin.orderProfilePublishCheck.failed')); }
|
||||
function fail(error: unknown): void {
|
||||
message.error(error instanceof BusinessError ? error.message : t('admin.orderProfilePublishCheck.failed'));
|
||||
}
|
||||
|
||||
/** 获取租约后才允许创建或消费报告,避免发布页绕过草稿写保护。 */
|
||||
async function ensureLease(): Promise<boolean> { if (leaseToken.value) return true; try { leaseToken.value = (await acquireOrderDocumentProfileEditLease(profileId, { browser_session_id: sessionId, operation_id: crypto.randomUUID() })).lease_token; return true; } catch (error) { fail(error); return false; } }
|
||||
/** 读取当前草稿仍有效的样本试读;历史 stale 运行不可用于发布。 */
|
||||
async function loadRuns(): Promise<void> { try { runs.value = await listOrderProfileValidationRuns(profileId); } catch (error) { fail(error); } }
|
||||
/** 创建发布检查报告;后端继续复核当前验证、盲测与 Profile 发布前置条件。 */
|
||||
async function createReport(): Promise<void> { if (!validationRun.value || !(await ensureLease())) return; busy.value = true; try { report.value = await createOrderProfilePublishCheck(profileId, { validation_run_id: validationRun.value.id, browser_session_id: sessionId, lease_token: leaseToken.value, operation_id: crypto.randomUUID() }); confirmed.value = []; } catch (error) { fail(error); } finally { busy.value = false; } }
|
||||
async function ensureLease(): Promise<boolean> {
|
||||
if (leaseToken.value) return true;
|
||||
try {
|
||||
leaseToken.value = (await acquireOrderDocumentProfileEditLease(profileId, {
|
||||
browser_session_id: sessionId,
|
||||
operation_id: crypto.randomUUID(),
|
||||
})).lease_token;
|
||||
return true;
|
||||
} catch (error) {
|
||||
fail(error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** 读取当前草稿仍有效的验证运行;历史 stale 运行不可用于发布。 */
|
||||
async function loadRuns(): Promise<void> {
|
||||
try {
|
||||
runs.value = await listOrderProfileValidationRuns(profileId);
|
||||
} catch (error) {
|
||||
fail(error);
|
||||
}
|
||||
}
|
||||
|
||||
/** 创建发布检查报告;后端继续复核签名、跨模板唯一性、盲测与 Profile 发布前置条件。 */
|
||||
async function createReport(): Promise<void> {
|
||||
if (!validationRun.value || !(await ensureLease())) return;
|
||||
busy.value = true;
|
||||
try {
|
||||
report.value = await createOrderProfilePublishCheck(profileId, {
|
||||
validation_run_id: validationRun.value.id,
|
||||
matching_signature_run_id: signatureRun.value?.id,
|
||||
overlap_validation_run_id: overlapRun.value?.id,
|
||||
browser_session_id: sessionId,
|
||||
lease_token: leaseToken.value,
|
||||
operation_id: crypto.randomUUID(),
|
||||
});
|
||||
confirmed.value = [];
|
||||
await loadRuns();
|
||||
} catch (error) {
|
||||
fail(error);
|
||||
} finally {
|
||||
busy.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
/** 逐项确认警告后消费报告并发布;发布成功后进入只读版本详情。 */
|
||||
async function publish(): Promise<void> { if (!report.value || !publishable.value || !(await ensureLease())) return; busy.value = true; try { const published = await confirmOrderProfilePublishCheck(profileId, report.value.report_no, { confirmed_warning_keys: confirmed.value, browser_session_id: sessionId, lease_token: leaseToken.value, operation_id: crypto.randomUUID() }); await router.replace({ name: 'AdminShippingOrderDocumentProfileVersionDetail', params: { profileCode: published.profile_code, version: String(published.version) } }); } catch (error) { fail(error); } finally { busy.value = false; } }
|
||||
async function publish(): Promise<void> {
|
||||
if (!report.value || !publishable.value || !(await ensureLease())) return;
|
||||
busy.value = true;
|
||||
try {
|
||||
const published = await confirmOrderProfilePublishCheck(profileId, report.value.report_no, {
|
||||
confirmed_warning_keys: confirmed.value,
|
||||
browser_session_id: sessionId,
|
||||
lease_token: leaseToken.value,
|
||||
operation_id: crypto.randomUUID(),
|
||||
});
|
||||
await router.replace({
|
||||
name: 'AdminShippingOrderDocumentProfileVersionDetail',
|
||||
params: { profileCode: published.profile_code, version: String(published.version) },
|
||||
});
|
||||
} catch (error) {
|
||||
fail(error);
|
||||
} finally {
|
||||
busy.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
/** 归一化有限的已知门禁码;未知内容仍保留后端安全摘要。 */
|
||||
function itemMessage(item: Record<string, unknown>): string { const key = String(item.key || ''); return key === 'current_validation_required' ? t('admin.orderProfilePublishCheck.currentValidationRequired') : key === 'semantic_diff_review' ? t('admin.orderProfilePublishCheck.semanticDiffReview') : String(item.message || t('admin.orderProfilePublishCheck.unknownIssue')); }
|
||||
function backToValidation(): void { router.push({ name: 'AdminShippingOrderDocumentProfileValidate', params: route.params, query: { editorSessionId: sessionId } }); }
|
||||
function itemMessage(item: Record<string, unknown>): string {
|
||||
const key = String(item.key || '');
|
||||
const map: Record<string, string> = {
|
||||
current_validation_required: t('admin.orderProfilePublishCheck.currentValidationRequired'),
|
||||
semantic_diff_review: t('admin.orderProfilePublishCheck.semanticDiffReview'),
|
||||
signature_required: t('admin.orderProfilePublishCheck.signatureRequired'),
|
||||
signature_stale: t('admin.orderProfilePublishCheck.signatureStale'),
|
||||
overlap_validation_required: t('admin.orderProfilePublishCheck.overlapRequired'),
|
||||
overlap_validation_stale: t('admin.orderProfilePublishCheck.overlapStale'),
|
||||
overlap_validation_failed: t('admin.orderProfilePublishCheck.overlapFailed'),
|
||||
self_match_not_unique: t('admin.orderProfilePublishCheck.selfMatchNotUnique'),
|
||||
self_match_not_unique_blind: t('admin.orderProfilePublishCheck.selfMatchNotUniqueBlind'),
|
||||
cross_template_false_hit: t('admin.orderProfilePublishCheck.crossTemplateFalseHit'),
|
||||
cross_template_ambiguous: t('admin.orderProfilePublishCheck.crossTemplateAmbiguous'),
|
||||
cross_template_parse_failed: t('admin.orderProfilePublishCheck.crossTemplateParseFailed'),
|
||||
cross_template_coverage_insufficient: t('admin.orderProfilePublishCheck.crossTemplateCoverageInsufficient'),
|
||||
cross_template_margin_insufficient: t('admin.orderProfilePublishCheck.crossTemplateMarginInsufficient'),
|
||||
sample_role_pollution: t('admin.orderProfilePublishCheck.sampleRolePollution'),
|
||||
cross_template_conflict_profiles: t('admin.orderProfilePublishCheck.crossTemplateConflictProfiles'),
|
||||
};
|
||||
return map[key] || String(item.message || t('admin.orderProfilePublishCheck.unknownIssue'));
|
||||
}
|
||||
|
||||
/** 格式化百分比指标,供唯一性卡片展示。 */
|
||||
function formatRate(value: number | null | undefined): string {
|
||||
if (value == null) return '—';
|
||||
return `${Math.round(value * 1000) / 10}%`;
|
||||
}
|
||||
|
||||
function backToValidation(): void {
|
||||
router.push({ name: 'AdminShippingOrderDocumentProfileValidate', params: route.params, query: { editorSessionId: sessionId } });
|
||||
}
|
||||
|
||||
/** 冲突修复必须回到唯一可修改的模板编辑器,避免用户在验证页无路可走。 */
|
||||
function backToEditor(): void {
|
||||
router.push({ name: 'AdminShippingOrderDocumentProfileEdit', params: route.params, query: { editorSessionId: sessionId } });
|
||||
}
|
||||
|
||||
function signatureStatus(value: string | undefined): string {
|
||||
const map: Record<string, string> = {
|
||||
valid: t('admin.orderProfilePublishCheck.statusValid'),
|
||||
missing: t('admin.orderProfilePublishCheck.statusMissing'),
|
||||
stale: t('admin.orderProfilePublishCheck.statusStale'),
|
||||
};
|
||||
return map[value || ''] || '—';
|
||||
}
|
||||
|
||||
function conflictReason(value: string): string {
|
||||
const map: Record<string, string> = {
|
||||
false_hit: t('admin.orderProfilePublishCheck.crossTemplateFalseHit'),
|
||||
reverse_false_hit: t('admin.orderProfilePublishCheck.crossTemplateFalseHit'),
|
||||
ambiguous: t('admin.orderProfilePublishCheck.crossTemplateAmbiguous'),
|
||||
profile_parse_validation_failed: t('admin.orderProfilePublishCheck.crossTemplateParseFailed'),
|
||||
profile_evidence_coverage_insufficient: t('admin.orderProfilePublishCheck.crossTemplateCoverageInsufficient'),
|
||||
profile_margin_insufficient: t('admin.orderProfilePublishCheck.crossTemplateMarginInsufficient'),
|
||||
};
|
||||
return map[value] || t('admin.orderProfilePublishCheck.unknownIssue');
|
||||
}
|
||||
|
||||
onMounted(loadRuns);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="page">
|
||||
<header><div><h1 class="section-title">{{ t('admin.orderProfilePublishCheck.title') }}</h1><small class="section-desc mt-1">{{ t('admin.orderProfilePublishCheck.description') }}</small></div><button type="button" class="btn-secondary" @click="backToValidation">{{ t('admin.orderProfilePublishCheck.back') }}</button></header>
|
||||
<section v-if="!report" class="card"><h2>{{ t('admin.orderProfilePublishCheck.readyTitle') }}</h2><p>{{ validationRun ? t('admin.orderProfilePublishCheck.readyHint') : t('admin.orderProfilePublishCheck.noRun') }}</p><button class="btn-primary" :disabled="busy || !validationRun" type="button" @click="createReport">{{ t('admin.orderProfilePublishCheck.create') }}</button></section>
|
||||
<section v-else class="card"><h2>{{ t('admin.orderProfilePublishCheck.reportTitle') }}</h2><p>{{ report.blocking_items.length ? t('admin.orderProfilePublishCheck.blockedHint') : t('admin.orderProfilePublishCheck.reviewHint') }}</p><h3>{{ t('admin.orderProfilePublishCheck.blocking') }}</h3><p v-if="!report.blocking_items.length" class="good">{{ t('admin.orderProfilePublishCheck.noBlocking') }}</p><ul><li v-for="item in report.blocking_items" :key="String(item.key)">{{ itemMessage(item) }}</li></ul><h3>{{ t('admin.orderProfilePublishCheck.warnings') }}</h3><label v-for="item in report.warning_items" :key="String(item.key)"><input v-model="confirmed" type="checkbox" :value="String(item.key)"><span>{{ itemMessage(item) }}</span></label><p v-if="report.warning_items.length" class="hint">{{ t('admin.orderProfilePublishCheck.confirmHint') }}</p><button class="btn-primary" :disabled="busy || !publishable" type="button" @click="publish">{{ t('admin.orderProfilePublishCheck.confirm') }}</button></section>
|
||||
<header>
|
||||
<div>
|
||||
<h1 class="section-title">{{ t('admin.orderProfilePublishCheck.title') }}</h1>
|
||||
<small class="section-desc mt-1">{{ t('admin.orderProfilePublishCheck.description') }}</small>
|
||||
</div>
|
||||
<button type="button" class="btn-secondary" @click="backToValidation">{{ t('admin.orderProfilePublishCheck.back') }}</button>
|
||||
</header>
|
||||
|
||||
<section v-if="!report" class="card">
|
||||
<h2>{{ t('admin.orderProfilePublishCheck.readyTitle') }}</h2>
|
||||
<p>{{ validationRun ? t('admin.orderProfilePublishCheck.readyHint') : t('admin.orderProfilePublishCheck.noRun') }}</p>
|
||||
<button class="btn-primary" :disabled="busy || !validationRun" type="button" @click="createReport">
|
||||
{{ t('admin.orderProfilePublishCheck.create') }}
|
||||
</button>
|
||||
</section>
|
||||
|
||||
<template v-else>
|
||||
<section class="card">
|
||||
<div class="card-head">
|
||||
<h2>{{ t('admin.orderProfilePublishCheck.reportTitle') }}</h2>
|
||||
<button class="btn-secondary" :disabled="busy || !validationRun" type="button" @click="createReport">
|
||||
{{ t('admin.orderProfilePublishCheck.rerun') }}
|
||||
</button>
|
||||
</div>
|
||||
<p :class="['gate-status', gateStatus]">{{ gateStatus === 'blocked' ? t('admin.orderProfilePublishCheck.blockedHint') : t('admin.orderProfilePublishCheck.reviewHint') }}</p>
|
||||
</section>
|
||||
|
||||
<section class="card">
|
||||
<h3>{{ isXfaReport ? t('admin.orderProfilePublishCheck.xfaStructureSignatureTitle') : 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>
|
||||
</dl>
|
||||
</section>
|
||||
|
||||
<section class="card">
|
||||
<h3>{{ t('admin.orderProfilePublishCheck.uniquenessTitle') }}</h3>
|
||||
<dl class="metrics">
|
||||
<div><dt>{{ t('admin.orderProfilePublishCheck.trainingUniqueRate') }}</dt><dd>{{ formatRate(report.overlap_summary?.self_unique_hit_rate_training) }}</dd></div>
|
||||
<div><dt>{{ t('admin.orderProfilePublishCheck.blindUniqueRate') }}</dt><dd>{{ formatRate(report.overlap_summary?.self_unique_hit_rate_blind) }}</dd></div>
|
||||
<div><dt>{{ t('admin.orderProfilePublishCheck.falseHitCount') }}</dt><dd>{{ report.overlap_summary?.false_hit_other_count ?? 0 }}</dd></div>
|
||||
<div><dt>{{ t('admin.orderProfilePublishCheck.reverseFalseHitCount') }}</dt><dd>{{ report.overlap_summary?.reverse_false_hit_count ?? 0 }}</dd></div>
|
||||
<div><dt>{{ t('admin.orderProfilePublishCheck.ambiguousCount') }}</dt><dd>{{ report.overlap_summary?.ambiguous_count ?? 0 }}</dd></div>
|
||||
<div><dt>{{ t('admin.orderProfilePublishCheck.minEvidenceCoverage') }}</dt><dd>{{ formatRate(report.overlap_summary?.min_evidence_coverage) }} / ≥ {{ formatRate(report.overlap_summary?.thresholds?.evidence_coverage_minimum) }}</dd></div>
|
||||
<div><dt>{{ t('admin.orderProfilePublishCheck.minMargin') }}</dt><dd>{{ report.overlap_summary?.min_margin ?? '—' }} / ≥ {{ report.overlap_summary?.thresholds?.minimum_margin ?? '—' }}</dd></div>
|
||||
<div><dt>{{ t('admin.orderProfilePublishCheck.parseFailedCount') }}</dt><dd>{{ report.overlap_summary?.parse_validation_failed_count ?? 0 }}</dd></div>
|
||||
</dl>
|
||||
</section>
|
||||
|
||||
<section v-if="conflictProfiles.length" class="card">
|
||||
<h3>{{ t('admin.orderProfilePublishCheck.conflictsTitle') }}</h3>
|
||||
<article v-for="conflict in conflictProfiles" :key="`${conflict.profile_code}-${conflict.version}`" class="conflict-card">
|
||||
<strong>{{ conflict.profile_code }} v{{ conflict.version }}</strong>
|
||||
<p class="reasons">{{ conflict.reason_codes.map(conflictReason).join(';') }}</p>
|
||||
<p>{{ conflict.suggestion }}</p>
|
||||
<button type="button" class="btn-secondary" @click="backToEditor">{{ t('admin.orderProfilePublishCheck.backToEditor') }}</button>
|
||||
</article>
|
||||
</section>
|
||||
|
||||
<section class="card">
|
||||
<h3>{{ t('admin.orderProfilePublishCheck.blocking') }}</h3>
|
||||
<p v-if="!report.blocking_items.length" class="good">{{ t('admin.orderProfilePublishCheck.noBlocking') }}</p>
|
||||
<ul v-else>
|
||||
<li v-for="item in report.blocking_items" :key="String(item.key)">{{ itemMessage(item) }}</li>
|
||||
</ul>
|
||||
|
||||
<h3>{{ t('admin.orderProfilePublishCheck.warnings') }}</h3>
|
||||
<label v-for="item in report.warning_items" :key="String(item.key)">
|
||||
<input v-model="confirmed" type="checkbox" :value="String(item.key)">
|
||||
<span>{{ itemMessage(item) }}</span>
|
||||
</label>
|
||||
<p v-if="report.warning_items.length" class="hint">{{ t('admin.orderProfilePublishCheck.confirmHint') }}</p>
|
||||
<button class="btn-primary" :disabled="busy || !publishable" type="button" @click="publish">
|
||||
{{ t('admin.orderProfilePublishCheck.confirm') }}
|
||||
</button>
|
||||
</section>
|
||||
</template>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.page { width: 100%; margin: 0; padding: 24px; color: #334155; }
|
||||
.page header { display: flex; flex-wrap: wrap; align-items: flex-start; justify-content: space-between; gap: 16px; }
|
||||
@@ -48,8 +275,29 @@ onMounted(loadRuns);
|
||||
.page small:not(.section-desc), .card p { color: #64748b; font-size: 13px; line-height: 1.5; }
|
||||
.page small { display: block; margin-top: 5px; }
|
||||
.card { margin-top: 20px; border: 1px solid #dfe7ef; border-radius: 10px; background: #fff; padding: 16px; box-shadow: 0 1px 2px rgb(15 23 42 / 3%); }
|
||||
.card h2 { margin: 0; color: #1e293b; font-size: 15px; font-weight: 600; }.card h3 { margin: 20px 0 8px; color: #1e293b; font-size: 14px; }
|
||||
.card label { display: flex; gap: 8px; margin: 10px 0; color: #475569; font-size: 13px; }.card input { accent-color: #0ea5e9; }
|
||||
.card .btn-primary { margin-top: 14px; }.good { color: #15803d; font-size: 13px; }.hint { font-size: 13px; }ul { margin: 8px 0; padding-left: 20px; color: #b91c1c; font-size: 13px; }
|
||||
@media(max-width:767px) { .page { padding: 16px; }.page header { display: grid; }.page header button { width: 100%; } }
|
||||
.card-head { display: flex; align-items: center; justify-content: space-between; gap: 12px; }
|
||||
.card h2 { margin: 0; color: #1e293b; font-size: 15px; font-weight: 600; }
|
||||
.card h3 { margin: 0 0 12px; color: #1e293b; font-size: 14px; }
|
||||
.card label { display: flex; gap: 8px; margin: 10px 0; color: #475569; font-size: 13px; }
|
||||
.card input { accent-color: #0ea5e9; }
|
||||
.card .btn-primary { margin-top: 14px; }
|
||||
.good { color: #15803d; font-size: 13px; }
|
||||
.gate-status { font-weight: 600; }
|
||||
.gate-status.blocked { color: #b91c1c; }
|
||||
.gate-status.pass, .status-valid { color: #15803d; }
|
||||
.status-missing, .status-stale { color: #b45309; }
|
||||
.hint { font-size: 13px; }
|
||||
ul { margin: 8px 0; padding-left: 20px; color: #b91c1c; font-size: 13px; }
|
||||
.metrics { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 12px; margin: 0; }
|
||||
.metrics div { display: grid; gap: 4px; }
|
||||
.metrics dt { color: #64748b; font-size: 12px; }
|
||||
.metrics dd { margin: 0; color: #1e293b; font-size: 14px; font-weight: 600; }
|
||||
.conflict-card { border: 1px solid #fecaca; background: #fff7f7; border-radius: 8px; padding: 12px; margin-top: 10px; }
|
||||
.conflict-card strong { color: #991b1b; font-size: 13px; }
|
||||
.conflict-card .reasons { color: #b45309; font-size: 12px; }
|
||||
@media (max-width: 767px) {
|
||||
.page { padding: 16px; }
|
||||
.page header, .card-head { display: grid; }
|
||||
.page header button, .card-head button { width: 100%; }
|
||||
}
|
||||
</style>
|
||||
+194
-21
@@ -2,7 +2,8 @@
|
||||
features/admin/modules/shipping-order-document-profiles/OrderProfileValidationPage.vue
|
||||
用途:验证当前订单模板草稿,并按“基础验证、盲测、发布检查”顺序引导管理员。
|
||||
依赖:Profile 验证 API、编辑租约、Vue Router、统一消息提示。
|
||||
逻辑:一次动作依次执行结构检查和当前样本试读;盲测批准前不解锁发布检查入口。
|
||||
逻辑:一次动作依次执行结构检查和当前样本试读;XFA 从验证摘要展示脱敏字段级结果;
|
||||
盲测批准前不解锁发布检查入口。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref } from 'vue';
|
||||
@@ -30,10 +31,14 @@ import type {
|
||||
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();
|
||||
const { t } = useI18n();
|
||||
const { t, te } = useI18n();
|
||||
const message = useMessage();
|
||||
const profileId = Number(route.params.profileId);
|
||||
const runs = ref<OrderProfileValidationRun[]>([]);
|
||||
@@ -49,6 +54,94 @@ 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 xfaLines = computed(() => {
|
||||
const rows = xfaSummary.value?.lines;
|
||||
return Array.isArray(rows) ? rows as Array<Record<string, unknown>> : [];
|
||||
});
|
||||
const XFA_CROSS_CHECK_KEYS = [
|
||||
'mirror_status',
|
||||
'acroform_status',
|
||||
'line_amount_status',
|
||||
'total_amount_status',
|
||||
] as const;
|
||||
|
||||
/**
|
||||
* 从字段预览中取标准化值。
|
||||
*/
|
||||
function xfaFieldNormalized(
|
||||
fields: Array<Record<string, unknown>>,
|
||||
fieldCode: string,
|
||||
): string {
|
||||
const hit = fields.find((item) => String(item.field_code || '') === fieldCode);
|
||||
return String(hit?.normalized_value ?? '').trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* 将交叉校验技术状态映射为管理员可读说明(含金额计算过程)。
|
||||
*/
|
||||
const xfaCrossCheckEntries = computed(() => {
|
||||
const checks = xfaSummary.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 n = Number(raw);
|
||||
return Number.isFinite(n) ? sum + n : sum;
|
||||
}, 0);
|
||||
const lineSumText = Number.isFinite(lineSum) && lineSum > 0
|
||||
? String(Number(lineSum.toFixed(2)))
|
||||
: amount;
|
||||
|
||||
return XFA_CROSS_CHECK_KEYS
|
||||
.filter((key) => map[key] != null && String(map[key]).trim() !== '')
|
||||
.map((key) => {
|
||||
const status = String(map[key] ?? '').trim().toLowerCase();
|
||||
const label = t(`admin.orderProfileValidation.xfaCheckLabel.${key}`);
|
||||
const statusLabel = t(
|
||||
`admin.orderProfileValidation.xfaCheckStatus.${status}`,
|
||||
status || '-',
|
||||
);
|
||||
let detail = '';
|
||||
if (key === 'line_amount_status' && qty && unitPrice && amount) {
|
||||
detail = t('admin.orderProfileValidation.xfaAmountFormula', {
|
||||
quantity: qty,
|
||||
unitPrice,
|
||||
priceUnit,
|
||||
amount,
|
||||
});
|
||||
} else if (key === 'total_amount_status' && total && lineSumText) {
|
||||
detail = t('admin.orderProfileValidation.xfaTotalFormula', {
|
||||
total,
|
||||
lineSum: lineSumText,
|
||||
});
|
||||
} else if (key === 'mirror_status' || key === 'acroform_status') {
|
||||
const hintKey = `admin.orderProfileValidation.xfaCheckHint.${key}.${status}`;
|
||||
detail = te(hintKey) ? t(hintKey) : '';
|
||||
}
|
||||
return { key, label, statusLabel, detail, status };
|
||||
});
|
||||
});
|
||||
|
||||
const latestRun = (runType: OrderProfileValidationRun['run_type']) =>
|
||||
runs.value.find((item) => item.run_type === runType) || null;
|
||||
@@ -95,7 +188,12 @@ async function loadContext(): Promise<void> {
|
||||
getOrderDocumentProfileDetail(profileId), listOrderProfileBoundSamples(profileId),
|
||||
]);
|
||||
profile.value = detail;
|
||||
sample.value = samples.find((item) => item.sample_role === 'annotation' || item.sample_role === 'training') || null;
|
||||
const selectedSample = samples.find((item) => item.sample_role === 'annotation' || item.sample_role === 'training') || null;
|
||||
// Validation must use the immutable table identity captured with the sample;
|
||||
// a legacy mutable binding can point at a table id from a newer layout.
|
||||
sample.value = selectedSample
|
||||
? { ...selectedSample, table_id: selectedSample.table_identity_snapshot?.table_id || selectedSample.table_id }
|
||||
: null;
|
||||
const schema = await getShippingOrderSchemaVersion(detail.schema_version_id);
|
||||
fieldNames.value = new Map((schema.definition?.fields || []).map((field) => [field.field_code || '', field.display_name]));
|
||||
} catch (error) { report(error); }
|
||||
@@ -104,28 +202,44 @@ 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?.table_id) return;
|
||||
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 pageNos = Array.from(new Set((profile.value.definition.order_field_layouts || []).map((item) => (
|
||||
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;
|
||||
const [headers, lines] = await Promise.all([
|
||||
previewOrderProfileOrderFieldValues(
|
||||
sample.value.document_id, profile.value.schema_version_id, pageNo, profile.value.definition, pageNos,
|
||||
),
|
||||
previewOrderProfileRegion(profileId, sample.value.document_id, sample.value.table_id, profile.value.definition),
|
||||
]);
|
||||
headerValues.value = headers.fields;
|
||||
linePreview.value = lines;
|
||||
} catch {
|
||||
headerValues.value = [];
|
||||
linePreview.value = null;
|
||||
resultFailed.value = true;
|
||||
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; }
|
||||
}
|
||||
|
||||
@@ -226,8 +340,65 @@ 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>{{ t('admin.orderProfileValidation.resultsHint') }}</p></div><button type="button" class="btn-secondary btn-sm" :disabled="resultLoading" @click="loadReadResults">{{ t('admin.orderProfileValidation.refreshResults') }}</button></div>
|
||||
<p v-if="resultLoading">{{ t('admin.orderProfileValidation.resultsLoading') }}</p>
|
||||
<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">
|
||||
<dl class="header-results">
|
||||
<div><dt>{{ t('admin.orderProfileValidation.xfaTemplateMode') }}</dt><dd>XFA</dd></div>
|
||||
<div><dt>{{ t('admin.orderProfileValidation.xfaRequiredMissing') }}</dt><dd>{{ xfaSummary?.header_required_missing_count ?? '-' }}</dd></div>
|
||||
<div><dt>{{ t('admin.orderProfileValidation.xfaAutoCreateMissing') }}</dt><dd>{{ xfaSummary?.auto_create_key_missing_count ?? '-' }}</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>
|
||||
</dl>
|
||||
|
||||
<h3>{{ t('admin.orderProfileValidation.xfaCrossCheckStatus') }}</h3>
|
||||
<dl v-if="xfaCrossCheckEntries.length" class="header-results">
|
||||
<div
|
||||
v-for="item in xfaCrossCheckEntries"
|
||||
:key="item.key"
|
||||
:class="`field-${item.status === 'matched' || item.status === 'passed' || item.status === 'skipped' ? 'passed' : 'failed'}`"
|
||||
>
|
||||
<dt>{{ item.label }}</dt>
|
||||
<dd>{{ item.statusLabel }}</dd>
|
||||
<dd v-if="item.detail" class="field-code">{{ item.detail }}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
|
||||
<h3>{{ t('admin.orderProfileValidation.xfaHeaderFields') }}</h3>
|
||||
<dl v-if="xfaHeaderFields.length" class="header-results">
|
||||
<div
|
||||
v-for="field in xfaHeaderFields"
|
||||
: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.xfaMaskedRaw') }}:{{ field.masked_raw_value || t('admin.orderProfileValidation.noValue') }}</dd>
|
||||
<dd>{{ t('admin.orderProfileValidation.xfaNormalized') }}:{{ field.normalized_value || t('admin.orderProfileValidation.noValue') }}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
<p v-else>{{ t('admin.orderProfileValidation.xfaNoFieldPreview') }}</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">
|
||||
<h4>#{{ Number(line.row_index) + 1 }}</h4>
|
||||
<dl class="header-results">
|
||||
<div
|
||||
v-for="field in (Array.isArray(line.fields) ? 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.xfaMaskedRaw') }}:{{ field.masked_raw_value || t('admin.orderProfileValidation.noValue') }}</dd>
|
||||
<dd>{{ t('admin.orderProfileValidation.xfaNormalized') }}:{{ field.normalized_value || t('admin.orderProfileValidation.noValue') }}</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>
|
||||
@@ -254,6 +425,8 @@ button:disabled { cursor: not-allowed; opacity: .55; }
|
||||
.current-draft-validation { display: grid; gap: 16px; margin-top: 20px; padding: 16px; }.current-draft-validation > header { align-items: center; }.current-draft-validation > header > div { min-width: 0; }.current-draft-validation > header button { flex: 0 0 auto; }.checks { display: grid; gap: 10px; }.checks article { display: flex; align-items: center; justify-content: space-between; gap: 20px; border-radius: 8px; padding: 15px 16px; }.status { min-width: 72px; text-align: right; font-size: 13px; font-weight: 600; }.passed { color: #15803d; }.failed, .stale { color: #b91c1c; }.pending, .running { color: #64748b; }
|
||||
.blind-test-gate { display: flex; align-items: center; justify-content: space-between; gap: 20px; margin-top: 20px; padding: 16px; }.blind-test-gate h2 { margin: 0; color: #1e293b; font-size: 15px; font-weight: 600; }.gate-actions { display: flex; align-items: center; flex-wrap: wrap; gap: 8px; }.gate-actions .approved { color: #15803d; }.gate-actions .draft, .gate-actions .missing { color: #b45309; }
|
||||
.results { margin-top: 20px; padding: 16px; }.results-heading { display: flex; align-items: center; justify-content: space-between; gap: 16px; }.results h2, .results h3 { margin: 0; color: #1e293b; }.results h2 { font-size: 15px; }.results h3 { margin-top: 20px; font-size: 14px; }.results-heading p { margin: 5px 0 0; color: #64748b; font-size: 13px; line-height: 1.5; }.header-results { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 10px; margin: 12px 0 0; }.header-results div { border: 1px solid #e5ebf1; border-radius: 6px; background: #fbfdff; padding: 10px; }.header-results dt { color: #475569; font-size: 13px; font-weight: 600; }.header-results dd { margin: 4px 0 0; overflow-wrap: anywhere; }.header-results .field-code, .line-results th small { color: #94a3b8; font-size: 11px; font-weight: 400; }.line-results { margin-top: 12px; overflow-x: auto; border: 1px solid #e5ebf1; border-radius: 6px; }.line-results table { width: 100%; min-width: 560px; border-collapse: collapse; }.line-results th, .line-results td { padding: 10px 12px; border-bottom: 1px solid #e5ebf1; text-align: left; vertical-align: top; overflow-wrap: anywhere; }.line-results tbody tr:last-child td { border-bottom: 0; }.line-results th { background: #f8fafc; color: #64748b; font-size: 12px; font-weight: 600; }.line-results th span, .line-results th small { display: block; }.deleted-row { color: #94a3b8; text-decoration: line-through; }.result-error { color: #b91c1c; }
|
||||
.header-results .field-needs_review, .header-results .field-unavailable { border-color: #fed7aa; background: #fff7ed; }.header-results .field-issues { color: #b45309; font-size: 11px; }
|
||||
.header-results .field-needs_review, .header-results .field-unavailable, .header-results .field-failed, .header-results .field-missing { border-color: #fed7aa; background: #fff7ed; }.header-results .field-issues { color: #b45309; font-size: 11px; }
|
||||
.header-results .field-passed { border-color: #bbf7d0; background: #f0fdf4; }
|
||||
.xfa-line-card { margin-top: 12px; padding: 12px; border: 1px solid #e5ebf1; border-radius: 8px; background: #fbfdff; }.xfa-line-card h4 { margin: 0 0 8px; font-size: 13px; color: #475569; }
|
||||
@media (max-width: 767px) { .validation-page { padding: 16px; } header, .validation-state, .current-draft-validation > header, .checks article, .blind-test-gate, .results-heading { display: grid; }.validation-state button, .current-draft-validation > header button, .blind-test-gate button, .results-heading button { width: 100%; } }
|
||||
</style>
|
||||
+293
@@ -0,0 +1,293 @@
|
||||
/**
|
||||
* features/admin/modules/shipping-order-document-profiles/XfaProfileMappingPage.spec.ts
|
||||
* 用途:挂载 XFA 映射页并验证四栏布局加载。
|
||||
* 依赖:Vitest、@vue/test-utils、XfaProfileMappingPage。
|
||||
*/
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { mount, flushPromises } from '@vue/test-utils';
|
||||
import { createI18n } from 'vue-i18n';
|
||||
import XfaProfileMappingPage from './XfaProfileMappingPage.vue';
|
||||
import XfaSplitRulePanel from './components/XfaSplitRulePanel.vue';
|
||||
|
||||
const { saveDraftMock, splitPreviewMock, detailDefinition } = vi.hoisted(() => ({
|
||||
saveDraftMock: vi.fn(),
|
||||
splitPreviewMock: vi.fn(),
|
||||
detailDefinition: { value: null as Record<string, unknown> | null },
|
||||
}));
|
||||
|
||||
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: [],
|
||||
};
|
||||
|
||||
vi.mock('vue-router', () => ({
|
||||
useRoute: () => ({ params: { profileId: '52', profileCode: 'ODP-TEST' }, query: {} }),
|
||||
useRouter: () => ({ push: vi.fn() }),
|
||||
onBeforeRouteLeave: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('@/shared/composables/useMessage', () => ({
|
||||
useMessage: () => ({ success: vi.fn(), error: 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 }],
|
||||
})),
|
||||
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(),
|
||||
}));
|
||||
|
||||
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',
|
||||
}, {
|
||||
field_id: 'f-bill', field_code: 'bill_to_customer', scope: 'header', display_name: '账款客户', required: false,
|
||||
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',
|
||||
}, {
|
||||
field_id: 'f-line', field_code: 'part_number', scope: 'line', display_name: '料号', required: false,
|
||||
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',
|
||||
}],
|
||||
},
|
||||
}],
|
||||
})),
|
||||
}));
|
||||
|
||||
vi.mock('@/features/auth/stores/auth.store', () => ({
|
||||
useAuthStore: () => ({
|
||||
user: {
|
||||
feature_permissions: {
|
||||
'shipping_notice.xfa_split_rule_edit': true,
|
||||
'shipping_notice.xfa_split_rule_preview': true,
|
||||
'shipping_notice.audit_sensitive_read': true,
|
||||
},
|
||||
},
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock('pinia', async () => {
|
||||
const actual = await vi.importActual<typeof import('pinia')>('pinia');
|
||||
return {
|
||||
...actual,
|
||||
storeToRefs: (store: { user: unknown }) => ({ user: { value: store.user } }),
|
||||
};
|
||||
});
|
||||
|
||||
const i18n = createI18n({
|
||||
legacy: false,
|
||||
locale: 'zh-CN',
|
||||
fallbackLocale: 'zh-CN',
|
||||
messages: {
|
||||
'zh-CN': {
|
||||
common: { yes: '是', no: '否' },
|
||||
admin: {
|
||||
shippingOrderProfiles: {
|
||||
templateModes: { xfa_dataset: 'XFA' },
|
||||
workbench: {
|
||||
headerReturnToLibrary: '返回',
|
||||
headerSaveDraft: '保存',
|
||||
headerValidate: '验证',
|
||||
headerRecoverLease: '恢复',
|
||||
headerTakeOverLease: '接管',
|
||||
saveStatus: { saved: '已保存', saving: '保存中', failed: '失败', readonly: '只读' },
|
||||
leaveConfirm: '离开?',
|
||||
},
|
||||
xfaWorkbench: {
|
||||
loading: '加载', loadFailed: '失败', saved: '已保存', saveFailed: '失败', scopeMismatch: 'scope',
|
||||
treeTitle: '树', searchPaths: '搜', collectionBadge: '集合', treeEmpty: '空',
|
||||
schemaTitle: 'Schema', selectLeafFirst: '选叶子', unbind: '解除',
|
||||
filter: { all: '全部', unmapped: '未映射', required: '必填' },
|
||||
scope: { header: '表头', line: '明细' },
|
||||
previewTitle: '预览', blockersTitle: '阻断', currentNode: '节点', noneSelected: '无',
|
||||
headerMaps: '表头映射', lineMaps: '明细映射', requiredCoverage: '{mapped}/{total}',
|
||||
maskedSample: '脱敏', noMappings: '无映射', crossChecksTitle: '交叉校验',
|
||||
crossCheck: { acroform: 'AcroForm', mirror: '镜像', lineAmount: '金额', totalAmount: '总额' },
|
||||
previewHint: '验证页', retryLoad: '重试',
|
||||
blocker: {
|
||||
authoritative_collection_required: '权威必选',
|
||||
duplicate_field_binding: '重复',
|
||||
required_fields_unmapped: '必填未映射',
|
||||
},
|
||||
collectionsTitle: '集合', authoritativeCollection: '权威', selectAuthoritative: '选择',
|
||||
mirrorCollections: '镜像', rowCount: '{count} 行',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
describe('XfaProfileMappingPage', () => {
|
||||
beforeEach(() => {
|
||||
saveDraftMock.mockReset();
|
||||
splitPreviewMock.mockReset();
|
||||
detailDefinition.value = null;
|
||||
});
|
||||
|
||||
const mountPage = async () => {
|
||||
const wrapper = mount(XfaProfileMappingPage, { global: { plugins: [i18n] } });
|
||||
for (let i = 0; i < 5; i += 1) {
|
||||
await flushPromises();
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
if (wrapper.find('.xfa-workbench__grid').exists()) break;
|
||||
}
|
||||
return wrapper;
|
||||
};
|
||||
|
||||
it('mounts four-column grid after bootstrap', async () => {
|
||||
const wrapper = await mountPage();
|
||||
expect(wrapper.find('.xfa-workbench__grid').exists()).toBe(true);
|
||||
expect(wrapper.find('.xfa-tree').exists()).toBe(true);
|
||||
expect(wrapper.find('.xfa-schema__filters').text()).not.toContain('必填');
|
||||
|
||||
await wrapper.find('[data-xfa-path-id="material-path"] .add-rule').trigger('click');
|
||||
await flushPromises();
|
||||
expect(wrapper.find('.xfa-rule-dialog').exists()).toBe(true);
|
||||
});
|
||||
|
||||
it('persists confirmed rules and renders them below the source tree node', async () => {
|
||||
saveDraftMock.mockResolvedValueOnce({
|
||||
id: 52, profile_code: 'ODP-TEST', display_name: 'Fox PO', schema_version_id: 1, lock_version: 2,
|
||||
template_mode: 'xfa_dataset',
|
||||
definition: {
|
||||
...structuredClone(baseDefinition),
|
||||
split_rules: [{
|
||||
rule_id: 'ruleset-1', rule_version: 1, source_path_id: 'material-path', source_field_code: 'MATNR',
|
||||
strategy: 'pipeline', status: 'confirmed', requires_confirmation: false, source: 'user',
|
||||
rules: [{
|
||||
rule_id: 'rule-1', order: 1,
|
||||
stages: [{ stage_id: 'stage-1', type: 'select_line', line_index: 1 }],
|
||||
segment: { segment_id: 'seg-1', segment_code: 'customer_part', display_name: '客户料号', handling: 'mapped', target_field_id: 'f1', target_field_code: 'customer_po_no' },
|
||||
}],
|
||||
}],
|
||||
},
|
||||
});
|
||||
splitPreviewMock.mockResolvedValueOnce({
|
||||
preview: {
|
||||
segments: [{ rule_id: 'rule-1', normalized_text: 'TEMP••922', raw_text: 'TEMP-922' }],
|
||||
},
|
||||
});
|
||||
const wrapper = await mountPage();
|
||||
await wrapper.find('[data-xfa-path-id="material-path"] .add-rule').trigger('click');
|
||||
await flushPromises();
|
||||
|
||||
const rules = [{
|
||||
rule_id: 'ruleset-1', rule_version: 1, source_path_id: 'material-path', source_field_code: 'MATNR',
|
||||
strategy: 'pipeline' as const, status: 'confirmed' as const, requires_confirmation: false, source: 'user' as const,
|
||||
rules: [{
|
||||
rule_id: 'rule-1', order: 1,
|
||||
stages: [{ stage_id: 'stage-1', type: 'select_line' as const, line_index: 1 }],
|
||||
segment: { segment_id: 'seg-1', segment_code: 'customer_part', display_name: '客户料号', handling: 'mapped' as const, target_field_id: 'f1', target_field_code: 'customer_po_no' },
|
||||
}],
|
||||
}];
|
||||
wrapper.findComponent(XfaSplitRulePanel).vm.$emit('confirmed', rules);
|
||||
await flushPromises();
|
||||
|
||||
expect(saveDraftMock).toHaveBeenCalledWith(52, expect.objectContaining({
|
||||
definition: expect.objectContaining({ split_rules: rules }),
|
||||
}));
|
||||
expect(wrapper.find('[data-xfa-path-id="material-path"] + .xfa-tree__rules').text()).toContain('客户料号');
|
||||
expect(wrapper.find('.xfa-schema').text()).toContain('TEMP••922');
|
||||
expect(wrapper.findAll('.field__value').map((item) => item.text())).not.toContain('TEMP-S');
|
||||
expect(wrapper.find('.xfa-rule-dialog').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it('keeps the rule dialog open when confirmed rules fail to save', async () => {
|
||||
saveDraftMock.mockRejectedValueOnce(new Error('save failed'));
|
||||
const wrapper = await mountPage();
|
||||
await wrapper.find('[data-xfa-path-id="material-path"] .add-rule').trigger('click');
|
||||
await flushPromises();
|
||||
const rules = [{
|
||||
rule_id: 'ruleset-1', rule_version: 1, source_path_id: 'material-path', source_field_code: 'MATNR',
|
||||
strategy: 'pipeline' as const, status: 'confirmed' as const, requires_confirmation: false,
|
||||
rules: [],
|
||||
}];
|
||||
wrapper.findComponent(XfaSplitRulePanel).vm.$emit('confirmed', rules);
|
||||
await flushPromises();
|
||||
expect(wrapper.find('.xfa-rule-dialog').exists()).toBe(true);
|
||||
});
|
||||
|
||||
it('allows a header source split rule to map a header field only', async () => {
|
||||
detailDefinition.value = {
|
||||
...structuredClone(baseDefinition),
|
||||
split_rules: [{
|
||||
rule_id: 'header-rules', rule_version: 1, source_path_id: 'invoiced-to-path', source_field_code: 'INVOICED_TO',
|
||||
strategy: 'pipeline', status: 'confirmed', requires_confirmation: false, source: 'user',
|
||||
rules: [{
|
||||
rule_id: 'bill-rule', order: 1,
|
||||
stages: [{ stage_id: 'stage-1', type: 'select_line', line_index: 1 }],
|
||||
segment: { segment_id: 'seg-bill', segment_code: 'bill_customer', display_name: '账款客户', handling: 'evidence_only' },
|
||||
}],
|
||||
}],
|
||||
};
|
||||
const wrapper = await mountPage();
|
||||
await wrapper.find('[data-xfa-path-id="invoiced-to-path"] + .xfa-tree__rules .xfa-tree__rule-main').trigger('click');
|
||||
await flushPromises();
|
||||
|
||||
const billButton = wrapper.findAll('button.field').find((item) => item.text().includes('bill_to_customer'));
|
||||
const lineButton = wrapper.findAll('button.field').find((item) => item.text().includes('part_number'));
|
||||
expect(billButton?.attributes('disabled')).toBeUndefined();
|
||||
expect(lineButton?.attributes('disabled')).toBeDefined();
|
||||
await billButton?.trigger('click');
|
||||
expect((wrapper.vm as unknown as { definition: typeof baseDefinition }).definition.split_rules?.[0].rules[0].segment)
|
||||
.toMatchObject({ handling: 'mapped', target_field_id: 'f-bill', target_field_code: 'bill_to_customer' });
|
||||
});
|
||||
});
|
||||
+748
@@ -0,0 +1,748 @@
|
||||
<!--
|
||||
features/admin/modules/shipping-order-document-profiles/XfaProfileMappingPage.vue
|
||||
用途:XFA 四栏映射工作台(数据树 / 拆分规则 / Schema / 预览),复用 Lease/Revision/operation_id。
|
||||
依赖:Profile/XFA API、Schema API、Xfa* 组件、xfaProfileMapping.utils。
|
||||
逻辑:加载草稿与样本树;权威集合必选后可保存;租约 409 进入只读;脏状态离开确认。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue';
|
||||
import { onBeforeRouteLeave, useRoute, useRouter } from 'vue-router';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { BusinessError } from '@/shared/api/client';
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
import { getShippingOrderSchemaState } from '@/features/admin/api/shipping-order-schema.api';
|
||||
import {
|
||||
acquireOrderDocumentProfileEditLease,
|
||||
getOrderDocumentProfileDetail,
|
||||
getOrderProfileSampleXfaCollections,
|
||||
getOrderProfileSampleXfaFieldTree,
|
||||
previewOrderProfileSampleXfaSplitRules,
|
||||
previewOrderProfileSampleXfaValue,
|
||||
listOrderProfileBoundSamples,
|
||||
releaseOrderDocumentProfileEditLease,
|
||||
renewOrderDocumentProfileEditLease,
|
||||
saveOrderDocumentProfileDraft,
|
||||
} from '@/features/admin/api/shipping-order-document-profile.api';
|
||||
import type {
|
||||
OrderXfaDatasetProfileDefinition,
|
||||
XfaCollectionCandidate,
|
||||
XfaFieldTreeNode,
|
||||
} from '@/features/admin/types/shipping-order-document-profile.types';
|
||||
import { isXfaDatasetProfileDefinition } from '@/features/admin/types/shipping-order-document-profile.types';
|
||||
import type { ShippingOrderFieldConfig } from '@/features/admin/types/shipping-order-schema.types';
|
||||
import XfaDatasetTree from './components/XfaDatasetTree.vue';
|
||||
import XfaSchemaMappingPanel from './components/XfaSchemaMappingPanel.vue';
|
||||
import XfaSplitRulePanel from './components/XfaSplitRulePanel.vue';
|
||||
import {
|
||||
bindXfaSchemaField,
|
||||
buildXfaPathLabel,
|
||||
computeXfaMappingCoverage,
|
||||
flattenXfaTreeNodes,
|
||||
isSameXfaDefinition,
|
||||
resolveAuthoritativePathId,
|
||||
resolveMirrorPathIds,
|
||||
resolveXfaNodeScope,
|
||||
summarizeXfaMappingBlockers,
|
||||
unbindXfaSchemaField,
|
||||
} from './xfaProfileMapping.utils';
|
||||
|
||||
const { t } = useI18n();
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
const message = useMessage();
|
||||
|
||||
const profileId = computed(() => Number(route.params.profileId));
|
||||
const editorSessionId = String(route.query.editorSessionId || crypto.randomUUID());
|
||||
const loading = ref(true);
|
||||
const loadError = ref(false);
|
||||
const saving = ref(false);
|
||||
const saveState = ref<'saved' | 'saving' | 'failed' | 'readonly'>('saved');
|
||||
const editLeaseToken = ref('');
|
||||
const lockVersion = ref(0);
|
||||
const schemaFields = ref<ShippingOrderFieldConfig[]>([]);
|
||||
const definition = ref<OrderXfaDatasetProfileDefinition | null>(null);
|
||||
const savedSnapshot = ref<OrderXfaDatasetProfileDefinition | null>(null);
|
||||
const tree = ref<XfaFieldTreeNode | null>(null);
|
||||
const collections = ref<XfaCollectionCandidate[]>([]);
|
||||
const excludedCollections = ref<XfaCollectionCandidate[]>([]);
|
||||
const annotationDocumentId = ref(0);
|
||||
const selectedPathId = ref<string | null>(null);
|
||||
const selectedPathIsLeaf = ref(false);
|
||||
const selectedRuleId = ref<string | null>(null);
|
||||
const splitRuleDialogOpen = ref(false);
|
||||
const splitRuleDialogAutoAdd = ref(false);
|
||||
const splitRulePanel = ref<{ addRule: () => void; runPreview: () => void; confirmRules: () => void } | null>(null);
|
||||
const dialogDefinition = ref<OrderXfaDatasetProfileDefinition | null>(null);
|
||||
const revealedValues = ref<Record<string, string>>({});
|
||||
const splitRulePreviewValues = ref<Record<string, string>>({});
|
||||
const revealingPathId = ref('');
|
||||
const revealTimers = new Map<string, ReturnType<typeof setTimeout>>();
|
||||
const authoritativePathId = ref('');
|
||||
const mirrorPathIds = ref<string[]>([]);
|
||||
const displayName = ref('');
|
||||
const profileCode = ref('');
|
||||
const schemaVersionId = ref(0);
|
||||
let renewTimer: ReturnType<typeof setInterval> | null = null;
|
||||
|
||||
const flatNodes = computed(() => flattenXfaTreeNodes(tree.value));
|
||||
const selectedPathLabel = computed(() => (
|
||||
selectedPathId.value ? buildXfaPathLabel(selectedPathId.value, flatNodes.value) : ''
|
||||
));
|
||||
const selectedFieldCode = computed(() => {
|
||||
if (!selectedPathId.value) return '';
|
||||
return flatNodes.value.find((item) => item.pathId === selectedPathId.value)?.localName || '';
|
||||
});
|
||||
const selectedIsMultiline = computed(() => {
|
||||
if (!selectedPathId.value) return false;
|
||||
const node = flatNodes.value.find((item) => item.pathId === selectedPathId.value);
|
||||
return (node?.lineCount || 0) > 1;
|
||||
});
|
||||
const selectedSourceScope = computed(() => (
|
||||
selectedPathId.value
|
||||
? resolveXfaNodeScope(selectedPathId.value, authoritativePathId.value, flatNodes.value)
|
||||
: null
|
||||
));
|
||||
const canEditSplitRules = computed(() => saveState.value !== 'readonly');
|
||||
const canPreviewSplitRules = computed(() => true);
|
||||
const canRevealSensitiveSplit = computed(() => true);
|
||||
const splitRulePersistedConfirmed = computed(() => {
|
||||
const pathId = selectedPathId.value;
|
||||
if (!pathId || !definition.value || !savedSnapshot.value) return true;
|
||||
const current = (definition.value.split_rules || []).find((item) => item.source_path_id === pathId);
|
||||
if (!current || current.status !== 'confirmed') return true;
|
||||
const saved = (savedSnapshot.value.split_rules || []).find((item) => item.source_path_id === pathId);
|
||||
return !!saved && JSON.stringify(current) === JSON.stringify(saved);
|
||||
});
|
||||
const mappedFieldPreviews = computed(() => {
|
||||
if (!definition.value) return { header: [], line: [] };
|
||||
const byPath = new Map(flatNodes.value.map((item) => [item.pathId, item]));
|
||||
const mapItems = (items: Array<{ mapping_id: string; field_code: string; path_id: string }>) =>
|
||||
items.map((item) => ({
|
||||
mappingId: item.mapping_id,
|
||||
fieldCode: item.field_code,
|
||||
pathId: item.path_id,
|
||||
pathLabel: byPath.get(item.path_id)
|
||||
? buildXfaPathLabel(item.path_id, flatNodes.value)
|
||||
: item.path_id,
|
||||
maskedValue: revealedValues.value[item.path_id] || byPath.get(item.path_id)?.sampleValueDisplay || null,
|
||||
}));
|
||||
const splitItems = (definition.value.split_rules || []).flatMap((ruleSet) =>
|
||||
[...ruleSet.rules]
|
||||
.sort((a, b) => a.order - b.order)
|
||||
.filter((rule) => rule.segment.handling === 'mapped' && rule.segment.target_field_code)
|
||||
.map((rule, index) => ({
|
||||
mappingId: rule.segment.segment_id,
|
||||
fieldCode: String(rule.segment.target_field_code),
|
||||
pathId: ruleSet.source_path_id,
|
||||
pathLabel: `${buildXfaPathLabel(ruleSet.source_path_id, flatNodes.value)} / ${t('admin.shippingOrderProfiles.xfaSplit.ruleLabel', { index: index + 1 })} · ${rule.segment.display_name || rule.segment.segment_code}`,
|
||||
maskedValue: splitRulePreviewValues.value[rule.rule_id] || null,
|
||||
})),
|
||||
);
|
||||
const splitItemsByScope = splitItems.reduce((groups, item) => {
|
||||
const scope = resolveXfaNodeScope(item.pathId, authoritativePathId.value, flatNodes.value);
|
||||
if (scope) groups[scope].push(item);
|
||||
return groups;
|
||||
}, { header: [] as typeof splitItems, line: [] as typeof splitItems });
|
||||
return {
|
||||
header: [...mapItems(definition.value.header_mappings || []), ...splitItemsByScope.header],
|
||||
line: [...mapItems(definition.value.line_mapping?.fields || []), ...splitItemsByScope.line],
|
||||
};
|
||||
});
|
||||
|
||||
const dirty = computed(() => !isSameXfaDefinition(definition.value, savedSnapshot.value)
|
||||
|| Boolean(authoritativePathId.value && definition.value
|
||||
&& authoritativePathId.value !== savedAuthoritativePathId.value)
|
||||
|| JSON.stringify([...mirrorPathIds.value].sort()) !== JSON.stringify([...savedMirrorPathIds.value].sort()));
|
||||
const savedAuthoritativePathId = ref('');
|
||||
const savedMirrorPathIds = ref<string[]>([]);
|
||||
|
||||
/**
|
||||
* 将 XFA JSON 契约数据复制为不含 Vue Proxy 的普通对象。
|
||||
* 核心逻辑:定义和规则契约只包含可序列化字段;JSON 快照可安全跨越组件事件与保存 payload。
|
||||
* @param value 当前响应式或普通 JSON 契约数据
|
||||
* @returns 可独立编辑和持久化的纯对象副本
|
||||
*/
|
||||
function cloneXfaData<T>(value: T): T {
|
||||
return JSON.parse(JSON.stringify(value)) as T;
|
||||
}
|
||||
const coverage = computed(() => computeXfaMappingCoverage(
|
||||
schemaFields.value,
|
||||
definition.value || undefined,
|
||||
authoritativePathId.value,
|
||||
));
|
||||
const blockers = computed(() => summarizeXfaMappingBlockers(coverage.value));
|
||||
const mappedPathIds = computed(() => {
|
||||
if (!definition.value) return [];
|
||||
return [
|
||||
...definition.value.header_mappings.map((item) => item.path_id),
|
||||
...definition.value.line_mapping.fields.map((item) => item.path_id),
|
||||
];
|
||||
});
|
||||
const splitRuleSets = computed(() => definition.value?.split_rules || []);
|
||||
const dialogHasRules = computed(() => Boolean(
|
||||
selectedPathId.value
|
||||
&& dialogDefinition.value?.split_rules?.find((item) => item.source_path_id === selectedPathId.value)?.rules.length,
|
||||
));
|
||||
|
||||
/**
|
||||
* 获取或恢复编辑租约。
|
||||
*/
|
||||
async function acquireLease(confirmTakeover = false): Promise<void> {
|
||||
try {
|
||||
const lease = await acquireOrderDocumentProfileEditLease(profileId.value, {
|
||||
browser_session_id: editorSessionId,
|
||||
operation_id: crypto.randomUUID(),
|
||||
confirm_takeover: confirmTakeover,
|
||||
});
|
||||
editLeaseToken.value = lease.lease_token;
|
||||
saveState.value = 'saved';
|
||||
} catch (error) {
|
||||
if (error instanceof BusinessError && String(error.code || '').includes('LEASE')) {
|
||||
saveState.value = 'readonly';
|
||||
return;
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 从已保存 definition 恢复权威/镜像集合选择(按路径哈希精确匹配)。
|
||||
*/
|
||||
async function restoreCollectionSelection(def: OrderXfaDatasetProfileDefinition): Promise<void> {
|
||||
const flat = flattenXfaTreeNodes(tree.value);
|
||||
const restoredAuth = await resolveAuthoritativePathId(def, collections.value, flat);
|
||||
authoritativePathId.value = restoredAuth;
|
||||
savedAuthoritativePathId.value = restoredAuth;
|
||||
const restoredMirrors = await resolveMirrorPathIds(def, collections.value, restoredAuth);
|
||||
mirrorPathIds.value = restoredMirrors;
|
||||
savedMirrorPathIds.value = [...restoredMirrors];
|
||||
}
|
||||
|
||||
/**
|
||||
* 加载 Profile、Schema、XFA 树与集合,并恢复已保存权威/镜像选择。
|
||||
*/
|
||||
async function load(): Promise<void> {
|
||||
loading.value = true;
|
||||
loadError.value = false;
|
||||
try {
|
||||
const [profile, schemaState, samples] = await Promise.all([
|
||||
getOrderDocumentProfileDetail(profileId.value),
|
||||
getShippingOrderSchemaState(),
|
||||
listOrderProfileBoundSamples(profileId.value),
|
||||
]);
|
||||
if (!isXfaDatasetProfileDefinition(profile.definition)) {
|
||||
throw new Error('not_xfa');
|
||||
}
|
||||
definition.value = structuredClone(profile.definition);
|
||||
savedSnapshot.value = structuredClone(profile.definition);
|
||||
lockVersion.value = profile.lock_version;
|
||||
displayName.value = profile.display_name;
|
||||
profileCode.value = profile.profile_code;
|
||||
schemaVersionId.value = profile.schema_version_id;
|
||||
const schema = (schemaState.versions || []).find((item) => item.id === profile.schema_version_id);
|
||||
schemaFields.value = (schema?.definition?.fields || []) as ShippingOrderFieldConfig[];
|
||||
const annotation = samples.find((item) => item.sample_role === 'annotation') || samples[0];
|
||||
annotationDocumentId.value = annotation?.document_id || 0;
|
||||
if (!annotationDocumentId.value) throw new Error('missing_sample');
|
||||
const [treeRes, collRes] = await Promise.all([
|
||||
getOrderProfileSampleXfaFieldTree(annotationDocumentId.value),
|
||||
getOrderProfileSampleXfaCollections(annotationDocumentId.value),
|
||||
]);
|
||||
tree.value = (treeRes.tree && 'path_id' in treeRes.tree) ? treeRes.tree as XfaFieldTreeNode : null;
|
||||
collections.value = collRes.collection_candidates || [];
|
||||
excludedCollections.value = collRes.excluded_collection_candidates || [];
|
||||
await restoreCollectionSelection(profile.definition);
|
||||
await refreshSplitRulePreviews(profile.definition.split_rules || []);
|
||||
await acquireLease(false);
|
||||
startRenewal();
|
||||
} catch (error) {
|
||||
loadError.value = true;
|
||||
definition.value = null;
|
||||
message.error(error instanceof BusinessError ? error.message : t('admin.shippingOrderProfiles.xfaWorkbench.loadFailed'));
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行各字段拆分规则并按 rule_id 缓存脱敏结果。
|
||||
* 核心逻辑:规则预览失败时保持空值,禁止回退到源字段整段内容造成错误映射认知。
|
||||
* @param ruleSets 当前已保存或待展示的规则集合
|
||||
*/
|
||||
async function refreshSplitRulePreviews(
|
||||
ruleSets: import('@/features/admin/types/shipping-order-document-profile.types').XfaSplitRuleSet[],
|
||||
): Promise<void> {
|
||||
if (!annotationDocumentId.value) {
|
||||
splitRulePreviewValues.value = {};
|
||||
return;
|
||||
}
|
||||
const next: Record<string, string> = {};
|
||||
await Promise.allSettled(ruleSets.map(async (ruleSet) => {
|
||||
if (!ruleSet.rules?.length) return;
|
||||
const response = await previewOrderProfileSampleXfaSplitRules(annotationDocumentId.value, {
|
||||
path_id: ruleSet.source_path_id,
|
||||
rule_set: ruleSet as unknown as Record<string, unknown>,
|
||||
profile_id: profileId.value,
|
||||
reveal: false,
|
||||
});
|
||||
for (const segment of response.preview?.segments || []) {
|
||||
const value = String(segment.normalized_text || segment.raw_text || '').trim();
|
||||
if (segment.rule_id && value) next[segment.rule_id] = value;
|
||||
}
|
||||
}));
|
||||
splitRulePreviewValues.value = next;
|
||||
}
|
||||
|
||||
/**
|
||||
* 绑定选中叶子或规则结果到同作用域 Schema 字段。
|
||||
* 规则继承源节点作用域,避免 Header 源规则被错误限制为明细字段。
|
||||
*/
|
||||
function onBindField(field: ShippingOrderFieldConfig, scope: 'header' | 'line'): void {
|
||||
if (!definition.value || !selectedPathId.value) return;
|
||||
if (selectedRuleId.value) {
|
||||
if (!selectedSourceScope.value || scope !== selectedSourceScope.value) {
|
||||
message.error(t('admin.shippingOrderProfiles.xfaWorkbench.scopeMismatch'));
|
||||
return;
|
||||
}
|
||||
const selectedId = selectedRuleId.value;
|
||||
const nextDefinition = unbindXfaSchemaField(definition.value, field.field_id);
|
||||
definition.value = {
|
||||
...nextDefinition,
|
||||
split_rules: (nextDefinition.split_rules || []).map((ruleSet) => ({
|
||||
...ruleSet,
|
||||
rules: ruleSet.rules.map((rule) => {
|
||||
const segment = rule.segment;
|
||||
if (rule.rule_id === selectedId) {
|
||||
return {
|
||||
...rule,
|
||||
segment: {
|
||||
...segment,
|
||||
handling: 'mapped',
|
||||
target_field_id: field.field_id,
|
||||
target_field_code: field.field_code,
|
||||
},
|
||||
};
|
||||
}
|
||||
if (segment.target_field_id === field.field_id) {
|
||||
return {
|
||||
...rule,
|
||||
segment: { ...segment, handling: 'evidence_only', target_field_id: null, target_field_code: null },
|
||||
};
|
||||
}
|
||||
return rule;
|
||||
}),
|
||||
})),
|
||||
};
|
||||
return;
|
||||
}
|
||||
const current = [
|
||||
...(definition.value.header_mappings || []),
|
||||
...(definition.value.line_mapping?.fields || []),
|
||||
].find((item) => item.field_id === field.field_id);
|
||||
if (current && current.path_id !== selectedPathId.value) {
|
||||
const oldLabel = buildXfaPathLabel(current.path_id, flatNodes.value) || current.path_id;
|
||||
const newLabel = buildXfaPathLabel(selectedPathId.value, flatNodes.value) || selectedPathId.value;
|
||||
if (!window.confirm(t('admin.shippingOrderProfiles.xfaWorkbench.replaceConfirm', { old: oldLabel, next: newLabel }))) return;
|
||||
}
|
||||
try {
|
||||
const definitionWithoutSplitTarget = {
|
||||
...definition.value,
|
||||
split_rules: (definition.value.split_rules || []).map((ruleSet) => ({
|
||||
...ruleSet,
|
||||
rules: ruleSet.rules.map((rule) => rule.segment.target_field_id === field.field_id
|
||||
? { ...rule, segment: { ...rule.segment, handling: 'evidence_only' as const, target_field_id: null, target_field_code: null } }
|
||||
: rule),
|
||||
})),
|
||||
};
|
||||
definition.value = bindXfaSchemaField({
|
||||
definition: definitionWithoutSplitTarget,
|
||||
scope,
|
||||
field,
|
||||
pathId: selectedPathId.value,
|
||||
});
|
||||
} catch {
|
||||
message.error(t('admin.shippingOrderProfiles.xfaWorkbench.scopeMismatch'));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 按管理员敏感读权限临时查看当前字段完整值。
|
||||
* 核心逻辑:只保存在当前页面内存;后端对每次读取写入敏感审计与加密快照。
|
||||
*/
|
||||
async function revealSelectedValue(): Promise<void> {
|
||||
if (!selectedPathId.value || !annotationDocumentId.value) return;
|
||||
const pathId = selectedPathId.value;
|
||||
revealingPathId.value = pathId;
|
||||
try {
|
||||
const result = await previewOrderProfileSampleXfaValue(annotationDocumentId.value, pathId, true);
|
||||
const previousTimer = revealTimers.get(pathId);
|
||||
if (previousTimer) clearTimeout(previousTimer);
|
||||
revealedValues.value = { ...revealedValues.value, [pathId]: result.display_value };
|
||||
revealTimers.set(pathId, setTimeout(() => {
|
||||
const next = { ...revealedValues.value };
|
||||
delete next[pathId];
|
||||
revealedValues.value = next;
|
||||
revealTimers.delete(pathId);
|
||||
}, 60_000));
|
||||
} catch (error) {
|
||||
message.error(error instanceof BusinessError ? error.message : t('admin.shippingOrderProfiles.xfaWorkbench.revealFailed'));
|
||||
} finally {
|
||||
revealingPathId.value = '';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 解除字段映射。
|
||||
*/
|
||||
function onUnbindField(fieldId: string): void {
|
||||
if (!definition.value) return;
|
||||
const next = unbindXfaSchemaField(definition.value, fieldId);
|
||||
definition.value = {
|
||||
...next,
|
||||
split_rules: (next.split_rules || []).map((ruleSet) => ({
|
||||
...ruleSet,
|
||||
rules: ruleSet.rules.map((rule) => rule.segment.target_field_id === fieldId
|
||||
? { ...rule, segment: { ...rule.segment, handling: 'evidence_only', target_field_id: null, target_field_code: null } }
|
||||
: rule),
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存映射:要求权威集合;Lease/lock_version/operation_id 复用坐标治理。
|
||||
*/
|
||||
async function save(): Promise<boolean> {
|
||||
if (!definition.value || saveState.value === 'readonly') return false;
|
||||
if (!authoritativePathId.value) {
|
||||
message.error(t('admin.shippingOrderProfiles.xfaWorkbench.blocker.authoritative_collection_required'));
|
||||
return false;
|
||||
}
|
||||
saving.value = true;
|
||||
saveState.value = 'saving';
|
||||
try {
|
||||
const payloadDefinition: OrderXfaDatasetProfileDefinition & Record<string, unknown> = {
|
||||
...definition.value,
|
||||
authoritative_collection_path_id: authoritativePathId.value,
|
||||
mirror_collection_path_ids: mirrorPathIds.value,
|
||||
};
|
||||
const saved = await saveOrderDocumentProfileDraft(profileId.value, {
|
||||
profile_code: profileCode.value,
|
||||
display_name: displayName.value,
|
||||
schema_version_id: schemaVersionId.value,
|
||||
expected_lock_version: lockVersion.value,
|
||||
definition: payloadDefinition as OrderXfaDatasetProfileDefinition,
|
||||
browser_session_id: editorSessionId,
|
||||
lease_token: editLeaseToken.value,
|
||||
operation_id: crypto.randomUUID(),
|
||||
});
|
||||
if (!isXfaDatasetProfileDefinition(saved.definition)) throw new Error('bad_mode');
|
||||
definition.value = structuredClone(saved.definition);
|
||||
savedSnapshot.value = structuredClone(saved.definition);
|
||||
lockVersion.value = saved.lock_version;
|
||||
await restoreCollectionSelection(saved.definition);
|
||||
await refreshSplitRulePreviews(saved.definition.split_rules || []);
|
||||
saveState.value = 'saved';
|
||||
message.success(t('admin.shippingOrderProfiles.xfaWorkbench.saved'));
|
||||
return true;
|
||||
} catch (error) {
|
||||
if (error instanceof BusinessError && (
|
||||
String(error.code || '').includes('LEASE')
|
||||
|| String(error.code || '').includes('VERSION_CONFLICT')
|
||||
)) {
|
||||
saveState.value = 'readonly';
|
||||
message.error(error.message);
|
||||
return false;
|
||||
}
|
||||
saveState.value = 'failed';
|
||||
message.error(error instanceof BusinessError ? error.message : t('admin.shippingOrderProfiles.xfaWorkbench.saveFailed'));
|
||||
return false;
|
||||
} finally {
|
||||
saving.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
function startRenewal(): void {
|
||||
stopRenewal();
|
||||
renewTimer = setInterval(async () => {
|
||||
if (!editLeaseToken.value || saveState.value === 'readonly') return;
|
||||
try {
|
||||
await renewOrderDocumentProfileEditLease(profileId.value, {
|
||||
browser_session_id: editorSessionId,
|
||||
lease_token: editLeaseToken.value,
|
||||
operation_id: crypto.randomUUID(),
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof BusinessError && String(error.code || '').includes('LEASE')) {
|
||||
saveState.value = 'readonly';
|
||||
}
|
||||
}
|
||||
}, 90_000);
|
||||
}
|
||||
|
||||
function stopRenewal(): void {
|
||||
if (renewTimer) clearInterval(renewTimer);
|
||||
renewTimer = null;
|
||||
}
|
||||
|
||||
onBeforeRouteLeave(async () => {
|
||||
if (!dirty.value) return true;
|
||||
return window.confirm(t('admin.shippingOrderProfiles.workbench.leaveConfirm'));
|
||||
});
|
||||
|
||||
/**
|
||||
* 更新 definition.split_rules 并标记脏状态。
|
||||
*/
|
||||
function onSplitRulesUpdate(rules: import('@/features/admin/types/shipping-order-document-profile.types').XfaSplitRuleSet[]): void {
|
||||
if (!definition.value) return;
|
||||
definition.value = { ...definition.value, split_rules: rules };
|
||||
}
|
||||
|
||||
/**
|
||||
* 弹窗内只更新临时 definition;关闭弹窗不会污染页面草稿。
|
||||
*/
|
||||
function onDialogSplitRulesUpdate(
|
||||
rules: import('@/features/admin/types/shipping-order-document-profile.types').XfaSplitRuleSet[],
|
||||
): void {
|
||||
if (!dialogDefinition.value) return;
|
||||
dialogDefinition.value = { ...dialogDefinition.value, split_rules: rules };
|
||||
}
|
||||
|
||||
/**
|
||||
* 放弃本次弹窗编辑,恢复到打开弹窗前的页面状态。
|
||||
*/
|
||||
function closeSplitRuleDialog(): void {
|
||||
dialogDefinition.value = null;
|
||||
splitRuleDialogAutoAdd.value = false;
|
||||
splitRuleDialogOpen.value = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 确认拆分规则后立即刷新树并保存整个 XFA 定义。
|
||||
* 核心逻辑:使用子组件传回的最终规则消除事件时序差异;保存成功才关闭弹窗,失败保留编辑现场。
|
||||
* @param rules 已标记为 confirmed 的完整拆分规则数组
|
||||
*/
|
||||
async function commitDialogSplitRules(
|
||||
rules: import('@/features/admin/types/shipping-order-document-profile.types').XfaSplitRuleSet[],
|
||||
): Promise<void> {
|
||||
if (!dialogDefinition.value) return;
|
||||
const confirmedDefinition = {
|
||||
...cloneXfaData(dialogDefinition.value),
|
||||
split_rules: cloneXfaData(rules),
|
||||
};
|
||||
dialogDefinition.value = confirmedDefinition;
|
||||
definition.value = structuredClone(confirmedDefinition);
|
||||
const saved = await save();
|
||||
if (saved) closeSplitRuleDialog();
|
||||
}
|
||||
|
||||
function openSplitRuleDialog(autoAdd = false): void {
|
||||
if (!definition.value) return;
|
||||
dialogDefinition.value = cloneXfaData(definition.value);
|
||||
splitRuleDialogAutoAdd.value = autoAdd;
|
||||
splitRuleDialogOpen.value = true;
|
||||
}
|
||||
|
||||
function addRuleForPath(pathId: string): void {
|
||||
selectedPathId.value = pathId;
|
||||
selectedPathIsLeaf.value = true;
|
||||
selectedRuleId.value = null;
|
||||
openSplitRuleDialog(true);
|
||||
}
|
||||
|
||||
/** 选择规则作为 Schema 映射来源,不打开编辑弹窗。 */
|
||||
function selectRule(pathId: string, ruleId: string): void {
|
||||
selectedPathId.value = pathId;
|
||||
selectedPathIsLeaf.value = true;
|
||||
selectedRuleId.value = ruleId;
|
||||
}
|
||||
|
||||
/** 仅由规则行编辑图标打开维护弹窗。 */
|
||||
function editRule(pathId: string, ruleId: string): void {
|
||||
selectRule(pathId, ruleId);
|
||||
openSplitRuleDialog();
|
||||
}
|
||||
|
||||
function deleteRule(pathId: string, ruleId: string): void {
|
||||
const current = definition.value?.split_rules?.find((item) => item.source_path_id === pathId);
|
||||
if (!current || !window.confirm(t('admin.shippingOrderProfiles.xfaSplit.deleteConfirm'))) return;
|
||||
onSplitRulesUpdate((definition.value?.split_rules || []).map((item) => item.source_path_id === pathId
|
||||
? { ...item, rules: item.rules.filter((rule) => rule.rule_id !== ruleId).map((rule, index) => ({ ...rule, order: index + 1 })) }
|
||||
: item));
|
||||
}
|
||||
|
||||
watch(authoritativePathId, (pathId) => {
|
||||
if (!definition.value || !pathId) return;
|
||||
// 本地标记权威已选;真正路径由后端按 path_id 重写。
|
||||
mirrorPathIds.value = mirrorPathIds.value.filter((item) => item !== pathId);
|
||||
});
|
||||
|
||||
onMounted(load);
|
||||
onBeforeUnmount(async () => {
|
||||
revealTimers.forEach((timer) => clearTimeout(timer));
|
||||
revealTimers.clear();
|
||||
stopRenewal();
|
||||
if (editLeaseToken.value) {
|
||||
try {
|
||||
await releaseOrderDocumentProfileEditLease(profileId.value, {
|
||||
browser_session_id: editorSessionId,
|
||||
lease_token: editLeaseToken.value,
|
||||
operation_id: crypto.randomUUID(),
|
||||
});
|
||||
} catch { /* ignore release errors on unload */ }
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="xfa-workbench" v-if="!loading && definition">
|
||||
<header class="xfa-workbench__header">
|
||||
<div>
|
||||
<button type="button" class="link" @click="router.push({ name: 'AdminShippingOrderDocumentProfiles' })">
|
||||
← {{ t('admin.shippingOrderProfiles.workbench.headerReturnToLibrary') }}
|
||||
</button>
|
||||
<h1>{{ displayName }} · {{ profileCode }}</h1>
|
||||
<p>
|
||||
<span class="mode">{{ t('admin.shippingOrderProfiles.templateModes.xfa_dataset') }}</span>
|
||||
<span>{{ t(`admin.shippingOrderProfiles.workbench.saveStatus.${saveState}`) }}</span>
|
||||
</p>
|
||||
</div>
|
||||
<div class="actions">
|
||||
<button v-if="saveState === 'readonly'" type="button" class="btn-secondary" @click="acquireLease(false)">
|
||||
{{ t('admin.shippingOrderProfiles.workbench.headerRecoverLease') }}
|
||||
</button>
|
||||
<button v-if="saveState === 'readonly'" type="button" class="btn-secondary" @click="acquireLease(true)">
|
||||
{{ t('admin.shippingOrderProfiles.workbench.headerTakeOverLease') }}
|
||||
</button>
|
||||
<button type="button" class="btn-secondary" :disabled="saving || !dirty" @click="save()">
|
||||
{{ t('admin.shippingOrderProfiles.workbench.headerSaveDraft') }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="btn-primary"
|
||||
:disabled="dirty || blockers.includes('authoritative_collection_required')"
|
||||
@click="router.push({ name: 'AdminShippingOrderDocumentProfileValidate', params: { profileCode, profileId } })"
|
||||
>
|
||||
{{ t('admin.shippingOrderProfiles.workbench.headerValidate') }}
|
||||
</button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div class="xfa-workbench__grid">
|
||||
<XfaDatasetTree
|
||||
:tree="tree"
|
||||
:selected-path-id="selectedPathId"
|
||||
:selected-rule-id="selectedRuleId"
|
||||
:mapped-path-ids="mappedPathIds"
|
||||
:revealed-values="revealedValues"
|
||||
:revealing-path-id="revealingPathId"
|
||||
:split-rule-sets="splitRuleSets"
|
||||
@select-path="(pathId, isLeaf) => { selectedPathId = pathId; selectedPathIsLeaf = isLeaf; selectedRuleId = null; }"
|
||||
@reveal-path="(pathId) => { selectedPathId = pathId; void revealSelectedValue(); }"
|
||||
@add-rule="addRuleForPath"
|
||||
@select-rule="selectRule"
|
||||
@edit-rule="editRule"
|
||||
@delete-rule="deleteRule"
|
||||
/>
|
||||
<div class="xfa-workbench__mapping-column">
|
||||
<XfaSchemaMappingPanel
|
||||
:schema-fields="schemaFields"
|
||||
:definition="definition"
|
||||
:mapped-field-previews="mappedFieldPreviews"
|
||||
:selected-path-id="selectedPathId"
|
||||
:selected-path-is-leaf="selectedPathIsLeaf"
|
||||
:selected-rule-id="selectedRuleId"
|
||||
:selected-source-scope="selectedSourceScope"
|
||||
@bind-field="onBindField"
|
||||
@unbind-field="onUnbindField"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="splitRuleDialogOpen" class="xfa-rule-dialog" role="dialog" aria-modal="true">
|
||||
<div class="xfa-rule-dialog__backdrop" @click="closeSplitRuleDialog" />
|
||||
<section class="xfa-rule-dialog__panel">
|
||||
<header class="xfa-rule-dialog__header">
|
||||
<div><strong>{{ t('admin.shippingOrderProfiles.xfaSplit.title') }}</strong><p>{{ selectedPathLabel }}</p></div>
|
||||
<div class="xfa-rule-dialog__actions">
|
||||
<button type="button" class="btn-secondary" :disabled="saveState === 'readonly'" @click="splitRulePanel?.addRule()">
|
||||
{{ t('admin.shippingOrderProfiles.xfaSplit.addRule') }}
|
||||
</button>
|
||||
<button type="button" class="btn-secondary" :disabled="!dialogHasRules" @click="splitRulePanel?.runPreview()">
|
||||
{{ t('admin.shippingOrderProfiles.xfaSplit.preview') }}
|
||||
</button>
|
||||
<button type="button" class="btn-primary" :disabled="saveState === 'readonly' || !dialogHasRules" @click="splitRulePanel?.confirmRules()">
|
||||
{{ t('admin.shippingOrderProfiles.xfaSplit.confirm') }}
|
||||
</button>
|
||||
<button type="button" class="xfa-rule-dialog__close" :aria-label="t('common.close')" @click="closeSplitRuleDialog">×</button>
|
||||
</div>
|
||||
</header>
|
||||
<XfaSplitRulePanel
|
||||
ref="splitRulePanel"
|
||||
:definition="dialogDefinition || definition"
|
||||
:selected-path-id="selectedPathIsLeaf ? selectedPathId : null"
|
||||
:selected-path-label="selectedPathLabel"
|
||||
:selected-field-code="selectedFieldCode"
|
||||
:selected-is-multiline="selectedIsMultiline"
|
||||
:document-id="annotationDocumentId"
|
||||
:profile-id="profileId"
|
||||
:readonly="saveState === 'readonly'"
|
||||
:can-edit="canEditSplitRules"
|
||||
:can-preview="canPreviewSplitRules"
|
||||
:can-reveal-sensitive="canRevealSensitiveSplit"
|
||||
:dirty-unsaved="false"
|
||||
:persisted-confirmed="splitRulePersistedConfirmed"
|
||||
:auto-add-rule="splitRuleDialogAutoAdd"
|
||||
@update:split-rules="onDialogSplitRulesUpdate"
|
||||
@confirmed="commitDialogSplitRules"
|
||||
/>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
</section>
|
||||
<p v-else-if="loading" class="loading">{{ t('admin.shippingOrderProfiles.xfaWorkbench.loading') }}</p>
|
||||
<section v-else-if="loadError" class="xfa-workbench__error" role="alert">
|
||||
<p>{{ t('admin.shippingOrderProfiles.xfaWorkbench.loadFailed') }}</p>
|
||||
<button type="button" class="btn-primary" @click="load()">
|
||||
{{ t('admin.shippingOrderProfiles.xfaWorkbench.retryLoad') }}
|
||||
</button>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.xfa-workbench { display: grid; grid-template-rows: auto minmax(0, 1fr); gap: 12px; height: calc(100dvh - 24px); min-height: 0; padding: 12px 16px; overflow: hidden; background: var(--bg-page); }
|
||||
.xfa-workbench__header { display: flex; justify-content: space-between; gap: 16px; align-items: start; padding: 12px 16px; border: 1px solid var(--border-default); border-radius: var(--radius-surface); background: var(--bg-surface); color: var(--text-primary); }
|
||||
.xfa-workbench__header h1 { margin: 4px 0; font-size: 1.15rem; }
|
||||
.xfa-workbench__header p { display: flex; gap: 12px; margin: 0; color: var(--text-muted); }
|
||||
.mode { color: var(--status-info-fg); font-weight: 700; }
|
||||
.actions { display: flex; flex-wrap: wrap; gap: 8px; }
|
||||
.xfa-workbench__grid { display: grid; grid-template-columns: 360px minmax(0, 1fr); gap: 12px; min-height: 0; min-width: 0; width: 100%; overflow: hidden; }
|
||||
.xfa-workbench__grid > * { min-width: 0; max-width: 100%; overflow: hidden; padding: 12px; border: 1px solid var(--border-default); border-radius: var(--radius-surface); background: var(--bg-surface); min-height: 0; }
|
||||
.xfa-workbench__grid > .xfa-workbench__mapping-column { display: grid; grid-template-rows: minmax(0, 1fr); gap: 10px; padding: 0; border: 0; background: transparent; }
|
||||
.xfa-workbench__mapping-column > * { min-width: 0; min-height: 0; overflow: auto; padding: 12px; border: 1px solid var(--border-default); border-radius: var(--radius-surface); background: var(--bg-surface); }
|
||||
.xfa-workbench__split-column > .xfa-split { height: 100%; overflow: auto; }
|
||||
.xfa-collections-inline { padding: 8px 12px !important; }
|
||||
.xfa-collections-inline summary { cursor: pointer; color: var(--text-secondary); font-size: .78rem; font-weight: 700; }
|
||||
.xfa-rule-dialog { position: fixed; z-index: 50; inset: 0; display: grid; place-items: center; padding: 24px; }
|
||||
.xfa-rule-dialog__backdrop { position: absolute; inset: 0; background: rgb(15 23 42 / .42); }
|
||||
.xfa-rule-dialog__panel { position: relative; display: flex; width: min(860px, 94vw); max-height: min(820px, 90vh); flex-direction: column; overflow: hidden; border: 1px solid var(--border-default); border-radius: var(--radius-surface); background: var(--bg-surface); box-shadow: 0 24px 70px rgb(15 23 42 / .24); }
|
||||
.xfa-rule-dialog__header { display: flex; justify-content: space-between; gap: 12px; padding: 14px 16px; border-bottom: 1px solid var(--border-default); }
|
||||
.xfa-rule-dialog__header p { margin: 3px 0 0; color: var(--text-muted); font-size: .76rem; }
|
||||
.xfa-rule-dialog__actions { display: flex; flex-wrap: wrap; align-items: center; justify-content: flex-end; gap: 8px; }
|
||||
.xfa-rule-dialog__actions button { min-height: 34px; }
|
||||
.xfa-rule-dialog__close { display: inline-grid; width: 34px; padding: 0; place-items: center; border: 0; border-radius: var(--radius-control); background: transparent; color: var(--text-muted); cursor: pointer; font-size: 1.15rem; }
|
||||
.xfa-rule-dialog__close:hover { background: var(--bg-page); color: var(--text-primary); }
|
||||
.xfa-rule-dialog__panel > .xfa-split { min-height: 0; overflow: auto; padding: 14px 16px 18px; }
|
||||
.link { border: 0; background: transparent; color: var(--status-info-fg); cursor: pointer; }
|
||||
.loading { padding: 24px; }
|
||||
.xfa-workbench__error {
|
||||
display: flex; flex-direction: column; gap: 12px; align-items: flex-start;
|
||||
margin: 24px; padding: 20px; border: 1px solid var(--status-error-border); border-radius: var(--radius-surface); background: var(--status-error-bg); color: var(--status-error-fg);
|
||||
}
|
||||
@media (max-width: 1400px) {
|
||||
.xfa-workbench__grid { grid-template-columns: 240px minmax(420px, 1fr); }
|
||||
.xfa-workbench__grid > :last-child { grid-column: 1 / -1; max-height: 36vh; }
|
||||
}
|
||||
@media (max-width: 1100px) {
|
||||
.xfa-workbench__grid { grid-template-columns: 1fr; }
|
||||
}
|
||||
</style>
|
||||
+41
-2
@@ -1,8 +1,9 @@
|
||||
<!--
|
||||
features/admin/modules/shipping-order-document-profiles/components/OrderProfileAuditTimeline.vue
|
||||
用途:展示订单模板版本中心的治理审计时间线。
|
||||
用途:展示订单模板版本中心的治理审计时间线(含 XFA operation_id / checksum)。
|
||||
依赖:版本中心审计 API、版本详情 DTO、Vue I18n。
|
||||
逻辑:使用 before_id 游标分页避免新增事件导致翻页重复;只展示安全 detail 摘要,不展示 PDF、正文或盲测真值。
|
||||
逻辑:使用 before_id 游标分页避免新增事件导致翻页重复;只展示安全 detail 摘要,
|
||||
以及 XFA 变更前后 definition checksum 与 operation_id;不展示 PDF、正文或盲测真值。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, reactive, ref, watch } from "vue";
|
||||
@@ -177,8 +178,26 @@ watch(
|
||||
<div class="meta">
|
||||
<span>{{ formatTime(item.created_at) }}</span>
|
||||
<code v-if="item.request_id">{{ item.request_id }}</code>
|
||||
<code
|
||||
v-if="item.operation_id"
|
||||
data-testid="order-profile-audit-operation-id"
|
||||
>{{ item.operation_id }}</code>
|
||||
</div>
|
||||
</header>
|
||||
<dl
|
||||
v-if="item.definition_checksum || item.before_definition_checksum"
|
||||
class="checksum-row"
|
||||
data-testid="order-profile-audit-checksums"
|
||||
>
|
||||
<div v-if="item.before_definition_checksum">
|
||||
<dt>{{ t("admin.shippingOrderProfiles.versionCenter.audit.beforeChecksum") }}</dt>
|
||||
<dd><code>{{ item.before_definition_checksum }}</code></dd>
|
||||
</div>
|
||||
<div v-if="item.definition_checksum">
|
||||
<dt>{{ t("admin.shippingOrderProfiles.versionCenter.audit.afterChecksum") }}</dt>
|
||||
<dd><code>{{ item.definition_checksum }}</code></dd>
|
||||
</div>
|
||||
</dl>
|
||||
<pre>{{ formatJson(item.detail) }}</pre>
|
||||
</article>
|
||||
</div>
|
||||
@@ -273,6 +292,26 @@ watch(
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.checksum-row {
|
||||
display: grid;
|
||||
gap: 0.35rem;
|
||||
margin: 0.5rem 0;
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
|
||||
.checksum-row dt {
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
.checksum-row dd {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.checksum-row code {
|
||||
font-size: 0.7rem;
|
||||
word-break: break-all;
|
||||
}
|
||||
|
||||
.meta {
|
||||
display: grid;
|
||||
justify-items: end;
|
||||
|
||||
+13
-4
@@ -20,13 +20,19 @@ import type {
|
||||
} from '@/features/admin/types/shipping-order-document-profile.types';
|
||||
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);
|
||||
@@ -109,9 +115,11 @@ const loadRegionDiagnostics = async (): Promise<void> => {
|
||||
regionDiagnostics.value = new Map(payload.items.map((item) => [item.region_id, item]));
|
||||
} catch (error) {
|
||||
regionDiagnostics.value = new Map();
|
||||
errorMessage.value = error instanceof BusinessError
|
||||
? error.message
|
||||
: t('admin.shippingOrderProfiles.versionCenter.regionDiagnosticsLoadFailed');
|
||||
// 区域诊断是增强信息;冻结版面没有 coordinate_evidence 时不能阻断 PDF 主画布。
|
||||
// 仅保留诊断区域为空,具体字段会回退到“未读取到值”。
|
||||
if (error instanceof BusinessError && error.code !== 'SHIPPING.ORDER_DOCUMENT_PROFILE_PREVIEW_NOT_FOUND') {
|
||||
errorMessage.value = error.message;
|
||||
}
|
||||
} finally {
|
||||
diagnosticsLoading.value = false;
|
||||
}
|
||||
@@ -136,7 +144,8 @@ watch([selectedSampleId, pageNo], () => {
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="readonly-layout">
|
||||
<XfaReadOnlyMapping v-if="isXfa" :detail="detail" />
|
||||
<section v-else class="readonly-layout">
|
||||
<div v-if="!immutable" class="state-card">
|
||||
{{ t('admin.shippingOrderProfiles.versionCenter.draftCanvasHint') }}
|
||||
</div>
|
||||
|
||||
+54
-1
@@ -8,6 +8,7 @@
|
||||
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;
|
||||
@@ -15,6 +16,15 @@ 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);
|
||||
|
||||
const formatDateTime = (value?: string | null) =>
|
||||
value ? new Date(value).toLocaleString() : "-";
|
||||
|
||||
@@ -39,6 +49,12 @@ const testStatusLabel = computed(() => {
|
||||
const status = props.detail.test_summary?.status || "missing";
|
||||
return t(`admin.shippingOrderProfiles.versionCenter.testStatus.${status}`);
|
||||
});
|
||||
|
||||
const templateModeLabel = computed(() => (
|
||||
isXfa.value
|
||||
? t("admin.shippingOrderProfiles.versionCenter.templateModeXfa")
|
||||
: t("admin.shippingOrderProfiles.versionCenter.templateModeCoordinate")
|
||||
));
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -52,6 +68,7 @@ const testStatusLabel = 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 ?? "-" }}
|
||||
@@ -67,7 +84,21 @@ const testStatusLabel = computed(() => {
|
||||
<div class="summary-grid">
|
||||
<article class="summary-card">
|
||||
<h3>{{ t("admin.shippingOrderProfiles.versionCenter.definitionStats") }}</h3>
|
||||
<dl>
|
||||
<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>
|
||||
<div>
|
||||
<dt>{{ t("admin.shippingOrderProfiles.versionCenter.tableRegions") }}</dt>
|
||||
<dd>{{ detail.definition_stats?.table_region_count || 0 }}</dd>
|
||||
@@ -87,6 +118,28 @@ const testStatusLabel = computed(() => {
|
||||
</dl>
|
||||
</article>
|
||||
|
||||
<article v-if="isXfa && xfaIdentity" 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>
|
||||
</div>
|
||||
<div>
|
||||
<dt>{{ t("admin.shippingOrderProfiles.versionCenter.xfaDatasetFingerprint") }}</dt>
|
||||
<dd>{{ xfaIdentity.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>
|
||||
</div>
|
||||
<div>
|
||||
<dt>{{ t("admin.shippingOrderProfiles.versionCenter.mirrorCollections") }}</dt>
|
||||
<dd>{{ xfaIdentity.mirror_collection_count ?? 0 }}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
</article>
|
||||
|
||||
<article class="summary-card">
|
||||
<h3>{{ t("admin.shippingOrderProfiles.versionCenter.frozenEvidenceTitle") }}</h3>
|
||||
<dl>
|
||||
|
||||
+106
@@ -0,0 +1,106 @@
|
||||
<!--
|
||||
features/admin/modules/shipping-order-document-profiles/components/OrderProfileXfaConfirmStep.vue
|
||||
用途:创建向导第三步——XFA 样本结构与明细集合确认(不要求 table_id)。
|
||||
依赖:XFA collections API、XfaCollectionSelector、vue-i18n。
|
||||
逻辑:父级传入 documentId 与 v-model 集合 path_id;watch(immediate) 加载上下文,
|
||||
避免 onMounted 再次触发导致重复请求。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, ref, watch } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { BusinessError } from '@/shared/api/client';
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
import {
|
||||
getOrderProfileSampleXfaCollections,
|
||||
getOrderProfileSampleXfaFieldTree,
|
||||
} 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[]];
|
||||
}>();
|
||||
|
||||
const { t } = useI18n();
|
||||
const message = useMessage();
|
||||
const loading = ref(false);
|
||||
const collections = ref<Awaited<ReturnType<typeof getOrderProfileSampleXfaCollections>> | null>(null);
|
||||
const flatNodes = ref(flattenXfaTreeNodes(null));
|
||||
const excludedCollections = computed(() => collections.value?.excluded_collection_candidates || []);
|
||||
|
||||
const documentKindLabel = computed(() => {
|
||||
const kind = props.sample?.document_kind || collections.value?.document_kind || 'xfa_hybrid';
|
||||
return t(`admin.shippingOrderProfiles.xfa.documentKinds.${kind}`, kind);
|
||||
});
|
||||
|
||||
/**
|
||||
* 加载 XFA 集合候选与字段树(用于展示标签)。
|
||||
* @returns 完成后更新 flatNodes 与 collections。
|
||||
*/
|
||||
async function loadXfaContext(): Promise<void> {
|
||||
if (!props.documentId) return;
|
||||
loading.value = true;
|
||||
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);
|
||||
}
|
||||
} catch (error) {
|
||||
message.error(error instanceof BusinessError ? error.message : t('admin.shippingOrderProfiles.wizard.xfa.loadFailed'));
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
watch(() => props.documentId, () => void loadXfaContext(), { immediate: true });
|
||||
</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>
|
||||
<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)"
|
||||
/>
|
||||
<p v-else-if="!loading" 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); }
|
||||
</style>
|
||||
+105
@@ -0,0 +1,105 @@
|
||||
/**
|
||||
* features/admin/modules/shipping-order-document-profiles/components/XfaCollectionSelector.spec.ts
|
||||
* 用途:断言权威集合卡片选择、证据展示与排除原因可见。
|
||||
* 依赖:Vitest、@vue/test-utils、XfaCollectionSelector。
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { mount } from '@vue/test-utils';
|
||||
import { createI18n } from 'vue-i18n';
|
||||
import XfaCollectionSelector from './XfaCollectionSelector.vue';
|
||||
|
||||
const i18n = createI18n({
|
||||
legacy: false,
|
||||
locale: 'zh-CN',
|
||||
messages: {
|
||||
'zh-CN': {
|
||||
admin: {
|
||||
shippingOrderProfiles: {
|
||||
xfaWorkbench: {
|
||||
collectionsTitle: '集合',
|
||||
authoritativeCollection: '权威',
|
||||
selectAuthoritative: '请选择',
|
||||
mirrorCollections: '镜像',
|
||||
rowCount: '{count} 行',
|
||||
collectionEvidenceHint: '证据',
|
||||
recommendedAuthoritative: '推荐权威',
|
||||
selectedAuthoritative: '已选权威',
|
||||
nonEmptyCoverage: '{filled}/{total} {percent}',
|
||||
excludedCollections: '空集合 {count}',
|
||||
emptyStructureReason: '空结构',
|
||||
allCandidatesExcluded: '全部被排除',
|
||||
collectionReason: {
|
||||
empty_structure: '空结构',
|
||||
data_description_structure: '结构描述',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
describe('XfaCollectionSelector', () => {
|
||||
it('emits authoritative path when a candidate card is selected', async () => {
|
||||
const wrapper = mount(XfaCollectionSelector, {
|
||||
global: { plugins: [i18n] },
|
||||
props: {
|
||||
candidates: [
|
||||
{
|
||||
path_id: 'a',
|
||||
collection_path_hash: 'ha',
|
||||
row_count: 1,
|
||||
path_label: 'data / ITEMS / DATA',
|
||||
field_names: ['MATNR', 'MENGE'],
|
||||
non_empty_field_count: 2,
|
||||
field_count: 2,
|
||||
sample_fields: [{ field_name: 'MENGE', display_value: '30', display_policy: 'full' }],
|
||||
recommended_role: 'authoritative',
|
||||
},
|
||||
{
|
||||
path_id: 'b',
|
||||
collection_path_hash: 'hb',
|
||||
row_count: 1,
|
||||
path_label: 'data / ITEMS1 / DATA',
|
||||
field_names: ['MATNR', 'MENGE'],
|
||||
non_empty_field_count: 2,
|
||||
field_count: 2,
|
||||
recommended_role: 'mirror',
|
||||
},
|
||||
],
|
||||
authoritativePathId: 'a',
|
||||
mirrorPathIds: [],
|
||||
},
|
||||
});
|
||||
const radios = wrapper.findAll('input[type="radio"]');
|
||||
await radios[1].setValue(true);
|
||||
expect(wrapper.emitted('update:authoritativePathId')?.[0]).toEqual(['b']);
|
||||
expect(wrapper.text()).toContain('data / ITEMS / DATA');
|
||||
expect(wrapper.text()).toContain('MATNR');
|
||||
expect(wrapper.text()).toContain('MENGE');
|
||||
});
|
||||
|
||||
it('shows excluded reasons when no selectable candidates remain', () => {
|
||||
const wrapper = mount(XfaCollectionSelector, {
|
||||
global: { plugins: [i18n] },
|
||||
props: {
|
||||
candidates: [],
|
||||
authoritativePathId: '',
|
||||
mirrorPathIds: [],
|
||||
excludedCandidates: [
|
||||
{
|
||||
path_id: 'desc',
|
||||
collection_path_hash: 'hd',
|
||||
row_count: 0,
|
||||
path_label: 'dataDescription / ITEMS / DATA',
|
||||
selectable: false,
|
||||
exclusion_reasons: ['data_description_structure'],
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
expect(wrapper.text()).toContain('全部被排除');
|
||||
expect(wrapper.text()).toContain('dataDescription / ITEMS / DATA');
|
||||
expect(wrapper.text()).toContain('结构描述');
|
||||
});
|
||||
});
|
||||
+195
@@ -0,0 +1,195 @@
|
||||
<!--
|
||||
features/admin/modules/shipping-order-document-profiles/components/XfaCollectionSelector.vue
|
||||
用途:权威明细集合与镜像对账集合选择。
|
||||
依赖:vue-i18n、XfaCollectionCandidate。
|
||||
逻辑:以候选卡片直接展示完整路径、字段覆盖与样本证据;权威单选强制,镜像多选仅用于对账;
|
||||
全部候选被排除时仍展示排除原因,禁止只显示“没有集合”。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import type { XfaCollectionCandidate } from '@/features/admin/types/shipping-order-document-profile.types';
|
||||
import { listMirrorCollectionCandidates } from '../xfaProfileMapping.utils';
|
||||
|
||||
const props = defineProps<{
|
||||
candidates: XfaCollectionCandidate[];
|
||||
authoritativePathId: string;
|
||||
mirrorPathIds: string[];
|
||||
excludedCandidates?: XfaCollectionCandidate[];
|
||||
}>();
|
||||
const emit = defineEmits<{
|
||||
'update:authoritativePathId': [pathId: string];
|
||||
'update:mirrorPathIds': [pathIds: string[]];
|
||||
}>();
|
||||
const { t, te } = useI18n();
|
||||
const mirrors = computed(() => listMirrorCollectionCandidates(props.candidates, props.authoritativePathId));
|
||||
const selectedAuthoritative = computed(() => props.candidates.find((item) => item.path_id === props.authoritativePathId));
|
||||
const hasSelectable = computed(() => props.candidates.length > 0);
|
||||
const hasExcludedOnly = computed(() => !hasSelectable.value && Boolean(props.excludedCandidates?.length));
|
||||
|
||||
/** 将非空率转为管理员可读百分比。 */
|
||||
function percent(value?: number): string {
|
||||
return `${Math.round(Number(value || 0) * 100)}%`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 切换镜像集合勾选。
|
||||
*/
|
||||
function toggleMirror(pathId: string, checked: boolean): void {
|
||||
const next = new Set(props.mirrorPathIds);
|
||||
if (checked) next.add(pathId);
|
||||
else next.delete(pathId);
|
||||
emit('update:mirrorPathIds', [...next]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 将排除/推荐原因码映射为可读文案。
|
||||
* @param reasons 原因码列表
|
||||
*/
|
||||
function reasonLabels(reasons?: string[]): string {
|
||||
return (reasons || [])
|
||||
.map((code) => {
|
||||
const key = `admin.shippingOrderProfiles.xfaWorkbench.collectionReason.${code}`;
|
||||
return te(key) ? t(key) : code;
|
||||
})
|
||||
.join(' · ');
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="xfa-collections" :aria-label="t('admin.shippingOrderProfiles.xfaWorkbench.collectionsTitle')">
|
||||
<div class="collection-heading">
|
||||
<strong>{{ t('admin.shippingOrderProfiles.xfaWorkbench.collectionsTitle') }}</strong>
|
||||
<span>{{ t('admin.shippingOrderProfiles.xfaWorkbench.collectionEvidenceHint') }}</span>
|
||||
</div>
|
||||
|
||||
<p v-if="hasExcludedOnly" class="empty-selectable" role="status">
|
||||
{{ t('admin.shippingOrderProfiles.xfaWorkbench.allCandidatesExcluded') }}
|
||||
</p>
|
||||
|
||||
<fieldset v-if="hasSelectable" class="auth-cards" :aria-invalid="!authoritativePathId">
|
||||
<legend>{{ t('admin.shippingOrderProfiles.xfaWorkbench.authoritativeCollection') }}</legend>
|
||||
<label
|
||||
v-for="item in candidates"
|
||||
:key="item.path_id"
|
||||
class="candidate-card"
|
||||
:class="{
|
||||
selected: authoritativePathId === item.path_id,
|
||||
recommended: item.recommended_role === 'authoritative',
|
||||
}"
|
||||
>
|
||||
<input
|
||||
type="radio"
|
||||
name="xfa-authoritative-collection"
|
||||
:value="item.path_id"
|
||||
:checked="authoritativePathId === item.path_id"
|
||||
@change="emit('update:authoritativePathId', item.path_id)"
|
||||
/>
|
||||
<span class="candidate-body">
|
||||
<span class="candidate-title">
|
||||
<strong>{{ item.path_label || item.local_name }}</strong>
|
||||
<span v-if="item.recommended_role === 'authoritative'" class="role-badge">
|
||||
{{ t('admin.shippingOrderProfiles.xfaWorkbench.recommendedAuthoritative') }}
|
||||
</span>
|
||||
<span>{{ t('admin.shippingOrderProfiles.xfaWorkbench.rowCount', { count: item.row_count }) }}</span>
|
||||
</span>
|
||||
<small>{{ t('admin.shippingOrderProfiles.xfaWorkbench.nonEmptyCoverage', {
|
||||
filled: item.non_empty_field_count || 0,
|
||||
total: item.field_count || 0,
|
||||
percent: percent(item.non_empty_rate),
|
||||
}) }}</small>
|
||||
<span class="fields">{{ (item.field_names || []).slice(0, 8).join(' · ') }}</span>
|
||||
<span class="samples">
|
||||
<span v-for="field in item.sample_fields || []" :key="`${item.path_id}-${field.field_name}`">
|
||||
<b>{{ field.field_name }}</b> {{ field.display_value }}
|
||||
</span>
|
||||
</span>
|
||||
</span>
|
||||
</label>
|
||||
</fieldset>
|
||||
|
||||
<article v-if="selectedAuthoritative" class="collection-card authoritative">
|
||||
<header>
|
||||
<div>
|
||||
<strong>{{ selectedAuthoritative.path_label || selectedAuthoritative.local_name }}</strong>
|
||||
<span class="role-badge">{{ t('admin.shippingOrderProfiles.xfaWorkbench.selectedAuthoritative') }}</span>
|
||||
</div>
|
||||
<span>{{ t('admin.shippingOrderProfiles.xfaWorkbench.rowCount', { count: selectedAuthoritative.row_count }) }}</span>
|
||||
</header>
|
||||
<p>{{ t('admin.shippingOrderProfiles.xfaWorkbench.nonEmptyCoverage', {
|
||||
filled: selectedAuthoritative.non_empty_field_count || 0,
|
||||
total: selectedAuthoritative.field_count || 0,
|
||||
percent: percent(selectedAuthoritative.non_empty_rate),
|
||||
}) }}</p>
|
||||
<div class="sample-grid">
|
||||
<span v-for="field in selectedAuthoritative.sample_fields || []" :key="field.field_name">
|
||||
<b>{{ field.field_name }}</b> {{ field.display_value }}
|
||||
</span>
|
||||
</div>
|
||||
<small>{{ (selectedAuthoritative.field_names || []).join(' · ') }}</small>
|
||||
</article>
|
||||
|
||||
<fieldset v-if="mirrors.length" class="mirror-fieldset">
|
||||
<legend>{{ t('admin.shippingOrderProfiles.xfaWorkbench.mirrorCollections') }}</legend>
|
||||
<label v-for="item in mirrors" :key="item.path_id" class="mirror">
|
||||
<input
|
||||
type="checkbox"
|
||||
:checked="mirrorPathIds.includes(item.path_id)"
|
||||
@change="toggleMirror(item.path_id, ($event.target as HTMLInputElement).checked)"
|
||||
/>
|
||||
<span class="mirror-copy">
|
||||
<strong>{{ item.path_label || item.local_name }}</strong>
|
||||
<small>{{ t('admin.shippingOrderProfiles.xfaWorkbench.nonEmptyCoverage', {
|
||||
filled: item.non_empty_field_count || 0,
|
||||
total: item.field_count || 0,
|
||||
percent: percent(item.non_empty_rate),
|
||||
}) }}</small>
|
||||
<span>{{ (item.sample_fields || []).map((field) => `${field.field_name} ${field.display_value}`).join(' · ') }}</span>
|
||||
</span>
|
||||
</label>
|
||||
</fieldset>
|
||||
|
||||
<details v-if="excludedCandidates?.length" class="excluded" :open="hasExcludedOnly">
|
||||
<summary>{{ t('admin.shippingOrderProfiles.xfaWorkbench.excludedCollections', { count: excludedCandidates.length }) }}</summary>
|
||||
<ul>
|
||||
<li v-for="item in excludedCandidates" :key="item.path_id">
|
||||
<span>{{ item.path_label || item.local_name }}</span>
|
||||
<small>{{ reasonLabels(item.exclusion_reasons || item.recommendation_reasons) || t('admin.shippingOrderProfiles.xfaWorkbench.emptyStructureReason') }}</small>
|
||||
</li>
|
||||
</ul>
|
||||
</details>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.xfa-collections { display: grid; grid-template-columns: minmax(280px, 1fr) minmax(320px, 1fr); gap: 12px 16px; align-items: start; width: 100%; }
|
||||
.collection-heading { grid-column: 1 / -1; display: flex; flex-direction: column; gap: 3px; color: var(--text-primary); }
|
||||
.collection-heading span { color: var(--text-muted); font-size: .82rem; }
|
||||
.empty-selectable { grid-column: 1 / -1; margin: 0; padding: 10px 12px; border: 1px solid var(--status-warning-border); border-radius: var(--radius-control); background: var(--status-warning-bg); color: var(--status-warning-fg); }
|
||||
.auth-cards { grid-column: 1 / -1; display: grid; gap: 10px; margin: 0; padding: 0; border: 0; }
|
||||
.auth-cards[aria-invalid='true'] .candidate-card { border-color: var(--status-error-border); }
|
||||
.candidate-card { display: flex; gap: 10px; align-items: flex-start; padding: 12px; border: 1px solid var(--border-default); border-radius: var(--radius-control); background: var(--bg-surface); cursor: pointer; }
|
||||
.candidate-card.selected, .candidate-card.recommended.selected { border-color: var(--status-info-border); background: var(--status-info-bg); }
|
||||
.candidate-body { display: flex; min-width: 0; flex: 1; flex-direction: column; gap: 4px; color: var(--text-secondary); }
|
||||
.candidate-title { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; color: var(--text-primary); }
|
||||
.role-badge { color: var(--status-info-fg); font-size: .75rem; }
|
||||
.fields, .samples { color: var(--text-muted); font-size: .78rem; }
|
||||
.samples { display: flex; flex-wrap: wrap; gap: 6px 12px; }
|
||||
.samples b { color: var(--text-primary); }
|
||||
.collection-card, .mirror-fieldset, .excluded { border: 1px solid var(--border-default); border-radius: var(--radius-control); padding: 12px; background: var(--bg-surface); }
|
||||
.collection-card.authoritative { border-color: var(--status-info-border); background: var(--status-info-bg); }
|
||||
.collection-card header { display: flex; justify-content: space-between; gap: 12px; color: var(--text-primary); }
|
||||
.collection-card header div { display: flex; align-items: center; gap: 8px; }
|
||||
.collection-card p, .collection-card small { color: var(--text-muted); }
|
||||
.sample-grid { display: flex; flex-wrap: wrap; gap: 6px 12px; margin: 8px 0; color: var(--text-secondary); font-size: .82rem; }
|
||||
.sample-grid b { color: var(--text-primary); }
|
||||
.mirror-fieldset { grid-column: 1 / -1; }
|
||||
.mirror { display: flex; gap: 10px; align-items: flex-start; padding: 8px 0; }
|
||||
.mirror-copy { display: flex; flex-direction: column; gap: 2px; color: var(--text-secondary); }
|
||||
.mirror-copy small, .mirror-copy span { color: var(--text-muted); font-size: .78rem; }
|
||||
.excluded { grid-column: 1 / -1; color: var(--text-secondary); }
|
||||
.excluded ul { margin: 8px 0 0; padding-left: 18px; }
|
||||
.excluded li { display: flex; flex-wrap: wrap; gap: 10px; }
|
||||
.excluded small { color: var(--status-warning-fg); }
|
||||
@media (max-width: 900px) { .xfa-collections { grid-template-columns: 1fr; } }
|
||||
</style>
|
||||
+169
@@ -0,0 +1,169 @@
|
||||
/**
|
||||
* features/admin/modules/shipping-order-document-profiles/components/XfaDatasetTree.spec.ts
|
||||
* 用途:断言 XFA 字段树渲染与 select-path 事件。
|
||||
* 依赖:Vitest、@vue/test-utils、XfaDatasetTree。
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { mount } from '@vue/test-utils';
|
||||
import { createI18n } from 'vue-i18n';
|
||||
import XfaDatasetTree from './XfaDatasetTree.vue';
|
||||
|
||||
const i18n = createI18n({
|
||||
legacy: false,
|
||||
locale: 'zh-CN',
|
||||
messages: {
|
||||
'zh-CN': {
|
||||
admin: {
|
||||
shippingOrderProfiles: {
|
||||
xfaWorkbench: {
|
||||
treeTitle: '树', searchPaths: '搜索', collectionBadge: '集合', treeEmpty: '空',
|
||||
revealValue: '查看 {field}',
|
||||
},
|
||||
xfaSplit: { addRule: '新增规则', ruleLabel: '规则 {index}', unnamedRule: '未命名规则', deleteRule: '删除' },
|
||||
},
|
||||
},
|
||||
common: { edit: '编辑' },
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
describe('XfaDatasetTree', () => {
|
||||
it('emits select-path when a tree node button is clicked', async () => {
|
||||
const wrapper = mount(XfaDatasetTree, {
|
||||
global: { plugins: [i18n] },
|
||||
props: {
|
||||
tree: {
|
||||
path_id: 'root', local_name: 'data', data_path_hash: 'h', depth: 0, cardinality: 'one',
|
||||
is_leaf: false,
|
||||
children: [{
|
||||
path_id: 'leaf', local_name: 'EBELN', data_path_hash: 'h2', depth: 1, cardinality: 'one',
|
||||
is_leaf: true, sample_value_masked: '451***',
|
||||
}],
|
||||
},
|
||||
},
|
||||
});
|
||||
const nodes = wrapper.findAll('[role="treeitem"]');
|
||||
expect(nodes.length).toBeGreaterThan(0);
|
||||
await nodes[nodes.length - 1].trigger('click');
|
||||
expect(wrapper.emitted('select-path')?.[0]).toEqual(['leaf', true]);
|
||||
});
|
||||
|
||||
it('exposes tree levels and supports collapse keyboard navigation', async () => {
|
||||
const wrapper = mount(XfaDatasetTree, {
|
||||
global: { plugins: [i18n] },
|
||||
props: {
|
||||
tree: {
|
||||
path_id: 'root', local_name: 'data', data_path_hash: 'h', depth: 0, cardinality: 'one',
|
||||
is_leaf: false, children: [{
|
||||
path_id: 'leaf', local_name: 'WAERS', data_path_hash: 'h2', depth: 1, cardinality: 'one',
|
||||
is_leaf: true, sample_value_display: 'USD', display_policy: 'full',
|
||||
}],
|
||||
},
|
||||
},
|
||||
});
|
||||
const root = wrapper.find('[data-xfa-path-id="root"]');
|
||||
expect(root.attributes('aria-level')).toBe('1');
|
||||
expect(root.attributes('aria-expanded')).toBe('true');
|
||||
await root.trigger('keydown', { key: 'ArrowLeft' });
|
||||
expect(root.attributes('aria-expanded')).toBe('false');
|
||||
expect(wrapper.text()).not.toContain('USD');
|
||||
});
|
||||
|
||||
it('selects the focused node with Enter and Space', async () => {
|
||||
const wrapper = mount(XfaDatasetTree, {
|
||||
global: { plugins: [i18n] },
|
||||
props: {
|
||||
tree: {
|
||||
path_id: 'root', local_name: 'data', data_path_hash: 'h', depth: 0, cardinality: 'one',
|
||||
is_leaf: false, children: [{
|
||||
path_id: 'leaf', local_name: 'WAERS', data_path_hash: 'h2', depth: 1, cardinality: 'one',
|
||||
is_leaf: true, sample_value_display: 'USD', display_policy: 'full',
|
||||
}],
|
||||
},
|
||||
},
|
||||
});
|
||||
const leaf = wrapper.find('[data-xfa-path-id="leaf"]');
|
||||
await leaf.trigger('keydown', { key: 'Enter' });
|
||||
await leaf.trigger('keydown', { key: ' ' });
|
||||
expect(wrapper.emitted('select-path')).toEqual([['leaf', true], ['leaf', true]]);
|
||||
});
|
||||
|
||||
it('emits add-rule when the leaf add button is clicked', async () => {
|
||||
const wrapper = mount(XfaDatasetTree, {
|
||||
global: { plugins: [i18n] },
|
||||
props: {
|
||||
selectedPathId: 'leaf',
|
||||
tree: {
|
||||
path_id: 'root', local_name: 'data', data_path_hash: 'h', depth: 0, cardinality: 'one',
|
||||
is_leaf: false, children: [{
|
||||
path_id: 'leaf', local_name: 'MATNR', data_path_hash: 'h2', depth: 1, cardinality: 'one',
|
||||
is_leaf: true, sample_value_display: 'TEMP-S', display_policy: 'full',
|
||||
}],
|
||||
},
|
||||
},
|
||||
});
|
||||
await wrapper.find('[data-xfa-path-id="leaf"] .add-rule').trigger('click');
|
||||
expect(wrapper.emitted('add-rule')).toEqual([['leaf']]);
|
||||
expect(wrapper.emitted('select-path')).toBeUndefined();
|
||||
});
|
||||
|
||||
it('selects a rule row without editing and uses explicit edit and delete controls', async () => {
|
||||
const wrapper = mount(XfaDatasetTree, {
|
||||
global: { plugins: [i18n] },
|
||||
props: {
|
||||
tree: {
|
||||
path_id: 'root', local_name: 'data', data_path_hash: 'h', depth: 0, cardinality: 'one',
|
||||
is_leaf: false, children: [{
|
||||
path_id: 'leaf', local_name: 'MATNR', data_path_hash: 'h2', depth: 1, cardinality: 'one',
|
||||
is_leaf: true, sample_value_display: 'TEMP-S', display_policy: 'full',
|
||||
}],
|
||||
},
|
||||
splitRuleSets: [{
|
||||
rule_id: 'set-1', rule_version: 1, source_path_id: 'leaf', source_field_code: 'MATNR', strategy: 'pipeline',
|
||||
rules: [{
|
||||
rule_id: 'rule-1', order: 1, stages: [{ stage_id: 'stage-1', type: 'select_line', line_index: 1 }],
|
||||
segment: { segment_id: 'seg-1', segment_code: 'customer_part', display_name: '客户料号', handling: 'evidence_only' },
|
||||
}],
|
||||
}],
|
||||
},
|
||||
});
|
||||
await wrapper.find('.xfa-tree__rule-main').trigger('click');
|
||||
expect(wrapper.emitted('select-rule')).toEqual([['leaf', 'rule-1']]);
|
||||
expect(wrapper.emitted('edit-rule')).toBeUndefined();
|
||||
|
||||
await wrapper.find('.rule-edit').trigger('click');
|
||||
expect(wrapper.emitted('edit-rule')).toEqual([['leaf', 'rule-1']]);
|
||||
await wrapper.find('.rule-delete').trigger('click');
|
||||
expect(wrapper.emitted('delete-rule')).toEqual([['leaf', 'rule-1']]);
|
||||
});
|
||||
|
||||
it('indents rule nodes beyond their deep parent field', () => {
|
||||
const wrapper = mount(XfaDatasetTree, {
|
||||
global: { plugins: [i18n] },
|
||||
props: {
|
||||
tree: {
|
||||
path_id: 'root', local_name: 'datasets', data_path_hash: 'h0', depth: 0, cardinality: 'one', is_leaf: false,
|
||||
children: [{
|
||||
path_id: 'data', local_name: 'data', data_path_hash: 'h1', depth: 1, cardinality: 'one', is_leaf: false,
|
||||
children: [{
|
||||
path_id: 'items', local_name: 'ITEMS', data_path_hash: 'h2', depth: 2, cardinality: 'one', is_leaf: false,
|
||||
children: [{
|
||||
path_id: 'leaf', local_name: 'MATNR', data_path_hash: 'h3', depth: 3, cardinality: 'one', is_leaf: true,
|
||||
}],
|
||||
}],
|
||||
}],
|
||||
},
|
||||
splitRuleSets: [{
|
||||
rule_id: 'set-1', rule_version: 1, source_path_id: 'leaf', source_field_code: 'MATNR', strategy: 'pipeline',
|
||||
rules: [{
|
||||
rule_id: 'rule-1', order: 1, stages: [{ stage_id: 'stage-1', type: 'select_line', line_index: 1 }],
|
||||
segment: { segment_id: 'seg-1', segment_code: 'customer_part', display_name: '客户料号', handling: 'evidence_only' },
|
||||
}],
|
||||
}],
|
||||
},
|
||||
});
|
||||
const parentPadding = Number.parseFloat(wrapper.find('[data-xfa-path-id="leaf"]').attributes('style').match(/padding-left:\s*([\d.]+)px/)?.[1] || '0');
|
||||
const ruleIndentValue = Number.parseFloat(wrapper.find('.xfa-tree__rules').attributes('style').match(/--rule-indent:\s*([\d.]+)px/)?.[1] || '0');
|
||||
expect(ruleIndentValue).toBeGreaterThan(parentPadding);
|
||||
});
|
||||
});
|
||||
+282
@@ -0,0 +1,282 @@
|
||||
<!--
|
||||
features/admin/modules/shipping-order-document-profiles/components/XfaDatasetTree.vue
|
||||
用途:XFA 映射工作台左侧受控数据树(仅分析记录节点)。
|
||||
依赖:vue-i18n、xfaProfileMapping.utils。
|
||||
逻辑:支持展开折叠、方向键导航与分级样本展示;叶子展示父路径提示区分同名来源。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, nextTick, ref } from 'vue';
|
||||
import { ChevronDown, ChevronRight, Eye, Pencil } from 'lucide-vue-next';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import type { XfaFieldTreeNode } from '@/features/admin/types/shipping-order-document-profile.types';
|
||||
import type { XfaSplitRuleSet } from '@/features/admin/types/shipping-order-document-profile.types';
|
||||
import {
|
||||
buildXfaPathLabel,
|
||||
filterXfaTreeNodes,
|
||||
flattenXfaTreeNodes,
|
||||
type XfaFlatTreeNode,
|
||||
} from '../xfaProfileMapping.utils';
|
||||
|
||||
const props = defineProps<{
|
||||
tree: XfaFieldTreeNode | null;
|
||||
selectedPathId?: string | null;
|
||||
selectedRuleId?: string | null;
|
||||
mappedPathIds?: string[];
|
||||
revealedValues?: Record<string, string>;
|
||||
revealingPathId?: string;
|
||||
splitRuleSets?: XfaSplitRuleSet[];
|
||||
}>();
|
||||
const emit = defineEmits<{
|
||||
'select-path': [pathId: string, isLeaf: boolean];
|
||||
'reveal-path': [pathId: string];
|
||||
'add-rule': [pathId: string];
|
||||
'select-rule': [pathId: string, ruleId: string];
|
||||
'edit-rule': [pathId: string, ruleId: string];
|
||||
'delete-rule': [pathId: string, ruleId: string];
|
||||
'move-rule': [pathId: string, ruleId: string, direction: -1 | 1];
|
||||
}>();
|
||||
const { t } = useI18n();
|
||||
const query = ref('');
|
||||
const flat = computed(() => flattenXfaTreeNodes(props.tree || undefined));
|
||||
const collapsed = ref(new Set<string>());
|
||||
const focusedPathId = ref('');
|
||||
const visible = computed(() => {
|
||||
const filtered = filterXfaTreeNodes(flat.value, query.value);
|
||||
if (query.value.trim()) return filtered;
|
||||
return filtered.filter((node) => {
|
||||
let parent = node.parentPathId;
|
||||
while (parent) {
|
||||
if (collapsed.value.has(parent)) return false;
|
||||
parent = flat.value.find((item) => item.pathId === parent)?.parentPathId;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
});
|
||||
const mapped = computed(() => new Set(props.mappedPathIds || []));
|
||||
const rulesFor = (pathId: string) => props.splitRuleSets?.find((item) => item.source_path_id === pathId)?.rules || [];
|
||||
|
||||
/**
|
||||
* 选择树节点;叶子才用于字段绑定。
|
||||
* @param pathId 分析 path_id
|
||||
* @param isLeaf 是否叶子
|
||||
*/
|
||||
function onSelect(pathId: string, isLeaf: boolean): void {
|
||||
focusedPathId.value = pathId;
|
||||
emit('select-path', pathId, isLeaf);
|
||||
}
|
||||
|
||||
/** 切换非叶子节点展开状态。 */
|
||||
function toggle(pathId: string): void {
|
||||
const next = new Set(collapsed.value);
|
||||
if (next.has(pathId)) next.delete(pathId);
|
||||
else next.add(pathId);
|
||||
collapsed.value = next;
|
||||
}
|
||||
|
||||
/**
|
||||
* 完整可读路径(节点名链路),用于 title / 无障碍标签。
|
||||
* @param node 扁平树节点
|
||||
*/
|
||||
function pathTitle(node: XfaFlatTreeNode): string {
|
||||
return buildXfaPathLabel(node.pathId, flat.value);
|
||||
}
|
||||
|
||||
/**
|
||||
* 叶子节点的父路径提示,便于区分同名字段来源。
|
||||
* @param node 扁平树节点
|
||||
*/
|
||||
function parentPathHint(node: XfaFlatTreeNode): string {
|
||||
const full = buildXfaPathLabel(node.pathId, flat.value);
|
||||
const parts = full.split('/').filter(Boolean);
|
||||
if (parts.length <= 1) return '';
|
||||
return parts.slice(0, -1).join(' / ');
|
||||
}
|
||||
|
||||
/** 使用完整深度缩进,确保任意层级都能辨认父子关系。 */
|
||||
function nodeIndent(node: XfaFlatTreeNode): string {
|
||||
return `${8 + node.depth * 14}px`;
|
||||
}
|
||||
|
||||
/** 当前层级导轨位置与完整缩进同步。 */
|
||||
function nodeGuide(node: XfaFlatTreeNode): string {
|
||||
return `${8 + Math.max(node.depth - 1, 0) * 14}px`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 规则作为叶子字段的下一级虚拟节点,缩进必须基于父字段真实深度计算。
|
||||
* @param node 拆分规则所属的原始叶子节点
|
||||
* @returns 规则列表左内边距及导轨位置
|
||||
*/
|
||||
function ruleIndent(node: XfaFlatTreeNode): Record<string, string> {
|
||||
const parentIndent = 8 + node.depth * 14;
|
||||
return {
|
||||
'--rule-indent': `${parentIndent + 30}px`,
|
||||
'--rule-guide-offset': `${parentIndent + 18}px`,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 实现 WAI-ARIA Tree 方向键、Home/End 与父子导航。
|
||||
* @param event 键盘事件
|
||||
* @param pathId 当前节点 path_id
|
||||
*/
|
||||
async function onKeydown(event: KeyboardEvent, pathId: string): Promise<void> {
|
||||
const index = visible.value.findIndex((item) => item.pathId === pathId);
|
||||
const current = visible.value[index];
|
||||
if (!current) return;
|
||||
let target: string | undefined;
|
||||
if (event.key === 'Enter' || event.key === ' ') {
|
||||
event.preventDefault();
|
||||
onSelect(pathId, current.isLeaf);
|
||||
return;
|
||||
}
|
||||
if (event.key === 'ArrowDown') target = visible.value[index + 1]?.pathId;
|
||||
else if (event.key === 'ArrowUp') target = visible.value[index - 1]?.pathId;
|
||||
else if (event.key === 'Home') target = visible.value[0]?.pathId;
|
||||
else if (event.key === 'End') target = visible.value[visible.value.length - 1]?.pathId;
|
||||
else if (event.key === 'ArrowRight' && !current.isLeaf) {
|
||||
if (collapsed.value.has(pathId)) toggle(pathId);
|
||||
else target = visible.value[index + 1]?.parentPathId === pathId ? visible.value[index + 1]?.pathId : undefined;
|
||||
} else if (event.key === 'ArrowLeft') {
|
||||
if (!current.isLeaf && !collapsed.value.has(pathId)) toggle(pathId);
|
||||
else target = current.parentPathId;
|
||||
} else return;
|
||||
event.preventDefault();
|
||||
if (target) {
|
||||
focusedPathId.value = target;
|
||||
await nextTick();
|
||||
document.querySelector<HTMLElement>(`[data-xfa-path-id="${CSS.escape(target)}"]`)?.focus();
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="xfa-tree" :aria-label="t('admin.shippingOrderProfiles.xfaWorkbench.treeTitle')">
|
||||
<label class="xfa-tree__search">
|
||||
<span class="sr-only">{{ t('admin.shippingOrderProfiles.xfaWorkbench.searchPaths') }}</span>
|
||||
<input v-model="query" type="search" :placeholder="t('admin.shippingOrderProfiles.xfaWorkbench.searchPaths')" />
|
||||
</label>
|
||||
<ul class="xfa-tree__list" role="tree">
|
||||
<li v-for="(node, index) in visible" :key="node.pathId" role="none">
|
||||
<div
|
||||
role="treeitem"
|
||||
class="xfa-tree__node"
|
||||
:class="{
|
||||
selected: selectedPathId === node.pathId,
|
||||
mapped: mapped.has(node.pathId),
|
||||
leaf: node.isLeaf,
|
||||
}"
|
||||
:style="{ paddingLeft: nodeIndent(node), '--tree-guide-offset': nodeGuide(node) }"
|
||||
:data-xfa-path-id="node.pathId"
|
||||
:tabindex="focusedPathId === node.pathId || (!focusedPathId && node === visible[0]) ? 0 : -1"
|
||||
:aria-level="node.depth + 1"
|
||||
:aria-setsize="visible.length"
|
||||
:aria-posinset="index + 1"
|
||||
:aria-expanded="node.isLeaf ? undefined : !collapsed.has(node.pathId)"
|
||||
:aria-selected="selectedPathId === node.pathId"
|
||||
:title="pathTitle(node)"
|
||||
@click="onSelect(node.pathId, node.isLeaf)"
|
||||
@focus="focusedPathId = node.pathId"
|
||||
@keydown="onKeydown($event, node.pathId)"
|
||||
>
|
||||
<span v-if="!node.isLeaf" class="toggle" @click.stop="toggle(node.pathId)">
|
||||
<ChevronRight v-if="collapsed.has(node.pathId)" :size="14" aria-hidden="true" />
|
||||
<ChevronDown v-else :size="14" aria-hidden="true" />
|
||||
</span>
|
||||
<span v-else class="toggle-spacer" />
|
||||
<span class="name-block">
|
||||
<span class="name">{{ node.localName }}</span>
|
||||
<span v-if="node.isLeaf && parentPathHint(node)" class="path-hint">{{ parentPathHint(node) }}</span>
|
||||
</span>
|
||||
<span v-if="node.isCollectionCandidate" class="badge">{{ t('admin.shippingOrderProfiles.xfaWorkbench.collectionBadge') }}</span>
|
||||
<button
|
||||
v-if="node.isLeaf"
|
||||
type="button"
|
||||
class="add-rule"
|
||||
:class="{ 'add-rule--active': selectedPathId === node.pathId }"
|
||||
:title="t('admin.shippingOrderProfiles.xfaSplit.addRule')"
|
||||
:aria-label="t('admin.shippingOrderProfiles.xfaSplit.addRule')"
|
||||
@click.stop="emit('add-rule', node.pathId)"
|
||||
>+</button>
|
||||
<span v-if="revealedValues?.[node.pathId] || node.sampleValueDisplay" class="sample">
|
||||
{{ revealedValues?.[node.pathId] || node.sampleValueDisplay }}
|
||||
</span>
|
||||
<button
|
||||
v-if="node.isLeaf && node.canReveal && !revealedValues?.[node.pathId]"
|
||||
type="button"
|
||||
class="reveal"
|
||||
:disabled="revealingPathId === node.pathId"
|
||||
:aria-label="t('admin.shippingOrderProfiles.xfaWorkbench.revealValue', { field: pathTitle(node) })"
|
||||
@click.stop="emit('reveal-path', node.pathId)"
|
||||
>
|
||||
<Eye :size="14" aria-hidden="true" />
|
||||
</button>
|
||||
</div>
|
||||
<ul
|
||||
v-if="node.isLeaf && rulesFor(node.pathId).length"
|
||||
class="xfa-tree__rules"
|
||||
role="group"
|
||||
:style="ruleIndent(node)"
|
||||
>
|
||||
<li
|
||||
v-for="(rule, ruleIndex) in rulesFor(node.pathId)"
|
||||
:key="rule.rule_id"
|
||||
class="xfa-tree__rule"
|
||||
:class="{ selected: selectedRuleId === rule.rule_id }"
|
||||
>
|
||||
<button type="button" class="xfa-tree__rule-main" @click="emit('select-rule', node.pathId, rule.rule_id)">
|
||||
<span class="rule-glyph">↳</span>
|
||||
<span class="rule-label">{{ t('admin.shippingOrderProfiles.xfaSplit.ruleLabel', { index: ruleIndex + 1 }) }} · {{ rule.segment.display_name || rule.segment.segment_code || t('admin.shippingOrderProfiles.xfaSplit.unnamedRule') }}</span>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="rule-edit"
|
||||
:title="t('common.edit')"
|
||||
:aria-label="t('common.edit')"
|
||||
@click.stop="emit('edit-rule', node.pathId, rule.rule_id)"
|
||||
><Pencil :size="12" aria-hidden="true" /></button>
|
||||
<button type="button" class="rule-delete" :title="t('admin.shippingOrderProfiles.xfaSplit.deleteRule')" @click.stop="emit('delete-rule', node.pathId, rule.rule_id)">×</button>
|
||||
</li>
|
||||
</ul>
|
||||
</li>
|
||||
</ul>
|
||||
<p v-if="!visible.length" class="xfa-tree__empty">{{ t('admin.shippingOrderProfiles.xfaWorkbench.treeEmpty') }}</p>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.xfa-tree { display: flex; flex-direction: column; min-height: 0; height: 100%; }
|
||||
.xfa-tree__search input { width: 100%; padding: 8px 10px; border: 1px solid var(--border-default); border-radius: var(--radius-control); background: var(--bg-surface); color: var(--text-primary); }
|
||||
.xfa-tree__list { margin: 8px -6px 0 0; padding: 0 6px 0 0; list-style: none; overflow: auto; flex: 1; scrollbar-gutter: stable; }
|
||||
.xfa-tree__node { position: relative; display: flex; width: 100%; min-width: 0; gap: 5px; align-items: center; min-height: 34px; padding-block: 4px; padding-right: 6px; border: 0; border-radius: var(--radius-control); background: transparent; color: var(--text-secondary); text-align: left; cursor: pointer; }
|
||||
.xfa-tree__node::before { content: ''; position: absolute; top: 0; bottom: 0; left: max(13px, calc(var(--tree-guide-offset, 0px))); width: 1px; background: var(--border-default); opacity: .65; pointer-events: none; }
|
||||
.xfa-tree__node[aria-level='1']::before { display: none; }
|
||||
.xfa-tree__node:focus-visible { outline: 2px solid var(--focus-ring); outline-offset: 1px; }
|
||||
.xfa-tree__node.selected { background: var(--status-info-bg); color: var(--status-info-fg); }
|
||||
.xfa-tree__node.mapped .name::after { content: ' ✓'; color: var(--status-success-fg); }
|
||||
.name-block { display: grid; min-width: 0; flex: 1; gap: 0; }
|
||||
.xfa-tree__node:not(.leaf) .name { font-weight: 650; }
|
||||
.xfa-tree__node .name { min-width: 0; overflow: hidden; font-size: .82rem; line-height: 1.2; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.xfa-tree__node .path-hint { min-width: 0; overflow: hidden; color: var(--text-muted); font-size: .64rem; line-height: 1.2; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.xfa-tree__node .sample { min-width: 3.2rem; margin-left: auto; max-width: 30%; overflow: hidden; color: var(--text-muted); font-size: .68rem; text-align: right; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.xfa-tree__node .badge { color: var(--status-warning-fg); font-size: .72rem; font-weight: 700; }
|
||||
.toggle, .toggle-spacer { display: inline-flex; width: 16px; flex: 0 0 16px; }
|
||||
.reveal { display: inline-flex; padding: 3px; border: 0; border-radius: 6px; background: transparent; color: var(--status-info-fg); cursor: pointer; }
|
||||
.add-rule { display: none; position: relative; z-index: 1; min-width: 24px; min-height: 24px; align-items: center; justify-content: center; margin-left: 2px; border: 1px solid transparent; border-radius: 5px; background: transparent; color: var(--status-info-fg); font-size: 1rem; line-height: 1; cursor: pointer; }
|
||||
.add-rule--active { display: inline-flex; border-color: var(--status-info-border); background: var(--status-info-bg); }
|
||||
.xfa-tree__node:hover .add-rule, .xfa-tree__node:focus-within .add-rule { display: inline-flex; }
|
||||
.xfa-tree__rules { position: relative; margin: 0; padding: 1px 0 5px var(--rule-indent); list-style: none; }
|
||||
.xfa-tree__rules::before { content: ''; position: absolute; top: 0; bottom: 8px; left: var(--rule-guide-offset); width: 1px; background: var(--border-default); }
|
||||
.xfa-tree__rule { display: flex; min-width: 0; align-items: center; gap: 3px; border-radius: 4px; }
|
||||
.xfa-tree__rule.selected { background: var(--status-info-bg); }
|
||||
.xfa-tree__rule-main { display: flex; min-width: 0; flex: 1; gap: 4px; padding: 3px 2px; border: 0; background: transparent; color: var(--text-muted); text-align: left; font-size: .68rem; cursor: pointer; }
|
||||
.rule-label { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.rule-glyph { color: var(--status-info-fg); }
|
||||
.rule-edit, .rule-delete { display: inline-flex; width: 20px; height: 20px; flex: 0 0 20px; align-items: center; justify-content: center; padding: 0; border: 0; border-radius: 4px; background: transparent; cursor: pointer; }
|
||||
.rule-edit { color: var(--status-info-fg); }
|
||||
.rule-delete { color: var(--status-error-fg); font-size: .9rem; }
|
||||
.rule-edit:hover, .rule-delete:hover { background: var(--bg-page); }
|
||||
.reveal:focus-visible { outline: 2px solid var(--focus-ring); }
|
||||
.xfa-tree__empty { color: var(--text-muted); font-size: .85rem; }
|
||||
.sr-only { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0,0,0,0); border: 0; }
|
||||
</style>
|
||||
+73
@@ -0,0 +1,73 @@
|
||||
/**
|
||||
* features/admin/modules/shipping-order-document-profiles/components/XfaReadOnlyMapping.spec.ts
|
||||
* 用途:验证 XFA 只读映射组件不依赖 PDF 预览,并能展示结构身份摘要。
|
||||
* 依赖:@vue/test-utils、vue-i18n、组件本身。
|
||||
* 逻辑:传入含 xfa_readonly_mapping 的详情 DTO,断言标题与字段映射渲染。
|
||||
*/
|
||||
import { mount } from '@vue/test-utils';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { createI18n } from 'vue-i18n';
|
||||
import XfaReadOnlyMapping from './XfaReadOnlyMapping.vue';
|
||||
|
||||
const i18n = createI18n({
|
||||
legacy: false,
|
||||
locale: 'zh-CN',
|
||||
messages: {
|
||||
'zh-CN': {
|
||||
admin: {
|
||||
shippingOrderProfiles: {
|
||||
xfaReadonly: {
|
||||
title: 'XFA 只读映射',
|
||||
noPdfHint: '不显示空白 PDF',
|
||||
missing: '暂无映射',
|
||||
identityTitle: '结构身份',
|
||||
templateChecksum: 'Template',
|
||||
structureFingerprint: 'Dataset',
|
||||
authoritativeCollection: '权威集合',
|
||||
mirrorCollections: '镜像集合',
|
||||
signatureChecksum: '匹配签名',
|
||||
headerMaps: 'Header 映射',
|
||||
lineMaps: 'Line 映射',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
describe('XfaReadOnlyMapping', () => {
|
||||
it('renders structure identity and mappings without requesting PDF', () => {
|
||||
const wrapper = mount(XfaReadOnlyMapping, {
|
||||
props: {
|
||||
detail: {
|
||||
id: 1,
|
||||
profile_code: 'XFA',
|
||||
display_name: 'XFA',
|
||||
version: 1,
|
||||
status: 'published',
|
||||
schema_version_id: 1,
|
||||
structure_fingerprint: 'a'.repeat(64),
|
||||
definition: { template_mode: 'xfa_dataset' },
|
||||
template_mode: 'xfa_dataset',
|
||||
lock_version: 1,
|
||||
xfa_readonly_mapping: {
|
||||
source_contract: {
|
||||
template_packet_checksum: 'sha256:tpl',
|
||||
dataset_structure_fingerprint: 'sha256:fp',
|
||||
authoritative_line_collection_path: '/data/ITEMS/DATA',
|
||||
mirror_collection_paths: ['/data/ITEMS1/DATA'],
|
||||
},
|
||||
header_mappings: [{ mapping_id: 'm1', field_code: 'customer_po_no', path_id: 'p-po' }],
|
||||
line_mappings: [{ mapping_id: 'm2', field_code: 'material_no', path_id: 'p-mat' }],
|
||||
matching_signature_checksum: 'sig',
|
||||
},
|
||||
} as never,
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
expect(wrapper.text()).toContain('sha256:tpl');
|
||||
expect(wrapper.text()).toContain('customer_po_no');
|
||||
expect(wrapper.text()).toContain('material_no');
|
||||
expect(wrapper.text()).not.toContain('preview-pages');
|
||||
});
|
||||
});
|
||||
+97
@@ -0,0 +1,97 @@
|
||||
<!--
|
||||
features/admin/modules/shipping-order-document-profiles/components/XfaReadOnlyMapping.vue
|
||||
用途:版本详情页 XFA 只读映射证据,替代空白 PDF 画布。
|
||||
依赖:vue-i18n、XFA readonly mapping DTO。
|
||||
逻辑:展示结构身份、Header/Line 映射与集合策略;不请求 PDF 预览页。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import type { ShippingOrderDocumentProfile } from '@/features/admin/types/shipping-order-document-profile.types';
|
||||
|
||||
const props = defineProps<{
|
||||
detail: ShippingOrderDocumentProfile;
|
||||
}>();
|
||||
|
||||
const { t } = useI18n();
|
||||
|
||||
const mapping = computed(() => (props.detail as ShippingOrderDocumentProfile & {
|
||||
xfa_readonly_mapping?: {
|
||||
source_contract?: Record<string, unknown>;
|
||||
header_mappings?: Array<Record<string, unknown>>;
|
||||
line_mappings?: Array<Record<string, unknown>>;
|
||||
cross_checks?: Record<string, unknown>;
|
||||
frozen_samples?: Array<Record<string, unknown>>;
|
||||
matching_signature_checksum?: string | null;
|
||||
};
|
||||
}).xfa_readonly_mapping || null);
|
||||
|
||||
const source = computed(() => mapping.value?.source_contract || {});
|
||||
const headerMaps = computed(() => mapping.value?.header_mappings || []);
|
||||
const lineMaps = computed(() => mapping.value?.line_mappings || []);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="xfa-readonly" :aria-label="t('admin.shippingOrderProfiles.xfaReadonly.title')">
|
||||
<p 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">
|
||||
<h3>{{ t('admin.shippingOrderProfiles.xfaReadonly.identityTitle') }}</h3>
|
||||
<dl>
|
||||
<div>
|
||||
<dt>{{ t('admin.shippingOrderProfiles.xfaReadonly.templateChecksum') }}</dt>
|
||||
<dd>{{ source.template_packet_checksum || '-' }}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>{{ t('admin.shippingOrderProfiles.xfaReadonly.structureFingerprint') }}</dt>
|
||||
<dd>{{ source.dataset_structure_fingerprint || '-' }}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>{{ t('admin.shippingOrderProfiles.xfaReadonly.authoritativeCollection') }}</dt>
|
||||
<dd>{{ source.authoritative_line_collection_path || '-' }}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>{{ t('admin.shippingOrderProfiles.xfaReadonly.mirrorCollections') }}</dt>
|
||||
<dd>{{ (source.mirror_collection_paths as string[] | undefined)?.join(', ') || '-' }}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>{{ t('admin.shippingOrderProfiles.xfaReadonly.signatureChecksum') }}</dt>
|
||||
<dd>{{ mapping.matching_signature_checksum || '-' }}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
</div>
|
||||
<div class="maps">
|
||||
<div>
|
||||
<h3>{{ t('admin.shippingOrderProfiles.xfaReadonly.headerMaps') }}</h3>
|
||||
<ul>
|
||||
<li v-for="item in headerMaps" :key="String(item.mapping_id)">
|
||||
{{ item.field_code }} ← {{ item.path_id }}
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
<div>
|
||||
<h3>{{ t('admin.shippingOrderProfiles.xfaReadonly.lineMaps') }}</h3>
|
||||
<ul>
|
||||
<li v-for="item in lineMaps" :key="String(item.mapping_id)">
|
||||
{{ item.field_code }} ← {{ item.path_id }}
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.xfa-readonly { border: 1px solid #dfe7ef; border-radius: 10px; background: #fff; padding: 16px; }
|
||||
.hint { margin: 0 0 12px; color: #64748b; font-size: 13px; }
|
||||
.identity dl { display: grid; gap: 8px; margin: 8px 0 0; }
|
||||
.identity dt { color: #64748b; font-size: 12px; }
|
||||
.identity dd { margin: 2px 0 0; overflow-wrap: anywhere; font-size: 13px; }
|
||||
.maps { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; margin-top: 16px; }
|
||||
.maps h3, .identity h3 { margin: 0; font-size: 14px; color: #1e293b; }
|
||||
.maps ul { margin: 8px 0 0; padding-left: 18px; color: #334155; font-size: 13px; }
|
||||
.empty { color: #b45309; }
|
||||
@media (max-width: 767px) { .maps { grid-template-columns: 1fr; } }
|
||||
</style>
|
||||
+163
@@ -0,0 +1,163 @@
|
||||
<!--
|
||||
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; maskedValue: string | null }>;
|
||||
line: Array<{ fieldCode: string; pathLabel: string; maskedValue: 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)?.maskedValue" class="field__value">{{ mappingFor(field)?.maskedValue }}</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>
|
||||
+476
@@ -0,0 +1,476 @@
|
||||
/**
|
||||
* features/admin/modules/shipping-order-document-profiles/components/XfaSplitRulePanel.spec.ts
|
||||
* 用途:验证 XfaSplitRulePanel pipeline 规则增删、确认门禁、order 重排与 reveal 传参。
|
||||
* 依赖:Vitest、@vue/test-utils、shipping-order-document-profile API mock。
|
||||
*/
|
||||
|
||||
import { describe, expect, it, vi, beforeEach } from 'vitest';
|
||||
import { mount, flushPromises } from '@vue/test-utils';
|
||||
import { createI18n } from 'vue-i18n';
|
||||
import XfaSplitRulePanel from './XfaSplitRulePanel.vue';
|
||||
import type { OrderXfaDatasetProfileDefinition } from '@/features/admin/types/shipping-order-document-profile.types';
|
||||
|
||||
const previewMock = vi.fn();
|
||||
const messageError = vi.fn();
|
||||
|
||||
vi.mock('@/features/admin/api/shipping-order-document-profile.api', () => ({
|
||||
previewOrderProfileSampleXfaSplitRules: (...args: unknown[]) => previewMock(...args),
|
||||
}));
|
||||
|
||||
vi.mock('@/shared/composables/useMessage', () => ({
|
||||
useMessage: () => ({ success: vi.fn(), error: messageError }),
|
||||
}));
|
||||
|
||||
const baseDefinition: 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: [],
|
||||
line_mapping: { row_path: '/data/ITEMS/DATA', fields: [] },
|
||||
cross_checks: {
|
||||
acroform_enabled: false,
|
||||
mirror_collection_policy: 'ignore',
|
||||
line_amount_formula: 'disabled',
|
||||
total_amount_policy: 'disabled',
|
||||
},
|
||||
split_rules: [],
|
||||
};
|
||||
|
||||
const xfaSplitMessages = {
|
||||
title: '拆分',
|
||||
expand: '展开',
|
||||
collapse: '收起',
|
||||
preview: '预览',
|
||||
confirm: '确认',
|
||||
addRule: '新增规则',
|
||||
deleteRule: '删除',
|
||||
deleteStage: '删除阶段',
|
||||
moveUp: '上移',
|
||||
moveDown: '下移',
|
||||
ruleLabel: '规则 {index}',
|
||||
stageLabel: '阶段 {index}',
|
||||
handling: '处理',
|
||||
mapped: '映射',
|
||||
evidenceOnly: '证据',
|
||||
needsReview: '复核',
|
||||
targetField: '目标',
|
||||
selectField: '选择',
|
||||
segmentCode: '编码',
|
||||
displayName: '名称',
|
||||
note: '备注',
|
||||
lineIndex: '行号',
|
||||
prefix: '前缀',
|
||||
separators: '分隔符',
|
||||
caseSensitive: '大小写',
|
||||
regex: '正则',
|
||||
captureGroup: '捕获',
|
||||
find: '查找',
|
||||
replaceWith: '替换为',
|
||||
substringStart: '起始',
|
||||
substringEnd: '结束',
|
||||
unmatchedPolicy: '未匹配',
|
||||
revealFullValues: '完整值',
|
||||
noRules: '无规则',
|
||||
confirmNeedsPreview: '需先预览',
|
||||
confirmBlockedDiagnostics: '诊断阻断',
|
||||
confirmDialog: '确认 mapped={mapped} evidence={evidence} diagnostics={diagnostics}',
|
||||
confirmSuccess: '已确认',
|
||||
previewTitle: '预览',
|
||||
previewStatus: '状态 {status}',
|
||||
previewMapped: '映射',
|
||||
previewNoMapped: '无',
|
||||
previewSegments: '段',
|
||||
previewNoSegments: '无段',
|
||||
previewValue: '值',
|
||||
previewRuleStatus: '状态',
|
||||
diagnostics: '诊断',
|
||||
ruleSetSettings: '规则集',
|
||||
normalization: '归一化',
|
||||
stages: '阶段',
|
||||
extractionMode: '提取方式',
|
||||
extractionByLine: '按行号提取',
|
||||
extractionByLineRange: '连续多行提取',
|
||||
extractionByLabel: '按标签提取',
|
||||
extractionByRegex: '按正则提取',
|
||||
extractionBySubstring: '截取文本',
|
||||
extractLineNumber: '提取第几行',
|
||||
extractStartLine: '起始行',
|
||||
extractEndLine: '结束行',
|
||||
joinLinesWith: '合并方式',
|
||||
joinWithNewline: '保留换行',
|
||||
joinWithSpace: '空格',
|
||||
joinWithComma: '逗号',
|
||||
recognizedValue: '识别值',
|
||||
previewRequired: '预览后显示',
|
||||
showAdvanced: '高级处理',
|
||||
hideAdvanced: '收起高级处理',
|
||||
advancedProcessing: '高级处理',
|
||||
addAdvancedStep: '添加高级处理',
|
||||
advancedExtractAfterLabel: '提取标签后内容',
|
||||
stageType: '类型',
|
||||
addStage: '添加阶段',
|
||||
stageTrim: 'trim',
|
||||
stageRemoveEmptyLines: '去空行',
|
||||
lineBreaks: '换行',
|
||||
lineBreaksPlaceholder: '\\n',
|
||||
stageTypeSplitLines: '拆分行',
|
||||
stageTypeSelectLine: '选行',
|
||||
stageTypeSelectLineRange: '连续多行',
|
||||
stageTypeExtractPrefix: '前缀',
|
||||
stageTypeRegexCapture: '正则',
|
||||
stageTypeReplace: '替换',
|
||||
stageTypeSubstring: '子串',
|
||||
stageTypeNormalize: '归一化',
|
||||
validationRequired: '必填',
|
||||
validationSegmentCode: '蛇形',
|
||||
validationMappedTarget: '目标必填',
|
||||
validationPrefixValue: '前缀必填',
|
||||
validationPrefixSeparators: '分隔符必填',
|
||||
validationRegexPattern: '正则必填',
|
||||
validationLineBreaks: '换行必填',
|
||||
validationLineRangeRequired: '范围必填',
|
||||
validationLineRangeOrder: '范围错误',
|
||||
status: { draft: '草稿', confirmed: '已确认', published: '已发布' },
|
||||
};
|
||||
|
||||
const i18n = createI18n({
|
||||
legacy: false,
|
||||
locale: 'zh-CN',
|
||||
messages: {
|
||||
'zh-CN': {
|
||||
admin: {
|
||||
shippingOrderProfiles: {
|
||||
xfaSplit: xfaSplitMessages,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
function makePipelineRuleSet(overrides: Record<string, unknown> = {}) {
|
||||
return {
|
||||
rule_id: 'ruleset-1',
|
||||
rule_version: 1,
|
||||
source_path_id: 'path-matnr',
|
||||
source_field_code: 'MATNR',
|
||||
strategy: 'pipeline' as const,
|
||||
normalization: { trim: true, remove_empty_lines: true, line_breaks: ['\r\n', '\r', '\n'] },
|
||||
rules: [{
|
||||
rule_id: 'rule-1',
|
||||
order: 1,
|
||||
stages: [
|
||||
{ stage_id: 'stage-1', type: 'split_lines' as const, line_breaks: ['\n'] },
|
||||
{ stage_id: 'stage-2', type: 'select_line' as const, line_index: 1 },
|
||||
],
|
||||
segment: {
|
||||
segment_id: 'seg-1',
|
||||
segment_code: 'cpn',
|
||||
display_name: 'CPN',
|
||||
handling: 'evidence_only' as const,
|
||||
},
|
||||
}],
|
||||
status: 'draft' as const,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function mountPanel(overrides: Record<string, unknown> = {}) {
|
||||
return mount(XfaSplitRulePanel, {
|
||||
global: { plugins: [i18n] },
|
||||
props: {
|
||||
definition: structuredClone(baseDefinition),
|
||||
selectedPathId: 'path-matnr',
|
||||
selectedPathLabel: 'MATNR',
|
||||
selectedFieldCode: 'MATNR',
|
||||
selectedIsMultiline: true,
|
||||
documentId: 85,
|
||||
profileId: 52,
|
||||
schemaFields: [{
|
||||
field_id: 'f1',
|
||||
field_code: 'customer_part_number',
|
||||
scope: 'line',
|
||||
enabled: true,
|
||||
required: true,
|
||||
value_type: 'string',
|
||||
}],
|
||||
canEdit: true,
|
||||
canPreview: true,
|
||||
canRevealSensitive: true,
|
||||
persistedConfirmed: true,
|
||||
dirtyUnsaved: false,
|
||||
...overrides,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取父弹窗可调用的组件操作,验证头部按钮迁移后仍保持原有业务行为。
|
||||
* @param wrapper - 已挂载的拆分规则组件
|
||||
* @returns 组件通过 defineExpose 暴露的新增、预览与确认方法
|
||||
*/
|
||||
function exposedActions(wrapper: ReturnType<typeof mountPanel>) {
|
||||
return wrapper.vm as unknown as {
|
||||
addRule: () => void;
|
||||
runPreview: () => Promise<void>;
|
||||
confirmRules: () => void;
|
||||
};
|
||||
}
|
||||
|
||||
describe('XfaSplitRulePanel', () => {
|
||||
beforeEach(() => {
|
||||
previewMock.mockReset();
|
||||
messageError.mockReset();
|
||||
vi.spyOn(window, 'confirm').mockReturnValue(true);
|
||||
});
|
||||
|
||||
it('adds a rule with default pipeline stages and emits updated split_rules', async () => {
|
||||
const wrapper = mountPanel();
|
||||
exposedActions(wrapper).addRule();
|
||||
const emitted = wrapper.emitted('update:split-rules');
|
||||
expect(emitted?.length).toBeGreaterThan(0);
|
||||
const last = emitted?.[emitted.length - 1]?.[0] as typeof baseDefinition.split_rules;
|
||||
const ruleSet = last?.find((item) => item.source_path_id === 'path-matnr');
|
||||
expect(ruleSet?.strategy).toBe('pipeline');
|
||||
expect(ruleSet?.rules?.length).toBe(1);
|
||||
expect(ruleSet?.rules?.[0]?.stages?.length).toBe(2);
|
||||
expect(ruleSet?.rules?.[0]?.stages?.[0]?.type).toBe('split_lines');
|
||||
expect(ruleSet?.rules?.[0]?.stages?.[1]?.type).toBe('select_line');
|
||||
expect(ruleSet?.rules?.[0]?.order).toBe(1);
|
||||
expect(ruleSet?.status).toBe('draft');
|
||||
expect(ruleSet?.requires_confirmation).toBe(true);
|
||||
});
|
||||
|
||||
it('editing a confirmed rule emits draft with bumped rule_version', async () => {
|
||||
const wrapper = mountPanel({
|
||||
definition: {
|
||||
...baseDefinition,
|
||||
split_rules: [makePipelineRuleSet({
|
||||
status: 'confirmed',
|
||||
requires_confirmation: false,
|
||||
rule_version: 3,
|
||||
})],
|
||||
},
|
||||
});
|
||||
const inputs = wrapper.findAll('input');
|
||||
const segmentCodeInput = inputs.find((input) => {
|
||||
const label = input.element.closest('label');
|
||||
return label?.textContent?.includes('编码');
|
||||
});
|
||||
expect(segmentCodeInput).toBeTruthy();
|
||||
await segmentCodeInput!.setValue('cpn_updated');
|
||||
await segmentCodeInput!.trigger('input');
|
||||
const emitted = wrapper.emitted('update:split-rules');
|
||||
const last = emitted?.[emitted.length - 1]?.[0] as typeof baseDefinition.split_rules;
|
||||
const ruleSet = last?.[0];
|
||||
expect(ruleSet?.status).toBe('draft');
|
||||
expect(ruleSet?.requires_confirmation).toBe(true);
|
||||
expect(ruleSet?.rule_version).toBe(4);
|
||||
});
|
||||
|
||||
it('blocks confirm when preview has diagnostics', async () => {
|
||||
previewMock.mockResolvedValue({
|
||||
preview: {
|
||||
status: 'ok',
|
||||
mapped_fields: {},
|
||||
segments: [],
|
||||
evidence_only_segments: [],
|
||||
diagnostics: [{ code: 'DUPLICATE', message: 'dup' }],
|
||||
},
|
||||
});
|
||||
const wrapper = mountPanel({
|
||||
definition: {
|
||||
...baseDefinition,
|
||||
split_rules: [makePipelineRuleSet()],
|
||||
},
|
||||
});
|
||||
await exposedActions(wrapper).runPreview();
|
||||
await flushPromises();
|
||||
exposedActions(wrapper).confirmRules();
|
||||
expect(messageError).toHaveBeenCalledWith('诊断阻断');
|
||||
const confirmed = wrapper.emitted('update:split-rules')?.some((entry) => {
|
||||
const rules = entry[0] as typeof baseDefinition.split_rules;
|
||||
return rules?.[0]?.status === 'confirmed';
|
||||
});
|
||||
expect(confirmed).toBeFalsy();
|
||||
});
|
||||
|
||||
it('configures consecutive line extraction with range and join mode', async () => {
|
||||
const wrapper = mountPanel({
|
||||
definition: { ...baseDefinition, split_rules: [makePipelineRuleSet()] },
|
||||
});
|
||||
const extractionSelect = wrapper.findAll('select').find((select) => (
|
||||
select.element.closest('label')?.textContent?.includes('提取方式')
|
||||
));
|
||||
expect(extractionSelect).toBeTruthy();
|
||||
await extractionSelect!.setValue('select_line_range');
|
||||
const emitted = wrapper.emitted('update:split-rules');
|
||||
const last = emitted?.[emitted.length - 1]?.[0] as typeof baseDefinition.split_rules;
|
||||
const range = last?.[0]?.rules?.[0]?.stages?.find((stage) => stage.type === 'select_line_range');
|
||||
expect(range).toMatchObject({ line_start: 1, line_end: 2, join_with: 'newline' });
|
||||
const rangeWrapper = mountPanel({
|
||||
definition: { ...baseDefinition, split_rules: last },
|
||||
});
|
||||
expect(rangeWrapper.text()).toContain('起始行');
|
||||
expect(rangeWrapper.text()).toContain('结束行');
|
||||
expect(rangeWrapper.text()).toContain('合并方式');
|
||||
});
|
||||
|
||||
it('emits the final confirmed rules for parent persistence', async () => {
|
||||
previewMock.mockResolvedValue({
|
||||
preview: {
|
||||
status: 'ok',
|
||||
mapped_fields: {},
|
||||
segments: [{
|
||||
segment_id: 'seg-1', segment_code: 'cpn', rule_id: 'rule-1',
|
||||
matcher_type: 'pipeline', normalized_text: 'CPN-001', raw_text: 'CPN-001', status: 'matched',
|
||||
}],
|
||||
evidence_only_segments: [],
|
||||
diagnostics: [],
|
||||
},
|
||||
});
|
||||
const wrapper = mountPanel({
|
||||
definition: { ...baseDefinition, split_rules: [makePipelineRuleSet()] },
|
||||
});
|
||||
await exposedActions(wrapper).runPreview();
|
||||
await flushPromises();
|
||||
exposedActions(wrapper).confirmRules();
|
||||
|
||||
const confirmed = wrapper.emitted('confirmed');
|
||||
const rules = confirmed?.[0]?.[0] as typeof baseDefinition.split_rules;
|
||||
expect(rules?.[0]?.status).toBe('confirmed');
|
||||
expect(rules?.[0]?.requires_confirmation).toBe(false);
|
||||
expect(rules?.[0]?.source_path_id).toBe('path-matnr');
|
||||
expect(() => JSON.parse(JSON.stringify(rules))).not.toThrow();
|
||||
});
|
||||
|
||||
it('move up/down updates rule order field', async () => {
|
||||
const wrapper = mountPanel({
|
||||
definition: {
|
||||
...baseDefinition,
|
||||
split_rules: [makePipelineRuleSet({
|
||||
rules: [
|
||||
{
|
||||
rule_id: 'rule-a',
|
||||
order: 1,
|
||||
stages: [
|
||||
{ stage_id: 's1', type: 'split_lines', line_breaks: ['\n'] },
|
||||
{ stage_id: 's2', type: 'select_line', line_index: 1 },
|
||||
],
|
||||
segment: {
|
||||
segment_id: 'seg-a',
|
||||
segment_code: 'a',
|
||||
display_name: 'A',
|
||||
handling: 'evidence_only',
|
||||
},
|
||||
},
|
||||
{
|
||||
rule_id: 'rule-b',
|
||||
order: 2,
|
||||
stages: [
|
||||
{ stage_id: 's3', type: 'split_lines', line_breaks: ['\n'] },
|
||||
{ stage_id: 's4', type: 'select_line', line_index: 2 },
|
||||
],
|
||||
segment: {
|
||||
segment_id: 'seg-b',
|
||||
segment_code: 'b',
|
||||
display_name: 'B',
|
||||
handling: 'evidence_only',
|
||||
},
|
||||
},
|
||||
],
|
||||
})],
|
||||
},
|
||||
});
|
||||
const moveDownButtons = wrapper.findAll('button').filter((btn) => btn.text() === '下移');
|
||||
expect(moveDownButtons.length).toBeGreaterThan(0);
|
||||
await moveDownButtons[0]!.trigger('click');
|
||||
const emitted = wrapper.emitted('update:split-rules');
|
||||
const last = emitted?.[emitted.length - 1]?.[0] as typeof baseDefinition.split_rules;
|
||||
const rules = last?.[0]?.rules || [];
|
||||
const ruleA = rules.find((item) => item.rule_id === 'rule-a');
|
||||
const ruleB = rules.find((item) => item.rule_id === 'rule-b');
|
||||
expect(ruleA?.order).toBe(2);
|
||||
expect(ruleB?.order).toBe(1);
|
||||
});
|
||||
|
||||
it('defaults the third rule to extract line three', async () => {
|
||||
const wrapper = mountPanel({
|
||||
definition: {
|
||||
...baseDefinition,
|
||||
split_rules: [makePipelineRuleSet({
|
||||
rules: [
|
||||
makePipelineRuleSet().rules[0],
|
||||
{ ...makePipelineRuleSet().rules[0], rule_id: 'rule-2', order: 2 },
|
||||
],
|
||||
})],
|
||||
},
|
||||
});
|
||||
exposedActions(wrapper).addRule();
|
||||
const emitted = wrapper.emitted('update:split-rules');
|
||||
const last = emitted?.[emitted.length - 1]?.[0] as typeof baseDefinition.split_rules;
|
||||
const third = last?.[0]?.rules.find((rule) => rule.order === 3);
|
||||
expect(third?.stages.find((stage) => stage.type === 'select_line')?.line_index).toBe(3);
|
||||
});
|
||||
|
||||
it('keeps line extraction and appends label extraction as advanced processing', async () => {
|
||||
const wrapper = mountPanel({
|
||||
definition: { ...baseDefinition, split_rules: [makePipelineRuleSet()] },
|
||||
});
|
||||
const advancedButton = wrapper.findAll('button').find((btn) => btn.text().includes('高级处理'));
|
||||
await advancedButton!.trigger('click');
|
||||
const addAdvanced = wrapper.find('.xfa-split__add-stage-select');
|
||||
await addAdvanced.setValue('extract_prefix');
|
||||
await addAdvanced.trigger('change');
|
||||
const emitted = wrapper.emitted('update:split-rules');
|
||||
const last = emitted?.[emitted.length - 1]?.[0] as typeof baseDefinition.split_rules;
|
||||
expect(last?.[0]?.rules[0]?.stages.map((stage) => stage.type)).toEqual([
|
||||
'split_lines', 'select_line', 'extract_prefix',
|
||||
]);
|
||||
});
|
||||
|
||||
it('adds a rule after mounting when autoAddRule is enabled', () => {
|
||||
const wrapper = mountPanel({
|
||||
autoAddRule: true,
|
||||
definition: { ...baseDefinition, split_rules: [] },
|
||||
});
|
||||
const emitted = wrapper.emitted('update:split-rules');
|
||||
const rules = emitted?.[emitted.length - 1]?.[0] as typeof baseDefinition.split_rules;
|
||||
expect(rules?.[0]?.rules).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('passes reveal:true to preview API when checkbox enabled and canRevealSensitive', async () => {
|
||||
previewMock.mockResolvedValue({
|
||||
preview: {
|
||||
status: 'ok',
|
||||
mapped_fields: {},
|
||||
segments: [],
|
||||
evidence_only_segments: [],
|
||||
diagnostics: [],
|
||||
},
|
||||
});
|
||||
const wrapper = mountPanel({
|
||||
definition: {
|
||||
...baseDefinition,
|
||||
split_rules: [makePipelineRuleSet({ rules: [] })],
|
||||
},
|
||||
});
|
||||
const revealCheckbox = wrapper.find('.xfa-split__reveal input[type="checkbox"]');
|
||||
await revealCheckbox.setValue(true);
|
||||
await exposedActions(wrapper).runPreview();
|
||||
await flushPromises();
|
||||
expect(previewMock).toHaveBeenCalledWith(85, expect.objectContaining({ reveal: true }));
|
||||
});
|
||||
|
||||
it('ignores exposed edit actions when canEdit is false', () => {
|
||||
const wrapper = mountPanel({ canEdit: false });
|
||||
exposedActions(wrapper).addRule();
|
||||
exposedActions(wrapper).confirmRules();
|
||||
expect(wrapper.emitted('update:split-rules')).toBeUndefined();
|
||||
expect(wrapper.emitted('confirmed')).toBeUndefined();
|
||||
});
|
||||
});
|
||||
+1158
File diff suppressed because it is too large.
Load diff
+94
@@ -0,0 +1,94 @@
|
||||
/**
|
||||
* 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', maskedValue: '4510***227',
|
||||
}],
|
||||
line: [],
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(wrapper.text()).toContain('customer_po_no');
|
||||
expect(wrapper.text()).not.toContain('交叉校验策略');
|
||||
expect(wrapper.text()).not.toContain('quantity_times_unit_price');
|
||||
});
|
||||
});
|
||||
+100
@@ -0,0 +1,100 @@
|
||||
<!--
|
||||
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;
|
||||
maskedValue: 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,
|
||||
maskedValue: 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,
|
||||
maskedValue: 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.maskedValue" class="masked">({{ item.maskedValue }})</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; }
|
||||
.masked { 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>
|
||||
-36
@@ -7,8 +7,6 @@
|
||||
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
buildOrderProfileColumnRules,
|
||||
findDuplicateOrderProfileTargets,
|
||||
mergeOrderProfileHeaderLabels,
|
||||
restoreOrderProfileRegionPageNo,
|
||||
suggestFieldCodeFromHeaders,
|
||||
@@ -44,40 +42,6 @@ describe('order profile form rules', () => {
|
||||
},
|
||||
);
|
||||
|
||||
it('builds only registered direct and composite rules', () => {
|
||||
const rules = buildOrderProfileColumnRules([
|
||||
{ extractor_key: 'direct', target: 'qty' },
|
||||
{ extractor_key: 'direct', target: '' },
|
||||
{ extractor_key: 'temp_internal_parts', target: '' },
|
||||
], true);
|
||||
|
||||
// 断言忽略空列,并保持复合解析器的固定双字段输出契约。
|
||||
expect(rules).toEqual([
|
||||
{ column_index: 0, extractor_key: 'direct', target_field_codes: ['qty'] },
|
||||
{
|
||||
column_index: 2,
|
||||
extractor_key: 'temp_internal_parts',
|
||||
target_field_codes: ['customer_part_number', 'part_number'],
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it('blocks targets repeated by direct or composite mappings', () => {
|
||||
const rules = buildOrderProfileColumnRules([
|
||||
{ extractor_key: 'temp_internal_parts', target: '' },
|
||||
{ extractor_key: 'direct', target: 'part_number' },
|
||||
], true);
|
||||
|
||||
// 断言复合解析器与普通列之间的隐式重复也能在提交前被发现。
|
||||
expect(findDuplicateOrderProfileTargets(rules)).toEqual(['part_number']);
|
||||
});
|
||||
|
||||
it('does not emit an unavailable composite extractor', () => {
|
||||
expect(buildOrderProfileColumnRules([
|
||||
{ extractor_key: 'temp_internal_parts', target: '' },
|
||||
], false)).toEqual([]);
|
||||
});
|
||||
|
||||
it('keeps directly configurable tables visible despite stale multi-row state', () => {
|
||||
// 断言上一张表残留的多物理行开关不能隐藏当前可直接配置的表格。
|
||||
expect(shouldShowStandardOrderProfilePreview(true, true, true)).toBe(true);
|
||||
|
||||
-35
@@ -9,16 +9,10 @@ import type {
|
||||
CoordinateReconstructionPreview,
|
||||
OrderFieldValuePreview,
|
||||
OrderProfileCanvasRegion,
|
||||
OrderProfileColumnRule,
|
||||
OrderProfileRelativeRegion,
|
||||
OrderProfileTableRegion,
|
||||
} from '@/features/admin/types/shipping-order-document-profile.types';
|
||||
|
||||
export interface OrderProfileColumnSelection {
|
||||
extractor_key: 'direct' | 'temp_internal_parts';
|
||||
target: string;
|
||||
}
|
||||
|
||||
export interface OrderProfileLineFieldGroups {
|
||||
fieldsByLayout: Map<string, OrderProfileCanvasRegion[]>;
|
||||
boundRegionIds: Set<string>;
|
||||
@@ -101,35 +95,6 @@ export const mergeOrderProfileHeaderLabels = (
|
||||
return labels.join(' / ');
|
||||
});
|
||||
|
||||
/** 将逐列选择转换为后端白名单规则;不可用的复合解析器不会进入请求。 */
|
||||
export const buildOrderProfileColumnRules = (
|
||||
selections: OrderProfileColumnSelection[], compositeExtractorAvailable: boolean,
|
||||
): OrderProfileColumnRule[] => {
|
||||
const rules: OrderProfileColumnRule[] = [];
|
||||
selections.forEach((item, columnIndex) => {
|
||||
if (item.extractor_key === 'temp_internal_parts') {
|
||||
if (compositeExtractorAvailable) rules.push({
|
||||
column_index: columnIndex,
|
||||
extractor_key: 'temp_internal_parts',
|
||||
target_field_codes: ['customer_part_number', 'part_number'],
|
||||
});
|
||||
} else if (item.target) {
|
||||
rules.push({
|
||||
column_index: columnIndex,
|
||||
extractor_key: 'direct',
|
||||
target_field_codes: [item.target],
|
||||
});
|
||||
}
|
||||
});
|
||||
return rules;
|
||||
};
|
||||
|
||||
/** 返回跨列重复映射的目标字段,供页面阻止提交并显示明确提示。 */
|
||||
export const findDuplicateOrderProfileTargets = (rules: OrderProfileColumnRule[]): string[] => {
|
||||
const targets = rules.flatMap((item) => item.target_field_codes);
|
||||
return [...new Set(targets.filter((target, index) => targets.indexOf(target) !== index))];
|
||||
};
|
||||
|
||||
/**
|
||||
* 将历史页作用域恢复为单页画布页码;旧 all_pages 缺少原始页号时按首篇样例页迁移。
|
||||
* @param tableRegion - 已保存的 v2 表格区域
|
||||
|
||||
+7
-5
@@ -9,6 +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 { restoreOrderProfileRegionPageNo } from './orderProfileForm.utils';
|
||||
|
||||
const mergeEquivalentOrderAnchors = (items: OrderProfileCanvasRegion[]) => {
|
||||
@@ -60,8 +61,9 @@ const pageNoOf = (pageScope: 'first_page' | 'all_pages' | 'exact_page', pageNo?:
|
||||
export const buildOrderProfileReadonlyRegions = (
|
||||
profile: ShippingOrderDocumentProfile,
|
||||
): OrderProfileCanvasRegion[] => {
|
||||
const definition = asCoordinateProfileDefinition(profile.definition);
|
||||
const restored: OrderProfileCanvasRegion[] = [
|
||||
...(profile.definition.document_match.required_anchors || []).flatMap<OrderProfileCanvasRegion>((anchor) => {
|
||||
...(definition.document_match.required_anchors || []).flatMap<OrderProfileCanvasRegion>((anchor) => {
|
||||
if (!anchor.label_region || !anchor.value_region || !anchor.page_no) return [];
|
||||
return [{
|
||||
id: `${anchor.anchor_id}_label`,
|
||||
@@ -81,7 +83,7 @@ export const buildOrderProfileReadonlyRegions = (
|
||||
pageNo: anchor.page_no,
|
||||
}];
|
||||
}),
|
||||
...(profile.definition.draft_unbound_order_field_layouts || []).flatMap<OrderProfileCanvasRegion>((item) => {
|
||||
...(definition.draft_unbound_order_field_layouts || []).flatMap<OrderProfileCanvasRegion>((item) => {
|
||||
const pageNo = pageNoOf(item.page_scope, item.page_no);
|
||||
if (!item.anchor?.region || !item.absolute_value_region) {
|
||||
return [{
|
||||
@@ -111,7 +113,7 @@ export const buildOrderProfileReadonlyRegions = (
|
||||
pageNo,
|
||||
}];
|
||||
}),
|
||||
...(profile.definition.order_field_layouts || []).filter((item) => !item.anchor).map((item) => ({
|
||||
...(definition.order_field_layouts || []).filter((item) => !item.anchor).map((item) => ({
|
||||
id: item.layout_id,
|
||||
kind: 'order_field' as const,
|
||||
label: item.field_code,
|
||||
@@ -119,7 +121,7 @@ export const buildOrderProfileReadonlyRegions = (
|
||||
fieldCode: item.field_code,
|
||||
pageNo: pageNoOf(item.page_scope, item.page_no),
|
||||
})),
|
||||
...(profile.definition.order_field_layouts || []).flatMap((item) => {
|
||||
...(definition.order_field_layouts || []).flatMap((item) => {
|
||||
if (!item.anchor?.region || !item.absolute_value_region) return [];
|
||||
const anchor = item.anchor.region;
|
||||
return [{
|
||||
@@ -141,7 +143,7 @@ export const buildOrderProfileReadonlyRegions = (
|
||||
pageNo: pageNoOf(item.page_scope, item.page_no),
|
||||
}];
|
||||
}),
|
||||
...profile.definition.table_regions.flatMap((table) => {
|
||||
...definition.table_regions.flatMap((table) => {
|
||||
const regionPageNo = restoreOrderProfileRegionPageNo(table);
|
||||
const headerLayoutIds = new Set(table.header_layouts.map((item) => item.layout_id));
|
||||
return [
|
||||
|
||||
+126
@@ -0,0 +1,126 @@
|
||||
/**
|
||||
* features/admin/modules/shipping-order-document-profiles/xfaProfileMapping.utils.spec.ts
|
||||
* 用途:验证 XFA 映射工具函数——含 split_rules mapped 目标的 bound field 与覆盖率。
|
||||
* 依赖:Vitest、xfaProfileMapping.utils。
|
||||
*/
|
||||
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
collectBoundXfaFieldIds,
|
||||
computeXfaMappingCoverage,
|
||||
flattenXfaTreeNodes,
|
||||
summarizeXfaMappingBlockers,
|
||||
} from './xfaProfileMapping.utils';
|
||||
import type { OrderXfaDatasetProfileDefinition, XfaFieldTreeNode } from '@/features/admin/types/shipping-order-document-profile.types';
|
||||
|
||||
const baseDefinition: 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: [],
|
||||
line_mapping: { row_path: '/data/ITEMS/DATA', fields: [] },
|
||||
cross_checks: {
|
||||
acroform_enabled: false,
|
||||
mirror_collection_policy: 'ignore',
|
||||
line_amount_formula: 'disabled',
|
||||
total_amount_policy: 'disabled',
|
||||
},
|
||||
split_rules: [{
|
||||
rule_id: 'matnr-v1',
|
||||
rule_version: 1,
|
||||
source_path_id: 'path-matnr',
|
||||
source_field_code: 'MATNR',
|
||||
strategy: 'pipeline',
|
||||
rules: [{
|
||||
rule_id: 'r1',
|
||||
order: 1,
|
||||
stages: [
|
||||
{ stage_id: 'st1', type: 'split_lines', line_breaks: ['\n'] },
|
||||
{ stage_id: 'st2', type: 'select_line', line_index: 1 },
|
||||
],
|
||||
segment: {
|
||||
segment_id: 'seg-1',
|
||||
segment_code: 'cpn',
|
||||
display_name: 'CPN',
|
||||
handling: 'mapped',
|
||||
target_field_id: 'f-cpn',
|
||||
target_field_code: 'customer_part_number',
|
||||
},
|
||||
}],
|
||||
status: 'confirmed',
|
||||
source: 'user',
|
||||
requires_confirmation: false,
|
||||
}],
|
||||
};
|
||||
|
||||
describe('xfaProfileMapping split utils', () => {
|
||||
it('collectBoundXfaFieldIds includes split mapped targets', () => {
|
||||
const ids = collectBoundXfaFieldIds(baseDefinition);
|
||||
expect(ids.has('f-cpn')).toBe(true);
|
||||
});
|
||||
|
||||
it('computeXfaMappingCoverage does not treat Schema required fields as template blockers', () => {
|
||||
const coverage = computeXfaMappingCoverage(
|
||||
[{
|
||||
field_id: 'f-cpn',
|
||||
field_code: 'customer_part_number',
|
||||
scope: 'line',
|
||||
enabled: true,
|
||||
required: true,
|
||||
value_type: 'string',
|
||||
}],
|
||||
baseDefinition,
|
||||
'path-data',
|
||||
);
|
||||
expect(coverage.missingRequired).toHaveLength(0);
|
||||
expect(coverage.requiredTotal).toBe(0);
|
||||
expect(coverage.requiredMapped).toBe(0);
|
||||
expect(summarizeXfaMappingBlockers(coverage)).not.toContain('required_fields_unmapped');
|
||||
});
|
||||
|
||||
it('flattenXfaTreeNodes copies line_count to lineCount', () => {
|
||||
const tree: XfaFieldTreeNode = {
|
||||
path_id: 'root',
|
||||
local_name: 'data',
|
||||
data_path_hash: 'h-root',
|
||||
depth: 0,
|
||||
cardinality: 'one',
|
||||
is_leaf: false,
|
||||
children: [{
|
||||
path_id: 'matnr',
|
||||
local_name: 'MATNR',
|
||||
data_path_hash: 'h-matnr',
|
||||
depth: 1,
|
||||
cardinality: 'one',
|
||||
is_leaf: true,
|
||||
line_count: 5,
|
||||
}],
|
||||
};
|
||||
const flat = flattenXfaTreeNodes(tree);
|
||||
const matnr = flat.find((item) => item.pathId === 'matnr');
|
||||
expect(matnr?.lineCount).toBe(5);
|
||||
});
|
||||
|
||||
it('selectedIsMultiline uses lineCount greater than one', () => {
|
||||
const tree: XfaFieldTreeNode = {
|
||||
path_id: 'single',
|
||||
local_name: 'FIELD',
|
||||
data_path_hash: 'h1',
|
||||
depth: 0,
|
||||
cardinality: 'one',
|
||||
is_leaf: true,
|
||||
line_count: 1,
|
||||
};
|
||||
const flat = flattenXfaTreeNodes(tree);
|
||||
expect((flat[0]?.lineCount || 0) > 1).toBe(false);
|
||||
|
||||
const multiline: XfaFieldTreeNode = { ...tree, path_id: 'multi', line_count: 3 };
|
||||
const flatMulti = flattenXfaTreeNodes(multiline);
|
||||
expect((flatMulti[0]?.lineCount || 0) > 1).toBe(true);
|
||||
});
|
||||
});
|
||||
+476
@@ -0,0 +1,476 @@
|
||||
/**
|
||||
* features/admin/modules/shipping-order-document-profiles/xfaProfileMapping.utils.ts
|
||||
* 用途:XFA 映射工作台纯函数——树投影、Schema 过滤、覆盖率、保存 payload 与脏状态检测。
|
||||
* 依赖:shipping-order-document-profile.types、订单 Schema 字段类型。
|
||||
* 逻辑:页面与组件只调用本文件;不发网络请求,不持有明文 XML 或 data_path。
|
||||
*/
|
||||
|
||||
import type {
|
||||
OrderXfaDatasetProfileDefinition,
|
||||
XfaCollectionCandidate,
|
||||
XfaFieldMapping,
|
||||
XfaFieldTreeNode,
|
||||
XfaMappingCoverageSummary,
|
||||
} from '@/features/admin/types/shipping-order-document-profile.types';
|
||||
import type { ShippingOrderFieldConfig } from '@/features/admin/types/shipping-order-schema.types';
|
||||
|
||||
export type XfaSchemaFilterMode = 'all' | 'unmapped';
|
||||
|
||||
export interface XfaFlatTreeNode {
|
||||
pathId: string;
|
||||
localName: string;
|
||||
depth: number;
|
||||
isLeaf: boolean;
|
||||
isHeaderCandidate: boolean;
|
||||
isCollectionCandidate: boolean;
|
||||
sampleValueMasked?: string;
|
||||
sampleValueDisplay?: string;
|
||||
displayPolicy: 'empty' | 'full' | 'partial' | 'restricted';
|
||||
canReveal: boolean;
|
||||
lineCount?: number;
|
||||
dataPathHash: string;
|
||||
parentPathId?: string;
|
||||
}
|
||||
|
||||
export interface XfaMappingWorkbenchState {
|
||||
definition: OrderXfaDatasetProfileDefinition;
|
||||
authoritativeCollectionPathId: string;
|
||||
mirrorCollectionPathIds: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* 将 XFA 字段树投影为可键盘导航的扁平节点列表。
|
||||
* 核心逻辑:深度优先展开;仅保留分析记录返回的节点。
|
||||
* @param tree 字段树根节点
|
||||
* @returns 扁平节点(含 depth / leaf / collection 标记)
|
||||
*/
|
||||
export function flattenXfaTreeNodes(tree: XfaFieldTreeNode | null | undefined): XfaFlatTreeNode[] {
|
||||
if (!tree || !tree.path_id) return [];
|
||||
const rows: XfaFlatTreeNode[] = [];
|
||||
|
||||
const walk = (node: XfaFieldTreeNode, parentPathId?: string): void => {
|
||||
rows.push({
|
||||
pathId: node.path_id,
|
||||
localName: node.local_name,
|
||||
depth: node.depth,
|
||||
isLeaf: Boolean(node.is_leaf),
|
||||
isHeaderCandidate: Boolean(node.is_header_candidate),
|
||||
isCollectionCandidate: Boolean(node.is_collection_candidate),
|
||||
sampleValueMasked: node.sample_value_masked,
|
||||
sampleValueDisplay: node.sample_value_display || node.sample_value_masked,
|
||||
displayPolicy: node.display_policy || 'empty',
|
||||
canReveal: Boolean(node.can_reveal),
|
||||
lineCount: node.line_count,
|
||||
dataPathHash: node.data_path_hash,
|
||||
parentPathId,
|
||||
});
|
||||
for (const child of node.children || []) walk(child, node.path_id);
|
||||
};
|
||||
walk(tree);
|
||||
return rows;
|
||||
}
|
||||
|
||||
/**
|
||||
* 由 path_id 链向上拼接 local_name 展示标签(不含服务端明文路径)。
|
||||
* @param pathId 目标节点 path_id
|
||||
* @param nodes 扁平树节点
|
||||
*/
|
||||
export function buildXfaPathLabel(pathId: string, nodes: XfaFlatTreeNode[]): string {
|
||||
const byId = new Map(nodes.map((item) => [item.pathId, item]));
|
||||
const parts: string[] = [];
|
||||
let current = byId.get(pathId);
|
||||
while (current) {
|
||||
parts.unshift(current.localName);
|
||||
current = current.parentPathId ? byId.get(current.parentPathId) : undefined;
|
||||
}
|
||||
return parts.join('/') || pathId;
|
||||
}
|
||||
|
||||
/**
|
||||
* 按关键字过滤扁平树(匹配 local_name / path_id / 脱敏样例)。
|
||||
* @param nodes 扁平节点
|
||||
* @param query 搜索词
|
||||
*/
|
||||
export function filterXfaTreeNodes(nodes: XfaFlatTreeNode[], query: string): XfaFlatTreeNode[] {
|
||||
const needle = query.trim().toLowerCase();
|
||||
if (!needle) return nodes;
|
||||
return nodes.filter((item) => (
|
||||
item.localName.toLowerCase().includes(needle)
|
||||
|| item.pathId.toLowerCase().includes(needle)
|
||||
|| String(item.sampleValueMasked || '').toLowerCase().includes(needle)
|
||||
));
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断节点是否位于权威明细集合之下(用于 Header/Line scope 划分)。
|
||||
* @param pathId 选中叶子 path_id
|
||||
* @param authoritativePathId 权威集合 path_id
|
||||
* @param nodes 扁平树
|
||||
*/
|
||||
export function isXfaPathUnderCollection(
|
||||
pathId: string,
|
||||
authoritativePathId: string,
|
||||
nodes: XfaFlatTreeNode[],
|
||||
): boolean {
|
||||
if (!authoritativePathId || pathId === authoritativePathId) return false;
|
||||
const byId = new Map(nodes.map((item) => [item.pathId, item]));
|
||||
let current = byId.get(pathId);
|
||||
while (current) {
|
||||
if (current.pathId === authoritativePathId) return true;
|
||||
current = current.parentPathId ? byId.get(current.parentPathId) : undefined;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析选中树节点应绑定的 Schema scope。
|
||||
* @param pathId 选中 path_id
|
||||
* @param authoritativePathId 权威集合 path_id
|
||||
* @param nodes 扁平树
|
||||
*/
|
||||
export function resolveXfaNodeScope(
|
||||
pathId: string,
|
||||
authoritativePathId: string,
|
||||
nodes: XfaFlatTreeNode[],
|
||||
): 'header' | 'line' | null {
|
||||
const node = nodes.find((item) => item.pathId === pathId);
|
||||
if (!node?.isLeaf) return null;
|
||||
return isXfaPathUnderCollection(pathId, authoritativePathId, nodes) ? 'line' : 'header';
|
||||
}
|
||||
|
||||
/**
|
||||
* 过滤 Schema 字段列表供映射面板展示。
|
||||
* @param fields 已启用字段
|
||||
* @param scope 当前节点 scope
|
||||
* @param filterMode 全部/未映射
|
||||
* @param definition 当前 definition
|
||||
* @param boundFieldIds 已绑定 field_id 集合
|
||||
*/
|
||||
export function filterXfaSchemaFields(
|
||||
fields: ShippingOrderFieldConfig[],
|
||||
scope: 'header' | 'line',
|
||||
filterMode: XfaSchemaFilterMode,
|
||||
definition: OrderXfaDatasetProfileDefinition,
|
||||
): ShippingOrderFieldConfig[] {
|
||||
const mappings = scope === 'header'
|
||||
? definition.header_mappings || []
|
||||
: definition.line_mapping?.fields || [];
|
||||
const mappedCodes = new Set(mappings.map((item) => item.field_code));
|
||||
return fields.filter((field) => {
|
||||
if (field.enabled === false || field.scope !== scope || !field.field_code) return false;
|
||||
if (filterMode === 'unmapped' && mappedCodes.has(field.field_code)) return false;
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 收集全部已绑定 field_id,含 split_rules 中 mapped 目标字段。
|
||||
*/
|
||||
export function collectBoundXfaFieldIds(definition: OrderXfaDatasetProfileDefinition): Set<string> {
|
||||
const ids = new Set<string>();
|
||||
for (const item of [...(definition.header_mappings || []), ...(definition.line_mapping?.fields || [])]) {
|
||||
if (item.field_id) ids.add(item.field_id);
|
||||
}
|
||||
for (const ruleSet of 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;
|
||||
}
|
||||
|
||||
/**
|
||||
* 查找 path_id 对应的映射项。
|
||||
*/
|
||||
export function findXfaMappingByPathId(
|
||||
definition: OrderXfaDatasetProfileDefinition,
|
||||
pathId: string,
|
||||
): XfaFieldMapping | null {
|
||||
const all = [...(definition.header_mappings || []), ...(definition.line_mapping?.fields || [])];
|
||||
return all.find((item) => item.path_id === pathId) || null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 查找 field_id 对应的映射项。
|
||||
*/
|
||||
export function findXfaMappingByFieldId(
|
||||
definition: OrderXfaDatasetProfileDefinition,
|
||||
fieldId: string,
|
||||
): XfaFieldMapping | null {
|
||||
const all = [...(definition.header_mappings || []), ...(definition.line_mapping?.fields || [])];
|
||||
return all.find((item) => item.field_id === fieldId) || null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 计算 XFA 模板映射的重复绑定与权威集合状态。
|
||||
* @param schemaFields 已启用 Schema 字段
|
||||
* @param definition 当前 XFA definition
|
||||
* @param authoritativePathId 权威集合 path_id(UI 态)
|
||||
*/
|
||||
export function computeXfaMappingCoverage(
|
||||
schemaFields: ShippingOrderFieldConfig[],
|
||||
definition: OrderXfaDatasetProfileDefinition | null | undefined,
|
||||
authoritativePathId = '',
|
||||
): XfaMappingCoverageSummary {
|
||||
const headers = definition?.header_mappings || [];
|
||||
const lines = definition?.line_mapping?.fields || [];
|
||||
const bound = new Map<string, string>();
|
||||
const duplicateFieldIds: string[] = [];
|
||||
for (const item of [...headers, ...lines]) {
|
||||
const key = String(item.field_id || '');
|
||||
if (!key) continue;
|
||||
if (bound.has(key)) duplicateFieldIds.push(key);
|
||||
else bound.set(key, item.field_code);
|
||||
}
|
||||
void schemaFields;
|
||||
const authPath = String(definition?.source_contract?.authoritative_line_collection_path || '').trim();
|
||||
return {
|
||||
requiredTotal: 0,
|
||||
requiredMapped: 0,
|
||||
missingRequired: [],
|
||||
duplicateFieldIds: [...new Set(duplicateFieldIds)],
|
||||
authoritativeMissing: !authoritativePathId && !authPath,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断集合是否可作为镜像(与权威不同)。
|
||||
* @param candidates 集合候选
|
||||
* @param authoritativePathId 权威 path_id
|
||||
*/
|
||||
export function listMirrorCollectionCandidates(
|
||||
candidates: XfaCollectionCandidate[],
|
||||
authoritativePathId: string,
|
||||
): XfaCollectionCandidate[] {
|
||||
return candidates.filter((item) => item.path_id && item.path_id !== authoritativePathId);
|
||||
}
|
||||
|
||||
/**
|
||||
* 绑定 Schema 字段到选中 path_id,返回新的 definition(不可变)。
|
||||
* 核心逻辑:同 field_id 覆盖;拒绝跨 scope;保留既有 mapping_id。
|
||||
*/
|
||||
export function bindXfaSchemaField(options: {
|
||||
definition: OrderXfaDatasetProfileDefinition;
|
||||
scope: 'header' | 'line';
|
||||
field: ShippingOrderFieldConfig;
|
||||
pathId: string;
|
||||
}): OrderXfaDatasetProfileDefinition {
|
||||
const { definition, scope, field, pathId } = options;
|
||||
if (field.scope !== scope) {
|
||||
throw new Error('scope_mismatch');
|
||||
}
|
||||
const existing = findXfaMappingByFieldId(definition, field.field_id);
|
||||
const mapping: XfaFieldMapping = {
|
||||
mapping_id: existing?.mapping_id || `map-${field.field_id}-${pathId}`.slice(0, 64),
|
||||
field_id: field.field_id,
|
||||
field_code: field.field_code || '',
|
||||
data_path: '',
|
||||
path_id: pathId,
|
||||
value_type: field.value_type || 'string',
|
||||
normalizer_key: field.normalizer_key ?? null,
|
||||
validator_key: field.validator_keys?.[0] ?? null,
|
||||
};
|
||||
if (scope === 'header') {
|
||||
const others = (definition.header_mappings || []).filter((item) => item.field_id !== field.field_id);
|
||||
return { ...definition, header_mappings: [...others, mapping] };
|
||||
}
|
||||
const others = (definition.line_mapping?.fields || []).filter((item) => item.field_id !== field.field_id);
|
||||
return {
|
||||
...definition,
|
||||
line_mapping: {
|
||||
row_path: definition.line_mapping?.row_path || definition.source_contract.authoritative_line_collection_path,
|
||||
fields: [...others, mapping],
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 解除 Schema 字段映射。
|
||||
*/
|
||||
export function unbindXfaSchemaField(
|
||||
definition: OrderXfaDatasetProfileDefinition,
|
||||
fieldId: string,
|
||||
): OrderXfaDatasetProfileDefinition {
|
||||
return {
|
||||
...definition,
|
||||
header_mappings: (definition.header_mappings || []).filter((item) => item.field_id !== fieldId),
|
||||
line_mapping: {
|
||||
row_path: definition.line_mapping?.row_path || definition.source_contract.authoritative_line_collection_path,
|
||||
fields: (definition.line_mapping?.fields || []).filter((item) => item.field_id !== fieldId),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 组装保存请求 definition:附带 path_id 集合选择,data_path 由服务端重写。
|
||||
* @param state 工作台当前状态
|
||||
*/
|
||||
export function buildXfaSaveDefinitionPayload(state: XfaMappingWorkbenchState): Record<string, unknown> {
|
||||
const { definition, authoritativeCollectionPathId, mirrorCollectionPathIds } = state;
|
||||
return {
|
||||
...definition,
|
||||
template_mode: 'xfa_dataset',
|
||||
authoritative_collection_path_id: authoritativeCollectionPathId,
|
||||
mirror_collection_path_ids: mirrorCollectionPathIds,
|
||||
header_mappings: (definition.header_mappings || []).map((item) => ({
|
||||
mapping_id: item.mapping_id,
|
||||
field_id: item.field_id,
|
||||
field_code: item.field_code,
|
||||
path_id: item.path_id,
|
||||
value_type: item.value_type,
|
||||
normalizer_key: item.normalizer_key,
|
||||
validator_key: item.validator_key,
|
||||
})),
|
||||
line_mapping: {
|
||||
fields: (definition.line_mapping?.fields || []).map((item) => ({
|
||||
mapping_id: item.mapping_id,
|
||||
field_id: item.field_id,
|
||||
field_code: item.field_code,
|
||||
path_id: item.path_id,
|
||||
value_type: item.value_type,
|
||||
normalizer_key: item.normalizer_key,
|
||||
validator_key: item.validator_key,
|
||||
})),
|
||||
},
|
||||
split_rules: definition.split_rules || [],
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 本地校验摘要:权威集合、重复绑定、必填缺口。
|
||||
*/
|
||||
export function summarizeXfaMappingBlockers(coverage: XfaMappingCoverageSummary): string[] {
|
||||
const blockers: string[] = [];
|
||||
if (coverage.authoritativeMissing) blockers.push('authoritative_collection_required');
|
||||
if (coverage.duplicateFieldIds.length) blockers.push('duplicate_field_binding');
|
||||
return blockers;
|
||||
}
|
||||
|
||||
/**
|
||||
* 截断 checksum 供页眉展示。
|
||||
*/
|
||||
export function shortenXfaChecksum(value: string | null | undefined, length = 4): string {
|
||||
const text = String(value || '').replace(/^sha256:/i, '');
|
||||
if (!text) return '—';
|
||||
return text.length <= length * 2 ? text : `${text.slice(0, length)}…`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断工作台状态是否与已保存快照不同(脏状态检测)。
|
||||
*/
|
||||
export function isXfaMappingDirty(
|
||||
saved: XfaMappingWorkbenchState | null | undefined,
|
||||
current: XfaMappingWorkbenchState,
|
||||
): boolean {
|
||||
if (!saved) return true;
|
||||
return JSON.stringify(buildXfaSaveDefinitionPayload(saved))
|
||||
!== JSON.stringify(buildXfaSaveDefinitionPayload(current));
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断两个 definition 是否语义相等(兼容旧调用)。
|
||||
*/
|
||||
export function isSameXfaDefinition(
|
||||
left: OrderXfaDatasetProfileDefinition | null | undefined,
|
||||
right: OrderXfaDatasetProfileDefinition | null | undefined,
|
||||
): boolean {
|
||||
return JSON.stringify(left || null) === JSON.stringify(right || null);
|
||||
}
|
||||
|
||||
/**
|
||||
* 计算与后端 `hash_data_path` 一致的路径哈希(`sha256:<hex>`)。
|
||||
* 核心逻辑:对已 trim 的绝对路径做 UTF-8 SHA-256;用于从已保存明文路径反查 path_id。
|
||||
* @param path 受控 data_path(如 `/data/ITEMS/DATA`)
|
||||
*/
|
||||
export async function hashXfaDataPath(path: string): Promise<string> {
|
||||
const text = String(path || '').trim();
|
||||
if (!text.startsWith('/')) {
|
||||
throw new Error('invalid_xfa_data_path');
|
||||
}
|
||||
const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(text));
|
||||
const hex = [...new Uint8Array(digest)]
|
||||
.map((byte) => byte.toString(16).padStart(2, '0'))
|
||||
.join('');
|
||||
return `sha256:${hex}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 从已保存 definition 与集合候选反查权威集合 path_id。
|
||||
* 核心逻辑:优先用权威明文路径哈希精确匹配 collection_path_hash / 树节点 dataPathHash;
|
||||
* 再回退 line 映射祖先集合;最后才用唯一候选。
|
||||
*/
|
||||
export async function resolveAuthoritativePathId(
|
||||
definition: OrderXfaDatasetProfileDefinition,
|
||||
candidates: XfaCollectionCandidate[],
|
||||
flatNodes: XfaFlatTreeNode[],
|
||||
): Promise<string> {
|
||||
const authPath = String(definition.source_contract?.authoritative_line_collection_path || '').trim();
|
||||
if (authPath) {
|
||||
try {
|
||||
const wanted = await hashXfaDataPath(authPath);
|
||||
const byCandidate = candidates.find((item) => item.collection_path_hash === wanted && item.path_id);
|
||||
if (byCandidate?.path_id) return byCandidate.path_id;
|
||||
const byTree = flatNodes.find(
|
||||
(item) => item.isCollectionCandidate && item.dataPathHash === wanted && item.pathId,
|
||||
);
|
||||
if (byTree?.pathId) return byTree.pathId;
|
||||
} catch {
|
||||
// 非法路径时继续走启发式回退。
|
||||
}
|
||||
}
|
||||
|
||||
const linePathId = (definition.line_mapping?.fields || [])[0]?.path_id;
|
||||
if (linePathId) {
|
||||
let current = flatNodes.find((item) => item.pathId === linePathId);
|
||||
while (current) {
|
||||
if (current.isCollectionCandidate) return current.pathId;
|
||||
current = current.parentPathId
|
||||
? flatNodes.find((item) => item.pathId === current?.parentPathId)
|
||||
: undefined;
|
||||
}
|
||||
}
|
||||
|
||||
const collectionNodes = flatNodes.filter((item) => item.isCollectionCandidate);
|
||||
if (collectionNodes.length === 1 && collectionNodes[0]?.pathId) {
|
||||
return collectionNodes[0].pathId;
|
||||
}
|
||||
if (candidates.length === 1 && candidates[0]?.path_id) {
|
||||
return candidates[0].path_id;
|
||||
}
|
||||
const preferred = collectionNodes.find((item) => item.localName.toUpperCase() === 'DATA');
|
||||
return preferred?.pathId || '';
|
||||
}
|
||||
|
||||
/**
|
||||
* 从已保存镜像明文路径精确恢复镜像集合 path_id 列表。
|
||||
* 核心逻辑:逐条 hash 匹配;排除权威;不按“前 N 个候选”猜测。
|
||||
*/
|
||||
export async function resolveMirrorPathIds(
|
||||
definition: OrderXfaDatasetProfileDefinition,
|
||||
candidates: XfaCollectionCandidate[],
|
||||
authoritativePathId: string,
|
||||
): Promise<string[]> {
|
||||
const mirrors = (definition.source_contract?.mirror_collection_paths || [])
|
||||
.map((item) => String(item || '').trim())
|
||||
.filter(Boolean);
|
||||
if (!mirrors.length) return [];
|
||||
const resolved: string[] = [];
|
||||
for (const path of mirrors) {
|
||||
try {
|
||||
const wanted = await hashXfaDataPath(path);
|
||||
const hit = candidates.find(
|
||||
(item) => item.collection_path_hash === wanted
|
||||
&& item.path_id
|
||||
&& item.path_id !== authoritativePathId,
|
||||
);
|
||||
if (hit?.path_id && !resolved.includes(hit.path_id)) {
|
||||
resolved.push(hit.path_id);
|
||||
}
|
||||
} catch {
|
||||
// skip invalid mirror path
|
||||
}
|
||||
}
|
||||
return resolved;
|
||||
}
|
||||
@@ -1,17 +1,19 @@
|
||||
/**
|
||||
* features/admin/types/shipping-order-document-profile.types.ts
|
||||
* 用途:订单文档坐标模板 v2、受控样本预览和字段区域 DTO。
|
||||
* 用途:订单文档坐标模板、XFA 数据路径模板、受控样本预览和字段区域 DTO。
|
||||
* 依赖:无。
|
||||
* 逻辑:管理页面只提交样本选择和白名单解析器,不持有或提交 HTML/结构指纹。
|
||||
* 逻辑:管理页面只提交样本选择、白名单解析器与受控 path_id;不持有或提交 HTML/
|
||||
* 完整 XML、原始 PDF bytes 或对象存储地址。template_mode 为鉴别联合入口。
|
||||
*/
|
||||
|
||||
export type OrderProfileTemplateMode = 'coordinate' | 'xfa_dataset';
|
||||
export type OrderProfileExtractorKey = 'direct' | 'temp_internal_parts' | 'quantity_uom' | 'amount_currency' | 'price_currency';
|
||||
export type OrderProfileEvidenceLevel = 'coordinate' | 'ocr_coordinate';
|
||||
export type OrderProfileAllowedSource = 'pdf_coordinate' | 'ocr_coordinate';
|
||||
export type OrderProfileRowReconstructionMode = 'fixed_subrows' | 'adaptive_record_columns';
|
||||
export type OrderProfileChangeSource = 'wizard_created' | 'manual_save' | 'autosave' | 'restore' | 'sample_changed';
|
||||
export type OrderProfileLeaseState = 'active' | 'expired' | 'released' | 'taken_over';
|
||||
export type OrderProfileValidationRunType = 'instant_check' | 'current_sample' | 'blind_test' | 'scenario_coverage' | 'schema_compatibility';
|
||||
export type OrderProfileValidationRunType = 'instant_check' | 'current_sample' | 'blind_test' | 'scenario_coverage' | 'schema_compatibility' | 'layout_signature' | 'cross_template_overlap' | 'xfa_structure_signature';
|
||||
export type OrderProfileValidationRunStatus = 'pending' | 'running' | 'passed' | 'failed' | 'stale';
|
||||
export type OrderProfilePublishCheckStatus = 'valid' | 'invalidated' | 'consumed' | 'expired';
|
||||
|
||||
@@ -23,7 +25,37 @@ export type OrderProfileGovernanceErrorCode =
|
||||
| 'SHIPPING.ORDER_DOCUMENT_PROFILE_REVISION_NOT_FOUND'
|
||||
| 'SHIPPING.ORDER_DOCUMENT_PROFILE_VALIDATION_STALE'
|
||||
| 'SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_CHECK_INVALID'
|
||||
| 'SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_CHECK_CONSUMED';
|
||||
| 'SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_CHECK_CONSUMED'
|
||||
| 'SHIPPING.ORDER_DOCUMENT_PROFILE_SIGNATURE_REQUIRED'
|
||||
| 'SHIPPING.ORDER_DOCUMENT_PROFILE_SIGNATURE_STALE'
|
||||
| 'SHIPPING.ORDER_DOCUMENT_PROFILE_OVERLAP_DETECTED';
|
||||
|
||||
/** XFA 稳定错误码(阶段 0 冻结;与后端 XFA_ERROR_CODES 对齐)。 */
|
||||
export type OrderProfileXfaErrorCode =
|
||||
| 'XFA_DATASET_MISSING'
|
||||
| 'XFA_UNSAFE_XML'
|
||||
| 'XFA_PACKET_TOO_LARGE'
|
||||
| 'XFA_XML_DEPTH_EXCEEDED'
|
||||
| 'XFA_XML_NODE_LIMIT_EXCEEDED'
|
||||
| 'XFA_LINE_ROW_LIMIT_EXCEEDED'
|
||||
| 'XFA_PARSE_TIMEOUT'
|
||||
| 'XFA_UNSUPPORTED_DOCUMENT'
|
||||
| 'XFA_PROFILE_NOT_MATCHED'
|
||||
| 'XFA_PROFILE_AMBIGUOUS'
|
||||
| 'XFA_REQUIRED_FIELD_MISSING'
|
||||
| 'XFA_MIRROR_COLLECTION_MISMATCH'
|
||||
| 'XFA_ACROFORM_MISMATCH'
|
||||
| 'XFA_BUSINESS_VALIDATION_FAILED'
|
||||
| 'XFA_AUTHORITATIVE_COLLECTION_MISSING'
|
||||
| 'XFA_PATH_INVALID'
|
||||
| 'XFA_PATH_UNKNOWN'
|
||||
| 'XFA_DEFINITION_INVALID';
|
||||
|
||||
export type XfaDocumentKind = 'plain_pdf' | 'acroform' | 'xfa_hybrid' | 'pure_xfa' | 'unsupported';
|
||||
export type XfaCrossCheckStatus = 'matched' | 'partial' | 'mismatched' | 'skipped' | 'unavailable' | 'failed';
|
||||
export type XfaMirrorCollectionPolicy = 'must_match_when_present' | 'ignore';
|
||||
export type XfaLineAmountFormula = 'quantity_times_unit_price' | 'disabled';
|
||||
export type XfaTotalAmountPolicy = 'must_equal_line_sum' | 'disabled';
|
||||
|
||||
export interface OrderProfileRelativeRegion { x0: number; y0: number; x1: number; y1: number; }
|
||||
export interface OrderProfileDocumentMatchAnchor { anchor_id: string; label: string; value: string; value_position: 'right' | 'below'; page_no?: number | null; label_region?: OrderProfileRelativeRegion | null; value_region?: OrderProfileRelativeRegion | null; minimum_evidence_level: OrderProfileEvidenceLevel; }
|
||||
@@ -36,8 +68,212 @@ export interface OrderProfileLineLayout { layout_id: string; row_offset: number;
|
||||
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 OrderProfileDocumentMatch { document_type: 'purchase_order'; page_pattern: 'one_or_more'; required_anchors: OrderProfileDocumentMatchAnchor[]; optional_anchors: OrderProfileDocumentMatchAnchor[]; minimum_score: number; minimum_margin: number; }
|
||||
|
||||
/** 阶段 3 重构前仅用于让旧工作台编译;不能作为 v2 API 请求或持久化定义。 */
|
||||
export interface OrderProfileColumnRule { column_index: number; extractor_key: 'direct' | 'temp_internal_parts'; target_field_codes: string[]; target_fields?: Array<{ field_id: string; field_code: string }>; }
|
||||
/** coordinate 模式 definition:不得与 XFA 映射字段混用。 */
|
||||
export interface OrderCoordinateProfileDefinition {
|
||||
template_mode?: 'coordinate';
|
||||
document_match: OrderProfileDocumentMatch;
|
||||
table_regions: OrderProfileTableRegion[];
|
||||
order_field_layouts?: OrderProfileOrderFieldLayout[];
|
||||
draft_unbound_order_field_layouts?: OrderProfileDraftUnboundOrderFieldLayout[];
|
||||
}
|
||||
|
||||
export interface XfaSourceContract {
|
||||
template_packet_checksum: string;
|
||||
dataset_structure_fingerprint: string;
|
||||
dataset_root_path: string;
|
||||
authoritative_line_collection_path: string;
|
||||
mirror_collection_paths: string[];
|
||||
}
|
||||
|
||||
export interface XfaFieldMapping {
|
||||
mapping_id: string;
|
||||
field_id: string;
|
||||
field_code: string;
|
||||
data_path: string;
|
||||
path_id: string;
|
||||
value_type: string;
|
||||
normalizer_key?: string | null;
|
||||
validator_key?: string | null;
|
||||
}
|
||||
|
||||
export interface XfaLineMapping {
|
||||
row_path: string;
|
||||
fields: XfaFieldMapping[];
|
||||
}
|
||||
|
||||
export interface XfaCrossChecks {
|
||||
acroform_enabled: boolean;
|
||||
mirror_collection_policy: XfaMirrorCollectionPolicy;
|
||||
line_amount_formula: XfaLineAmountFormula;
|
||||
total_amount_policy: XfaTotalAmountPolicy;
|
||||
}
|
||||
|
||||
/** xfa_dataset 模式 definition:禁止混入 table_regions / order_field_layouts。 */
|
||||
export interface OrderXfaDatasetProfileDefinition {
|
||||
template_mode: 'xfa_dataset';
|
||||
source_contract: XfaSourceContract;
|
||||
header_mappings: XfaFieldMapping[];
|
||||
line_mapping: XfaLineMapping;
|
||||
cross_checks: XfaCrossChecks;
|
||||
split_rules?: XfaSplitRuleSet[];
|
||||
}
|
||||
|
||||
export type XfaSplitHandling = 'mapped' | 'evidence_only';
|
||||
export type XfaSplitStageType =
|
||||
| 'split_lines'
|
||||
| 'select_line'
|
||||
| 'select_line_range'
|
||||
| 'extract_prefix'
|
||||
| 'regex_capture'
|
||||
| 'replace'
|
||||
| 'substring'
|
||||
| 'normalize';
|
||||
export type XfaSplitRuleStatus = 'draft' | 'confirmed' | 'published';
|
||||
export type XfaSplitRuleSource = 'system_suggestion' | 'user' | 'imported';
|
||||
|
||||
export interface XfaSplitSegment {
|
||||
segment_id: string;
|
||||
segment_code: string;
|
||||
display_name: string;
|
||||
handling: XfaSplitHandling;
|
||||
target_field_id?: string | null;
|
||||
target_field_code?: string | null;
|
||||
note?: string | null;
|
||||
}
|
||||
|
||||
export interface XfaSplitStage {
|
||||
stage_id: string;
|
||||
type: XfaSplitStageType;
|
||||
trim?: boolean;
|
||||
remove_empty_lines?: boolean;
|
||||
line_breaks?: string[];
|
||||
line_index?: number | null;
|
||||
line_start?: number | null;
|
||||
line_end?: number | null;
|
||||
join_with?: 'newline' | 'space' | 'comma';
|
||||
value?: string | null;
|
||||
separators?: string[];
|
||||
case_sensitive?: boolean;
|
||||
pattern?: string | null;
|
||||
capture_group?: number | null;
|
||||
find?: string | null;
|
||||
replace_with?: string | null;
|
||||
start?: number | null;
|
||||
end?: number | null;
|
||||
}
|
||||
|
||||
export interface XfaSplitRule {
|
||||
rule_id: string;
|
||||
order: number;
|
||||
segment: XfaSplitSegment;
|
||||
stages: XfaSplitStage[];
|
||||
}
|
||||
|
||||
export interface XfaSplitNormalization {
|
||||
trim?: boolean;
|
||||
remove_empty_lines?: boolean;
|
||||
line_breaks?: string[];
|
||||
}
|
||||
|
||||
export interface XfaSplitRuleSet {
|
||||
rule_id: string;
|
||||
rule_version: number;
|
||||
source_path_id: string;
|
||||
source_field_code: string;
|
||||
/** 服务端从当前 XFA 分析重写的受控源路径,供正式提取使用。 */
|
||||
source_data_path?: string | null;
|
||||
strategy: 'pipeline';
|
||||
normalization?: XfaSplitNormalization;
|
||||
rules: XfaSplitRule[];
|
||||
unmatched_line_policy?: 'evidence_only' | 'needs_review';
|
||||
duplicate_match_policy?: 'needs_review';
|
||||
same_field_multiple_segment_policy?: 'needs_review';
|
||||
source?: XfaSplitRuleSource;
|
||||
status?: XfaSplitRuleStatus;
|
||||
requires_confirmation?: boolean;
|
||||
}
|
||||
|
||||
export interface XfaSplitSegmentPreview {
|
||||
segment_id: string;
|
||||
segment_code: string;
|
||||
display_name: string;
|
||||
line_no?: number | null;
|
||||
line_end_no?: number | null;
|
||||
raw_text: string;
|
||||
normalized_text: string;
|
||||
handling: XfaSplitHandling;
|
||||
target_field_id?: string | null;
|
||||
target_field_code?: string | null;
|
||||
rule_id: string;
|
||||
status: string;
|
||||
matcher_type: string;
|
||||
}
|
||||
|
||||
export interface XfaSplitPreviewResult {
|
||||
status: string;
|
||||
rule_id?: string | null;
|
||||
rule_version?: number | null;
|
||||
full_values_revealed?: boolean;
|
||||
mapped_fields: Record<string, string>;
|
||||
segments: XfaSplitSegmentPreview[];
|
||||
evidence_only_segments: Array<Pick<
|
||||
XfaSplitSegmentPreview,
|
||||
'segment_id' | 'segment_code' | 'display_name' | 'line_no' | 'line_end_no' | 'raw_text' | 'normalized_text' | 'status' | 'matcher_type' | 'rule_id'
|
||||
>>;
|
||||
diagnostics: Array<{ code: string; message: string; line_no?: number | null; field_code?: string | null; rule_ids?: string[] }>;
|
||||
}
|
||||
|
||||
export interface XfaSplitRulesPreviewResponse {
|
||||
document_id: number;
|
||||
path_id: string;
|
||||
preview: XfaSplitPreviewResult;
|
||||
rule_checksum?: string;
|
||||
sample_checksum?: string;
|
||||
preview_token?: string;
|
||||
}
|
||||
|
||||
export interface XfaSplitRulesValidateResponse {
|
||||
valid: boolean;
|
||||
split_rules: XfaSplitRuleSet[];
|
||||
issues: Array<{ code: string; message: string }>;
|
||||
}
|
||||
|
||||
export type OrderProfileDefinition = OrderCoordinateProfileDefinition | OrderXfaDatasetProfileDefinition;
|
||||
|
||||
/**
|
||||
* 判断 definition 是否为 xfa_dataset 鉴别分支。
|
||||
* @param definition Profile definition 联合类型
|
||||
*/
|
||||
export function isXfaDatasetProfileDefinition(
|
||||
definition: OrderProfileDefinition | null | undefined,
|
||||
): definition is OrderXfaDatasetProfileDefinition {
|
||||
return !!definition && (definition as OrderXfaDatasetProfileDefinition).template_mode === 'xfa_dataset';
|
||||
}
|
||||
|
||||
/**
|
||||
* 将 definition 收窄为 coordinate 分支;XFA 模式不得进入坐标画布逻辑。
|
||||
* @param definition Profile definition 联合类型
|
||||
*/
|
||||
export function asCoordinateProfileDefinition(
|
||||
definition: OrderProfileDefinition,
|
||||
): OrderCoordinateProfileDefinition {
|
||||
if (isXfaDatasetProfileDefinition(definition)) {
|
||||
throw new Error('XFA dataset definition cannot be projected as coordinate regions');
|
||||
}
|
||||
return definition;
|
||||
}
|
||||
|
||||
export interface XfaFieldEvidenceRef {
|
||||
source: 'xfa_dataset';
|
||||
document_id: number;
|
||||
packet_checksum: string;
|
||||
data_path_hash: string;
|
||||
mapping_id: string;
|
||||
raw_value_snapshot_ref?: string | null;
|
||||
normalized_value?: string | null;
|
||||
normalizer_key?: string | null;
|
||||
cross_check_status: XfaCrossCheckStatus;
|
||||
}
|
||||
|
||||
export interface ShippingOrderDocumentProfile {
|
||||
id: number;
|
||||
@@ -48,23 +284,14 @@ export interface ShippingOrderDocumentProfile {
|
||||
schema_version_id: number;
|
||||
schema_version?: number | null;
|
||||
schema_checksum?: string | null;
|
||||
definition: {
|
||||
contract_version: 'order_coordinate_profile.v2';
|
||||
document_match: OrderProfileDocumentMatch;
|
||||
table_regions: OrderProfileTableRegion[];
|
||||
order_field_layouts?: OrderProfileOrderFieldLayout[];
|
||||
draft_unbound_order_field_layouts?: OrderProfileDraftUnboundOrderFieldLayout[];
|
||||
/** 阶段 3 前允许旧页面只读显示历史 v1 版本;新写入不会产生这些字段。 */
|
||||
row_structure?: 'preserved' | 'unsupported_row_structure';
|
||||
drop_zero_qty?: boolean;
|
||||
};
|
||||
definition: OrderProfileDefinition;
|
||||
checksum?: string | null;
|
||||
lock_version: number;
|
||||
change_note?: string | null;
|
||||
source_profile_id?: number | null;
|
||||
published_at?: string | null;
|
||||
retired_at?: string | null;
|
||||
template_mode?: string;
|
||||
template_mode?: OrderProfileTemplateMode;
|
||||
training_sample_count?: number;
|
||||
match_strategy_summary?: Record<string, number | null>;
|
||||
schema_compatibility?: {
|
||||
@@ -100,12 +327,33 @@ export interface ShippingOrderDocumentProfile {
|
||||
checksum?: string | null;
|
||||
};
|
||||
definition_stats?: {
|
||||
template_mode?: OrderProfileTemplateMode;
|
||||
table_region_count: number;
|
||||
header_layout_count: number;
|
||||
line_layout_count: number;
|
||||
order_field_layout_count: number;
|
||||
draft_unbound_order_field_layout_count: number;
|
||||
draft_unbound_order_field_layout_count?: number;
|
||||
header_mapping_count?: number;
|
||||
line_mapping_count?: number;
|
||||
mirror_collection_count?: number;
|
||||
};
|
||||
xfa_structure_identity?: {
|
||||
template_packet_checksum?: string | null;
|
||||
dataset_structure_fingerprint?: string | null;
|
||||
has_authoritative_collection?: boolean;
|
||||
mirror_collection_count?: number;
|
||||
header_mapping_count?: number;
|
||||
line_mapping_count?: number;
|
||||
} | null;
|
||||
xfa_readonly_mapping?: {
|
||||
source_contract?: Record<string, unknown>;
|
||||
header_mappings?: Array<Record<string, unknown>>;
|
||||
line_mappings?: Array<Record<string, unknown>>;
|
||||
cross_checks?: Record<string, unknown>;
|
||||
frozen_samples?: Array<Record<string, unknown>>;
|
||||
matching_signature_checksum?: string | null;
|
||||
pdf_preview_enabled?: boolean;
|
||||
} | null;
|
||||
sample_summary?: {
|
||||
annotation_count: number;
|
||||
training_count: number;
|
||||
@@ -131,6 +379,11 @@ export interface ShippingOrderDocumentProfile {
|
||||
status: 'draft' | 'published' | 'retired';
|
||||
checksum?: string | null;
|
||||
} | null;
|
||||
/** XFA 草稿保存后服务端返回的映射缺口摘要;不阻断草稿保存。 */
|
||||
mapping_issues?: {
|
||||
missing_required_fields: Array<{ scope: string; field_code: string; field_id: string }>;
|
||||
blocking_for_publish?: boolean;
|
||||
} | null;
|
||||
}
|
||||
|
||||
/** 不可变草稿快照;修改 Profile 时只追加新修订,禁止覆盖历史定义。 */
|
||||
@@ -172,6 +425,52 @@ export interface OrderProfileValidationRun {
|
||||
operation_id: string;
|
||||
created_at: string;
|
||||
completed_at: string | null;
|
||||
signature_checksum?: string | null;
|
||||
signature_version?: string | null;
|
||||
matcher_policy_version?: string | null;
|
||||
conflict_profile_count?: number;
|
||||
}
|
||||
|
||||
export interface OrderProfileLayoutSignatureStatus {
|
||||
status: 'missing' | 'valid' | 'stale';
|
||||
signature_kind?: string | null;
|
||||
run_id?: number | null;
|
||||
signature_checksum?: string | null;
|
||||
signature_version?: string | null;
|
||||
source_sample_count?: number | null;
|
||||
tables_with_header_tokens?: number | null;
|
||||
header_token_coverage?: number | null;
|
||||
dataset_structure_fingerprint?: string | null;
|
||||
template_packet_checksum?: string | null;
|
||||
matcher_policy_version?: string | null;
|
||||
provider_versions?: Array<Record<string, unknown>> | null;
|
||||
}
|
||||
|
||||
export interface OrderProfileOverlapConflictProfile {
|
||||
profile_code: string;
|
||||
version: number;
|
||||
reason_codes: string[];
|
||||
suggestion: string;
|
||||
}
|
||||
|
||||
export interface OrderProfileOverlapSummary {
|
||||
run_id?: number;
|
||||
status?: string;
|
||||
definition_checksum?: string;
|
||||
matcher_policy_version?: string | null;
|
||||
self_unique_hit_rate_training?: number | null;
|
||||
self_unique_hit_rate_blind?: number | null;
|
||||
false_hit_other_count?: number | null;
|
||||
reverse_false_hit_count?: number | null;
|
||||
reverse_ambiguous_count?: number | null;
|
||||
reverse_skipped_profile_count?: number | null;
|
||||
ambiguous_count?: number | null;
|
||||
min_evidence_coverage?: number | null;
|
||||
min_margin?: number | null;
|
||||
parse_validation_failed_count?: number | null;
|
||||
sample_role_pollution?: boolean | null;
|
||||
thresholds?: { evidence_coverage_minimum?: number | null; minimum_margin?: number | null } | null;
|
||||
conflict_profiles?: OrderProfileOverlapConflictProfile[];
|
||||
}
|
||||
|
||||
/** 发布检查冻结草稿、验证运行与锁版本;只能被一次原子发布消费。 */
|
||||
@@ -183,6 +482,10 @@ export interface OrderProfilePublishCheckReport {
|
||||
definition_checksum: string;
|
||||
lock_version: number;
|
||||
validation_run_id: number | null;
|
||||
matching_signature_run_id?: number | null;
|
||||
matching_signature_checksum?: string | null;
|
||||
overlap_validation_run_id?: number | null;
|
||||
matcher_policy_version?: string | null;
|
||||
semantic_diff?: Record<string, unknown>;
|
||||
status: OrderProfilePublishCheckStatus;
|
||||
blocking_items: Array<Record<string, unknown>>;
|
||||
@@ -190,6 +493,13 @@ 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;
|
||||
template_mode?: 'coordinate' | 'xfa_dataset' | null;
|
||||
overlap_summary?: OrderProfileOverlapSummary | null;
|
||||
conflict_profiles?: OrderProfileOverlapConflictProfile[];
|
||||
}
|
||||
|
||||
export interface OrderProfileVersionFamilySummary {
|
||||
@@ -225,7 +535,7 @@ export interface OrderProfileVersionSummary {
|
||||
source_profile_id?: number | null;
|
||||
published_at?: string | null;
|
||||
retired_at?: string | null;
|
||||
template_mode?: string;
|
||||
template_mode?: OrderProfileTemplateMode;
|
||||
training_sample_count?: number;
|
||||
match_strategy_summary?: Record<string, number | null>;
|
||||
migration_status?: 'normal' | 'needs_revalidation' | 'blocked';
|
||||
@@ -285,7 +595,11 @@ export interface OrderProfileAuditEvent {
|
||||
id: number;
|
||||
event_type: string;
|
||||
request_id?: string | null;
|
||||
operation_id?: string | null;
|
||||
document_id?: number | null;
|
||||
revision_no?: number | null;
|
||||
definition_checksum?: string | null;
|
||||
before_definition_checksum?: string | null;
|
||||
actor: {
|
||||
id?: number | null;
|
||||
username?: string | null;
|
||||
@@ -413,9 +727,19 @@ export interface OrderProfileBlindTestAvailableSample {
|
||||
row_count: number;
|
||||
column_count: number;
|
||||
header_preview: string[];
|
||||
review_mode: 'preparing' | 'diagnostic' | 'formal_review';
|
||||
confirmable: boolean;
|
||||
layout_version_id: number | null;
|
||||
layout_payload_checksum: string | null;
|
||||
layout_parser_key: string | null;
|
||||
layout_parser_version: string | null;
|
||||
layout_issue_codes: string[];
|
||||
}
|
||||
export interface OrderProfileBlindTestCandidate {
|
||||
document_id: number; table_id: string; rows: Array<Record<string, unknown>>;
|
||||
review_mode: 'diagnostic' | 'formal_review'; confirmable: boolean;
|
||||
layout_version_id: number | null; layout_payload_checksum: string | null;
|
||||
layout_parser_key: string | null; layout_parser_version: string | null;
|
||||
order_fields: Array<{ field_id: string; field_code: string; scope: 'header'; value: unknown; status: 'confirmed' | 'needs_review' | 'unavailable'; page_no: number | null; issues: string[] }>;
|
||||
}
|
||||
|
||||
@@ -455,6 +779,8 @@ export interface OrderProfileSampleDocument {
|
||||
provider?: string | null;
|
||||
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;
|
||||
@@ -463,6 +789,84 @@ export interface OrderProfileSampleDocument {
|
||||
delete_block_reason?: 'blind_test_referenced' | null;
|
||||
}
|
||||
|
||||
/** XFA 字段树节点(普通 DTO 不含明文 data_path)。 */
|
||||
export interface XfaFieldTreeNode {
|
||||
path_id: string;
|
||||
local_name: string;
|
||||
namespace_uri?: string;
|
||||
data_path_hash: string;
|
||||
depth: number;
|
||||
cardinality: 'one' | 'many';
|
||||
is_leaf: boolean;
|
||||
is_header_candidate?: boolean;
|
||||
is_collection_candidate?: boolean;
|
||||
sample_value_masked?: string;
|
||||
sample_value_display?: string;
|
||||
display_policy?: 'empty' | 'full' | 'partial' | 'restricted';
|
||||
can_reveal?: boolean;
|
||||
line_count?: number;
|
||||
children?: XfaFieldTreeNode[];
|
||||
}
|
||||
|
||||
export interface XfaFieldTreeResponse {
|
||||
analysis_id: number;
|
||||
document_kind?: string | null;
|
||||
dataset_structure_fingerprint?: string | null;
|
||||
tree: XfaFieldTreeNode | Record<string, never>;
|
||||
header_candidates?: Array<Record<string, unknown>>;
|
||||
stats?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export interface XfaCollectionCandidate {
|
||||
collection_path_hash: string;
|
||||
path_id: string;
|
||||
row_count: number;
|
||||
sibling_collection_path_hashes?: string[];
|
||||
local_name?: string;
|
||||
path_label?: string;
|
||||
field_names?: string[];
|
||||
field_count?: number;
|
||||
non_empty_field_count?: number;
|
||||
non_empty_rate?: number;
|
||||
sample_fields?: Array<{
|
||||
field_name: string;
|
||||
display_value: string;
|
||||
display_policy: 'empty' | 'full' | 'partial' | 'restricted';
|
||||
}>;
|
||||
selectable?: boolean;
|
||||
recommended_role?: 'authoritative' | 'mirror' | 'unavailable' | 'candidate';
|
||||
recommendation_reasons?: string[];
|
||||
recommendation_rank?: number | null;
|
||||
exclusion_reasons?: string[];
|
||||
}
|
||||
|
||||
export interface XfaCollectionsResponse {
|
||||
analysis_id: number;
|
||||
document_kind?: string | null;
|
||||
dataset_structure_fingerprint?: string | null;
|
||||
collection_candidates: XfaCollectionCandidate[];
|
||||
excluded_collection_candidates?: XfaCollectionCandidate[];
|
||||
stats?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export interface XfaValuePreviewResponse {
|
||||
analysis_id: number;
|
||||
path_id: string;
|
||||
sample_value_masked: string;
|
||||
display_value: string;
|
||||
display_policy: 'empty' | 'full' | 'partial' | 'restricted';
|
||||
can_reveal: boolean;
|
||||
full_value_revealed: boolean;
|
||||
}
|
||||
|
||||
export interface XfaMappingCoverageSummary {
|
||||
requiredTotal: number;
|
||||
requiredMapped: number;
|
||||
missingRequired: Array<{ scope: 'header' | 'line'; field_code: string; field_id?: string }>;
|
||||
duplicateFieldIds: string[];
|
||||
authoritativeMissing: boolean;
|
||||
}
|
||||
|
||||
export interface OrderProfileSampleTable {
|
||||
table_id: string;
|
||||
page_no: number;
|
||||
@@ -485,6 +889,7 @@ export interface OrderProfileSampleIntake {
|
||||
intake_no: string;
|
||||
parse_status: string;
|
||||
document_count: number;
|
||||
document_ids?: number[];
|
||||
error_code?: string | null;
|
||||
}
|
||||
|
||||
@@ -497,14 +902,6 @@ export interface CreateOrderProfileFromSampleInput {
|
||||
change_note?: string;
|
||||
}
|
||||
|
||||
export interface CoordinateReconstructionSettings {
|
||||
method: 'native_pdf_coordinates.v1' | 'ocr_pdf_coordinates.v1';
|
||||
column_boundaries: number[];
|
||||
column_field_codes?: Array<string | null>;
|
||||
line_start_column_index?: number;
|
||||
subrow_layouts?: CoordinateSubrowLayout[];
|
||||
}
|
||||
|
||||
export interface CoordinateSubrowLayout {
|
||||
role: 'main' | 'continuation';
|
||||
row_offset: number;
|
||||
|
||||
@@ -45,7 +45,12 @@ export const hydrateShippingOrderExtractionState = (message: ChatMessage): ChatM
|
||||
if (!state || typeof state !== 'object') return message;
|
||||
const status = String((state as Record<string, unknown>).status || '');
|
||||
if (!['queued', 'processing', 'completed', 'partially_completed', 'review_required', 'failed', 'cancelled'].includes(status)) return message;
|
||||
message.shipping_order_extraction_state = state as ShippingOrderExtractionState;
|
||||
const normalized = state as ShippingOrderExtractionState;
|
||||
if (normalized.supersedingRunNo) {
|
||||
normalized.isCurrent = false;
|
||||
normalized.readOnlyReason = normalized.readOnlyReason || 'superseded_by_newer_run';
|
||||
}
|
||||
message.shipping_order_extraction_state = normalized;
|
||||
return message;
|
||||
};
|
||||
|
||||
|
||||
@@ -1,38 +1,48 @@
|
||||
/**
|
||||
* features/chat/api/shipping.api.ts
|
||||
* 用途:封装发货通知相关 HTTP API,包括任务/批次查询、人工决策、订单抽取取消/时间线与 Excel 导出。
|
||||
* 用途:封装发货通知相关 HTTP API,包括任务查询、人工决策、订单抽取取消/时间线与 Excel 导出。
|
||||
* 依赖:统一 requestJson / BusinessError、shipping.api.types 类型定义。
|
||||
* 逻辑:上游由 useChatShipping、shipping-task-center 与 shipping/* handler 调用;
|
||||
* 含阶段 4+ `/shipping-processing/*` 统一进度投影;
|
||||
* co8 后已移除 create_batch / Workflow list·cancel·reparse 客户端导出;
|
||||
* 「我的待办」列表/徽标见 features/workspace/api/shipping-tasks.api.ts。
|
||||
*/
|
||||
import { BusinessError, requestJson } from '@/shared/api/client';
|
||||
import { getAuthHeaders } from '@/shared/utils/auth';
|
||||
import { reportShippingDebugEvent } from '../shipping/shippingDebugReporter';
|
||||
import {
|
||||
normalizeShippingProcessingProjection,
|
||||
normalizeShippingProcessingWorkItems,
|
||||
} from '../shipping/normalizeShippingProcessing';
|
||||
import type {
|
||||
ShippingBatchSummary,
|
||||
ShippingBatchUiState,
|
||||
ShippingConversationWorkspace,
|
||||
ShippingDecisionResponse,
|
||||
ShippingOrderExtractionDocumentsResponse,
|
||||
ShippingNoticeHeader,
|
||||
ShippingNoticeLine,
|
||||
ShippingNoticeUploadResponse,
|
||||
ShippingNoticeIntakeResponse,
|
||||
ShippingCreateBatchFromIntakesResponse,
|
||||
ShippingTaskCreateResponse,
|
||||
ShippingTaskDetail,
|
||||
ShippingTaskBatchDispositionResponse,
|
||||
ShippingTaskPage,
|
||||
ShippingTaskSummary,
|
||||
ShippingCustomerOption,
|
||||
ShippingOrderExtractionDocumentResult,
|
||||
ShippingOrderExtractionRun,
|
||||
ShippingOrderExtractionProgressEvent,
|
||||
ShippingOrderExtractionRunCreateResponse,
|
||||
OrderExtractionSubmissionRequest,
|
||||
OrderExtractionSubmissionResponse,
|
||||
ConversationProcessingProjection,
|
||||
ShippingOrderReviewAuditTimelinePage,
|
||||
ShippingTaskAuditTimelinePage,
|
||||
ShippingOrderReviewCase,
|
||||
ShippingOrderReviewCustomerResolution,
|
||||
ShippingOrderReviewDuplicate,
|
||||
ShippingOrderReviewFieldConflict,
|
||||
ShippingOrderReviewLineFulfillment,
|
||||
ShippingOrderReviewLineFulfillmentDecisionCode,
|
||||
ShippingOrderReviewReservation,
|
||||
ShippingOrderReviewResumeOutcome,
|
||||
ShippingDuplicateAction,
|
||||
ShippingOrderReviewDraftWrite,
|
||||
ShippingOrderReviewEvidence,
|
||||
@@ -45,9 +55,6 @@ import type {
|
||||
ShippingOrderReviewLlmSuggestionResponse,
|
||||
ShippingOrderReviewReparseResponse,
|
||||
ShippingOrderReviewRun,
|
||||
ShippingWorkflow,
|
||||
ShippingWorkflowConversationProjection,
|
||||
ShippingWorkflowItem,
|
||||
ShippingTaskUiState,
|
||||
} from '../types/shipping.api.types';
|
||||
|
||||
@@ -112,45 +119,29 @@ export const listWorkspaceShippingTasks = (params?: {
|
||||
return requestJson<ShippingTaskPage>(`/api/workspace/shipping-tasks${qs ? '?' + qs : ''}`);
|
||||
};
|
||||
|
||||
export const listWorkspaceShippingBatches = (params?: { limit?: number }) => {
|
||||
/** 拉取当前用户的发货批次摘要列表。 */
|
||||
const sp = new URLSearchParams();
|
||||
if (params?.limit) sp.set('limit', String(params.limit));
|
||||
const qs = sp.toString();
|
||||
return requestJson<ShippingBatchSummary[]>(`/api/workspace/shipping-batches${qs ? '?' + qs : ''}`);
|
||||
};
|
||||
|
||||
/** 拉取用户可见 Agent 列表,供发货工作台跳转 Chat 时定位目标 Agent。 */
|
||||
export const listShippingChatAgents = () => requestJson<ShippingChatAgentOption[]>('/api/agents');
|
||||
|
||||
/** 获取批次详情、批次任务列表与当前焦点任务。 */
|
||||
export const getWorkspaceShippingBatch = (batchNo: string) =>
|
||||
requestJson<ShippingBatchUiState>(
|
||||
`/api/workspace/shipping-batches/${encodeURIComponent(batchNo)}`,
|
||||
);
|
||||
|
||||
/** 获取批次级 UI State,供工作台、步骤条和任务卡片统一消费。 */
|
||||
export const getWorkspaceShippingBatchUiState = (batchNo: string) =>
|
||||
requestJson<ShippingBatchUiState>(
|
||||
`/api/workspace/shipping-batches/${encodeURIComponent(batchNo)}/ui-state`,
|
||||
);
|
||||
|
||||
/** 获取一个 Agent 会话下的多批次执行工作台快照。 */
|
||||
export const getWorkspaceShippingConversationBatches = (conversationId: string) =>
|
||||
requestJson<ShippingConversationWorkspace>(
|
||||
`/api/workspace/shipping-conversations/${encodeURIComponent(conversationId)}/batch-workspace`,
|
||||
);
|
||||
|
||||
/** 获取指定批次当前焦点任务。 */
|
||||
export const getWorkspaceShippingBatchFocusTask = (batchNo: string) =>
|
||||
requestJson<ShippingTaskSummary>(
|
||||
`/api/workspace/shipping-batches/${encodeURIComponent(batchNo)}/focus-task`,
|
||||
);
|
||||
|
||||
/** 获取单个发货任务详情。 */
|
||||
export const getWorkspaceShippingTask = (taskNo: string) =>
|
||||
requestJson<ShippingTaskDetail>(`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}`);
|
||||
|
||||
/**
|
||||
* 分页拉取任务工作台统一审计时间线(ShippingAuditEvent 单源)。
|
||||
*/
|
||||
export const listWorkspaceShippingTaskAuditTimeline = (
|
||||
taskNo: string,
|
||||
params?: { page?: number; page_size?: number },
|
||||
) => {
|
||||
const sp = new URLSearchParams();
|
||||
if (params?.page) sp.set('page', String(params.page));
|
||||
if (params?.page_size) sp.set('page_size', String(params.page_size));
|
||||
const qs = sp.toString();
|
||||
return requestJson<ShippingTaskAuditTimelinePage>(
|
||||
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/audit-timeline${qs ? `?${qs}` : ''}`,
|
||||
);
|
||||
};
|
||||
|
||||
/** 获取单票任务 UI State,后续 Chat 按钮与顶部步骤条统一读取此状态。 */
|
||||
export const getWorkspaceShippingTaskUiState = (taskNo: string) =>
|
||||
requestJson<ShippingTaskUiState>(`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/ui-state`);
|
||||
@@ -188,6 +179,86 @@ export const createWorkspaceShippingOrderExtractionRun = (payload: {
|
||||
jsonPost(payload),
|
||||
);
|
||||
|
||||
/**
|
||||
* 统一订单抽取提交:后端事务内裁决追加或新建用户可见任务。
|
||||
* 核心逻辑:携带 submission_id 幂等;前端不得本地选择 append/create API。
|
||||
*/
|
||||
export const createWorkspaceOrderExtractionSubmission = (
|
||||
payload: OrderExtractionSubmissionRequest,
|
||||
) => requestJson<OrderExtractionSubmissionResponse>(
|
||||
'/api/workspace/shipping-notice/order-extraction-submissions',
|
||||
jsonPost(payload),
|
||||
);
|
||||
|
||||
/**
|
||||
* 拉取统一 ShippingProcessingProjection(唯一进度读源;含 order_intake / order_task)。
|
||||
* 核心逻辑:内嵌 conversation_processing 可选;缺省时前端由 work_items 合成分组;
|
||||
* 旧 conversation processing GET 已移除(无历史兼容)。
|
||||
*/
|
||||
export const getWorkspaceShippingProcessing = async (
|
||||
conversationId: string,
|
||||
signal?: AbortSignal,
|
||||
) => {
|
||||
const raw = await requestJson<{
|
||||
conversation_id?: string;
|
||||
work_items?: unknown[];
|
||||
conversation_processing?: ConversationProcessingProjection | null;
|
||||
}>(
|
||||
`/api/workspace/shipping-processing/conversations/${encodeURIComponent(conversationId)}`,
|
||||
{ signal },
|
||||
);
|
||||
return {
|
||||
conversation_id: String(raw?.conversation_id || conversationId),
|
||||
work_items: normalizeShippingProcessingWorkItems(raw?.work_items),
|
||||
conversation_processing: raw?.conversation_processing ?? null,
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* 按工作项类型与编号读取统一进度投影详情。
|
||||
*/
|
||||
export const getWorkspaceShippingProcessingWorkItem = async (
|
||||
workItemType: 'order_intake' | 'order_task',
|
||||
workItemNo: string,
|
||||
signal?: AbortSignal,
|
||||
) => {
|
||||
const raw = await requestJson<Record<string, unknown>>(
|
||||
`/api/workspace/shipping-processing/work-items/${encodeURIComponent(workItemType)}/${encodeURIComponent(workItemNo)}`,
|
||||
{ signal },
|
||||
);
|
||||
const normalized = normalizeShippingProcessingProjection(raw);
|
||||
if (!normalized) {
|
||||
throw new BusinessError({
|
||||
message: 'Invalid shipping processing projection',
|
||||
code: 'SHIPPING.PROCESSING_PROJECTION_INVALID',
|
||||
status: 500,
|
||||
});
|
||||
}
|
||||
return normalized;
|
||||
};
|
||||
|
||||
/**
|
||||
* 标记会话用户可见任务为当前焦点(写审计;返回最新 processing)。
|
||||
*/
|
||||
export const focusWorkspaceConversationTask = (
|
||||
taskNo: string,
|
||||
payload?: { conversation_id?: string | null },
|
||||
) => requestJson<{ processing: ConversationProcessingProjection }>(
|
||||
`/api/workspace/shipping-notice/conversation-tasks/${encodeURIComponent(taskNo)}/focus`,
|
||||
jsonPost(payload || {}),
|
||||
);
|
||||
|
||||
/**
|
||||
* 标记用户可见任务详情已查看(viewed,不等于业务已处理)。
|
||||
*/
|
||||
export const markWorkspaceConversationTaskViewed = (
|
||||
taskNo: string,
|
||||
payload?: { conversation_id?: string | null },
|
||||
) => requestJson<{ processing: ConversationProcessingProjection }>(
|
||||
`/api/workspace/shipping-notice/conversation-tasks/${encodeURIComponent(taskNo)}/viewed`,
|
||||
jsonPost(payload || {}),
|
||||
);
|
||||
|
||||
/**
|
||||
* 查询单个订单抽取 Run,供聊天页短轮询。
|
||||
* @param runNo - Run 业务编号。
|
||||
@@ -370,6 +441,7 @@ export const retryWorkspaceShippingOrderReviewCustomerResolution = (caseNo: stri
|
||||
requestJson<{
|
||||
case: ShippingOrderReviewCase;
|
||||
customer_resolution: ShippingOrderReviewCustomerResolution;
|
||||
resume_outcome?: ShippingOrderReviewResumeOutcome;
|
||||
}>(
|
||||
`/api/workspace/shipping-notice/order-review-cases/${encodeURIComponent(caseNo)}/customer-resolution/retry`,
|
||||
{ method: 'POST' },
|
||||
@@ -384,6 +456,7 @@ export const confirmWorkspaceShippingOrderReviewCustomer = (
|
||||
) => requestJson<{
|
||||
case: ShippingOrderReviewCase;
|
||||
customer_resolution: ShippingOrderReviewCustomerResolution;
|
||||
resume_outcome?: ShippingOrderReviewResumeOutcome;
|
||||
}>(
|
||||
`/api/workspace/shipping-notice/order-review-cases/${encodeURIComponent(caseNo)}/customer-resolution/confirm`,
|
||||
{
|
||||
@@ -400,6 +473,7 @@ export const refreshWorkspaceShippingOrderReviewDuplicate = (caseNo: string) =>
|
||||
requestJson<{
|
||||
case: ShippingOrderReviewCase;
|
||||
duplicate: ShippingOrderReviewDuplicate;
|
||||
resume_outcome?: ShippingOrderReviewResumeOutcome;
|
||||
}>(
|
||||
`/api/workspace/shipping-notice/order-review-cases/${encodeURIComponent(caseNo)}/duplicate-refresh`,
|
||||
{ method: 'POST' },
|
||||
@@ -418,6 +492,7 @@ export const resolveWorkspaceShippingOrderReviewDuplicate = (
|
||||
) => requestJson<{
|
||||
case: ShippingOrderReviewCase;
|
||||
duplicate: ShippingOrderReviewDuplicate;
|
||||
resume_outcome?: ShippingOrderReviewResumeOutcome;
|
||||
}>(
|
||||
`/api/workspace/shipping-notice/order-review-cases/${encodeURIComponent(caseNo)}/duplicate-resolution`,
|
||||
{
|
||||
@@ -457,6 +532,7 @@ export const resolveWorkspaceShippingOrderReviewFieldConflict = (
|
||||
) => requestJson<{
|
||||
case: ShippingOrderReviewCase;
|
||||
field_conflicts: ShippingOrderReviewFieldConflict[];
|
||||
resume_outcome?: ShippingOrderReviewResumeOutcome;
|
||||
}>(
|
||||
`/api/workspace/shipping-notice/order-review-cases/${encodeURIComponent(caseNo)}/field-conflicts/${encodeURIComponent(conflictKey)}/resolve`,
|
||||
{
|
||||
@@ -606,6 +682,107 @@ export const adjudicateWorkspaceShippingOrderReviewLlmSuggestion = (
|
||||
jsonPost(body),
|
||||
);
|
||||
|
||||
/**
|
||||
* 显式重校验 Reservation 并触发统一恢复协调。
|
||||
* 核心逻辑:validate_draft + resume;返回 case 与 resume_outcome。
|
||||
*/
|
||||
export const revalidateWorkspaceShippingOrderReviewReservation = (
|
||||
caseNo: string,
|
||||
payload: { expected_draft_version: number },
|
||||
) => requestJson<{
|
||||
case: ShippingOrderReviewCase;
|
||||
reservation?: ShippingOrderReviewReservation;
|
||||
resume_outcome?: ShippingOrderReviewResumeOutcome;
|
||||
}>(
|
||||
`/api/workspace/shipping-notice/order-review-cases/${encodeURIComponent(caseNo)}/reservation/revalidate`,
|
||||
jsonPost(payload),
|
||||
);
|
||||
|
||||
/**
|
||||
* 分页拉取复核 Case 业务审计时间线(打开抽屉时按需加载)。
|
||||
*/
|
||||
export const listWorkspaceShippingOrderReviewAuditTimeline = (
|
||||
caseNo: string,
|
||||
params?: { page?: number; page_size?: number },
|
||||
) => {
|
||||
const sp = new URLSearchParams();
|
||||
if (params?.page) sp.set('page', String(params.page));
|
||||
if (params?.page_size) sp.set('page_size', String(params.page_size));
|
||||
const qs = sp.toString();
|
||||
return requestJson<ShippingOrderReviewAuditTimelinePage>(
|
||||
`/api/workspace/shipping-notice/order-review-cases/${encodeURIComponent(caseNo)}/audit-timeline${qs ? `?${qs}` : ''}`,
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* 写入一行履约决定(等待补货 / 完整行先行 / 关闭等)。
|
||||
*/
|
||||
export const decideWorkspaceShippingOrderReviewLineFulfillment = (
|
||||
caseNo: string,
|
||||
payload: {
|
||||
line_key: string;
|
||||
decision_code: ShippingOrderReviewLineFulfillmentDecisionCode | string;
|
||||
reason?: string;
|
||||
expected_draft_version?: number;
|
||||
},
|
||||
) => requestJson<{
|
||||
case: ShippingOrderReviewCase;
|
||||
decision?: Record<string, unknown>;
|
||||
line_fulfillment?: ShippingOrderReviewLineFulfillment;
|
||||
resume_outcome?: ShippingOrderReviewResumeOutcome;
|
||||
}>(
|
||||
`/api/workspace/shipping-notice/order-review-cases/${encodeURIComponent(caseNo)}/line-fulfillment/decide`,
|
||||
jsonPost(payload),
|
||||
);
|
||||
|
||||
/**
|
||||
* 为选中完整明细行创建履约波次 Task。
|
||||
*/
|
||||
export const waveWorkspaceShippingOrderReviewLineFulfillment = (
|
||||
caseNo: string,
|
||||
payload: {
|
||||
line_keys: string[];
|
||||
expected_draft_version: number;
|
||||
idempotency_key: string;
|
||||
reason?: string;
|
||||
},
|
||||
) => requestJson<{
|
||||
case: ShippingOrderReviewCase;
|
||||
line_fulfillment?: ShippingOrderReviewLineFulfillment;
|
||||
resume_outcome?: ShippingOrderReviewResumeOutcome;
|
||||
task_no?: string | null;
|
||||
wave_no?: number | null;
|
||||
}>(
|
||||
`/api/workspace/shipping-notice/order-review-cases/${encodeURIComponent(caseNo)}/line-fulfillment/wave`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Idempotency-Key': payload.idempotency_key,
|
||||
},
|
||||
body: JSON.stringify(payload),
|
||||
},
|
||||
);
|
||||
|
||||
/**
|
||||
* 关闭指定行或 Case 剩余开放行。
|
||||
*/
|
||||
export const closeWorkspaceShippingOrderReviewLineFulfillment = (
|
||||
caseNo: string,
|
||||
payload: {
|
||||
reason: string;
|
||||
line_keys?: string[];
|
||||
expected_draft_version?: number;
|
||||
},
|
||||
) => requestJson<{
|
||||
case: ShippingOrderReviewCase;
|
||||
line_fulfillment?: ShippingOrderReviewLineFulfillment;
|
||||
resume_outcome?: ShippingOrderReviewResumeOutcome;
|
||||
}>(
|
||||
`/api/workspace/shipping-notice/order-review-cases/${encodeURIComponent(caseNo)}/line-fulfillment/close`,
|
||||
jsonPost(payload),
|
||||
);
|
||||
|
||||
/** 打开版本历史抽屉时写入服务端访问审计(失败不阻断 UI)。 */
|
||||
export const auditWorkspaceShippingOrderReviewVersionHistory = (caseNo: string) =>
|
||||
requestJson<{ audited: boolean; case_no: string }>(
|
||||
@@ -645,92 +822,6 @@ export const markWorkspaceShippingOrderExtractionRunSeen = (runNo: string) =>
|
||||
jsonPost(),
|
||||
);
|
||||
|
||||
/**
|
||||
* 列出会话开放 Workflow 与 Items(版面阶段 Item 已存在)。
|
||||
* @param conversationId - 聊天会话 ID
|
||||
* @param options.signal - 可选中止信号(轮询超时)
|
||||
*/
|
||||
export const listWorkspaceShippingWorkflows = (
|
||||
conversationId: string,
|
||||
options?: { signal?: AbortSignal },
|
||||
) => {
|
||||
const params = new URLSearchParams({ conversation_id: conversationId });
|
||||
return requestJson<ShippingWorkflowConversationProjection>(
|
||||
`/api/workspace/shipping-notice/workflows?${params.toString()}`,
|
||||
{ signal: options?.signal },
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* 读取单个 Workflow 详情(含 Items 摘要)。
|
||||
* @param workflowNo - Workflow 业务编号
|
||||
*/
|
||||
export const getWorkspaceShippingWorkflow = (
|
||||
workflowNo: string,
|
||||
options?: { signal?: AbortSignal },
|
||||
) =>
|
||||
requestJson<ShippingWorkflow>(
|
||||
`/api/workspace/shipping-notice/workflows/${encodeURIComponent(workflowNo)}`,
|
||||
{ signal: options?.signal },
|
||||
);
|
||||
|
||||
/**
|
||||
* 读取单个 WorkflowItem 详情(默认含 events)。
|
||||
* @param itemNo - Item 业务编号
|
||||
* @param options.include_events - 是否附带事件时间线;默认 true
|
||||
* @param options.signal - 可选中止信号
|
||||
*/
|
||||
export const getWorkspaceShippingWorkflowItem = (
|
||||
itemNo: string,
|
||||
options?: { signal?: AbortSignal; include_events?: boolean },
|
||||
) => {
|
||||
const params = new URLSearchParams();
|
||||
if (options?.include_events === false) {
|
||||
params.set('include_events', 'false');
|
||||
} else if (options?.include_events === true) {
|
||||
params.set('include_events', 'true');
|
||||
}
|
||||
const query = params.toString();
|
||||
return requestJson<ShippingWorkflowItem>(
|
||||
`/api/workspace/shipping-notice/workflow-items/${encodeURIComponent(itemNo)}${query ? `?${query}` : ''}`,
|
||||
{ signal: options?.signal },
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* 取消单个 WorkflowItem;须填写 reason,可选乐观锁。
|
||||
* @param itemNo - Item 业务编号
|
||||
* @param payload.reason - 取消原因(必填)
|
||||
* @param payload.expected_lock_version - 可选乐观锁版本
|
||||
*/
|
||||
export const cancelWorkspaceShippingWorkflowItem = (
|
||||
itemNo: string,
|
||||
payload: { reason: string; expected_lock_version?: number | null },
|
||||
) =>
|
||||
requestJson<{ item: ShippingWorkflowItem }>(
|
||||
`/api/workspace/shipping-notice/workflow-items/${encodeURIComponent(itemNo)}/cancel`,
|
||||
jsonPost(payload),
|
||||
);
|
||||
|
||||
/**
|
||||
* 对单个 WorkflowItem 发起重试/重新识别。
|
||||
* 核心逻辑:POST reparse;后端可能并行补齐,客户端契约先行对齐。
|
||||
* @param itemNo - Item 业务编号
|
||||
* @param payload.reason - 重识别原因(必填)
|
||||
* @param payload.comment - 可选补充说明
|
||||
*/
|
||||
export const reparseWorkspaceShippingWorkflowItem = (
|
||||
itemNo: string,
|
||||
payload: { reason: string; comment?: string | null },
|
||||
) =>
|
||||
requestJson<{ item: ShippingWorkflowItem; reused?: boolean }>(
|
||||
`/api/workspace/shipping-notice/workflow-items/${encodeURIComponent(itemNo)}/reparse`,
|
||||
jsonPost({
|
||||
reason: payload.reason,
|
||||
comment: payload.comment ?? undefined,
|
||||
}),
|
||||
);
|
||||
|
||||
/** 按会话恢复订单抽取 Run,刷新页面后不依赖聊天 SSE 历史。 */
|
||||
export const listWorkspaceShippingOrderExtractionRuns = (
|
||||
conversationId?: string | null,
|
||||
@@ -865,56 +956,6 @@ export async function replaceWorkspaceShippingTaskNotice(taskNo: string, file: F
|
||||
return assertShippingOk(body);
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量上传多份发货通知并创建批次。
|
||||
* @param files - 发货通知附件列表
|
||||
* @param conversationId - 可选会话 ID
|
||||
* @returns 批次与任务创建结果
|
||||
*/
|
||||
export async function createWorkspaceShippingBatchFromNotices(
|
||||
files: File[],
|
||||
conversationId?: string,
|
||||
idempotencyKey?: string,
|
||||
) {
|
||||
const form = new FormData();
|
||||
files.forEach((file) => form.append('files', file));
|
||||
if (conversationId) form.append('conversation_id', conversationId);
|
||||
if (idempotencyKey) form.append('idempotency_key', idempotencyKey);
|
||||
const headers: Record<string, string> = {};
|
||||
if (idempotencyKey) {
|
||||
headers['Idempotency-Key'] = idempotencyKey;
|
||||
}
|
||||
const body = await requestJson<ShippingNoticeUploadResponse & ShippingApiStatusPayload & {
|
||||
error?: string;
|
||||
batch_no?: string;
|
||||
idempotent_replay?: boolean;
|
||||
file_summary?: unknown;
|
||||
data?: unknown;
|
||||
}>('/api/workspace/shipping-batches/create-from-notices', {
|
||||
method: 'POST',
|
||||
body: form,
|
||||
headers,
|
||||
});
|
||||
return assertShippingOk(body);
|
||||
}
|
||||
|
||||
/**
|
||||
* 切换批次当前焦点任务。
|
||||
* @param batchNo - 批次编号
|
||||
* @param taskNo - 目标任务编号
|
||||
* @returns 更新后的批次摘要与焦点任务
|
||||
*/
|
||||
export async function switchWorkspaceShippingBatchFocusTask(batchNo: string, taskNo: string) {
|
||||
const body = await requestJson<ShippingApiStatusPayload & {
|
||||
batch?: ShippingBatchSummary;
|
||||
focus_task?: ShippingTaskSummary;
|
||||
}>(
|
||||
`/api/workspace/shipping-batches/${encodeURIComponent(batchNo)}/focus-task`,
|
||||
jsonPost({ task_no: taskNo }),
|
||||
);
|
||||
return assertShippingOk(body);
|
||||
}
|
||||
|
||||
/**
|
||||
* 重试当前发货任务。
|
||||
* @param taskNo - 发货任务编号
|
||||
@@ -929,19 +970,6 @@ export async function retryWorkspaceShippingTask(taskNo: string, comment?: strin
|
||||
return assertShippingOk(body);
|
||||
}
|
||||
|
||||
/**
|
||||
* 重试批次中仍可自动推进的任务。
|
||||
* @param batchNo - 批次编号
|
||||
* @returns 批次重试结果
|
||||
*/
|
||||
export async function retryWorkspaceShippingBatchPending(batchNo: string) {
|
||||
const body = await requestJson<ShippingApiStatusPayload>(
|
||||
`/api/workspace/shipping-batches/${encodeURIComponent(batchNo)}/retry-pending`,
|
||||
jsonPost(),
|
||||
);
|
||||
return assertShippingOk(body);
|
||||
}
|
||||
|
||||
/**
|
||||
* 提交人工决策。
|
||||
* @param taskNo - 发货任务编号
|
||||
@@ -1349,29 +1377,7 @@ export const resolveShippingNoticeCandidateDuplicate = (
|
||||
},
|
||||
);
|
||||
|
||||
export const createWorkspaceShippingBatchFromIntakes = (
|
||||
intakeNos: string[],
|
||||
conversationId?: string | null,
|
||||
idempotencyKey?: string,
|
||||
candidateNos?: string[],
|
||||
) =>
|
||||
requestJson<ShippingCreateBatchFromIntakesResponse>('/api/workspace/shipping-batches/create-from-intakes', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...(idempotencyKey ? { 'Idempotency-Key': idempotencyKey } : {}),
|
||||
},
|
||||
body: JSON.stringify({
|
||||
intake_nos: intakeNos,
|
||||
conversation_id: conversationId || undefined,
|
||||
idempotency_key: idempotencyKey,
|
||||
candidate_nos: candidateNos,
|
||||
}),
|
||||
});
|
||||
|
||||
export type {
|
||||
ShippingBatchSummary,
|
||||
ShippingBatchUiState,
|
||||
ShippingChatAction,
|
||||
ShippingConversationBatch,
|
||||
ShippingConversationWorkspace,
|
||||
@@ -1383,7 +1389,6 @@ export type {
|
||||
ShippingNoticeLine,
|
||||
ShippingNoticeUploadResponse,
|
||||
ShippingNoticeIntakeResponse,
|
||||
ShippingCreateBatchFromIntakesResponse,
|
||||
ShippingTaskCreateResponse,
|
||||
ShippingTaskDetail,
|
||||
ShippingTaskBatchDispositionResponse,
|
||||
|
||||
@@ -77,6 +77,35 @@ const getMessageKey = (msg: ChatMessage, index: number) => (
|
||||
|| `${msg.role}:${msg.run_id || 'none'}:${String(msg.content || '').slice(0, 40)}:${index}`
|
||||
);
|
||||
|
||||
/** 同一 Run 只展示最后一张状态卡,避免历史恢复/SSE 补帧造成重复窗口。 */
|
||||
const isDuplicateShippingExtractionMessage = (items: ChatMessage[], index: number): boolean => {
|
||||
const current = items[index];
|
||||
if (!current?.shipping_order_extraction_state) return false;
|
||||
const payload = current.payload && typeof current.payload === 'object'
|
||||
? current.payload as Record<string, unknown>
|
||||
: {};
|
||||
const identity = String(
|
||||
payload.order_extraction_run_no
|
||||
|| payload.formId
|
||||
|| current.shipping_order_extraction_state.runNo
|
||||
|| '',
|
||||
).trim();
|
||||
if (!identity) return false;
|
||||
return items.slice(index + 1).some((candidate) => {
|
||||
if (!candidate?.shipping_order_extraction_state) return false;
|
||||
const candidatePayload = candidate.payload && typeof candidate.payload === 'object'
|
||||
? candidate.payload as Record<string, unknown>
|
||||
: {};
|
||||
const candidateIdentity = String(
|
||||
candidatePayload.order_extraction_run_no
|
||||
|| candidatePayload.formId
|
||||
|| candidate.shipping_order_extraction_state.runNo
|
||||
|| '',
|
||||
).trim();
|
||||
return candidateIdentity === identity;
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* 标记“当前消息后面是否还存在新的 assistant 消息”。
|
||||
* 核心逻辑:培训题卡属于“最新一张 assistant 题卡”才能继续交互;
|
||||
@@ -111,7 +140,7 @@ const isLatestAssistantMessage = (items: ChatMessage[], index: number) => {
|
||||
|
||||
<template v-for="(msg, index) in messages" :key="getMessageKey(msg, index)">
|
||||
<ChatMessageBubble
|
||||
v-if="shouldRenderMessage(msg)"
|
||||
v-if="shouldRenderMessage(msg) && !isDuplicateShippingExtractionMessage(messages, index)"
|
||||
:message="msg"
|
||||
:index="index"
|
||||
:message-count="messages.length"
|
||||
|
||||
@@ -84,11 +84,11 @@ type MaintenanceRecordPanelCommand = {
|
||||
|
||||
const page = useChatPageContext();
|
||||
|
||||
const shippingWorkflow = useShippingNoticeWorkflow({
|
||||
const shippingProcessing = useShippingNoticeWorkflow({
|
||||
conversationId: () => page.conversationId,
|
||||
refreshTrigger: () => page.workflowRefreshTrigger,
|
||||
});
|
||||
provide(SHIPPING_WORKFLOW_KEY, shippingWorkflow);
|
||||
provide(SHIPPING_WORKFLOW_KEY, shippingProcessing);
|
||||
|
||||
|
||||
const route = useRoute();
|
||||
@@ -155,12 +155,7 @@ const activeExtractionRunNo = computed(() => {
|
||||
|
||||
const showShippingWorkflowTimeline = computed(() => (
|
||||
page.isShippingNoticeAgent
|
||||
&& Boolean(
|
||||
page.conversationId
|
||||
|| page.shippingBatchSummary
|
||||
|| page.shippingConversationWorkspace?.batches?.length
|
||||
|| activeExtractionRunNo.value
|
||||
)
|
||||
&& Boolean(page.conversationId || activeExtractionRunNo.value)
|
||||
));
|
||||
|
||||
const embeddedIframeSrc = computed(() => {
|
||||
@@ -673,7 +668,7 @@ watch(() => page.currentAgentId, () => {
|
||||
v-if="showShippingWorkflowTimeline"
|
||||
:conversation-id="page.conversationId"
|
||||
:refresh-trigger="page.workflowRefreshTrigger"
|
||||
:controller="shippingWorkflow"
|
||||
:controller="shippingProcessing"
|
||||
/>
|
||||
|
||||
|
||||
|
||||
@@ -134,6 +134,10 @@ const shippingOrderExtractionRunNo = computed(() => {
|
||||
: {};
|
||||
return String(payload.order_extraction_run_no || '').trim();
|
||||
});
|
||||
const shippingOrderExtractionReadonly = computed(() => (
|
||||
shippingOrderExtractionState.value?.isCurrent === false
|
||||
|| Boolean(shippingOrderExtractionState.value?.supersedingRunNo)
|
||||
));
|
||||
/** 失败卡片复用原 Run 重试;按钮本地防重,成功后状态卡由 Run 轮询原位更新。 */
|
||||
const retryShippingOrderExtraction = async () => {
|
||||
if (!shippingOrderExtractionRunNo.value || retryingOrderExtraction.value) return;
|
||||
@@ -690,6 +694,8 @@ function handleInlineDownload(file: InlineDownloadFile): void {
|
||||
v-if="shippingOrderExtractionState"
|
||||
:state="shippingOrderExtractionState"
|
||||
:run-no="shippingOrderExtractionRunNo"
|
||||
:readonly="shippingOrderExtractionReadonly"
|
||||
:readonly-reason="shippingOrderExtractionState?.readOnlyReason"
|
||||
:retrying="retryingOrderExtraction"
|
||||
:refreshing="refreshingOrderExtraction"
|
||||
:cancelling="cancellingOrderExtraction"
|
||||
|
||||
@@ -0,0 +1,326 @@
|
||||
<!--
|
||||
features/chat/components/shipping-review/ReviewAuditTrailDrawer.vue
|
||||
用途:复核 Case 业务审计时间线按需抽屉(含变更前后快照与字段差异)。
|
||||
依赖:vue-i18n、listWorkspaceShippingOrderReviewAuditTimeline。
|
||||
逻辑:open 时拉取第一页;展开优先展示业务可读差异(字段名/前后值/原因);
|
||||
原始 JSON 折叠为技术详情;敏感事件显示脱敏提示。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { ref, watch } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { BusinessError, resolveLocalizedErrorMessage } from '@/shared/api/client';
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
import { listWorkspaceShippingOrderReviewAuditTimeline } from '@/features/chat/api/shipping.api';
|
||||
import type { ShippingOrderReviewAuditTimelineItem } from '@/features/chat/types/shipping.api.types';
|
||||
|
||||
type AuditDiffRow = {
|
||||
key?: string;
|
||||
path?: string;
|
||||
field?: string;
|
||||
label?: string;
|
||||
change?: string;
|
||||
before?: unknown;
|
||||
after?: unknown;
|
||||
};
|
||||
|
||||
const props = defineProps<{
|
||||
open: boolean;
|
||||
caseNo: string;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
close: [];
|
||||
}>();
|
||||
|
||||
const { t, te } = useI18n();
|
||||
const msg = useMessage();
|
||||
const items = ref<ShippingOrderReviewAuditTimelineItem[]>([]);
|
||||
const loading = ref(false);
|
||||
const page = ref(1);
|
||||
const total = ref(0);
|
||||
const expandedId = ref<number | null>(null);
|
||||
const pageSize = 50;
|
||||
|
||||
/**
|
||||
* 格式化审计时间。
|
||||
*/
|
||||
function formatTime(value: string | null | undefined): string {
|
||||
if (!value) return '—';
|
||||
const date = new Date(value);
|
||||
return Number.isNaN(date.getTime()) ? value : date.toLocaleString();
|
||||
}
|
||||
|
||||
/**
|
||||
* 事件类型本地化。
|
||||
*/
|
||||
function eventLabel(item: ShippingOrderReviewAuditTimelineItem): string {
|
||||
const eventType = String(item.event_type || item.action || '').trim();
|
||||
const key = `chat.shippingOrderReview.auditTrail.events.${eventType}`;
|
||||
if (eventType && te(key)) return t(key);
|
||||
return eventType || t('chat.shippingOrderReview.auditTrail.unknownEvent');
|
||||
}
|
||||
|
||||
/**
|
||||
* 将审计标量格式化为业务可读短文本。
|
||||
*/
|
||||
function formatScalar(value: unknown): string {
|
||||
if (value == null || value === '') return '—';
|
||||
if (typeof value === 'boolean') {
|
||||
return value
|
||||
? t('chat.shippingOrderReview.auditTrail.boolTrue')
|
||||
: t('chat.shippingOrderReview.auditTrail.boolFalse');
|
||||
}
|
||||
if (typeof value === 'object') {
|
||||
try {
|
||||
return JSON.stringify(value);
|
||||
} catch {
|
||||
return String(value);
|
||||
}
|
||||
}
|
||||
return String(value);
|
||||
}
|
||||
|
||||
/**
|
||||
* 快照/差异技术详情(原始 JSON)。
|
||||
*/
|
||||
function formatJson(value: unknown): string {
|
||||
if (value == null) return '—';
|
||||
try {
|
||||
return JSON.stringify(value, null, 2);
|
||||
} catch {
|
||||
return String(value);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 复制技术详情 JSON 到剪贴板。
|
||||
*/
|
||||
async function copyJson(value: unknown) {
|
||||
const text = formatJson(value);
|
||||
try {
|
||||
await navigator.clipboard.writeText(text);
|
||||
msg.success(t('chat.shippingOrderReview.auditTrail.copyDone'));
|
||||
} catch {
|
||||
msg.warning(t('chat.shippingOrderReview.auditTrail.copyFailed'));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 差异字段业务名称(优先 label/field,其次 path)。
|
||||
*/
|
||||
function diffFieldLabel(row: AuditDiffRow): string {
|
||||
const label = String(row.label || row.field || row.key || row.path || '').trim();
|
||||
return label || t('chat.shippingOrderReview.auditTrail.unknownField');
|
||||
}
|
||||
|
||||
/**
|
||||
* 规范化差异列表,供业务表格渲染。
|
||||
*/
|
||||
function normalizeDiffRows(diff: unknown): AuditDiffRow[] {
|
||||
if (!Array.isArray(diff)) return [];
|
||||
return diff.filter((row): row is AuditDiffRow => Boolean(row) && typeof row === 'object');
|
||||
}
|
||||
|
||||
/**
|
||||
* 切换条目展开。
|
||||
*/
|
||||
function toggleExpand(id: number) {
|
||||
expandedId.value = expandedId.value === id ? null : id;
|
||||
}
|
||||
|
||||
/**
|
||||
* 拉取指定页审计条目并合并。
|
||||
*/
|
||||
async function loadPage(nextPage: number, append = false) {
|
||||
if (!props.caseNo || loading.value) return;
|
||||
loading.value = true;
|
||||
try {
|
||||
const result = await listWorkspaceShippingOrderReviewAuditTimeline(props.caseNo, {
|
||||
page: nextPage,
|
||||
page_size: pageSize,
|
||||
});
|
||||
total.value = result.total;
|
||||
page.value = result.page;
|
||||
items.value = append ? [...items.value, ...result.items] : result.items;
|
||||
} catch (error: unknown) {
|
||||
const message = error instanceof BusinessError
|
||||
? resolveLocalizedErrorMessage(error.code, error.message)
|
||||
: (error instanceof Error ? error.message : t('chat.shippingOrderReview.auditTrail.loadFailed'));
|
||||
msg.warning(message);
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 打开抽屉时重置并加载第一页。
|
||||
*/
|
||||
watch(
|
||||
() => [props.open, props.caseNo] as const,
|
||||
([isOpen, caseNo]) => {
|
||||
if (!isOpen || !caseNo) return;
|
||||
items.value = [];
|
||||
page.value = 1;
|
||||
total.value = 0;
|
||||
expandedId.value = null;
|
||||
void loadPage(1, false);
|
||||
},
|
||||
);
|
||||
|
||||
/**
|
||||
* 加载下一页。
|
||||
*/
|
||||
function loadMore() {
|
||||
if (items.value.length >= total.value) return;
|
||||
void loadPage(page.value + 1, true);
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div
|
||||
v-if="open"
|
||||
class="fixed inset-0 z-40 flex justify-end bg-slate-900/30"
|
||||
data-testid="review-audit-trail-drawer"
|
||||
@click.self="emit('close')"
|
||||
>
|
||||
<aside class="flex h-full w-full max-w-xl flex-col bg-white shadow-xl dark:bg-slate-900">
|
||||
<header class="flex items-center justify-between gap-2 border-b border-slate-200 px-4 py-3 dark:border-slate-800">
|
||||
<div>
|
||||
<h2 class="text-sm font-semibold">{{ t('chat.shippingOrderReview.auditTrail.title') }}</h2>
|
||||
<p class="text-[11px] text-muted">{{ t('chat.shippingOrderReview.auditTrail.subtitle') }}</p>
|
||||
</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-audit-trail-close"
|
||||
@click="emit('close')"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.workbench.close') }}
|
||||
</button>
|
||||
</header>
|
||||
<div class="min-h-0 flex-1 overflow-y-auto p-4">
|
||||
<p v-if="loading && !items.length" class="text-sm text-muted">
|
||||
{{ t('chat.shippingOrderReview.auditTrail.loading') }}
|
||||
</p>
|
||||
<p v-else-if="!items.length" class="text-sm text-muted">
|
||||
{{ t('chat.shippingOrderReview.auditTrail.empty') }}
|
||||
</p>
|
||||
<ol v-else class="space-y-3">
|
||||
<li
|
||||
v-for="item in items"
|
||||
:key="item.id"
|
||||
class="rounded-lg border border-slate-200 bg-slate-50 px-3 py-2 text-xs dark:border-slate-800 dark:bg-slate-950/40"
|
||||
:data-testid="`review-audit-item-${item.id}`"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
class="flex w-full flex-wrap items-center justify-between gap-2 text-left"
|
||||
@click="toggleExpand(item.id)"
|
||||
>
|
||||
<span class="font-medium text-primary">{{ eventLabel(item) }}</span>
|
||||
<time class="text-[10px] text-muted">{{ formatTime(item.created_at) }}</time>
|
||||
</button>
|
||||
<div class="mt-1 space-y-0.5 text-muted">
|
||||
<p v-if="item.actor_display || item.actor_type">
|
||||
{{ t('chat.shippingOrderReview.auditTrail.actor', {
|
||||
actor: item.actor_display || item.actor_type || '—',
|
||||
}) }}
|
||||
</p>
|
||||
<p v-if="item.task_no">
|
||||
{{ t('chat.shippingOrderReview.auditTrail.taskNo', { taskNo: item.task_no }) }}
|
||||
</p>
|
||||
<p v-if="item.result">
|
||||
{{ t('chat.shippingOrderReview.auditTrail.result', { result: item.result }) }}
|
||||
</p>
|
||||
<p v-if="item.error_code" class="text-rose-700 dark:text-rose-300">
|
||||
{{ item.error_code }}
|
||||
</p>
|
||||
<p v-if="item.reason" class="text-secondary">{{ item.reason }}</p>
|
||||
</div>
|
||||
<div
|
||||
v-if="expandedId === item.id"
|
||||
class="mt-2 space-y-2 border-t border-slate-200 pt-2 dark:border-slate-800"
|
||||
data-testid="review-audit-item-details"
|
||||
>
|
||||
<p v-if="item.sensitive_redacted" class="text-amber-800 dark:text-amber-200">
|
||||
{{ t('chat.shippingOrderReview.auditTrail.sensitiveRedacted') }}
|
||||
</p>
|
||||
<template v-else>
|
||||
<div v-if="normalizeDiffRows(item.diff).length" data-testid="review-audit-business-diff">
|
||||
<p class="mb-1 font-medium text-secondary">
|
||||
{{ t('chat.shippingOrderReview.auditTrail.diff') }}
|
||||
</p>
|
||||
<ul class="space-y-1.5">
|
||||
<li
|
||||
v-for="(row, idx) in normalizeDiffRows(item.diff)"
|
||||
:key="idx"
|
||||
class="rounded bg-white px-2 py-1.5 text-[11px] dark:bg-slate-900"
|
||||
>
|
||||
<p class="font-medium text-primary">{{ diffFieldLabel(row) }}</p>
|
||||
<p class="mt-0.5 text-muted">
|
||||
{{ t('chat.shippingOrderReview.auditTrail.beforeValue') }}:
|
||||
<span class="text-secondary">{{ formatScalar(row.before) }}</span>
|
||||
</p>
|
||||
<p class="text-muted">
|
||||
{{ t('chat.shippingOrderReview.auditTrail.afterValue') }}:
|
||||
<span class="text-secondary">{{ formatScalar(row.after) }}</span>
|
||||
</p>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
<p v-if="item.reason" class="text-[11px] text-secondary">
|
||||
{{ t('chat.shippingOrderReview.auditTrail.reason') }}:{{ item.reason }}
|
||||
</p>
|
||||
<details class="rounded border border-slate-200 dark:border-slate-800">
|
||||
<summary class="cursor-pointer px-2 py-1 text-[11px] text-muted">
|
||||
{{ t('chat.shippingOrderReview.auditTrail.technicalDetails') }}
|
||||
</summary>
|
||||
<div class="space-y-2 border-t border-slate-200 p-2 dark:border-slate-800">
|
||||
<div class="flex items-center justify-between gap-2">
|
||||
<p class="font-medium text-secondary">
|
||||
{{ t('chat.shippingOrderReview.auditTrail.before') }}
|
||||
</p>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded border border-slate-300 px-1.5 py-0.5 text-[11px] hover:bg-slate-50 dark:border-slate-600 dark:hover:bg-slate-800"
|
||||
data-testid="review-audit-copy-before"
|
||||
@click="copyJson(item.before_snapshot)"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.auditTrail.copyJson') }}
|
||||
</button>
|
||||
</div>
|
||||
<pre class="max-h-32 overflow-auto rounded bg-white p-2 text-xs leading-relaxed dark:bg-slate-900">{{ formatJson(item.before_snapshot) }}</pre>
|
||||
<div class="flex items-center justify-between gap-2">
|
||||
<p class="font-medium text-secondary">
|
||||
{{ t('chat.shippingOrderReview.auditTrail.after') }}
|
||||
</p>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded border border-slate-300 px-1.5 py-0.5 text-[11px] hover:bg-slate-50 dark:border-slate-600 dark:hover:bg-slate-800"
|
||||
data-testid="review-audit-copy-after"
|
||||
@click="copyJson(item.after_snapshot)"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.auditTrail.copyJson') }}
|
||||
</button>
|
||||
</div>
|
||||
<pre class="max-h-32 overflow-auto rounded bg-white p-2 text-xs leading-relaxed dark:bg-slate-900">{{ formatJson(item.after_snapshot) }}</pre>
|
||||
</div>
|
||||
</details>
|
||||
</template>
|
||||
</div>
|
||||
</li>
|
||||
</ol>
|
||||
<button
|
||||
v-if="items.length < total"
|
||||
type="button"
|
||||
class="mt-3 w-full rounded border border-slate-300 px-2 py-1.5 text-xs hover:bg-slate-50 disabled:opacity-50 dark:border-slate-600 dark:hover:bg-slate-800"
|
||||
data-testid="review-audit-trail-load-more"
|
||||
:disabled="loading"
|
||||
@click="loadMore"
|
||||
>
|
||||
{{ loading ? t('chat.shippingOrderReview.auditTrail.loading') : t('chat.shippingOrderReview.auditTrail.loadMore') }}
|
||||
</button>
|
||||
</div>
|
||||
</aside>
|
||||
</div>
|
||||
</template>
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
/**
|
||||
* features/chat/components/shipping-review/ReviewAutomationStatusPanel.spec.ts
|
||||
* 用途:锁定自动处理状态仅在建单后展示,并保持阶段顺序一致。
|
||||
* 依赖:vitest、@vue/test-utils、vue-i18n。
|
||||
* 逻辑:上游未开始时,下游即使后端旧投影为 passed 也按未开始展示。
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { mount } from '@vue/test-utils';
|
||||
import { createI18n } from 'vue-i18n';
|
||||
import ReviewAutomationStatusPanel from './ReviewAutomationStatusPanel.vue';
|
||||
|
||||
const i18n = createI18n({
|
||||
legacy: false,
|
||||
locale: 'zh-CN',
|
||||
messages: {
|
||||
'zh-CN': {
|
||||
chat: {
|
||||
shippingOrderReview: {
|
||||
automationStatus: {
|
||||
title: '自动处理状态',
|
||||
subtitle: '状态',
|
||||
statuses: { not_started: '未开始', passed: '已通过' },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const processGate = {
|
||||
execution_no: 'EX-1',
|
||||
status: 'pending',
|
||||
gates_track: [
|
||||
{ gate_code: 'document', label: '文档解析', status: 'not_started', sequence_no: 1 },
|
||||
{ gate_code: 'reservation', label: '预约校验', status: 'passed', sequence_no: 2 },
|
||||
],
|
||||
};
|
||||
|
||||
describe('ReviewAutomationStatusPanel', () => {
|
||||
it('stays hidden before a ShippingTask is created', () => {
|
||||
const wrapper = mount(ReviewAutomationStatusPanel, {
|
||||
props: { processGate, taskCreated: false },
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
expect(wrapper.find('[data-testid="review-automation-status-panel"]').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it('does not show a downstream stage as passed when its upstream stage has not started', () => {
|
||||
const wrapper = mount(ReviewAutomationStatusPanel, {
|
||||
props: { processGate, taskCreated: true },
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
expect(wrapper.text()).toContain('预约校验');
|
||||
expect(wrapper.text()).not.toContain('已通过');
|
||||
expect(wrapper.text().match(/未开始/g)).toHaveLength(2);
|
||||
});
|
||||
});
|
||||
+107
@@ -0,0 +1,107 @@
|
||||
<!--
|
||||
features/chat/components/shipping-review/ReviewAutomationStatusPanel.vue
|
||||
用途:复核工作台「自动处理状态」只读区(技术 Gate 进度,禁止业务用户点技术重试)。
|
||||
依赖:vue-i18n、ShippingProcessGateUserSummary。
|
||||
逻辑:仅在任务已创建后展示 gates_track;按 sequence_no 排序,并在首个未完成阶段后
|
||||
抑制矛盾的下游“已通过”,不提供技术写操作。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import type { ShippingProcessGateUserSummary } from '@/features/chat/types/shipping.api.types';
|
||||
|
||||
const props = defineProps<{
|
||||
processGate: ShippingProcessGateUserSummary | null | undefined;
|
||||
taskCreated?: boolean;
|
||||
}>();
|
||||
|
||||
const { t, te } = useI18n();
|
||||
|
||||
const track = computed(() => {
|
||||
if (!props.taskCreated) return [];
|
||||
const ordered = [...(props.processGate?.gates_track || [])]
|
||||
.sort((left, right) => Number(left.sequence_no || 0) - Number(right.sequence_no || 0));
|
||||
let upstreamReached = true;
|
||||
return ordered.map((item) => {
|
||||
const status = String(item.status || 'not_started');
|
||||
const normalizedStatus = upstreamReached ? status : 'not_started';
|
||||
if (!['passed', 'skipped'].includes(status)) upstreamReached = false;
|
||||
return { ...item, status: normalizedStatus };
|
||||
});
|
||||
});
|
||||
const visible = computed(() => track.value.length > 0);
|
||||
const technicalOnly = computed(() => Boolean(
|
||||
(props.processGate as { technical_auto_only?: boolean } | null | undefined)?.technical_auto_only,
|
||||
));
|
||||
|
||||
/**
|
||||
* Gate 状态本地化标签。
|
||||
*/
|
||||
function statusLabel(status: string): string {
|
||||
const key = `chat.shippingOrderReview.automationStatus.statuses.${status}`;
|
||||
return te(key) ? t(key) : status;
|
||||
}
|
||||
|
||||
/**
|
||||
* 状态点样式。
|
||||
*/
|
||||
function statusClass(status: string): string {
|
||||
const s = String(status || '');
|
||||
if (s === 'passed' || s === 'skipped') {
|
||||
return 'bg-emerald-500';
|
||||
}
|
||||
if (s === 'running' || s === 'queued') {
|
||||
return 'bg-sky-500 animate-pulse';
|
||||
}
|
||||
if (s === 'blocked_manual' || s === 'blocked_retryable' || s === 'waiting_external') {
|
||||
return 'bg-amber-500';
|
||||
}
|
||||
if (s === 'failed_terminal') {
|
||||
return 'bg-rose-500';
|
||||
}
|
||||
return 'bg-slate-300 dark:bg-slate-600';
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section
|
||||
v-if="visible"
|
||||
class="rounded-xl border border-slate-200 bg-white p-3 shadow-sm dark:border-slate-800 dark:bg-slate-900"
|
||||
data-testid="review-automation-status-panel"
|
||||
>
|
||||
<header class="mb-2">
|
||||
<h2 class="text-sm font-semibold">{{ t('chat.shippingOrderReview.automationStatus.title') }}</h2>
|
||||
<p class="mt-0.5 text-xs text-muted">{{ t('chat.shippingOrderReview.automationStatus.subtitle') }}</p>
|
||||
</header>
|
||||
|
||||
<ol class="space-y-1.5">
|
||||
<li
|
||||
v-for="item in track"
|
||||
:key="String(item.gate_code)"
|
||||
class="flex items-center gap-2 text-[11px] text-secondary"
|
||||
>
|
||||
<span
|
||||
class="inline-block h-2 w-2 shrink-0 rounded-full"
|
||||
:class="statusClass(String(item.status || ''))"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
<span class="min-w-0 flex-1 truncate">{{ item.label || item.gate_code }}</span>
|
||||
<span class="shrink-0 text-muted">{{ statusLabel(String(item.status || '')) }}</span>
|
||||
</li>
|
||||
</ol>
|
||||
|
||||
<p
|
||||
v-if="technicalOnly"
|
||||
class="mt-2 text-[11px] text-muted"
|
||||
data-testid="review-automation-technical-hint"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.automationStatus.technicalHint') }}
|
||||
</p>
|
||||
<p
|
||||
v-else-if="processGate?.blocking_message"
|
||||
class="mt-2 text-[11px] text-amber-900 dark:text-amber-100"
|
||||
>
|
||||
{{ processGate.blocking_message }}
|
||||
</p>
|
||||
</section>
|
||||
</template>
|
||||
+90
@@ -0,0 +1,90 @@
|
||||
/**
|
||||
* features/chat/components/shipping-review/ReviewBuildEligibilityDetailsDrawer.spec.ts
|
||||
* 用途:锁定完整检查必须展示具体冲突字段、行号、来源和值。
|
||||
* 依赖:vitest、@vue/test-utils、vue-i18n。
|
||||
* 逻辑:field_conflict issue 不再输出笼统问题;专用冲突投影负责完整展示。
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { mount } from '@vue/test-utils';
|
||||
import { createI18n } from 'vue-i18n';
|
||||
import ReviewBuildEligibilityDetailsDrawer from './ReviewBuildEligibilityDetailsDrawer.vue';
|
||||
|
||||
const i18n = createI18n({
|
||||
legacy: false,
|
||||
locale: 'zh-CN',
|
||||
messages: {
|
||||
'zh-CN': {
|
||||
chat: { shippingOrderReview: {
|
||||
line: '第 {index} 行',
|
||||
buildEligibility: {
|
||||
overallResult: '整单结果', canBuildYes: '可建单', canBuildNo: '待处理',
|
||||
manualConfirmOnly: '需人工确认', blockReasons: { unknown: '未知阻断' },
|
||||
routingStatus: { unknown: '未知' },
|
||||
},
|
||||
workbench: {
|
||||
fullChecksTitle: '完整订单检查', close: '关闭', issueDetails: '问题明细',
|
||||
conflictFields: '字段冲突明细', conflictDetailsPending: '冲突明细尚未同步,请刷新后查看。',
|
||||
requiredField: '字段', missingValue: '缺少值', noLineChecks: '暂无明细检查',
|
||||
manualReview: { customer: '确认客户', lineInventory: '第 {line} 行库存', noCandidates: '无' },
|
||||
},
|
||||
} },
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const eligibility = {
|
||||
can_build: false,
|
||||
status: 'qualified',
|
||||
issues: [{ code: 'field_conflict', message: '同一字段存在不同来源值冲突' }],
|
||||
line_projections: [],
|
||||
};
|
||||
|
||||
describe('ReviewBuildEligibilityDetailsDrawer', () => {
|
||||
it('lists the exact conflicting field, line, sources and values', () => {
|
||||
const wrapper = mount(ReviewBuildEligibilityDetailsDrawer, {
|
||||
props: {
|
||||
open: true,
|
||||
eligibility,
|
||||
fieldLabels: { unit_price: '单价' },
|
||||
fieldConflicts: [{
|
||||
conflict_key: 'unit_price:0', field_code: 'unit_price', line_index: 0,
|
||||
reason: 'field_conflict',
|
||||
options: [
|
||||
{ value_key: '50.43', display_value: '50.43', sources: ['PDF 表格'] },
|
||||
{ value_key: '51.00', display_value: '51.00', sources: ['邮件正文'] },
|
||||
],
|
||||
}],
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
|
||||
const details = wrapper.find('[data-testid="review-eligibility-conflict-details"]');
|
||||
expect(details.text()).toContain('第 1 行');
|
||||
expect(details.text()).toContain('单价');
|
||||
expect(details.text()).toContain('PDF 表格:50.43');
|
||||
expect(details.text()).toContain('邮件正文:51.00');
|
||||
expect(wrapper.find('[data-testid="review-eligibility-blocking-reasons"]').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it('shows an explicit synchronization warning when conflict detail is absent', () => {
|
||||
const wrapper = mount(ReviewBuildEligibilityDetailsDrawer, {
|
||||
props: { open: true, eligibility, fieldConflicts: [] },
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
expect(wrapper.find('[data-testid="review-eligibility-conflict-details-missing"]').text())
|
||||
.toContain('冲突明细尚未同步');
|
||||
});
|
||||
|
||||
it('filters a stale conflict issue after the current order is buildable', () => {
|
||||
const wrapper = mount(ReviewBuildEligibilityDetailsDrawer, {
|
||||
props: {
|
||||
open: true,
|
||||
eligibility: { ...eligibility, can_build: true },
|
||||
fieldConflicts: [],
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
expect(wrapper.find('[data-testid="review-eligibility-conflict-details-missing"]').exists()).toBe(false);
|
||||
expect(wrapper.text()).not.toContain('同一字段存在不同来源值冲突');
|
||||
});
|
||||
});
|
||||
+172
-3
@@ -2,16 +2,22 @@
|
||||
features/chat/components/shipping-review/ReviewBuildEligibilityDetailsDrawer.vue
|
||||
用途:完整建单检查项抽屉(逐行投影、阻断原因)。
|
||||
依赖:vue-i18n、ShippingOrderReviewBuildEligibility。
|
||||
逻辑:仅在用户主动展开时挂载;关闭不写服务端审计(敏感访问审计由阶段 5 统一补齐)。
|
||||
逻辑:仅在用户主动展开时挂载;字段冲突必须展开 Case.field_conflicts 的字段、行号、
|
||||
来源和值,资格 issue 只作为汇总,不得用笼统文案替代冲突明细。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import type { ShippingOrderReviewBuildEligibility } from '@/features/chat/types/shipping.api.types';
|
||||
import type { ShippingOrderReviewFieldConflict } from '@/features/chat/types/shipping.api.types';
|
||||
|
||||
const props = defineProps<{
|
||||
open: boolean;
|
||||
eligibility: ShippingOrderReviewBuildEligibility | null;
|
||||
fieldConflicts?: ShippingOrderReviewFieldConflict[] | null;
|
||||
fieldLabels?: Record<string, string>;
|
||||
/** 客户面板的权威确认事实;已确认时不得重放历史 customer_* issue。 */
|
||||
customerResolved?: boolean;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
@@ -41,6 +47,42 @@ function routingStatusLabel(status?: string | null): string {
|
||||
return te(key) ? t(key) : t('chat.shippingOrderReview.buildEligibility.routingStatus.unknown');
|
||||
}
|
||||
|
||||
function issueLabel(issue: Record<string, unknown>): string {
|
||||
const field = String(issue.field_code || issue.field_id || '').trim();
|
||||
const code = String(issue.code || '').trim();
|
||||
if (field) {
|
||||
const label = props.fieldLabels?.[field] || field;
|
||||
return `${t('chat.shippingOrderReview.workbench.requiredField')}: ${label}`;
|
||||
}
|
||||
const lineIndex = Number.isFinite(Number(issue.line_index)) ? Number(issue.line_index) : null;
|
||||
const candidates = Array.isArray(issue.candidate_inventory_source_codes)
|
||||
? issue.candidate_inventory_source_codes.map((item) => {
|
||||
const sourceCode = String(item || '').trim();
|
||||
return props.eligibility?.inventory_source_labels?.[sourceCode] || sourceCode;
|
||||
}).filter(Boolean)
|
||||
: [];
|
||||
if (code === 'customer_unresolved') return t('chat.shippingOrderReview.workbench.manualReview.customer');
|
||||
if (lineIndex !== null && (candidates.length || code === 'require_manual_review' || code.includes('inventory_source'))) {
|
||||
return t('chat.shippingOrderReview.workbench.manualReview.lineInventory', {
|
||||
line: lineIndex + 1,
|
||||
candidates: candidates.length ? candidates.join('、') : t('chat.shippingOrderReview.workbench.manualReview.noCandidates'),
|
||||
});
|
||||
}
|
||||
const key = `chat.shippingOrderReview.workbench.issueCodes.${code}`;
|
||||
return code && te(key) ? t(key) : blockReasonLabel(code);
|
||||
}
|
||||
|
||||
function missingFieldLabel(code: string): string {
|
||||
const label = props.fieldLabels?.[String(code)] || code;
|
||||
return `${label}:${t('chat.shippingOrderReview.workbench.missingValue')}`;
|
||||
}
|
||||
|
||||
function conflictOptionLabel(option: { display_value?: unknown; value_key?: string; sources?: string[] }): string {
|
||||
const value = String(option.display_value ?? option.value_key ?? '—').trim() || '—';
|
||||
const sources = (option.sources || []).map((source) => String(source || '').trim()).filter(Boolean);
|
||||
return sources.length ? `${sources.join('、')}:${value}` : value;
|
||||
}
|
||||
|
||||
/** 异常行置顶,已通过行排后。 */
|
||||
const orderedLines = computed(() => {
|
||||
const lines = [...(props.eligibility?.line_projections || [])];
|
||||
@@ -51,6 +93,47 @@ const orderedLines = computed(() => {
|
||||
return (a.line_index ?? 0) - (b.line_index ?? 0);
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* 完整检查与摘要卡共用客户确认事实:服务端刷新前残留的客户 issue 不得误导用户。
|
||||
*/
|
||||
const effectiveIssues = computed(() => (props.eligibility?.issues || []).filter((issue) => {
|
||||
if (props.customerResolved !== true) return true;
|
||||
const code = String(issue.code || '').trim().toLowerCase();
|
||||
const reason = String(issue.reason_code || '').trim().toLowerCase();
|
||||
const gate = String(issue.owning_gate_code || '').trim().toLowerCase();
|
||||
return !(
|
||||
code.startsWith('customer_')
|
||||
|| reason.startsWith('customer_')
|
||||
|| gate === 'customer_resolution'
|
||||
|| gate === 'customer_confirmed'
|
||||
);
|
||||
}));
|
||||
|
||||
/** 资格 issue 中是否声明了字段冲突。 */
|
||||
const hasFieldConflictIssue = computed(() => props.eligibility?.can_build === false && effectiveIssues.value.some((issue) => {
|
||||
const code = String(issue.code || issue.reason_code || '').trim().toLowerCase();
|
||||
const gate = String(issue.owning_gate_code || '').trim().toLowerCase();
|
||||
return code.includes('field_conflict') || gate === 'field_conflict_resolution';
|
||||
}));
|
||||
|
||||
/** 字段冲突由专用明细区展示,避免问题列表重复输出一句笼统说明。 */
|
||||
const nonConflictIssues = computed(() => effectiveIssues.value.filter((issue) => {
|
||||
const code = String(issue.code || issue.reason_code || '').trim().toLowerCase();
|
||||
const gate = String(issue.owning_gate_code || '').trim().toLowerCase();
|
||||
const isConflict = code.includes('field_conflict') || gate === 'field_conflict_resolution';
|
||||
if (!isConflict) return true;
|
||||
// 当前资格已通过且专用冲突投影为空时,这是旧 validation snapshot 残留,禁止误报。
|
||||
return false;
|
||||
}));
|
||||
const unexplainedBlocked = computed(() => Boolean(
|
||||
props.eligibility
|
||||
&& props.eligibility.can_build === false
|
||||
&& !effectiveIssues.value.length
|
||||
&& !props.eligibility.failed_gates?.length
|
||||
&& !props.eligibility.assessment?.missing_required_fields?.length
|
||||
&& !(props.eligibility.line_projections || []).some((line) => line.can_build === false),
|
||||
));
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -69,10 +152,94 @@ const orderedLines = computed(() => {
|
||||
data-testid="review-eligibility-details-close"
|
||||
@click="emit('close')"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.workbench.closePdf') }}
|
||||
{{ t('chat.shippingOrderReview.workbench.close') }}
|
||||
</button>
|
||||
</header>
|
||||
<div class="min-h-0 flex-1 space-y-2 overflow-y-auto p-4">
|
||||
<section
|
||||
class="rounded-lg border px-3 py-2 text-xs"
|
||||
:class="eligibility.can_build
|
||||
? 'border-emerald-200 bg-emerald-50 text-emerald-900 dark:border-emerald-900 dark:bg-emerald-950/30 dark:text-emerald-100'
|
||||
: 'border-amber-200 bg-amber-50 text-amber-900 dark:border-amber-900 dark:bg-amber-950/30 dark:text-amber-100'"
|
||||
data-testid="review-eligibility-details-overall"
|
||||
>
|
||||
<div class="flex items-center justify-between gap-2">
|
||||
<span class="font-semibold">{{ t('chat.shippingOrderReview.buildEligibility.overallResult') }}</span>
|
||||
<span class="rounded-full px-2 py-0.5 font-medium" :class="eligibility.can_build ? 'bg-emerald-100 text-emerald-800 dark:bg-emerald-900/60 dark:text-emerald-100' : 'bg-amber-100 text-amber-900 dark:bg-amber-900/60 dark:text-amber-100'">
|
||||
{{ eligibility.can_build
|
||||
? t('chat.shippingOrderReview.buildEligibility.canBuildYes')
|
||||
: t('chat.shippingOrderReview.buildEligibility.canBuildNo') }}
|
||||
</span>
|
||||
</div>
|
||||
<p v-if="eligibility.can_build && eligibility.can_auto_create === false" class="mt-1">
|
||||
{{ t('chat.shippingOrderReview.buildEligibility.manualConfirmOnly') }}
|
||||
</p>
|
||||
<div v-if="eligibility.can_build && eligibility.can_auto_create === false && (eligibility.auto_create_diagnostics?.reason_codes?.length || eligibility.auto_create_diagnostics?.failed_gates?.length)" class="mt-2">
|
||||
<div class="font-medium">{{ t('chat.shippingOrderReview.buildEligibility.autoCreateFailureTitle') }}</div>
|
||||
<ul class="mt-1 list-disc pl-4">
|
||||
<li v-for="reason in (eligibility.auto_create_failure_reasons?.length ? eligibility.auto_create_failure_reasons.map((item) => item.message) : (eligibility.auto_create_diagnostics.reason_codes?.length ? eligibility.auto_create_diagnostics.reason_codes : eligibility.auto_create_diagnostics.failed_gates))" :key="reason">
|
||||
{{ reason }}
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</section>
|
||||
<section class="rounded-lg border border-slate-200 bg-slate-50 p-3 text-xs dark:border-slate-700 dark:bg-slate-950/40">
|
||||
<div v-if="eligibility.assessment?.missing_required_fields?.length" class="mt-2">
|
||||
<div class="font-medium">{{ t('chat.shippingOrderReview.workbench.requiredFields') }}</div>
|
||||
<div class="mt-1 text-rose-700 dark:text-rose-300">
|
||||
<ul class="mt-1 list-disc pl-4">
|
||||
<li v-for="code in eligibility.assessment.missing_required_fields" :key="String(code)">
|
||||
{{ missingFieldLabel(String(code)) }}
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="nonConflictIssues.length" class="mt-2" data-testid="review-eligibility-blocking-reasons">
|
||||
<div class="font-medium">{{ t('chat.shippingOrderReview.workbench.issueDetails') }}</div>
|
||||
<ul class="mt-1 list-disc pl-4">
|
||||
<li v-for="(issue, index) in nonConflictIssues" :key="index">
|
||||
{{ issueLabel(issue) }}
|
||||
<span v-if="issue.explainability?.message || issue.message" class="text-slate-600 dark:text-slate-300">
|
||||
— {{ issue.explainability?.message || issue.message }}
|
||||
</span>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
<div v-if="unexplainedBlocked" class="mt-2 rounded border border-rose-200 bg-rose-50 px-2 py-1.5 text-rose-900 dark:border-rose-900 dark:bg-rose-950/30 dark:text-rose-100" data-testid="review-eligibility-details-unexplained-block">
|
||||
{{ t('chat.shippingOrderReview.buildEligibility.unexplainedBlocked') }}
|
||||
</div>
|
||||
<div
|
||||
v-if="props.fieldConflicts?.length"
|
||||
class="mt-2 rounded-lg border border-rose-200 bg-rose-50 px-2.5 py-2 text-rose-950 dark:border-rose-900 dark:bg-rose-950/30 dark:text-rose-100"
|
||||
data-testid="review-eligibility-conflict-details"
|
||||
>
|
||||
<div class="font-medium">{{ t('chat.shippingOrderReview.workbench.conflictFields') }}</div>
|
||||
<ul class="mt-2 space-y-2">
|
||||
<li
|
||||
v-for="conflict in props.fieldConflicts"
|
||||
:key="conflict.conflict_key"
|
||||
class="rounded border border-rose-200 bg-white px-2 py-1.5 dark:border-rose-900 dark:bg-slate-900"
|
||||
>
|
||||
<div class="font-semibold">
|
||||
<span v-if="conflict.line_index != null">{{ t('chat.shippingOrderReview.line', { index: conflict.line_index + 1 }) }} · </span>
|
||||
{{ props.fieldLabels?.[String(conflict.field_code)] || conflict.field_code }}
|
||||
</div>
|
||||
<ul class="mt-1 space-y-1 font-normal">
|
||||
<li v-for="(option, optionIndex) in conflict.options" :key="`${conflict.conflict_key}-${optionIndex}`">
|
||||
{{ conflictOptionLabel(option) }}
|
||||
</li>
|
||||
</ul>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
<div
|
||||
v-else-if="hasFieldConflictIssue"
|
||||
class="mt-2 rounded border border-amber-300 bg-amber-50 px-2.5 py-2 text-amber-900 dark:border-amber-800 dark:bg-amber-950/30 dark:text-amber-100"
|
||||
data-testid="review-eligibility-conflict-details-missing"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.workbench.conflictDetailsPending') }}
|
||||
</div>
|
||||
</section>
|
||||
<article
|
||||
v-for="line in orderedLines"
|
||||
:key="String(line.line_key || line.line_index)"
|
||||
@@ -95,7 +262,9 @@ const orderedLines = computed(() => {
|
||||
>
|
||||
{{
|
||||
line.can_build
|
||||
? t('chat.shippingOrderReview.buildEligibility.lineCanBuild')
|
||||
? (eligibility.can_build
|
||||
? t('chat.shippingOrderReview.buildEligibility.lineCanBuild')
|
||||
: t('chat.shippingOrderReview.buildEligibility.linePassesOrderBlocked'))
|
||||
: t('chat.shippingOrderReview.buildEligibility.lineBlocked')
|
||||
}}
|
||||
</span>
|
||||
|
||||
+76
-2
@@ -13,7 +13,7 @@ import type { ShippingOrderReviewBuildEligibility } from '@/features/chat/types/
|
||||
/**
|
||||
* 挂载摘要卡。
|
||||
*/
|
||||
function mountSummary(eligibility: ShippingOrderReviewBuildEligibility) {
|
||||
function mountSummary(eligibility: ShippingOrderReviewBuildEligibility, customerResolved = false) {
|
||||
const i18n = createI18n({
|
||||
legacy: false,
|
||||
locale: 'zh-CN',
|
||||
@@ -32,6 +32,12 @@ function mountSummary(eligibility: ShippingOrderReviewBuildEligibility) {
|
||||
primaryBlock: '首要阻断原因',
|
||||
blockCount: '阻断项 {count} 项',
|
||||
viewFullChecks: '查看完整检查',
|
||||
manualReview: {
|
||||
customer: '请确认客户',
|
||||
field: '请确认字段:{field}',
|
||||
lineInventory: '第 {line} 行:请确认库存来源(候选:{candidates})',
|
||||
noCandidates: '暂无候选',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -39,7 +45,7 @@ function mountSummary(eligibility: ShippingOrderReviewBuildEligibility) {
|
||||
},
|
||||
});
|
||||
return mount(ReviewBuildEligibilitySummary, {
|
||||
props: { eligibility },
|
||||
props: { eligibility, customerResolved },
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
}
|
||||
@@ -66,4 +72,72 @@ describe('ReviewBuildEligibilitySummary', () => {
|
||||
await wrapper.find('[data-testid="review-open-eligibility-details"]').trigger('click');
|
||||
expect(wrapper.emitted('open-details')).toBeTruthy();
|
||||
});
|
||||
|
||||
it('does not keep a stale customer block after the customer is confirmed', () => {
|
||||
const wrapper = mountSummary({
|
||||
can_build: false,
|
||||
status: 'blocked',
|
||||
issues: [{
|
||||
code: 'customer_unresolved',
|
||||
severity: 'blocking',
|
||||
explainability: { message: '未能识别客户' },
|
||||
}],
|
||||
line_projections: [{
|
||||
line_key: 'L1',
|
||||
line_index: 0,
|
||||
can_build: false,
|
||||
block_reason: 'customer_unresolved',
|
||||
}],
|
||||
gates: { customer_confirmed: false },
|
||||
}, true);
|
||||
|
||||
expect(wrapper.find('[data-testid="review-eligibility-primary-block"]').exists()).toBe(false);
|
||||
expect(wrapper.find('[data-testid="review-eligibility-gate-checklist"]').text()).toContain('✓');
|
||||
});
|
||||
|
||||
it('projects concrete manual review facts before falling back to generic copy', () => {
|
||||
const wrapper = mountSummary({
|
||||
can_build: false,
|
||||
status: 'blocked',
|
||||
issues: [{
|
||||
code: 'require_manual_review',
|
||||
severity: 'blocking',
|
||||
line_index: 1,
|
||||
candidate_inventory_source_codes: ['WH_A', 'WH_B'],
|
||||
}],
|
||||
line_projections: [],
|
||||
inventory_source_labels: { WH_A: '华东仓', WH_B: '华南仓' },
|
||||
});
|
||||
|
||||
expect(wrapper.find('[data-testid="review-eligibility-primary-block"]').text())
|
||||
.toContain('第 2 行:请确认库存来源(候选:华东仓、华南仓)');
|
||||
});
|
||||
|
||||
it('explains a blocked order even when the API has no issue detail', () => {
|
||||
const wrapper = mountSummary({
|
||||
can_build: false,
|
||||
status: 'blocked',
|
||||
failed_gates: ['required_fields_complete'],
|
||||
issues: [],
|
||||
line_projections: [],
|
||||
});
|
||||
|
||||
expect(wrapper.find('[data-testid="review-eligibility-primary-block"]').text())
|
||||
.toContain('未知问题');
|
||||
expect(wrapper.text()).not.toContain('required_fields_complete');
|
||||
});
|
||||
|
||||
it('does not expose internal build and auto-create layer names', () => {
|
||||
const wrapper = mountSummary({
|
||||
can_build: true,
|
||||
can_auto_create: false,
|
||||
status: 'qualified',
|
||||
issues: [],
|
||||
line_projections: [],
|
||||
});
|
||||
|
||||
expect(wrapper.find('[data-testid="review-eligibility-layers"]').exists()).toBe(false);
|
||||
expect(wrapper.text()).not.toContain('can_build');
|
||||
expect(wrapper.text()).not.toContain('can_auto_create');
|
||||
});
|
||||
});
|
||||
+184
-12
@@ -2,19 +2,34 @@
|
||||
features/chat/components/shipping-review/ReviewBuildEligibilitySummary.vue
|
||||
用途:复核摘要侧栏的建单资格压缩卡(可建单状态、门禁清单、首要阻断)。
|
||||
依赖:vue-i18n、ShippingOrderReviewBuildEligibility。
|
||||
逻辑:展示客户确认等关键门禁勾选;「查看完整检查」emit open-details;完整逐行结果不常驻。
|
||||
逻辑:只展示业务结论、具体字段/明细问题与异常导航;隐藏 Gate code、
|
||||
can_build/can_auto_create 等实现标识;「查看完整检查」emit open-details。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import type { ShippingOrderReviewBuildEligibility } from '@/features/chat/types/shipping.api.types';
|
||||
import type { ShippingOrderReviewFieldConflict } from '@/features/chat/types/shipping.api.types';
|
||||
|
||||
const props = defineProps<{
|
||||
eligibility: ShippingOrderReviewBuildEligibility | null;
|
||||
fieldConflicts?: ShippingOrderReviewFieldConflict[] | null;
|
||||
fieldLabels?: Record<string, string>;
|
||||
customerResolved?: boolean;
|
||||
/** 可定位异常总数;由工作台统一收集草稿与门禁问题。 */
|
||||
exceptionCount?: number;
|
||||
/** 当前定位异常序号;未定位时为 0。 */
|
||||
exceptionOrdinal?: number;
|
||||
/**
|
||||
* 为 true 时只展示能否建单/自动建单与异常导航,隐藏门禁清单与首要阻断文案,
|
||||
* 避免与 ProcessGateRecoveryCard 重复表达同一业务阻断。
|
||||
*/
|
||||
focusBuildability?: boolean;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
'open-details': [];
|
||||
'navigate-exception': [delta: -1 | 1];
|
||||
}>();
|
||||
|
||||
const { t, te } = useI18n();
|
||||
@@ -29,28 +44,84 @@ const CHECKLIST_GATES = [
|
||||
] as const;
|
||||
|
||||
/** 阻断 issue 数量(优先 blocking severity)。 */
|
||||
const blockingIssueCount = computed(() => {
|
||||
const effectiveIssues = computed(() => {
|
||||
const issues = props.eligibility?.issues || [];
|
||||
if (props.customerResolved !== true) return issues;
|
||||
return issues.filter((item) => {
|
||||
const code = String(item.code || '').trim().toLowerCase();
|
||||
const reason = String(item.reason_code || '').trim().toLowerCase();
|
||||
const gate = String(item.owning_gate_code || '').trim().toLowerCase();
|
||||
return !(
|
||||
code.startsWith('customer_')
|
||||
|| reason.startsWith('customer_')
|
||||
|| gate === 'customer_resolution'
|
||||
|| gate === 'customer_confirmed'
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
const blockingIssueCount = computed(() => {
|
||||
const issues = effectiveIssues.value;
|
||||
const blocking = issues.filter((item) => String(item.severity || '') === 'blocking');
|
||||
return blocking.length || issues.length;
|
||||
});
|
||||
|
||||
/** 首要阻断文案。 */
|
||||
const primaryBlockMessage = computed(() => {
|
||||
const issues = props.eligibility?.issues || [];
|
||||
const issues = effectiveIssues.value;
|
||||
const primary = issues.find((item) => String(item.severity || '') === 'blocking') || issues[0];
|
||||
if (!primary) {
|
||||
const blockedLines = (props.eligibility?.line_projections || []).filter((line) => line.can_build === false);
|
||||
if (!blockedLines.length) return '';
|
||||
const blockedLines = (props.eligibility?.line_projections || []).filter((line) => {
|
||||
if (line.can_build !== false) return false;
|
||||
if (props.customerResolved !== true) return true;
|
||||
const reason = String(line.block_reason || '').trim().toLowerCase();
|
||||
return !reason.startsWith('customer_');
|
||||
});
|
||||
if (!blockedLines.length) {
|
||||
const failedGate = (props.eligibility?.failed_gates || [])[0];
|
||||
if (!failedGate) return '';
|
||||
const gateKey = `chat.shippingOrderReview.buildEligibility.gates.${failedGate}`;
|
||||
return te(gateKey) ? t(gateKey) : t('chat.shippingOrderReview.issueCodes.unknown');
|
||||
}
|
||||
const reason = String(blockedLines[0]?.block_reason || '').trim();
|
||||
const key = `chat.shippingOrderReview.buildEligibility.blockReasons.${reason}`;
|
||||
return reason && te(key) ? t(key) : t('chat.shippingOrderReview.buildEligibility.blockReasons.unknown');
|
||||
}
|
||||
const code = String(primary.code || '').trim().toLowerCase();
|
||||
// Draft 基础校验按冻结 Schema 返回 field_id,资格评估返回 field_code;两者都要映射,
|
||||
// 否则会丢失“究竟哪个字段没有值”的事实,只剩笼统的不可建单。
|
||||
const field = String(primary.field_code || primary.field_id || '').trim();
|
||||
const lineIndex = Number.isFinite(Number(primary.line_index)) ? Number(primary.line_index) : null;
|
||||
const candidates = Array.isArray(primary.candidate_inventory_source_codes)
|
||||
? primary.candidate_inventory_source_codes.map((item) => {
|
||||
const sourceCode = String(item || '').trim();
|
||||
return props.eligibility?.inventory_source_labels?.[sourceCode] || sourceCode;
|
||||
}).filter(Boolean)
|
||||
: [];
|
||||
if (code === 'customer_unresolved') {
|
||||
return t('chat.shippingOrderReview.workbench.manualReview.customer');
|
||||
}
|
||||
if (field) {
|
||||
return t('chat.shippingOrderReview.workbench.manualReview.field', {
|
||||
field: props.fieldLabels?.[field] || field,
|
||||
});
|
||||
}
|
||||
if (lineIndex !== null && (candidates.length || code === 'require_manual_review' || code.includes('inventory_source'))) {
|
||||
return t('chat.shippingOrderReview.workbench.manualReview.lineInventory', {
|
||||
line: lineIndex + 1,
|
||||
candidates: candidates.length ? candidates.join('、') : t('chat.shippingOrderReview.workbench.manualReview.noCandidates'),
|
||||
});
|
||||
}
|
||||
const message = String(primary.explainability?.message || primary.message || '').trim();
|
||||
if (message) return message;
|
||||
const code = String(primary.code || '').trim();
|
||||
const key = `chat.shippingOrderReview.issueCodes.${code}`;
|
||||
return code && te(key) ? t(key) : t('chat.shippingOrderReview.issueCodes.unknown');
|
||||
if (code && te(key)) return t(key);
|
||||
const failedGate = (props.eligibility?.failed_gates || [])[0];
|
||||
if (failedGate) {
|
||||
const gateKey = `chat.shippingOrderReview.buildEligibility.gates.${failedGate}`;
|
||||
return te(gateKey) ? t(gateKey) : t('chat.shippingOrderReview.issueCodes.unknown');
|
||||
}
|
||||
return t('chat.shippingOrderReview.issueCodes.unknown');
|
||||
});
|
||||
|
||||
/** 不可建单的行数。 */
|
||||
@@ -58,6 +129,25 @@ const blockedLineCount = computed(() =>
|
||||
(props.eligibility?.line_projections || []).filter((line) => line.can_build === false).length,
|
||||
);
|
||||
|
||||
const missingRequiredFields = computed(() => (props.eligibility?.assessment?.missing_required_fields || [])
|
||||
.map((code) => props.fieldLabels?.[String(code)] || String(code)));
|
||||
const conflictFields = computed(() => (props.fieldConflicts || []).map((item) => props.fieldLabels?.[String(item.field_code || '').trim()] || String(item.field_code || '').trim())
|
||||
.filter(Boolean));
|
||||
const lowConfidenceFields = computed(() => props.eligibility?.issues?.flatMap((issue) =>
|
||||
(issue.low_confidence_fields || []).map((item) => ({
|
||||
...item,
|
||||
label: props.fieldLabels?.[item.field_code] || item.field_code,
|
||||
})),
|
||||
) || []);
|
||||
const unexplainedBlocked = computed(() => Boolean(
|
||||
props.eligibility
|
||||
&& props.eligibility.can_build === false
|
||||
&& !props.eligibility.issues?.length
|
||||
&& !props.eligibility.failed_gates?.length
|
||||
&& !props.eligibility.assessment?.missing_required_fields?.length
|
||||
&& !(props.eligibility.line_projections || []).some((line) => line.can_build === false),
|
||||
));
|
||||
|
||||
/**
|
||||
* 门禁勾选列表:优先 gates 映射;客户未确认时强制展示失败项。
|
||||
*/
|
||||
@@ -66,17 +156,37 @@ const gateChecklist = computed(() => {
|
||||
const failed = new Set((props.eligibility?.failed_gates || []).map(String));
|
||||
const issues = props.eligibility?.issues || [];
|
||||
const customerIssue = issues.some((item) => String(item.code || '').startsWith('customer_'));
|
||||
return CHECKLIST_GATES.map((gate) => {
|
||||
const checks = CHECKLIST_GATES.map((gate) => {
|
||||
const known = Object.prototype.hasOwnProperty.call(gates, gate);
|
||||
let passed = known ? Boolean(gates[gate]) : !failed.has(gate);
|
||||
if (gate === 'customer_confirmed' && customerIssue) passed = false;
|
||||
if (gate === 'customer_confirmed') {
|
||||
passed = props.customerResolved === true ? true : (customerIssue ? false : passed);
|
||||
}
|
||||
if (gate === 'field_conflicts_resolved' && props.fieldConflicts) {
|
||||
passed = props.fieldConflicts.length === 0;
|
||||
}
|
||||
if (gate === 'required_fields_complete' && props.eligibility?.assessment) {
|
||||
const missing = props.eligibility.assessment.missing_required_fields || [];
|
||||
const invalid = props.eligibility.assessment.invalid_lines || [];
|
||||
passed = missing.length === 0 && invalid.length === 0;
|
||||
}
|
||||
const labelKey = `chat.shippingOrderReview.buildEligibility.gates.${gate}`;
|
||||
return {
|
||||
gate,
|
||||
passed,
|
||||
label: te(labelKey) ? t(labelKey) : gate,
|
||||
label: te(labelKey) ? t(labelKey) : t('chat.shippingOrderReview.issueCodes.unknown'),
|
||||
};
|
||||
}).filter((item) => Object.keys(gates).length === 0 || Object.prototype.hasOwnProperty.call(gates, item.gate) || item.gate === 'customer_confirmed');
|
||||
return [
|
||||
{
|
||||
gate: 'overall_build_result',
|
||||
passed: props.eligibility?.can_build === true,
|
||||
label: props.eligibility?.can_build === true
|
||||
? t('chat.shippingOrderReview.buildEligibility.overallPass')
|
||||
: t('chat.shippingOrderReview.buildEligibility.overallBlocked'),
|
||||
},
|
||||
...checks,
|
||||
];
|
||||
});
|
||||
</script>
|
||||
|
||||
@@ -103,8 +213,15 @@ const gateChecklist = computed(() => {
|
||||
</span>
|
||||
</header>
|
||||
|
||||
<p
|
||||
v-if="eligibility.can_build && eligibility.can_auto_create === false"
|
||||
class="mt-2 rounded-lg border border-amber-200 bg-amber-50 px-2.5 py-2 text-xs text-amber-950 dark:border-amber-900 dark:bg-amber-950/30 dark:text-amber-100"
|
||||
data-testid="review-auto-create-blocked"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.buildEligibility.manualConfirmOnly') }}
|
||||
</p>
|
||||
<ul
|
||||
v-if="gateChecklist.length"
|
||||
v-if="!focusBuildability && gateChecklist.length"
|
||||
class="mt-2 space-y-1 text-xs"
|
||||
data-testid="review-eligibility-gate-checklist"
|
||||
>
|
||||
@@ -119,9 +236,57 @@ const gateChecklist = computed(() => {
|
||||
</span>
|
||||
</li>
|
||||
</ul>
|
||||
<div
|
||||
v-if="exceptionCount"
|
||||
class="mt-2 flex flex-wrap items-center justify-between gap-2 rounded-lg border border-amber-200 bg-amber-50 px-2.5 py-2 text-xs text-amber-950 dark:border-amber-900 dark:bg-amber-950/30 dark:text-amber-100"
|
||||
data-testid="review-exception-nav"
|
||||
>
|
||||
<span>
|
||||
{{ t('chat.shippingOrderReview.issues') }}
|
||||
<span class="ml-1 text-muted">
|
||||
{{ exceptionOrdinal ? `${exceptionOrdinal}/${exceptionCount}` : `0/${exceptionCount}` }}
|
||||
</span>
|
||||
</span>
|
||||
<div class="flex items-center gap-2">
|
||||
<button
|
||||
type="button"
|
||||
class="rounded border border-amber-300 px-2 py-1 text-amber-900 hover:bg-amber-100 dark:border-amber-800 dark:text-amber-100 dark:hover:bg-amber-950"
|
||||
data-testid="review-exception-prev"
|
||||
:title="t('chat.shippingOrderReview.exceptionNav.prevHint')"
|
||||
@click="emit('navigate-exception', -1)"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.exceptionNav.prev') }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded border border-amber-300 px-2 py-1 text-amber-900 hover:bg-amber-100 dark:border-amber-800 dark:text-amber-100 dark:hover:bg-amber-950"
|
||||
data-testid="review-exception-next"
|
||||
:title="t('chat.shippingOrderReview.exceptionNav.nextHint')"
|
||||
@click="emit('navigate-exception', 1)"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.exceptionNav.next') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="missingRequiredFields.length || conflictFields.length" class="mt-2 space-y-1 rounded-lg border border-rose-200 bg-rose-50 px-2.5 py-2 text-xs text-rose-900 dark:border-rose-900 dark:bg-rose-950/30 dark:text-rose-100">
|
||||
<p v-if="missingRequiredFields.length"><span class="font-semibold">{{ t('chat.shippingOrderReview.workbench.missingRequiredFields') }}:</span>{{ missingRequiredFields.join('、') }}</p>
|
||||
<p v-if="conflictFields.length"><span class="font-semibold">{{ t('chat.shippingOrderReview.workbench.conflictFields') }}:</span>{{ [...new Set(conflictFields)].join('、') }}</p>
|
||||
</div>
|
||||
<div
|
||||
v-if="!focusBuildability && lowConfidenceFields.length"
|
||||
class="mt-2 rounded-lg border border-amber-200 bg-amber-50 px-2.5 py-2 text-xs text-amber-950 dark:border-amber-900 dark:bg-amber-950/30 dark:text-amber-100"
|
||||
data-testid="review-low-confidence-fields"
|
||||
>
|
||||
<p class="font-semibold">{{ t('chat.shippingOrderReview.workbench.lowConfidenceFields') }}:</p>
|
||||
<ul class="mt-1 list-disc pl-4">
|
||||
<li v-for="item in lowConfidenceFields" :key="item.field_code">
|
||||
{{ item.label }}({{ item.confidence == null ? '—' : `${Math.round(item.confidence * 100)}%` }},{{ t('chat.shippingOrderReview.workbench.confidenceThreshold', { threshold: Math.round(Number(item.minimum_confidence || 0) * 100) }) }})
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="!eligibility.can_build && primaryBlockMessage"
|
||||
v-if="!focusBuildability && !eligibility.can_build && primaryBlockMessage"
|
||||
class="mt-2 rounded-lg border border-amber-200 bg-amber-50 px-2.5 py-2 text-xs text-amber-950 dark:border-amber-900 dark:bg-amber-950/30 dark:text-amber-100"
|
||||
data-testid="review-eligibility-primary-block"
|
||||
>
|
||||
@@ -133,6 +298,13 @@ const gateChecklist = computed(() => {
|
||||
}) }}
|
||||
</p>
|
||||
</div>
|
||||
<div
|
||||
v-if="unexplainedBlocked"
|
||||
class="mt-2 rounded-lg border border-rose-200 bg-rose-50 px-2.5 py-2 text-xs text-rose-900 dark:border-rose-900 dark:bg-rose-950/30 dark:text-rose-100"
|
||||
data-testid="review-eligibility-unexplained-block"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.buildEligibility.unexplainedBlocked') }}
|
||||
</div>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
|
||||
+130
@@ -0,0 +1,130 @@
|
||||
<!--
|
||||
features/chat/components/shipping-review/ReviewCloseFulfillmentDialog.vue
|
||||
用途:关闭行级或剩余开放行的履约决定确认弹窗(原因必填)。
|
||||
依赖:vue-i18n、closeWorkspaceShippingOrderReviewLineFulfillment、showReviewResumeOutcome。
|
||||
逻辑:父级传入 lineKeys;空数组表示关闭全部剩余开放行;成功后 emit confirmed。
|
||||
-->
|
||||
<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 { closeWorkspaceShippingOrderReviewLineFulfillment } from '@/features/chat/api/shipping.api';
|
||||
import { showReviewResumeOutcome } from '@/features/chat/shipping-review/showReviewResumeOutcome';
|
||||
|
||||
const props = defineProps<{
|
||||
open: boolean;
|
||||
caseNo: string;
|
||||
draftVersion: number | null | undefined;
|
||||
lineKeys: string[];
|
||||
closeAllRemaining?: boolean;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
'update:open': [value: boolean];
|
||||
confirmed: [];
|
||||
}>();
|
||||
|
||||
const { t } = useI18n();
|
||||
const msg = useMessage();
|
||||
const reason = ref('');
|
||||
const busy = ref(false);
|
||||
|
||||
const title = computed(() => (
|
||||
props.closeAllRemaining || !props.lineKeys.length
|
||||
? t('chat.shippingOrderReview.closeFulfillment.titleAll')
|
||||
: t('chat.shippingOrderReview.closeFulfillment.titleSelected', { count: props.lineKeys.length })
|
||||
));
|
||||
|
||||
watch(
|
||||
() => props.open,
|
||||
(isOpen) => {
|
||||
if (!isOpen) {
|
||||
reason.value = '';
|
||||
busy.value = false;
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
/**
|
||||
* 提交关闭履约行决定。
|
||||
*/
|
||||
async function onConfirm() {
|
||||
const trimmed = reason.value.trim();
|
||||
if (!trimmed || !props.caseNo || busy.value) return;
|
||||
busy.value = true;
|
||||
try {
|
||||
const result = await closeWorkspaceShippingOrderReviewLineFulfillment(props.caseNo, {
|
||||
reason: trimmed,
|
||||
line_keys: props.lineKeys.length ? props.lineKeys : undefined,
|
||||
expected_draft_version: props.draftVersion ?? undefined,
|
||||
});
|
||||
showReviewResumeOutcome(
|
||||
result.resume_outcome,
|
||||
msg,
|
||||
t,
|
||||
t('chat.shippingOrderReview.closeFulfillment.success'),
|
||||
);
|
||||
emit('update:open', false);
|
||||
emit('confirmed');
|
||||
} catch (error: unknown) {
|
||||
const message = error instanceof BusinessError
|
||||
? resolveLocalizedErrorMessage(error.code, error.message)
|
||||
: (error instanceof Error ? error.message : t('chat.shippingOrderReview.closeFulfillment.failed'));
|
||||
msg.warning(message);
|
||||
} finally {
|
||||
busy.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 取消并关闭弹窗。
|
||||
*/
|
||||
function onCancel() {
|
||||
emit('update:open', false);
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div
|
||||
v-if="open"
|
||||
class="fixed inset-0 z-50 flex items-center justify-center bg-slate-900/40 p-4"
|
||||
data-testid="review-close-fulfillment-dialog"
|
||||
@click.self="onCancel"
|
||||
>
|
||||
<div class="w-full max-w-md rounded-xl border border-slate-200 bg-white p-4 shadow-xl dark:border-slate-800 dark:bg-slate-900">
|
||||
<h2 class="text-sm font-semibold">{{ title }}</h2>
|
||||
<p class="mt-1 text-xs text-muted">{{ t('chat.shippingOrderReview.closeFulfillment.subtitle') }}</p>
|
||||
<label class="mt-3 block text-xs font-medium text-secondary">
|
||||
{{ t('chat.shippingOrderReview.closeFulfillment.reasonLabel') }}
|
||||
<textarea
|
||||
v-model="reason"
|
||||
rows="3"
|
||||
class="mt-1 w-full rounded-md border border-default bg-surface px-2.5 py-2 text-sm"
|
||||
data-testid="review-close-fulfillment-reason"
|
||||
:placeholder="t('chat.shippingOrderReview.closeFulfillment.reasonPlaceholder')"
|
||||
:disabled="busy"
|
||||
/>
|
||||
</label>
|
||||
<div class="mt-4 flex justify-end gap-2">
|
||||
<button
|
||||
type="button"
|
||||
class="rounded border border-default px-3 py-1.5 text-sm hover:bg-surface-soft disabled:opacity-50"
|
||||
:disabled="busy"
|
||||
@click="onCancel"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.workbench.close') }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded bg-rose-600 px-3 py-1.5 text-sm font-medium text-white disabled:opacity-50"
|
||||
data-testid="review-close-fulfillment-submit"
|
||||
:disabled="busy || !reason.trim()"
|
||||
@click="onConfirm"
|
||||
>
|
||||
{{ busy ? t('chat.shippingOrderReview.closeFulfillment.closing') : t('chat.shippingOrderReview.closeFulfillment.confirm') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
+76
-7
@@ -2,7 +2,8 @@
|
||||
features/chat/components/shipping-review/ReviewCustomerResolutionPanel.vue
|
||||
用途:复核工作台固定「建单前客户确认」区域(与重新识别 PDF 分层)。
|
||||
依赖:vue-i18n、ShippingCustomerConfirmDialog、shipping.api 客户确认/重识别接口。
|
||||
逻辑:始终展示客户识别状态;选择标准客户 / 重新识别客户;成功后 emit refreshed 刷新建单资格。
|
||||
逻辑:未解决时完整展开置顶;已解决且 compact 时缩为一行摘要;
|
||||
选择标准客户 / 重新识别客户;成功后 emit refreshed 刷新建单资格。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, ref } from 'vue';
|
||||
@@ -24,6 +25,8 @@ const props = defineProps<{
|
||||
caseNo: string;
|
||||
resolution: ShippingOrderReviewCustomerResolution | null | undefined;
|
||||
editable: boolean;
|
||||
/** 已解决时缩为一行摘要(放入「更多状态」) */
|
||||
compact?: boolean;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
@@ -56,6 +59,27 @@ const displayName = computed(() => {
|
||||
return name || code || String(props.resolution?.raw_name || '').trim() || '—';
|
||||
});
|
||||
|
||||
const inputValues = computed(() => props.resolution?.input_values || []);
|
||||
const candidateRows = computed(() => props.resolution?.candidates || []);
|
||||
|
||||
function inputLabel(definitionCode: string | null | undefined): string {
|
||||
const code = String(definitionCode || '').trim().toLowerCase();
|
||||
if (code.includes('customer') && code.includes('code')) return t('chat.shippingOrderReview.customerResolution.inputLabels.customerCode');
|
||||
if (code.includes('customer') && code.includes('name')) return t('chat.shippingOrderReview.customerResolution.inputLabels.customerName');
|
||||
if (code.includes('address')) return t('chat.shippingOrderReview.customerResolution.inputLabels.address');
|
||||
if (code.endsWith('customer_code')) return t('chat.shippingOrderReview.customerResolution.inputLabels.customerCode');
|
||||
if (code.endsWith('customer_name')) return t('chat.shippingOrderReview.customerResolution.inputLabels.customerName');
|
||||
if (code.endsWith('address')) return t('chat.shippingOrderReview.customerResolution.inputLabels.address');
|
||||
if (code.includes('email')) return t('chat.shippingOrderReview.customerResolution.inputLabels.email');
|
||||
if (code.includes('domain')) return t('chat.shippingOrderReview.customerResolution.inputLabels.domain');
|
||||
return t('chat.shippingOrderReview.customerResolution.inputLabels.other');
|
||||
}
|
||||
|
||||
function candidateValue(candidate: unknown, key: string): string {
|
||||
const row = candidate && typeof candidate === 'object' ? candidate as Record<string, unknown> : {};
|
||||
return String(row[key] ?? '').trim() || '—';
|
||||
}
|
||||
|
||||
/**
|
||||
* 打开标准客户选择弹窗并加载选项。
|
||||
*/
|
||||
@@ -94,12 +118,21 @@ async function onConfirm(customerId: number) {
|
||||
if (!props.caseNo || busy.value) return;
|
||||
busy.value = true;
|
||||
try {
|
||||
await confirmWorkspaceShippingOrderReviewCustomer(props.caseNo, {
|
||||
const result = await confirmWorkspaceShippingOrderReviewCustomer(props.caseNo, {
|
||||
customer_id: customerId,
|
||||
reason: t('chat.shippingOrderReview.customerResolution.confirmReason'),
|
||||
});
|
||||
dialogOpen.value = false;
|
||||
msg.success(t('chat.shippingOrderReview.customerResolution.confirmed'));
|
||||
const resume = result.resume_outcome;
|
||||
if (resume?.outcome === 'auto_created' || resume?.outcome === 'idempotent_replay') {
|
||||
msg.success(t('chat.shippingOrderReview.resume.autoCreated', {
|
||||
taskNo: resume.task_no || '',
|
||||
}));
|
||||
} else if (resume?.outcome === 'waiting_manual_confirm') {
|
||||
msg.success(t('chat.shippingOrderReview.resume.waitingManualConfirm'));
|
||||
} else {
|
||||
msg.success(t('chat.shippingOrderReview.customerResolution.confirmed'));
|
||||
}
|
||||
emit('refreshed');
|
||||
} catch (error: unknown) {
|
||||
const message = error instanceof BusinessError
|
||||
@@ -136,7 +169,28 @@ async function onRetry() {
|
||||
<section
|
||||
class="rounded-xl border border-slate-200 bg-white p-3 shadow-sm dark:border-slate-800 dark:bg-slate-900"
|
||||
data-testid="review-customer-resolution-panel"
|
||||
:data-compact="compact && resolved ? 'true' : 'false'"
|
||||
>
|
||||
<!-- 已解决摘要:一行展示客户与状态,避免占满侧栏首位 -->
|
||||
<div
|
||||
v-if="compact && resolved"
|
||||
class="flex flex-wrap items-center justify-between gap-2"
|
||||
data-testid="review-customer-resolution-compact"
|
||||
>
|
||||
<p class="text-xs text-secondary">
|
||||
<span class="font-medium text-primary">{{ t('chat.shippingOrderReview.customerResolution.title') }}</span>
|
||||
<span class="mx-1 text-muted">·</span>
|
||||
<span>{{ displayName }}</span>
|
||||
</p>
|
||||
<span
|
||||
class="rounded-full bg-emerald-100 px-2 py-0.5 text-[11px] font-medium text-emerald-800 dark:bg-emerald-950 dark:text-emerald-100"
|
||||
data-testid="review-customer-resolution-badge"
|
||||
>
|
||||
{{ statusLabel }}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<template v-else>
|
||||
<header class="flex flex-wrap items-start justify-between gap-2">
|
||||
<div>
|
||||
<h2 class="text-sm font-semibold">{{ t('chat.shippingOrderReview.customerResolution.title') }}</h2>
|
||||
@@ -155,12 +209,26 @@ async function onRetry() {
|
||||
|
||||
<dl class="mt-2 space-y-1 text-xs text-secondary">
|
||||
<div class="flex flex-wrap gap-x-2">
|
||||
<dt class="text-muted">{{ t('chat.shippingOrderReview.customerResolution.recognizedAs') }}</dt>
|
||||
<dt class="text-muted">{{ t('chat.shippingOrderReview.customerResolution.standardCustomer') }}</dt>
|
||||
<dd class="font-medium text-primary">{{ displayName }}</dd>
|
||||
</div>
|
||||
<div v-if="resolution?.raw_name && resolution.raw_name !== displayName" class="flex flex-wrap gap-x-2">
|
||||
<dt class="text-muted">{{ t('chat.shippingOrderReview.customerResolution.rawName') }}</dt>
|
||||
<dd>{{ resolution.raw_name }}</dd>
|
||||
<div v-if="resolution?.short_code" class="flex flex-wrap gap-x-2">
|
||||
<dt class="text-muted">{{ t('chat.shippingOrderReview.customerResolution.customerCode') }}</dt>
|
||||
<dd class="font-mono font-medium text-primary">{{ resolution.short_code }}</dd>
|
||||
</div>
|
||||
<div v-if="inputValues.length" class="mt-2 border-t border-default pt-2">
|
||||
<dt class="text-muted">{{ t('chat.shippingOrderReview.customerResolution.matchedInputs') }}</dt>
|
||||
<dd v-for="item in inputValues" :key="`${item.definition_code}:${item.normalized_value}`" class="mt-1 flex flex-wrap gap-x-2">
|
||||
<span class="text-muted">{{ inputLabel(item.definition_label || item.definition_code) }}</span>
|
||||
<span class="font-mono text-primary">{{ item.raw_value || item.normalized_value || '—' }}</span>
|
||||
</dd>
|
||||
</div>
|
||||
<div v-if="candidateRows.length > 1" class="mt-2 border-t border-default pt-2">
|
||||
<dt class="text-muted">{{ t('chat.shippingOrderReview.customerResolution.candidates') }}</dt>
|
||||
<dd v-for="candidate in candidateRows" :key="String(candidate.customer_id)" class="mt-1 flex flex-wrap gap-x-2">
|
||||
<span class="text-primary">{{ candidateValue(candidate, 'standard_name') }}</span>
|
||||
<span class="font-mono text-muted">{{ candidateValue(candidate, 'short_code') }}</span>
|
||||
</dd>
|
||||
</div>
|
||||
</dl>
|
||||
|
||||
@@ -196,5 +264,6 @@ async function onRetry() {
|
||||
@search="searchCustomers"
|
||||
@confirm="onConfirm"
|
||||
/>
|
||||
</template>
|
||||
</section>
|
||||
</template>
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
refreshWorkspaceShippingOrderReviewDuplicate,
|
||||
resolveWorkspaceShippingOrderReviewDuplicate,
|
||||
} from '@/features/chat/api/shipping.api';
|
||||
import { showReviewResumeOutcome } from '@/features/chat/shipping-review/showReviewResumeOutcome';
|
||||
import type {
|
||||
ShippingDuplicateAction,
|
||||
ShippingOrderReviewDuplicate,
|
||||
@@ -78,13 +79,13 @@ async function resolve(action: ShippingDuplicateAction) {
|
||||
busy.value = true;
|
||||
selectedAction.value = action;
|
||||
try {
|
||||
await resolveWorkspaceShippingOrderReviewDuplicate(props.caseNo, {
|
||||
const result = await resolveWorkspaceShippingOrderReviewDuplicate(props.caseNo, {
|
||||
action,
|
||||
target_task_no: target,
|
||||
reason: action === 'force_create' ? forceReason.value.trim() : undefined,
|
||||
});
|
||||
forceReason.value = '';
|
||||
msg.success(t('chat.shippingOrderReview.duplicate.resolveSuccess'));
|
||||
showReviewResumeOutcome(result.resume_outcome, msg, t, t('chat.shippingOrderReview.duplicate.resolveSuccess'));
|
||||
emit('refreshed');
|
||||
} catch (error: unknown) {
|
||||
const message = error instanceof BusinessError
|
||||
@@ -104,8 +105,8 @@ async function onRefresh() {
|
||||
if (!props.editable || !props.caseNo || busy.value) return;
|
||||
busy.value = true;
|
||||
try {
|
||||
await refreshWorkspaceShippingOrderReviewDuplicate(props.caseNo);
|
||||
msg.success(t('chat.shippingOrderReview.duplicate.refreshDone'));
|
||||
const result = await refreshWorkspaceShippingOrderReviewDuplicate(props.caseNo);
|
||||
showReviewResumeOutcome(result.resume_outcome, msg, t, t('chat.shippingOrderReview.duplicate.refreshDone'));
|
||||
emit('refreshed');
|
||||
} catch (error: unknown) {
|
||||
const message = error instanceof BusinessError
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
features/chat/components/shipping-review/ReviewFieldConflictPanel.vue
|
||||
用途:复核工作台建单前字段冲突集中裁决区(采用候选值 / 手工值)。
|
||||
依赖:vue-i18n、shipping.api.resolveWorkspaceShippingOrderReviewFieldConflict、useMessage。
|
||||
逻辑:展示 Case.field_conflicts;裁决成功后 emit refreshed;可 emit focus-conflict 定位证据。
|
||||
逻辑:展示 Case.field_conflicts;选项标注 evidence_role(主 PDF / 辅助 / 正文);
|
||||
裁决成功后 emit refreshed;可 emit focus-conflict 定位证据。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, ref } from 'vue';
|
||||
@@ -10,6 +11,7 @@ import { useI18n } from 'vue-i18n';
|
||||
import { BusinessError, resolveLocalizedErrorMessage } from '@/shared/api/client';
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
import { resolveWorkspaceShippingOrderReviewFieldConflict } from '@/features/chat/api/shipping.api';
|
||||
import { showReviewResumeOutcome } from '@/features/chat/shipping-review/showReviewResumeOutcome';
|
||||
import type { ShippingOrderReviewFieldConflict } from '@/features/chat/types/shipping.api.types';
|
||||
|
||||
const props = defineProps<{
|
||||
@@ -48,6 +50,16 @@ function reasonLabel(reason: string): string {
|
||||
return te(key) ? t(key) : reason;
|
||||
}
|
||||
|
||||
/**
|
||||
* 证据角色本地化(主 PDF / 辅助 / 邮件正文)。
|
||||
*/
|
||||
function evidenceRoleLabel(role: string | undefined | null): string {
|
||||
const code = String(role || '').trim();
|
||||
if (!code) return '';
|
||||
const key = `chat.shippingOrderReview.fieldConflict.evidenceRole.${code}`;
|
||||
return te(key) ? t(key) : code;
|
||||
}
|
||||
|
||||
/**
|
||||
* 定位冲突字段到草稿/证据区。
|
||||
*/
|
||||
@@ -66,13 +78,13 @@ async function adoptOption(conflict: ShippingOrderReviewFieldConflict, optionInd
|
||||
if (!props.editable || !props.caseNo || props.draftVersion == null || resolvingKey.value) return;
|
||||
resolvingKey.value = conflict.conflict_key;
|
||||
try {
|
||||
await resolveWorkspaceShippingOrderReviewFieldConflict(props.caseNo, conflict.conflict_key, {
|
||||
const result = await resolveWorkspaceShippingOrderReviewFieldConflict(props.caseNo, conflict.conflict_key, {
|
||||
resolution: 'adopt_option',
|
||||
option_index: optionIndex,
|
||||
expected_draft_version: props.draftVersion,
|
||||
reason: t('chat.shippingOrderReview.fieldConflict.resolveReason'),
|
||||
});
|
||||
msg.success(t('chat.shippingOrderReview.fieldConflict.resolveSuccess'));
|
||||
showReviewResumeOutcome(result.resume_outcome, msg, t, t('chat.shippingOrderReview.fieldConflict.resolveSuccess'));
|
||||
emit('refreshed');
|
||||
} catch (error: unknown) {
|
||||
const message = error instanceof BusinessError
|
||||
@@ -105,7 +117,7 @@ async function submitCustom(conflict: ShippingOrderReviewFieldConflict) {
|
||||
if (!value || !props.editable || props.draftVersion == null || resolvingKey.value) return;
|
||||
resolvingKey.value = conflict.conflict_key;
|
||||
try {
|
||||
await resolveWorkspaceShippingOrderReviewFieldConflict(props.caseNo, conflict.conflict_key, {
|
||||
const result = await resolveWorkspaceShippingOrderReviewFieldConflict(props.caseNo, conflict.conflict_key, {
|
||||
resolution: 'custom',
|
||||
custom_value: value,
|
||||
expected_draft_version: props.draftVersion,
|
||||
@@ -113,7 +125,7 @@ async function submitCustom(conflict: ShippingOrderReviewFieldConflict) {
|
||||
});
|
||||
customOpenKey.value = null;
|
||||
customValue.value = '';
|
||||
msg.success(t('chat.shippingOrderReview.fieldConflict.resolveSuccess'));
|
||||
showReviewResumeOutcome(result.resume_outcome, msg, t, t('chat.shippingOrderReview.fieldConflict.resolveSuccess'));
|
||||
emit('refreshed');
|
||||
} catch (error: unknown) {
|
||||
const message = error instanceof BusinessError
|
||||
@@ -172,9 +184,22 @@ async function submitCustom(conflict: ShippingOrderReviewFieldConflict) {
|
||||
:key="`${conflict.conflict_key}-${idx}`"
|
||||
class="rounded border border-default bg-surface-soft px-2 py-1.5"
|
||||
>
|
||||
<div class="text-muted">
|
||||
{{ t('chat.shippingOrderReview.fieldConflict.optionLabel', { index: idx + 1 }) }}
|
||||
<span v-if="option.sources?.length" class="ml-1">({{ option.sources.join(', ') }})</span>
|
||||
<div class="flex flex-wrap items-center gap-1 text-muted">
|
||||
<span>
|
||||
{{ t('chat.shippingOrderReview.fieldConflict.optionLabel', { index: idx + 1 }) }}
|
||||
<span v-if="option.sources?.length" class="ml-1">({{ option.sources.join(', ') }})</span>
|
||||
</span>
|
||||
<span
|
||||
v-if="evidenceRoleLabel(option.evidence_role)"
|
||||
class="rounded px-1 py-0.5 text-[10px] font-medium"
|
||||
:class="option.evidence_role === 'primary_pdf'
|
||||
? 'bg-sky-100 text-sky-800 dark:bg-sky-950 dark:text-sky-200'
|
||||
: 'bg-slate-100 text-slate-700 dark:bg-slate-800 dark:text-slate-200'"
|
||||
:data-testid="`review-field-conflict-evidence-role-${idx}`"
|
||||
:data-evidence-role="option.evidence_role"
|
||||
>
|
||||
{{ evidenceRoleLabel(option.evidence_role) }}
|
||||
</span>
|
||||
</div>
|
||||
<div class="mt-0.5 font-mono text-primary">{{ option.display_value || option.value_key || '—' }}</div>
|
||||
<button
|
||||
|
||||
+275
@@ -0,0 +1,275 @@
|
||||
<!--
|
||||
features/chat/components/shipping-review/ReviewFulfillmentDecisionPanel.vue
|
||||
用途:复核工作台行级履约决定(等待补货 / 完整行先行 / 关闭)。
|
||||
依赖:vue-i18n、decide/wave line-fulfillment API、showReviewResumeOutcome。
|
||||
逻辑:展示 qty/shortage;逐行决定;选中 fulfill 行可确认波次;关闭 emit open-close-dialog。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, ref } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { BusinessError, resolveLocalizedErrorMessage } from '@/shared/api/client';
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
import {
|
||||
decideWorkspaceShippingOrderReviewLineFulfillment,
|
||||
waveWorkspaceShippingOrderReviewLineFulfillment,
|
||||
} from '@/features/chat/api/shipping.api';
|
||||
import { showReviewResumeOutcome } from '@/features/chat/shipping-review/showReviewResumeOutcome';
|
||||
import type {
|
||||
ShippingOrderReviewLineFulfillment,
|
||||
ShippingOrderReviewLineFulfillmentDecisionCode,
|
||||
ShippingOrderReviewLineFulfillmentLine,
|
||||
} from '@/features/chat/types/shipping.api.types';
|
||||
|
||||
const props = defineProps<{
|
||||
caseNo: string;
|
||||
draftVersion: number | null | undefined;
|
||||
lineFulfillment: ShippingOrderReviewLineFulfillment | null | undefined;
|
||||
editable: boolean;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
refreshed: [];
|
||||
'open-close-dialog': [lineKeys: string[]];
|
||||
}>();
|
||||
|
||||
const { t, te } = useI18n();
|
||||
const msg = useMessage();
|
||||
const busyKey = ref<string | null>(null);
|
||||
const selectedFulfillKeys = ref<string[]>([]);
|
||||
const waveBusy = ref(false);
|
||||
|
||||
const TERMINAL_STATUSES = new Set(['task_created', 'fulfilled', 'closed_unfulfillable']);
|
||||
|
||||
const visible = computed(() => Boolean(
|
||||
props.lineFulfillment?.has_open_lines
|
||||
|| props.lineFulfillment?.has_shortage,
|
||||
));
|
||||
|
||||
const openLines = computed(() => (props.lineFulfillment?.lines || []).filter(
|
||||
(line) => !TERMINAL_STATUSES.has(String(line.line_status || '')),
|
||||
));
|
||||
|
||||
/**
|
||||
* 行状态本地化。
|
||||
*/
|
||||
function lineStatusLabel(status: string | null | undefined): string {
|
||||
const normalized = String(status || 'pending_decision').trim();
|
||||
const key = `chat.shippingOrderReview.fulfillmentDecision.lineStatus.${normalized}`;
|
||||
return te(key) ? t(key) : normalized;
|
||||
}
|
||||
|
||||
/**
|
||||
* 切换 fulfill 波次选中行。
|
||||
*/
|
||||
function toggleFulfillSelection(lineKey: string, checked: boolean) {
|
||||
const set = new Set(selectedFulfillKeys.value);
|
||||
if (checked) set.add(lineKey);
|
||||
else set.delete(lineKey);
|
||||
selectedFulfillKeys.value = [...set];
|
||||
}
|
||||
|
||||
/**
|
||||
* 行是否可选入 fulfill 波次。
|
||||
*/
|
||||
function canSelectForWave(line: ShippingOrderReviewLineFulfillmentLine): boolean {
|
||||
if (TERMINAL_STATUSES.has(String(line.line_status || ''))) return false;
|
||||
return Boolean(line.can_fulfill_complete_line);
|
||||
}
|
||||
|
||||
/**
|
||||
* 写入单行履约决定。
|
||||
*/
|
||||
async function onDecide(
|
||||
line: ShippingOrderReviewLineFulfillmentLine,
|
||||
decisionCode: ShippingOrderReviewLineFulfillmentDecisionCode,
|
||||
) {
|
||||
if (!props.caseNo || !props.editable || busyKey.value) return;
|
||||
if (decisionCode === 'close_unfulfillable') {
|
||||
emit('open-close-dialog', [line.line_key]);
|
||||
return;
|
||||
}
|
||||
busyKey.value = line.line_key;
|
||||
try {
|
||||
const result = await decideWorkspaceShippingOrderReviewLineFulfillment(props.caseNo, {
|
||||
line_key: line.line_key,
|
||||
decision_code: decisionCode,
|
||||
expected_draft_version: props.draftVersion ?? undefined,
|
||||
});
|
||||
showReviewResumeOutcome(
|
||||
result.resume_outcome,
|
||||
msg,
|
||||
t,
|
||||
t('chat.shippingOrderReview.fulfillmentDecision.decideSuccess'),
|
||||
);
|
||||
emit('refreshed');
|
||||
} catch (error: unknown) {
|
||||
const message = error instanceof BusinessError
|
||||
? resolveLocalizedErrorMessage(error.code, error.message)
|
||||
: (error instanceof Error ? error.message : t('chat.shippingOrderReview.fulfillmentDecision.decideFailed'));
|
||||
msg.warning(message);
|
||||
} finally {
|
||||
busyKey.value = null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 为选中完整行创建履约波次 Task。
|
||||
*/
|
||||
async function onConfirmWave() {
|
||||
if (!props.caseNo || props.draftVersion == null || waveBusy.value || !selectedFulfillKeys.value.length) return;
|
||||
waveBusy.value = true;
|
||||
try {
|
||||
const idempotencyKey = `review-wave-${props.caseNo}-${Date.now()}-${selectedFulfillKeys.value.sort().join(',')}`;
|
||||
const result = await waveWorkspaceShippingOrderReviewLineFulfillment(props.caseNo, {
|
||||
line_keys: [...selectedFulfillKeys.value],
|
||||
expected_draft_version: props.draftVersion,
|
||||
idempotency_key: idempotencyKey,
|
||||
});
|
||||
showReviewResumeOutcome(
|
||||
result.resume_outcome,
|
||||
msg,
|
||||
t,
|
||||
t('chat.shippingOrderReview.fulfillmentDecision.waveSuccess', {
|
||||
taskNo: result.task_no || '',
|
||||
}),
|
||||
);
|
||||
selectedFulfillKeys.value = [];
|
||||
emit('refreshed');
|
||||
} catch (error: unknown) {
|
||||
const message = error instanceof BusinessError
|
||||
? resolveLocalizedErrorMessage(error.code, error.message)
|
||||
: (error instanceof Error ? error.message : t('chat.shippingOrderReview.fulfillmentDecision.waveFailed'));
|
||||
msg.warning(message);
|
||||
} finally {
|
||||
waveBusy.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 打开关闭剩余行对话框(全部开放行)。
|
||||
*/
|
||||
function onCloseRemaining() {
|
||||
const keys = openLines.value.map((line) => line.line_key);
|
||||
emit('open-close-dialog', keys);
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section
|
||||
v-if="visible"
|
||||
class="rounded-xl border border-sky-200 bg-sky-50/70 p-3 shadow-sm dark:border-sky-900 dark:bg-sky-950/40"
|
||||
data-testid="review-fulfillment-decision-panel"
|
||||
>
|
||||
<header class="flex flex-wrap items-start justify-between gap-2">
|
||||
<div>
|
||||
<h2 class="text-sm font-semibold text-sky-950 dark:text-sky-50">
|
||||
{{ t('chat.shippingOrderReview.fulfillmentDecision.title') }}
|
||||
</h2>
|
||||
<p class="mt-0.5 text-xs text-sky-900 dark:text-sky-200">
|
||||
{{ t('chat.shippingOrderReview.fulfillmentDecision.subtitle') }}
|
||||
</p>
|
||||
</div>
|
||||
<span class="rounded-full bg-sky-100 px-2.5 py-1 text-xs font-medium text-sky-900 dark:bg-sky-950 dark:text-sky-100">
|
||||
{{ t('chat.shippingOrderReview.fulfillmentDecision.openCount', { count: lineFulfillment?.open_count ?? openLines.length }) }}
|
||||
</span>
|
||||
</header>
|
||||
|
||||
<div class="mt-2 overflow-x-auto">
|
||||
<table class="min-w-full text-left text-xs">
|
||||
<thead class="text-muted">
|
||||
<tr>
|
||||
<th v-if="editable" class="px-1 py-1 font-medium">{{ t('chat.shippingOrderReview.fulfillmentDecision.waveSelect') }}</th>
|
||||
<th class="px-1 py-1 font-medium">#</th>
|
||||
<th class="px-1 py-1 font-medium">{{ t('chat.shippingOrderReview.fulfillmentDecision.partNumber') }}</th>
|
||||
<th class="px-1 py-1 font-medium">{{ t('chat.shippingOrderReview.fulfillmentDecision.qty') }}</th>
|
||||
<th class="px-1 py-1 font-medium">{{ t('chat.shippingOrderReview.fulfillmentDecision.shortage') }}</th>
|
||||
<th class="px-1 py-1 font-medium">{{ t('chat.shippingOrderReview.fulfillmentDecision.status') }}</th>
|
||||
<th v-if="editable" class="px-1 py-1 font-medium">{{ t('chat.shippingOrderReview.fulfillmentDecision.actions') }}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr
|
||||
v-for="line in lineFulfillment?.lines || []"
|
||||
:key="line.line_key"
|
||||
class="border-t border-sky-100 dark:border-sky-900"
|
||||
>
|
||||
<td v-if="editable" class="px-1 py-1">
|
||||
<input
|
||||
v-if="canSelectForWave(line)"
|
||||
type="checkbox"
|
||||
class="rounded border-default"
|
||||
:checked="selectedFulfillKeys.includes(line.line_key)"
|
||||
:data-testid="`review-fulfill-select-${line.line_key}`"
|
||||
@change="toggleFulfillSelection(line.line_key, ($event.target as HTMLInputElement).checked)"
|
||||
>
|
||||
</td>
|
||||
<td class="px-1 py-1">{{ (line.line_index ?? 0) + 1 }}</td>
|
||||
<td class="px-1 py-1 font-mono">{{ line.part_number || line.reservation_id || '—' }}</td>
|
||||
<td class="px-1 py-1">
|
||||
{{ line.required_qty ?? '—' }}
|
||||
<span v-if="line.available_qty" class="text-muted"> / {{ line.available_qty }}</span>
|
||||
</td>
|
||||
<td class="px-1 py-1" :class="line.shortage_qty ? 'font-medium text-rose-700 dark:text-rose-300' : ''">
|
||||
{{ line.shortage_qty || '—' }}
|
||||
</td>
|
||||
<td class="px-1 py-1">{{ lineStatusLabel(line.line_status) }}</td>
|
||||
<td v-if="editable && !TERMINAL_STATUSES.has(String(line.line_status || ''))" class="px-1 py-1">
|
||||
<div class="flex flex-wrap gap-1">
|
||||
<button
|
||||
type="button"
|
||||
class="rounded border border-sky-300 px-2 py-1 text-xs hover:bg-sky-100 disabled:opacity-50 dark:border-sky-800 dark:hover:bg-sky-950"
|
||||
:disabled="busyKey != null"
|
||||
@click="onDecide(line, 'wait_inventory')"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.fulfillmentDecision.waitInventory') }}
|
||||
</button>
|
||||
<button
|
||||
v-if="line.can_fulfill_complete_line"
|
||||
type="button"
|
||||
class="rounded border border-emerald-300 px-2 py-1 text-xs hover:bg-emerald-50 disabled:opacity-50 dark:border-emerald-800 dark:hover:bg-emerald-950"
|
||||
:disabled="busyKey != null"
|
||||
@click="onDecide(line, 'fulfill_complete_line_now')"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.fulfillmentDecision.fulfillNow') }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded border border-rose-300 px-2 py-1 text-xs text-rose-800 hover:bg-rose-50 disabled:opacity-50 dark:border-rose-800 dark:text-rose-200 dark:hover:bg-rose-950"
|
||||
:disabled="busyKey != null"
|
||||
@click="onDecide(line, 'close_unfulfillable')"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.fulfillmentDecision.closeLine') }}
|
||||
</button>
|
||||
</div>
|
||||
</td>
|
||||
<td v-else-if="editable" class="px-1 py-1 text-muted">—</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<div v-if="editable" class="mt-3 flex flex-wrap gap-2">
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-xl bg-emerald-600 px-3 py-1.5 text-sm font-medium text-white disabled:opacity-60"
|
||||
data-testid="review-fulfillment-confirm-wave"
|
||||
:disabled="waveBusy || !selectedFulfillKeys.length || draftVersion == null"
|
||||
@click="onConfirmWave"
|
||||
>
|
||||
{{ waveBusy
|
||||
? t('chat.shippingOrderReview.fulfillmentDecision.waving')
|
||||
: t('chat.shippingOrderReview.fulfillmentDecision.confirmWave', { count: selectedFulfillKeys.length }) }}
|
||||
</button>
|
||||
<button
|
||||
v-if="openLines.length"
|
||||
type="button"
|
||||
class="rounded-xl border border-rose-300 bg-white px-3 py-1.5 text-sm text-rose-800 hover:bg-rose-50 disabled:opacity-60 dark:border-rose-800 dark:bg-slate-900 dark:text-rose-200"
|
||||
data-testid="review-fulfillment-close-remaining"
|
||||
:disabled="waveBusy || busyKey != null"
|
||||
@click="onCloseRemaining"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.fulfillmentDecision.closeRemaining') }}
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
<!--
|
||||
features/chat/components/shipping-review/ReviewFulfillmentSummaryCard.vue
|
||||
用途:复核侧栏紧凑展示行级履约缺口摘要,完整表格在库存模式主区处理。
|
||||
依赖:vue-i18n、ShippingOrderReviewLineFulfillment。
|
||||
逻辑:仅显示开放行/缺口计数与进入库存处理入口;不渲染 7 列表格。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import type { ShippingOrderReviewLineFulfillment } from '@/features/chat/types/shipping.api.types';
|
||||
|
||||
const props = defineProps<{
|
||||
lineFulfillment: ShippingOrderReviewLineFulfillment | null | undefined;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
'enter-inventory': [];
|
||||
}>();
|
||||
|
||||
const { t } = useI18n();
|
||||
|
||||
const visible = computed(() => Boolean(
|
||||
props.lineFulfillment?.has_open_lines
|
||||
|| props.lineFulfillment?.has_shortage
|
||||
|| (props.lineFulfillment?.open_count || 0) > 0,
|
||||
));
|
||||
|
||||
const openCount = computed(() => Number(props.lineFulfillment?.open_count || 0));
|
||||
const readyCount = computed(() => Number(props.lineFulfillment?.ready_count || 0));
|
||||
const shortageCount = computed(() => (
|
||||
props.lineFulfillment?.lines || []
|
||||
).filter((line) => Boolean(line.shortage_qty)).length);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section
|
||||
v-if="visible"
|
||||
class="rounded-xl border border-sky-200 bg-sky-50/70 p-3 shadow-sm dark:border-sky-900 dark:bg-sky-950/40"
|
||||
data-testid="review-fulfillment-summary-card"
|
||||
>
|
||||
<header class="mb-2">
|
||||
<h2 class="text-sm font-semibold text-sky-950 dark:text-sky-50">
|
||||
{{ t('chat.shippingOrderReview.fulfillmentDecision.title') }}
|
||||
</h2>
|
||||
<p class="mt-0.5 text-xs text-sky-900 dark:text-sky-200">
|
||||
{{ t('chat.shippingOrderReview.fulfillmentDecision.railHint') }}
|
||||
</p>
|
||||
</header>
|
||||
<ul class="space-y-1 text-xs text-secondary">
|
||||
<li>{{ t('chat.shippingOrderReview.fulfillmentDecision.openCount', { count: openCount }) }}</li>
|
||||
<li>{{ t('chat.shippingOrderReview.fulfillmentDecision.readyCount', { count: readyCount }) }}</li>
|
||||
<li v-if="shortageCount">
|
||||
{{ t('chat.shippingOrderReview.fulfillmentDecision.shortageCount', { count: shortageCount }) }}
|
||||
</li>
|
||||
</ul>
|
||||
<button
|
||||
type="button"
|
||||
class="mt-3 w-full rounded-xl border border-sky-300 bg-white px-3 py-1.5 text-sm text-sky-950 hover:bg-sky-100 dark:border-sky-800 dark:bg-slate-900 dark:text-sky-50 dark:hover:bg-sky-950"
|
||||
data-testid="review-fulfillment-enter-inventory"
|
||||
@click="emit('enter-inventory')"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.fulfillmentDecision.enterInventory') }}
|
||||
</button>
|
||||
</section>
|
||||
</template>
|
||||
@@ -11,6 +11,10 @@ import type { ShippingOrderReviewBuildEligibilityLineProjection } from '@/featur
|
||||
|
||||
defineProps<{
|
||||
lines: ShippingOrderReviewBuildEligibilityLineProjection[];
|
||||
/**
|
||||
* 仅展示「进入库存」入口,不列出行明细(Gate/履约摘要已表达缺口时使用)。
|
||||
*/
|
||||
summaryOnly?: boolean;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
@@ -48,7 +52,7 @@ function blockReasonLabel(reason?: string | null): string {
|
||||
{{ t('chat.shippingOrderReview.workbench.enterInventory') }}
|
||||
</button>
|
||||
</header>
|
||||
<ul class="space-y-1.5">
|
||||
<ul v-if="!summaryOnly" class="space-y-1.5">
|
||||
<li
|
||||
v-for="line in lines"
|
||||
:key="String(line.line_key || line.line_index)"
|
||||
|
||||
+27
-1
@@ -33,6 +33,8 @@ const messages = {
|
||||
sourceEvidence: 'Evidence',
|
||||
verbatimOk: 'OK',
|
||||
verbatimFailed: 'Failed',
|
||||
unavailableDisabled: 'AI suggestions are disabled in this environment.',
|
||||
unavailableProvider: 'AI suggestion service is unavailable. Try again later.',
|
||||
evidenceAtCell: 'page {page} {cell}',
|
||||
noEvidenceCoords: 'no coords',
|
||||
cancel: 'Cancel',
|
||||
@@ -41,7 +43,13 @@ const messages = {
|
||||
noteOptional: 'Note',
|
||||
reasonRequired: 'Reason required',
|
||||
evidenceLevel: { L1_field: 'Current field content', unknown: 'Relevant document content' },
|
||||
status: { idle: 'Idle', pending: 'Pending', validated: 'Validated', unknown: 'Status pending confirmation' },
|
||||
status: {
|
||||
idle: 'Idle',
|
||||
pending: 'Pending',
|
||||
validated: 'Validated',
|
||||
provider_unavailable: 'Unavailable',
|
||||
unknown: 'Status pending confirmation',
|
||||
},
|
||||
decisions: { accept: 'Accept', modify: 'Modify', reject: 'Reject' },
|
||||
},
|
||||
},
|
||||
@@ -195,4 +203,22 @@ describe('ReviewLlmSuggestionPanel', () => {
|
||||
expect(wrapper.text()).not.toContain('internal_evidence_level');
|
||||
wrapper.unmount();
|
||||
});
|
||||
|
||||
it('shows a visible disabled message when Dify was not called', () => {
|
||||
const unavailable: ShippingOrderReviewLlmSuggestion = {
|
||||
suggestion_no: 'RSG-DISABLED',
|
||||
field_id: 'fld-po',
|
||||
scope: 'header',
|
||||
evidence_level: 'L1_field',
|
||||
status: 'provider_unavailable',
|
||||
error_code: 'SHIPPING.REVIEW_LLM_DISABLED',
|
||||
validation_issues: [],
|
||||
};
|
||||
const wrapper = mountPanel({ suggestions: [unavailable] });
|
||||
|
||||
expect(wrapper.get('[data-testid="review-llm-provider-unavailable"]').text())
|
||||
.toContain('AI suggestions are disabled in this environment.');
|
||||
expect(wrapper.text()).not.toContain('No suggestions');
|
||||
wrapper.unmount();
|
||||
});
|
||||
});
|
||||
@@ -3,7 +3,7 @@
|
||||
用途:AI 建议列表与裁决内容(布局重构后作为抽屉内容组件,非常驻主区大卡片)。
|
||||
依赖:vue-i18n、ReviewLlmSuggestionDialog、ShippingOrderReview* 类型。
|
||||
逻辑:由 ReviewLlmSuggestionDrawer 挂载;请求须用户主动触发;仅 validated 可接受;
|
||||
validation_failed 仅可拒绝;证据按 field_id + line_key/line_index 绑定。
|
||||
validation_failed 仅可拒绝;provider_unavailable 明示原因;证据按 field_id + line_key/line_index 绑定。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, ref } from 'vue';
|
||||
@@ -51,6 +51,19 @@ const failedSuggestions = computed(() =>
|
||||
(props.suggestions || []).filter((item) => String(item.status || '') === 'validation_failed' && !item.decision),
|
||||
);
|
||||
|
||||
/** Provider 未调用或调用失败的记录必须明确展示,避免用户把静默空态误认为 AI 已执行。 */
|
||||
const unavailableSuggestions = computed(() =>
|
||||
(props.suggestions || []).filter((item) => String(item.status || '') === 'provider_unavailable'),
|
||||
);
|
||||
|
||||
/** 将 Provider 失败码转成可执行的业务提示,不向用户暴露底层地址或异常正文。 */
|
||||
function unavailableMessage(item?: ShippingOrderReviewLlmSuggestion): string {
|
||||
if (String(item?.error_code || '') === 'SHIPPING.REVIEW_LLM_DISABLED') {
|
||||
return t('chat.shippingOrderReview.llmSuggestion.unavailableDisabled');
|
||||
}
|
||||
return t('chat.shippingOrderReview.llmSuggestion.unavailableProvider');
|
||||
}
|
||||
|
||||
const statusLabel = computed(() => {
|
||||
if (props.suggestionLoading) return t('chat.shippingOrderReview.llmSuggestion.status.pending');
|
||||
const latest = (props.suggestions || [])[0];
|
||||
@@ -197,7 +210,18 @@ function onDecide(payload: { decision: 'accept' | 'modify' | 'reject'; reason: s
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<p v-if="!pendingSuggestions.length && !failedSuggestions.length" class="mt-3 text-xs text-slate-500">
|
||||
<div
|
||||
v-if="unavailableSuggestions.length"
|
||||
class="mt-3 rounded border border-rose-200 bg-rose-50 px-2 py-2 text-xs text-rose-700 dark:border-rose-900 dark:bg-rose-950/30 dark:text-rose-300"
|
||||
data-testid="review-llm-provider-unavailable"
|
||||
role="alert"
|
||||
>
|
||||
{{ unavailableMessage(unavailableSuggestions[0]) }}
|
||||
</div>
|
||||
<p
|
||||
v-if="!pendingSuggestions.length && !failedSuggestions.length && !unavailableSuggestions.length"
|
||||
class="mt-3 text-xs text-slate-500"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.llmSuggestion.empty') }}
|
||||
</p>
|
||||
<ul v-if="pendingSuggestions.length" class="mt-3 space-y-2">
|
||||
|
||||
@@ -0,0 +1,182 @@
|
||||
<!--
|
||||
features/chat/components/shipping-review/ReviewReservationPanel.vue
|
||||
用途:复核工作台 Reservation 校验摘要;展示行级有效预约号与阻断 issue。
|
||||
依赖:vue-i18n、revalidateWorkspaceShippingOrderReviewReservation、showReviewResumeOutcome。
|
||||
逻辑:needs_attention 时展示;编辑聚焦明细行;重校验后 emit refreshed 并展示 resume 提示。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, ref } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { BusinessError, resolveLocalizedErrorMessage } from '@/shared/api/client';
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
import { revalidateWorkspaceShippingOrderReviewReservation } from '@/features/chat/api/shipping.api';
|
||||
import { showReviewResumeOutcome } from '@/features/chat/shipping-review/showReviewResumeOutcome';
|
||||
import type { ShippingOrderReviewReservation } from '@/features/chat/types/shipping.api.types';
|
||||
|
||||
const props = defineProps<{
|
||||
caseNo: string;
|
||||
draftVersion: number | null | undefined;
|
||||
reservation: ShippingOrderReviewReservation | null | undefined;
|
||||
editable: boolean;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
refreshed: [];
|
||||
'focus-line': [lineIndex: number];
|
||||
}>();
|
||||
|
||||
const { t, te } = useI18n();
|
||||
const msg = useMessage();
|
||||
const busy = ref(false);
|
||||
|
||||
const visible = computed(() => Boolean(props.reservation?.needs_attention || props.reservation?.issues?.length));
|
||||
const lines = computed(() => props.reservation?.lines || []);
|
||||
const issues = computed(() => props.reservation?.issues || []);
|
||||
|
||||
/**
|
||||
* Reservation 状态本地化。
|
||||
*/
|
||||
const statusLabel = computed(() => {
|
||||
const status = String(props.reservation?.status || '').trim();
|
||||
const key = `chat.shippingOrderReview.reservation.status.${status}`;
|
||||
if (status && te(key)) return t(key);
|
||||
return props.reservation?.needs_attention
|
||||
? t('chat.shippingOrderReview.reservation.status.needs_attention')
|
||||
: t('chat.shippingOrderReview.reservation.status.ok');
|
||||
});
|
||||
|
||||
/**
|
||||
* issue / block_reason 本地化文案。
|
||||
*/
|
||||
function issueLabel(code: string | null | undefined): string {
|
||||
const normalized = String(code || '').trim();
|
||||
if (!normalized) return t('chat.shippingOrderReview.reservation.unknownIssue');
|
||||
const key = `chat.shippingOrderReview.reservation.issues.${normalized}`;
|
||||
return te(key) ? t(key) : normalized;
|
||||
}
|
||||
|
||||
/**
|
||||
* 聚焦明细行以便编辑 reservation_id。
|
||||
*/
|
||||
function onFocusLine(lineIndex: number | null | undefined) {
|
||||
if (lineIndex == null || !Number.isFinite(Number(lineIndex))) return;
|
||||
emit('focus-line', Number(lineIndex));
|
||||
}
|
||||
|
||||
/**
|
||||
* 显式重校验 Reservation 并刷新 Case / 建单资格。
|
||||
*/
|
||||
async function onRevalidate() {
|
||||
if (!props.caseNo || props.draftVersion == null || !props.editable || busy.value) return;
|
||||
busy.value = true;
|
||||
try {
|
||||
const result = await revalidateWorkspaceShippingOrderReviewReservation(props.caseNo, {
|
||||
expected_draft_version: props.draftVersion,
|
||||
});
|
||||
showReviewResumeOutcome(
|
||||
result.resume_outcome,
|
||||
msg,
|
||||
t,
|
||||
t('chat.shippingOrderReview.reservation.revalidateDone'),
|
||||
);
|
||||
emit('refreshed');
|
||||
} catch (error: unknown) {
|
||||
const message = error instanceof BusinessError
|
||||
? resolveLocalizedErrorMessage(error.code, error.message)
|
||||
: (error instanceof Error ? error.message : t('chat.shippingOrderReview.reservation.revalidateFailed'));
|
||||
msg.warning(message);
|
||||
} finally {
|
||||
busy.value = false;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section
|
||||
v-if="visible"
|
||||
class="rounded-xl border border-violet-200 bg-violet-50/70 p-3 shadow-sm dark:border-violet-900 dark:bg-violet-950/40"
|
||||
data-testid="review-reservation-panel"
|
||||
>
|
||||
<header class="flex flex-wrap items-start justify-between gap-2">
|
||||
<div>
|
||||
<h2 class="text-sm font-semibold text-violet-950 dark:text-violet-50">
|
||||
{{ t('chat.shippingOrderReview.reservation.title') }}
|
||||
</h2>
|
||||
<p class="mt-0.5 text-xs text-violet-900 dark:text-violet-200">
|
||||
{{ t('chat.shippingOrderReview.reservation.subtitle') }}
|
||||
</p>
|
||||
</div>
|
||||
<span
|
||||
class="rounded-full px-2.5 py-1 text-xs font-medium"
|
||||
:class="reservation?.needs_attention
|
||||
? 'bg-amber-100 text-amber-900 dark:bg-amber-950 dark:text-amber-100'
|
||||
: 'bg-emerald-100 text-emerald-800 dark:bg-emerald-950 dark:text-emerald-100'"
|
||||
data-testid="review-reservation-badge"
|
||||
>
|
||||
{{ statusLabel }}
|
||||
</span>
|
||||
</header>
|
||||
|
||||
<ul v-if="issues.length" class="mt-2 space-y-1 text-xs text-violet-950 dark:text-violet-100">
|
||||
<li
|
||||
v-for="(issue, idx) in issues"
|
||||
:key="`${issue.code}-${issue.line_index}-${idx}`"
|
||||
class="rounded border border-violet-200 bg-white/90 px-2 py-1 dark:border-violet-900 dark:bg-slate-900"
|
||||
>
|
||||
<span v-if="issue.line_index != null">#{{ issue.line_index + 1 }} · </span>
|
||||
{{ issue.message || issueLabel(issue.code) }}
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
<div v-if="lines.length" class="mt-2 overflow-x-auto">
|
||||
<table class="min-w-full text-left text-xs">
|
||||
<thead class="text-muted">
|
||||
<tr>
|
||||
<th class="px-1 py-1 font-medium">#</th>
|
||||
<th class="px-1 py-1 font-medium">{{ t('chat.shippingOrderReview.reservation.reservationId') }}</th>
|
||||
<th class="px-1 py-1 font-medium">{{ t('chat.shippingOrderReview.reservation.action') }}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr
|
||||
v-for="line in lines"
|
||||
:key="String(line.line_key || line.line_index)"
|
||||
class="border-t border-violet-100 dark:border-violet-900"
|
||||
:class="line.needs_attention ? 'bg-amber-50/80 dark:bg-amber-950/20' : ''"
|
||||
>
|
||||
<td class="px-1 py-1">{{ (line.line_index ?? 0) + 1 }}</td>
|
||||
<td class="px-1 py-1 font-mono">
|
||||
{{ line.effective_reservation_id || '—' }}
|
||||
<span v-if="line.block_reason" class="ml-1 text-[10px] text-rose-600 dark:text-rose-400">
|
||||
{{ issueLabel(line.block_reason) }}
|
||||
</span>
|
||||
</td>
|
||||
<td class="px-1 py-1">
|
||||
<button
|
||||
v-if="editable && line.line_index != null"
|
||||
type="button"
|
||||
class="text-[11px] text-primary underline-offset-2 hover:underline"
|
||||
data-testid="review-reservation-focus-line"
|
||||
@click="onFocusLine(line.line_index)"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.reservation.editLine') }}
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<div v-if="editable" class="mt-3 flex flex-wrap gap-2">
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-xl border border-violet-300 bg-white px-3 py-1.5 text-sm text-violet-950 hover:bg-violet-100 disabled:opacity-60 dark:border-violet-800 dark:bg-slate-900 dark:text-violet-100 dark:hover:bg-violet-950"
|
||||
data-testid="review-reservation-revalidate"
|
||||
:disabled="busy || draftVersion == null"
|
||||
@click="onRevalidate"
|
||||
>
|
||||
{{ busy ? t('chat.shippingOrderReview.reservation.revalidating') : t('chat.shippingOrderReview.reservation.revalidate') }}
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
+1
-1
@@ -41,7 +41,7 @@ const { t } = useI18n();
|
||||
data-testid="review-version-history-close"
|
||||
@click="emit('close')"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.workbench.closePdf') }}
|
||||
{{ t('chat.shippingOrderReview.workbench.close') }}
|
||||
</button>
|
||||
</header>
|
||||
<div class="min-h-0 flex-1 overflow-y-auto p-4">
|
||||
|
||||
@@ -65,10 +65,10 @@ function selectVersion(version: ShippingWorkflowItemVersion) {
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div v-if="loading" class="py-4 text-sm text-slate-500">{{ t('chat.shippingWorkflow.loading') }}</div>
|
||||
<div v-if="loading" class="py-4 text-sm text-slate-500">{{ t('chat.shippingProcessing.loading') }}</div>
|
||||
<template v-else>
|
||||
<p class="mb-2 text-xs text-slate-500 dark:text-slate-400">
|
||||
{{ t('chat.shippingWorkflow.versionHistoryNote') }}
|
||||
{{ t('chat.shippingProcessing.versionHistoryNote') }}
|
||||
</p>
|
||||
<p v-if="!versions.length" class="py-4 text-sm text-slate-500">
|
||||
{{ t('chat.shippingSessionWorkItem.noVersions') }}
|
||||
@@ -88,7 +88,7 @@ function selectVersion(version: ShippingWorkflowItemVersion) {
|
||||
<div class="min-w-0">
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<span class="font-medium">
|
||||
{{ version.version_label || t('chat.shippingWorkflow.versionLabel', { version: version.version_no || '?' }) }}
|
||||
{{ version.version_label || t('chat.shippingProcessing.versionLabel', { version: version.version_no || '?' }) }}
|
||||
</span>
|
||||
<span
|
||||
v-if="version.is_current"
|
||||
|
||||
@@ -14,6 +14,8 @@ const props = defineProps<{
|
||||
saving: boolean;
|
||||
isReadOnly: boolean;
|
||||
hasDraft: boolean;
|
||||
/** can_build && can_auto_create 时隐藏确认按钮并展示自动推进提示 */
|
||||
hideConfirmBecauseAutoGate?: boolean;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
@@ -84,6 +86,13 @@ function hasAction(action: string): boolean {
|
||||
</label>
|
||||
</div>
|
||||
<div class="order-2 flex flex-wrap items-center justify-end gap-2 sm:order-2">
|
||||
<p
|
||||
v-if="hideConfirmBecauseAutoGate"
|
||||
class="text-xs text-muted"
|
||||
data-testid="review-auto-gate-hint"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.buildEligibility.autoGateProgressHint') }}
|
||||
</p>
|
||||
<button
|
||||
v-if="hasAction('validate')"
|
||||
type="button"
|
||||
@@ -94,7 +103,7 @@ function hasAction(action: string): boolean {
|
||||
<Save class="h-4 w-4" />{{ t('chat.shippingOrderReview.saveNow') }}
|
||||
</button>
|
||||
<button
|
||||
v-if="hasAction('confirm')"
|
||||
v-if="hasAction('confirm') && !hideConfirmBecauseAutoGate"
|
||||
type="button"
|
||||
:disabled="saving || !canConfirmBuild"
|
||||
class="rounded bg-emerald-600 px-3 py-2 text-sm font-medium text-white disabled:opacity-50"
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
features/chat/components/shipping-review/ReviewWorkbenchHeader.vue
|
||||
用途:订单复核工作台顶栏,展示标题上下文与保存状态。
|
||||
依赖:vue-i18n、lucide-vue-next。
|
||||
逻辑:ShippingOrderReviewView 传入 run/workItem 上下文;emit back 与 open-version-history;不含对话上下文切换。
|
||||
逻辑:ShippingOrderReviewView 传入 run/reviewProgressContext 上下文;emit back 与 open-version-history;不含对话上下文切换。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue';
|
||||
@@ -18,11 +18,13 @@ const props = defineProps<{
|
||||
draftConflict: boolean;
|
||||
isReadOnly: boolean;
|
||||
showVersionHistory?: boolean;
|
||||
showAuditTrail?: boolean;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
back: [];
|
||||
'open-version-history': [];
|
||||
'open-audit-trail': [];
|
||||
}>();
|
||||
|
||||
const { t } = useI18n();
|
||||
@@ -55,6 +57,15 @@ const subtitle = computed(() => {
|
||||
<h1 class="text-base font-semibold">{{ t('chat.shippingOrderReview.title') }}</h1>
|
||||
<p class="truncate text-xs text-slate-500 dark:text-slate-400">{{ subtitle }}</p>
|
||||
</div>
|
||||
<button
|
||||
v-if="showAuditTrail"
|
||||
type="button"
|
||||
class="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-audit-trail"
|
||||
@click="emit('open-audit-trail')"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.auditTrail.open') }}
|
||||
</button>
|
||||
<button
|
||||
v-if="showVersionHistory"
|
||||
type="button"
|
||||
|
||||
@@ -36,6 +36,7 @@ function setMode(next: ReviewWorkbenchMode) {
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<!-- 产品契约:工作台模式条始终可见,便于发现库存/证据模式入口。 -->
|
||||
<div
|
||||
class="flex flex-wrap items-center justify-between gap-2 rounded-lg border border-slate-200 bg-white px-3 py-2 text-xs dark:border-slate-800 dark:bg-slate-900"
|
||||
data-testid="review-workbench-mode"
|
||||
|
||||
+96
-25
@@ -1,14 +1,17 @@
|
||||
/**
|
||||
* features/chat/components/shipping-review/ReviewWorkflowProgressPanel.spec.ts
|
||||
* 用途:确认后自动进度面板节点状态与无货代上传按钮契约。
|
||||
* 用途:复核统一进度面板——UnifiedProgressTrack 挂载;人工入口仅 Gate 动作。
|
||||
* 依赖:vitest、@vue/test-utils、vue-i18n stub、RouterLink stub。
|
||||
* 逻辑:按 lifecycle_status 断言 done/active/pending;待登记时展示下一步说明与任务处理台入口。
|
||||
* 逻辑:有 processingProjection 才渲染轨道节点;manual upload 入口需 nextActionCode;RPA 不展示人工 CTA。
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { mount } from '@vue/test-utils';
|
||||
import { createI18n } from 'vue-i18n';
|
||||
import ReviewWorkflowProgressPanel from './ReviewWorkflowProgressPanel.vue';
|
||||
import type { ShippingWorkflowItem } from '@/features/chat/types/shipping.api.types';
|
||||
import type {
|
||||
ShippingProcessingProjection,
|
||||
ShippingReviewProgressContext,
|
||||
} from '@/features/chat/types/shipping.api.types';
|
||||
|
||||
const messages = {
|
||||
en: {
|
||||
@@ -16,19 +19,25 @@ const messages = {
|
||||
shippingOrderReview: {
|
||||
workflowProgress: {
|
||||
title: 'Auto progress',
|
||||
subtitle: 'Stops at waiting for manual upload registration',
|
||||
subtitle: 'Advances through freight upload',
|
||||
polling: 'Refreshing…',
|
||||
taskNo: 'Task {taskNo}',
|
||||
progressUnavailable: 'Progress unavailable — refresh the page.',
|
||||
openTaskWorkbench: 'Open task workbench to register',
|
||||
noUploadHint: 'Register credentials in the task workbench',
|
||||
nextStepsManualUpload:
|
||||
'Next: download Excel → upload on freight platform → submit evidence and receipt',
|
||||
nodes: {
|
||||
building_order: 'Create task',
|
||||
inventory_matching: 'Match inventory',
|
||||
generating_excel: 'Generate Excel',
|
||||
manual_upload_pending: 'Awaiting upload registration',
|
||||
},
|
||||
nextStepsGeneric: 'Manual action required — follow the system prompt.',
|
||||
},
|
||||
},
|
||||
shippingProcessing: {
|
||||
panelTitle: 'Shipping processing',
|
||||
status: {
|
||||
automating: 'Automating',
|
||||
blocked: 'Blocked',
|
||||
processing: 'Processing',
|
||||
},
|
||||
stage: {
|
||||
freight_uploading: 'Uploading to freight',
|
||||
excel_generating: 'Generating Excel',
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -38,13 +47,18 @@ const messages = {
|
||||
/**
|
||||
* 挂载进度面板。
|
||||
*/
|
||||
function mountPanel(item: Partial<ShippingWorkflowItem> | null, extras?: { taskNo?: string; polling?: boolean }) {
|
||||
function mountPanel(extras?: {
|
||||
taskNo?: string;
|
||||
polling?: boolean;
|
||||
processingProjection?: Partial<ShippingProcessingProjection> | null;
|
||||
}) {
|
||||
const i18n = createI18n({ legacy: false, locale: 'en', messages });
|
||||
return mount(ReviewWorkflowProgressPanel, {
|
||||
props: {
|
||||
item: item as ShippingWorkflowItem | null,
|
||||
item: null as ShippingReviewProgressContext | null,
|
||||
taskNo: extras?.taskNo ?? 'SN-1',
|
||||
polling: extras?.polling ?? true,
|
||||
processingProjection: (extras?.processingProjection || null) as ShippingProcessingProjection | null,
|
||||
},
|
||||
global: {
|
||||
plugins: [i18n],
|
||||
@@ -59,25 +73,82 @@ function mountPanel(item: Partial<ShippingWorkflowItem> | null, extras?: { taskN
|
||||
}
|
||||
|
||||
describe('ReviewWorkflowProgressPanel', () => {
|
||||
it('marks earlier nodes done and current active', () => {
|
||||
const wrapper = mountPanel({ lifecycle_status: 'generating_excel', current_stage: 'generating_excel' });
|
||||
expect(wrapper.get('[data-testid="review-workflow-progress-node-building_order"]').attributes('data-state')).toBe('done');
|
||||
expect(wrapper.get('[data-testid="review-workflow-progress-node-inventory_matching"]').attributes('data-state')).toBe('done');
|
||||
expect(wrapper.get('[data-testid="review-workflow-progress-node-generating_excel"]').attributes('data-state')).toBe('active');
|
||||
expect(wrapper.get('[data-testid="review-workflow-progress-node-manual_upload_pending"]').attributes('data-state')).toBe('pending');
|
||||
it('shows unavailable state without projection', () => {
|
||||
const wrapper = mountPanel({ polling: false, processingProjection: null });
|
||||
expect(wrapper.find('[data-testid="review-progress-unavailable"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="unified-progress-track"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="review-open-task-workbench"]').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it('renders unified track nodes from projection stage', () => {
|
||||
const wrapper = mountPanel({
|
||||
polling: false,
|
||||
processingProjection: {
|
||||
status: 'processing',
|
||||
stage: 'excel_generating',
|
||||
sourceType: 'eml',
|
||||
},
|
||||
});
|
||||
expect(wrapper.find('[data-testid="review-progress-unavailable"]').exists()).toBe(false);
|
||||
const current = wrapper.findAll('[data-testid="unified-progress-node"]')
|
||||
.find((node) => node.attributes('data-stage') === 'excel_generating');
|
||||
expect(current?.attributes('data-current')).toBe('true');
|
||||
expect(current?.attributes('data-state')).toBe('running');
|
||||
});
|
||||
|
||||
it('lights freight_uploading and hides manual CTA while automating', () => {
|
||||
const wrapper = mountPanel({
|
||||
polling: false,
|
||||
processingProjection: {
|
||||
status: 'automating',
|
||||
stage: 'freight_uploading',
|
||||
sourceType: 'eml',
|
||||
},
|
||||
});
|
||||
const freight = wrapper.findAll('[data-testid="unified-progress-node"]')
|
||||
.find((node) => node.attributes('data-stage') === 'freight_uploading');
|
||||
expect(freight?.attributes('data-current')).toBe('true');
|
||||
expect(wrapper.find('[data-testid="review-open-task-workbench"]').exists()).toBe(false);
|
||||
expect(wrapper.find('[data-testid="review-manual-upload-next-steps"]').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it('shows manual_upload_pending next steps and task workbench link', () => {
|
||||
const wrapper = mountPanel({ lifecycle_status: 'manual_upload_pending' }, { polling: false });
|
||||
expect(wrapper.get('[data-testid="review-workflow-progress-node-manual_upload_pending"]').attributes('data-state')).toBe('active');
|
||||
it('shows task workbench link when gate next_action is manual upload', () => {
|
||||
const wrapper = mountPanel({
|
||||
polling: false,
|
||||
processingProjection: {
|
||||
status: 'blocked',
|
||||
stage: 'excel_generating',
|
||||
sourceType: 'eml',
|
||||
currentGate: {
|
||||
gateCode: 'manual_upload',
|
||||
status: 'blocked',
|
||||
nextActionCode: 'wait_manual_upload',
|
||||
},
|
||||
availableActions: ['wait_manual_upload', 'mark_manual_uploaded'],
|
||||
},
|
||||
});
|
||||
expect(wrapper.get('[data-testid="review-manual-upload-next-steps"]').text()).toContain('download Excel');
|
||||
const link = wrapper.get('[data-testid="review-open-task-workbench"]');
|
||||
expect(link.text()).toContain('Open task workbench to register');
|
||||
expect(link.attributes('href')).toContain('workspace-shipping-my-tasks');
|
||||
expect(link.attributes('href')).toContain('SN-1');
|
||||
expect(wrapper.find('[data-testid="review-upload-freight"]').exists()).toBe(false);
|
||||
expect(wrapper.find('[data-testid="review-workflow-progress-polling"]').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it('does not show manual upload tip for blocked retry_freight_upload_rpa', () => {
|
||||
const wrapper = mountPanel({
|
||||
polling: false,
|
||||
processingProjection: {
|
||||
status: 'blocked',
|
||||
stage: 'freight_uploading',
|
||||
sourceType: 'eml',
|
||||
currentGate: {
|
||||
gateCode: 'freight_upload',
|
||||
status: 'blocked',
|
||||
nextActionCode: 'retry_freight_upload_rpa',
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(wrapper.find('[data-testid="review-manual-upload-next-steps"]').exists()).toBe(false);
|
||||
expect(wrapper.find('[data-testid="review-open-task-workbench"]').exists()).toBe(false);
|
||||
});
|
||||
});
|
||||
+98
-101
@@ -1,150 +1,147 @@
|
||||
<!--
|
||||
features/chat/components/shipping-review/ReviewWorkflowProgressPanel.vue
|
||||
用途:复核确认后展示自动进度节点:创建任务 → 库存匹配 → 生成 Excel → 待人工上传登记。
|
||||
依赖:vue-i18n、vue-router、ShippingWorkflowItem。
|
||||
逻辑:ShippingOrderReviewView 在确认后挂载;按 lifecycle_status / current_stage 点亮节点;
|
||||
无货代上传按钮;待登记时说明下一步并提供跳转任务处理台入口;
|
||||
轮询由父级 composable 负责。
|
||||
用途:复核工作台统一进度轨道(完整 15 阶密度窗口)+ Gate 下一步提示。
|
||||
依赖:vue-i18n、ShippingProcessingProjection、UnifiedProgressTrack、shippingProcessingFulfillment。
|
||||
逻辑:节点高亮仅读统一投影;任务台入口仅当 currentGate.nextActionCode 指人工上传。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { RouterLink } from 'vue-router';
|
||||
import type { ShippingWorkflowItem } from '@/features/chat/types/shipping.api.types';
|
||||
import type {
|
||||
ShippingProcessingProjection,
|
||||
ShippingReviewProgressContext,
|
||||
} from '@/features/chat/types/shipping.api.types';
|
||||
import {
|
||||
projectionRequiresManualUploadWorkbench,
|
||||
} from '@/features/chat/shipping/shippingProcessingFulfillment';
|
||||
import {
|
||||
resolveShippingProcessingStatusLabel,
|
||||
shippingProcessingStageKey,
|
||||
} from '@/features/chat/shipping/shippingProcessingLabels';
|
||||
import UnifiedProgressTrack from '@/features/shipping-progress/components/UnifiedProgressTrack.vue';
|
||||
|
||||
const props = defineProps<{
|
||||
item: ShippingWorkflowItem | null;
|
||||
item: ShippingReviewProgressContext | null;
|
||||
taskNo?: string | null;
|
||||
polling?: boolean;
|
||||
/** 统一进度投影:节点与文案的权威来源。 */
|
||||
processingProjection?: ShippingProcessingProjection | null;
|
||||
}>();
|
||||
|
||||
const { t } = useI18n();
|
||||
const { t, te } = useI18n();
|
||||
|
||||
/** 进度节点稳定键;与 WorkflowItem lifecycle 对齐。 */
|
||||
type ReviewProgressNodeKey =
|
||||
| 'building_order'
|
||||
| 'inventory_matching'
|
||||
| 'generating_excel'
|
||||
| 'manual_upload_pending';
|
||||
const hasProjection = computed(() => Boolean(props.processingProjection));
|
||||
|
||||
const NODES: ReviewProgressNodeKey[] = [
|
||||
'building_order',
|
||||
'inventory_matching',
|
||||
'generating_excel',
|
||||
'manual_upload_pending',
|
||||
];
|
||||
const unifiedStatusLabel = computed(() => {
|
||||
const status = props.processingProjection?.status;
|
||||
if (!status) return '';
|
||||
return resolveShippingProcessingStatusLabel(status, te, t);
|
||||
});
|
||||
|
||||
/**
|
||||
* 将 Item 生命周期映射到进度节点索引(0..3);未知时按建单中。
|
||||
*/
|
||||
function nodeIndex(status?: string | null): number {
|
||||
const normalized = String(status || '').trim();
|
||||
const idx = NODES.indexOf(normalized as ReviewProgressNodeKey);
|
||||
if (idx >= 0) return idx;
|
||||
if (['closed', 'cancelled'].includes(normalized)) return NODES.length - 1;
|
||||
if (['pending_review', 'queued', 'layout_parsing', 'extracting'].includes(normalized)) return -1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
const activeIndex = computed(() =>
|
||||
nodeIndex(props.item?.lifecycle_status || props.item?.current_stage),
|
||||
);
|
||||
|
||||
const showTaskWorkbenchLink = computed(() => {
|
||||
const status = String(props.item?.lifecycle_status || props.item?.current_stage || '').trim();
|
||||
return status === 'manual_upload_pending' && Boolean(String(props.taskNo || '').trim());
|
||||
const unifiedStageLabel = computed(() => {
|
||||
const stage = props.processingProjection?.stage;
|
||||
if (!stage) return '';
|
||||
const key = shippingProcessingStageKey(stage);
|
||||
return te(key) ? t(key) : stage;
|
||||
});
|
||||
|
||||
/**
|
||||
* 任务处理台路由:带 task_no,便于直接定位待登记任务。
|
||||
* 仅当 Gate next_action 明确指人工上传且非 RPA 阶段时展示任务台入口。
|
||||
*/
|
||||
const taskWorkbenchTo = computed(() => ({
|
||||
name: 'workspace-shipping-my-tasks',
|
||||
query: {
|
||||
task_no: String(props.taskNo || '').trim(),
|
||||
},
|
||||
}));
|
||||
const showTaskWorkbenchLink = computed(() => {
|
||||
if (!props.processingProjection) return false;
|
||||
if (!projectionRequiresManualUploadWorkbench(props.processingProjection)) return false;
|
||||
return Boolean(String(props.taskNo || '').trim());
|
||||
});
|
||||
|
||||
/**
|
||||
* 节点展示态:done / active / pending。
|
||||
* blocked 且非人工上传时展示通用下一步提示(来自 Gate 动作 i18n)。
|
||||
*/
|
||||
function nodeState(index: number): 'done' | 'active' | 'pending' {
|
||||
const current = activeIndex.value;
|
||||
if (current < 0) return 'pending';
|
||||
if (index < current) return 'done';
|
||||
if (index === current) return 'active';
|
||||
return 'pending';
|
||||
}
|
||||
const showGenericNextSteps = computed(() => {
|
||||
const projection = props.processingProjection;
|
||||
if (!projection || showTaskWorkbenchLink.value) return false;
|
||||
const nextAction = String(projection.currentGate?.nextActionCode || '').trim();
|
||||
if (!nextAction) return false;
|
||||
const status = String(projection.status || '').trim().toLowerCase();
|
||||
return status === 'blocked' || status === 'needs_action';
|
||||
});
|
||||
|
||||
const genericNextStepMessage = computed(() => {
|
||||
const code = String(props.processingProjection?.currentGate?.nextActionCode || '').trim();
|
||||
if (code) {
|
||||
const gateKey = `workspace.shippingNotice.processGate.actions.${code}`;
|
||||
if (te(gateKey)) return t(gateKey);
|
||||
}
|
||||
return t('chat.shippingOrderReview.workflowProgress.nextStepsGeneric');
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section
|
||||
class="rounded-xl border border-slate-200 bg-white p-4 shadow-sm dark:border-slate-800 dark:bg-slate-900"
|
||||
class="rounded-xl border border-default bg-surface-soft/60 p-3"
|
||||
data-testid="review-workflow-progress-panel"
|
||||
>
|
||||
<header class="mb-3 flex flex-wrap items-center justify-between gap-2">
|
||||
<div>
|
||||
<h2 class="text-sm font-semibold">{{ t('chat.shippingOrderReview.workflowProgress.title') }}</h2>
|
||||
<p class="mt-0.5 text-xs text-slate-500 dark:text-slate-400">
|
||||
<div class="flex items-start justify-between gap-2">
|
||||
<div class="min-w-0">
|
||||
<div class="text-sm font-semibold text-primary">
|
||||
{{ t('chat.shippingOrderReview.workflowProgress.title') }}
|
||||
</div>
|
||||
<div
|
||||
v-if="hasProjection && (unifiedStatusLabel || unifiedStageLabel)"
|
||||
class="mt-0.5 text-[11px] text-secondary"
|
||||
data-testid="review-progress-unified-label"
|
||||
>
|
||||
<span v-if="unifiedStatusLabel">{{ unifiedStatusLabel }}</span>
|
||||
<span v-if="unifiedStageLabel"> · {{ unifiedStageLabel }}</span>
|
||||
</div>
|
||||
<div
|
||||
v-else-if="!hasProjection"
|
||||
class="mt-0.5 text-[11px] text-amber-700 dark:text-amber-300"
|
||||
data-testid="review-progress-unavailable"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.workflowProgress.progressUnavailable') }}
|
||||
</div>
|
||||
<div v-else class="mt-0.5 text-[11px] text-secondary">
|
||||
{{ t('chat.shippingOrderReview.workflowProgress.subtitle') }}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<span
|
||||
v-if="polling"
|
||||
class="text-xs text-sky-700 dark:text-sky-300"
|
||||
class="shrink-0 text-[11px] text-muted"
|
||||
data-testid="review-workflow-progress-polling"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.workflowProgress.polling') }}
|
||||
</span>
|
||||
</header>
|
||||
</div>
|
||||
|
||||
<div class="mt-3" data-testid="review-progress-nodes">
|
||||
<UnifiedProgressTrack
|
||||
:projection="processingProjection"
|
||||
density="review"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="taskNo"
|
||||
class="mb-3 flex flex-wrap items-center gap-2 text-xs text-slate-600 dark:text-slate-400"
|
||||
v-if="showTaskWorkbenchLink"
|
||||
class="mt-3 rounded-md border border-amber-200 bg-amber-50 px-2.5 py-2 text-[11px] text-amber-900 dark:border-amber-900/50 dark:bg-amber-950/30 dark:text-amber-100"
|
||||
data-testid="review-manual-upload-next-steps"
|
||||
>
|
||||
<span>{{ t('chat.shippingOrderReview.workflowProgress.taskNo', { taskNo }) }}</span>
|
||||
<p>{{ t('chat.shippingOrderReview.workflowProgress.nextStepsManualUpload') }}</p>
|
||||
<RouterLink
|
||||
v-if="showTaskWorkbenchLink"
|
||||
:to="taskWorkbenchTo"
|
||||
class="inline-flex items-center rounded-lg bg-brand-600 px-2.5 py-1 text-xs font-medium text-white hover:bg-brand-700"
|
||||
class="mt-1 inline-flex font-medium text-brand-700 underline dark:text-brand-300"
|
||||
:to="{ name: 'workspace-shipping-my-tasks', query: { task_no: taskNo || undefined } }"
|
||||
data-testid="review-open-task-workbench"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.workflowProgress.openTaskWorkbench') }}
|
||||
</RouterLink>
|
||||
</div>
|
||||
|
||||
<ol class="space-y-2" data-testid="review-workflow-progress-nodes">
|
||||
<li
|
||||
v-for="(key, index) in NODES"
|
||||
:key="key"
|
||||
class="flex items-center gap-3 rounded-lg border px-3 py-2 text-sm"
|
||||
:class="{
|
||||
'border-emerald-200 bg-emerald-50 text-emerald-900 dark:border-emerald-900 dark:bg-emerald-950/40 dark:text-emerald-100': nodeState(index) === 'done',
|
||||
'border-sky-200 bg-sky-50 text-sky-950 dark:border-sky-900 dark:bg-sky-950/40 dark:text-sky-100': nodeState(index) === 'active',
|
||||
'border-slate-200 bg-slate-50 text-slate-500 dark:border-slate-800 dark:bg-slate-950/40 dark:text-slate-400': nodeState(index) === 'pending',
|
||||
}"
|
||||
:data-testid="`review-workflow-progress-node-${key}`"
|
||||
:data-state="nodeState(index)"
|
||||
>
|
||||
<span class="inline-flex h-6 w-6 shrink-0 items-center justify-center rounded-full border text-xs font-semibold">
|
||||
{{ index + 1 }}
|
||||
</span>
|
||||
<span>{{ t(`chat.shippingOrderReview.workflowProgress.nodes.${key}`) }}</span>
|
||||
</li>
|
||||
</ol>
|
||||
|
||||
<p
|
||||
v-if="showTaskWorkbenchLink"
|
||||
class="mt-3 rounded-lg border border-amber-200 bg-amber-50 px-3 py-2 text-xs text-amber-900 dark:border-amber-900/60 dark:bg-amber-950/40 dark:text-amber-100"
|
||||
data-testid="review-manual-upload-next-steps"
|
||||
<div
|
||||
v-else-if="showGenericNextSteps"
|
||||
class="mt-3 rounded-md border border-default bg-surface-soft px-2.5 py-2 text-[11px] text-secondary"
|
||||
data-testid="review-generic-next-steps"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.workflowProgress.nextStepsManualUpload') }}
|
||||
</p>
|
||||
<p
|
||||
v-else
|
||||
class="mt-3 text-xs text-slate-500 dark:text-slate-400"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.workflowProgress.noUploadHint') }}
|
||||
</p>
|
||||
<p>{{ genericNextStepMessage }}</p>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
+318
@@ -0,0 +1,318 @@
|
||||
/**
|
||||
* features/chat/components/shipping/ShippingConversationProcessingCard.spec.ts
|
||||
* 用途:验收右侧任务分组卡——needs_action/processing 与短时反馈标签。
|
||||
* 依赖:Vitest、Vue Test Utils、vue-i18n、ShippingConversationProcessingCard。
|
||||
* 逻辑:构造 ConversationProcessingProjection;断言分组、焦点 emit;右侧不渲染 history。
|
||||
*/
|
||||
import { mount, flushPromises } from '@vue/test-utils';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { createI18n } from 'vue-i18n';
|
||||
import chatZhCn from '@/locales/zh-CN/chat.json';
|
||||
import type { ConversationProcessingProjection } from '@/features/chat/types/shipping.api.types';
|
||||
import ShippingConversationProcessingCard from './ShippingConversationProcessingCard.vue';
|
||||
|
||||
const i18n = createI18n({
|
||||
legacy: false,
|
||||
locale: 'zh-CN',
|
||||
messages: { 'zh-CN': { chat: chatZhCn } },
|
||||
});
|
||||
|
||||
function buildProjection(): ConversationProcessingProjection {
|
||||
return {
|
||||
summary: { total_tasks: 3, processing: 1, needs_action: 1, completed: 1, history: 0 },
|
||||
focused_task_no: 'OT-PROC',
|
||||
recent_task_no: 'OT-PROC',
|
||||
needs_action: [{
|
||||
user_task_no: 'OT-NEED',
|
||||
group: 'needs_action',
|
||||
status_label: 'pending_review',
|
||||
file_count: 2,
|
||||
run_no: 'RUN-NEED',
|
||||
can_append: false,
|
||||
recently_created: false,
|
||||
}],
|
||||
processing: [{
|
||||
user_task_no: 'OT-PROC',
|
||||
submission_ordinal: 2,
|
||||
group: 'processing',
|
||||
status_label: 'extracting',
|
||||
file_count: 1,
|
||||
run_no: 'RUN-PROC',
|
||||
can_append: true,
|
||||
recently_created: true,
|
||||
focused: true,
|
||||
}],
|
||||
completed: [{
|
||||
user_task_no: 'OT-DONE',
|
||||
group: 'completed',
|
||||
status_label: 'completed',
|
||||
title: 'done.pdf',
|
||||
file_count: 1,
|
||||
run_no: 'RUN-DONE',
|
||||
can_append: false,
|
||||
available_actions: ['view_details'],
|
||||
}],
|
||||
history: [{
|
||||
user_task_no: 'OT-HIST',
|
||||
group: 'history',
|
||||
status_label: 'completed',
|
||||
file_count: 1,
|
||||
run_no: 'RUN-HIST',
|
||||
can_append: false,
|
||||
viewed: true,
|
||||
}],
|
||||
};
|
||||
}
|
||||
|
||||
describe('ShippingConversationProcessingCard', () => {
|
||||
it('renders needs_action / processing / completed groups, hides history on the right panel', async () => {
|
||||
const wrapper = mount(ShippingConversationProcessingCard, {
|
||||
props: { projection: buildProjection() },
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
await flushPromises();
|
||||
|
||||
expect(wrapper.find('[data-testid="shipping-conversation-processing-card"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="shipping-processing-group-needs_action"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="shipping-processing-group-processing"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="shipping-processing-group-completed"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="shipping-processing-task-OT-NEED"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="shipping-processing-task-OT-PROC"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="shipping-processing-task-OT-DONE"]').exists()).toBe(true);
|
||||
expect(wrapper.text()).toContain('刚刚创建');
|
||||
expect(wrapper.text()).toContain('已完成');
|
||||
// UI-04:右侧不展示处理记录分组。
|
||||
expect(wrapper.find('[data-testid="shipping-processing-group-history"]').exists()).toBe(false);
|
||||
expect(wrapper.find('[data-testid="shipping-processing-task-OT-HIST"]').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it('renders multi-PDF task title instead of first filename', async () => {
|
||||
const wrapper = mount(ShippingConversationProcessingCard, {
|
||||
props: {
|
||||
projection: {
|
||||
summary: { total_tasks: 1, processing: 0, needs_action: 1, completed: 0, history: 0 },
|
||||
needs_action: [{
|
||||
user_task_no: 'OT-MULTI',
|
||||
group: 'needs_action',
|
||||
status_label: 'pending_review',
|
||||
title: null,
|
||||
display_kind: 'multi_document_task',
|
||||
document_names: ['4518838152.pdf', '4518838154.pdf'],
|
||||
file_count: 2,
|
||||
run_no: 'RUN-MULTI',
|
||||
can_append: false,
|
||||
available_actions: ['view_details', 'cancel_task'],
|
||||
}],
|
||||
processing: [],
|
||||
completed: [],
|
||||
history: [],
|
||||
},
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
await flushPromises();
|
||||
expect(wrapper.text()).toContain('订单识别任务');
|
||||
expect(wrapper.text()).toContain('2 个 PDF');
|
||||
expect(wrapper.text()).toContain('4518838152.pdf、4518838154.pdf');
|
||||
expect(wrapper.text()).toContain('取消整个任务');
|
||||
// 主标题不得单独伪装成首个 PDF 文件名任务。
|
||||
const titleEl = wrapper.find('[data-testid="shipping-processing-task-OT-MULTI"] .text-sm.font-semibold');
|
||||
expect(titleEl.text()).toContain('订单识别任务');
|
||||
expect(titleEl.text()).not.toContain('4518838152.pdf');
|
||||
});
|
||||
|
||||
it('shows multi-document title from authoritative projection without workflow fallback', async () => {
|
||||
const wrapper = mount(ShippingConversationProcessingCard, {
|
||||
props: {
|
||||
projection: {
|
||||
summary: { total_tasks: 1, total_files: 2, processing: 0, needs_action: 1, completed: 0, history: 0 },
|
||||
needs_action: [{
|
||||
user_task_no: 'OT-MULTI',
|
||||
group: 'needs_action',
|
||||
status_label: 'pending_review',
|
||||
title: null,
|
||||
display_kind: 'multi_document_task',
|
||||
document_names: ['4518838152.pdf', '4518838154.pdf'],
|
||||
file_count: 2,
|
||||
run_no: 'RUN-MULTI',
|
||||
can_append: false,
|
||||
available_actions: ['view_details', 'cancel_task'],
|
||||
objects: [],
|
||||
}],
|
||||
processing: [],
|
||||
completed: [],
|
||||
history: [],
|
||||
},
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
await flushPromises();
|
||||
expect(wrapper.text()).toContain('订单识别任务');
|
||||
expect(wrapper.text()).toContain('2 个 PDF');
|
||||
const titleEl = wrapper.find('[data-testid="shipping-processing-task-OT-MULTI"] .text-sm.font-semibold');
|
||||
expect(titleEl.text()).toContain('订单识别任务');
|
||||
expect(titleEl.text()).not.toContain('4518838152.pdf');
|
||||
});
|
||||
|
||||
it('falls back to unnamed PDF instead of internal OT number', async () => {
|
||||
const wrapper = mount(ShippingConversationProcessingCard, {
|
||||
props: {
|
||||
projection: {
|
||||
summary: { total_tasks: 1, processing: 1, needs_action: 0, completed: 0, history: 0 },
|
||||
needs_action: [],
|
||||
processing: [{
|
||||
user_task_no: 'OT-20260803-A13F95D2',
|
||||
group: 'processing',
|
||||
status_label: 'processing',
|
||||
title: null,
|
||||
file_count: 1,
|
||||
run_no: 'SNER-X',
|
||||
can_append: false,
|
||||
}],
|
||||
completed: [],
|
||||
history: [],
|
||||
},
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
await flushPromises();
|
||||
expect(wrapper.text()).toContain('未命名 PDF');
|
||||
expect(wrapper.text()).not.toContain('20260803-A13F95D2');
|
||||
});
|
||||
|
||||
it('emits focus only when selecting a task (not viewed)', async () => {
|
||||
const wrapper = mount(ShippingConversationProcessingCard, {
|
||||
props: { projection: buildProjection() },
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
await flushPromises();
|
||||
await wrapper.find('[data-testid="shipping-processing-task-OT-NEED"] button').trigger('click');
|
||||
expect(wrapper.emitted('focus')?.[0]).toEqual(['OT-NEED']);
|
||||
expect(wrapper.emitted('viewed')).toBeUndefined();
|
||||
expect(wrapper.emitted('expandFiles')).toBeUndefined();
|
||||
});
|
||||
|
||||
it('applies visible focus ring on needs_action card when focused', async () => {
|
||||
const wrapper = mount(ShippingConversationProcessingCard, {
|
||||
props: {
|
||||
projection: {
|
||||
...buildProjection(),
|
||||
focused_task_no: 'OT-NEED',
|
||||
},
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
await flushPromises();
|
||||
const needCard = wrapper.find('[data-testid="shipping-processing-task-OT-NEED"]');
|
||||
// 关键断言:待操作聚焦卡必须有用户可见 ring,不能只写 data-focused。
|
||||
expect(needCard.attributes('data-focused')).toBe('1');
|
||||
expect(needCard.classes().join(' ')).toContain('ring-brand-400');
|
||||
const other = wrapper.find('[data-testid="shipping-processing-task-OT-PROC"]');
|
||||
expect(other.attributes('data-focused')).toBe('0');
|
||||
expect(other.classes().join(' ')).not.toContain('ring-brand-400');
|
||||
});
|
||||
|
||||
it('emits expandFiles / collapseFiles when toggling file details', async () => {
|
||||
const wrapper = mount(ShippingConversationProcessingCard, {
|
||||
props: {
|
||||
projection: {
|
||||
...buildProjection(),
|
||||
needs_action: [{
|
||||
...buildProjection().needs_action[0],
|
||||
available_actions: ['view_details', 'open_review', 'cancel_task'],
|
||||
}],
|
||||
},
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
await flushPromises();
|
||||
const taskRoot = wrapper.find('[data-testid="shipping-processing-task-OT-NEED"]');
|
||||
const buttons = taskRoot.findAll('button');
|
||||
// 最后一个按钮是展开/收起文件详情
|
||||
await buttons[buttons.length - 1].trigger('click');
|
||||
expect(wrapper.emitted('expandFiles')?.[0]?.[0]).toMatchObject({ user_task_no: 'OT-NEED' });
|
||||
await buttons[buttons.length - 1].trigger('click');
|
||||
expect(wrapper.emitted('collapseFiles')).toBeTruthy();
|
||||
});
|
||||
|
||||
it('renders twenty processing tasks in one top-level container', async () => {
|
||||
const processing = Array.from({ length: 20 }, (_, index) => ({
|
||||
user_task_no: `OT-${index}`,
|
||||
group: 'processing' as const,
|
||||
status_label: 'extracting',
|
||||
file_count: 1,
|
||||
run_no: `RUN-${index}`,
|
||||
can_append: false,
|
||||
}));
|
||||
const wrapper = mount(ShippingConversationProcessingCard, {
|
||||
props: {
|
||||
projection: {
|
||||
summary: { total_tasks: 20, processing: 20, needs_action: 0, history: 0 },
|
||||
needs_action: [],
|
||||
processing,
|
||||
history: [],
|
||||
},
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
await flushPromises();
|
||||
expect(wrapper.findAll('[data-testid^="shipping-processing-task-"]')).toHaveLength(20);
|
||||
expect(wrapper.findAll('[data-testid="shipping-conversation-processing-card"]')).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('renders pending order_intake work items above task groups', async () => {
|
||||
const wrapper = mount(ShippingConversationProcessingCard, {
|
||||
props: {
|
||||
projection: null,
|
||||
workItems: [{
|
||||
workItemType: 'order_intake',
|
||||
workItemNo: 'SNI-1',
|
||||
sourceType: 'direct_pdf',
|
||||
rootOrderTaskNo: null,
|
||||
shippingNoticeNo: null,
|
||||
conversationId: 'conv-1',
|
||||
submissionNo: 'SOS-1',
|
||||
intakeNo: 'SNI-1',
|
||||
status: 'failed',
|
||||
stage: 'document_parsing',
|
||||
progressVersion: 1,
|
||||
lastActivityAt: '2026-08-04T12:00:00Z',
|
||||
currentGate: {
|
||||
gateCode: 'intake_document_parse',
|
||||
status: 'blocked',
|
||||
nextActionCode: 'retry_parse',
|
||||
blockingReasonCode: 'SHIPPING_NOTICE.INTAKE_PARSE_FAILED',
|
||||
attemptNo: 2,
|
||||
},
|
||||
availableActions: ['view_details', 'retry_parse'],
|
||||
sourceSummary: {
|
||||
emailSubject: null,
|
||||
filename: 'po.pdf',
|
||||
documentCount: 1,
|
||||
parsedDocumentCount: 0,
|
||||
candidateCount: 0,
|
||||
customerName: null,
|
||||
poNumber: null,
|
||||
failureReasonCode: 'SHIPPING_NOTICE.INTAKE_PARSE_FAILED',
|
||||
parseAttemptCount: 2,
|
||||
assetStatus: 'ready',
|
||||
},
|
||||
childOrderTasks: [],
|
||||
}],
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
await flushPromises();
|
||||
expect(wrapper.find('[data-testid="shipping-processing-group-order-intake"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="shipping-processing-intake-SNI-1"]').exists()).toBe(true);
|
||||
expect(wrapper.text()).toContain('po.pdf');
|
||||
// 关键断言:失败恢复元信息(原因 / Attempt / 资产)出现在材料卡。
|
||||
expect(wrapper.find('[data-testid="shipping-processing-intake-recovery"]').exists()).toBe(true);
|
||||
expect(wrapper.text()).toContain('SHIPPING_NOTICE.INTAKE_PARSE_FAILED');
|
||||
await wrapper.find('[data-testid="shipping-processing-intake-action-retry_parse"]').trigger('click');
|
||||
expect(wrapper.emitted('intakeAction')?.[0]?.[0]).toMatchObject({
|
||||
action: 'retry_parse',
|
||||
item: { workItemNo: 'SNI-1' },
|
||||
});
|
||||
});
|
||||
});
|
||||
+686
@@ -0,0 +1,686 @@
|
||||
/**
|
||||
* features/chat/components/shipping/ShippingConversationProcessingCard.vue
|
||||
* 用途:右侧「本次处理中」顶层任务卡——按 needs_action / processing / completed 展示。
|
||||
* 依赖:vue-i18n、ConversationProcessingProjection、conversationProcessingState、
|
||||
* shippingProcessingLabels。
|
||||
* 逻辑:由 ShippingWorkflowTimeline 嵌入;只消费统一 projection / workItems,禁止 Workflow fallback;
|
||||
* 单 PDF 主标题用文件名,多 PDF 用「订单识别任务」;右侧不渲染 history;
|
||||
* 任务级操作只消费后端 available_actions;另渲染尚未建 OT 的 order_intake 材料卡。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import { computed, watch } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { ChevronDown, ChevronRight } from 'lucide-vue-next';
|
||||
import type {
|
||||
ConversationProcessingProjection,
|
||||
ConversationProcessingUserTask,
|
||||
ShippingProcessingProjection,
|
||||
} from '@/features/chat/types/shipping.api.types';
|
||||
import {
|
||||
createConversationProcessingUiState,
|
||||
focusTaskManually,
|
||||
markTaskViewed,
|
||||
resetConversationProcessingUiState,
|
||||
resolveFocusedTask,
|
||||
shouldExpandTaskDetails,
|
||||
toggleTaskDetails,
|
||||
} from '@/features/chat/shipping/conversationProcessingState';
|
||||
import {
|
||||
resolveShippingProcessingMessage,
|
||||
resolveShippingProcessingStatusLabel,
|
||||
shippingProcessingSourceTypeKey,
|
||||
shippingProcessingStageKey,
|
||||
} from '@/features/chat/shipping/shippingProcessingLabels';
|
||||
|
||||
const props = defineProps<{
|
||||
projection: ConversationProcessingProjection | null;
|
||||
/** 统一 ShippingProcessing work_items(含 order_intake) */
|
||||
workItems?: ShippingProcessingProjection[] | null;
|
||||
/** 当前会话 ID;切换时重置本地焦点/展开状态 */
|
||||
conversationId?: string | null;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
focus: [taskNo: string];
|
||||
viewed: [taskNo: string];
|
||||
/** 请求展开某任务下的文件列表(由 Timeline 按 OT objects 合成) */
|
||||
expandFiles: [task: ConversationProcessingUserTask];
|
||||
/** 收起文件详情:父级应清空过滤并隐藏文件列表 */
|
||||
collapseFiles: [];
|
||||
/** 任务级权威操作(后端 available_actions) */
|
||||
taskAction: [payload: { task: ConversationProcessingUserTask; action: string }];
|
||||
/** Intake 级统一投影动作(如 retry_parse) */
|
||||
intakeAction: [payload: { item: ShippingProcessingProjection; action: string }];
|
||||
}>();
|
||||
|
||||
const { t, te } = useI18n();
|
||||
const uiState = createConversationProcessingUiState();
|
||||
|
||||
/** 唯一进度源:统一 conversation_processing / work_items 合成投影。 */
|
||||
const activeProjection = computed((): ConversationProcessingProjection | null => (
|
||||
props.projection || null
|
||||
));
|
||||
|
||||
/** 尚未建 OT、仍应展示在「待处理材料」的 Intake 工作项。 */
|
||||
const pendingIntakeItems = computed((): ShippingProcessingProjection[] => {
|
||||
const items = Array.isArray(props.workItems) ? props.workItems : [];
|
||||
return items.filter((item) => {
|
||||
if (item.workItemType !== 'order_intake') return false;
|
||||
return !['completed', 'cancelled'].includes(String(item.status || ''));
|
||||
});
|
||||
});
|
||||
|
||||
const hasContent = computed(() => Boolean(
|
||||
activeProjection.value
|
||||
|| pendingIntakeItems.value.length,
|
||||
));
|
||||
|
||||
const completedTasks = computed(() => activeProjection.value?.completed || []);
|
||||
|
||||
const focusedTaskNo = computed(() => resolveFocusedTask(uiState, {
|
||||
serverFocusedTaskNo: activeProjection.value?.focused_task_no,
|
||||
recentTaskNo: activeProjection.value?.recent_task_no,
|
||||
}));
|
||||
|
||||
/**
|
||||
* 切会话时重置本地焦点/展开,避免跨会话残留。
|
||||
*/
|
||||
watch(
|
||||
() => String(props.conversationId || '').trim(),
|
||||
(next, prev) => {
|
||||
if (next === prev) return;
|
||||
resetConversationProcessingUiState(uiState);
|
||||
},
|
||||
);
|
||||
|
||||
/**
|
||||
* 点击任务卡:只聚焦,不标记正式 viewed、不强制展开文件。
|
||||
* 非权威任务号仅更新本地 UI 焦点,不向后端 focus 写接口。
|
||||
*/
|
||||
function onSelectTask(task: ConversationProcessingUserTask) {
|
||||
const taskNo = String(task.user_task_no || '').trim();
|
||||
if (!taskNo) return;
|
||||
focusTaskManually(uiState, taskNo, { expandDetails: false });
|
||||
if (task.user_task_authoritative === false) return;
|
||||
emit('focus', taskNo);
|
||||
}
|
||||
|
||||
/**
|
||||
* 切换文件详情展开;展开时通知父级过滤,收起时清空过滤。
|
||||
*/
|
||||
function onToggleDetails(task: ConversationProcessingUserTask) {
|
||||
const taskNo = String(task.user_task_no || '').trim();
|
||||
if (!taskNo) return;
|
||||
toggleTaskDetails(uiState, taskNo);
|
||||
if (uiState.expandedDetailTaskNo === taskNo) {
|
||||
markTaskViewed(uiState, taskNo);
|
||||
emit('expandFiles', task);
|
||||
} else {
|
||||
emit('collapseFiles');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 是否为多 PDF 任务卡(禁止用首个文件名伪装单文件任务)。
|
||||
*/
|
||||
function isMultiDocumentTask(task: ConversationProcessingUserTask): boolean {
|
||||
if (String(task.display_kind || '').trim() === 'multi_document_task') return true;
|
||||
if (Number(task.file_count || 0) > 1) return true;
|
||||
return Array.isArray(task.document_names) && task.document_names.length > 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* 任务主标题:单 PDF 用文件名;多 PDF 用 i18n「订单识别任务」;禁止 OT/Run 编号。
|
||||
*/
|
||||
function taskLabel(task: ConversationProcessingUserTask): string {
|
||||
if (isMultiDocumentTask(task)) {
|
||||
return t('chat.shippingProcessing.multiPdfTaskTitle');
|
||||
}
|
||||
const title = String(task.title || '').trim();
|
||||
if (title) return title;
|
||||
return t('chat.shippingProcessing.unnamedPdf');
|
||||
}
|
||||
|
||||
/**
|
||||
* 多 PDF 副标题:前两个文件名;超过两个时追加「等 N 个 PDF」。
|
||||
*/
|
||||
function documentNamesPreview(task: ConversationProcessingUserTask): string {
|
||||
const names = (Array.isArray(task.document_names) ? task.document_names : [])
|
||||
.map((name) => String(name || '').trim())
|
||||
.filter(Boolean);
|
||||
if (names.length <= 1) return '';
|
||||
const head = names.slice(0, 2).join(t('chat.shippingProcessing.multiPdfNameSeparator'));
|
||||
if (names.length === 2) return head;
|
||||
return t('chat.shippingProcessing.multiPdfNamesMore', {
|
||||
names: head,
|
||||
count: names.length,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 文件数量文案:多 PDF 用「N 个 PDF」,单文件仍用「N 个文件」。
|
||||
*/
|
||||
function fileCountLabel(task: ConversationProcessingUserTask): string {
|
||||
const count = Number(task.file_count || 0);
|
||||
if (count <= 0) return '';
|
||||
if (isMultiDocumentTask(task)) {
|
||||
return t('chat.shippingProcessing.taskPdfCount', { count });
|
||||
}
|
||||
return t('chat.shippingProcessing.taskFiles', { count });
|
||||
}
|
||||
|
||||
/**
|
||||
* 任务状态文案:优先统一 shippingProcessing,回退 shippingWorkflow。
|
||||
*/
|
||||
function statusLabel(task: ConversationProcessingUserTask): string {
|
||||
return resolveShippingProcessingStatusLabel(String(task.status_label || ''), te, t);
|
||||
}
|
||||
|
||||
/**
|
||||
* 最近活动时间:当天仅时分;昨天带「昨天」;更早带月日。
|
||||
*/
|
||||
function activityLabel(task: ConversationProcessingUserTask): string {
|
||||
const raw = String(task.last_activity_at || '').trim();
|
||||
if (!raw) return '';
|
||||
const date = new Date(raw);
|
||||
if (Number.isNaN(date.getTime())) return '';
|
||||
const hh = String(date.getHours()).padStart(2, '0');
|
||||
const mm = String(date.getMinutes()).padStart(2, '0');
|
||||
const time = `${hh}:${mm}`;
|
||||
const now = new Date();
|
||||
const startOfToday = new Date(now.getFullYear(), now.getMonth(), now.getDate());
|
||||
const startOfTarget = new Date(date.getFullYear(), date.getMonth(), date.getDate());
|
||||
const dayDiff = Math.round((startOfToday.getTime() - startOfTarget.getTime()) / 86400000);
|
||||
if (dayDiff === 0) {
|
||||
return t('chat.shippingProcessing.updatedAt', { time });
|
||||
}
|
||||
if (dayDiff === 1) {
|
||||
return t('chat.shippingProcessing.updatedYesterday', { time });
|
||||
}
|
||||
const month = String(date.getMonth() + 1).padStart(2, '0');
|
||||
const day = String(date.getDate()).padStart(2, '0');
|
||||
return t('chat.shippingProcessing.updatedOnDate', { date: `${month}-${day}`, time });
|
||||
}
|
||||
|
||||
/**
|
||||
* 是否高亮 needs_action 任务。
|
||||
*/
|
||||
function isNeedsActionHighlight(task: ConversationProcessingUserTask): boolean {
|
||||
return task.group === 'needs_action';
|
||||
}
|
||||
|
||||
/**
|
||||
* 是否展开该任务的文件详情区。
|
||||
*/
|
||||
function isDetailsExpanded(task: ConversationProcessingUserTask): boolean {
|
||||
return shouldExpandTaskDetails(uiState, task.user_task_no, {
|
||||
focusedTaskNo: focusedTaskNo.value,
|
||||
forceExpand: false,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 任务级可见操作:只展示后端权威动作中的业务入口。
|
||||
*/
|
||||
function visibleTaskActions(task: ConversationProcessingUserTask): string[] {
|
||||
const actions = Array.isArray(task.available_actions) ? task.available_actions : [];
|
||||
const preferred = [
|
||||
'view_details',
|
||||
'open_review',
|
||||
'enter_manual_review',
|
||||
'retry_failed_documents',
|
||||
'retry_failed_attachments',
|
||||
'cancel_task',
|
||||
'cancel_run',
|
||||
];
|
||||
const seen = new Set<string>();
|
||||
const result: string[] = [];
|
||||
for (const code of preferred) {
|
||||
if (!actions.includes(code) || seen.has(code)) continue;
|
||||
// 别名去重:只保留一套展示
|
||||
if (code === 'open_review' && seen.has('enter_manual_review')) continue;
|
||||
if (code === 'enter_manual_review' && seen.has('open_review')) continue;
|
||||
if (code === 'retry_failed_documents' && seen.has('retry_failed_attachments')) continue;
|
||||
if (code === 'retry_failed_attachments' && seen.has('retry_failed_documents')) continue;
|
||||
if (code === 'cancel_task' && seen.has('cancel_run')) continue;
|
||||
if (code === 'cancel_run' && seen.has('cancel_task')) continue;
|
||||
seen.add(code);
|
||||
result.push(code);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 动作按钮文案:任务级取消在多 PDF 时明确为「取消整个任务」。
|
||||
*/
|
||||
function actionLabel(task: ConversationProcessingUserTask, action: string): string {
|
||||
const code = String(action || '').trim();
|
||||
if (
|
||||
(code === 'cancel_task' || code === 'cancel_run')
|
||||
&& isMultiDocumentTask(task)
|
||||
) {
|
||||
return t('chat.shippingProcessing.cancelEntireTask');
|
||||
}
|
||||
if (code === 'cancel_task' || code === 'cancel_run') {
|
||||
return t('chat.shippingProcessing.cancelEntireTaskSingle');
|
||||
}
|
||||
const extractionKey = `chat.shippingOrderExtractionAction.${code}`;
|
||||
if (te(extractionKey)) return t(extractionKey);
|
||||
const aliases: Record<string, string> = {
|
||||
open_review: 'chat.shippingOrderExtractionAction.enter_manual_review',
|
||||
retry_failed_documents: 'chat.shippingOrderExtractionAction.retry_failed_attachments',
|
||||
};
|
||||
const alias = aliases[code];
|
||||
if (alias && te(alias)) return t(alias);
|
||||
return code;
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行任务级动作:view_details 展开文件;其余交给父级。
|
||||
* 非权威任务号禁止向后端 focus/viewed 写接口。
|
||||
*/
|
||||
function onTaskAction(task: ConversationProcessingUserTask, action: string) {
|
||||
const code = String(action || '').trim();
|
||||
if (!code) return;
|
||||
if (code === 'view_details') {
|
||||
focusTaskManually(uiState, task.user_task_no, { expandDetails: true });
|
||||
markTaskViewed(uiState, task.user_task_no);
|
||||
emit('expandFiles', task);
|
||||
if (task.user_task_authoritative !== false) {
|
||||
emit('focus', task.user_task_no);
|
||||
emit('viewed', task.user_task_no);
|
||||
}
|
||||
return;
|
||||
}
|
||||
emit('taskAction', { task, action: code });
|
||||
}
|
||||
|
||||
/**
|
||||
* Intake 材料标题:文件名 / 邮件主题 / Intake 编号。
|
||||
*/
|
||||
function intakeTitle(item: ShippingProcessingProjection): string {
|
||||
return String(
|
||||
item.sourceSummary?.filename
|
||||
|| item.sourceSummary?.emailSubject
|
||||
|| item.workItemNo
|
||||
|| '',
|
||||
).trim() || item.workItemNo;
|
||||
}
|
||||
|
||||
/**
|
||||
* Intake 状态文案。
|
||||
*/
|
||||
function intakeStatusLabel(item: ShippingProcessingProjection): string {
|
||||
return resolveShippingProcessingStatusLabel(item.status, te, t);
|
||||
}
|
||||
|
||||
/**
|
||||
* Intake 阶段文案。
|
||||
*/
|
||||
function intakeStageLabel(item: ShippingProcessingProjection): string {
|
||||
const key = shippingProcessingStageKey(item.stage);
|
||||
return te(key) ? t(key) : String(item.stage || '');
|
||||
}
|
||||
|
||||
/**
|
||||
* Intake 来源类型文案。
|
||||
*/
|
||||
function intakeSourceLabel(item: ShippingProcessingProjection): string {
|
||||
const key = shippingProcessingSourceTypeKey(item.sourceType);
|
||||
return te(key) ? t(key) : String(item.sourceType || '');
|
||||
}
|
||||
|
||||
/**
|
||||
* Intake / OT 门禁与失败恢复元信息(Gate / Attempt / 资产状态)。
|
||||
*/
|
||||
function intakeRecoveryMeta(item: ShippingProcessingProjection): string[] {
|
||||
const parts: string[] = [];
|
||||
const gate = item.currentGate;
|
||||
const reason = String(
|
||||
gate?.blockingReasonCode
|
||||
|| item.sourceSummary?.failureReasonCode
|
||||
|| '',
|
||||
).trim();
|
||||
if (reason) {
|
||||
parts.push(t('chat.shippingProcessing.failureReason', { code: reason }));
|
||||
}
|
||||
const attempt = gate?.attemptNo ?? item.sourceSummary?.parseAttemptCount;
|
||||
if (attempt != null && Number(attempt) > 0) {
|
||||
parts.push(t('chat.shippingProcessing.parseAttempt', { count: Number(attempt) }));
|
||||
}
|
||||
const assetStatus = String(item.sourceSummary?.assetStatus || '').trim();
|
||||
if (assetStatus) {
|
||||
const key = `chat.shippingProcessing.assetStatus.${assetStatus}`;
|
||||
parts.push(te(key) ? t(key) : t('chat.shippingProcessing.assetStatusLabel', { status: assetStatus }));
|
||||
}
|
||||
if (gate?.gateCode) {
|
||||
parts.push(t('chat.shippingProcessing.gateCode', { code: gate.gateCode }));
|
||||
}
|
||||
return parts;
|
||||
}
|
||||
|
||||
/**
|
||||
* Intake 可见动作(仅展示 retry_parse)。
|
||||
*/
|
||||
function visibleIntakeActions(item: ShippingProcessingProjection): string[] {
|
||||
const actions = Array.isArray(item.availableActions) ? item.availableActions : [];
|
||||
return actions.filter((code) => code === 'retry_parse');
|
||||
}
|
||||
|
||||
/**
|
||||
* Intake 动作文案。
|
||||
*/
|
||||
function intakeActionLabel(action: string): string {
|
||||
if (action === 'retry_parse') return t('chat.shippingProcessing.retryFromFailure');
|
||||
return action;
|
||||
}
|
||||
|
||||
/**
|
||||
* 触发 Intake 级动作。
|
||||
*/
|
||||
function onIntakeAction(item: ShippingProcessingProjection, action: string) {
|
||||
const code = String(action || '').trim();
|
||||
if (!code) return;
|
||||
emit('intakeAction', { item, action: code });
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div
|
||||
v-if="hasContent"
|
||||
class="space-y-3"
|
||||
data-testid="shipping-conversation-processing-card"
|
||||
>
|
||||
<section
|
||||
v-if="pendingIntakeItems.length"
|
||||
data-testid="shipping-processing-group-order-intake"
|
||||
>
|
||||
<div class="mb-1.5 text-[11px] font-semibold uppercase tracking-wide text-violet-700 dark:text-violet-300">
|
||||
{{ t('chat.shippingProcessing.pendingMaterials') }}
|
||||
· {{ pendingIntakeItems.length }}
|
||||
</div>
|
||||
<div class="space-y-2">
|
||||
<article
|
||||
v-for="item in pendingIntakeItems"
|
||||
:key="item.workItemNo"
|
||||
class="rounded-lg border border-default bg-surface px-2.5 py-2"
|
||||
:data-testid="`shipping-processing-intake-${item.workItemNo}`"
|
||||
:data-source-type="item.sourceType"
|
||||
:data-status="item.status"
|
||||
>
|
||||
<div class="text-sm font-semibold text-primary">
|
||||
{{ intakeTitle(item) }}
|
||||
</div>
|
||||
<div class="mt-0.5 flex flex-wrap gap-x-2 gap-y-0.5 text-[11px] text-secondary">
|
||||
<span>{{ intakeSourceLabel(item) }}</span>
|
||||
<span>{{ intakeStatusLabel(item) }}</span>
|
||||
<span v-if="intakeStageLabel(item)">{{ intakeStageLabel(item) }}</span>
|
||||
</div>
|
||||
<div
|
||||
v-if="intakeRecoveryMeta(item).length"
|
||||
class="mt-1 flex flex-wrap gap-x-2 gap-y-0.5 text-[11px] text-rose-700 dark:text-rose-300"
|
||||
data-testid="shipping-processing-intake-recovery"
|
||||
>
|
||||
<span
|
||||
v-for="(meta, idx) in intakeRecoveryMeta(item)"
|
||||
:key="`${item.workItemNo}-meta-${idx}`"
|
||||
>{{ meta }}</span>
|
||||
</div>
|
||||
<div
|
||||
v-if="visibleIntakeActions(item).length"
|
||||
class="mt-1.5 flex flex-wrap gap-1.5"
|
||||
data-testid="shipping-processing-intake-actions"
|
||||
>
|
||||
<button
|
||||
v-for="action in visibleIntakeActions(item)"
|
||||
:key="`${item.workItemNo}-${action}`"
|
||||
type="button"
|
||||
class="rounded-md border border-default bg-surface px-2 py-0.5 text-[11px] text-secondary hover:text-primary"
|
||||
:data-testid="`shipping-processing-intake-action-${action}`"
|
||||
@click="onIntakeAction(item, action)"
|
||||
>
|
||||
{{ intakeActionLabel(action) }}
|
||||
</button>
|
||||
</div>
|
||||
</article>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section
|
||||
v-if="activeProjection?.needs_action.length"
|
||||
data-testid="shipping-processing-group-needs_action"
|
||||
>
|
||||
<div class="mb-1.5 text-[11px] font-semibold uppercase tracking-wide text-amber-700 dark:text-amber-300">
|
||||
{{ resolveShippingProcessingMessage('groupNeedsAction', te, t, { count: activeProjection.needs_action.length }) }}
|
||||
</div>
|
||||
<div class="space-y-2">
|
||||
<article
|
||||
v-for="task in activeProjection.needs_action"
|
||||
:key="task.user_task_no"
|
||||
class="rounded-lg border px-2.5 py-2 transition"
|
||||
:class="[
|
||||
isNeedsActionHighlight(task)
|
||||
? 'border-amber-400 bg-amber-50/80 dark:border-amber-700 dark:bg-amber-950/30'
|
||||
: 'border-default bg-surface',
|
||||
focusedTaskNo === task.user_task_no ? 'ring-1 ring-brand-400' : '',
|
||||
]"
|
||||
:data-testid="`shipping-processing-task-${task.user_task_no}`"
|
||||
:data-focused="focusedTaskNo === task.user_task_no ? '1' : '0'"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
class="w-full text-left"
|
||||
@click="onSelectTask(task)"
|
||||
>
|
||||
<div class="text-sm font-semibold text-primary">
|
||||
{{ resolveShippingProcessingMessage('taskTitle', te, t, { label: taskLabel(task) }) }}
|
||||
</div>
|
||||
<div class="mt-0.5 flex flex-wrap gap-x-2 gap-y-0.5 text-[11px] text-secondary">
|
||||
<span v-if="fileCountLabel(task)">{{ fileCountLabel(task) }}</span>
|
||||
<span>{{ statusLabel(task) }}</span>
|
||||
<span v-if="activityLabel(task)">{{ activityLabel(task) }}</span>
|
||||
</div>
|
||||
<div
|
||||
v-if="documentNamesPreview(task)"
|
||||
class="mt-0.5 truncate text-[11px] text-muted"
|
||||
data-testid="shipping-processing-task-document-names"
|
||||
>
|
||||
{{ documentNamesPreview(task) }}
|
||||
</div>
|
||||
<div
|
||||
v-if="task.recent_append_count"
|
||||
class="mt-1 text-[11px] font-medium text-brand-700 dark:text-brand-300"
|
||||
>
|
||||
{{ resolveShippingProcessingMessage('justAppended', te, t, { count: task.recent_append_count }) }}
|
||||
</div>
|
||||
<div
|
||||
v-else-if="task.recently_created"
|
||||
class="mt-1 text-[11px] font-medium text-brand-700 dark:text-brand-300"
|
||||
>
|
||||
{{ resolveShippingProcessingMessage('justCreated', te, t) }}
|
||||
</div>
|
||||
</button>
|
||||
<div
|
||||
v-if="visibleTaskActions(task).length"
|
||||
class="mt-1.5 flex flex-wrap gap-1.5"
|
||||
data-testid="shipping-processing-task-actions"
|
||||
>
|
||||
<button
|
||||
v-for="action in visibleTaskActions(task)"
|
||||
:key="`${task.user_task_no}-${action}`"
|
||||
type="button"
|
||||
class="rounded-md border border-default bg-surface px-2 py-0.5 text-[11px] text-secondary hover:text-primary"
|
||||
:data-testid="`shipping-processing-action-${action}`"
|
||||
@click="onTaskAction(task, action)"
|
||||
>
|
||||
{{ actionLabel(task, action) }}
|
||||
</button>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
class="mt-1.5 flex items-center gap-1 text-[11px] text-secondary hover:text-primary"
|
||||
@click="onToggleDetails(task)"
|
||||
>
|
||||
<ChevronDown v-if="isDetailsExpanded(task)" class="h-3 w-3" />
|
||||
<ChevronRight v-else class="h-3 w-3" />
|
||||
{{ isDetailsExpanded(task)
|
||||
? t('chat.shippingProcessing.collapseFileDetails')
|
||||
: t('chat.shippingProcessing.expandFileDetails') }}
|
||||
</button>
|
||||
</article>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section
|
||||
v-if="activeProjection?.processing.length"
|
||||
data-testid="shipping-processing-group-processing"
|
||||
>
|
||||
<div class="mb-1.5 text-[11px] font-semibold uppercase tracking-wide text-sky-700 dark:text-sky-300">
|
||||
{{ resolveShippingProcessingMessage('groupProcessing', te, t, { count: activeProjection.processing.length }) }}
|
||||
</div>
|
||||
<div class="space-y-2">
|
||||
<article
|
||||
v-for="task in activeProjection.processing"
|
||||
:key="task.user_task_no"
|
||||
class="rounded-lg border border-default bg-surface px-2.5 py-2"
|
||||
:class="focusedTaskNo === task.user_task_no
|
||||
? 'ring-1 ring-brand-400'
|
||||
: ''"
|
||||
:data-testid="`shipping-processing-task-${task.user_task_no}`"
|
||||
:data-focused="focusedTaskNo === task.user_task_no ? '1' : '0'"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
class="w-full text-left"
|
||||
@click="onSelectTask(task)"
|
||||
>
|
||||
<div class="text-sm font-semibold text-primary">
|
||||
{{ resolveShippingProcessingMessage('taskTitle', te, t, { label: taskLabel(task) }) }}
|
||||
</div>
|
||||
<div class="mt-0.5 flex flex-wrap gap-x-2 gap-y-0.5 text-[11px] text-secondary">
|
||||
<span v-if="fileCountLabel(task)">{{ fileCountLabel(task) }}</span>
|
||||
<span>{{ statusLabel(task) }}</span>
|
||||
<span v-if="activityLabel(task)">{{ activityLabel(task) }}</span>
|
||||
</div>
|
||||
<div
|
||||
v-if="documentNamesPreview(task)"
|
||||
class="mt-0.5 truncate text-[11px] text-muted"
|
||||
data-testid="shipping-processing-task-document-names"
|
||||
>
|
||||
{{ documentNamesPreview(task) }}
|
||||
</div>
|
||||
<div
|
||||
v-if="task.recent_append_count"
|
||||
class="mt-1 text-[11px] font-medium text-brand-700 dark:text-brand-300"
|
||||
>
|
||||
{{ resolveShippingProcessingMessage('justAppended', te, t, { count: task.recent_append_count }) }}
|
||||
</div>
|
||||
<div
|
||||
v-else-if="task.recently_created"
|
||||
class="mt-1 text-[11px] font-medium text-brand-700 dark:text-brand-300"
|
||||
>
|
||||
{{ resolveShippingProcessingMessage('justCreated', te, t) }}
|
||||
</div>
|
||||
</button>
|
||||
<div
|
||||
v-if="visibleTaskActions(task).length"
|
||||
class="mt-1.5 flex flex-wrap gap-1.5"
|
||||
data-testid="shipping-processing-task-actions"
|
||||
>
|
||||
<button
|
||||
v-for="action in visibleTaskActions(task)"
|
||||
:key="`${task.user_task_no}-${action}`"
|
||||
type="button"
|
||||
class="rounded-md border border-default bg-surface px-2 py-0.5 text-[11px] text-secondary hover:text-primary"
|
||||
:data-testid="`shipping-processing-action-${action}`"
|
||||
@click="onTaskAction(task, action)"
|
||||
>
|
||||
{{ actionLabel(task, action) }}
|
||||
</button>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
class="mt-1.5 flex items-center gap-1 text-[11px] text-secondary hover:text-primary"
|
||||
@click="onToggleDetails(task)"
|
||||
>
|
||||
<ChevronDown v-if="isDetailsExpanded(task)" class="h-3 w-3" />
|
||||
<ChevronRight v-else class="h-3 w-3" />
|
||||
{{ isDetailsExpanded(task)
|
||||
? t('chat.shippingProcessing.collapseFileDetails')
|
||||
: t('chat.shippingProcessing.expandFileDetails') }}
|
||||
</button>
|
||||
</article>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section
|
||||
v-if="completedTasks.length"
|
||||
data-testid="shipping-processing-group-completed"
|
||||
>
|
||||
<div class="mb-1.5 text-[11px] font-semibold uppercase tracking-wide text-emerald-700 dark:text-emerald-300">
|
||||
{{ resolveShippingProcessingMessage('groupCompleted', te, t, { count: completedTasks.length }) }}
|
||||
</div>
|
||||
<div class="space-y-2">
|
||||
<article
|
||||
v-for="task in completedTasks"
|
||||
:key="task.user_task_no"
|
||||
class="rounded-lg border border-default bg-surface px-2.5 py-2"
|
||||
:class="focusedTaskNo === task.user_task_no
|
||||
? 'ring-1 ring-brand-400'
|
||||
: ''"
|
||||
:data-testid="`shipping-processing-task-${task.user_task_no}`"
|
||||
:data-focused="focusedTaskNo === task.user_task_no ? '1' : '0'"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
class="w-full text-left"
|
||||
@click="onSelectTask(task)"
|
||||
>
|
||||
<div class="text-sm font-semibold text-primary">
|
||||
{{ resolveShippingProcessingMessage('taskTitle', te, t, { label: taskLabel(task) }) }}
|
||||
</div>
|
||||
<div class="mt-0.5 flex flex-wrap gap-x-2 gap-y-0.5 text-[11px] text-secondary">
|
||||
<span v-if="fileCountLabel(task)">{{ fileCountLabel(task) }}</span>
|
||||
<span>{{ statusLabel(task) }}</span>
|
||||
<span v-if="activityLabel(task)">{{ activityLabel(task) }}</span>
|
||||
</div>
|
||||
<div
|
||||
v-if="documentNamesPreview(task)"
|
||||
class="mt-0.5 truncate text-[11px] text-muted"
|
||||
data-testid="shipping-processing-task-document-names"
|
||||
>
|
||||
{{ documentNamesPreview(task) }}
|
||||
</div>
|
||||
</button>
|
||||
<div
|
||||
v-if="visibleTaskActions(task).length"
|
||||
class="mt-1.5 flex flex-wrap gap-1.5"
|
||||
data-testid="shipping-processing-task-actions"
|
||||
>
|
||||
<button
|
||||
v-for="action in visibleTaskActions(task)"
|
||||
:key="`${task.user_task_no}-${action}`"
|
||||
type="button"
|
||||
class="rounded-md border border-default bg-surface px-2 py-0.5 text-[11px] text-secondary hover:text-primary"
|
||||
:data-testid="`shipping-processing-action-${action}`"
|
||||
@click="onTaskAction(task, action)"
|
||||
>
|
||||
{{ actionLabel(task, action) }}
|
||||
</button>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
class="mt-1.5 flex items-center gap-1 text-[11px] text-secondary hover:text-primary"
|
||||
@click="onToggleDetails(task)"
|
||||
>
|
||||
<ChevronDown v-if="isDetailsExpanded(task)" class="h-3 w-3" />
|
||||
<ChevronRight v-else class="h-3 w-3" />
|
||||
{{ isDetailsExpanded(task)
|
||||
? t('chat.shippingProcessing.collapseFileDetails')
|
||||
: t('chat.shippingProcessing.expandFileDetails') }}
|
||||
</button>
|
||||
</article>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
</template>
|
||||
@@ -2,12 +2,10 @@
|
||||
* features/chat/components/shipping/ShippingOrderExtractionCard.vue
|
||||
* 用途:聊天主区批次进度卡——摘要计数、Run 级处理事项、当前文件阶段、健康提醒与动作。
|
||||
* 依赖:订单抽取 Run 状态卡 DTO、shipping.api 文档/进度接口、ShippingOrderExtractionDetailsDrawer、
|
||||
* orderExtractionProgressDisplay、Workflow 计数投影、vue-router、vue-i18n。
|
||||
* 逻辑:有 Workflow 投影时优先展示统一 counts;否则回退 handling_items / primary_notice;
|
||||
* Run 失败优先展示 errorExplainability.message(含 request_id 提示),禁止只展示技术错误码;
|
||||
* 「查看处理详情」挂载详情抽屉;抽屉内证据/复核入口携带 focus+document_id 打开复核页;
|
||||
* 文档与时间线加载失败支持独立就地重试;右侧 ShippingWorkflowTimeline 承接逐 PDF 明细;
|
||||
* Gate confirm_customer 经 ChatPage 打开客户选择弹窗。
|
||||
* orderExtractionProgressDisplay、vue-router、vue-i18n、ProcessGateRecoveryCard。
|
||||
* 逻辑:回退 handling_items / primary_notice / Run summary;
|
||||
* Run 失败优先展示 errorExplainability.message;详情抽屉证据入口携带 focus+document_id;
|
||||
* Gate confirm_customer 经 ChatPage 打开客户选择弹窗;不再读取 Workflow 空壳 counts。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import { computed, inject, ref } from 'vue';
|
||||
@@ -23,7 +21,6 @@ import type {
|
||||
ShippingOrderExtractionDocumentResult,
|
||||
ShippingOrderExtractionProgressEvent,
|
||||
ShippingProcessGateUserSummary,
|
||||
ShippingWorkflowItemCounts,
|
||||
} from '../../types/shipping.api.types';
|
||||
import ProcessGateRecoveryCard from '@/features/shipping-process-gates/components/ProcessGateRecoveryCard.vue';
|
||||
import {
|
||||
@@ -39,7 +36,6 @@ import {
|
||||
type ShippingHandlingAffectedRef,
|
||||
type ShippingHandlingRefTarget,
|
||||
} from '../../shipping/orderExtractionHandlingRefs';
|
||||
import { SHIPPING_WORKFLOW_KEY } from '../../shipping/useShippingNoticeWorkflow';
|
||||
import ShippingOrderExtractionDetailsDrawer from './ShippingOrderExtractionDetailsDrawer.vue';
|
||||
|
||||
const props = defineProps<{
|
||||
@@ -48,8 +44,9 @@ const props = defineProps<{
|
||||
retrying?: boolean;
|
||||
refreshing?: boolean;
|
||||
cancelling?: boolean;
|
||||
/** 可选:父级传入的 Workflow 计数;优先于 Run summary。 */
|
||||
workflowSummary?: ShippingWorkflowItemCounts | null;
|
||||
/** 新版 Run 已替代旧版时,历史卡仅允许查看详情。 */
|
||||
readonly?: boolean;
|
||||
readonlyReason?: string | null;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
@@ -64,7 +61,6 @@ const router = useRouter();
|
||||
const chatPage = inject(CHAT_PAGE_KEY, null);
|
||||
const confirmCancelOpen = ref(false);
|
||||
const cancelReason = ref('');
|
||||
const injectedWorkflow = inject(SHIPPING_WORKFLOW_KEY, null);
|
||||
|
||||
/**
|
||||
* Gate 恢复卡「确认客户」:打开对话叠层客户选择弹窗。
|
||||
@@ -74,15 +70,9 @@ async function onGateConfirmCustomer(taskNo: string) {
|
||||
}
|
||||
|
||||
/**
|
||||
* 从 Workflow Items 中取首个阻断 Gate 摘要,供 Run 级卡片展示。
|
||||
* Run 级阻断 Gate:co8 后不再从 Workflow items 读取;由复核/Gate 主路径承接。
|
||||
*/
|
||||
const runLevelProcessGate = computed((): ShippingProcessGateUserSummary | null => {
|
||||
const items = injectedWorkflow?.items.value || [];
|
||||
for (const item of items) {
|
||||
if (item.process_gate?.current_blocking_gate) return item.process_gate;
|
||||
}
|
||||
return null;
|
||||
});
|
||||
const runLevelProcessGate = computed((): ShippingProcessGateUserSummary | null => null);
|
||||
|
||||
const gateNavigationContext = computed(() => ({
|
||||
agentId: String(route.params.agentId || ''),
|
||||
@@ -97,47 +87,10 @@ const progressLoading = ref(false);
|
||||
const progressLoadFailed = ref(false);
|
||||
const progressEvents = ref<ShippingOrderExtractionProgressEvent[]>([]);
|
||||
|
||||
/**
|
||||
* 统一计数:优先 props.workflowSummary,其次 inject 的 Workflow.counts,最后回退 Run summary。
|
||||
*/
|
||||
const unifiedCounts = computed(() => {
|
||||
const fromProp = props.workflowSummary;
|
||||
if (fromProp && Number(fromProp.total || 0) > 0) return fromProp;
|
||||
const fromInject = injectedWorkflow?.workflow.value?.counts;
|
||||
if (fromInject && Number(fromInject.total || 0) > 0) return fromInject;
|
||||
return null;
|
||||
});
|
||||
const displaySummary = computed(() => props.state.summary);
|
||||
|
||||
const displaySummary = computed(() => {
|
||||
const counts = unifiedCounts.value;
|
||||
if (!counts) return props.state.summary;
|
||||
return {
|
||||
totalDocuments: counts.total,
|
||||
processingDocuments: counts.processing,
|
||||
pendingDocuments: 0,
|
||||
completedDocuments: counts.completed,
|
||||
reviewRequiredDocuments: counts.pending_review,
|
||||
failedDocuments: counts.failed,
|
||||
cancelledDocuments: 0,
|
||||
candidateCount: props.state.summary.candidateCount,
|
||||
openedExistingCount: props.state.summary.openedExistingCount,
|
||||
};
|
||||
});
|
||||
|
||||
const workflowStageLabel = computed(() => {
|
||||
const stage = String(injectedWorkflow?.workflow.value?.current_stage || '').trim();
|
||||
if (!stage) return '';
|
||||
const key = `chat.shippingWorkflow.itemStatus.${stage}`;
|
||||
return te(key) ? t(key) : stage;
|
||||
});
|
||||
|
||||
const workflowLastActivityLabel = computed(() => {
|
||||
const raw = injectedWorkflow?.workflow.value?.last_activity_at;
|
||||
if (!raw) return '';
|
||||
const date = new Date(String(raw));
|
||||
if (Number.isNaN(date.getTime())) return '';
|
||||
return date.toLocaleString();
|
||||
});
|
||||
const workflowStageLabel = computed(() => '');
|
||||
const workflowLastActivityLabel = computed(() => '');
|
||||
|
||||
const handlingItems = computed(() => props.state.handlingItems || []);
|
||||
|
||||
@@ -261,11 +214,15 @@ const activityKey = computed(() => {
|
||||
});
|
||||
|
||||
const showRetry = computed(() => (
|
||||
!props.readonly && (
|
||||
props.state.availableActions.includes('retry_failed_attachments')
|
||||
|| displaySummary.value.failedDocuments > 0
|
||||
)
|
||||
));
|
||||
const showRefresh = computed(() => props.state.availableActions.includes('refresh_status'));
|
||||
const showRefresh = computed(() => !props.readonly && props.state.availableActions.includes('refresh_status'));
|
||||
const showCancel = computed(() => (
|
||||
!props.readonly
|
||||
&&
|
||||
props.state.availableActions.includes('cancel_run')
|
||||
&& !(props.state.cancellation?.requested && !props.state.cancellation?.completedAt)
|
||||
));
|
||||
@@ -404,6 +361,7 @@ function closeDetailsDrawer() {
|
||||
* 从详情抽屉进入复核/证据页。
|
||||
*/
|
||||
async function enterReviewFromDetails(payload?: { focus?: 'evidence' | 'draft'; documentId?: number }) {
|
||||
if (props.readonly) return;
|
||||
await openOrderReview({
|
||||
documentId: payload?.documentId,
|
||||
focus: payload?.focus === 'evidence' ? 'evidence' : 'draft',
|
||||
@@ -458,6 +416,7 @@ function affectedRows(item: ShippingOrderExtractionHandlingItemState) {
|
||||
* @param item - 处理事项
|
||||
*/
|
||||
async function handleHandlingAction(item: ShippingOrderExtractionHandlingItemState) {
|
||||
if (props.readonly) return;
|
||||
const action = String(item.primaryAction || '').trim();
|
||||
if (action === 'retry_failed_attachments') {
|
||||
emit('retry');
|
||||
@@ -489,6 +448,7 @@ function confirmCancel() {
|
||||
|
||||
/** 打开取消确认并清空上次填写的原因。 */
|
||||
function openCancelConfirm() {
|
||||
if (props.readonly) return;
|
||||
cancelReason.value = '';
|
||||
confirmCancelOpen.value = true;
|
||||
}
|
||||
@@ -516,6 +476,13 @@ function openCancelConfirm() {
|
||||
<CircleX v-else class="mt-0.5 h-4 w-4 shrink-0" />
|
||||
|
||||
<div class="min-w-0 flex-1">
|
||||
<div
|
||||
v-if="readonly"
|
||||
class="mb-1 text-xs font-medium opacity-80"
|
||||
data-testid="shipping-order-extraction-readonly"
|
||||
>
|
||||
{{ t('chat.shippingOrderExtractionHistory.superseded') }}
|
||||
</div>
|
||||
<div class="text-sm font-medium">{{ compactLine }}</div>
|
||||
<p
|
||||
v-if="state.errorExplainability?.request_id"
|
||||
@@ -564,7 +531,7 @@ function openCancelConfirm() {
|
||||
v-if="runLevelProcessGate?.current_blocking_gate"
|
||||
class="mt-2"
|
||||
:summary="runLevelProcessGate"
|
||||
:can-handle="true"
|
||||
:can-handle="!readonly"
|
||||
:navigation-context="gateNavigationContext"
|
||||
@refreshed="emit('refresh')"
|
||||
@refresh-needed="emit('refresh')"
|
||||
@@ -591,13 +558,15 @@ function openCancelConfirm() {
|
||||
<span class="ml-1 opacity-80">{{ t('chat.shippingOrderExtractionHandling.count', { count: item.count }) }}</span>
|
||||
</div>
|
||||
<button
|
||||
v-if="item.primaryAction"
|
||||
v-if="item.primaryAction && !readonly && (item.primaryAction !== 'review_candidate' || !handlingItems.some((other) => other.primaryAction === 'enter_manual_review'))"
|
||||
type="button"
|
||||
class="shrink-0 rounded-md border border-current/20 px-2 py-0.5 text-[11px] font-medium hover:bg-black/5 dark:hover:bg-white/5"
|
||||
@click="handleHandlingAction(item)"
|
||||
>
|
||||
{{ te(`chat.shippingOrderExtractionAction.${item.primaryAction}`)
|
||||
? t(`chat.shippingOrderExtractionAction.${item.primaryAction}`)
|
||||
{{ (item.primaryAction === 'review_candidate' || item.primaryAction === 'enter_manual_review')
|
||||
? t('chat.shippingOrderExtractionAction.enter_manual_review')
|
||||
: te(`chat.shippingOrderExtractionAction.${item.primaryAction}`)
|
||||
? t(`chat.shippingOrderExtractionAction.${item.primaryAction}`)
|
||||
: t('chat.shippingOrderExtractionAction.view_details') }}
|
||||
</button>
|
||||
</div>
|
||||
@@ -616,6 +585,7 @@ function openCancelConfirm() {
|
||||
:key="row.key"
|
||||
type="button"
|
||||
class="rounded border border-current/20 px-1.5 py-0.5 text-[11px] font-medium underline-offset-2 hover:underline"
|
||||
:disabled="readonly"
|
||||
@click="openAffectedRef(row.target)"
|
||||
>
|
||||
{{ row.label }}
|
||||
|
||||
+23
-23
@@ -65,21 +65,21 @@ const canReparse = computed(() => {
|
||||
|
||||
const reparseActionLabel = computed(() => {
|
||||
if (props.item?.reparse_kind === 'failed_run_retry') {
|
||||
return t('chat.shippingWorkflow.actions.retryFailedRun');
|
||||
return t('chat.shippingProcessing.actions.retryFailedRun');
|
||||
}
|
||||
return t('chat.shippingWorkflow.actions.reparse');
|
||||
return t('chat.shippingProcessing.actions.reparse');
|
||||
});
|
||||
|
||||
const filename = computed(() => {
|
||||
const name = String(props.item?.current_document_filename || '').trim();
|
||||
if (name) return name;
|
||||
if (!props.item) return '';
|
||||
return t('chat.shippingWorkflow.filenameFallback', {
|
||||
return t('chat.shippingProcessing.filenameFallback', {
|
||||
docId: props.item.current_document_id,
|
||||
});
|
||||
});
|
||||
|
||||
const title = computed(() => t('chat.shippingWorkflow.detail.title'));
|
||||
const title = computed(() => t('chat.shippingProcessing.detail.title'));
|
||||
|
||||
/**
|
||||
* 解析生命周期 / 阶段文案。
|
||||
@@ -87,8 +87,8 @@ const title = computed(() => t('chat.shippingWorkflow.detail.title'));
|
||||
function statusLabel(status?: string | null): string {
|
||||
const normalized = String(status || '').trim();
|
||||
if (!normalized) return '';
|
||||
const key = `chat.shippingWorkflow.itemStatus.${normalized}`;
|
||||
return te(key) ? t(key) : t('chat.shippingWorkflow.itemStatus.unknown');
|
||||
const key = `chat.shippingProcessing.itemStatus.${normalized}`;
|
||||
return te(key) ? t(key) : t('chat.shippingProcessing.itemStatus.unknown');
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -97,8 +97,8 @@ function statusLabel(status?: string | null): string {
|
||||
function eventLabel(event: ShippingWorkflowEvent): string {
|
||||
const code = String(event.message_code || event.event_code || '').trim();
|
||||
if (!code) return '—';
|
||||
const key = `chat.shippingWorkflow.event.${code}`;
|
||||
return te(key) ? t(key) : t('chat.shippingWorkflow.event.unknown');
|
||||
const key = `chat.shippingProcessing.event.${code}`;
|
||||
return te(key) ? t(key) : t('chat.shippingProcessing.event.unknown');
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -226,7 +226,7 @@ onBeforeUnmount(() => {
|
||||
ref="closeButtonRef"
|
||||
type="button"
|
||||
class="rounded-md p-1 text-muted hover:bg-surface-muted"
|
||||
:aria-label="t('chat.shippingWorkflow.detail.close')"
|
||||
:aria-label="t('chat.shippingProcessing.detail.close')"
|
||||
data-testid="shipping-workflow-item-drawer-close"
|
||||
@click="handleClose"
|
||||
>
|
||||
@@ -236,41 +236,41 @@ onBeforeUnmount(() => {
|
||||
|
||||
<div class="min-h-0 flex-1 overflow-auto p-4">
|
||||
<div v-if="loading" class="text-xs text-muted">
|
||||
{{ t('chat.shippingWorkflow.loading') }}
|
||||
{{ t('chat.shippingProcessing.loading') }}
|
||||
</div>
|
||||
<template v-else-if="item">
|
||||
<dl class="space-y-2 text-xs">
|
||||
<div class="flex justify-between gap-2">
|
||||
<dt class="text-secondary">{{ t('chat.shippingWorkflow.detail.filename') }}</dt>
|
||||
<dt class="text-secondary">{{ t('chat.shippingProcessing.detail.filename') }}</dt>
|
||||
<dd class="max-w-[60%] truncate font-medium text-primary" :title="filename">{{ filename }}</dd>
|
||||
</div>
|
||||
<div class="flex justify-between gap-2">
|
||||
<dt class="text-secondary">{{ t('chat.shippingWorkflow.detail.status') }}</dt>
|
||||
<dt class="text-secondary">{{ t('chat.shippingProcessing.detail.status') }}</dt>
|
||||
<dd class="font-medium text-primary">{{
|
||||
statusLabel(item.display_lifecycle_status || item.lifecycle_status)
|
||||
}}</dd>
|
||||
</div>
|
||||
<div class="flex justify-between gap-2">
|
||||
<dt class="text-secondary">{{ t('chat.shippingWorkflow.detail.stage') }}</dt>
|
||||
<dt class="text-secondary">{{ t('chat.shippingProcessing.detail.stage') }}</dt>
|
||||
<dd class="font-medium text-primary">{{ statusLabel(item.current_stage) || item.current_stage }}</dd>
|
||||
</div>
|
||||
<div v-if="item.current_run_no" class="flex justify-between gap-2">
|
||||
<dt class="text-secondary">{{ t('chat.shippingWorkflow.detail.runNo') }}</dt>
|
||||
<dt class="text-secondary">{{ t('chat.shippingProcessing.detail.runNo') }}</dt>
|
||||
<dd class="font-medium text-primary">{{ item.current_run_no }}</dd>
|
||||
</div>
|
||||
<div v-if="item.current_case_no" class="flex justify-between gap-2">
|
||||
<dt class="text-secondary">{{ t('chat.shippingWorkflow.detail.caseNo') }}</dt>
|
||||
<dt class="text-secondary">{{ t('chat.shippingProcessing.detail.caseNo') }}</dt>
|
||||
<dd class="font-medium text-primary">{{ item.current_case_no }}</dd>
|
||||
</div>
|
||||
<div v-if="item.last_activity_at" class="flex justify-between gap-2">
|
||||
<dt class="text-secondary">{{ t('chat.shippingWorkflow.detail.lastActivity') }}</dt>
|
||||
<dt class="text-secondary">{{ t('chat.shippingProcessing.detail.lastActivity') }}</dt>
|
||||
<dd class="font-medium text-primary">{{ formatTime(item.last_activity_at) }}</dd>
|
||||
</div>
|
||||
<div v-if="item.closed_reason" class="flex justify-between gap-2">
|
||||
<dt class="text-secondary">{{ t('chat.shippingWorkflow.detail.closedReason') }}</dt>
|
||||
<dt class="text-secondary">{{ t('chat.shippingProcessing.detail.closedReason') }}</dt>
|
||||
<dd class="font-medium text-primary">
|
||||
{{ te(`chat.shippingWorkflow.closedReason.${item.closed_reason}`)
|
||||
? t(`chat.shippingWorkflow.closedReason.${item.closed_reason}`)
|
||||
{{ te(`chat.shippingProcessing.closedReason.${item.closed_reason}`)
|
||||
? t(`chat.shippingProcessing.closedReason.${item.closed_reason}`)
|
||||
: item.closed_reason }}
|
||||
</dd>
|
||||
</div>
|
||||
@@ -289,7 +289,7 @@ onBeforeUnmount(() => {
|
||||
|
||||
<section class="mt-4">
|
||||
<h3 class="text-xs font-semibold text-secondary">
|
||||
{{ t('chat.shippingWorkflow.detail.eventsTitle') }}
|
||||
{{ t('chat.shippingProcessing.detail.eventsTitle') }}
|
||||
</h3>
|
||||
<ul v-if="events.length" class="mt-2 space-y-2" data-testid="shipping-workflow-item-events">
|
||||
<li
|
||||
@@ -306,11 +306,11 @@ onBeforeUnmount(() => {
|
||||
</li>
|
||||
</ul>
|
||||
<p v-else class="mt-2 text-xs text-muted">
|
||||
{{ t('chat.shippingWorkflow.detail.eventsEmpty') }}
|
||||
{{ t('chat.shippingProcessing.detail.eventsEmpty') }}
|
||||
</p>
|
||||
</section>
|
||||
</template>
|
||||
<p v-else class="text-xs text-muted">{{ t('chat.shippingWorkflow.detail.empty') }}</p>
|
||||
<p v-else class="text-xs text-muted">{{ t('chat.shippingProcessing.detail.empty') }}</p>
|
||||
</div>
|
||||
|
||||
<footer v-if="item && (canCancel || canReparse)" class="space-y-2 border-t border-default p-3">
|
||||
@@ -332,7 +332,7 @@ onBeforeUnmount(() => {
|
||||
data-testid="shipping-workflow-item-drawer-cancel"
|
||||
@click="emit('cancel', item)"
|
||||
>
|
||||
{{ t('chat.shippingWorkflow.actions.cancelFile') }}
|
||||
{{ t('chat.shippingProcessing.actions.cancelFile') }}
|
||||
</button>
|
||||
</footer>
|
||||
</aside>
|
||||
|
||||
@@ -32,18 +32,18 @@ const reasonInputRef = ref<HTMLTextAreaElement | null>(null);
|
||||
|
||||
const title = computed(() => (
|
||||
props.action === 'reparse'
|
||||
? t('chat.shippingWorkflow.reasonDialog.reparseTitle')
|
||||
: t('chat.shippingWorkflow.reasonDialog.cancelTitle')
|
||||
? t('chat.shippingProcessing.reasonDialog.reparseTitle')
|
||||
: t('chat.shippingProcessing.reasonDialog.cancelTitle')
|
||||
));
|
||||
|
||||
const confirmLabel = computed(() => (
|
||||
props.action === 'reparse'
|
||||
? t('chat.shippingWorkflow.reasonDialog.reparseConfirm')
|
||||
: t('chat.shippingWorkflow.reasonDialog.cancelConfirm')
|
||||
? t('chat.shippingProcessing.reasonDialog.reparseConfirm')
|
||||
: t('chat.shippingProcessing.reasonDialog.cancelConfirm')
|
||||
));
|
||||
|
||||
const reasonLabel = computed(() => t('chat.shippingWorkflow.reasonDialog.reasonLabel'));
|
||||
const reasonRequiredHint = computed(() => t('chat.shippingWorkflow.reasonRequired'));
|
||||
const reasonLabel = computed(() => t('chat.shippingProcessing.reasonDialog.reasonLabel'));
|
||||
const reasonRequiredHint = computed(() => t('chat.shippingProcessing.reasonRequired'));
|
||||
|
||||
/**
|
||||
* 关闭弹窗并重置本地表单。
|
||||
@@ -128,7 +128,7 @@ onBeforeUnmount(() => {
|
||||
>
|
||||
<h3 class="text-sm font-semibold text-primary">{{ title }}</h3>
|
||||
<p class="mt-1 text-xs text-secondary">
|
||||
{{ t('chat.shippingWorkflow.reasonDialog.impact') }}
|
||||
{{ t('chat.shippingProcessing.reasonDialog.impact') }}
|
||||
</p>
|
||||
|
||||
<label class="mt-3 block text-xs text-secondary">
|
||||
@@ -141,7 +141,7 @@ onBeforeUnmount(() => {
|
||||
class="input-field mt-1 w-full py-1.5 text-xs"
|
||||
:aria-invalid="reasonMissing"
|
||||
data-testid="shipping-workflow-reason-input"
|
||||
:placeholder="t('chat.shippingWorkflow.reasonDialog.reasonPlaceholder')"
|
||||
:placeholder="t('chat.shippingProcessing.reasonDialog.reasonPlaceholder')"
|
||||
/>
|
||||
</label>
|
||||
<p v-if="reasonMissing" class="mt-1 text-[11px] text-rose-600" data-testid="shipping-workflow-reason-missing">
|
||||
@@ -152,7 +152,7 @@ onBeforeUnmount(() => {
|
||||
v-if="action === 'reparse'"
|
||||
class="mt-2 block text-xs text-secondary"
|
||||
>
|
||||
{{ t('chat.shippingWorkflow.reasonDialog.commentOptional') }}
|
||||
{{ t('chat.shippingProcessing.reasonDialog.commentOptional') }}
|
||||
<textarea
|
||||
v-model="comment"
|
||||
rows="2"
|
||||
@@ -169,7 +169,7 @@ onBeforeUnmount(() => {
|
||||
data-testid="shipping-workflow-reason-cancel"
|
||||
@click="handleCancel"
|
||||
>
|
||||
{{ t('chat.shippingWorkflow.reasonDialog.dismiss') }}
|
||||
{{ t('chat.shippingProcessing.reasonDialog.dismiss') }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
@@ -179,7 +179,7 @@ onBeforeUnmount(() => {
|
||||
@click="handleConfirm"
|
||||
>
|
||||
{{ confirmLoading
|
||||
? t('chat.shippingWorkflow.reasonDialog.submitting')
|
||||
? t('chat.shippingProcessing.reasonDialog.submitting')
|
||||
: confirmLabel }}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
@@ -1,330 +1,464 @@
|
||||
/**
|
||||
* features/chat/components/shipping/ShippingWorkflowTimeline.spec.ts
|
||||
* 用途:验证右侧 Workflow 时间线分组、文件名、批次切换、过滤与取消/重识别弹窗。
|
||||
* 依赖:Vitest、Vue Test Utils、vue-i18n、shipping.api mock。
|
||||
* 逻辑:先展开侧栏并打开详情抽屉;断言 layout_parsing 可见;文件名优先;过滤与 cancel。
|
||||
*/
|
||||
import { mount, flushPromises } from '@vue/test-utils';
|
||||
import { describe, expect, it, vi, beforeEach } from 'vitest';
|
||||
import { createI18n } from 'vue-i18n';
|
||||
import { ref } from 'vue';
|
||||
import chatZhCn from '@/locales/zh-CN/chat.json';
|
||||
import ShippingWorkflowTimeline from './ShippingWorkflowTimeline.vue';
|
||||
import type { ShippingWorkflow, ShippingWorkflowItem } from '../../types/shipping.api.types';
|
||||
import type { UseShippingNoticeWorkflowReturn } from '../../shipping/useShippingNoticeWorkflow';
|
||||
|
||||
const routerPush = vi.fn(async () => undefined);
|
||||
vi.mock('vue-router', () => ({
|
||||
useRoute: () => ({ params: { agentId: 'agent-1' }, query: {} }),
|
||||
useRouter: () => ({ push: routerPush }),
|
||||
}));
|
||||
|
||||
vi.mock('@/features/chat/api/shipping.api', () => ({
|
||||
getWorkspaceShippingWorkflowItem: vi.fn(async (itemNo: string) => ({
|
||||
item_no: itemNo,
|
||||
workflow_no: 'SNWF-1',
|
||||
conversation_id: 'conv-1',
|
||||
root_document_id: 1,
|
||||
current_document_id: 1,
|
||||
current_document_filename: 'detail.pdf',
|
||||
current_version_no: 1,
|
||||
lifecycle_status: 'layout_parsing',
|
||||
current_stage: 'layout_parsing',
|
||||
lock_version: 1,
|
||||
events: [],
|
||||
})),
|
||||
listWorkspaceShippingWorkflows: vi.fn(),
|
||||
cancelWorkspaceShippingWorkflowItem: vi.fn(),
|
||||
reparseWorkspaceShippingWorkflowItem: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('@/shared/composables/useMessage', () => ({
|
||||
useMessage: () => ({
|
||||
success: vi.fn(),
|
||||
error: vi.fn(),
|
||||
warning: vi.fn(),
|
||||
info: vi.fn(),
|
||||
}),
|
||||
}));
|
||||
|
||||
const i18n = createI18n({
|
||||
legacy: false,
|
||||
locale: 'zh-CN',
|
||||
messages: { 'zh-CN': { chat: chatZhCn, errors: { generic: '错误' } } },
|
||||
});
|
||||
|
||||
function buildItem(patch: Partial<ShippingWorkflowItem> = {}): ShippingWorkflowItem {
|
||||
return {
|
||||
item_no: 'SWI-1',
|
||||
workflow_no: 'SNWF-1',
|
||||
conversation_id: 'conv-1',
|
||||
root_document_id: 10,
|
||||
current_document_id: 10,
|
||||
current_document_filename: 'shipping-notice.pdf',
|
||||
current_version_no: 1,
|
||||
lifecycle_status: 'layout_parsing',
|
||||
current_stage: 'layout_parsing',
|
||||
lock_version: 1,
|
||||
...patch,
|
||||
};
|
||||
}
|
||||
|
||||
function buildController(
|
||||
items: ShippingWorkflowItem[],
|
||||
extras?: { workflows?: ShippingWorkflow[] },
|
||||
): UseShippingNoticeWorkflowReturn {
|
||||
const workflowList = extras?.workflows ?? [{
|
||||
workflow_no: 'SNWF-1',
|
||||
conversation_id: 'conv-1',
|
||||
status: 'open',
|
||||
current_stage: 'layout_parsing',
|
||||
lock_version: 1,
|
||||
counts: {
|
||||
total: items.length,
|
||||
processing: items.filter((i) => i.lifecycle_status === 'layout_parsing' || i.lifecycle_status === 'extracting').length,
|
||||
pending_review: items.filter((i) => i.lifecycle_status === 'pending_review').length,
|
||||
failed: items.filter((i) => i.lifecycle_status === 'failed' || i.lifecycle_status === 'reparse_failed').length,
|
||||
completed: items.filter((i) => i.lifecycle_status === 'closed').length,
|
||||
},
|
||||
items,
|
||||
}];
|
||||
const selectedWorkflowNo = ref(workflowList[0]?.workflow_no || null);
|
||||
const workflows = ref(workflowList);
|
||||
const workflow = ref(workflowList[0] || null);
|
||||
const itemRef = ref(items);
|
||||
return {
|
||||
workflows,
|
||||
selectedWorkflowNo,
|
||||
selectWorkflow: vi.fn((no: string) => {
|
||||
selectedWorkflowNo.value = no;
|
||||
workflow.value = workflows.value.find((row) => row.workflow_no === no) || null;
|
||||
itemRef.value = workflow.value?.items || [];
|
||||
}),
|
||||
workflow,
|
||||
items: itemRef,
|
||||
loading: ref(false),
|
||||
error: ref(null),
|
||||
refresh: vi.fn(async () => undefined),
|
||||
cancelItem: vi.fn(async () => null),
|
||||
reparseItem: vi.fn(async () => null),
|
||||
stop: vi.fn(),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 展开窄侧栏并打开详情抽屉(完整列表仅在抽屉内)。
|
||||
*/
|
||||
async function openDetailsDrawer(wrapper: ReturnType<typeof mount>) {
|
||||
const toggleCollapse = wrapper.find('[data-testid="shipping-workflow-timeline"] button');
|
||||
if (toggleCollapse.exists()) {
|
||||
await toggleCollapse.trigger('click');
|
||||
await flushPromises();
|
||||
}
|
||||
const openDetails = wrapper.find('[data-testid="shipping-workflow-toggle-details"]');
|
||||
expect(openDetails.exists()).toBe(true);
|
||||
await openDetails.trigger('click');
|
||||
await flushPromises();
|
||||
expect(wrapper.find('[data-testid="shipping-workflow-details-drawer"]').exists()).toBe(true);
|
||||
}
|
||||
|
||||
const mountOptions = {
|
||||
global: {
|
||||
plugins: [i18n],
|
||||
stubs: {
|
||||
// 抽屉/原因框经 Teleport;单测就地渲染便于查询。
|
||||
teleport: true,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
describe('ShippingWorkflowTimeline', () => {
|
||||
beforeEach(() => {
|
||||
document.body.innerHTML = '';
|
||||
routerPush.mockClear();
|
||||
});
|
||||
|
||||
it('shows layout_parsing items with filename before review case exists', async () => {
|
||||
const controller = buildController([
|
||||
buildItem({
|
||||
item_no: 'SWI-LAYOUT',
|
||||
lifecycle_status: 'layout_parsing',
|
||||
current_case_no: null,
|
||||
current_document_filename: 'layout.pdf',
|
||||
}),
|
||||
buildItem({ item_no: 'SWI-REVIEW', lifecycle_status: 'pending_review', current_case_no: 'SNRC-1' }),
|
||||
]);
|
||||
const wrapper = mount(ShippingWorkflowTimeline, {
|
||||
props: { conversationId: 'conv-1', controller },
|
||||
...mountOptions,
|
||||
});
|
||||
await flushPromises();
|
||||
await openDetailsDrawer(wrapper);
|
||||
await wrapper.find('[data-testid="shipping-workflow-pending-only-filter"]').setValue(false);
|
||||
expect(wrapper.find('[data-testid="shipping-workflow-item-SWI-LAYOUT"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="shipping-workflow-item-SWI-LAYOUT"]').text()).toContain('layout.pdf');
|
||||
expect(wrapper.text()).toContain('尚无复核单');
|
||||
expect(wrapper.find('[data-testid="shipping-workflow-group-processing"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="shipping-workflow-group-pending_review"]').exists()).toBe(true);
|
||||
});
|
||||
|
||||
it('filters to actionable items when pending-only is checked', async () => {
|
||||
const controller = buildController([
|
||||
buildItem({ item_no: 'SWI-A', lifecycle_status: 'extracting' }),
|
||||
buildItem({ item_no: 'SWI-B', lifecycle_status: 'pending_review' }),
|
||||
]);
|
||||
const wrapper = mount(ShippingWorkflowTimeline, {
|
||||
props: { conversationId: 'conv-1', controller },
|
||||
...mountOptions,
|
||||
});
|
||||
await flushPromises();
|
||||
await openDetailsDrawer(wrapper);
|
||||
await wrapper.find('[data-testid="shipping-workflow-pending-only-filter"]').setValue(true);
|
||||
expect(wrapper.find('[data-testid="shipping-workflow-item-SWI-B"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="shipping-workflow-item-SWI-A"]').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it('opens the review workspace directly for pending review items', async () => {
|
||||
const controller = buildController([
|
||||
buildItem({
|
||||
item_no: 'SWI-REVIEW-OPEN',
|
||||
lifecycle_status: 'pending_review',
|
||||
current_run_no: 'RUN-REVIEW-1',
|
||||
current_case_no: 'CASE-REVIEW-1',
|
||||
current_document_id: 42,
|
||||
}),
|
||||
]);
|
||||
const wrapper = mount(ShippingWorkflowTimeline, {
|
||||
props: { conversationId: 'conv-1', controller },
|
||||
...mountOptions,
|
||||
});
|
||||
await flushPromises();
|
||||
await openDetailsDrawer(wrapper);
|
||||
await wrapper.find('[data-testid="shipping-workflow-action-open-review"]').trigger('click');
|
||||
expect(routerPush).toHaveBeenCalledWith(expect.objectContaining({
|
||||
name: 'Chat',
|
||||
params: { agentId: 'agent-1' },
|
||||
query: expect.objectContaining({
|
||||
mode: 'order-review',
|
||||
run_no: 'RUN-REVIEW-1',
|
||||
case_no: 'CASE-REVIEW-1',
|
||||
document_id: '42',
|
||||
focus: 'draft',
|
||||
}),
|
||||
}));
|
||||
});
|
||||
|
||||
it('cancels an item via in-app reason dialog', async () => {
|
||||
const controller = buildController([
|
||||
buildItem({ item_no: 'SWI-CANCEL', lifecycle_status: 'extracting', lock_version: 3 }),
|
||||
]);
|
||||
const wrapper = mount(ShippingWorkflowTimeline, {
|
||||
props: { conversationId: 'conv-1', controller },
|
||||
...mountOptions,
|
||||
});
|
||||
await flushPromises();
|
||||
await openDetailsDrawer(wrapper);
|
||||
await wrapper.find('[data-testid="shipping-workflow-pending-only-filter"]').setValue(false);
|
||||
await wrapper.find('[data-testid="shipping-workflow-action-cancel"]').trigger('click');
|
||||
await flushPromises();
|
||||
const reasonInput = wrapper.find('[data-testid="shipping-workflow-reason-input"]');
|
||||
expect(reasonInput.exists()).toBe(true);
|
||||
await reasonInput.setValue('cancel reason');
|
||||
await wrapper.find('[data-testid="shipping-workflow-reason-confirm"]').trigger('click');
|
||||
await flushPromises();
|
||||
expect(controller.cancelItem).toHaveBeenCalledWith('SWI-CANCEL', {
|
||||
reason: 'cancel reason',
|
||||
expected_lock_version: 3,
|
||||
});
|
||||
});
|
||||
|
||||
it('shows batch switcher for multiple workflows', async () => {
|
||||
const itemsA = [buildItem({ item_no: 'SWI-A', workflow_no: 'SNWF-A' })];
|
||||
const itemsB = [buildItem({ item_no: 'SWI-B', workflow_no: 'SNWF-B', lifecycle_status: 'failed' })];
|
||||
const workflows = [
|
||||
{
|
||||
workflow_no: 'SNWF-A',
|
||||
conversation_id: 'conv-1',
|
||||
status: 'open',
|
||||
current_stage: 'layout_parsing',
|
||||
lock_version: 1,
|
||||
counts: { total: 1, processing: 1, pending_review: 0, failed: 0, completed: 0 },
|
||||
items: itemsA,
|
||||
},
|
||||
{
|
||||
workflow_no: 'SNWF-B',
|
||||
conversation_id: 'conv-1',
|
||||
status: 'open',
|
||||
current_stage: 'failed',
|
||||
lock_version: 1,
|
||||
counts: { total: 1, processing: 0, pending_review: 0, failed: 1, completed: 0 },
|
||||
items: itemsB,
|
||||
},
|
||||
];
|
||||
const controller = buildController(itemsA, { workflows });
|
||||
const wrapper = mount(ShippingWorkflowTimeline, {
|
||||
props: { conversationId: 'conv-1', controller },
|
||||
...mountOptions,
|
||||
});
|
||||
await flushPromises();
|
||||
await openDetailsDrawer(wrapper);
|
||||
expect(wrapper.find('[data-testid="shipping-workflow-batch-switcher"]').exists()).toBe(true);
|
||||
await wrapper.find('[data-testid="shipping-workflow-batch-SNWF-B"]').trigger('click');
|
||||
expect(controller.selectWorkflow).toHaveBeenCalledWith('SNWF-B');
|
||||
});
|
||||
|
||||
it('shows reparse action for failed items', async () => {
|
||||
const controller = buildController([
|
||||
buildItem({
|
||||
item_no: 'SWI-FAIL',
|
||||
lifecycle_status: 'failed',
|
||||
current_document_filename: 'bad.pdf',
|
||||
available_actions: ['cancel', 'reparse'],
|
||||
reparse_kind: 'failed_run_retry',
|
||||
}),
|
||||
]);
|
||||
const wrapper = mount(ShippingWorkflowTimeline, {
|
||||
props: { conversationId: 'conv-1', controller },
|
||||
...mountOptions,
|
||||
});
|
||||
await flushPromises();
|
||||
await openDetailsDrawer(wrapper);
|
||||
expect(wrapper.find('[data-testid="shipping-workflow-action-reparse"]').exists()).toBe(true);
|
||||
expect(wrapper.text()).toContain('重试失败识别');
|
||||
});
|
||||
|
||||
it('hides reparse for pending_review without available_actions.reparse', async () => {
|
||||
const controller = buildController([
|
||||
buildItem({
|
||||
item_no: 'SWI-PR',
|
||||
lifecycle_status: 'pending_review',
|
||||
current_case_no: null,
|
||||
available_actions: ['cancel'],
|
||||
reparse_kind: null,
|
||||
}),
|
||||
]);
|
||||
const wrapper = mount(ShippingWorkflowTimeline, {
|
||||
props: { conversationId: 'conv-1', controller },
|
||||
...mountOptions,
|
||||
});
|
||||
await flushPromises();
|
||||
await openDetailsDrawer(wrapper);
|
||||
expect(wrapper.find('[data-testid="shipping-workflow-action-reparse"]').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it('keeps sidebar width when opening details dialog overlay', async () => {
|
||||
const controller = buildController([buildItem()]);
|
||||
const wrapper = mount(ShippingWorkflowTimeline, {
|
||||
props: { conversationId: 'conv-1', controller },
|
||||
...mountOptions,
|
||||
});
|
||||
await flushPromises();
|
||||
await openDetailsDrawer(wrapper);
|
||||
const aside = wrapper.find('[data-testid="shipping-workflow-timeline"]');
|
||||
// 关键断言:弹层打开后侧栏仍固定窄宽,对话区不被列表撑开。
|
||||
expect(aside.classes().join(' ')).toContain('md:w-60');
|
||||
const overlay = wrapper.find('[data-testid="shipping-workflow-details-drawer"]');
|
||||
expect(overlay.exists()).toBe(true);
|
||||
expect(overlay.classes().join(' ')).toContain('fixed');
|
||||
expect(overlay.find('[role="dialog"]').exists()).toBe(true);
|
||||
});
|
||||
});
|
||||
/**␍
|
||||
* features/chat/components/shipping/ShippingWorkflowTimeline.spec.ts␍
|
||||
* 用途:验证右侧「本次处理中」OT 任务卡、展开后文件明细、过滤与取消/重识别弹窗。␍
|
||||
* 依赖:Vitest、Vue Test Utils、vue-i18n、shipping.api mock。␍
|
||||
* 逻辑:文件明细由 expandedTask.objects 经 mapUserTaskObjectsToFileRows 合成;␍
|
||||
* 须先展开 processing 任务才出现文件抽屉;WF 批次切换器恒隐藏。␍
|
||||
*/␍
|
||||
import { mount, flushPromises } from '@vue/test-utils';␍
|
||||
import { describe, expect, it, vi, beforeEach } from 'vitest';␍
|
||||
import { createI18n } from 'vue-i18n';␍
|
||||
import { ref } from 'vue';␍
|
||||
import chatZhCn from '@/locales/zh-CN/chat.json';␍
|
||||
import ShippingWorkflowTimeline from './ShippingWorkflowTimeline.vue';␍
|
||||
import type {␍
|
||||
ConversationProcessingObject,␍
|
||||
ConversationProcessingProjection,␍
|
||||
ConversationProcessingUserTask,␍
|
||||
ShippingWorkflowItem,␍
|
||||
} from '../../types/shipping.api.types';␍
|
||||
import type { UseShippingNoticeWorkflowReturn } from '../../shipping/useShippingNoticeWorkflow';␍
|
||||
␍
|
||||
const routerPush = vi.fn(async () => undefined);␍
|
||||
vi.mock('vue-router', () => ({␍
|
||||
useRoute: () => ({ params: { agentId: 'agent-1' }, query: {} }),␍
|
||||
useRouter: () => ({ push: routerPush }),␍
|
||||
}));␍
|
||||
␍
|
||||
const api = vi.hoisted(() => ({␍
|
||||
cancelRun: vi.fn(async () => ({})),␍
|
||||
reparseRun: vi.fn(async () => ({})),␍
|
||||
retryRun: vi.fn(async () => ({})),␍
|
||||
retryIntake: vi.fn(async () => ({})),␍
|
||||
}));␍
|
||||
␍
|
||||
vi.mock('@/features/chat/api/shipping.api', () => ({␍
|
||||
cancelWorkspaceShippingOrderExtractionRun: api.cancelRun,␍
|
||||
reparseWorkspaceShippingOrderExtractionRun: api.reparseRun,␍
|
||||
retryWorkspaceShippingOrderExtractionRun: api.retryRun,␍
|
||||
retryShippingNoticeIntake: api.retryIntake,␍
|
||||
}));␍
|
||||
␍
|
||||
vi.mock('@/shared/composables/useMessage', () => ({␍
|
||||
useMessage: () => ({␍
|
||||
success: vi.fn(),␍
|
||||
error: vi.fn(),␍
|
||||
warning: vi.fn(),␍
|
||||
info: vi.fn(),␍
|
||||
}),␍
|
||||
}));␍
|
||||
␍
|
||||
const i18n = createI18n({␍
|
||||
legacy: false,␍
|
||||
locale: 'zh-CN',␍
|
||||
messages: { 'zh-CN': { chat: chatZhCn, errors: { generic: '错误' } } },␍
|
||||
});␍
|
||||
␍
|
||||
const DEFAULT_TASK_NO = 'OT-TEST';␍
|
||||
␍
|
||||
function buildItem(patch: Partial<ShippingWorkflowItem> = {}): ShippingWorkflowItem {␍
|
||||
return {␍
|
||||
item_no: 'SWI-1',␍
|
||||
workflow_no: 'SNWF-1',␍
|
||||
conversation_id: 'conv-1',␍
|
||||
root_document_id: 10,␍
|
||||
current_document_id: 10,␍
|
||||
current_document_filename: 'shipping-notice.pdf',␍
|
||||
current_version_no: 1,␍
|
||||
lifecycle_status: 'layout_parsing',␍
|
||||
current_stage: 'layout_parsing',␍
|
||||
lock_version: 1,␍
|
||||
current_run_no: 'RUN-1',␍
|
||||
...patch,␍
|
||||
};␍
|
||||
}␍
|
||||
␍
|
||||
type DocumentObject = ConversationProcessingObject & {␍
|
||||
available_actions?: string[];␍
|
||||
reparse_kind?: string | null;␍
|
||||
lock_version?: number;␍
|
||||
};␍
|
||||
␍
|
||||
/**␍
|
||||
* 将 buildItem 文档行映射为 OT document object(供 processingFromDocuments 使用)。␍
|
||||
*/␍
|
||||
function documentObjectFromItem(doc: ShippingWorkflowItem): DocumentObject {␍
|
||||
return {␍
|
||||
kind: 'document',␍
|
||||
object_key: doc.item_no,␍
|
||||
workflow_item_no: doc.item_no,␍
|
||||
label: String(doc.current_document_filename || doc.item_no),␍
|
||||
filename: doc.current_document_filename ?? null,␍
|
||||
status_label: doc.lifecycle_status,␍
|
||||
document_id: doc.current_document_id,␍
|
||||
root_document_id: doc.root_document_id,␍
|
||||
content_hash: doc.content_hash ?? null,␍
|
||||
current_run_no: doc.current_run_no ?? null,␍
|
||||
case_no: doc.current_case_no ?? null,␍
|
||||
available_actions: doc.available_actions,␍
|
||||
reparse_kind: doc.reparse_kind ?? null,␍
|
||||
lock_version: doc.lock_version,␍
|
||||
};␍
|
||||
}␍
|
||||
␍
|
||||
/**␍
|
||||
* 构造含单个 processing 任务与 document objects 的会话投影。␍
|
||||
* 核心逻辑:objects 默认由 docs 映射;taskOverrides 可覆盖任务卡字段或整组 objects。␍
|
||||
*/␍
|
||||
function processingFromDocuments(␍
|
||||
docs: ShippingWorkflowItem[],␍
|
||||
taskOverrides?: Partial<ConversationProcessingUserTask>,␍
|
||||
): ConversationProcessingProjection {␍
|
||||
const userTaskNo = taskOverrides?.user_task_no ?? DEFAULT_TASK_NO;␍
|
||||
const objects = taskOverrides?.objects ?? docs.map(documentObjectFromItem);␍
|
||||
const filenames = docs␍
|
||||
.map((doc) => String(doc.current_document_filename || '').trim())␍
|
||||
.filter(Boolean);␍
|
||||
const task: ConversationProcessingUserTask = {␍
|
||||
user_task_no: userTaskNo,␍
|
||||
group: 'processing',␍
|
||||
status_label: docs[0]?.lifecycle_status ?? 'extracting',␍
|
||||
title: docs.length === 1 ? (docs[0]?.current_document_filename ?? null) : null,␍
|
||||
display_kind: docs.length > 1 ? 'multi_document_task' : 'single_document_task',␍
|
||||
document_names: filenames.length ? filenames : null,␍
|
||||
file_count: docs.length,␍
|
||||
run_no: docs[0]?.current_run_no ?? null,␍
|
||||
can_append: false,␍
|
||||
objects,␍
|
||||
...taskOverrides,␍
|
||||
};␍
|
||||
␍
|
||||
return {␍
|
||||
summary: {␍
|
||||
total_tasks: 1,␍
|
||||
total_files: docs.length,␍
|
||||
processing: 1,␍
|
||||
needs_action: 0,␍
|
||||
completed: 0,␍
|
||||
history: 0,␍
|
||||
},␍
|
||||
focused_task_no: null,␍
|
||||
recent_task_no: null,␍
|
||||
needs_action: [],␍
|
||||
processing: [task],␍
|
||||
completed: [],␍
|
||||
history: [],␍
|
||||
};␍
|
||||
}␍
|
||||
␍
|
||||
function buildController(␍
|
||||
extras?: {␍
|
||||
processing?: UseShippingNoticeWorkflowReturn['processing']['value'];␍
|
||||
},␍
|
||||
): UseShippingNoticeWorkflowReturn {␍
|
||||
return {␍
|
||||
processing: ref(extras?.processing ?? null),␍
|
||||
processingWorkItems: ref([]),␍
|
||||
loading: ref(false),␍
|
||||
error: ref(null),␍
|
||||
refresh: vi.fn(async () => undefined),␍
|
||||
focusConversationTask: vi.fn(async () => undefined),␍
|
||||
markConversationTaskViewed: vi.fn(async () => undefined),␍
|
||||
stop: vi.fn(),␍
|
||||
};␍
|
||||
}␍
|
||||
␍
|
||||
/**␍
|
||||
* 展开 processing 任务卡,使文件明细抽屉可见。␍
|
||||
*/␍
|
||||
async function expandProcessingTask(␍
|
||||
wrapper: ReturnType<typeof mount>,␍
|
||||
taskNo = DEFAULT_TASK_NO,␍
|
||||
) {␍
|
||||
if (wrapper.find('[data-testid="shipping-workflow-details-drawer"]').exists()) {␍
|
||||
return;␍
|
||||
}␍
|
||||
const task = wrapper.find(`[data-testid="shipping-processing-task-${taskNo}"]`);␍
|
||||
expect(task.exists()).toBe(true);␍
|
||||
await task.findAll('button').at(-1)!.trigger('click');␍
|
||||
await flushPromises();␍
|
||||
}␍
|
||||
␍
|
||||
async function openDetailsDrawer(␍
|
||||
wrapper: ReturnType<typeof mount>,␍
|
||||
taskNo = DEFAULT_TASK_NO,␍
|
||||
) {␍
|
||||
await flushPromises();␍
|
||||
await expandProcessingTask(wrapper, taskNo);␍
|
||||
expect(wrapper.find('[data-testid="shipping-workflow-details-drawer"]').exists()).toBe(true);␍
|
||||
}␍
|
||||
␍
|
||||
const mountOptions = {␍
|
||||
global: {␍
|
||||
plugins: [i18n],␍
|
||||
stubs: {␍
|
||||
teleport: true,␍
|
||||
},␍
|
||||
},␍
|
||||
};␍
|
||||
␍
|
||||
describe('ShippingWorkflowTimeline', () => {␍
|
||||
beforeEach(() => {␍
|
||||
document.body.innerHTML = '';␍
|
||||
routerPush.mockClear();␍
|
||||
});␍
|
||||
␍
|
||||
it('shows layout_parsing items with filename before review case exists', async () => {␍
|
||||
const processing = processingFromDocuments([␍
|
||||
buildItem({␍
|
||||
item_no: 'SWI-LAYOUT',␍
|
||||
lifecycle_status: 'layout_parsing',␍
|
||||
current_case_no: null,␍
|
||||
current_document_filename: 'layout.pdf',␍
|
||||
}),␍
|
||||
buildItem({ item_no: 'SWI-REVIEW', lifecycle_status: 'pending_review', current_case_no: 'SNRC-1' }),␍
|
||||
]);␍
|
||||
const wrapper = mount(ShippingWorkflowTimeline, {␍
|
||||
props: { conversationId: 'conv-1', controller: buildController({ processing }) },␍
|
||||
...mountOptions,␍
|
||||
});␍
|
||||
await openDetailsDrawer(wrapper);␍
|
||||
// 断言:layout 文件行展示文件名␍
|
||||
expect(wrapper.find('[data-testid="shipping-workflow-item-SWI-LAYOUT"]').exists()).toBe(true);␍
|
||||
expect(wrapper.find('[data-testid="shipping-workflow-item-SWI-LAYOUT"]').text()).toContain('layout.pdf');␍
|
||||
// 断言:无复核单时展示占位文案␍
|
||||
expect(wrapper.text()).toContain('尚无复核单');␍
|
||||
// 断言:有 OT 任务投影时隐藏独立「当前阶段」卡(UI-F04)␍
|
||||
expect(wrapper.find('[data-testid="shipping-workflow-current-stage"]').exists()).toBe(false);␍
|
||||
// 断言:processing / pending_review 分组均可见␍
|
||||
expect(wrapper.find('[data-testid="shipping-workflow-group-processing"]').exists()).toBe(true);␍
|
||||
expect(wrapper.find('[data-testid="shipping-workflow-group-pending_review"]').exists()).toBe(true);␍
|
||||
});␍
|
||||
␍
|
||||
it('shows processing and pending-review files together by default', async () => {␍
|
||||
const processing = processingFromDocuments([␍
|
||||
buildItem({ item_no: 'SWI-A', lifecycle_status: 'extracting' }),␍
|
||||
buildItem({ item_no: 'SWI-B', lifecycle_status: 'pending_review' }),␍
|
||||
]);␍
|
||||
const wrapper = mount(ShippingWorkflowTimeline, {␍
|
||||
props: { conversationId: 'conv-1', controller: buildController({ processing }) },␍
|
||||
...mountOptions,␍
|
||||
});␍
|
||||
await openDetailsDrawer(wrapper);␍
|
||||
// 断言:默认同时展示处理中与待复核文件␍
|
||||
expect(wrapper.find('[data-testid="shipping-workflow-item-SWI-B"]').exists()).toBe(true);␍
|
||||
expect(wrapper.find('[data-testid="shipping-workflow-item-SWI-A"]').exists()).toBe(true);␍
|
||||
});␍
|
||||
␍
|
||||
it('opens the review workspace directly for pending review items', async () => {␍
|
||||
const processing = processingFromDocuments([␍
|
||||
buildItem({␍
|
||||
item_no: 'SWI-REVIEW-OPEN',␍
|
||||
lifecycle_status: 'pending_review',␍
|
||||
current_run_no: 'RUN-REVIEW-1',␍
|
||||
current_case_no: 'CASE-REVIEW-1',␍
|
||||
current_document_id: 42,␍
|
||||
}),␍
|
||||
]);␍
|
||||
const wrapper = mount(ShippingWorkflowTimeline, {␍
|
||||
props: { conversationId: 'conv-1', controller: buildController({ processing }) },␍
|
||||
...mountOptions,␍
|
||||
});␍
|
||||
await openDetailsDrawer(wrapper);␍
|
||||
await wrapper.find('[data-testid="shipping-workflow-action-open-review"]').trigger('click');␍
|
||||
// 断言:跳转 order-review 并携带 run / case / document 上下文␍
|
||||
expect(routerPush).toHaveBeenCalledWith(expect.objectContaining({␍
|
||||
name: 'Chat',␍
|
||||
params: { agentId: 'agent-1' },␍
|
||||
query: expect.objectContaining({␍
|
||||
mode: 'order-review',␍
|
||||
run_no: 'RUN-REVIEW-1',␍
|
||||
case_no: 'CASE-REVIEW-1',␍
|
||||
document_id: '42',␍
|
||||
focus: 'draft',␍
|
||||
}),␍
|
||||
}));␍
|
||||
});␍
|
||||
␍
|
||||
it('cancels an item via Run API from in-app reason dialog', async () => {␍
|
||||
api.cancelRun.mockClear();␍
|
||||
const processing = processingFromDocuments([␍
|
||||
buildItem({␍
|
||||
item_no: 'SWI-CANCEL',␍
|
||||
lifecycle_status: 'extracting',␍
|
||||
lock_version: 3,␍
|
||||
current_run_no: 'RUN-CANCEL',␍
|
||||
available_actions: ['cancel'],␍
|
||||
}),␍
|
||||
]);␍
|
||||
const wrapper = mount(ShippingWorkflowTimeline, {␍
|
||||
props: { conversationId: 'conv-1', controller: buildController({ processing }) },␍
|
||||
...mountOptions,␍
|
||||
});␍
|
||||
await openDetailsDrawer(wrapper);␍
|
||||
await wrapper.find('[data-testid="shipping-workflow-action-cancel"]').trigger('click');␍
|
||||
await flushPromises();␍
|
||||
const reasonInput = wrapper.find('[data-testid="shipping-workflow-reason-input"]');␍
|
||||
// 断言:应用内原因弹窗出现␍
|
||||
expect(reasonInput.exists()).toBe(true);␍
|
||||
await reasonInput.setValue('cancel reason');␍
|
||||
await wrapper.find('[data-testid="shipping-workflow-reason-confirm"]').trigger('click');␍
|
||||
await flushPromises();␍
|
||||
// 断言:调用 Run 取消 API␍
|
||||
expect(api.cancelRun).toHaveBeenCalledWith('RUN-CANCEL', { reason: 'cancel reason' });␍
|
||||
});␍
|
||||
␍
|
||||
it('hides WF batch switcher as primary path', async () => {␍
|
||||
const processing = processingFromDocuments([buildItem({ item_no: 'SWI-A' })]);␍
|
||||
const wrapper = mount(ShippingWorkflowTimeline, {␍
|
||||
props: {␍
|
||||
conversationId: 'conv-1',␍
|
||||
controller: buildController({ processing }),␍
|
||||
},␍
|
||||
...mountOptions,␍
|
||||
});␍
|
||||
await openDetailsDrawer(wrapper);␍
|
||||
// 断言:批次切换器不再作为主路径展示␍
|
||||
expect(wrapper.find('[data-testid="shipping-workflow-batch-switcher"]').exists()).toBe(false);␍
|
||||
});␍
|
||||
␍
|
||||
it('shows reparse action for failed items', async () => {␍
|
||||
const processing = processingFromDocuments([␍
|
||||
buildItem({␍
|
||||
item_no: 'SWI-FAIL',␍
|
||||
lifecycle_status: 'failed',␍
|
||||
current_document_filename: 'bad.pdf',␍
|
||||
current_run_no: 'RUN-FAIL',␍
|
||||
available_actions: ['cancel', 'reparse'],␍
|
||||
reparse_kind: 'failed_run_retry',␍
|
||||
}),␍
|
||||
]);␍
|
||||
const wrapper = mount(ShippingWorkflowTimeline, {␍
|
||||
props: { conversationId: 'conv-1', controller: buildController({ processing }) },␍
|
||||
...mountOptions,␍
|
||||
});␍
|
||||
await openDetailsDrawer(wrapper);␍
|
||||
// 断言:失败项展示重识别按钮与文案␍
|
||||
expect(wrapper.find('[data-testid="shipping-workflow-action-reparse"]').exists()).toBe(true);␍
|
||||
expect(wrapper.text()).toContain('重试失败识别');␍
|
||||
});␍
|
||||
␍
|
||||
it('hides reparse for pending_review without available_actions.reparse', async () => {␍
|
||||
const processing = processingFromDocuments([␍
|
||||
buildItem({␍
|
||||
item_no: 'SWI-PR',␍
|
||||
lifecycle_status: 'pending_review',␍
|
||||
current_case_no: null,␍
|
||||
available_actions: ['cancel'],␍
|
||||
reparse_kind: null,␍
|
||||
}),␍
|
||||
]);␍
|
||||
const wrapper = mount(ShippingWorkflowTimeline, {␍
|
||||
props: { conversationId: 'conv-1', controller: buildController({ processing }) },␍
|
||||
...mountOptions,␍
|
||||
});␍
|
||||
await openDetailsDrawer(wrapper);␍
|
||||
// 断言:无 reparse 契约时不展示重识别␍
|
||||
expect(wrapper.find('[data-testid="shipping-workflow-action-reparse"]').exists()).toBe(false);␍
|
||||
});␍
|
||||
␍
|
||||
it('keeps sidebar width while showing inline workflow details', async () => {␍
|
||||
const processing = processingFromDocuments([buildItem()]);␍
|
||||
const wrapper = mount(ShippingWorkflowTimeline, {␍
|
||||
props: {␍
|
||||
conversationId: 'conv-1',␍
|
||||
controller: buildController({ processing }),␍
|
||||
},␍
|
||||
...mountOptions,␍
|
||||
});␍
|
||||
await openDetailsDrawer(wrapper);␍
|
||||
const aside = wrapper.find('[data-testid="shipping-workflow-timeline"]');␍
|
||||
// 断言:侧栏宽度不变␍
|
||||
expect(aside.classes().join(' ')).toContain('md:w-[clamp(20rem,28vw,30rem)]');␍
|
||||
const overlay = wrapper.find('[data-testid="shipping-workflow-details-drawer"]');␍
|
||||
// 断言:文件明细内联展示,非 modal␍
|
||||
expect(overlay.exists()).toBe(true);␍
|
||||
expect(overlay.classes().join(' ')).toContain('rounded-xl');␍
|
||||
expect(overlay.find('[role="dialog"]').exists()).toBe(false);␍
|
||||
});␍
|
||||
␍
|
||||
it('keeps panel expanded while processing tasks exist', async () => {␍
|
||||
const processing = processingFromDocuments([buildItem()], {␍
|
||||
user_task_no: 'OT-PIN',␍
|
||||
status_label: 'extracting',␍
|
||||
title: 'order.pdf',␍
|
||||
file_count: 1,␍
|
||||
run_no: 'RUN-PIN',␍
|
||||
});␍
|
||||
const wrapper = mount(ShippingWorkflowTimeline, {␍
|
||||
props: { conversationId: 'conv-1', controller: buildController({ processing }) },␍
|
||||
...mountOptions,␍
|
||||
});␍
|
||||
await flushPromises();␍
|
||||
const aside = wrapper.find('[data-testid="shipping-workflow-timeline"]');␍
|
||||
const toggle = wrapper.find('[data-testid="shipping-workflow-panel-toggle"]');␍
|
||||
// 断言:有 processing 任务时侧栏默认展开␍
|
||||
expect(aside.classes().join(' ')).not.toContain('!w-14');␍
|
||||
expect(wrapper.find('[data-testid="shipping-processing-task-OT-PIN"]').exists()).toBe(true);␍
|
||||
await toggle.trigger('click');␍
|
||||
await flushPromises();␍
|
||||
// 断言:点击收起仍保持展开(pinned)␍
|
||||
expect(aside.classes().join(' ')).not.toContain('!w-14');␍
|
||||
expect(wrapper.find('[data-testid="shipping-processing-task-OT-PIN"]').exists()).toBe(true);␍
|
||||
expect(wrapper.find('[data-testid="shipping-workflow-panel-pinned"]').exists()).toBe(true);␍
|
||||
expect(wrapper.find('[data-testid="shipping-workflow-panel-summary"]').exists()).toBe(true);␍
|
||||
expect(wrapper.find('[data-testid="shipping-processing-summary"]').exists()).toBe(false);␍
|
||||
});␍
|
||||
␍
|
||||
it('expands all effective PDFs for one task even when they belong to different runs', async () => {␍
|
||||
const docs = [␍
|
||||
buildItem({␍
|
||||
item_no: 'SWI-PDF-91',␍
|
||||
current_run_no: 'RUN-NEW',␍
|
||||
root_document_id: 91,␍
|
||||
current_document_id: 191,␍
|
||||
content_hash: 'hash-a',␍
|
||||
current_document_filename: '4518838152.pdf',␍
|
||||
}),␍
|
||||
buildItem({␍
|
||||
item_no: 'SWI-PDF-92',␍
|
||||
current_run_no: 'RUN-OLD',␍
|
||||
root_document_id: 92,␍
|
||||
current_document_id: 92,␍
|
||||
content_hash: 'hash-b',␍
|
||||
current_document_filename: '4518838154.pdf',␍
|
||||
}),␍
|
||||
];␍
|
||||
const processing = processingFromDocuments(docs, {␍
|
||||
user_task_no: 'OT-MULTI-RUN',␍
|
||||
status_label: 'extracting',␍
|
||||
title: null,␍
|
||||
display_kind: 'multi_document_task',␍
|
||||
document_names: ['4518838152.pdf', '4518838154.pdf'],␍
|
||||
file_count: 2,␍
|
||||
run_no: 'RUN-NEW',␍
|
||||
objects: [␍
|
||||
{␍
|
||||
kind: 'document', object_key: 'DOC-191', workflow_item_no: 'SWI-PDF-91', label: '4518838152.pdf',␍
|
||||
status_label: 'extracting', document_id: 191, root_document_id: 91,␍
|
||||
content_hash: 'hash-a', current_run_no: 'RUN-NEW',␍
|
||||
},␍
|
||||
{␍
|
||||
kind: 'document', object_key: 'DOC-92', workflow_item_no: 'SWI-PDF-92', label: '4518838154.pdf',␍
|
||||
status_label: 'pending_review', document_id: 92, root_document_id: 92,␍
|
||||
content_hash: 'hash-b', current_run_no: 'RUN-OLD',␍
|
||||
},␍
|
||||
],␍
|
||||
});␍
|
||||
const wrapper = mount(ShippingWorkflowTimeline, {␍
|
||||
props: { conversationId: 'conv-1', controller: buildController({ processing }) },␍
|
||||
...mountOptions,␍
|
||||
});␍
|
||||
await flushPromises();␍
|
||||
␍
|
||||
const task = wrapper.find('[data-testid="shipping-processing-task-OT-MULTI-RUN"]');␍
|
||||
expect(task.exists()).toBe(true);␍
|
||||
await task.findAll('button').at(-1)!.trigger('click');␍
|
||||
await flushPromises();␍
|
||||
␍
|
||||
// 断言:任务内两 PDF 均展示,无关 PDF 被过滤␍
|
||||
expect(wrapper.find('[data-testid="shipping-workflow-item-SWI-PDF-91"]').exists()).toBe(true);␍
|
||||
expect(wrapper.find('[data-testid="shipping-workflow-item-SWI-PDF-92"]').exists()).toBe(true);␍
|
||||
expect(wrapper.find('[data-testid="shipping-workflow-item-SWI-OTHER"]').exists()).toBe(false);␍
|
||||
});␍
|
||||
});␍
|
||||
File diff suppressed because it is too large.
Load diff
@@ -629,6 +629,8 @@ export function useChatPage() {
|
||||
activeShippingTaskDetail: shipping.activeShippingTaskDetail,
|
||||
getActiveOrderExtractionRunNo: shipping.getActiveOrderExtractionRunNo,
|
||||
workflowRefreshTrigger: shipping.workflowRefreshTrigger,
|
||||
focusedConversationTaskNo: shipping.focusedConversationTaskNo,
|
||||
setFocusedConversationTaskNo: shipping.setFocusedConversationTaskNo,
|
||||
shippingInventorySelectionActive: shipping.shippingInventorySelectionActive,
|
||||
shippingInventorySelectionTaskId: shipping.shippingInventorySelectionTaskId,
|
||||
switchShippingBatch: shipping.switchShippingBatch,
|
||||
|
||||
@@ -13,6 +13,7 @@ const { deleteAllChatSessions, deleteChatSession, listChatSessions } = vi.hoiste
|
||||
deleteChatSession: vi.fn(),
|
||||
listChatSessions: vi.fn(),
|
||||
}));
|
||||
const listWorkspaceShippingOrderExtractionRuns = vi.hoisted(() => vi.fn());
|
||||
|
||||
const {
|
||||
getSessionHistory,
|
||||
@@ -29,6 +30,7 @@ vi.mock('../api/chat.api', () => ({
|
||||
deleteChatSession,
|
||||
listChatSessions,
|
||||
}));
|
||||
vi.mock('../api/shipping.api', () => ({ listWorkspaceShippingOrderExtractionRuns }));
|
||||
|
||||
vi.mock('../stores/chat.store', () => ({
|
||||
useChatStore: () => ({
|
||||
@@ -43,6 +45,7 @@ describe('useChatSessions', () => {
|
||||
deleteAllChatSessions.mockReset();
|
||||
deleteChatSession.mockReset();
|
||||
listChatSessions.mockReset();
|
||||
listWorkspaceShippingOrderExtractionRuns.mockReset();
|
||||
getSessionHistory.mockReset();
|
||||
setSessionHistory.mockReset();
|
||||
patchSessionHistory.mockReset();
|
||||
@@ -91,4 +94,41 @@ describe('useChatSessions', () => {
|
||||
expect(runs.value).toEqual([]);
|
||||
expect(startNewChat).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('rebuilds order-review query from the selected conversation', async () => {
|
||||
const replace = vi.fn();
|
||||
listWorkspaceShippingOrderExtractionRuns.mockResolvedValue({
|
||||
items: [{ run_no: 'RUN-NEW', status: 'review_required' }],
|
||||
});
|
||||
const sessions = useChatSessions({
|
||||
deps: {
|
||||
t: (key: string) => key,
|
||||
router: { replace },
|
||||
route: {
|
||||
path: '/chat/7',
|
||||
query: {
|
||||
conversation_id: 'conv-old', mode: 'order-review', run_no: 'RUN-OLD',
|
||||
case_no: 'CASE-OLD', document_id: '91', focus: 'evidence',
|
||||
},
|
||||
},
|
||||
} as never,
|
||||
currentAgentId: computed(() => 7),
|
||||
conversationId: ref('conv-old'),
|
||||
activeRunId: ref(null),
|
||||
runs: ref([]),
|
||||
activateRun: vi.fn(),
|
||||
loadConversation: vi.fn(async () => {}),
|
||||
isSidebarOpen: ref(true),
|
||||
onConfirmDelete: vi.fn(),
|
||||
startNewChat: vi.fn(),
|
||||
});
|
||||
|
||||
await sessions.handleHistorySelect({ id: 2, conversation_id: 'conv-new' } as never);
|
||||
|
||||
expect(listWorkspaceShippingOrderExtractionRuns).toHaveBeenCalledWith('conv-new', 20);
|
||||
expect(replace).toHaveBeenCalledWith({
|
||||
path: '/chat/7',
|
||||
query: { conversation_id: 'conv-new', mode: 'order-review', run_no: 'RUN-NEW' },
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
deleteChatSession,
|
||||
listChatSessions,
|
||||
} from '../api/chat.api';
|
||||
import { listWorkspaceShippingOrderExtractionRuns } from '../api/shipping.api';
|
||||
import type { ChatRun, ChatSessionItem, DisplayHistoryItem } from '../types/chat.types';
|
||||
import type { ChatDeps } from './chat.deps';
|
||||
import { useChatStore } from '../stores/chat.store';
|
||||
@@ -133,6 +134,22 @@ export function useChatSessions(options: UseChatSessionsOptions) {
|
||||
return;
|
||||
}
|
||||
|
||||
const isOrderReview = route.query.mode === 'order-review';
|
||||
if (isOrderReview) {
|
||||
// 复核工作台的 Run/Case/文档上下文属于旧会话,切换时必须整体重建,不能只替换 conversation_id。
|
||||
const restored = await listWorkspaceShippingOrderExtractionRuns(item.conversation_id, 20);
|
||||
const nextRun = (restored.items || []).find((candidate) =>
|
||||
['review_required', 'partially_completed'].includes(String(candidate.status || '')),
|
||||
);
|
||||
const nextQuery: Record<string, string> = { conversation_id: item.conversation_id };
|
||||
if (nextRun?.run_no) {
|
||||
nextQuery.mode = 'order-review';
|
||||
nextQuery.run_no = String(nextRun.run_no);
|
||||
}
|
||||
await router.replace({ path: route.path, query: nextQuery });
|
||||
return;
|
||||
}
|
||||
|
||||
const nextQuery: Record<string, string | string[]> = { ...route.query, conversation_id: item.conversation_id };
|
||||
delete nextQuery.task_id;
|
||||
delete nextQuery.preset;
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
/**
|
||||
* features/chat/composables/useChatShipping.ts
|
||||
* 用途:发货通知聊天编排入口,组合 shipping/* 子模块并对 ChatView 暴露统一交互能力。
|
||||
* 依赖:shipping.api、shipping/ 下各 handler 工厂、chat.deps、chat.types、Vue refs/computed/watch。
|
||||
* 依赖:shipping.api(任务/客户等)、shipping/ 下各 handler 工厂、chat.deps、chat.types、Vue refs/computed/watch。
|
||||
* 逻辑:上游由 ChatView/ChatPage 调用本 composable;本文件维护会话任务摘要 + ui_state 同步,
|
||||
* 不再管理批次抽屉/焦点条/聊天履约写按钮(履约写改由任务处理工作台承接)。
|
||||
* 以及 focusedConversationTaskNo(提交追加优先级 / 侧栏焦点);
|
||||
* co8:shipping_batches 工作台轮询已下线,进度改由 shipping-processing projection 承接;
|
||||
* 保留 resolvedShippingBatchNo / shippingBatchSummary 等 ref 供调用方兼容,不再发起批次网络请求。
|
||||
*/
|
||||
|
||||
import {
|
||||
@@ -38,18 +40,18 @@ import {
|
||||
import { isShippingSpreadsheetFile } from '../shipping/shippingUploadPrompt';
|
||||
import { extractExt } from '../constants/shipping';
|
||||
import {
|
||||
getWorkspaceShippingConversationBatches,
|
||||
getWorkspaceShippingBatch,
|
||||
getWorkspaceShippingTask,
|
||||
listWorkspaceShippingCustomerOptions,
|
||||
confirmWorkspaceShippingCustomer,
|
||||
type ShippingBatchUiState,
|
||||
type ShippingBatchSummary,
|
||||
type ShippingConversationWorkspace,
|
||||
type ShippingTaskDetail,
|
||||
type ShippingTaskSummary,
|
||||
} from '@/features/chat/api/shipping.api';
|
||||
import type { ShippingCustomerOption } from '../types/shipping.api.types';
|
||||
import type {
|
||||
ShippingBatchSummary,
|
||||
ShippingBatchUiState,
|
||||
ShippingCustomerOption,
|
||||
} from '../types/shipping.api.types';
|
||||
import { buildShippingQueryShortageTurn } from '../shipping/shippingTurnActions';
|
||||
import {
|
||||
hasShortageLines,
|
||||
@@ -346,6 +348,12 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 同步批次摘要占位(co8 已下线批次详情 API)。
|
||||
*
|
||||
* 核心逻辑:batchNo 为空时清空摘要;否则仅回填本地 batch_no 与已有 task 焦点,不发起网络请求。
|
||||
* @param batchNo - 目标批次号
|
||||
*/
|
||||
const syncShippingBatchSummary = async (batchNo: string) => {
|
||||
const normalized = String(batchNo || '').trim();
|
||||
if (!normalized) {
|
||||
@@ -353,52 +361,32 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
shippingBatchTasks.value = [];
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const detail = await getWorkspaceShippingBatch(normalized);
|
||||
applyShippingBatchDetail(detail, normalized);
|
||||
} catch {
|
||||
// ignore summary refresh failure in chat flow
|
||||
resolvedShippingBatchNo.value = normalized;
|
||||
if (!activeShippingBatchNo.value) {
|
||||
activeShippingBatchNo.value = normalized;
|
||||
}
|
||||
shippingBatchSummary.value = {
|
||||
id: 0,
|
||||
batch_no: normalized,
|
||||
conversation_id: conversationId.value,
|
||||
current_focus_task_no: resolvedShippingTaskId.value || null,
|
||||
process_summary: null,
|
||||
};
|
||||
};
|
||||
|
||||
const applyConversationWorkspaceFocus = (
|
||||
workspace: ShippingConversationWorkspace,
|
||||
options?: { preferLatest?: boolean },
|
||||
) => {
|
||||
const batches = Array.isArray(workspace.batches) ? workspace.batches : [];
|
||||
if (!batches.length) return;
|
||||
const queryBatchNo = String(shippingBatchNoFromQuery.value || '').trim();
|
||||
const currentBatchNo = String(activeShippingBatchNo.value || resolvedShippingBatchNo.value || queryBatchNo || '').trim();
|
||||
const selectedBatch = selectShippingConversationBatch(
|
||||
batches,
|
||||
currentBatchNo,
|
||||
queryBatchNo,
|
||||
Boolean(options?.preferLatest),
|
||||
);
|
||||
if (!selectedBatch) return;
|
||||
if (options?.preferLatest) {
|
||||
activeShippingBatchNo.value = selectedBatch.batch_no;
|
||||
}
|
||||
applyShippingBatchDetail(selectedBatch, selectedBatch.batch_no);
|
||||
};
|
||||
|
||||
/**
|
||||
* 同步会话批次工作台(co8 已下线 conversation batches API)。
|
||||
*
|
||||
* 核心逻辑:保留调用签名供抽取 Run / 终态刷新链路兼容;始终清空 workspace 并返回 false,不发起网络。
|
||||
* @param _options - 历史参数,保留兼容
|
||||
* @returns 恒为 false
|
||||
*/
|
||||
const syncShippingConversationWorkspace = async (
|
||||
options?: { preferLatest?: boolean },
|
||||
_options?: { preferLatest?: boolean },
|
||||
): Promise<boolean> => {
|
||||
const localConversationId = String(conversationId.value || '').trim();
|
||||
if (!localConversationId || !isShippingNoticeAgent.value) {
|
||||
shippingConversationWorkspace.value = null;
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
const workspace = await getWorkspaceShippingConversationBatches(localConversationId);
|
||||
shippingConversationWorkspace.value = workspace;
|
||||
applyConversationWorkspaceFocus(workspace, options);
|
||||
return true;
|
||||
} catch {
|
||||
shippingConversationWorkspace.value = null;
|
||||
return false;
|
||||
}
|
||||
void _options;
|
||||
shippingConversationWorkspace.value = null;
|
||||
return false;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -469,13 +457,8 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
recovered = true;
|
||||
}
|
||||
if (!snapshot && batchNo) {
|
||||
try {
|
||||
const detail = await getWorkspaceShippingBatch(batchNo);
|
||||
applyShippingBatchDetail(detail, batchNo);
|
||||
recovered = true;
|
||||
} catch {
|
||||
// ignore and continue with task-first recovery
|
||||
}
|
||||
await syncShippingBatchSummary(batchNo);
|
||||
recovered = true;
|
||||
}
|
||||
if (taskNo) {
|
||||
await syncActiveShippingTaskDetail(taskNo);
|
||||
@@ -486,13 +469,8 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
activeShippingBatchNo.value = detailBatchNo;
|
||||
}
|
||||
if (!snapshot && batchNo && String(shippingBatchSummary.value?.batch_no || '').trim() !== batchNo) {
|
||||
try {
|
||||
const detail = await getWorkspaceShippingBatch(batchNo);
|
||||
applyShippingBatchDetail(detail, batchNo);
|
||||
recovered = true;
|
||||
} catch {
|
||||
// ignore and keep task-only recovery
|
||||
}
|
||||
await syncShippingBatchSummary(batchNo);
|
||||
recovered = true;
|
||||
}
|
||||
recovered = recovered || Boolean(activeShippingTaskDetail.value);
|
||||
}
|
||||
@@ -504,33 +482,17 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
);
|
||||
|
||||
/**
|
||||
* 切换会话上传摘要中的活动批次(只读同步,无焦点条/抽屉写操作)。
|
||||
* 切换会话上传摘要中的活动批次(co8 已下线,保留签名兼容)。
|
||||
*
|
||||
* 核心逻辑:批次工作台 API 已移除,调用时仅提示用户改由右侧 processing 工作台操作。
|
||||
* @param batchNo - 目标批次号
|
||||
* @returns 是否切换成功
|
||||
* @returns 恒为 false
|
||||
*/
|
||||
const switchShippingBatch = async (batchNo: string) => {
|
||||
const normalizedBatchNo = String(batchNo || '').trim();
|
||||
if (!normalizedBatchNo) return false;
|
||||
activeShippingBatchNo.value = normalizedBatchNo;
|
||||
resolvedShippingBatchNo.value = normalizedBatchNo;
|
||||
const workspaceBatch = shippingConversationWorkspace.value?.batches.find((item) => item.batch_no === normalizedBatchNo);
|
||||
if (workspaceBatch) {
|
||||
applyShippingBatchDetail(workspaceBatch, normalizedBatchNo);
|
||||
} else {
|
||||
await syncShippingBatchSummary(normalizedBatchNo);
|
||||
}
|
||||
const nextFocusState = resolveShippingBatchFocusState(
|
||||
shippingBatchSummary.value,
|
||||
shippingBatchTasks.value,
|
||||
'',
|
||||
);
|
||||
const nextTaskNo = nextFocusState.taskNo;
|
||||
if (nextTaskNo) {
|
||||
resolvedShippingTaskId.value = nextTaskNo;
|
||||
await syncActiveShippingTaskDetail(nextTaskNo);
|
||||
}
|
||||
await refreshShippingActions();
|
||||
return true;
|
||||
msg.warning(t('chat.shippingNoticeUi.batchSwitchRemoved'));
|
||||
return false;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -540,6 +502,9 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
* 避免会话摘要和待上传库存文件残留到下一次新会话。
|
||||
*/
|
||||
const resetShippingConversationState = () => {
|
||||
// 新对话不会触发 onConversationIdChanging;必须在此清掉旧 Run,
|
||||
// 否则右侧面板仍会将其作为当前会话的展示条件。
|
||||
shippingOrderExtractionRuns.clearActiveRun();
|
||||
shippingAutoFlowRequested.value = false;
|
||||
pendingShippingUploadTaskId.value = '';
|
||||
pendingShippingNoticeTaskId.value = '';
|
||||
@@ -796,6 +761,11 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
const bumpWorkflowRefresh = () => {
|
||||
workflowRefreshTrigger.value += 1;
|
||||
};
|
||||
/** 侧栏/提交共用的当前聚焦用户可见任务(OT-…)。 */
|
||||
const focusedConversationTaskNo = ref<string | null>(null);
|
||||
const setFocusedConversationTaskNo = (taskNo: string | null) => {
|
||||
focusedConversationTaskNo.value = String(taskNo || '').trim() || null;
|
||||
};
|
||||
const shippingOrderExtractionRuns = useShippingOrderExtractionRuns({
|
||||
messages,
|
||||
conversationId,
|
||||
@@ -818,6 +788,8 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
},
|
||||
onRetryError: (message) => msg.error(message),
|
||||
onWorkflowRefresh: bumpWorkflowRefresh,
|
||||
getFocusedUserTaskNo: () => focusedConversationTaskNo.value,
|
||||
setFocusedUserTaskNo: setFocusedConversationTaskNo,
|
||||
t,
|
||||
});
|
||||
|
||||
@@ -1024,6 +996,8 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
getParsedIntakeNos: shippingIntakes.getParsedIntakeNos,
|
||||
getSelectedCandidateNos: shippingIntakes.getSelectedCandidateNos,
|
||||
clearConsumedNoticeAttachments: shippingIntakes.clearConsumedAttachments,
|
||||
enqueueNoticeFiles: shippingIntakes.enqueueNoticeFiles,
|
||||
startOrderExtractionRun: (...args) => shippingOrderExtractionRuns.startRun(...args),
|
||||
sendTemporaryInventoryMessage: async (assetNo, fileName) => sendMessage(
|
||||
`我已上传库存文件:${fileName},请先检查文件结构并说明下一步。`,
|
||||
currentAgentId.value,
|
||||
@@ -1147,6 +1121,7 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
onNoticeBatchConversationChanging(nextId, prevId);
|
||||
shippingIntakes.stopPolling();
|
||||
if (nextId && nextId !== prevId) {
|
||||
focusedConversationTaskNo.value = null;
|
||||
void shippingIntakes.restoreForConversation(nextId);
|
||||
void shippingOrderExtractionRuns.restoreForConversation(nextId);
|
||||
} else {
|
||||
@@ -1163,33 +1138,17 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
};
|
||||
|
||||
/**
|
||||
* 重试当前聚焦批次中可恢复的失败/排队任务(供页面级确认弹窗调用;Chat 本身不再挂批次抽屉按钮)。
|
||||
* @returns 成功时返回 started/skipped;失败或跳过时返回 null
|
||||
* 重试当前聚焦批次中可恢复的失败/排队任务(co8 已下线,保留签名兼容)。
|
||||
*
|
||||
* 核心逻辑:批次重试 API 已移除,调用时提示用户改由 processing 工作台或任务动作重试。
|
||||
* @returns 恒为 null
|
||||
*/
|
||||
const retryCurrentShippingBatchPendingTasks = async (): Promise<{
|
||||
started: number;
|
||||
skipped: number;
|
||||
} | null> => {
|
||||
const batchNo = getActiveShippingBatchNo();
|
||||
if (!batchNo) return null;
|
||||
if (isShippingActionBusy.value) {
|
||||
msg.warning(t('chat.shippingNoticeUi.actionBusyHint'));
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
const { retryWorkspaceShippingBatchPending } = await import('@/features/chat/api/shipping.api');
|
||||
const result = await retryWorkspaceShippingBatchPending(batchNo);
|
||||
await syncShippingConversationWorkspace();
|
||||
await syncShippingBatchSummary(batchNo);
|
||||
await refreshShippingActions();
|
||||
return {
|
||||
started: Number(result.started ?? 0),
|
||||
skipped: Number(result.skipped ?? 0),
|
||||
};
|
||||
} catch (error) {
|
||||
msg.error(error instanceof Error ? error.message : t('chat.shippingNoticeUi.retryFailed'));
|
||||
return null;
|
||||
}
|
||||
msg.warning(t('chat.shippingNoticeUi.batchRetryRemoved'));
|
||||
return null;
|
||||
};
|
||||
|
||||
const handleShippingLocalFilesSelected = (event: Event): boolean => {
|
||||
@@ -1247,8 +1206,8 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
/**
|
||||
* 启停发货会话状态短轮询。
|
||||
*
|
||||
* 核心逻辑:聊天流当前没有 shipping 专属 SSE;因此在存在任务/批次上下文时每 3 秒补拉一次,
|
||||
* 让右侧会话摘要与通知态 ui_state 能在后端异步状态变化后自动更新。
|
||||
* 核心逻辑:co8 后不再轮询 shipping_batches;仅在存在任务上下文时每 3 秒补拉任务详情与动作按钮,
|
||||
* 批次/处理进度改由 shipping-processing projection 承接。
|
||||
*/
|
||||
const restartShippingStatusPolling = () => {
|
||||
if (shippingStatusPollTimer) {
|
||||
@@ -1256,22 +1215,16 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
shippingStatusPollTimer = null;
|
||||
}
|
||||
if (!isShippingNoticeAgent.value) return;
|
||||
const batchNo = getActiveShippingBatchNo();
|
||||
const taskId = getActiveBatchTaskId();
|
||||
if (!batchNo && !taskId) return;
|
||||
const taskId = getActiveBatchTaskId() || getActiveShippingTaskId();
|
||||
if (!taskId) return;
|
||||
|
||||
shippingStatusPollTimer = setInterval(() => {
|
||||
if (!isShippingNoticeAgent.value) return;
|
||||
const nextBatchNo = getActiveShippingBatchNo();
|
||||
const nextTaskId = getActiveBatchTaskId();
|
||||
if (!nextBatchNo && !nextTaskId) return;
|
||||
const nextTaskId = getActiveBatchTaskId() || getActiveShippingTaskId();
|
||||
if (!nextTaskId) return;
|
||||
void (async () => {
|
||||
await syncShippingConversationWorkspace();
|
||||
if (nextBatchNo) await syncShippingBatchSummary(nextBatchNo);
|
||||
if (nextTaskId) {
|
||||
await syncActiveShippingTaskDetail(nextTaskId);
|
||||
await syncConversationMessagesIfNeeded(nextTaskId);
|
||||
}
|
||||
await syncActiveShippingTaskDetail(nextTaskId);
|
||||
await syncConversationMessagesIfNeeded(nextTaskId);
|
||||
await refreshShippingActions();
|
||||
if (!hasRunningShippingBatchTasks() && !isShippingActionBusy.value && shippingStatusPollTimer) {
|
||||
clearInterval(shippingStatusPollTimer);
|
||||
@@ -1395,6 +1348,8 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
reparseOrderExtractionRun: shippingOrderExtractionRuns.reparseRun,
|
||||
getActiveOrderExtractionRunNo: shippingOrderExtractionRuns.getActiveRunNo,
|
||||
workflowRefreshTrigger,
|
||||
focusedConversationTaskNo,
|
||||
setFocusedConversationTaskNo,
|
||||
shippingNoticeAllReadyForConfirmation: shippingIntakes.allReadyForConfirmation,
|
||||
setShippingCandidateSelected,
|
||||
resolveShippingCandidateDuplicate,
|
||||
@@ -1404,6 +1359,7 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
showShippingCustomerDialog,
|
||||
shippingCustomerOptions,
|
||||
shippingCustomerLoading,
|
||||
openShippingCustomerDialog,
|
||||
searchShippingCustomers,
|
||||
confirmShippingCustomer,
|
||||
closeShippingCustomerDialog: () => {
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
/**
|
||||
* features/chat/e2e/shipping-conversation-multiple-runs.spec.ts
|
||||
* 用途:会话多任务聚合阶段 3–5 契约冒烟——发送无确认框、任务分组主路径、WF 非主标题。
|
||||
* 依赖:Vitest、conversationProcessingProjection、shippingSubmissionFeedback。
|
||||
* 逻辑:不启浏览器;用投影/反馈纯函数断言产品契约,避免 e2e 环境依赖。
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
classifyConversationProcessingGroup,
|
||||
groupConversationProcessingTasks,
|
||||
projectConversationProcessingTasks,
|
||||
} from '@/features/chat/shipping/conversationProcessingProjection';
|
||||
import { buildShippingSubmissionFeedback } from '@/features/chat/shipping/shippingSubmissionFeedback';
|
||||
import type { ShippingWorkflowItem } from '@/features/chat/types/shipping.api.types';
|
||||
|
||||
function item(partial: Partial<ShippingWorkflowItem>): ShippingWorkflowItem {
|
||||
return {
|
||||
item_no: 'WI-1',
|
||||
workflow_no: 'WF-1',
|
||||
conversation_id: 'conv-1',
|
||||
root_document_id: 1,
|
||||
current_document_id: 1,
|
||||
current_version_no: 1,
|
||||
lifecycle_status: 'queued',
|
||||
current_stage: 'queued',
|
||||
lock_version: 1,
|
||||
...partial,
|
||||
};
|
||||
}
|
||||
|
||||
describe('shipping conversation multiple runs e2e contract', () => {
|
||||
it('maps backend decisions to non-blocking feedback without dialog keys', () => {
|
||||
const appended = buildShippingSubmissionFeedback({
|
||||
decision: 'appended',
|
||||
user_task_no: 'OT-1',
|
||||
run_no: 'RUN-1',
|
||||
created_new: false,
|
||||
}, 2);
|
||||
const created = buildShippingSubmissionFeedback({
|
||||
decision: 'created',
|
||||
user_task_no: 'OT-2',
|
||||
run_no: 'RUN-2',
|
||||
created_new: true,
|
||||
}, 1);
|
||||
// 关键断言:仅两种决策;短时标签供右侧卡,不依赖确认弹窗。
|
||||
expect(appended.decision).toBe('appended');
|
||||
expect(created.decision).toBe('created');
|
||||
expect([appended.badgeCode, created.badgeCode]).toEqual(['just_appended', 'just_created']);
|
||||
});
|
||||
|
||||
it('keeps WF/run ids as secondary while grouping by user-visible tasks', () => {
|
||||
const tasks = projectConversationProcessingTasks([
|
||||
item({
|
||||
item_no: 'WI-A',
|
||||
workflow_no: 'WF-AAA',
|
||||
current_run_no: 'SNER-A',
|
||||
lifecycle_status: 'pending_review',
|
||||
}),
|
||||
item({
|
||||
item_no: 'WI-B',
|
||||
workflow_no: 'WF-BBB',
|
||||
current_run_no: 'SNER-B',
|
||||
lifecycle_status: 'extracting',
|
||||
}),
|
||||
]);
|
||||
const projection = groupConversationProcessingTasks(tasks);
|
||||
expect(projection.summary.total_tasks).toBe(2);
|
||||
expect(projection.needs_action).toHaveLength(1);
|
||||
expect(projection.processing).toHaveLength(1);
|
||||
// 关键断言:主对象是 OT-;WF 仅挂在任务上供诊断。
|
||||
expect(projection.needs_action[0]?.user_task_no.startsWith('OT-')).toBe(true);
|
||||
expect(projection.needs_action[0]?.workflow_no).toBe('WF-AAA');
|
||||
expect(classifyConversationProcessingGroup('failed')).toBe('needs_action');
|
||||
});
|
||||
|
||||
it('scales to twenty user-visible tasks without inventing progress percent', () => {
|
||||
const items = Array.from({ length: 20 }, (_, index) => item({
|
||||
item_no: `WI-${index}`,
|
||||
current_run_no: `SNER-${index}`,
|
||||
lifecycle_status: index % 2 === 0 ? 'extracting' : 'closed',
|
||||
}));
|
||||
const projection = groupConversationProcessingTasks(projectConversationProcessingTasks(items));
|
||||
expect(projection.summary.total_tasks).toBe(20);
|
||||
expect(projection.summary.processing + projection.summary.history).toBe(20);
|
||||
expect(JSON.stringify(projection).includes('percent')).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -1,8 +1,8 @@
|
||||
/**
|
||||
* features/chat/page/useChatPageConversation.spec.ts
|
||||
* 用途:验证新建聊天与 Agent 切换时清理发货通知待重试建批幂等状态。
|
||||
* 用途:验证新建聊天与 Agent 切换时清理发货通知外围状态。
|
||||
* 依赖:vitest、vue refs/computed、useChatPageConversation、useChatShippingUploadHandler。
|
||||
* 逻辑:覆盖 createNewChatView 不经 onConversationIdChanging 时仍生成新幂等键的回归场景。
|
||||
* 逻辑:覆盖 createNewChatView / Agent 切换调用 peripheral reset;建批幂等已随 co8 下线。
|
||||
*/
|
||||
import { computed, ref } from 'vue';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
@@ -18,21 +18,10 @@ const { listChatMessages } = vi.hoisted(() => ({
|
||||
listChatMessages: vi.fn(),
|
||||
}));
|
||||
|
||||
const { computeNoticeFilesContentFingerprint } = vi.hoisted(() => ({
|
||||
computeNoticeFilesContentFingerprint: vi.fn(async (files: File[]) => {
|
||||
const content = await files[0]?.text();
|
||||
return `fp-${content || 'empty'}`;
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock('../api/chat.api', () => ({
|
||||
listChatMessages,
|
||||
}));
|
||||
|
||||
vi.mock('../shipping/shippingNoticeBatchIdempotency', () => ({
|
||||
computeNoticeFilesContentFingerprint,
|
||||
}));
|
||||
|
||||
const createConversationContext = () => {
|
||||
const conversationId = ref<string | null>('conv-a');
|
||||
const messages = ref([]);
|
||||
@@ -41,6 +30,7 @@ const createConversationContext = () => {
|
||||
messages.value = [];
|
||||
});
|
||||
|
||||
const resetPeripheralState = vi.fn();
|
||||
return {
|
||||
conversationId,
|
||||
messages,
|
||||
@@ -68,18 +58,19 @@ const createConversationContext = () => {
|
||||
input: ref(''),
|
||||
resetCurrentAgent: vi.fn(),
|
||||
copiedIndex: ref(null),
|
||||
resetPeripheralState: vi.fn(),
|
||||
resetPeripheralState,
|
||||
filePreviewVisible: ref(false),
|
||||
previewFile: ref(null),
|
||||
previewFiles: ref([]),
|
||||
currentPreviewIndex: ref(0),
|
||||
}),
|
||||
resetPeripheralState,
|
||||
};
|
||||
};
|
||||
|
||||
const createUploadContext = (
|
||||
conversationId: ReturnType<typeof ref<string | null>>,
|
||||
startChatTurn: ReturnType<typeof vi.fn>,
|
||||
enqueueNoticeFiles: ReturnType<typeof vi.fn>,
|
||||
): ShippingUploadHandlerContext => ({
|
||||
conversationId,
|
||||
currentAgentId: computed(() => 42),
|
||||
@@ -97,35 +88,32 @@ const createUploadContext = (
|
||||
shippingBatchTasks: ref([]),
|
||||
shippingInventorySelectionActive: ref(false),
|
||||
shippingInventorySelectionTaskId: ref(''),
|
||||
shippingInventorySchemaPreviewCache: ref({}),
|
||||
getActiveShippingTaskId: () => '',
|
||||
startChatTurn,
|
||||
startChatTurn: vi.fn(async () => true),
|
||||
refreshShippingActions: vi.fn(async () => undefined),
|
||||
msg: { warning: vi.fn() },
|
||||
msg: { warning: vi.fn(), info: vi.fn() },
|
||||
t: (key: string) => key,
|
||||
enqueueNoticeFiles,
|
||||
startOrderExtractionRun: vi.fn(async () => true),
|
||||
sendTemporaryInventoryMessage: vi.fn(async () => undefined),
|
||||
});
|
||||
|
||||
describe('useChatPageConversation', () => {
|
||||
beforeEach(() => {
|
||||
listChatMessages.mockReset();
|
||||
computeNoticeFilesContentFingerprint.mockReset();
|
||||
computeNoticeFilesContentFingerprint.mockImplementation(async (files: File[]) => {
|
||||
const content = await files[0]?.text();
|
||||
return `fp-${content || 'empty'}`;
|
||||
});
|
||||
resetShippingNoticeBatchSubmitStateForTests();
|
||||
});
|
||||
|
||||
it('startNewChat clears pending notice batch retry and next upload uses a new idempotency key', async () => {
|
||||
const startChatTurn = vi.fn(async () => false);
|
||||
it('startNewChat clears peripheral state and subsequent notice upload still enqueues intakes', async () => {
|
||||
const enqueueNoticeFiles = vi.fn(async () => undefined);
|
||||
const { conversationId, createNewChatView, api } = createConversationContext();
|
||||
const { handleShippingAutoUploadNoticeBatch } = createShippingUploadHandlers(
|
||||
createUploadContext(conversationId, startChatTurn),
|
||||
createUploadContext(conversationId, enqueueNoticeFiles),
|
||||
);
|
||||
const file = new File(['notice'], 'notice.pdf', { type: 'application/pdf' });
|
||||
|
||||
await handleShippingAutoUploadNoticeBatch([file]);
|
||||
const firstKey = (startChatTurn.mock.calls[0]?.[0] as { payload?: Record<string, unknown> })?.payload?.idempotency_key;
|
||||
expect(enqueueNoticeFiles).toHaveBeenCalledTimes(1);
|
||||
|
||||
api.startNewChat();
|
||||
|
||||
@@ -133,23 +121,28 @@ describe('useChatPageConversation', () => {
|
||||
expect(conversationId.value).toBeNull();
|
||||
|
||||
await handleShippingAutoUploadNoticeBatch([file]);
|
||||
const secondKey = (startChatTurn.mock.calls[1]?.[0] as { payload?: Record<string, unknown> })?.payload?.idempotency_key;
|
||||
|
||||
expect(firstKey).toBeTruthy();
|
||||
expect(secondKey).toBeTruthy();
|
||||
expect(secondKey).not.toBe(firstKey);
|
||||
expect(enqueueNoticeFiles).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('resetChatStateForAgentChange clears pending notice batch retry and next upload uses a new idempotency key', async () => {
|
||||
const startChatTurn = vi.fn(async () => false);
|
||||
it('startNewChat calls peripheral reset so a shipping Run cannot remain visible in the blank view', () => {
|
||||
const { api, resetPeripheralState } = createConversationContext();
|
||||
|
||||
api.startNewChat();
|
||||
|
||||
// 关键断言:Shipping 状态在 useChatShipping.resetShippingConversationState 中随该回调清理。
|
||||
expect(resetPeripheralState).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('resetChatStateForAgentChange clears peripheral state and subsequent notice upload still enqueues intakes', async () => {
|
||||
const enqueueNoticeFiles = vi.fn(async () => undefined);
|
||||
const { conversationId, createNewChatView, api } = createConversationContext();
|
||||
const { handleShippingAutoUploadNoticeBatch } = createShippingUploadHandlers(
|
||||
createUploadContext(conversationId, startChatTurn),
|
||||
createUploadContext(conversationId, enqueueNoticeFiles),
|
||||
);
|
||||
const file = new File(['notice'], 'notice.pdf', { type: 'application/pdf' });
|
||||
|
||||
await handleShippingAutoUploadNoticeBatch([file]);
|
||||
const firstKey = (startChatTurn.mock.calls[0]?.[0] as { payload?: Record<string, unknown> })?.payload?.idempotency_key;
|
||||
expect(enqueueNoticeFiles).toHaveBeenCalledTimes(1);
|
||||
|
||||
api.resetChatStateForAgentChange();
|
||||
|
||||
@@ -157,10 +150,6 @@ describe('useChatPageConversation', () => {
|
||||
expect(conversationId.value).toBeNull();
|
||||
|
||||
await handleShippingAutoUploadNoticeBatch([file]);
|
||||
const secondKey = (startChatTurn.mock.calls[1]?.[0] as { payload?: Record<string, unknown> })?.payload?.idempotency_key;
|
||||
|
||||
expect(firstKey).toBeTruthy();
|
||||
expect(secondKey).toBeTruthy();
|
||||
expect(secondKey).not.toBe(firstKey);
|
||||
expect(enqueueNoticeFiles).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
});
|
||||
@@ -47,4 +47,15 @@ describe('parseOrderReviewConfirmResponse', () => {
|
||||
it('returns null without task_no', () => {
|
||||
expect(parseOrderReviewConfirmResponse(baseResponse({ task_no: null }))).toBeNull();
|
||||
});
|
||||
|
||||
it('prefers order_task_no for focus identity and keeps Notice as taskNo', () => {
|
||||
const parsed = parseOrderReviewConfirmResponse(baseResponse({
|
||||
task_no: 'SN-NOTICE',
|
||||
shipping_notice_no: 'SN-NOTICE',
|
||||
order_task_no: 'OT-ROOT-C102',
|
||||
}));
|
||||
// 关键断言:对话聚焦必须用 OT,不能把 Notice 编号当成 OT。
|
||||
expect(parsed?.taskNo).toBe('SN-NOTICE');
|
||||
expect(parsed?.orderTaskNo).toBe('OT-ROOT-C102');
|
||||
});
|
||||
});
|
||||
@@ -2,7 +2,8 @@
|
||||
* features/chat/shipping-review/parseOrderReviewConfirmResponse.ts
|
||||
* 用途:统一解析复核确认建单 API 的业务态,禁止调用方仅凭 HTTP/success/confirm_ok 判定推进成功。
|
||||
* 依赖:ShippingOrderReviewConfirmResponse 类型。
|
||||
* 逻辑:ShippingOrderReviewView / 其他确认调用方共用;与后端 resolve_confirm_outcome 枚举对齐。
|
||||
* 逻辑:ShippingOrderReviewView / 其他确认调用方共用;与后端 resolve_confirm_outcome 枚举对齐;
|
||||
* 同时暴露 shipping_notice_no 与 order_task_no,禁止用 Notice 编号聚焦 OT 卡。
|
||||
*/
|
||||
|
||||
import type { ShippingOrderReviewConfirmResponse } from '@/features/chat/types/shipping.api.types';
|
||||
@@ -16,7 +17,10 @@ export type ShippingOrderReviewConfirmOutcome =
|
||||
|
||||
/** 确认响应解析结果:建单与自动推进解耦。 */
|
||||
export interface ParsedOrderReviewConfirmResult {
|
||||
/** 正式 ShippingNotice 编号(自动推进 / 工作台)。 */
|
||||
taskNo: string;
|
||||
/** Candidate 一对一 OT 编号(对话右侧聚焦)。 */
|
||||
orderTaskNo: string;
|
||||
confirmOk: boolean;
|
||||
confirmOutcome: ShippingOrderReviewConfirmOutcome;
|
||||
/** 自动推进已入队/启动 */
|
||||
@@ -36,17 +40,26 @@ const PROGRESS_FAILED_STATUSES = new Set([
|
||||
|
||||
/**
|
||||
* 解析复核确认响应的业务态。
|
||||
* 核心逻辑:confirm_ok 仅表示建单成功;推进成败读 confirm_outcome / auto_progress.status。
|
||||
* 核心逻辑:confirm_ok 仅表示建单成功;推进成败读 confirm_outcome / auto_progress.status;
|
||||
* focus / 统一进度只认 order_task_no,task_no 仅表示 Notice。
|
||||
*
|
||||
* @param response - confirm API data(非 HTTP envelope)
|
||||
* @returns 解析结果;无 task_no 时返回 null
|
||||
* @returns 解析结果;无 Notice task_no 时返回 null
|
||||
*/
|
||||
export function parseOrderReviewConfirmResponse(
|
||||
response: ShippingOrderReviewConfirmResponse | null | undefined,
|
||||
): ParsedOrderReviewConfirmResult | null {
|
||||
const taskNo = String(response?.task_no || '').trim();
|
||||
const taskNo = String(
|
||||
response?.shipping_notice_no || response?.task_no || '',
|
||||
).trim();
|
||||
if (!taskNo) return null;
|
||||
|
||||
const orderTaskNo = String(
|
||||
response?.order_task_no
|
||||
|| response?.case?.order_task_no
|
||||
|| '',
|
||||
).trim();
|
||||
|
||||
const progressStatus = String(response?.auto_progress?.status || '').trim();
|
||||
const confirmOutcome = String(response?.confirm_outcome || '').trim()
|
||||
|| (PROGRESS_FAILED_STATUSES.has(progressStatus)
|
||||
@@ -63,6 +76,7 @@ export function parseOrderReviewConfirmResponse(
|
||||
|
||||
return {
|
||||
taskNo,
|
||||
orderTaskNo,
|
||||
confirmOk: response?.confirm_ok !== false,
|
||||
confirmOutcome,
|
||||
autoProgressStarted,
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
/**
|
||||
* features/chat/shipping-review/showReviewResumeOutcome.ts
|
||||
* 用途:复核写操作后统一展示 resume_outcome 提示(与 Customer 面板一致)。
|
||||
* 依赖:vue-i18n、ShippingOrderReviewResumeOutcome。
|
||||
* 逻辑:各 Reservation / 冲突 / 重复 / 履约面板在 API 成功后调用本 helper。
|
||||
*/
|
||||
import type { ComposerTranslation } from 'vue-i18n';
|
||||
import type { ShippingOrderReviewResumeOutcome } from '../types/shipping.api.types';
|
||||
|
||||
type ToastApi = {
|
||||
success: (message: string) => void;
|
||||
};
|
||||
|
||||
/**
|
||||
* 按 resume_outcome 展示成功提示;无 outcome 时使用 fallbackSuccess。
|
||||
* 核心逻辑:auto_created/idempotent_replay → 自动建单;waiting_manual_confirm → 待人工确认。
|
||||
* @param resume - 后端统一恢复协调结果
|
||||
* @param msg - useMessage 实例
|
||||
* @param t - vue-i18n translate
|
||||
* @param fallbackSuccess - 无特殊 outcome 时的默认成功文案
|
||||
* @returns 是否已展示 resume 专用提示(调用方可跳过 fallback)
|
||||
*/
|
||||
export function showReviewResumeOutcome(
|
||||
resume: ShippingOrderReviewResumeOutcome | null | undefined,
|
||||
msg: ToastApi,
|
||||
t: ComposerTranslation,
|
||||
fallbackSuccess?: string,
|
||||
): void {
|
||||
const outcome = String(resume?.outcome || '').trim();
|
||||
if (outcome === 'auto_created' || outcome === 'idempotent_replay') {
|
||||
msg.success(t('chat.shippingOrderReview.resume.autoCreated', {
|
||||
taskNo: resume?.task_no || '',
|
||||
}));
|
||||
return;
|
||||
}
|
||||
if (outcome === 'waiting_manual_confirm') {
|
||||
msg.success(t('chat.shippingOrderReview.resume.waitingManualConfirm'));
|
||||
return;
|
||||
}
|
||||
if (fallbackSuccess) {
|
||||
msg.success(fallbackSuccess);
|
||||
}
|
||||
}
|
||||
@@ -54,8 +54,8 @@ const api = vi.hoisted(() => ({
|
||||
|
||||
getPreview: vi.fn(),
|
||||
|
||||
listWorkflows: vi.fn(),
|
||||
getWorkflowItem: vi.fn(),
|
||||
getExtractionRun: vi.fn(),
|
||||
getProcessingWorkItem: vi.fn(),
|
||||
|
||||
reparseDocument: vi.fn(),
|
||||
|
||||
@@ -80,9 +80,8 @@ vi.mock('../api/shipping.api', () => ({
|
||||
|
||||
getWorkspaceShippingOrderReviewPreview: api.getPreview,
|
||||
|
||||
listWorkspaceShippingWorkflows: api.listWorkflows,
|
||||
|
||||
getWorkspaceShippingWorkflowItem: api.getWorkflowItem,
|
||||
getWorkspaceShippingOrderExtractionRun: api.getExtractionRun,
|
||||
getWorkspaceShippingProcessingWorkItem: api.getProcessingWorkItem,
|
||||
|
||||
putWorkspaceShippingOrderReviewInventoryCandidates: api.putInventoryCandidates,
|
||||
postWorkspaceShippingOrderReviewInventoryRoutingReroute: api.rerouteInventoryRouting,
|
||||
@@ -224,17 +223,12 @@ describe('useShippingOrderReview historical readonly', () => {
|
||||
|
||||
|
||||
it('forces readonly when session work item is closed', () => {
|
||||
|
||||
expect(isReviewWorkItemClosed({ lifecycle_status: 'closed', current_case_no: 'CASE-1' })).toBe(true);
|
||||
|
||||
expect(isReviewWorkItemClosed({ lifecycle_status: 'manual_upload_pending', current_case_no: 'CASE-1' })).toBe(false);
|
||||
expect(isReviewReadOnly(
|
||||
|
||||
{ case_no: 'CASE-1', status: 'draft' },
|
||||
|
||||
{ current_case_no: 'CASE-1', lifecycle_status: 'closed' },
|
||||
|
||||
)).toBe(true);
|
||||
|
||||
});
|
||||
|
||||
});
|
||||
@@ -377,20 +371,9 @@ describe('useShippingOrderReview build eligibility writes', () => {
|
||||
|
||||
api.getPreview.mockRejectedValue(new Error('preview unavailable'));
|
||||
|
||||
api.listWorkflows.mockResolvedValue({ conversation_id: 'conv-1', workflows: [] });
|
||||
|
||||
api.getWorkflowItem.mockResolvedValue({
|
||||
item_no: 'SWI-1',
|
||||
workflow_no: 'SNWF-1',
|
||||
conversation_id: 'conv-1',
|
||||
root_document_id: 1,
|
||||
current_document_id: 1,
|
||||
current_version_no: 1,
|
||||
current_case_no: 'CASE-1',
|
||||
lifecycle_status: 'pending_review',
|
||||
current_stage: 'pending_review',
|
||||
lock_version: 1,
|
||||
});
|
||||
api.getProcessingWorkItem.mockRejectedValue(
|
||||
Object.assign(new Error('not found'), { name: 'BusinessError', status: 404, code: 'NOT_FOUND' }),
|
||||
);
|
||||
|
||||
api.getCase.mockResolvedValue(buildCase());
|
||||
|
||||
@@ -559,21 +542,23 @@ describe('useShippingOrderReview build eligibility writes', () => {
|
||||
});
|
||||
api.getEvidence.mockResolvedValue({ items: [] });
|
||||
api.getPreview.mockResolvedValue({ preview_url: '' });
|
||||
api.listWorkflows.mockResolvedValue({ conversation_id: 'conv-1', workflows: [] });
|
||||
api.getWorkflowItem.mockResolvedValue({
|
||||
item_no: 'WFI-1',
|
||||
workflow_no: 'WF-1',
|
||||
lifecycle_status: 'building_order',
|
||||
current_stage: 'building_order',
|
||||
current_task_no: 'SN-1',
|
||||
current_version_no: 1,
|
||||
api.getProcessingWorkItem.mockResolvedValueOnce({
|
||||
work_item_no: 'OT-1',
|
||||
status: 'building_order',
|
||||
});
|
||||
api.getProcessingWorkItem.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',
|
||||
workflow_item_id: 'WFI-1',
|
||||
case: { ...readyCase, status: 'confirmed' },
|
||||
order_task_no: 'OT-1',
|
||||
shipping_notice_no: 'SN-1',
|
||||
case: { ...readyCase, status: 'confirmed', order_task_no: 'OT-1' },
|
||||
auto_progress_started: true,
|
||||
});
|
||||
|
||||
@@ -581,56 +566,104 @@ describe('useShippingOrderReview build eligibility writes', () => {
|
||||
await review.load('RUN-1', 'CASE-1', { conversationId: 'conv-1', itemNo: 'WFI-1' });
|
||||
const response = await review.confirm();
|
||||
|
||||
expect(response?.workflow_item_id).toBe('WFI-1');
|
||||
expect(response?.order_task_no).toBe('OT-1');
|
||||
expect(response?.shipping_notice_no || response?.task_no).toBeTruthy();
|
||||
expect(review.reviewProgressContext.value?.user_task_no).toBe('OT-1');
|
||||
expect(review.showWorkflowProgress.value).toBe(true);
|
||||
expect(review.workflowProgressPolling.value).toBe(true);
|
||||
expect(api.getWorkflowItem).toHaveBeenCalled();
|
||||
expect(api.getProcessingWorkItem).toHaveBeenCalled();
|
||||
|
||||
api.getWorkflowItem.mockResolvedValue({
|
||||
item_no: 'WFI-1',
|
||||
workflow_no: 'WF-1',
|
||||
lifecycle_status: 'manual_upload_pending',
|
||||
current_stage: 'manual_upload_pending',
|
||||
current_task_no: 'SN-1',
|
||||
current_version_no: 1,
|
||||
});
|
||||
await vi.advanceTimersByTimeAsync(2600);
|
||||
expect(review.workItem.value?.lifecycle_status).toBe('manual_upload_pending');
|
||||
await Promise.resolve();
|
||||
expect(review.workflowProgressPolling.value).toBe(false);
|
||||
|
||||
review.stopWorkflowProgressPolling();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it('does not fall back to extraction run root OT when case has candidate binding', async () => {
|
||||
api.getCase.mockResolvedValue(buildCase({
|
||||
candidate_id: 42,
|
||||
candidate: { candidate_no: 'CAND-42', validation_status: 'ready' },
|
||||
order_task_no: 'OT-CAND',
|
||||
}));
|
||||
api.getRun.mockResolvedValue({
|
||||
run_no: 'RUN-1',
|
||||
summary: {},
|
||||
items: [{ case_no: 'CASE-1', document_id: 1, status: 'draft', available_actions: ['edit_draft'] }],
|
||||
});
|
||||
api.getEvidence.mockResolvedValue({ items: [] });
|
||||
|
||||
const review = useShippingOrderReview();
|
||||
await review.load('RUN-1', 'CASE-1', { conversationId: 'conv-1' });
|
||||
|
||||
expect(review.reviewProgressContext.value?.user_task_no).toBe('OT-CAND');
|
||||
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 () => {
|
||||
vi.useFakeTimers();
|
||||
api.getCase.mockResolvedValue(buildCase({
|
||||
candidate_id: 42,
|
||||
candidate: { candidate_no: 'CAND-42', validation_status: 'ready' },
|
||||
}));
|
||||
api.getRun.mockResolvedValue({
|
||||
run_no: 'RUN-1',
|
||||
summary: {},
|
||||
items: [{ case_no: 'CASE-1', document_id: 1, status: 'reparse_pending', available_actions: [] }],
|
||||
});
|
||||
api.getEvidence.mockResolvedValue({ items: [] });
|
||||
api.reparseDocument.mockResolvedValue({
|
||||
run: { run_no: 'RUN-2' },
|
||||
reused: false,
|
||||
});
|
||||
api.getExtractionRun.mockResolvedValue({
|
||||
run_no: 'RUN-2',
|
||||
status: 'extracting',
|
||||
user_task_no: 'OT-ROOT',
|
||||
current_activity: { user_visible_stage: 'extracting' },
|
||||
});
|
||||
|
||||
const review = useShippingOrderReview();
|
||||
await review.load('RUN-1', 'CASE-1', { conversationId: 'conv-1' });
|
||||
await review.reparseDocument('layout_issue');
|
||||
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
await Promise.resolve();
|
||||
|
||||
expect(review.reviewProgressContext.value?.user_task_no).toBeNull();
|
||||
expect(review.reviewProgressContext.value?.user_task_authoritative).toBe(false);
|
||||
|
||||
review.stopReparseProgressPolling();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it('polls reparse progress and loads the new review version when ready', async () => {
|
||||
vi.useFakeTimers();
|
||||
let reparseStarted = false;
|
||||
let reparsePollCount = 0;
|
||||
api.reparseDocument.mockImplementation(async () => {
|
||||
reparseStarted = true;
|
||||
return { run: { run_no: 'RUN-2', items: [], summary: {} }, reused: false };
|
||||
});
|
||||
api.reparseDocument.mockImplementation(async () => ({
|
||||
run: { run_no: 'RUN-2', items: [], summary: {} },
|
||||
reused: false,
|
||||
}));
|
||||
api.getRun.mockImplementation(async (runNo: string) => ({
|
||||
run_no: runNo,
|
||||
status: runNo === 'RUN-2' ? 'review_required' : 'review_required',
|
||||
summary: {},
|
||||
items: [{ case_no: runNo === 'RUN-2' ? 'CASE-2' : 'CASE-1', status: 'draft', issue_count: 0 }],
|
||||
}));
|
||||
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' },
|
||||
};
|
||||
});
|
||||
api.getCase.mockImplementation(async (caseNo: string) => buildCase({
|
||||
case_no: caseNo,
|
||||
run_no: caseNo === 'CASE-2' ? 'RUN-2' : 'RUN-1',
|
||||
}));
|
||||
api.getWorkflowItem.mockImplementation(async () => {
|
||||
if (reparseStarted) reparsePollCount += 1;
|
||||
const ready = reparseStarted && reparsePollCount > 2;
|
||||
return {
|
||||
item_no: 'SWI-1',
|
||||
current_run_no: ready ? 'RUN-2' : 'RUN-1',
|
||||
current_case_no: ready ? 'CASE-2' : 'CASE-1',
|
||||
lifecycle_status: ready ? 'pending_review' : (reparseStarted ? 'extracting' : 'pending_review'),
|
||||
current_stage: ready ? 'pending_review' : (reparseStarted ? 'extracting' : 'pending_review'),
|
||||
current_version_no: ready ? 2 : 1,
|
||||
};
|
||||
});
|
||||
|
||||
const review = useShippingOrderReview();
|
||||
await review.load('RUN-1', 'CASE-1', { conversationId: 'conv-1', itemNo: 'SWI-1' });
|
||||
@@ -638,8 +671,8 @@ describe('useShippingOrderReview build eligibility writes', () => {
|
||||
|
||||
expect(review.reparseProgressActive.value).toBe(true);
|
||||
await vi.advanceTimersByTimeAsync(2600);
|
||||
await Promise.resolve();
|
||||
|
||||
// 关键断言:新版指针就绪后自动停止轮询并加载新的 Run/Case。
|
||||
expect(review.reparseProgressStage.value).toBe('draft_ready');
|
||||
expect(review.reparseProgressPolling.value).toBe(false);
|
||||
expect(review.reviewRun.value?.run_no).toBe('RUN-2');
|
||||
@@ -648,13 +681,49 @@ describe('useShippingOrderReview build eligibility writes', () => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it('refreshes the work item before resolving the current version target', async () => {
|
||||
it('loads a partially completed reparse result and clears the read-only progress state', async () => {
|
||||
vi.useFakeTimers();
|
||||
api.reparseDocument.mockImplementation(async () => ({
|
||||
run: { run_no: 'RUN-PARTIAL', items: [], summary: {} },
|
||||
reused: false,
|
||||
}));
|
||||
api.getRun.mockImplementation(async (runNo: string) => ({
|
||||
run_no: runNo,
|
||||
status: runNo === 'RUN-PARTIAL' ? 'partially_completed' : 'review_required',
|
||||
summary: {},
|
||||
items: [{ case_no: runNo === 'RUN-PARTIAL' ? 'CASE-PARTIAL' : 'CASE-1', status: 'draft', issue_count: 0 }],
|
||||
}));
|
||||
api.getExtractionRun.mockImplementation(async (runNo: string) => ({
|
||||
run_no: runNo,
|
||||
status: runNo === 'RUN-PARTIAL' ? 'partially_completed' : 'review_required',
|
||||
current_activity: { user_visible_stage: 'review_required' },
|
||||
}));
|
||||
api.getCase.mockImplementation(async (caseNo: string) => buildCase({
|
||||
case_no: caseNo,
|
||||
run_no: caseNo === 'CASE-PARTIAL' ? 'RUN-PARTIAL' : 'RUN-1',
|
||||
}));
|
||||
|
||||
const review = useShippingOrderReview();
|
||||
await review.load('RUN-1', 'CASE-1', { conversationId: 'conv-1', itemNo: 'SWI-1' });
|
||||
api.getWorkflowItem.mockResolvedValue({
|
||||
item_no: 'SWI-1', current_run_no: 'RUN-2', current_case_no: 'CASE-2',
|
||||
lifecycle_status: 'pending_review', current_stage: 'pending_review', current_version_no: 2,
|
||||
});
|
||||
await review.reparseDocument('document_quality');
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
await Promise.resolve();
|
||||
|
||||
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();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it('resolves the replacement run when superseded_by_run_no is set', async () => {
|
||||
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 }],
|
||||
});
|
||||
@@ -666,22 +735,49 @@ describe('useShippingOrderReview build eligibility writes', () => {
|
||||
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 () => {
|
||||
api.getRun.mockImplementation(async (runNo: string) => runNo === 'RUN-1'
|
||||
? {
|
||||
run_no: 'RUN-1',
|
||||
summary: {},
|
||||
items: [{ case_no: 'CASE-1', status: 'superseded', issue_count: 0 }],
|
||||
}
|
||||
: {
|
||||
run_no: 'RUN-2',
|
||||
summary: {},
|
||||
items: [{ case_no: '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',
|
||||
}));
|
||||
|
||||
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');
|
||||
});
|
||||
|
||||
it('shows a terminal failed stage when reparse fails', async () => {
|
||||
vi.useFakeTimers();
|
||||
api.reparseDocument.mockResolvedValue({
|
||||
run: { run_no: 'RUN-FAILED', items: [], summary: {} }, reused: false,
|
||||
});
|
||||
api.getWorkflowItem.mockResolvedValue({
|
||||
item_no: 'SWI-1', current_run_no: 'RUN-1', current_case_no: 'CASE-1',
|
||||
lifecycle_status: 'reparse_failed', current_stage: 'reparse_failed', current_version_no: 1,
|
||||
});
|
||||
api.getExtractionRun.mockResolvedValue({ run_no: 'RUN-FAILED', status: 'failed' });
|
||||
|
||||
const review = useShippingOrderReview();
|
||||
await review.load('RUN-1', 'CASE-1', { conversationId: 'conv-1', itemNo: 'SWI-1' });
|
||||
await review.reparseDocument('document_quality');
|
||||
await vi.runAllTicks();
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
await Promise.resolve();
|
||||
await vi.advanceTimersByTimeAsync(2600);
|
||||
await Promise.resolve();
|
||||
|
||||
// 关键断言:失败必须成为明确终态,不能继续伪装为字段提取进行中。
|
||||
expect(review.reparseProgressStage.value).toBe('failed');
|
||||
expect(review.reparseProgressPolling.value).toBe(false);
|
||||
review.stopReparseProgressPolling();
|
||||
@@ -708,18 +804,9 @@ describe('inventory routing recovery', () => {
|
||||
});
|
||||
api.getEvidence.mockResolvedValue({ items: [] });
|
||||
api.getPreview.mockResolvedValue(new Blob());
|
||||
api.listWorkflows.mockResolvedValue({ conversation_id: 'conv-1', workflows: [] });
|
||||
api.getWorkflowItem.mockResolvedValue({
|
||||
item_no: 'WFI-1',
|
||||
workflow_no: 'WF-1',
|
||||
root_document_id: 1,
|
||||
current_document_id: 1,
|
||||
current_version_no: 1,
|
||||
current_case_no: 'CASE-1',
|
||||
lifecycle_status: 'pending_review',
|
||||
current_stage: 'pending_review',
|
||||
lock_version: 1,
|
||||
});
|
||||
api.getProcessingWorkItem.mockRejectedValue(
|
||||
Object.assign(new Error('not found'), { name: 'BusinessError', status: 404, code: 'NOT_FOUND' }),
|
||||
);
|
||||
api.getCase.mockResolvedValue(buildCase());
|
||||
});
|
||||
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -7,9 +7,19 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
mapLifecycleToNodeStatus,
|
||||
mapShippingProcessingStatusToTaskGroup,
|
||||
mergeConversationProcessingFocusMetadata,
|
||||
projectConversationProcessingFromWorkItems,
|
||||
projectConversationProcessingObjects,
|
||||
projectConversationProcessingTasks,
|
||||
groupConversationProcessingTasks,
|
||||
mapUserTaskObjectsToFileRows,
|
||||
resolveConversationProcessingFromUnified,
|
||||
} from './conversationProcessingProjection';
|
||||
import type { ShippingWorkflowItem } from '@/features/chat/types/shipping.api.types';
|
||||
import type {
|
||||
ShippingProcessingProjection,
|
||||
ShippingWorkflowItem,
|
||||
} from '@/features/chat/types/shipping.api.types';
|
||||
|
||||
function item(partial: Partial<ShippingWorkflowItem>): ShippingWorkflowItem {
|
||||
return {
|
||||
@@ -84,4 +94,581 @@ describe('conversationProcessingProjection', () => {
|
||||
// 关键断言:侧栏 Task 使用后端权威 node_status,不覆盖为 running。
|
||||
expect(rows.find((row) => row.kind === 'task')?.node_status).toBe('manual_takeover');
|
||||
});
|
||||
|
||||
it('groups tasks into needs_action / processing / completed; closed stays history', () => {
|
||||
const tasks = projectConversationProcessingTasks([
|
||||
item({
|
||||
item_no: 'WI-A',
|
||||
current_run_no: 'RUN-A',
|
||||
root_document_id: 1,
|
||||
lifecycle_status: 'pending_review',
|
||||
current_document_filename: 'a.pdf',
|
||||
}),
|
||||
item({
|
||||
item_no: 'WI-B',
|
||||
current_run_no: 'RUN-B',
|
||||
root_document_id: 2,
|
||||
lifecycle_status: 'extracting',
|
||||
current_document_filename: 'b.pdf',
|
||||
}),
|
||||
item({
|
||||
item_no: 'WI-DONE',
|
||||
current_run_no: 'RUN-DONE',
|
||||
root_document_id: 3,
|
||||
lifecycle_status: 'completed',
|
||||
current_document_filename: 'done.pdf',
|
||||
}),
|
||||
item({
|
||||
item_no: 'WI-C',
|
||||
current_run_no: 'RUN-C',
|
||||
root_document_id: 4,
|
||||
lifecycle_status: 'closed',
|
||||
current_document_filename: 'c.pdf',
|
||||
}),
|
||||
item({
|
||||
item_no: 'WI-NO-NAME',
|
||||
current_run_no: 'RUN-NO-NAME',
|
||||
root_document_id: 5,
|
||||
lifecycle_status: 'extracting',
|
||||
current_document_filename: null,
|
||||
}),
|
||||
]);
|
||||
const projection = groupConversationProcessingTasks(tasks, { focusedTaskNo: 'OT-RUN-A' });
|
||||
// 右侧总数不含 history;completed 独立成组。
|
||||
expect(projection.summary).toEqual({
|
||||
total_tasks: 4,
|
||||
total_files: 4,
|
||||
processing: 2,
|
||||
needs_action: 1,
|
||||
completed: 1,
|
||||
history: 1,
|
||||
});
|
||||
expect(projection.needs_action[0]?.user_task_no).toBe('OT-RUN-A');
|
||||
expect(projection.processing.map((t) => t.user_task_no).sort()).toEqual([
|
||||
'OT-RUN-B',
|
||||
'OT-RUN-NO-NAME',
|
||||
]);
|
||||
expect(projection.completed?.[0]?.user_task_no).toBe('OT-RUN-DONE');
|
||||
expect(projection.history[0]?.user_task_no).toBe('OT-RUN-C');
|
||||
// [UI-02] 缺文件名时 title 为空,交给卡片回退「未命名 PDF」。
|
||||
const unnamed = projection.processing.find((t) => t.user_task_no === 'OT-RUN-NO-NAME');
|
||||
expect(unnamed?.title).toBeNull();
|
||||
});
|
||||
|
||||
it('uses multi_document_task when one run has two different PDFs', () => {
|
||||
const tasks = projectConversationProcessingTasks([
|
||||
item({
|
||||
item_no: 'WI-1',
|
||||
current_run_no: 'RUN-MULTI',
|
||||
root_document_id: 91,
|
||||
current_document_id: 91,
|
||||
content_hash: 'hash-a',
|
||||
user_task_no: 'OT-MULTI',
|
||||
lifecycle_status: 'extracting',
|
||||
current_document_filename: '4518838152.pdf',
|
||||
}),
|
||||
item({
|
||||
item_no: 'WI-2',
|
||||
current_run_no: 'RUN-MULTI',
|
||||
root_document_id: 92,
|
||||
current_document_id: 92,
|
||||
content_hash: 'hash-b',
|
||||
user_task_no: 'OT-MULTI',
|
||||
lifecycle_status: 'layout_parsing',
|
||||
current_document_filename: '4518838154.pdf',
|
||||
}),
|
||||
]);
|
||||
expect(tasks).toHaveLength(1);
|
||||
expect(tasks[0]?.title).toBeNull();
|
||||
expect(tasks[0]?.display_kind).toBe('multi_document_task');
|
||||
expect(tasks[0]?.file_count).toBe(2);
|
||||
expect(tasks[0]?.document_names).toEqual(['4518838152.pdf', '4518838154.pdf']);
|
||||
const docs = (tasks[0]?.objects || []).filter((row) => row.kind === 'document');
|
||||
expect(docs).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('keeps multi PDF when same OT spans different run_nos', () => {
|
||||
const tasks = projectConversationProcessingTasks([
|
||||
item({
|
||||
item_no: 'WI-1',
|
||||
current_run_no: 'RUN-A',
|
||||
root_document_id: 91,
|
||||
current_document_id: 91,
|
||||
content_hash: 'hash-a',
|
||||
user_task_no: 'OT-SHARED',
|
||||
lifecycle_status: 'pending_review',
|
||||
current_document_filename: 'a.pdf',
|
||||
last_activity_at: '2026-08-04T01:00:00Z',
|
||||
}),
|
||||
item({
|
||||
item_no: 'WI-2',
|
||||
current_run_no: 'RUN-B',
|
||||
root_document_id: 92,
|
||||
current_document_id: 92,
|
||||
content_hash: 'hash-b',
|
||||
user_task_no: 'OT-SHARED',
|
||||
lifecycle_status: 'pending_review',
|
||||
current_document_filename: 'b.pdf',
|
||||
last_activity_at: '2026-08-04T02:00:00Z',
|
||||
}),
|
||||
]);
|
||||
// 同 OT 跨 Run 时按 PDF 身份选最新版;未在新 Run 重识别的 PDF 继续有效。
|
||||
expect(tasks).toHaveLength(1);
|
||||
expect(tasks[0]?.file_count).toBe(2);
|
||||
expect(tasks[0]?.display_kind).toBe('multi_document_task');
|
||||
expect(tasks[0]?.title).toBeNull();
|
||||
expect(tasks[0]?.document_names).toEqual(['a.pdf', 'b.pdf']);
|
||||
expect(tasks[0]?.run_no).toBe('RUN-B');
|
||||
const documents = tasks[0]?.objects.filter((row) => row.kind === 'document') || [];
|
||||
expect(documents.map((row) => row.current_run_no)).toEqual(['RUN-A', 'RUN-B']);
|
||||
});
|
||||
|
||||
it('keeps only latest version when same PDF spans different run_nos', () => {
|
||||
const tasks = projectConversationProcessingTasks([
|
||||
item({
|
||||
item_no: 'WI-OLD',
|
||||
current_run_no: 'RUN-A',
|
||||
root_document_id: 91,
|
||||
current_document_id: 91,
|
||||
content_hash: 'hash-a',
|
||||
user_task_no: 'OT-SHARED',
|
||||
lifecycle_status: 'failed',
|
||||
current_document_filename: 'old.pdf',
|
||||
last_activity_at: '2026-08-04T01:00:00Z',
|
||||
}),
|
||||
item({
|
||||
item_no: 'WI-NEW',
|
||||
current_run_no: 'RUN-B',
|
||||
root_document_id: 91,
|
||||
current_document_id: 191,
|
||||
content_hash: 'hash-a',
|
||||
user_task_no: 'OT-SHARED',
|
||||
lifecycle_status: 'pending_review',
|
||||
current_document_filename: 'latest.pdf',
|
||||
last_activity_at: '2026-08-04T02:00:00Z',
|
||||
}),
|
||||
]);
|
||||
expect(tasks).toHaveLength(1);
|
||||
expect(tasks[0]?.file_count).toBe(1);
|
||||
expect(tasks[0]?.title).toBe('latest.pdf');
|
||||
const document = tasks[0]?.objects.find((row) => row.kind === 'document');
|
||||
expect(document?.document_id).toBe(191);
|
||||
expect(document?.current_run_no).toBe('RUN-B');
|
||||
});
|
||||
|
||||
it('keeps single PDF filename title for one-document run', () => {
|
||||
const tasks = projectConversationProcessingTasks([
|
||||
item({
|
||||
item_no: 'WI-1',
|
||||
current_run_no: 'RUN-ONE',
|
||||
root_document_id: 7,
|
||||
content_hash: 'solo',
|
||||
user_task_no: 'OT-ONE',
|
||||
lifecycle_status: 'extracting',
|
||||
current_document_filename: 'solo.pdf',
|
||||
}),
|
||||
]);
|
||||
expect(tasks[0]?.title).toBe('solo.pdf');
|
||||
expect(tasks[0]?.display_kind).toBe('single_document_task');
|
||||
expect(tasks[0]?.file_count).toBe(1);
|
||||
});
|
||||
|
||||
it('merges same root_document_id across runs into one fallback task', () => {
|
||||
const tasks = projectConversationProcessingTasks([
|
||||
item({
|
||||
item_no: 'WI-OLD',
|
||||
current_run_no: 'RUN-OLD',
|
||||
root_document_id: 42,
|
||||
lifecycle_status: 'failed',
|
||||
current_document_filename: 'order.pdf',
|
||||
last_activity_at: '2026-08-03T10:00:00Z',
|
||||
}),
|
||||
item({
|
||||
item_no: 'WI-NEW',
|
||||
current_run_no: 'RUN-NEW',
|
||||
root_document_id: 42,
|
||||
lifecycle_status: 'extracting',
|
||||
current_document_filename: 'order.pdf',
|
||||
last_activity_at: '2026-08-03T11:00:00Z',
|
||||
}),
|
||||
]);
|
||||
const projection = groupConversationProcessingTasks(tasks);
|
||||
// [UI-01] 同 root 只保留当前有效版本(处理中),旧失败不再单独出卡。
|
||||
expect(projection.summary.total_tasks).toBe(1);
|
||||
expect(projection.processing).toHaveLength(1);
|
||||
expect(projection.needs_action).toHaveLength(0);
|
||||
expect(projection.processing[0]?.run_no).toBe('RUN-NEW');
|
||||
expect(projection.processing[0]?.title).toBe('order.pdf');
|
||||
});
|
||||
|
||||
it('merges different root_document_id with same content_hash into one fallback task', () => {
|
||||
const tasks = projectConversationProcessingTasks([
|
||||
item({
|
||||
item_no: 'WI-A',
|
||||
current_run_no: 'RUN-A',
|
||||
root_document_id: 101,
|
||||
content_hash: 'aaa111',
|
||||
lifecycle_status: 'failed',
|
||||
current_document_filename: 'order.pdf',
|
||||
last_activity_at: '2026-08-03T10:00:00Z',
|
||||
}),
|
||||
item({
|
||||
item_no: 'WI-B',
|
||||
current_run_no: 'RUN-B',
|
||||
root_document_id: 202,
|
||||
content_hash: 'aaa111',
|
||||
lifecycle_status: 'extracting',
|
||||
current_document_filename: 'order.pdf',
|
||||
last_activity_at: '2026-08-03T11:00:00Z',
|
||||
}),
|
||||
]);
|
||||
const projection = groupConversationProcessingTasks(tasks);
|
||||
// [UI-01] 普通重传换 root,但同内容哈希只保留当前有效版本。
|
||||
expect(projection.summary.total_tasks).toBe(1);
|
||||
expect(projection.processing).toHaveLength(1);
|
||||
expect(projection.processing[0]?.run_no).toBe('RUN-B');
|
||||
});
|
||||
|
||||
it('merges different root_document_id with same user_task_no into one fallback task', () => {
|
||||
const tasks = projectConversationProcessingTasks([
|
||||
item({
|
||||
item_no: 'WI-A',
|
||||
current_run_no: 'RUN-A',
|
||||
root_document_id: 301,
|
||||
user_task_no: 'OT-SHARED',
|
||||
content_hash: 'hash-a',
|
||||
lifecycle_status: 'failed',
|
||||
current_document_filename: 'order.pdf',
|
||||
last_activity_at: '2026-08-03T10:00:00Z',
|
||||
}),
|
||||
item({
|
||||
item_no: 'WI-B',
|
||||
current_run_no: 'RUN-B',
|
||||
root_document_id: 302,
|
||||
user_task_no: 'OT-SHARED',
|
||||
content_hash: 'hash-b',
|
||||
lifecycle_status: 'extracting',
|
||||
current_document_filename: 'order.pdf',
|
||||
last_activity_at: '2026-08-03T11:00:00Z',
|
||||
}),
|
||||
]);
|
||||
const projection = groupConversationProcessingTasks(tasks);
|
||||
// user_task_no 优先于 content_hash / root;输出必须原样保留真实 OT。
|
||||
expect(projection.summary.total_tasks).toBe(1);
|
||||
expect(projection.processing[0]?.run_no).toBe('RUN-B');
|
||||
expect(projection.processing[0]?.user_task_no).toBe('OT-SHARED');
|
||||
expect(projection.processing[0]?.user_task_authoritative).toBe(true);
|
||||
});
|
||||
|
||||
it('preserves authoritative user_task_no for focus/viewed APIs', () => {
|
||||
const tasks = projectConversationProcessingTasks([
|
||||
item({
|
||||
item_no: 'WI-1',
|
||||
current_run_no: 'RUN-XXX',
|
||||
root_document_id: 55,
|
||||
user_task_no: 'OT-REAL-001',
|
||||
content_hash: 'abc',
|
||||
lifecycle_status: 'extracting',
|
||||
current_document_filename: 'order.pdf',
|
||||
last_activity_at: '2026-08-03T11:00:00Z',
|
||||
}),
|
||||
]);
|
||||
// [UI-01] 禁止输出伪造 OT-${runNo},否则 focus/viewed 会打到不存在的任务号。
|
||||
expect(tasks).toHaveLength(1);
|
||||
expect(tasks[0]?.user_task_no).toBe('OT-REAL-001');
|
||||
expect(tasks[0]?.user_task_no).not.toBe('OT-RUN-XXX');
|
||||
expect(tasks[0]?.user_task_authoritative).toBe(true);
|
||||
});
|
||||
|
||||
it('marks fabricated fallback task no as non-authoritative', () => {
|
||||
const tasks = projectConversationProcessingTasks([
|
||||
item({
|
||||
item_no: 'WI-1',
|
||||
current_run_no: 'RUN-LOCAL',
|
||||
root_document_id: 66,
|
||||
lifecycle_status: 'extracting',
|
||||
current_document_filename: 'order.pdf',
|
||||
}),
|
||||
]);
|
||||
expect(tasks[0]?.user_task_no).toBe('OT-RUN-LOCAL');
|
||||
expect(tasks[0]?.user_task_authoritative).toBe(false);
|
||||
});
|
||||
|
||||
it('does not merge different root_document_id with same filename', () => {
|
||||
const tasks = projectConversationProcessingTasks([
|
||||
item({
|
||||
item_no: 'WI-A',
|
||||
current_run_no: 'RUN-A',
|
||||
root_document_id: 101,
|
||||
lifecycle_status: 'extracting',
|
||||
current_document_filename: 'order.pdf',
|
||||
last_activity_at: '2026-08-03T10:00:00Z',
|
||||
}),
|
||||
item({
|
||||
item_no: 'WI-B',
|
||||
current_run_no: 'RUN-B',
|
||||
root_document_id: 202,
|
||||
lifecycle_status: 'extracting',
|
||||
current_document_filename: 'order.pdf',
|
||||
last_activity_at: '2026-08-03T11:00:00Z',
|
||||
}),
|
||||
]);
|
||||
const projection = groupConversationProcessingTasks(tasks);
|
||||
// [UI-01] 同名不同内容(不同 root)不得合并成一张卡。
|
||||
expect(projection.summary.total_tasks).toBe(2);
|
||||
expect(projection.processing).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('prefers newer failed over older processing for same identity', () => {
|
||||
const tasks = projectConversationProcessingTasks([
|
||||
item({
|
||||
item_no: 'WI-OLD',
|
||||
current_run_no: 'RUN-OLD',
|
||||
root_document_id: 77,
|
||||
lifecycle_status: 'extracting',
|
||||
current_document_filename: 'order.pdf',
|
||||
last_activity_at: '2026-08-03T10:00:00Z',
|
||||
}),
|
||||
item({
|
||||
item_no: 'WI-NEW',
|
||||
current_run_no: 'RUN-NEW',
|
||||
root_document_id: 77,
|
||||
lifecycle_status: 'failed',
|
||||
current_document_filename: 'order.pdf',
|
||||
last_activity_at: '2026-08-03T11:00:00Z',
|
||||
}),
|
||||
]);
|
||||
const projection = groupConversationProcessingTasks(tasks);
|
||||
// [UI-02] 最新有效版本按活动时间,不按 processing 严重度遮盖新失败。
|
||||
expect(projection.summary.total_tasks).toBe(1);
|
||||
expect(projection.processing).toHaveLength(0);
|
||||
expect(projection.needs_action).toHaveLength(1);
|
||||
expect(projection.needs_action[0]?.run_no).toBe('RUN-NEW');
|
||||
expect(projection.needs_action[0]?.status_label).toBe('failed');
|
||||
});
|
||||
|
||||
it('synthesizes conversation groups from unified order_task work_items', () => {
|
||||
const workItems: ShippingProcessingProjection[] = [
|
||||
{
|
||||
workItemType: 'order_intake',
|
||||
workItemNo: 'SNI-1',
|
||||
sourceType: 'direct_pdf',
|
||||
rootOrderTaskNo: null,
|
||||
shippingNoticeNo: null,
|
||||
conversationId: 'conv-1',
|
||||
submissionNo: 'SOS-1',
|
||||
intakeNo: 'SNI-1',
|
||||
status: 'failed',
|
||||
stage: 'document_parsing',
|
||||
progressVersion: 1,
|
||||
lastActivityAt: '2026-08-05T00:00:00Z',
|
||||
currentGate: null,
|
||||
availableActions: ['retry_parse'],
|
||||
sourceSummary: {
|
||||
emailSubject: null,
|
||||
filename: 'a.pdf',
|
||||
documentCount: 1,
|
||||
parsedDocumentCount: 0,
|
||||
candidateCount: 0,
|
||||
customerName: null,
|
||||
poNumber: null,
|
||||
},
|
||||
childOrderTasks: [],
|
||||
},
|
||||
{
|
||||
workItemType: 'order_task',
|
||||
workItemNo: 'OT-WAIT',
|
||||
sourceType: 'eml',
|
||||
rootOrderTaskNo: 'OT-WAIT',
|
||||
shippingNoticeNo: null,
|
||||
conversationId: 'conv-1',
|
||||
submissionNo: 'SOS-1',
|
||||
intakeNo: 'SNI-2',
|
||||
status: 'waiting_review',
|
||||
stage: 'waiting_review',
|
||||
progressVersion: 2,
|
||||
lastActivityAt: '2026-08-05T01:00:00Z',
|
||||
currentGate: {
|
||||
gateCode: 'order_freeze_readiness',
|
||||
status: 'blocked',
|
||||
nextActionCode: 'open_order_review',
|
||||
blockingReasonCode: 'review_case_draft',
|
||||
attemptNo: 0,
|
||||
},
|
||||
availableActions: ['open_order_review'],
|
||||
sourceSummary: {
|
||||
emailSubject: null,
|
||||
filename: 'po.pdf',
|
||||
documentCount: 2,
|
||||
parsedDocumentCount: 2,
|
||||
candidateCount: 1,
|
||||
customerName: 'ACME',
|
||||
poNumber: 'PO-1',
|
||||
},
|
||||
childOrderTasks: [],
|
||||
},
|
||||
{
|
||||
workItemType: 'order_task',
|
||||
workItemNo: 'OT-RUN',
|
||||
sourceType: 'direct_pdf',
|
||||
rootOrderTaskNo: 'OT-RUN',
|
||||
shippingNoticeNo: null,
|
||||
conversationId: 'conv-1',
|
||||
submissionNo: 'SOS-2',
|
||||
intakeNo: 'SNI-3',
|
||||
status: 'processing',
|
||||
stage: 'document_parsing',
|
||||
progressVersion: 1,
|
||||
lastActivityAt: '2026-08-05T02:00:00Z',
|
||||
currentGate: null,
|
||||
availableActions: ['view_details'],
|
||||
sourceSummary: {
|
||||
emailSubject: null,
|
||||
filename: 'solo.pdf',
|
||||
documentCount: 1,
|
||||
parsedDocumentCount: 1,
|
||||
candidateCount: 0,
|
||||
customerName: null,
|
||||
poNumber: null,
|
||||
},
|
||||
childOrderTasks: [],
|
||||
},
|
||||
];
|
||||
|
||||
expect(mapShippingProcessingStatusToTaskGroup(workItems[1]!)).toBe('needs_action');
|
||||
expect(mapShippingProcessingStatusToTaskGroup(workItems[2]!)).toBe('processing');
|
||||
|
||||
const projection = projectConversationProcessingFromWorkItems(workItems);
|
||||
// 关键断言:仅 order_task 入组;intake 不进入 conversation groups。
|
||||
expect(projection).not.toBeNull();
|
||||
expect(projection!.needs_action.map((t) => t.user_task_no)).toEqual(['OT-WAIT']);
|
||||
expect(projection!.processing.map((t) => t.user_task_no)).toEqual(['OT-RUN']);
|
||||
expect(projection!.needs_action[0]?.file_count).toBe(2);
|
||||
expect(projection!.needs_action[0]?.display_kind).toBe('multi_document_task');
|
||||
});
|
||||
|
||||
it('prefers work_items task lists over embedded conversation_processing when both exist', () => {
|
||||
const workItems: ShippingProcessingProjection[] = [
|
||||
{
|
||||
workItemType: 'order_task',
|
||||
workItemNo: 'OT-ROOT',
|
||||
sourceType: 'eml',
|
||||
rootOrderTaskNo: 'OT-ROOT',
|
||||
shippingNoticeNo: null,
|
||||
conversationId: 'conv-1',
|
||||
submissionNo: 'SOS-1',
|
||||
intakeNo: 'SNI-1',
|
||||
status: 'waiting_review',
|
||||
stage: 'waiting_review',
|
||||
progressVersion: 1,
|
||||
lastActivityAt: '2026-08-05T00:00:00Z',
|
||||
currentGate: null,
|
||||
availableActions: ['open_order_review'],
|
||||
sourceSummary: {
|
||||
emailSubject: null,
|
||||
filename: 'root.pdf',
|
||||
documentCount: 1,
|
||||
parsedDocumentCount: 1,
|
||||
candidateCount: 1,
|
||||
customerName: null,
|
||||
poNumber: 'PO-ROOT',
|
||||
},
|
||||
childOrderTasks: [],
|
||||
},
|
||||
{
|
||||
workItemType: 'order_task',
|
||||
workItemNo: 'OT-SIBLING',
|
||||
sourceType: 'eml',
|
||||
rootOrderTaskNo: 'OT-ROOT',
|
||||
shippingNoticeNo: null,
|
||||
conversationId: 'conv-1',
|
||||
submissionNo: 'SOS-1',
|
||||
intakeNo: 'SNI-1',
|
||||
status: 'processing',
|
||||
stage: 'candidate_creating',
|
||||
progressVersion: 1,
|
||||
lastActivityAt: '2026-08-05T01:00:00Z',
|
||||
currentGate: null,
|
||||
availableActions: ['view_details'],
|
||||
sourceSummary: {
|
||||
emailSubject: null,
|
||||
filename: 'sibling.pdf',
|
||||
documentCount: 1,
|
||||
parsedDocumentCount: 1,
|
||||
candidateCount: 1,
|
||||
customerName: null,
|
||||
poNumber: 'PO-SIB',
|
||||
},
|
||||
childOrderTasks: [],
|
||||
},
|
||||
];
|
||||
const embedded = {
|
||||
summary: {
|
||||
total_tasks: 1,
|
||||
total_files: 1,
|
||||
processing: 0,
|
||||
needs_action: 1,
|
||||
completed: 0,
|
||||
history: 0,
|
||||
},
|
||||
focused_task_no: 'OT-ROOT',
|
||||
recent_task_no: 'OT-SIBLING',
|
||||
needs_action: [{
|
||||
user_task_no: 'OT-ROOT',
|
||||
group: 'needs_action',
|
||||
can_append: false,
|
||||
file_count: 1,
|
||||
}],
|
||||
processing: [],
|
||||
completed: [],
|
||||
history: [],
|
||||
};
|
||||
|
||||
const projection = resolveConversationProcessingFromUnified(workItems, embedded);
|
||||
// 关键断言:兄弟 OT 仅出现在 work_items;embedded 缺 sibling 时不得覆盖任务列表。
|
||||
expect(projection?.needs_action.map((t) => t.user_task_no)).toEqual(['OT-ROOT']);
|
||||
expect(projection?.processing.map((t) => t.user_task_no)).toEqual(['OT-SIBLING']);
|
||||
expect(projection?.focused_task_no).toBe('OT-ROOT');
|
||||
expect(projection?.recent_task_no).toBe('OT-SIBLING');
|
||||
});
|
||||
|
||||
it('merges focus metadata from embedded onto work_items-derived projection', () => {
|
||||
const derived = projectConversationProcessingFromWorkItems([{
|
||||
workItemType: 'order_task',
|
||||
workItemNo: 'OT-1',
|
||||
sourceType: 'direct_pdf',
|
||||
rootOrderTaskNo: 'OT-1',
|
||||
shippingNoticeNo: null,
|
||||
conversationId: 'conv-1',
|
||||
submissionNo: 'SOS-1',
|
||||
intakeNo: 'SNI-1',
|
||||
status: 'processing',
|
||||
stage: 'document_parsing',
|
||||
progressVersion: 1,
|
||||
lastActivityAt: '2026-08-05T00:00:00Z',
|
||||
currentGate: null,
|
||||
availableActions: [],
|
||||
sourceSummary: {
|
||||
emailSubject: null,
|
||||
filename: 'a.pdf',
|
||||
documentCount: 1,
|
||||
parsedDocumentCount: 1,
|
||||
candidateCount: 0,
|
||||
customerName: null,
|
||||
poNumber: null,
|
||||
},
|
||||
childOrderTasks: [],
|
||||
}]);
|
||||
const merged = mergeConversationProcessingFocusMetadata(derived, {
|
||||
summary: derived!.summary,
|
||||
focused_task_no: 'OT-FOCUS',
|
||||
recent_task_no: 'OT-RECENT',
|
||||
needs_action: [{ user_task_no: 'OT-STALE', group: 'needs_action', can_append: false }],
|
||||
processing: [],
|
||||
history: [],
|
||||
});
|
||||
expect(merged?.processing[0]?.user_task_no).toBe('OT-1');
|
||||
expect(merged?.focused_task_no).toBe('OT-FOCUS');
|
||||
expect(merged?.recent_task_no).toBe('OT-RECENT');
|
||||
});
|
||||
});
|
||||
@@ -1,17 +1,56 @@
|
||||
/**
|
||||
* features/chat/shipping/conversationProcessingProjection.ts
|
||||
* 用途:将现有 Workflow Items 投影为对话「本次处理中」统一对象行。
|
||||
* 依赖:shipping.api.types(ConversationProcessingObject / WorkflowNodeStatus)。
|
||||
* 逻辑:Timeline 复用本投影;Task 优先消费后端 node_status / progress_nodes;
|
||||
* 不伪造进度百分比。
|
||||
* 用途:将 OT / 统一 processing 投影为对话「本次处理中」对象、任务分组与文件行。
|
||||
* 依赖:shipping.api.types(ConversationProcessingObject / UserTask / WorkflowNodeStatus /
|
||||
* ShippingProcessingProjection、合成 ShippingWorkflowItem)。
|
||||
* 逻辑:Timeline 与 ShippingConversationProcessingCard 复用;文件明细由
|
||||
* mapUserTaskObjectsToFileRows(task.objects) 合成;禁止 Workflow fallback reconcile;
|
||||
* 可由统一 work_items(order_task)合成兼容分组。
|
||||
*/
|
||||
|
||||
import type {
|
||||
ConversationProcessingObject,
|
||||
ConversationProcessingProjection,
|
||||
ConversationProcessingSummary,
|
||||
ConversationProcessingTaskGroup,
|
||||
ConversationProcessingUserTask,
|
||||
ShippingProcessingProjection,
|
||||
ShippingWorkflowItem,
|
||||
WorkflowNodeStatus,
|
||||
} from '@/features/chat/types/shipping.api.types';
|
||||
|
||||
/** 需要人工处理的生命周期集合。 */
|
||||
const NEEDS_ACTION_LIFECYCLES = new Set([
|
||||
'pending_review',
|
||||
'manual_upload_pending',
|
||||
'failed',
|
||||
'reparse_failed',
|
||||
'upload_rpa_failed',
|
||||
]);
|
||||
|
||||
/** 处理中生命周期集合。 */
|
||||
const PROCESSING_LIFECYCLES = new Set([
|
||||
'queued',
|
||||
'layout_parsing',
|
||||
'extracting',
|
||||
'building_order',
|
||||
'inventory_matching',
|
||||
'generating_excel',
|
||||
'upload_rpa_pending',
|
||||
'upload_rpa_running',
|
||||
]);
|
||||
|
||||
/** 历史生命周期集合(已关闭/取消;completed 单独进「已完成」通知组)。 */
|
||||
const HISTORY_LIFECYCLES = new Set([
|
||||
'closed',
|
||||
'cancelled',
|
||||
]);
|
||||
|
||||
/** 识别完成、仍应在右侧展示的成功通知生命周期。 */
|
||||
const COMPLETED_LIFECYCLES = new Set([
|
||||
'completed',
|
||||
]);
|
||||
|
||||
/**
|
||||
* 将生命周期状态映射为 WorkflowNodeStatus(展示用,非进度百分比)。
|
||||
*/
|
||||
@@ -58,6 +97,59 @@ export function resolveItemDisplayStatus(item: ShippingWorkflowItem): string {
|
||||
return String(item.lifecycle_status || '').trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* 将 OT 任务卡内 document objects 映射为侧栏文件行(合成 ShippingWorkflowItem 形态)。
|
||||
* 核心逻辑:仅消费 kind=document;item_no 优先 workflow_item_no / object_key;
|
||||
* available_actions / reparse_kind 可从 object 扩展字段透传(单测与后端可选投影)。
|
||||
*
|
||||
* @param task - 当前展开的用户可见任务
|
||||
* @returns 文件明细行;无文档对象时为空数组
|
||||
*/
|
||||
export function mapUserTaskObjectsToFileRows(
|
||||
task: ConversationProcessingUserTask | null | undefined,
|
||||
): ShippingWorkflowItem[] {
|
||||
if (!task) return [];
|
||||
const rows: ShippingWorkflowItem[] = [];
|
||||
for (const [index, object] of (task.objects || []).entries()) {
|
||||
if (object.kind !== 'document') continue;
|
||||
const documentId = Number(object.document_id || 0);
|
||||
const rootId = Number(object.root_document_id || documentId || 0);
|
||||
const status = String(object.status_label || task.status_label || 'queued').trim() || 'queued';
|
||||
const itemNo = String(
|
||||
object.workflow_item_no || object.object_key || `DOC-${documentId || index + 1}`,
|
||||
).trim();
|
||||
const extra = object as ConversationProcessingObject & {
|
||||
available_actions?: string[];
|
||||
reparse_kind?: string | null;
|
||||
lock_version?: number;
|
||||
};
|
||||
rows.push({
|
||||
item_no: itemNo,
|
||||
workflow_no: String(task.workflow_no || 'SNWF-OT').trim() || 'SNWF-OT',
|
||||
conversation_id: '',
|
||||
root_document_id: rootId,
|
||||
current_document_id: documentId || rootId,
|
||||
current_document_filename: object.filename || object.label || null,
|
||||
content_hash: object.content_hash || null,
|
||||
current_version_no: Number(object.current_version_no || 1) || 1,
|
||||
current_run_no: object.current_run_no || object.run_no || task.run_no || null,
|
||||
current_case_no: object.case_no || null,
|
||||
current_task_no: object.task_no || task.user_task_no || null,
|
||||
user_task_no: task.user_task_no,
|
||||
user_task_authoritative: task.user_task_authoritative,
|
||||
lifecycle_status: status,
|
||||
current_stage: status,
|
||||
display_lifecycle_status: status,
|
||||
lock_version: Number(extra.lock_version || 1) || 1,
|
||||
available_actions: Array.isArray(extra.available_actions)
|
||||
? extra.available_actions
|
||||
: (Array.isArray(task.available_actions) ? task.available_actions : undefined),
|
||||
reparse_kind: extra.reparse_kind ?? null,
|
||||
});
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
|
||||
/**
|
||||
* 从 Workflow Items 聚合 Run / Candidate / Task / Process Gate 侧栏行。
|
||||
*
|
||||
@@ -188,3 +280,416 @@ export function projectConversationProcessingObjects(
|
||||
|
||||
return rows;
|
||||
}
|
||||
|
||||
/**
|
||||
* 按生命周期/门禁将状态归入 needs_action | processing | completed | history。
|
||||
*/
|
||||
export function classifyConversationProcessingGroup(
|
||||
status: string | null | undefined,
|
||||
options?: { hasBlockingGate?: boolean; needsCustomerConfirm?: boolean },
|
||||
): ConversationProcessingTaskGroup {
|
||||
if (options?.hasBlockingGate || options?.needsCustomerConfirm) return 'needs_action';
|
||||
const normalized = String(status || '').trim();
|
||||
if (NEEDS_ACTION_LIFECYCLES.has(normalized)) return 'needs_action';
|
||||
if (COMPLETED_LIFECYCLES.has(normalized)) return 'completed';
|
||||
if (HISTORY_LIFECYCLES.has(normalized)) return 'history';
|
||||
if (PROCESSING_LIFECYCLES.has(normalized)) return 'processing';
|
||||
if (normalized === 'review_required' || normalized === 'partially_completed') {
|
||||
return 'needs_action';
|
||||
}
|
||||
if (normalized === 'failed' || normalized === 'cancelled') return 'needs_action';
|
||||
if (normalized === 'completed') return 'completed';
|
||||
if (normalized === 'processing' || normalized === 'queued') return 'processing';
|
||||
return 'processing';
|
||||
}
|
||||
|
||||
/**
|
||||
* 兜底任务身份键:稳定业务身份优先,文件名仅作最弱兜底。
|
||||
* 顺序:user_task_no → content_hash → root_document_id → filename → run/item。
|
||||
* 普通重传会换 root_document_id,故不得把 root 放在 content_hash 之前。
|
||||
*/
|
||||
function fallbackTaskIdentityKey(item: ShippingWorkflowItem): string {
|
||||
const userTaskNo = String(item.user_task_no || '').trim();
|
||||
if (userTaskNo) return `task:${userTaskNo}`;
|
||||
const contentHash = String(item.content_hash || '').trim().toLowerCase();
|
||||
if (contentHash) return `hash:${contentHash}`;
|
||||
const rootId = Number(item.root_document_id || 0);
|
||||
if (rootId > 0) return `root:${rootId}`;
|
||||
const filename = String(item.current_document_filename || '').trim().toLowerCase();
|
||||
if (filename) return `fn:${filename}`;
|
||||
const runNo = String(item.current_run_no || '').trim();
|
||||
if (runNo) return `run:${runNo}`;
|
||||
return `item:${String(item.item_no || '').trim()}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 降级路径:按稳定身份去重 Workflow Items 中的业务 PDF。
|
||||
* 顺序:content_hash → root_document_id → current_document_id;禁止仅按文件名去重。
|
||||
*/
|
||||
function dedupeFallbackDocuments(items: ShippingWorkflowItem[]): Array<{
|
||||
filename: string | null;
|
||||
content_hash: string | null;
|
||||
root_document_id: number;
|
||||
document_id: number;
|
||||
status_label: string;
|
||||
current_run_no: string | null;
|
||||
source_item: ShippingWorkflowItem;
|
||||
}> {
|
||||
const unique: Array<{
|
||||
filename: string | null;
|
||||
content_hash: string | null;
|
||||
root_document_id: number;
|
||||
document_id: number;
|
||||
status_label: string;
|
||||
current_run_no: string | null;
|
||||
source_item: ShippingWorkflowItem;
|
||||
recency: number;
|
||||
identity: string;
|
||||
}> = [];
|
||||
const seen = new Map<string, number>();
|
||||
for (const item of items || []) {
|
||||
const contentHash = String(item.content_hash || '').trim().toLowerCase();
|
||||
const rootId = Number(item.root_document_id || 0);
|
||||
const documentId = Number(item.current_document_id || 0);
|
||||
const identity = contentHash
|
||||
? `hash:${contentHash}`
|
||||
: rootId > 0
|
||||
? `root:${rootId}`
|
||||
: documentId > 0
|
||||
? `doc:${documentId}`
|
||||
: `item:${String(item.item_no || '').trim()}`;
|
||||
const filename = String(item.current_document_filename || '').trim() || null;
|
||||
const row = {
|
||||
filename,
|
||||
content_hash: contentHash || null,
|
||||
root_document_id: rootId,
|
||||
document_id: documentId,
|
||||
status_label: resolveItemDisplayStatus(item),
|
||||
current_run_no: String(item.current_run_no || '').trim() || null,
|
||||
source_item: item,
|
||||
recency: Date.parse(String(item.last_activity_at || item.updated_at || '').trim()) || 0,
|
||||
identity,
|
||||
};
|
||||
const existingIndex = seen.get(identity);
|
||||
if (existingIndex == null) {
|
||||
seen.set(identity, unique.length);
|
||||
unique.push(row);
|
||||
continue;
|
||||
}
|
||||
const existing = unique[existingIndex]!;
|
||||
if (row.recency > existing.recency
|
||||
|| (row.recency === existing.recency && documentId >= existing.document_id)) {
|
||||
unique[existingIndex] = row;
|
||||
}
|
||||
}
|
||||
return unique;
|
||||
}
|
||||
|
||||
/**
|
||||
* 从 Workflow Items 聚合为用户可见任务列表(后端 processing 未就绪时的前端兜底)。
|
||||
* 核心逻辑:先按稳定任务身份(user_task_no / hash…)归并全部 Item,再按 PDF 去重计
|
||||
* file_count;禁止先按 run_no 拆桶再丢弃同 OT 的另一份 PDF;单 PDF 才用文件名作 title。
|
||||
*/
|
||||
export function projectConversationProcessingTasks(
|
||||
items: ShippingWorkflowItem[],
|
||||
options?: {
|
||||
focusTaskNo?: string | null;
|
||||
focusRunNo?: string | null;
|
||||
focusUserTaskNo?: string | null;
|
||||
},
|
||||
): ConversationProcessingUserTask[] {
|
||||
const byIdentity = new Map<string, ShippingWorkflowItem[]>();
|
||||
for (const item of items || []) {
|
||||
const identity = fallbackTaskIdentityKey(item);
|
||||
if (!identity || identity === 'item:') continue;
|
||||
const bucket = byIdentity.get(identity) || [];
|
||||
bucket.push(item);
|
||||
byIdentity.set(identity, bucket);
|
||||
}
|
||||
|
||||
const focusUserTask = String(options?.focusUserTaskNo || '').trim();
|
||||
const focusRun = String(options?.focusRunNo || '').trim();
|
||||
const tasks: ConversationProcessingUserTask[] = [];
|
||||
|
||||
for (const [identity, groupItems] of byIdentity) {
|
||||
void identity;
|
||||
if (!groupItems.length) continue;
|
||||
// [STEP 1] 取最近活动 Item 作为任务级代表 Run;PDF 则跨 Run 独立选择最新版本。
|
||||
const sorted = [...groupItems].sort((a, b) => {
|
||||
const aAt = Date.parse(String(a.last_activity_at || a.updated_at || '').trim()) || 0;
|
||||
const bAt = Date.parse(String(b.last_activity_at || b.updated_at || '').trim()) || 0;
|
||||
if (bAt !== aAt) return bAt - aAt;
|
||||
return String(b.current_run_no || '').localeCompare(String(a.current_run_no || ''));
|
||||
});
|
||||
const primaryItem = sorted[0];
|
||||
if (!primaryItem) continue;
|
||||
const runNo = String(
|
||||
primaryItem.current_run_no || primaryItem.workflow_no || primaryItem.item_no || '',
|
||||
).trim();
|
||||
// [STEP 2] 同 OT 的旧 Run 仍可能承载未重识别 PDF,禁止整批过滤到代表 Run。
|
||||
const uniqueDocuments = dedupeFallbackDocuments(groupItems);
|
||||
const effectiveItems = uniqueDocuments.map((row) => row.source_item);
|
||||
// 任务级分组/操作只由最近代表 Item 决定;旧 Run 仅贡献未受影响的 PDF,不得反向污染状态。
|
||||
const statuses = [resolveItemDisplayStatus(primaryItem)];
|
||||
const hasGate = Boolean(primaryItem.process_gate?.current_blocking_gate);
|
||||
let group: ConversationProcessingTaskGroup = 'history';
|
||||
for (const status of statuses) {
|
||||
const g = classifyConversationProcessingGroup(status, { hasBlockingGate: hasGate });
|
||||
if (g === 'needs_action') {
|
||||
group = 'needs_action';
|
||||
break;
|
||||
}
|
||||
if (g === 'processing') {
|
||||
group = 'processing';
|
||||
continue;
|
||||
}
|
||||
if (g === 'completed' && group !== 'processing') {
|
||||
group = 'completed';
|
||||
}
|
||||
}
|
||||
const primaryStatus = statuses.find((s) => NEEDS_ACTION_LIFECYCLES.has(s))
|
||||
|| statuses.find((s) => PROCESSING_LIFECYCLES.has(s))
|
||||
|| statuses.find((s) => COMPLETED_LIFECYCLES.has(s))
|
||||
|| statuses[0]
|
||||
|| 'queued';
|
||||
// [UI-01] 必须原样输出后端真实 OT;仅缺省时才用本地兼容号,且不得用于写接口。
|
||||
const authoritativeTaskNo = String(
|
||||
effectiveItems.map((row) => row.user_task_no).find((value) => String(value || '').trim())
|
||||
|| groupItems.map((row) => row.user_task_no).find((value) => String(value || '').trim())
|
||||
|| '',
|
||||
).trim();
|
||||
const userTaskNo = authoritativeTaskNo || `OT-${runNo}`;
|
||||
const documentNames = uniqueDocuments
|
||||
.map((row) => String(row.filename || '').trim())
|
||||
.filter(Boolean);
|
||||
const isMulti = uniqueDocuments.length > 1;
|
||||
const title = isMulti
|
||||
? null
|
||||
: (documentNames[0] || String(primaryItem.current_document_filename || '').trim() || null);
|
||||
const activityRaw = String(primaryItem.last_activity_at || primaryItem.updated_at || '').trim();
|
||||
const documentObjects = uniqueDocuments.map((row) => ({
|
||||
kind: 'document' as const,
|
||||
object_key: row.document_id > 0
|
||||
? `DOC-${row.document_id}`
|
||||
: `DOC-${row.root_document_id || row.filename || 'unknown'}`,
|
||||
label: row.filename || `DOC-${row.document_id || row.root_document_id}`,
|
||||
status_label: row.status_label,
|
||||
document_id: row.document_id || null,
|
||||
root_document_id: row.root_document_id || null,
|
||||
filename: row.filename,
|
||||
content_hash: row.content_hash,
|
||||
run_no: row.current_run_no,
|
||||
current_run_no: row.current_run_no,
|
||||
user_task_no: userTaskNo,
|
||||
focused: false,
|
||||
}));
|
||||
tasks.push({
|
||||
user_task_no: userTaskNo,
|
||||
user_task_authoritative: Boolean(authoritativeTaskNo),
|
||||
title,
|
||||
display_kind: isMulti ? 'multi_document_task' : 'single_document_task',
|
||||
document_names: documentNames,
|
||||
group,
|
||||
status_label: primaryStatus,
|
||||
file_count: uniqueDocuments.length,
|
||||
run_no: runNo || null,
|
||||
workflow_no: String(primaryItem.workflow_no || '').trim() || null,
|
||||
can_append: false,
|
||||
append_block_reason: 'input_already_frozen',
|
||||
last_activity_at: activityRaw || null,
|
||||
focused: Boolean(
|
||||
(focusUserTask && focusUserTask === userTaskNo)
|
||||
|| (focusRun && focusRun === runNo),
|
||||
),
|
||||
objects: [
|
||||
...projectConversationProcessingObjects(effectiveItems, {
|
||||
focusTaskNo: options?.focusTaskNo,
|
||||
focusRunNo: runNo,
|
||||
}),
|
||||
...documentObjects,
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
return tasks;
|
||||
}
|
||||
|
||||
/**
|
||||
* 将任务列表按分组装入 ConversationProcessingProjection。
|
||||
*/
|
||||
export function groupConversationProcessingTasks(
|
||||
tasks: ConversationProcessingUserTask[],
|
||||
options?: {
|
||||
focusedTaskNo?: string | null;
|
||||
recentTaskNo?: string | null;
|
||||
},
|
||||
): ConversationProcessingProjection {
|
||||
const needs_action = tasks.filter((t) => t.group === 'needs_action');
|
||||
const processing = tasks.filter((t) => t.group === 'processing');
|
||||
const completed = tasks.filter((t) => t.group === 'completed');
|
||||
const history = tasks.filter((t) => t.group === 'history');
|
||||
const active = [...needs_action, ...processing, ...completed];
|
||||
const totalFiles = active.reduce((sum, task) => sum + Number(task.file_count || 0), 0);
|
||||
const summary: ConversationProcessingSummary = {
|
||||
total_tasks: needs_action.length + processing.length + completed.length,
|
||||
total_files: totalFiles,
|
||||
processing: processing.length,
|
||||
needs_action: needs_action.length,
|
||||
completed: completed.length,
|
||||
history: history.length,
|
||||
};
|
||||
return {
|
||||
summary,
|
||||
focused_task_no: options?.focusedTaskNo || null,
|
||||
recent_task_no: options?.recentTaskNo || null,
|
||||
needs_action,
|
||||
processing,
|
||||
completed,
|
||||
history,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 用 Workflow 兜底投影补齐后端 processing 的多 PDF 标题/文件数。
|
||||
* 核心逻辑:同 user_task_no / run_no 时,若兜底 file_count 更大,采用兜底的
|
||||
* display_kind / title / document_names / objects(文档子对象)。
|
||||
*/
|
||||
/**
|
||||
* 将统一 ShippingProcessing status/gate 映射为会话任务分组。
|
||||
* 核心逻辑:waiting_review/blocked/failed → needs_action;completed → completed;
|
||||
* cancelled → history;其余 → processing。
|
||||
*/
|
||||
export function mapShippingProcessingStatusToTaskGroup(
|
||||
item: ShippingProcessingProjection,
|
||||
): ConversationProcessingTaskGroup {
|
||||
const status = String(item.status || '').trim().toLowerCase();
|
||||
const gateAction = String(item.currentGate?.nextActionCode || '').trim();
|
||||
if (
|
||||
status === 'waiting_review'
|
||||
|| status === 'blocked'
|
||||
|| status === 'failed'
|
||||
|| gateAction === 'open_order_review'
|
||||
|| gateAction === 'retry_parse'
|
||||
|| gateAction === 'retry_failed_documents'
|
||||
) {
|
||||
return 'needs_action';
|
||||
}
|
||||
if (status === 'completed') return 'completed';
|
||||
if (status === 'cancelled') return 'history';
|
||||
return 'processing';
|
||||
}
|
||||
|
||||
/**
|
||||
* 将 embedded conversation_processing 的焦点元数据合并到 work_items 派生投影。
|
||||
* 核心逻辑:任务列表必须来自 work_items;仅 focused_task_no / recent_task_no 可取自 embedded。
|
||||
*
|
||||
* @param derived - 由 projectConversationProcessingFromWorkItems 生成的投影
|
||||
* @param embedded - API 内嵌 conversation_processing(可选)
|
||||
* @returns 合并后的投影;derived 为空时回退 embedded
|
||||
*/
|
||||
export function mergeConversationProcessingFocusMetadata(
|
||||
derived: ConversationProcessingProjection | null,
|
||||
embedded: ConversationProcessingProjection | null | undefined,
|
||||
): ConversationProcessingProjection | null {
|
||||
if (!derived) {
|
||||
return embedded && typeof embedded === 'object' ? embedded : null;
|
||||
}
|
||||
if (!embedded || typeof embedded !== 'object') return derived;
|
||||
return {
|
||||
...derived,
|
||||
focused_task_no: embedded.focused_task_no ?? derived.focused_task_no ?? null,
|
||||
recent_task_no: embedded.recent_task_no ?? derived.recent_task_no ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 从统一 shipping-processing 响应解析 ConversationProcessingProjection。
|
||||
* 核心逻辑:work_items 非空时始终由 order_task 工作项合成任务列表;禁止优先 embedded
|
||||
* (兄弟 OT 仅出现在 work_items,embedded 可能缺 sibling)。
|
||||
*
|
||||
* @param workItems - unified.work_items
|
||||
* @param embedded - unified.conversation_processing
|
||||
* @returns 会话处理投影;无可用数据时 null
|
||||
*/
|
||||
export function resolveConversationProcessingFromUnified(
|
||||
workItems: ShippingProcessingProjection[] | null | undefined,
|
||||
embedded: ConversationProcessingProjection | null | undefined,
|
||||
): ConversationProcessingProjection | null {
|
||||
const items = Array.isArray(workItems) ? workItems : [];
|
||||
if (items.length > 0) {
|
||||
return mergeConversationProcessingFocusMetadata(
|
||||
projectConversationProcessingFromWorkItems(items),
|
||||
embedded,
|
||||
);
|
||||
}
|
||||
if (embedded && typeof embedded === 'object') return embedded;
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 从统一 work_items 合成 ConversationProcessingProjection(仅 order_task)。
|
||||
*
|
||||
* 核心逻辑:order_task 工作项填充 needs_action/processing/completed;intake 不入组。
|
||||
*
|
||||
* @param workItems - 统一投影 work_items
|
||||
* @returns 兼容投影;无 order_task 时返回 null
|
||||
*/
|
||||
export function projectConversationProcessingFromWorkItems(
|
||||
workItems: ShippingProcessingProjection[] | null | undefined,
|
||||
): ConversationProcessingProjection | null {
|
||||
const items = Array.isArray(workItems) ? workItems : [];
|
||||
const orderTasks = items.filter((row) => row.workItemType === 'order_task');
|
||||
if (!orderTasks.length) return null;
|
||||
|
||||
const needs_action: ConversationProcessingUserTask[] = [];
|
||||
const processing: ConversationProcessingUserTask[] = [];
|
||||
const completed: ConversationProcessingUserTask[] = [];
|
||||
const history: ConversationProcessingUserTask[] = [];
|
||||
|
||||
for (const item of orderTasks) {
|
||||
const taskNo = String(item.workItemNo || item.rootOrderTaskNo || '').trim();
|
||||
if (!taskNo) continue;
|
||||
const group = mapShippingProcessingStatusToTaskGroup(item);
|
||||
const docCount = Number(item.sourceSummary?.documentCount || 0);
|
||||
const filename = String(item.sourceSummary?.filename || '').trim();
|
||||
const task: ConversationProcessingUserTask = {
|
||||
user_task_no: taskNo,
|
||||
user_task_authoritative: true,
|
||||
title: filename || null,
|
||||
display_kind: docCount > 1 ? 'multi_document_task' : 'single_document_task',
|
||||
document_names: filename ? [filename] : [],
|
||||
group,
|
||||
status_label: String(item.status || '') || null,
|
||||
file_count: docCount > 0 ? docCount : (filename ? 1 : 0),
|
||||
run_no: null,
|
||||
can_append: false,
|
||||
last_activity_at: item.lastActivityAt || null,
|
||||
available_actions: Array.isArray(item.availableActions) ? [...item.availableActions] : [],
|
||||
primary_action: item.currentGate?.nextActionCode || item.availableActions?.[0] || null,
|
||||
};
|
||||
if (group === 'needs_action') needs_action.push(task);
|
||||
else if (group === 'processing') processing.push(task);
|
||||
else if (group === 'completed') completed.push(task);
|
||||
else history.push(task);
|
||||
}
|
||||
|
||||
const active = [...needs_action, ...processing, ...completed];
|
||||
if (!active.length && !history.length) return null;
|
||||
const totalFiles = active.reduce((sum, task) => sum + Number(task.file_count || 0), 0);
|
||||
return {
|
||||
summary: {
|
||||
total_tasks: active.length,
|
||||
total_files: totalFiles,
|
||||
processing: processing.length,
|
||||
needs_action: needs_action.length,
|
||||
completed: completed.length,
|
||||
history: history.length,
|
||||
},
|
||||
focused_task_no: null,
|
||||
recent_task_no: null,
|
||||
needs_action,
|
||||
processing,
|
||||
completed,
|
||||
history,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
/**
|
||||
* features/chat/shipping/conversationProcessingState.spec.ts
|
||||
* 用途:验收会话「本次处理中」焦点/查看/折叠状态不被普通轮询覆盖。
|
||||
* 依赖:Vitest、conversationProcessingState。
|
||||
* 逻辑:手动焦点优先于服务端;toggle 详情互斥;history 展开独立。
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
createConversationProcessingUiState,
|
||||
focusTaskManually,
|
||||
markTaskViewed,
|
||||
resolveFocusedTask,
|
||||
shouldExpandTaskDetails,
|
||||
toggleTaskDetails,
|
||||
} from './conversationProcessingState';
|
||||
|
||||
describe('conversationProcessingState', () => {
|
||||
it('prefers manual focus over server focused / recent', () => {
|
||||
const state = createConversationProcessingUiState();
|
||||
focusTaskManually(state, 'OT-2', { expandDetails: true });
|
||||
expect(resolveFocusedTask(state, {
|
||||
serverFocusedTaskNo: 'OT-1',
|
||||
recentTaskNo: 'OT-3',
|
||||
})).toBe('OT-2');
|
||||
expect(state.expandedDetailTaskNo).toBe('OT-2');
|
||||
});
|
||||
|
||||
it('falls back to server then recent when no manual focus', () => {
|
||||
const state = createConversationProcessingUiState();
|
||||
expect(resolveFocusedTask(state, {
|
||||
serverFocusedTaskNo: 'OT-1',
|
||||
recentTaskNo: 'OT-3',
|
||||
})).toBe('OT-1');
|
||||
expect(resolveFocusedTask(state, { recentTaskNo: 'OT-3' })).toBe('OT-3');
|
||||
});
|
||||
|
||||
it('marks viewed without implying resolved', () => {
|
||||
const state = createConversationProcessingUiState();
|
||||
markTaskViewed(state, 'OT-9');
|
||||
expect(state.viewedTaskNos.has('OT-9')).toBe(true);
|
||||
});
|
||||
|
||||
it('toggles file details and keeps only one expanded task', () => {
|
||||
const state = createConversationProcessingUiState();
|
||||
toggleTaskDetails(state, 'OT-A');
|
||||
expect(state.expandedDetailTaskNo).toBe('OT-A');
|
||||
toggleTaskDetails(state, 'OT-B');
|
||||
expect(state.expandedDetailTaskNo).toBe('OT-B');
|
||||
toggleTaskDetails(state, 'OT-B');
|
||||
expect(state.expandedDetailTaskNo).toBeNull();
|
||||
});
|
||||
|
||||
it('expands only when user explicitly toggles details', () => {
|
||||
const state = createConversationProcessingUiState();
|
||||
expect(shouldExpandTaskDetails(state, 'OT-1', { focusedTaskNo: 'OT-1' })).toBe(false);
|
||||
state.expandedDetailTaskNo = 'OT-1';
|
||||
expect(shouldExpandTaskDetails(state, 'OT-1', { focusedTaskNo: 'OT-1' })).toBe(true);
|
||||
state.expandedDetailTaskNo = 'OT-2';
|
||||
expect(shouldExpandTaskDetails(state, 'OT-1', { focusedTaskNo: 'OT-1' })).toBe(false);
|
||||
expect(shouldExpandTaskDetails(state, 'OT-2', { focusedTaskNo: 'OT-1' })).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,117 @@
|
||||
/**
|
||||
* features/chat/shipping/conversationProcessingState.ts
|
||||
* 用途:管理会话「本次处理中」焦点、已查看与文件详情展开的客户端状态。
|
||||
* 依赖:无 IO;由 ShippingConversationProcessingCard / useShippingNoticeWorkflow 消费。
|
||||
* 逻辑:普通轮询只合并服务端摘要,不覆盖用户手动折叠/焦点;高优先级状态只高亮不抢焦点。
|
||||
*/
|
||||
|
||||
import { reactive } from 'vue';
|
||||
|
||||
export interface ConversationProcessingUiState {
|
||||
/** 用户主动聚焦的用户可见任务号 */
|
||||
manualFocusedTaskNo: string | null;
|
||||
/** 已打开过详情的任务 */
|
||||
viewedTaskNos: Set<string>;
|
||||
/** 文件详情展开的任务(通常至多一个) */
|
||||
expandedDetailTaskNo: string | null;
|
||||
/** 处理记录分组是否展开 */
|
||||
historyExpanded: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建会话级 UI 状态容器(按 conversation 实例化,切会话时重建)。
|
||||
*/
|
||||
export function createConversationProcessingUiState(): ConversationProcessingUiState {
|
||||
return reactive({
|
||||
manualFocusedTaskNo: null,
|
||||
viewedTaskNos: new Set<string>(),
|
||||
expandedDetailTaskNo: null,
|
||||
historyExpanded: false,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 重置会话级 UI 状态(切 conversation 时调用)。
|
||||
*/
|
||||
export function resetConversationProcessingUiState(
|
||||
state: ConversationProcessingUiState,
|
||||
): void {
|
||||
state.manualFocusedTaskNo = null;
|
||||
state.viewedTaskNos.clear();
|
||||
state.expandedDetailTaskNo = null;
|
||||
state.historyExpanded = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析有效焦点:手动焦点优先,否则用服务端 focused_task_no / recent。
|
||||
*/
|
||||
export function resolveFocusedTask(
|
||||
state: ConversationProcessingUiState,
|
||||
options?: {
|
||||
serverFocusedTaskNo?: string | null;
|
||||
recentTaskNo?: string | null;
|
||||
},
|
||||
): string | null {
|
||||
const manual = String(state.manualFocusedTaskNo || '').trim();
|
||||
if (manual) return manual;
|
||||
const server = String(options?.serverFocusedTaskNo || '').trim();
|
||||
if (server) return server;
|
||||
const recent = String(options?.recentTaskNo || '').trim();
|
||||
return recent || null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 用户点击任务卡:设置手动焦点并可选展开详情。
|
||||
*/
|
||||
export function focusTaskManually(
|
||||
state: ConversationProcessingUiState,
|
||||
taskNo: string,
|
||||
options?: { expandDetails?: boolean },
|
||||
): void {
|
||||
const normalized = String(taskNo || '').trim();
|
||||
if (!normalized) return;
|
||||
state.manualFocusedTaskNo = normalized;
|
||||
if (options?.expandDetails !== false) {
|
||||
state.expandedDetailTaskNo = normalized;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 标记任务已查看(可折叠 history;不等于 resolved)。
|
||||
*/
|
||||
export function markTaskViewed(state: ConversationProcessingUiState, taskNo: string): void {
|
||||
const normalized = String(taskNo || '').trim();
|
||||
if (!normalized) return;
|
||||
state.viewedTaskNos.add(normalized);
|
||||
}
|
||||
|
||||
/**
|
||||
* 是否展开某任务文件详情:仅当用户显式展开(expandedDetailTaskNo),不因焦点自动展开。
|
||||
*/
|
||||
export function shouldExpandTaskDetails(
|
||||
state: ConversationProcessingUiState,
|
||||
taskNo: string,
|
||||
options?: {
|
||||
focusedTaskNo?: string | null;
|
||||
forceExpand?: boolean;
|
||||
},
|
||||
): boolean {
|
||||
const normalized = String(taskNo || '').trim();
|
||||
if (!normalized) return false;
|
||||
if (options?.forceExpand) return true;
|
||||
return state.expandedDetailTaskNo === normalized;
|
||||
}
|
||||
|
||||
/**
|
||||
* 切换文件详情展开;同一时刻只保留一个展开任务。
|
||||
*/
|
||||
export function toggleTaskDetails(
|
||||
state: ConversationProcessingUiState,
|
||||
taskNo: string,
|
||||
): void {
|
||||
const normalized = String(taskNo || '').trim();
|
||||
if (!normalized) return;
|
||||
state.expandedDetailTaskNo = state.expandedDetailTaskNo === normalized
|
||||
? null
|
||||
: normalized;
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
/**
|
||||
* features/chat/shipping/normalizeShippingProcessing.spec.ts
|
||||
* 用途:验收 snake_case → camelCase 规范与缺字段安全默认。
|
||||
* 依赖:Vitest、normalizeShippingProcessing。
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
normalizeShippingProcessingProjection,
|
||||
normalizeShippingProcessingWorkItems,
|
||||
} from './normalizeShippingProcessing';
|
||||
|
||||
describe('normalizeShippingProcessingProjection', () => {
|
||||
it('maps snake_case backend payload to camelCase DTO', () => {
|
||||
const normalized = normalizeShippingProcessingProjection({
|
||||
work_item_type: 'order_task',
|
||||
work_item_no: 'OT-1',
|
||||
source_type: 'direct_pdf',
|
||||
root_order_task_no: 'OT-1',
|
||||
shipping_notice_no: null,
|
||||
conversation_id: 'conv-1',
|
||||
submission_no: 'SOS-1',
|
||||
intake_no: 'SNI-1',
|
||||
status: 'waiting_review',
|
||||
stage: 'waiting_review',
|
||||
progress_version: 3,
|
||||
last_activity_at: '2026-08-04T12:00:00Z',
|
||||
current_gate: {
|
||||
gate_code: 'field_conflict_resolution',
|
||||
status: 'blocked',
|
||||
next_action_code: 'resolve_field_conflicts',
|
||||
blocking_reason_code: 'pdf_preferred_critical_conflict',
|
||||
attempt_no: 1,
|
||||
},
|
||||
available_actions: ['open_review'],
|
||||
source_summary: {
|
||||
email_subject: null,
|
||||
filename: 'a.pdf',
|
||||
document_count: 1,
|
||||
parsed_document_count: 1,
|
||||
candidate_count: 1,
|
||||
customer_name: 'ACME',
|
||||
po_number: 'PO-1',
|
||||
failure_reason_code: null,
|
||||
parse_attempt_count: 0,
|
||||
asset_status: 'ready',
|
||||
},
|
||||
child_order_tasks: [],
|
||||
});
|
||||
expect(normalized).not.toBeNull();
|
||||
expect(normalized!.workItemNo).toBe('OT-1');
|
||||
expect(normalized!.sourceType).toBe('direct_pdf');
|
||||
expect(normalized!.status).toBe('waiting_review');
|
||||
expect(normalized!.currentGate?.gateCode).toBe('field_conflict_resolution');
|
||||
expect(normalized!.currentGate?.attemptNo).toBe(1);
|
||||
expect(normalized!.sourceSummary.filename).toBe('a.pdf');
|
||||
expect(normalized!.sourceSummary.assetStatus).toBe('ready');
|
||||
expect(normalized!.availableActions).toEqual(['open_review']);
|
||||
});
|
||||
|
||||
it('returns null when work_item_no missing', () => {
|
||||
expect(normalizeShippingProcessingProjection({ status: 'processing' })).toBeNull();
|
||||
});
|
||||
|
||||
it('normalizes work_items arrays', () => {
|
||||
const items = normalizeShippingProcessingWorkItems([
|
||||
{ work_item_no: 'OT-A', work_item_type: 'order_task', status: 'processing', stage: 'document_parsing' },
|
||||
{ status: 'processing' },
|
||||
]);
|
||||
expect(items).toHaveLength(1);
|
||||
expect(items[0].workItemNo).toBe('OT-A');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,143 @@
|
||||
/**
|
||||
* features/chat/shipping/normalizeShippingProcessing.ts
|
||||
* 用途:将后端 snake_case ShippingProcessingProjection 规范为前端 camelCase DTO。
|
||||
* 依赖:shipping.api.types ShippingProcessingProjection / ProcessGateSummary。
|
||||
* 逻辑:API 边界一次性转换;透传 Gate attemptNo 与 Intake 失败恢复摘要字段。
|
||||
*/
|
||||
|
||||
import type {
|
||||
OrderIntakeSourceType,
|
||||
ProcessGateSummary,
|
||||
ShippingOrderTaskSummary,
|
||||
ShippingProcessingProjection,
|
||||
ShippingProcessingStage,
|
||||
ShippingProcessingStatus,
|
||||
ShippingProcessingWorkItemType,
|
||||
} from '../types/shipping.api.types';
|
||||
|
||||
/**
|
||||
* 读取原始对象上的字符串字段(兼容 snake / camel)。
|
||||
*/
|
||||
function readString(raw: Record<string, unknown>, snake: string, camel: string): string {
|
||||
const value = raw[snake] ?? raw[camel];
|
||||
return value == null ? '' : String(value);
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取可空字符串。
|
||||
*/
|
||||
function readNullableString(
|
||||
raw: Record<string, unknown>,
|
||||
snake: string,
|
||||
camel: string,
|
||||
): string | null {
|
||||
const value = raw[snake] ?? raw[camel];
|
||||
if (value == null || value === '') return null;
|
||||
return String(value);
|
||||
}
|
||||
|
||||
/**
|
||||
* 规范单个 OT 摘要。
|
||||
*/
|
||||
function normalizeChildTask(raw: unknown): ShippingOrderTaskSummary | null {
|
||||
if (!raw || typeof raw !== 'object') return null;
|
||||
const item = raw as Record<string, unknown>;
|
||||
const orderTaskNo = readString(item, 'order_task_no', 'orderTaskNo');
|
||||
if (!orderTaskNo) return null;
|
||||
return {
|
||||
orderTaskNo,
|
||||
status: readString(item, 'status', 'status') as ShippingProcessingStatus,
|
||||
stage: readString(item, 'stage', 'stage') as ShippingProcessingStage,
|
||||
customerName: readNullableString(item, 'customer_name', 'customerName'),
|
||||
poNumber: readNullableString(item, 'po_number', 'poNumber'),
|
||||
lastActivityAt: readNullableString(item, 'last_activity_at', 'lastActivityAt'),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 规范 Gate 摘要。
|
||||
*/
|
||||
function normalizeGate(raw: unknown): ProcessGateSummary | null {
|
||||
if (!raw || typeof raw !== 'object') return null;
|
||||
const item = raw as Record<string, unknown>;
|
||||
const gateCode = readString(item, 'gate_code', 'gateCode');
|
||||
if (!gateCode) return null;
|
||||
return {
|
||||
gateCode,
|
||||
status: readString(item, 'status', 'status') || 'unknown',
|
||||
nextActionCode: readNullableString(item, 'next_action_code', 'nextActionCode'),
|
||||
blockingReasonCode: readNullableString(item, 'blocking_reason_code', 'blockingReasonCode'),
|
||||
attemptNo: (() => {
|
||||
const rawAttempt = item.attempt_no ?? item.attemptNo;
|
||||
if (rawAttempt == null || rawAttempt === '') return null;
|
||||
const n = Number(rawAttempt);
|
||||
return Number.isFinite(n) ? n : null;
|
||||
})(),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 将后端 / 混合字段投影规范为 ShippingProcessingProjection。
|
||||
* 核心逻辑:缺字段给安全默认值,保证四页面可渲染;非法输入返回 null。
|
||||
*
|
||||
* @param raw - API 原始对象
|
||||
* @returns 规范化投影;无法识别时 null
|
||||
*/
|
||||
export function normalizeShippingProcessingProjection(
|
||||
raw: unknown,
|
||||
): ShippingProcessingProjection | null {
|
||||
if (!raw || typeof raw !== 'object') return null;
|
||||
const item = raw as Record<string, unknown>;
|
||||
const workItemNo = readString(item, 'work_item_no', 'workItemNo');
|
||||
if (!workItemNo) return null;
|
||||
|
||||
const summaryRaw = (item.source_summary ?? item.sourceSummary ?? {}) as Record<string, unknown>;
|
||||
const childrenRaw = item.child_order_tasks ?? item.childOrderTasks;
|
||||
const children = Array.isArray(childrenRaw)
|
||||
? childrenRaw.map(normalizeChildTask).filter((row): row is ShippingOrderTaskSummary => Boolean(row))
|
||||
: [];
|
||||
const actionsRaw = item.available_actions ?? item.availableActions;
|
||||
const availableActions = Array.isArray(actionsRaw)
|
||||
? actionsRaw.map((action) => String(action || '').trim()).filter(Boolean)
|
||||
: [];
|
||||
|
||||
return {
|
||||
workItemType: (readString(item, 'work_item_type', 'workItemType') || 'order_task') as ShippingProcessingWorkItemType,
|
||||
workItemNo,
|
||||
sourceType: (readNullableString(item, 'source_type', 'sourceType') || 'eml') as OrderIntakeSourceType,
|
||||
rootOrderTaskNo: readNullableString(item, 'root_order_task_no', 'rootOrderTaskNo'),
|
||||
shippingNoticeNo: readNullableString(item, 'shipping_notice_no', 'shippingNoticeNo'),
|
||||
conversationId: readNullableString(item, 'conversation_id', 'conversationId'),
|
||||
submissionNo: readString(item, 'submission_no', 'submissionNo'),
|
||||
intakeNo: readString(item, 'intake_no', 'intakeNo'),
|
||||
status: (readString(item, 'status', 'status') || 'processing') as ShippingProcessingStatus,
|
||||
stage: (readString(item, 'stage', 'stage') || 'upload_received') as ShippingProcessingStage,
|
||||
progressVersion: Number(item.progress_version ?? item.progressVersion ?? 0) || 0,
|
||||
lastActivityAt: readString(item, 'last_activity_at', 'lastActivityAt'),
|
||||
currentGate: normalizeGate(item.current_gate ?? item.currentGate),
|
||||
availableActions,
|
||||
sourceSummary: {
|
||||
emailSubject: readNullableString(summaryRaw, 'email_subject', 'emailSubject'),
|
||||
filename: readNullableString(summaryRaw, 'filename', 'filename'),
|
||||
documentCount: Number(summaryRaw.document_count ?? summaryRaw.documentCount ?? 0) || 0,
|
||||
parsedDocumentCount: Number(summaryRaw.parsed_document_count ?? summaryRaw.parsedDocumentCount ?? 0) || 0,
|
||||
candidateCount: Number(summaryRaw.candidate_count ?? summaryRaw.candidateCount ?? 0) || 0,
|
||||
customerName: readNullableString(summaryRaw, 'customer_name', 'customerName'),
|
||||
poNumber: readNullableString(summaryRaw, 'po_number', 'poNumber'),
|
||||
failureReasonCode: readNullableString(summaryRaw, 'failure_reason_code', 'failureReasonCode'),
|
||||
parseAttemptCount: Number(summaryRaw.parse_attempt_count ?? summaryRaw.parseAttemptCount ?? 0) || 0,
|
||||
assetStatus: readNullableString(summaryRaw, 'asset_status', 'assetStatus'),
|
||||
},
|
||||
childOrderTasks: children,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 将会话级统一投影响应中的 work_items 规范为数组。
|
||||
*/
|
||||
export function normalizeShippingProcessingWorkItems(raw: unknown): ShippingProcessingProjection[] {
|
||||
if (!Array.isArray(raw)) return [];
|
||||
return raw
|
||||
.map(normalizeShippingProcessingProjection)
|
||||
.filter((item): item is ShippingProcessingProjection => Boolean(item));
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
/**
|
||||
* features/chat/shipping/shippingProcessingFulfillment.ts
|
||||
*
|
||||
* 用途:履约相关节点索引与人工上传 Gate 动作判定(过渡期兼容)。
|
||||
* 依赖:ShippingProcessingProjection / ProcessGateSummary 的轻量字段形状。
|
||||
* 逻辑:ReviewWorkflowProgressPanel、ShippingTaskWorkbench、TaskTodoPanel 共用;
|
||||
* 禁止用 WorkflowItem.lifecycle 推断人工上传或节点高亮。
|
||||
* FULFILLMENT_PROGRESS_NODES 四节点不是 UI 主进度真相;主真相为
|
||||
* ShippingProcessingProjection 15 阶(阶段 2 换 UnifiedProgressTrack)。
|
||||
*/
|
||||
|
||||
/** 复核/任务台共用的履约四节点 stage 键。 */
|
||||
export const FULFILLMENT_PROGRESS_NODES = [
|
||||
'building_order',
|
||||
'inventory_matching',
|
||||
'generating_excel',
|
||||
'freight_uploading',
|
||||
] as const;
|
||||
|
||||
export type FulfillmentProgressNodeKey = typeof FULFILLMENT_PROGRESS_NODES[number];
|
||||
|
||||
/** 指人工上传登记的任务台 / Gate 动作码(不含 RPA retry)。 */
|
||||
export const MANUAL_UPLOAD_GATE_ACTIONS = new Set([
|
||||
'wait_manual_upload',
|
||||
'mark_manual_uploaded',
|
||||
'regenerate_manual_upload_todo',
|
||||
]);
|
||||
|
||||
/** 统一 ShippingProcessing 终态 status(停止轮询)。 */
|
||||
export const TERMINAL_PROCESSING_STATUSES = new Set([
|
||||
'completed',
|
||||
'cancelled',
|
||||
'failed',
|
||||
]);
|
||||
|
||||
/** 统一 ShippingProcessing 非终态 status(可继续轮询)。 */
|
||||
export const IN_PROGRESS_PROCESSING_STATUSES = new Set([
|
||||
'queued',
|
||||
'processing',
|
||||
'waiting_review',
|
||||
'automating',
|
||||
'blocked',
|
||||
'needs_action',
|
||||
]);
|
||||
|
||||
/**
|
||||
* 判定 Gate next_action / available_action 是否指人工上传登记。
|
||||
*
|
||||
* @param code - next_action_code 或 available_actions 项
|
||||
* @returns 是否为人工上传相关动作
|
||||
*/
|
||||
export function isManualUploadGateAction(code: string | null | undefined): boolean {
|
||||
const normalized = String(code || '').trim().toLowerCase();
|
||||
return MANUAL_UPLOAD_GATE_ACTIONS.has(normalized);
|
||||
}
|
||||
|
||||
/**
|
||||
* 从统一投影判断是否需要展示任务台人工上传入口。
|
||||
*
|
||||
* 核心逻辑:读 currentGate.nextActionCode 与 availableActions;RPA automating /
|
||||
* freight_uploading 阶段一律不算人工上传。
|
||||
*
|
||||
* @param projection - 统一 ShippingProcessing 投影
|
||||
* @returns 是否应展示人工上传任务台入口
|
||||
*/
|
||||
export function projectionRequiresManualUploadWorkbench(
|
||||
projection: {
|
||||
status?: string | null;
|
||||
stage?: string | null;
|
||||
currentGate?: { nextActionCode?: string | null; blockingReasonCode?: string | null } | null;
|
||||
availableActions?: string[] | null;
|
||||
} | null | undefined,
|
||||
): boolean {
|
||||
if (!projection) return false;
|
||||
const status = String(projection.status || '').trim().toLowerCase();
|
||||
const stage = String(projection.stage || '').trim().toLowerCase();
|
||||
if (status === 'automating' || stage === 'freight_uploading') return false;
|
||||
const gate = projection.currentGate;
|
||||
if (isManualUploadGateAction(gate?.nextActionCode)) return true;
|
||||
const actions = Array.isArray(projection.availableActions) ? projection.availableActions : [];
|
||||
return actions.some((action) => isManualUploadGateAction(action));
|
||||
}
|
||||
|
||||
/**
|
||||
* 从 Gate 摘要 / checkpoint 判断是否展示「待人工上传登记」提示。
|
||||
*
|
||||
* @param params.nextActionCode - process_gate 或 current_blocking_gate 的 next_action_code
|
||||
* @param params.checkpointKind - ui_state.checkpoint_kind
|
||||
* @param params.availableActions - 后端允许的 action 列表
|
||||
* @returns 是否展示人工上传说明
|
||||
*/
|
||||
export function gateSummaryIndicatesManualUpload(params: {
|
||||
nextActionCode?: string | null;
|
||||
checkpointKind?: string | null;
|
||||
availableActions?: string[] | null;
|
||||
}): boolean {
|
||||
if (isManualUploadGateAction(params.nextActionCode)) return true;
|
||||
if (String(params.checkpointKind || '').trim() === 'wait_manual_upload') return true;
|
||||
const actions = Array.isArray(params.availableActions) ? params.availableActions : [];
|
||||
return actions.some((action) => isManualUploadGateAction(action));
|
||||
}
|
||||
|
||||
/**
|
||||
* 将统一 stage/status 映射到履约四节点索引(0..3)。
|
||||
*
|
||||
* @param stage - ShippingProcessingStage
|
||||
* @param status - ShippingProcessingStatus
|
||||
* @returns 当前节点索引;无法映射时返回 -1
|
||||
*/
|
||||
export function fulfillmentNodeIndexFromStage(
|
||||
stage?: string | null,
|
||||
status?: string | null,
|
||||
): number {
|
||||
const s = String(stage || '').trim().toLowerCase();
|
||||
const st = String(status || '').trim().toLowerCase();
|
||||
if (st === 'completed' || s === 'completed') return 3;
|
||||
if (s === 'freight_uploading' || st === 'automating') return 3;
|
||||
if (s === 'excel_generating' || s === 'generating_excel') return 2;
|
||||
if (s === 'inventory_matching' || s.startsWith('inventory_')) return 1;
|
||||
if (
|
||||
s === 'building_order'
|
||||
|| s === 'order_creating'
|
||||
|| s === 'document_parsing'
|
||||
|| s === 'upload_received'
|
||||
|| s.startsWith('email_')
|
||||
|| s === 'waiting_review'
|
||||
|| s === 'customer_resolving'
|
||||
|| s === 'duplicate_checking'
|
||||
|| s === 'candidate_creating'
|
||||
) {
|
||||
return 0;
|
||||
}
|
||||
if (s) return 0;
|
||||
return -1;
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
/**
|
||||
* features/chat/shipping/shippingProcessingLabels.spec.ts
|
||||
* 用途:验收统一状态文案映射到 chat.shippingProcessing。
|
||||
* 依赖:Vitest、shippingProcessingLabels。
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
resolveShippingProcessingMessage,
|
||||
resolveShippingProcessingStatusLabel,
|
||||
shippingProcessingStatusKey,
|
||||
} from './shippingProcessingLabels';
|
||||
|
||||
describe('shippingProcessingLabels', () => {
|
||||
it('bridges pending_review to waiting_review key', () => {
|
||||
expect(shippingProcessingStatusKey('pending_review')).toBe(
|
||||
'chat.shippingProcessing.status.waiting_review',
|
||||
);
|
||||
});
|
||||
|
||||
it('falls back to shippingProcessing.taskStatus when unified status missing', () => {
|
||||
// 关键断言:旧 taskStatus 已合并进 shippingProcessing。
|
||||
const te = (key: string) => key === 'chat.shippingProcessing.taskStatus.queued';
|
||||
const t = (key: string) => (key.endsWith('queued') ? '排队中' : key);
|
||||
expect(resolveShippingProcessingStatusLabel('queued', te, t)).toBe('排队中');
|
||||
});
|
||||
|
||||
it('uses unified label when available', () => {
|
||||
const te = (key: string) => key === 'chat.shippingProcessing.status.waiting_review';
|
||||
const t = (key: string) => (key.includes('waiting_review') ? '待复核' : key);
|
||||
expect(resolveShippingProcessingStatusLabel('pending_review', te, t)).toBe('待复核');
|
||||
});
|
||||
|
||||
it('resolves group messages from shippingProcessing', () => {
|
||||
const te = (key: string) => key === 'chat.shippingProcessing.groupNeedsAction';
|
||||
const t = (key: string, params?: Record<string, unknown>) => (
|
||||
key.includes('groupNeedsAction') ? `需要你处理 · ${params?.count}` : key
|
||||
);
|
||||
expect(resolveShippingProcessingMessage('groupNeedsAction', te, t, { count: 2 })).toBe('需要你处理 · 2');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,114 @@
|
||||
/**
|
||||
* features/chat/shipping/shippingProcessingLabels.ts
|
||||
* 用途:将统一 ShippingProcessing 状态/阶段码映射到四语言 i18n 键。
|
||||
* 依赖:vue-i18n Composer(由调用方传入 t / te)。
|
||||
* 逻辑:统一读 chat.shippingProcessing.*(含原 shippingWorkflow 合并键,如 taskStatus)。
|
||||
*/
|
||||
|
||||
/** 会话 processing 旧 status_label → 统一 ShippingProcessingStatus。 */
|
||||
const LEGACY_STATUS_TO_PROCESSING: Record<string, string> = {
|
||||
queued: 'processing',
|
||||
processing: 'processing',
|
||||
pending_review: 'waiting_review',
|
||||
waiting_review: 'waiting_review',
|
||||
failed: 'failed',
|
||||
completed: 'completed',
|
||||
cancelled: 'cancelled',
|
||||
cancelling: 'processing',
|
||||
blocked: 'blocked',
|
||||
automating: 'automating',
|
||||
};
|
||||
|
||||
/**
|
||||
* 解析统一处理状态的展示文案键。
|
||||
* 核心逻辑:优先 `chat.shippingProcessing.status.<code>`。
|
||||
* @param status - ShippingProcessingStatus 码
|
||||
* @returns i18n key
|
||||
*/
|
||||
export function shippingProcessingStatusKey(status: string): string {
|
||||
const code = String(status || '').trim();
|
||||
const mapped = LEGACY_STATUS_TO_PROCESSING[code] || code;
|
||||
return mapped
|
||||
? `chat.shippingProcessing.status.${mapped}`
|
||||
: 'chat.shippingProcessing.status.processing';
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析任务状态展示文案。
|
||||
*
|
||||
* @param code - 后端 status / status_label
|
||||
* @param te - i18n te
|
||||
* @param t - i18n t
|
||||
* @returns 本地化文案;皆无则回退原码
|
||||
*/
|
||||
export function resolveShippingProcessingStatusLabel(
|
||||
code: string,
|
||||
te: (key: string) => boolean,
|
||||
t: (key: string) => string,
|
||||
): string {
|
||||
const raw = String(code || '').trim();
|
||||
if (!raw) return '—';
|
||||
const processingKey = shippingProcessingStatusKey(raw);
|
||||
if (te(processingKey)) return t(processingKey);
|
||||
const taskStatusKey = `chat.shippingProcessing.taskStatus.${raw}`;
|
||||
if (te(taskStatusKey)) return t(taskStatusKey);
|
||||
return raw;
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析统一处理文案。
|
||||
*
|
||||
* @param leaf - 文案叶子键(如 groupNeedsAction)
|
||||
* @param te - i18n te
|
||||
* @param t - i18n t
|
||||
* @param params - 插值参数
|
||||
* @returns 本地化文案
|
||||
*/
|
||||
export function resolveShippingProcessingMessage(
|
||||
leaf: string,
|
||||
te: (key: string) => boolean,
|
||||
t: (key: string, params?: Record<string, unknown>) => string,
|
||||
params?: Record<string, unknown>,
|
||||
): string {
|
||||
const code = String(leaf || '').trim();
|
||||
if (!code) return '';
|
||||
const primary = `chat.shippingProcessing.${code}`;
|
||||
if (te(primary)) return t(primary, params);
|
||||
return code;
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析统一处理阶段的展示文案键。
|
||||
* @param stage - ShippingProcessingStage 码
|
||||
* @returns i18n key
|
||||
*/
|
||||
export function shippingProcessingStageKey(stage: string): string {
|
||||
const code = String(stage || '').trim();
|
||||
return code
|
||||
? `chat.shippingProcessing.stage.${code}`
|
||||
: 'chat.shippingProcessing.stage.upload_received';
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析工作项类型文案键。
|
||||
* @param workItemType - order_intake | order_task
|
||||
* @returns i18n key
|
||||
*/
|
||||
export function shippingProcessingWorkItemTypeKey(workItemType: string): string {
|
||||
const code = String(workItemType || '').trim();
|
||||
return code
|
||||
? `chat.shippingProcessing.workItemType.${code}`
|
||||
: 'chat.shippingProcessing.workItemType.order_task';
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析来源类型文案键(eml / direct_pdf)。
|
||||
* @param sourceType - OrderIntakeSourceType
|
||||
* @returns i18n key
|
||||
*/
|
||||
export function shippingProcessingSourceTypeKey(sourceType: string): string {
|
||||
const code = String(sourceType || '').trim();
|
||||
return code
|
||||
? `chat.shippingProcessing.sourceType.${code}`
|
||||
: 'chat.shippingProcessing.sourceType.eml';
|
||||
}
|
||||
@@ -5,7 +5,10 @@
|
||||
* 逻辑:后端 UI State 缺失时,前端仍需把关键人工介入态渲染为 blocked。
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { buildShippingWorkflowSteps } from './shippingStepper';
|
||||
import {
|
||||
applyShippingProcessingStageToSteps,
|
||||
buildShippingWorkflowSteps,
|
||||
} from './shippingStepper';
|
||||
|
||||
describe('shippingStepper', () => {
|
||||
it('marks inventory step as blocked when RPA inventory is exhausted', () => {
|
||||
@@ -29,4 +32,19 @@ describe('shippingStepper', () => {
|
||||
|
||||
expect(steps[2]?.status).toBe('blocked');
|
||||
});
|
||||
|
||||
it('overlays unified processing stage onto base stepper steps', () => {
|
||||
const base = buildShippingWorkflowSteps({
|
||||
process_status: 'parsed',
|
||||
current_step: 'step2_parse_confirm',
|
||||
});
|
||||
const overlaid = applyShippingProcessingStageToSteps(base, {
|
||||
status: 'waiting_review',
|
||||
stage: 'waiting_review',
|
||||
currentGate: { status: 'blocked' },
|
||||
});
|
||||
// 关键断言:统一投影 waiting_review 应把第 2 步标为 blocked,而非沿用旧 process_status。
|
||||
expect(overlaid[1]?.status).toBe('blocked');
|
||||
expect(overlaid[0]?.status).toBe('completed');
|
||||
});
|
||||
});
|
||||
@@ -1,9 +1,15 @@
|
||||
/**
|
||||
* features/chat/shipping/shippingStepper.ts
|
||||
* 用途:基于 shipping task 状态推导前端七步 Stepper 展示数据。
|
||||
* 依赖:无外部模块;ShippingWorkflowStepper.vue 消费本模块输出。
|
||||
* 逻辑:buildShippingWorkflowSteps 将 process_status / checkpoint 等映射为步骤 id 与 done/active 状态。
|
||||
* 用途:基于 shipping task 状态推导前端 Stepper 展示数据(七步 legacy / 四步履约)。
|
||||
* 依赖:ShippingProcessingProjection(可选叠加)、shippingProcessingFulfillment;ShippingWorkflowStepper.vue 消费输出。
|
||||
* 逻辑:任务台优先 buildFulfillmentWorkflowSteps(四节点);无投影时不回退旧 ui_state;
|
||||
* resolveShippingWorkflowSteps 仍供对话等未切流页面作 legacy 回退。
|
||||
*/
|
||||
import {
|
||||
FULFILLMENT_PROGRESS_NODES,
|
||||
fulfillmentNodeIndexFromStage,
|
||||
type FulfillmentProgressNodeKey,
|
||||
} from './shippingProcessingFulfillment';
|
||||
export interface ShippingTaskStepperSource {
|
||||
process_status?: string | null;
|
||||
review_status?: string | null;
|
||||
@@ -135,6 +141,64 @@ function deriveCurrentIndex(task: ShippingTaskStepperSource | null | undefined):
|
||||
return 0;
|
||||
}
|
||||
|
||||
/** 统一 ShippingProcessingStage → 粗粒度 Stepper 下标(过渡期;阶段 2 换 UnifiedProgressTrack)。 */
|
||||
const PROCESSING_STAGE_INDEX_MAP: Record<string, number> = {
|
||||
upload_received: 0,
|
||||
email_parsing: 1,
|
||||
document_parsing: 1,
|
||||
email_adjudicating: 1,
|
||||
candidate_creating: 1,
|
||||
customer_resolving: 1,
|
||||
duplicate_checking: 1,
|
||||
// 业务 15 阶中库存源在复核前;七步 legacy 仍映射到「库存准备」步。
|
||||
inventory_source_resolving: 2,
|
||||
waiting_review: 1,
|
||||
order_creating: 1,
|
||||
inventory_fetching: 2,
|
||||
inventory_matching: 4,
|
||||
excel_generating: 5,
|
||||
freight_uploading: 6,
|
||||
completed: 6,
|
||||
};
|
||||
|
||||
/**
|
||||
* 用统一投影 stage/status 覆盖 Stepper 当前步(切流主源)。
|
||||
*
|
||||
* 核心逻辑:有投影时按 stage 重算 completed/current/pending;blocked/failed 标当前步 blocked;
|
||||
* 无投影或无法映射时原样返回 baseSteps。
|
||||
*
|
||||
* @param baseSteps - ui_state / process_status 推导的步骤
|
||||
* @param projection - 统一 order_task 投影
|
||||
*/
|
||||
export function applyShippingProcessingStageToSteps(
|
||||
baseSteps: ShippingWorkflowStepItem[],
|
||||
projection: { status?: string | null; stage?: string | null; currentGate?: { status?: string | null } | null } | null | undefined,
|
||||
): ShippingWorkflowStepItem[] {
|
||||
if (!projection || !baseSteps.length) return baseSteps;
|
||||
const stage = String(projection.stage || '').trim();
|
||||
const status = String(projection.status || '').trim().toLowerCase();
|
||||
const stageIndex = PROCESSING_STAGE_INDEX_MAP[stage];
|
||||
if (stageIndex === undefined && status !== 'completed' && status !== 'failed' && status !== 'blocked') {
|
||||
return baseSteps;
|
||||
}
|
||||
const currentIndex = status === 'completed' ? baseSteps.length - 1 : (stageIndex ?? 0);
|
||||
const gateBlocked = String(projection.currentGate?.status || '').trim().toLowerCase() === 'blocked'
|
||||
|| status === 'blocked'
|
||||
|| status === 'failed'
|
||||
|| status === 'waiting_review';
|
||||
return baseSteps.map((step, index) => {
|
||||
let nextStatus: ShippingWorkflowStepItem['status'] = 'pending';
|
||||
if (status === 'completed' || status === 'cancelled') {
|
||||
nextStatus = 'completed';
|
||||
} else if (index < currentIndex) {
|
||||
nextStatus = 'completed';
|
||||
} else if (index === currentIndex) {
|
||||
nextStatus = gateBlocked ? 'blocked' : 'current';
|
||||
}
|
||||
return { ...step, status: nextStatus };
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 将 task 状态映射为七步 Stepper 项(id / label / done / active)。
|
||||
*/
|
||||
@@ -178,3 +242,45 @@ export function buildShippingWorkflowSteps(
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 从统一 ShippingProcessing 投影构建履约四节点 Stepper(任务台主源)。
|
||||
*
|
||||
* 核心逻辑:仅在有投影时返回步骤;节点标签由调用方传入 i18n 文案。
|
||||
*
|
||||
* @param projection - 统一 order_task 投影
|
||||
* @param nodeLabels - 四节点展示文案(building_order … freight_uploading)
|
||||
* @returns 四步 Stepper 项;无投影时返回 null
|
||||
*/
|
||||
export function buildFulfillmentWorkflowSteps(
|
||||
projection: {
|
||||
stage?: string | null;
|
||||
status?: string | null;
|
||||
currentGate?: { status?: string | null } | null;
|
||||
} | null | undefined,
|
||||
nodeLabels: Record<FulfillmentProgressNodeKey, string>,
|
||||
): ShippingWorkflowStepItem[] | null {
|
||||
if (!projection) return null;
|
||||
const activeIndex = fulfillmentNodeIndexFromStage(projection.stage, projection.status);
|
||||
const status = String(projection.status || '').trim().toLowerCase();
|
||||
const gateBlocked = String(projection.currentGate?.status || '').trim().toLowerCase() === 'blocked'
|
||||
|| status === 'blocked'
|
||||
|| status === 'failed'
|
||||
|| status === 'waiting_review';
|
||||
|
||||
return FULFILLMENT_PROGRESS_NODES.map((key, index) => {
|
||||
let stepStatus: ShippingWorkflowStepItem['status'] = 'pending';
|
||||
if (status === 'completed' || status === 'cancelled') {
|
||||
stepStatus = 'completed';
|
||||
} else if (activeIndex >= 0 && index < activeIndex) {
|
||||
stepStatus = 'completed';
|
||||
} else if (activeIndex >= 0 && index === activeIndex) {
|
||||
stepStatus = gateBlocked ? 'blocked' : 'current';
|
||||
}
|
||||
return {
|
||||
id: `fulfillment-${key}`,
|
||||
label: nodeLabels[key as FulfillmentProgressNodeKey],
|
||||
status: stepStatus,
|
||||
};
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
/**
|
||||
* features/chat/shipping/shippingSubmissionFeedback.spec.ts
|
||||
* 用途:验收统一提交决策反馈结构(无弹窗、含短时标签码)。
|
||||
* 依赖:Vitest、shippingSubmissionFeedback。
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
buildShippingSubmissionFeedback,
|
||||
createComposerContextId,
|
||||
createShippingSubmissionId,
|
||||
} from './shippingSubmissionFeedback';
|
||||
|
||||
describe('shippingSubmissionFeedback', () => {
|
||||
it('maps appended / created decisions to badge codes', () => {
|
||||
expect(buildShippingSubmissionFeedback({
|
||||
decision: 'appended',
|
||||
user_task_no: 'OT-1',
|
||||
run_no: 'RUN-1',
|
||||
created_new: false,
|
||||
}, 3)).toMatchObject({
|
||||
decision: 'appended',
|
||||
badgeCode: 'just_appended',
|
||||
fileCount: 3,
|
||||
recentAppendCount: 3,
|
||||
});
|
||||
expect(buildShippingSubmissionFeedback({
|
||||
decision: 'created',
|
||||
user_task_no: 'OT-2',
|
||||
run_no: 'RUN-2',
|
||||
created_new: true,
|
||||
}, 1)).toMatchObject({
|
||||
decision: 'created',
|
||||
badgeCode: 'just_created',
|
||||
createdNew: true,
|
||||
});
|
||||
});
|
||||
|
||||
it('creates stable-looking submission and composer ids', () => {
|
||||
expect(createShippingSubmissionId()).toMatch(/^SUB-/);
|
||||
expect(createComposerContextId()).toMatch(/^CMP-/);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,63 @@
|
||||
/**
|
||||
* features/chat/shipping/shippingSubmissionFeedback.ts
|
||||
* 用途:根据统一提交决策生成聊天区非阻塞系统文案与右侧短时标签。
|
||||
* 依赖:OrderExtractionSubmissionResponse;不含敏感数据。
|
||||
* 逻辑:由 useShippingOrderExtractionRuns / ChatMessageBubble 消费;不弹窗、不作为唯一 Toast。
|
||||
*/
|
||||
|
||||
import type { OrderExtractionSubmissionResponse } from '@/features/chat/types/shipping.api.types';
|
||||
|
||||
export interface ShippingSubmissionFeedback {
|
||||
/** 聊天区可回看系统消息正文(调用方再走 i18n 模板时也可只用 decision) */
|
||||
decision: 'appended' | 'created';
|
||||
fileCount: number;
|
||||
userTaskNo: string;
|
||||
runNo: string;
|
||||
createdNew: boolean;
|
||||
reasonCode?: string | null;
|
||||
/** 右侧任务卡短时标签码 */
|
||||
badgeCode: 'just_appended' | 'just_created';
|
||||
recentAppendCount?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* 从提交响应生成用户可见反馈结构。
|
||||
* @param response - 统一提交 API 响应
|
||||
* @param fileCount - 本次发送附件数
|
||||
*/
|
||||
export function buildShippingSubmissionFeedback(
|
||||
response: OrderExtractionSubmissionResponse,
|
||||
fileCount: number,
|
||||
): ShippingSubmissionFeedback {
|
||||
const decision = response.decision === 'appended' ? 'appended' : 'created';
|
||||
return {
|
||||
decision,
|
||||
fileCount: Math.max(0, Number(fileCount) || 0),
|
||||
userTaskNo: String(response.user_task_no || '').trim(),
|
||||
runNo: String(response.run_no || '').trim(),
|
||||
createdNew: Boolean(response.created_new),
|
||||
reasonCode: response.reason_code ?? null,
|
||||
badgeCode: decision === 'appended' ? 'just_appended' : 'just_created',
|
||||
recentAppendCount: decision === 'appended' ? Math.max(0, Number(fileCount) || 0) : undefined,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成稳定 submission_id(同一次发送重试用同一 id)。
|
||||
*/
|
||||
export function createShippingSubmissionId(): string {
|
||||
if (typeof globalThis.crypto?.randomUUID === 'function') {
|
||||
return `SUB-${globalThis.crypto.randomUUID()}`;
|
||||
}
|
||||
return `SUB-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成输入区短生命周期 composer_context_id。
|
||||
*/
|
||||
export function createComposerContextId(): string {
|
||||
if (typeof globalThis.crypto?.randomUUID === 'function') {
|
||||
return `CMP-${globalThis.crypto.randomUUID()}`;
|
||||
}
|
||||
return `CMP-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
|
||||
}
|
||||
@@ -1,43 +1,24 @@
|
||||
/**
|
||||
* features/chat/shipping/shippingTurnActions.spec.ts
|
||||
* 用途:验证建批 Chat Turn payload 包含幂等键与会话映射。
|
||||
* 用途:验证决策/冻结等 Chat Turn 映射(不含已下线的 create_batch)。
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { buildShippingCreateBatchFromIntakesTurn, buildShippingCreateBatchTurn, resolveShippingChatTurn } from './shippingTurnActions';
|
||||
import { resolveShippingChatTurn } from './shippingTurnActions';
|
||||
|
||||
describe('shippingTurnActions', () => {
|
||||
it('buildShippingCreateBatchTurn includes idempotency_key in payload', () => {
|
||||
const files = [
|
||||
new File(['notice-a'], 'notice-a.txt', { type: 'text/plain' }),
|
||||
new File(['notice-b'], 'notice-b.txt', { type: 'text/plain' }),
|
||||
];
|
||||
const turn = buildShippingCreateBatchTurn(files, 'conv-001', 'idem-key-001');
|
||||
|
||||
expect(turn.actionType).toBe('shipping.create_batch_from_notices');
|
||||
expect(turn.payload.conversation_id).toBe('conv-001');
|
||||
expect(turn.payload.file_count).toBe(2);
|
||||
expect(turn.payload.idempotency_key).toBe('idem-key-001');
|
||||
expect(turn.files).toEqual(files);
|
||||
});
|
||||
|
||||
it('buildShippingCreateBatchFromIntakesTurn includes selected candidate_nos', () => {
|
||||
const turn = buildShippingCreateBatchFromIntakesTurn(
|
||||
['SNI-001'],
|
||||
'conv-001',
|
||||
'idem-candidate-001',
|
||||
['SNC-001', 'SNC-003'],
|
||||
);
|
||||
|
||||
expect(turn.actionType).toBe('shipping.create_batch_from_intakes');
|
||||
expect(turn.payload.intake_nos).toEqual(['SNI-001']);
|
||||
expect(turn.payload.candidate_nos).toEqual(['SNC-001', 'SNC-003']);
|
||||
});
|
||||
|
||||
it('maps freeze_order only with the version shown to the user', () => {
|
||||
// 关键断言:缺版本不得构造 freeze Turn,避免乐观锁盲写。
|
||||
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 },
|
||||
});
|
||||
});
|
||||
|
||||
it('maps confirm decision to submit_decision', () => {
|
||||
expect(resolveShippingChatTurn('confirm', 'sn-1')).toEqual({
|
||||
actionType: 'shipping.submit_decision',
|
||||
payload: { task_no: 'SN-1', decision: 'confirm' },
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -2,7 +2,8 @@
|
||||
* features/chat/shipping/shippingTurnActions.ts
|
||||
* 用途:将发货通知菜单/决策 action.id 映射为 Chat Turn action_type + payload。
|
||||
* 依赖:constants/shipping。
|
||||
* 逻辑:useChatShippingDecision 与 useChatShippingMenuHandler 调用本模块,不再直调 workspace API 插消息。
|
||||
* 逻辑:useChatShippingDecision 与 useChatShippingMenuHandler 调用本模块,不再直调 workspace API 插消息;
|
||||
* co8 后已移除 create_batch / switch_batch_focus Turn 构造器,上传改走 Intake + order extraction。
|
||||
*/
|
||||
import { SHIPPING_DECISION_ACTIONS } from '../constants/shipping';
|
||||
|
||||
@@ -82,55 +83,6 @@ export function buildShippingSubmitDecisionTurn(
|
||||
},
|
||||
};
|
||||
}
|
||||
/**
|
||||
* 构造发货通知建批 Chat Turn(multipart 上传)。
|
||||
*/
|
||||
export function buildShippingCreateBatchTurn(
|
||||
files: File[],
|
||||
conversationId?: string | null,
|
||||
idempotencyKey?: string,
|
||||
): { actionType: string; displayText: string; payload: Record<string, unknown>; files: File[] } {
|
||||
const count = files.length;
|
||||
const displayText = count === 1
|
||||
? `上传发货通知:${files[0]?.name || '附件'}`
|
||||
: `上传 ${count} 份发货通知`;
|
||||
return {
|
||||
actionType: 'shipping.create_batch_from_notices',
|
||||
displayText,
|
||||
payload: {
|
||||
conversation_id: conversationId || undefined,
|
||||
file_count: count,
|
||||
idempotency_key: idempotencyKey,
|
||||
},
|
||||
files,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 构造发货通知建批 Chat Turn(基于已解析 intake,不再携带 files)。
|
||||
*/
|
||||
export function buildShippingCreateBatchFromIntakesTurn(
|
||||
intakeNos: string[],
|
||||
conversationId?: string | null,
|
||||
idempotencyKey?: string,
|
||||
candidateNos?: string[],
|
||||
): { actionType: string; displayText: string; payload: Record<string, unknown> } {
|
||||
const count = intakeNos.length;
|
||||
const displayText = count === 1
|
||||
? `确认建单:${intakeNos[0]}`
|
||||
: `确认建单:${count} 份发货通知`;
|
||||
return {
|
||||
actionType: 'shipping.create_batch_from_intakes',
|
||||
displayText,
|
||||
payload: {
|
||||
intake_nos: intakeNos,
|
||||
conversation_id: conversationId || undefined,
|
||||
idempotency_key: idempotencyKey,
|
||||
candidate_nos: candidateNos,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 构造货代领域 refs,键名与 agent_runtime_context.refs 对齐。
|
||||
*/
|
||||
@@ -143,6 +95,9 @@ export function buildShippingTurnRefs(taskNo: string, batchNo?: string): Record<
|
||||
return refs;
|
||||
}
|
||||
|
||||
/**
|
||||
* 构造重新上传发货通知 Chat Turn。
|
||||
*/
|
||||
export function buildShippingReplaceNoticeTurn(taskNo: string, file: File) {
|
||||
const task = String(taskNo || '').trim().toUpperCase();
|
||||
return {
|
||||
@@ -154,17 +109,9 @@ export function buildShippingReplaceNoticeTurn(taskNo: string, file: File) {
|
||||
};
|
||||
}
|
||||
|
||||
export function buildShippingSwitchFocusTurn(batchNo: string, taskNo: string, displayText: string) {
|
||||
const batch = String(batchNo || '').trim();
|
||||
const task = String(taskNo || '').trim().toUpperCase();
|
||||
return {
|
||||
actionType: 'shipping.switch_batch_focus',
|
||||
displayText,
|
||||
payload: { batch_no: batch, task_no: task },
|
||||
refs: buildShippingTurnRefs(task, batch),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 构造短缺明细查询 Chat Turn。
|
||||
*/
|
||||
export function buildShippingQueryShortageTurn(taskNo: string, displayText: string) {
|
||||
const task = String(taskNo || '').trim().toUpperCase();
|
||||
return {
|
||||
|
||||
@@ -251,4 +251,17 @@ describe('useChatShippingSendHandler', () => {
|
||||
expect(attachments.value).toEqual([attachment]);
|
||||
expect(ctx.msg.warning).toHaveBeenCalledWith('run create failed');
|
||||
});
|
||||
|
||||
it('warns and consumes send when user tries batch task switching (co8 batch API retired)', async () => {
|
||||
const ctx = createContext({
|
||||
getActiveShippingBatchNo: () => 'SB-TEST',
|
||||
});
|
||||
const { tryHandleShippingSend } = createShippingSendHandlers(ctx);
|
||||
|
||||
const consumed = await tryHandleShippingSend(undefined, '下一票', '下一票');
|
||||
|
||||
expect(consumed).toBe(true);
|
||||
expect(ctx.startChatTurn).not.toHaveBeenCalled();
|
||||
expect(ctx.msg.warning).toHaveBeenCalledWith('chat.shippingNoticeUi.batchSwitchRemoved');
|
||||
});
|
||||
});
|
||||
@@ -1,15 +1,13 @@
|
||||
/**
|
||||
* features/chat/shipping/useChatShippingSendHandler.ts
|
||||
* 用途:在聊天发送前拦截发货通知专属意图,如订单抽取、切票、决策文本和附件自动流程。
|
||||
* 依赖:shipping.api、shippingIntents、shippingMenu、shippingDownload、chat.types。
|
||||
* 逻辑:已预处理 Intake 创建独立订单抽取 Run;其他业务动作经 Chat Turn / handleShippingMenuAction。
|
||||
* 依赖:shipping.api(任务详情)、shippingIntents、shippingMenu、shippingDownload、chat.types。
|
||||
* 逻辑:已预处理 Intake 创建独立订单抽取 Run;co8 后切票不再调用 shipping_batches API,改提示用户使用 processing 工作台。
|
||||
*/
|
||||
import {
|
||||
getWorkspaceShippingBatch,
|
||||
getWorkspaceShippingTask,
|
||||
} from '@/features/chat/api/shipping.api';
|
||||
import { SHIPPING_DECISION_ACTIONS, SHIPPING_MENU_ACTION_SPECS } from '../constants/shipping';
|
||||
import { buildShippingSwitchFocusTurn } from './shippingTurnActions';
|
||||
import { downloadWorkspaceShippingExcelFile } from './shippingDownload';
|
||||
import {
|
||||
isShippingDownloadExcelIntent,
|
||||
@@ -146,58 +144,17 @@ export function createShippingSendHandlers(ctx: ShippingSendHandlerContext) {
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 拦截切票/切任务意图(co8 已下线批次 API)。
|
||||
*
|
||||
* 核心逻辑:识别切换意图后提示用户使用右侧 processing 工作台,消费发送且不发起网络请求。
|
||||
* @param content - 用户输入
|
||||
* @returns 识别到切换意图时恒为 true
|
||||
*/
|
||||
const trySwitchShippingTask = async (content: string): Promise<boolean> => {
|
||||
const intent = parseShippingTaskSwitchIntent(content);
|
||||
if (!intent) return false;
|
||||
const batchNo = ctx.getActiveShippingBatchNo();
|
||||
if (!batchNo) {
|
||||
ctx.msg.warning('当前没有可切换的批次');
|
||||
return true;
|
||||
}
|
||||
try {
|
||||
const detail = await getWorkspaceShippingBatch(batchNo);
|
||||
const tasks = Array.isArray(detail.tasks) ? detail.tasks : [];
|
||||
if (tasks.length <= 1) {
|
||||
ctx.msg.info('当前批次只有 1 票,无需切换');
|
||||
return true;
|
||||
}
|
||||
const focusTaskNo = String(detail.focus_task?.task_no || detail.current_focus_task_no || '').trim().toUpperCase();
|
||||
const currentIndex = Math.max(tasks.findIndex((item) => String(item.task_no || '').trim().toUpperCase() === focusTaskNo), 0);
|
||||
let targetTaskNo = '';
|
||||
if (intent.mode === 'task') {
|
||||
targetTaskNo = String(intent.taskNo || '').trim().toUpperCase();
|
||||
} else if (intent.mode === 'next') {
|
||||
targetTaskNo = String(tasks[Math.min(currentIndex + 1, tasks.length - 1)]?.task_no || '').trim().toUpperCase();
|
||||
} else {
|
||||
targetTaskNo = String(tasks[Math.max(currentIndex - 1, 0)]?.task_no || '').trim().toUpperCase();
|
||||
}
|
||||
if (!targetTaskNo) {
|
||||
ctx.msg.warning('未找到要切换的任务');
|
||||
return true;
|
||||
}
|
||||
if (targetTaskNo === focusTaskNo) {
|
||||
ctx.msg.info(intent.mode === 'next' ? '已经是最后一票' : intent.mode === 'prev' ? '已经是第一票' : '已在当前任务');
|
||||
return true;
|
||||
}
|
||||
ctx.resolvedShippingTaskId.value = targetTaskNo;
|
||||
const turn = buildShippingSwitchFocusTurn(batchNo, targetTaskNo, content.trim());
|
||||
await ctx.startChatTurn({
|
||||
agentId: ctx.currentAgentId.value,
|
||||
inputType: 'action',
|
||||
displayText: turn.displayText,
|
||||
actionType: turn.actionType,
|
||||
payload: turn.payload,
|
||||
refs: turn.refs,
|
||||
hooks: {
|
||||
onAssistantMessageFinished: async () => {
|
||||
void ctx.refreshShippingActions();
|
||||
},
|
||||
},
|
||||
});
|
||||
} catch (e: unknown) {
|
||||
const errorMessage = e instanceof Error ? e.message : '切换任务失败';
|
||||
ctx.msg.warning(errorMessage);
|
||||
}
|
||||
ctx.msg.warning(ctx.t('chat.shippingNoticeUi.batchSwitchRemoved'));
|
||||
return true;
|
||||
};
|
||||
|
||||
@@ -293,10 +250,11 @@ export function createShippingSendHandlers(ctx: ShippingSendHandlerContext) {
|
||||
}
|
||||
if (!(ctx.shippingAutoFlowRequested.value || !trimmed)) return false;
|
||||
if (!trimmed || requestedAutoFlow) {
|
||||
// co8:本地文件改走 Intake 入队,不再清空后打 create_batch Chat Turn。
|
||||
if (typeof textOrEvent !== 'string') ctx.input.value = '';
|
||||
ctx.attachments.value = [];
|
||||
try {
|
||||
await ctx.handleShippingAutoUploadNoticeBatch(localFiles.map((item) => item.file));
|
||||
ctx.attachments.value = ctx.attachments.value.filter((item) => item.kind !== 'local');
|
||||
} catch (e: unknown) {
|
||||
const errorMessage = e instanceof Error ? e.message : '文件处理失败';
|
||||
ctx.msg.warning(errorMessage);
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
* features/chat/shipping/useChatShippingUploadHandler.spec.ts
|
||||
* 用途:验证发货通知上传 handler 在显式 taskId 场景下不会把库存/通知文件错投到当前激活任务。
|
||||
* 依赖:vitest、vue refs、shipping.api、useChatShippingUploadHandler。
|
||||
* 逻辑:覆盖库存/通知 picker 的任务锁定,以及 Chat Turn 建批/覆盖路径。
|
||||
* 逻辑:覆盖库存/通知 picker 的任务锁定、replace_notice Turn,以及 Intake/OT 提交路径。
|
||||
*/
|
||||
import { computed, ref } from 'vue';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
@@ -55,8 +55,10 @@ const createContext = (
|
||||
getActiveShippingTaskId: () => 'SN-ACTIVE-001',
|
||||
startChatTurn: vi.fn(async () => true),
|
||||
refreshShippingActions: vi.fn(async () => undefined),
|
||||
msg: { warning: vi.fn() },
|
||||
msg: { warning: vi.fn(), info: vi.fn() },
|
||||
t: (key: string) => key,
|
||||
enqueueNoticeFiles: vi.fn(async () => undefined),
|
||||
startOrderExtractionRun: vi.fn(async () => true),
|
||||
sendTemporaryInventoryMessage: vi.fn(async () => undefined),
|
||||
...overrides,
|
||||
});
|
||||
@@ -148,33 +150,50 @@ describe('useChatShippingUploadHandler', () => {
|
||||
expect(ctx.pendingShippingNoticeTaskId.value).toBe('');
|
||||
});
|
||||
|
||||
it('creates notice batch via Chat Turn instead of local assistant push', async () => {
|
||||
it('enqueues notice files as intakes instead of create_batch Chat Turn', async () => {
|
||||
const enqueueNoticeFiles = vi.fn(async () => undefined);
|
||||
const ctx = createContext({
|
||||
getActiveShippingTaskId: () => '',
|
||||
enqueueNoticeFiles,
|
||||
});
|
||||
const { handleShippingAutoUploadNoticeBatch } = createShippingUploadHandlers(ctx);
|
||||
const file = new File(['notice'], 'notice.pdf', { type: 'application/pdf' });
|
||||
|
||||
await handleShippingAutoUploadNoticeBatch([file]);
|
||||
|
||||
expect(ctx.startChatTurn).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
inputType: 'upload_followup',
|
||||
actionType: 'shipping.create_batch_from_notices',
|
||||
displayText: expect.stringContaining('notice.pdf'),
|
||||
files: [file],
|
||||
}),
|
||||
);
|
||||
expect(enqueueNoticeFiles).toHaveBeenCalledWith([file]);
|
||||
expect(ctx.startChatTurn).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('double click only calls startChatTurn once and keeps stable idempotency key', async () => {
|
||||
const startChatTurn = vi.fn(async () => {
|
||||
it('submits parsed intakes via order extraction instead of create_batch_from_intakes', async () => {
|
||||
const startOrderExtractionRun = vi.fn(async () => true);
|
||||
const clearConsumedNoticeAttachments = vi.fn();
|
||||
const ctx = createContext({
|
||||
getActiveShippingTaskId: () => '',
|
||||
getParsedIntakeNos: () => ['SNI-1'],
|
||||
startOrderExtractionRun,
|
||||
clearConsumedNoticeAttachments,
|
||||
});
|
||||
const { handleShippingAutoUploadNoticeBatch } = createShippingUploadHandlers(ctx);
|
||||
|
||||
await handleShippingAutoUploadNoticeBatch([]);
|
||||
|
||||
expect(startOrderExtractionRun).toHaveBeenCalledWith(
|
||||
'chat.shippingOrderExtractionDefaultUserMessage',
|
||||
['SNI-1'],
|
||||
[],
|
||||
);
|
||||
expect(clearConsumedNoticeAttachments).toHaveBeenCalled();
|
||||
expect(ctx.startChatTurn).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('double click only enqueues notice files once', async () => {
|
||||
const enqueueNoticeFiles = vi.fn(async () => {
|
||||
await new Promise((resolve) => setTimeout(resolve, 20));
|
||||
return true;
|
||||
});
|
||||
const ctx = createContext({
|
||||
getActiveShippingTaskId: () => '',
|
||||
startChatTurn,
|
||||
enqueueNoticeFiles,
|
||||
});
|
||||
const { handleShippingAutoUploadNoticeBatch } = createShippingUploadHandlers(ctx);
|
||||
const file = new File(['notice'], 'notice.pdf', { type: 'application/pdf' });
|
||||
@@ -183,168 +202,30 @@ describe('useChatShippingUploadHandler', () => {
|
||||
const second = handleShippingAutoUploadNoticeBatch([file]);
|
||||
await Promise.all([first, second]);
|
||||
|
||||
expect(startChatTurn).toHaveBeenCalledTimes(1);
|
||||
const payload = (startChatTurn.mock.calls[0]?.[0] as { payload?: Record<string, unknown> })?.payload;
|
||||
expect(payload?.idempotency_key).toBeTruthy();
|
||||
expect(enqueueNoticeFiles).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('reuses idempotency key on retry and generates new key after success', async () => {
|
||||
let attempt = 0;
|
||||
const startChatTurn = vi.fn(async () => {
|
||||
attempt += 1;
|
||||
return attempt >= 2;
|
||||
it('releases submit lock when enqueueNoticeFiles fails', async () => {
|
||||
const enqueueNoticeFiles = vi.fn(async () => {
|
||||
throw new Error('enqueue failed');
|
||||
});
|
||||
const ctx = createContext({
|
||||
getActiveShippingTaskId: () => '',
|
||||
startChatTurn,
|
||||
});
|
||||
const { handleShippingAutoUploadNoticeBatch } = createShippingUploadHandlers(ctx);
|
||||
const file = new File(['notice'], 'notice.pdf', { type: 'application/pdf' });
|
||||
|
||||
await handleShippingAutoUploadNoticeBatch([file]);
|
||||
const firstKey = (startChatTurn.mock.calls[0]?.[0] as { payload?: Record<string, unknown> })?.payload?.idempotency_key;
|
||||
await handleShippingAutoUploadNoticeBatch([file]);
|
||||
const secondKey = (startChatTurn.mock.calls[1]?.[0] as { payload?: Record<string, unknown> })?.payload?.idempotency_key;
|
||||
await handleShippingAutoUploadNoticeBatch([file]);
|
||||
const thirdKey = (startChatTurn.mock.calls[2]?.[0] as { payload?: Record<string, unknown> })?.payload?.idempotency_key;
|
||||
|
||||
expect(firstKey).toBe(secondKey);
|
||||
expect(thirdKey).not.toBe(secondKey);
|
||||
});
|
||||
|
||||
it('generates new idempotency key when files change after a failed attempt', async () => {
|
||||
const startChatTurn = vi.fn(async () => false);
|
||||
const ctx = createContext({
|
||||
getActiveShippingTaskId: () => '',
|
||||
startChatTurn,
|
||||
});
|
||||
const { handleShippingAutoUploadNoticeBatch } = createShippingUploadHandlers(ctx);
|
||||
const firstFile = new File(['notice-a'], 'notice-a.pdf', { type: 'application/pdf' });
|
||||
const secondFile = new File(['notice-b'], 'notice-b.pdf', { type: 'application/pdf' });
|
||||
|
||||
await handleShippingAutoUploadNoticeBatch([firstFile]);
|
||||
const firstKey = (startChatTurn.mock.calls[0]?.[0] as { payload?: Record<string, unknown> })?.payload?.idempotency_key;
|
||||
await handleShippingAutoUploadNoticeBatch([secondFile]);
|
||||
const secondKey = (startChatTurn.mock.calls[1]?.[0] as { payload?: Record<string, unknown> })?.payload?.idempotency_key;
|
||||
|
||||
expect(firstKey).toBeTruthy();
|
||||
expect(secondKey).toBeTruthy();
|
||||
expect(secondKey).not.toBe(firstKey);
|
||||
});
|
||||
|
||||
it('reuses idempotency key when conversation upgrades from empty to server-assigned after network failure', async () => {
|
||||
const conversationId = ref<string | null>(null);
|
||||
const startChatTurn = vi.fn(async () => {
|
||||
conversationId.value = 'conv-server-new';
|
||||
return false;
|
||||
});
|
||||
const ctx = createContext({
|
||||
conversationId,
|
||||
getActiveShippingTaskId: () => '',
|
||||
startChatTurn,
|
||||
});
|
||||
const { handleShippingAutoUploadNoticeBatch } = createShippingUploadHandlers(ctx);
|
||||
const file = new File(['notice'], 'notice.pdf', { type: 'application/pdf' });
|
||||
|
||||
await handleShippingAutoUploadNoticeBatch([file]);
|
||||
const firstKey = (startChatTurn.mock.calls[0]?.[0] as { payload?: Record<string, unknown> })?.payload?.idempotency_key;
|
||||
|
||||
await handleShippingAutoUploadNoticeBatch([file]);
|
||||
const secondKey = (startChatTurn.mock.calls[1]?.[0] as { payload?: Record<string, unknown> })?.payload?.idempotency_key;
|
||||
|
||||
expect(firstKey).toBeTruthy();
|
||||
expect(secondKey).toBe(firstKey);
|
||||
});
|
||||
|
||||
it('generates new idempotency key when switching from new chat to historical session', async () => {
|
||||
const startChatTurn = vi.fn(async () => false);
|
||||
const conversationId = ref<string | null>(null);
|
||||
const ctx = createContext({
|
||||
conversationId,
|
||||
getActiveShippingTaskId: () => '',
|
||||
startChatTurn,
|
||||
});
|
||||
const { handleShippingAutoUploadNoticeBatch } = createShippingUploadHandlers(ctx);
|
||||
const file = new File(['notice'], 'notice.pdf', { type: 'application/pdf' });
|
||||
|
||||
await handleShippingAutoUploadNoticeBatch([file]);
|
||||
const firstKey = (startChatTurn.mock.calls[0]?.[0] as { payload?: Record<string, unknown> })?.payload?.idempotency_key;
|
||||
|
||||
onNoticeBatchConversationChanging('conv-history', '');
|
||||
conversationId.value = 'conv-history';
|
||||
await handleShippingAutoUploadNoticeBatch([file]);
|
||||
const secondKey = (startChatTurn.mock.calls[1]?.[0] as { payload?: Record<string, unknown> })?.payload?.idempotency_key;
|
||||
|
||||
expect(firstKey).toBeTruthy();
|
||||
expect(secondKey).toBeTruthy();
|
||||
expect(secondKey).not.toBe(firstKey);
|
||||
});
|
||||
|
||||
it('generates new idempotency key after explicit clearPendingNoticeBatchRetry', async () => {
|
||||
const startChatTurn = vi.fn(async () => false);
|
||||
const conversationId = ref('conv-a');
|
||||
const ctx = createContext({
|
||||
conversationId,
|
||||
getActiveShippingTaskId: () => '',
|
||||
startChatTurn,
|
||||
});
|
||||
const { handleShippingAutoUploadNoticeBatch } = createShippingUploadHandlers(ctx);
|
||||
const file = new File(['notice'], 'notice.pdf', { type: 'application/pdf' });
|
||||
|
||||
await handleShippingAutoUploadNoticeBatch([file]);
|
||||
const firstKey = (startChatTurn.mock.calls[0]?.[0] as { payload?: Record<string, unknown> })?.payload?.idempotency_key;
|
||||
|
||||
clearPendingNoticeBatchRetry();
|
||||
conversationId.value = null;
|
||||
await handleShippingAutoUploadNoticeBatch([file]);
|
||||
const secondKey = (startChatTurn.mock.calls[1]?.[0] as { payload?: Record<string, unknown> })?.payload?.idempotency_key;
|
||||
|
||||
expect(firstKey).toBeTruthy();
|
||||
expect(secondKey).toBeTruthy();
|
||||
expect(secondKey).not.toBe(firstKey);
|
||||
});
|
||||
|
||||
it('generates new idempotency key when conversation changes after a failed attempt', async () => {
|
||||
const startChatTurn = vi.fn(async () => false);
|
||||
const conversationId = ref('conv-a');
|
||||
const ctx = createContext({
|
||||
conversationId,
|
||||
getActiveShippingTaskId: () => '',
|
||||
startChatTurn,
|
||||
});
|
||||
const { handleShippingAutoUploadNoticeBatch } = createShippingUploadHandlers(ctx);
|
||||
const file = new File(['notice'], 'notice.pdf', { type: 'application/pdf' });
|
||||
|
||||
await handleShippingAutoUploadNoticeBatch([file]);
|
||||
const firstKey = (startChatTurn.mock.calls[0]?.[0] as { payload?: Record<string, unknown> })?.payload?.idempotency_key;
|
||||
|
||||
onNoticeBatchConversationChanging('conv-b', 'conv-a');
|
||||
conversationId.value = 'conv-b';
|
||||
await handleShippingAutoUploadNoticeBatch([file]);
|
||||
const secondKey = (startChatTurn.mock.calls[1]?.[0] as { payload?: Record<string, unknown> })?.payload?.idempotency_key;
|
||||
|
||||
expect(firstKey).toBeTruthy();
|
||||
expect(secondKey).toBeTruthy();
|
||||
expect(secondKey).not.toBe(firstKey);
|
||||
});
|
||||
|
||||
it('releases submit lock when fingerprint computation fails', async () => {
|
||||
computeNoticeFilesContentFingerprint.mockRejectedValueOnce(new Error('digest failed'));
|
||||
const startChatTurn = vi.fn(async () => true);
|
||||
const ctx = createContext({
|
||||
getActiveShippingTaskId: () => '',
|
||||
startChatTurn,
|
||||
enqueueNoticeFiles,
|
||||
});
|
||||
const { handleShippingAutoUploadNoticeBatch, isShippingNoticeBatchSubmitting } = createShippingUploadHandlers(ctx);
|
||||
const file = new File(['notice'], 'notice.pdf', { type: 'application/pdf' });
|
||||
|
||||
await expect(handleShippingAutoUploadNoticeBatch([file])).rejects.toThrow('digest failed');
|
||||
expect(startChatTurn).not.toHaveBeenCalled();
|
||||
expect(isShippingNoticeBatchSubmitting()).toBe(false);
|
||||
|
||||
computeNoticeFilesContentFingerprint.mockResolvedValueOnce('fp-notice');
|
||||
await handleShippingAutoUploadNoticeBatch([file]);
|
||||
expect(startChatTurn).toHaveBeenCalledTimes(1);
|
||||
expect(ctx.startChatTurn).not.toHaveBeenCalled();
|
||||
expect(isShippingNoticeBatchSubmitting()).toBe(false);
|
||||
expect(ctx.msg.warning).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('compatibility hooks for pending batch retry remain callable after co8', () => {
|
||||
clearPendingNoticeBatchRetry();
|
||||
onNoticeBatchConversationChanging('conv-b', 'conv-a');
|
||||
expect(true).toBe(true);
|
||||
});
|
||||
|
||||
it('does not open notice picker when both explicit taskId and active task are missing', () => {
|
||||
|
||||
@@ -1,83 +1,39 @@
|
||||
/**
|
||||
* features/chat/shipping/useChatShippingUploadHandler.ts
|
||||
* 用途:处理发货通知与库存文件上传、批量建单和附件建议提示。
|
||||
* 用途:处理发货通知与库存文件上传、订单抽取提交和附件建议提示。
|
||||
* 依赖:shipping.api、file-assets.api、shippingUploadPrompt、shipping 常量、chat.types。
|
||||
* 逻辑:发货通知建批和单票覆盖经 Chat Turn;对话上传库存文件先成为私有临时资产,再进入 Dify 受控分析分支。
|
||||
* 逻辑:co8 后不再走 shipping_batches Chat Turn;新通知经 enqueueNoticeFiles / startOrderExtractionRun;
|
||||
* 单票覆盖仍经 replace_notice Turn;库存文件先成为私有临时资产再进 Dify 分析分支。
|
||||
*/
|
||||
import { computed } from 'vue';
|
||||
import type { ShippingTaskSummary } from '@/features/chat/api/shipping.api';
|
||||
import { uploadFileAsset } from '@/shared/api/file-assets.api';
|
||||
import { extractExt } from '../constants/shipping';
|
||||
import { buildShippingCreateBatchTurn, buildShippingCreateBatchFromIntakesTurn, buildShippingReplaceNoticeTurn, buildShippingTurnRefs } from './shippingTurnActions';
|
||||
import { computeNoticeFilesContentFingerprint, computeNoticeIntakeNosFingerprint } from './shippingNoticeBatchIdempotency';
|
||||
import { buildShippingReplaceNoticeTurn, buildShippingTurnRefs } from './shippingTurnActions';
|
||||
import type { StartChatTurnOptions } from '../types/chat-turn.types';
|
||||
import type { ChatMessage } from '../types/chat.types';
|
||||
import type { ChatMessage, ChatMessageAttachment } from '../types/chat.types';
|
||||
import type { PendingAttachment } from '../types/shipping.types';
|
||||
import type { ComputedRef, Ref } from 'vue';
|
||||
|
||||
let noticeBatchSubmitting = false;
|
||||
|
||||
interface PendingNoticeBatchRetryState {
|
||||
conversationId: string;
|
||||
idempotencyKey: string;
|
||||
fileFingerprint: string;
|
||||
}
|
||||
|
||||
let pendingNoticeBatchRetry: PendingNoticeBatchRetryState | null = null;
|
||||
|
||||
function normalizeConversationId(conversationId: string | null | undefined): string {
|
||||
return String(conversationId || '').trim();
|
||||
}
|
||||
|
||||
function clearPendingNoticeBatchRetryState(): void {
|
||||
pendingNoticeBatchRetry = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 显式清理待重试建批幂等状态(新建聊天、切换 Agent 等不经 onConversationIdChanging 的路径)。
|
||||
* 显式清理待重试建批幂等状态(co8 后建批已下线,保留空实现供会话切换调用方兼容)。
|
||||
*/
|
||||
export function clearPendingNoticeBatchRetry(): void {
|
||||
clearPendingNoticeBatchRetryState();
|
||||
/* no-op: shipping_batches 已 DROP */
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断待重试状态是否应绑定到当前会话。
|
||||
* 核心逻辑:允许「尚未分配会话」升级绑定服务端新 ID;两个非空且不同、或旧非空而新为空时清理。
|
||||
*/
|
||||
function reconcilePendingNoticeBatchConversation(
|
||||
pending: PendingNoticeBatchRetryState,
|
||||
conversationKey: string,
|
||||
): void {
|
||||
const pendingKey = pending.conversationId;
|
||||
if (pendingKey === conversationKey) {
|
||||
return;
|
||||
}
|
||||
if (!pendingKey && conversationKey) {
|
||||
pending.conversationId = conversationKey;
|
||||
return;
|
||||
}
|
||||
if (pendingKey && !conversationKey) {
|
||||
clearPendingNoticeBatchRetryState();
|
||||
return;
|
||||
}
|
||||
if (pendingKey && conversationKey && pendingKey !== conversationKey) {
|
||||
clearPendingNoticeBatchRetryState();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 用户主动切换会话时清理待重试建批状态,避免跨会话复用幂等键。
|
||||
* 仅由 onConversationIdChanging 调用;SSE 自动分配 conversation_id 不经过此函数。
|
||||
* 用户主动切换会话时的钩子(co8 后无幂等键可清)。
|
||||
* @param _nextId - 新会话 ID
|
||||
* @param _prevId - 旧会话 ID
|
||||
*/
|
||||
export function onNoticeBatchConversationChanging(
|
||||
nextId: string,
|
||||
prevId?: string | null,
|
||||
_nextId: string,
|
||||
_prevId?: string | null,
|
||||
): void {
|
||||
const next = normalizeConversationId(nextId);
|
||||
const prev = normalizeConversationId(prevId);
|
||||
if (next !== prev) {
|
||||
clearPendingNoticeBatchRetryState();
|
||||
}
|
||||
/* no-op */
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -113,11 +69,20 @@ export interface ShippingUploadHandlerContext {
|
||||
getActiveShippingTaskId: () => string;
|
||||
startChatTurn: (options: StartChatTurnOptions) => Promise<boolean>;
|
||||
refreshShippingActions: () => Promise<void>;
|
||||
msg: { warning: (text: string) => void };
|
||||
msg: { warning: (text: string) => void; info?: (text: string) => void };
|
||||
t: (key: string, params?: Record<string, unknown>) => string;
|
||||
getParsedIntakeNos?: () => string[];
|
||||
getSelectedCandidateNos?: () => string[];
|
||||
clearConsumedNoticeAttachments?: () => void;
|
||||
/** 将本地文件加入输入栏并创建 Intake(替代旧 create_batch_from_notices)。 */
|
||||
enqueueNoticeFiles?: (files: File[]) => Promise<void>;
|
||||
/** 对已解析 Intake 发起订单抽取提交。 */
|
||||
startOrderExtractionRun?: (
|
||||
query: string,
|
||||
intakeNos: string[],
|
||||
attachments: ChatMessageAttachment[],
|
||||
uploadBatchId?: string,
|
||||
) => Promise<boolean>;
|
||||
sendTemporaryInventoryMessage: (assetNo: string, fileName: string) => Promise<unknown>;
|
||||
}
|
||||
|
||||
@@ -202,56 +167,28 @@ export function createShippingUploadHandlers(ctx: ShippingUploadHandlerContext)
|
||||
if (taskId) ctx.resolvedShippingTaskId.value = taskId;
|
||||
};
|
||||
|
||||
/**
|
||||
* 将本地通知文件加入输入栏并创建 Intake(不再走 shipping_batches Chat Turn)。
|
||||
* @param files - 用户选择的发货通知文件
|
||||
* @returns 是否完成入队
|
||||
*/
|
||||
const runNoticeBatchChatTurn = async (files: File[]) => {
|
||||
if (noticeBatchSubmitting) {
|
||||
return true;
|
||||
}
|
||||
noticeBatchSubmitting = true;
|
||||
try {
|
||||
const conversationKey = normalizeConversationId(ctx.conversationId.value);
|
||||
const fileFingerprint = await computeNoticeFilesContentFingerprint(files);
|
||||
if (pendingNoticeBatchRetry) {
|
||||
reconcilePendingNoticeBatchConversation(pendingNoticeBatchRetry, conversationKey);
|
||||
}
|
||||
if (
|
||||
pendingNoticeBatchRetry
|
||||
&& pendingNoticeBatchRetry.fileFingerprint !== fileFingerprint
|
||||
) {
|
||||
clearPendingNoticeBatchRetryState();
|
||||
}
|
||||
if (!pendingNoticeBatchRetry) {
|
||||
pendingNoticeBatchRetry = {
|
||||
conversationId: conversationKey,
|
||||
idempotencyKey: crypto.randomUUID(),
|
||||
fileFingerprint,
|
||||
};
|
||||
} else {
|
||||
pendingNoticeBatchRetry.fileFingerprint = fileFingerprint;
|
||||
}
|
||||
const idempotencyKey = pendingNoticeBatchRetry.idempotencyKey;
|
||||
const turn = buildShippingCreateBatchTurn(files, ctx.conversationId.value, idempotencyKey);
|
||||
const ok = await ctx.startChatTurn({
|
||||
agentId: ctx.currentAgentId.value,
|
||||
inputType: 'upload_followup',
|
||||
displayText: turn.displayText,
|
||||
actionType: turn.actionType,
|
||||
payload: turn.payload,
|
||||
files: turn.files,
|
||||
hooks: {
|
||||
onAssistantMessageFinished: async (assistantMsg) => {
|
||||
syncBatchContextFromTurnMessage(assistantMsg);
|
||||
void ctx.refreshShippingActions();
|
||||
},
|
||||
},
|
||||
});
|
||||
if (ok) {
|
||||
if (pendingNoticeBatchRetry?.conversationId === conversationKey) {
|
||||
clearPendingNoticeBatchRetryState();
|
||||
}
|
||||
} else {
|
||||
if (!ctx.enqueueNoticeFiles) {
|
||||
ctx.msg.warning(ctx.t('chat.shippingNoticeUploadFailed'));
|
||||
return false;
|
||||
}
|
||||
return ok;
|
||||
await ctx.enqueueNoticeFiles(files);
|
||||
ctx.msg.info?.(ctx.t('chat.shippingNoticeWaitingForParse'));
|
||||
void ctx.refreshShippingActions();
|
||||
return true;
|
||||
} catch {
|
||||
ctx.msg.warning(ctx.t('chat.shippingNoticeUploadFailed'));
|
||||
return false;
|
||||
} finally {
|
||||
noticeBatchSubmitting = false;
|
||||
}
|
||||
@@ -278,61 +215,34 @@ export function createShippingUploadHandlers(ctx: ShippingUploadHandlerContext)
|
||||
return ok;
|
||||
};
|
||||
|
||||
const runNoticeBatchFromIntakes = async (intakeNos: string[], candidateNos: string[]) => {
|
||||
/**
|
||||
* 对已解析 Intake 发起订单抽取提交(替代 create_batch_from_intakes)。
|
||||
* @param intakeNos - 已解析 Intake 编号
|
||||
* @param _candidateNos - 保留签名;候选选择由提交服务侧裁决
|
||||
* @returns 是否提交成功
|
||||
*/
|
||||
const runNoticeBatchFromIntakes = async (intakeNos: string[], _candidateNos: string[]) => {
|
||||
if (noticeBatchSubmitting) {
|
||||
return true;
|
||||
}
|
||||
noticeBatchSubmitting = true;
|
||||
try {
|
||||
const conversationKey = normalizeConversationId(ctx.conversationId.value);
|
||||
const intakeFingerprint = computeNoticeIntakeNosFingerprint([...intakeNos, ...candidateNos]);
|
||||
if (pendingNoticeBatchRetry) {
|
||||
reconcilePendingNoticeBatchConversation(pendingNoticeBatchRetry, conversationKey);
|
||||
if (!ctx.startOrderExtractionRun) {
|
||||
ctx.msg.warning(ctx.t('chat.shippingNoticeUploadFailed'));
|
||||
return false;
|
||||
}
|
||||
if (
|
||||
pendingNoticeBatchRetry
|
||||
&& pendingNoticeBatchRetry.fileFingerprint !== intakeFingerprint
|
||||
) {
|
||||
clearPendingNoticeBatchRetryState();
|
||||
}
|
||||
if (!pendingNoticeBatchRetry) {
|
||||
pendingNoticeBatchRetry = {
|
||||
conversationId: conversationKey,
|
||||
idempotencyKey: crypto.randomUUID(),
|
||||
fileFingerprint: intakeFingerprint,
|
||||
};
|
||||
} else {
|
||||
pendingNoticeBatchRetry.fileFingerprint = intakeFingerprint;
|
||||
}
|
||||
const idempotencyKey = pendingNoticeBatchRetry.idempotencyKey;
|
||||
const turn = buildShippingCreateBatchFromIntakesTurn(
|
||||
intakeNos,
|
||||
ctx.conversationId.value,
|
||||
idempotencyKey,
|
||||
candidateNos,
|
||||
);
|
||||
const ok = await ctx.startChatTurn({
|
||||
agentId: ctx.currentAgentId.value,
|
||||
inputType: 'upload_followup',
|
||||
displayText: turn.displayText,
|
||||
actionType: turn.actionType,
|
||||
payload: turn.payload,
|
||||
hooks: {
|
||||
onAssistantMessageFinished: async (assistantMsg) => {
|
||||
syncBatchContextFromTurnMessage(assistantMsg);
|
||||
void ctx.refreshShippingActions();
|
||||
},
|
||||
},
|
||||
});
|
||||
const query = ctx.input.value.trim() || ctx.t('chat.shippingOrderExtractionDefaultUserMessage');
|
||||
const ok = await ctx.startOrderExtractionRun(query, intakeNos, []);
|
||||
if (ok) {
|
||||
if (pendingNoticeBatchRetry?.conversationId === conversationKey) {
|
||||
clearPendingNoticeBatchRetryState();
|
||||
}
|
||||
ctx.clearConsumedNoticeAttachments?.();
|
||||
void ctx.refreshShippingActions();
|
||||
} else {
|
||||
ctx.msg.warning(ctx.t('chat.shippingNoticeUploadFailed'));
|
||||
}
|
||||
return ok;
|
||||
} catch {
|
||||
ctx.msg.warning(ctx.t('chat.shippingNoticeUploadFailed'));
|
||||
return false;
|
||||
} finally {
|
||||
noticeBatchSubmitting = false;
|
||||
}
|
||||
|
||||
Loaded 100 of 571 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user