!11 feat(shipping-notice): 实现滚动履约功能,优化发货通知流程与代码清理
Merge pull request !11 from 曹惠鹏/hugo-shipping-notice
This commit is contained in:
402 files changed
+23045
-20484
No files matched your search
@@ -66,8 +66,6 @@ const ShippingAuditCenterPage = () =>
|
||||
import("@/features/admin/modules/shipping-audit/ShippingAuditCenterPage.vue");
|
||||
const ShippingProcessGateDiagnosticsPage = () =>
|
||||
import("@/features/admin/modules/shipping-process-gates/ShippingProcessGateDiagnosticsPage.vue");
|
||||
const ShippingLegacyStpJobsPage = () =>
|
||||
import("@/features/admin/modules/shipping-legacy-stp-jobs/ShippingLegacyStpJobsPage.vue");
|
||||
const ShippingOrderDocumentProfilesPage = () =>
|
||||
import("@/features/admin/modules/shipping-order-document-profiles/ShippingOrderDocumentProfilesPage.vue");
|
||||
const OrderProfileVersionDetailPage = () =>
|
||||
@@ -227,12 +225,6 @@ export const adminRoutes: RouteRecordRaw[] = [
|
||||
component: ShippingProcessGateDiagnosticsPage,
|
||||
meta: { requiresAdmin: true, adminModule: "shipping_inventory", adminSubModule: 'process_gates', title: "门禁诊断" },
|
||||
},
|
||||
{
|
||||
path: "shipping-legacy-stp-jobs",
|
||||
name: "AdminShippingLegacyStpJobs",
|
||||
component: ShippingLegacyStpJobsPage,
|
||||
meta: { requiresAdmin: true, adminModule: "shipping_inventory", adminSubModule: 'legacy_stp_jobs', title: "历史 STP Job" },
|
||||
},
|
||||
{
|
||||
path: "shipping-order-document-profiles",
|
||||
name: "AdminShippingOrderDocumentProfiles",
|
||||
|
||||
@@ -10,17 +10,4 @@ export const chatRoutes: RouteRecordRaw[] = [
|
||||
name: 'Chat',
|
||||
component: () => import('@/features/chat/views/ChatView.vue'),
|
||||
},
|
||||
{
|
||||
path: '/chat/:agentId/shipping-order-review/:runNo',
|
||||
name: 'ShippingOrderReviewLegacy',
|
||||
redirect: (to) => ({
|
||||
name: 'Chat',
|
||||
params: { agentId: to.params.agentId },
|
||||
query: {
|
||||
...to.query,
|
||||
mode: 'order-review',
|
||||
run_no: String(to.params.runNo || ''),
|
||||
},
|
||||
}),
|
||||
},
|
||||
];
|
||||
@@ -1,131 +0,0 @@
|
||||
/**
|
||||
* features/admin/api/shipping-legacy-stp-jobs.api.ts
|
||||
* 用途:Phase 5-1 —— 管理员历史 STP Job(928/929 面板)HTTP API 客户端。
|
||||
* 依赖:requestJson / getAuthHeaders(shared/api/client & shared/utils/auth)。
|
||||
* 逻辑:GET list / GET detail;后端 URL 为 /api/admin/shipping-notice/legacy-stp-jobs。
|
||||
*/
|
||||
import { getAuthHeaders } from '@/shared/utils/auth';
|
||||
import { requestJson } from '@/shared/api/client';
|
||||
import type { PaginatedResult } from '@/shared/types/pagination.types';
|
||||
|
||||
const auth = () => ({ headers: getAuthHeaders() });
|
||||
|
||||
export type LegacyStpJobRow = {
|
||||
job_id: number;
|
||||
domain: string;
|
||||
job_type: string;
|
||||
status: 'failed' | 'dead' | string;
|
||||
business_ref: string | null;
|
||||
reference_key: string | null;
|
||||
case_no: string | null;
|
||||
priority: number;
|
||||
attempts: number;
|
||||
max_attempts: number;
|
||||
message: string | null;
|
||||
error_message: string | null;
|
||||
error_code: string | null;
|
||||
blocking_reason: string | null;
|
||||
retryable: boolean | null;
|
||||
next_action: string | string[] | null;
|
||||
retry_of_job_id: number | null;
|
||||
created_by_id: number | null;
|
||||
result_json_masked: Record<string, unknown> | null;
|
||||
payload_json_masked: Record<string, unknown> | null;
|
||||
created_at: string | null;
|
||||
updated_at: string | null;
|
||||
started_at: string | null;
|
||||
finished_at: string | null;
|
||||
};
|
||||
|
||||
export type LegacyStpJobCaseBacklink = {
|
||||
case_id: number;
|
||||
case_no: string;
|
||||
status: string;
|
||||
candidate_id: number | null;
|
||||
confirmed_task_id: number | null;
|
||||
document_id: number | null;
|
||||
owner_user_id: number | null;
|
||||
created_at: string | null;
|
||||
updated_at: string | null;
|
||||
};
|
||||
|
||||
export type LegacyStpJobReplayPlan = {
|
||||
supported: boolean;
|
||||
recommended_user_action: 'force_create' | 'create_revision' | string;
|
||||
needs_replay_mode: boolean;
|
||||
reconcile_and_progress_endpoint: string | null;
|
||||
};
|
||||
|
||||
export type LegacyStpJobDetailPayload = {
|
||||
job: LegacyStpJobRow;
|
||||
case: LegacyStpJobCaseBacklink | null;
|
||||
replay_plan: LegacyStpJobReplayPlan;
|
||||
};
|
||||
|
||||
export type LegacyStpJobListFilters = {
|
||||
status?: '' | 'failed' | 'dead';
|
||||
job_type?: string;
|
||||
q?: string;
|
||||
case_no?: string;
|
||||
error_code?: string;
|
||||
blocking_reason?: string;
|
||||
created_from?: string;
|
||||
created_to?: string;
|
||||
sort?: string;
|
||||
};
|
||||
|
||||
const EMPTY_FILTERS: Required<LegacyStpJobListFilters> = {
|
||||
status: '',
|
||||
job_type: '',
|
||||
q: '',
|
||||
case_no: '',
|
||||
error_code: '',
|
||||
blocking_reason: '',
|
||||
created_from: '',
|
||||
created_to: '',
|
||||
sort: '-created_at',
|
||||
};
|
||||
|
||||
export const DEFAULT_LEGACY_STP_JOB_FILTERS = EMPTY_FILTERS;
|
||||
|
||||
export const LEGACY_STP_JOB_STATUS_OPTIONS = ['failed', 'dead'] as const;
|
||||
|
||||
function normalizeDateTimeFilter(value?: string): string {
|
||||
const raw = String(value || '').trim();
|
||||
if (!raw) return '';
|
||||
const date = new Date(raw);
|
||||
if (Number.isNaN(date.getTime())) return raw;
|
||||
return date.toISOString();
|
||||
}
|
||||
|
||||
function buildListSearchParams(filters: LegacyStpJobListFilters, page: number, pageSize: number): URLSearchParams {
|
||||
const params = new URLSearchParams({
|
||||
page: String(page),
|
||||
page_size: String(pageSize),
|
||||
});
|
||||
if (filters.status) params.set('status', filters.status);
|
||||
if (filters.job_type) params.set('job_type', filters.job_type);
|
||||
if (filters.q) params.set('q', filters.q);
|
||||
if (filters.case_no) params.set('case_no', filters.case_no);
|
||||
if (filters.error_code) params.set('error_code', filters.error_code);
|
||||
if (filters.blocking_reason) params.set('blocking_reason', filters.blocking_reason);
|
||||
if (filters.created_from) params.set('created_from', normalizeDateTimeFilter(filters.created_from));
|
||||
if (filters.created_to) params.set('created_to', normalizeDateTimeFilter(filters.created_to));
|
||||
if (filters.sort) params.set('sort', filters.sort);
|
||||
return params;
|
||||
}
|
||||
|
||||
export function listAdminLegacyStpJobs(
|
||||
page = 1,
|
||||
pageSize = 25,
|
||||
filters: LegacyStpJobListFilters = {},
|
||||
): Promise<PaginatedResult<LegacyStpJobRow> & {
|
||||
filters: { domain: string; job_types: string[]; statuses: string[] };
|
||||
}> {
|
||||
const params = buildListSearchParams(filters, page, pageSize);
|
||||
return requestJson(`/api/admin/shipping-notice/legacy-stp-jobs?${params}`, auth());
|
||||
}
|
||||
|
||||
export function getAdminLegacyStpJob(jobId: number): Promise<LegacyStpJobDetailPayload> {
|
||||
return requestJson(`/api/admin/shipping-notice/legacy-stp-jobs/${encodeURIComponent(String(jobId))}`, auth());
|
||||
}
|
||||
@@ -77,6 +77,9 @@ export const getOrderDocumentProfileDetail = (profileId: number) =>
|
||||
export const saveOrderDocumentProfileDraft = (profileId: number, payload: {
|
||||
profile_code: string; display_name: string; schema_version_id: number;
|
||||
definition: ShippingOrderDocumentProfile['definition']; change_note?: string;
|
||||
/** 标注样本文档及其冻结视觉主表;二者必须与 definition.main_table_id 保持一致。 */
|
||||
sample_document_id?: number;
|
||||
sample_table_id?: string;
|
||||
expected_lock_version: number; browser_session_id: string; lease_token: string; operation_id: string;
|
||||
/** path_id → 服务端签发的拆分预览确认令牌;confirmed 规则必须携带 */
|
||||
split_rule_confirmation_tokens?: Record<string, string>;
|
||||
@@ -583,9 +586,12 @@ export const getOrderProfilePageTextCandidates = (profileId: number, documentId:
|
||||
/** 读取当前受控样本中框选区域的坐标文本;仅用于画布生成文档匹配锚点。 */
|
||||
export const readOrderProfilePreviewPageRegionText = (
|
||||
profileId: number, documentId: number, pageNo: number, region: { x0: number; y0: number; x1: number; y1: number },
|
||||
) => requestJson<{ document_id: number; page_no: number; text: string; source: string | null; status: 'needs_review' }>(
|
||||
`/api/admin/shipping-notice/order-document-profiles/${profileId}/preview-pages/${pageNo}/region-text`, {
|
||||
method: 'POST', body: JSON.stringify({ document_id: documentId, region }), ...jsonAuth(),
|
||||
signal?: AbortSignal,
|
||||
purpose?: 'reservation_id_region',
|
||||
renderedImageBase64?: string | null,
|
||||
) => requestJson<{ document_id: number; page_no: number; text: string; source: string | null; status: 'needs_review'; reservation_candidates?: Array<{ value: string; line_no: number | null; scope: 'header' | 'line'; raw_text: string; status: string }> }>(
|
||||
`/api/admin/shipping-notice/order-document-profiles/${profileId}/preview-pages/${pageNo}/region-text`, {
|
||||
method: 'POST', body: JSON.stringify({ document_id: documentId, region, ...(purpose ? { purpose } : {}), ...(renderedImageBase64 ? { rendered_image_base64: renderedImageBase64 } : {}) }), signal, ...jsonAuth(),
|
||||
},
|
||||
);
|
||||
|
||||
|
||||
@@ -23,7 +23,6 @@ export interface ShippingConfigSubModuleMeta {
|
||||
| 'AdminShippingOrderExtractionRuns'
|
||||
| 'AdminShippingAudit'
|
||||
| 'AdminShippingProcessGates'
|
||||
| 'AdminShippingLegacyStpJobs'
|
||||
| 'AdminShippingOrderDocumentProfiles';
|
||||
path:
|
||||
| 'shipping-notice'
|
||||
@@ -33,7 +32,6 @@ export interface ShippingConfigSubModuleMeta {
|
||||
| 'shipping-order-extraction-runs'
|
||||
| 'shipping-audit'
|
||||
| 'shipping-process-gates'
|
||||
| 'shipping-legacy-stp-jobs'
|
||||
| 'shipping-order-document-profiles';
|
||||
labelKey: string;
|
||||
groupKey: 'admin.nav.shippingOrderRecognition' | 'admin.nav.shippingInventoryManagement' | 'admin.nav.shippingRunAudit';
|
||||
|
||||
-420
@@ -1,420 +0,0 @@
|
||||
<!--
|
||||
features/admin/modules/shipping-legacy-stp-jobs/ShippingLegacyStpJobsPage.vue
|
||||
用途:Phase 5-1 —— 管理员「历史 STP Job(928/929 回放)」运维面板。
|
||||
依赖:shipping-legacy-stp-jobs.api、Vue Router、Vue I18n、workspace.shippingNotice.actions 键。
|
||||
逻辑:
|
||||
[STEP 1] 左侧 ~38%:分页列表(筛选 q/case_no/error_code/blocking_reason/status/created_from/to)
|
||||
按创建时间倒序;
|
||||
[STEP 2] 右侧 sticky:详情 —— Job 摘要、回链 Review Case(case 非空时跳转工作台 Case 详情)、
|
||||
replay_plan(推荐 user_action)、
|
||||
「一键回放 Reconcile And Progress」按钮直接走
|
||||
POST /api/workspace/shipping-notice/order-review-cases/<case_no>/reconcile-and-progress
|
||||
带 legacy_job_id + replay_mode。
|
||||
全部只读 + 一个写操作(回放按钮),写操作必须管理员;非管理员会被后端 422。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { onMounted, ref, watch } from 'vue';
|
||||
import { useRouter } from 'vue-router';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import {
|
||||
DEFAULT_LEGACY_STP_JOB_FILTERS,
|
||||
LEGACY_STP_JOB_STATUS_OPTIONS,
|
||||
getAdminLegacyStpJob,
|
||||
listAdminLegacyStpJobs,
|
||||
type LegacyStpJobDetailPayload,
|
||||
type LegacyStpJobListFilters,
|
||||
type LegacyStpJobRow,
|
||||
} from '@/features/admin/api/shipping-legacy-stp-jobs.api';
|
||||
import { requestJson } from '@/shared/api/client';
|
||||
import { getAuthHeaders } from '@/shared/utils/auth';
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
|
||||
const { t, te } = useI18n();
|
||||
const router = useRouter();
|
||||
const message = useMessage();
|
||||
|
||||
const loading = ref(false);
|
||||
const detailLoading = ref(false);
|
||||
const replaying = ref(false);
|
||||
const error = ref('');
|
||||
const page = ref(1);
|
||||
const pageSize = ref(25);
|
||||
const total = ref(0);
|
||||
const filters = ref<LegacyStpJobListFilters>({ ...DEFAULT_LEGACY_STP_JOB_FILTERS });
|
||||
const rows = ref<LegacyStpJobRow[]>([]);
|
||||
const selectedJobId = ref<number | null>(null);
|
||||
const detail = ref<LegacyStpJobDetailPayload | null>(null);
|
||||
const replayUserAction = ref<'auto' | 'reuse_existing' | 'create_revision' | 'force_create' | 'adjudicate'>('create_revision');
|
||||
const replayLastResult = ref<{ ok: boolean; outcome?: string | null; message?: string | null } | null>(null);
|
||||
|
||||
const formatTime = (value?: string | null) => (value ? new Date(value).toLocaleString() : '—');
|
||||
function jsonFormat(value: unknown): string {
|
||||
if (value == null) return '—';
|
||||
try { return JSON.stringify(value, null, 2); } catch { return String(value); }
|
||||
}
|
||||
type CodeLabelNs = 'admin.legacyStpJobs.statusLabels' | 'admin.legacyStpJobs.reasonCodes' | 'workspace.shippingNotice.processGate.actionCodes';
|
||||
|
||||
function codeLabel(code?: string | null, ns: CodeLabelNs = 'admin.legacyStpJobs.statusLabels'): string {
|
||||
const key = String(code || '').trim();
|
||||
if (!key) return '—';
|
||||
const i18nKey = `${ns}.${key}`;
|
||||
return te(i18nKey) ? t(i18nKey) : key;
|
||||
}
|
||||
function actionLabel(code?: string | null): string { return codeLabel(code, 'workspace.shippingNotice.processGate.actionCodes'); }
|
||||
|
||||
function resetFilters() {
|
||||
filters.value = { ...DEFAULT_LEGACY_STP_JOB_FILTERS };
|
||||
page.value = 1;
|
||||
selectedJobId.value = null;
|
||||
detail.value = null;
|
||||
}
|
||||
|
||||
async function loadList() {
|
||||
loading.value = true;
|
||||
error.value = '';
|
||||
try {
|
||||
const payload = await listAdminLegacyStpJobs(page.value, pageSize.value, filters.value);
|
||||
const items = (payload as any).items ?? [];
|
||||
rows.value = Array.isArray(items) ? items : [];
|
||||
total.value = Number((payload as any).pagination?.total ?? 0);
|
||||
} catch (exc: any) {
|
||||
error.value = exc?.message || String(exc);
|
||||
rows.value = [];
|
||||
total.value = 0;
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function loadDetail(jobId: number) {
|
||||
detailLoading.value = true;
|
||||
detail.value = null;
|
||||
replayLastResult.value = null;
|
||||
replayUserAction.value = 'create_revision';
|
||||
try {
|
||||
detail.value = await getAdminLegacyStpJob(jobId);
|
||||
const plan = detail.value.replay_plan;
|
||||
if (plan?.recommended_user_action === 'force_create') {
|
||||
replayUserAction.value = 'force_create';
|
||||
} else if (plan?.recommended_user_action === 'create_revision') {
|
||||
replayUserAction.value = 'create_revision';
|
||||
}
|
||||
} catch (exc: any) {
|
||||
message.error(exc?.message || String(exc));
|
||||
} finally {
|
||||
detailLoading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
function onRowClick(row: LegacyStpJobRow) {
|
||||
selectedJobId.value = Number(row.job_id);
|
||||
loadDetail(Number(row.job_id)).catch(() => {});
|
||||
}
|
||||
|
||||
function openCaseInWorkspace(caseNo: string) {
|
||||
router.push({
|
||||
name: 'WorkspaceShippingNotice',
|
||||
query: { case_no: caseNo, focus: 'review_case' },
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 【回放按钮】严格只走 /workspace/shipping-notice/order-review-cases/<case_no>/reconcile-and-progress,
|
||||
* 携带 operation_id / legacy_job_id / replay_mode / user_action 四参数。
|
||||
* 禁止任何绕过该 API 的直接 SQL/Job.status 修改。
|
||||
*/
|
||||
async function replaySelected() {
|
||||
if (!detail.value || !detail.value.job.case_no) {
|
||||
message.error(t('admin.legacyStpJobs.replayError_noCaseNo'));
|
||||
return;
|
||||
}
|
||||
const caseNo = String(detail.value.job.case_no).trim();
|
||||
const legacyJobId = Number(detail.value.job.job_id);
|
||||
const replayMode = Boolean(detail.value.replay_plan?.needs_replay_mode);
|
||||
const action = replayUserAction.value;
|
||||
const operationId = crypto.randomUUID
|
||||
? crypto.randomUUID()
|
||||
: String(Date.now()) + '-' + Math.random().toString(36).slice(2);
|
||||
const url = `/api/workspace/shipping-notice/order-review-cases/${encodeURIComponent(caseNo)}/reconcile-and-progress`;
|
||||
const headers = { 'Content-Type': 'application/json', ...getAuthHeaders() };
|
||||
const body = JSON.stringify({
|
||||
operation_id: operationId,
|
||||
user_action: action,
|
||||
legacy_job_id: legacyJobId,
|
||||
replay_mode: replayMode || action === 'force_create',
|
||||
});
|
||||
replaying.value = true;
|
||||
replayLastResult.value = null;
|
||||
try {
|
||||
const resp = await requestJson<any>(url, { method: 'POST', headers, body });
|
||||
const outcome = (resp as any)?.data?.outcome ?? null;
|
||||
const ok = !!(resp as any)?.success && String(outcome || '') !== 'ERROR';
|
||||
replayLastResult.value = {
|
||||
ok,
|
||||
outcome: outcome,
|
||||
message: (resp as any)?.data?.message ?? null,
|
||||
};
|
||||
if (ok) {
|
||||
message.success(t('admin.legacyStpJobs.replaySuccess', { outcome: String(outcome || '') }));
|
||||
} else {
|
||||
message.error(t('admin.legacyStpJobs.replayRejected', { outcome: String(outcome || '') }));
|
||||
}
|
||||
} catch (exc: any) {
|
||||
const err = exc?.message || String(exc);
|
||||
replayLastResult.value = { ok: false, outcome: 'ERROR', message: err };
|
||||
message.error(err);
|
||||
} finally {
|
||||
replaying.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(loadList);
|
||||
watch([page, pageSize], loadList);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex flex-col h-full gap-4 lg:gap-6 p-4 lg:p-6">
|
||||
<div class="flex items-center justify-between flex-wrap gap-3">
|
||||
<div>
|
||||
<h2 class="text-xl font-semibold">{{ t('admin.legacyStpJobs.pageTitle') }}</h2>
|
||||
<p class="text-sm text-gray-600">{{ t('admin.legacyStpJobs.pageSubtitle') }}</p>
|
||||
</div>
|
||||
<div class="flex items-center gap-2">
|
||||
<button
|
||||
class="px-3 py-1.5 text-sm rounded border border-gray-300 hover:bg-gray-50"
|
||||
type="button"
|
||||
@click="resetFilters"
|
||||
>
|
||||
{{ t('common.reset') }}
|
||||
</button>
|
||||
<button
|
||||
class="px-3 py-1.5 text-sm rounded bg-indigo-600 text-white hover:bg-indigo-700"
|
||||
type="button"
|
||||
@click="loadList"
|
||||
:disabled="loading"
|
||||
>
|
||||
{{ t('common.refresh') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-5 gap-3">
|
||||
<input
|
||||
v-model="filters.q"
|
||||
class="px-3 py-2 border rounded text-sm"
|
||||
:placeholder="t('admin.legacyStpJobs.filterQ')"
|
||||
@keyup.enter="page = 1, loadList()"
|
||||
/>
|
||||
<input
|
||||
v-model="filters.case_no"
|
||||
class="px-3 py-2 border rounded text-sm"
|
||||
:placeholder="t('admin.legacyStpJobs.filterCaseNo')"
|
||||
@keyup.enter="page = 1, loadList()"
|
||||
/>
|
||||
<input
|
||||
v-model="filters.error_code"
|
||||
class="px-3 py-2 border rounded text-sm"
|
||||
:placeholder="t('admin.legacyStpJobs.filterErrorCode')"
|
||||
@keyup.enter="page = 1, loadList()"
|
||||
/>
|
||||
<select
|
||||
v-model="filters.status"
|
||||
class="px-3 py-2 border rounded text-sm"
|
||||
@change="page = 1, loadList()"
|
||||
>
|
||||
<option value="">{{ t('admin.legacyStpJobs.statusAll') }}</option>
|
||||
<option v-for="s in LEGACY_STP_JOB_STATUS_OPTIONS" :key="s" :value="s">{{ codeLabel(s) }}</option>
|
||||
</select>
|
||||
<input
|
||||
v-model="filters.created_from"
|
||||
type="datetime-local"
|
||||
class="px-3 py-2 border rounded text-sm"
|
||||
@change="page = 1, loadList()"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="grid grid-cols-1 lg:grid-cols-[minmax(0,38%)_1fr] gap-4 lg:gap-6 min-h-0 flex-1">
|
||||
<!-- 左侧列表 -->
|
||||
<section class="flex flex-col min-h-0 border rounded bg-white/60">
|
||||
<div class="flex items-center justify-between px-4 py-2 border-b">
|
||||
<span class="text-sm font-medium">{{ t('admin.legacyStpJobs.listTitle', { count: total }) }}</span>
|
||||
<span v-if="loading" class="text-xs text-gray-500">{{ t('common.loading') }}</span>
|
||||
</div>
|
||||
<div v-if="error" class="p-3 text-sm text-red-700 bg-red-50 border-b">{{ error }}</div>
|
||||
<div class="overflow-auto min-h-0 max-h-[72vh] divide-y">
|
||||
<div
|
||||
v-for="row in rows"
|
||||
:key="row.job_id"
|
||||
class="px-4 py-3 cursor-pointer hover:bg-indigo-50/60"
|
||||
:class="selectedJobId === row.job_id ? 'bg-indigo-50 ring-2 ring-inset ring-indigo-300' : ''"
|
||||
@click="onRowClick(row)"
|
||||
>
|
||||
<div class="flex items-center justify-between gap-3">
|
||||
<div class="min-w-0">
|
||||
<div class="flex items-center gap-2 text-sm">
|
||||
<span class="font-mono text-xs bg-gray-100 px-2 py-0.5 rounded">#{{ row.job_id }}</span>
|
||||
<span
|
||||
class="text-xs px-2 py-0.5 rounded"
|
||||
:class="row.status === 'failed' ? 'bg-red-100 text-red-700' : 'bg-gray-200 text-gray-700'"
|
||||
>{{ codeLabel(row.status) }}</span>
|
||||
<span class="truncate text-xs text-gray-500">{{ row.case_no || row.business_ref || '—' }}</span>
|
||||
</div>
|
||||
<div class="mt-1.5 text-sm">
|
||||
<span class="text-gray-700">{{ codeLabel(row.blocking_reason || row.error_code || '', 'admin.legacyStpJobs.reasonCodes') }}</span>
|
||||
<span class="mx-2 text-gray-300">·</span>
|
||||
<span class="text-xs text-gray-500">{{ row.attempts }}/{{ row.max_attempts }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="text-right text-xs text-gray-500 leading-5 shrink-0">
|
||||
<div>{{ formatTime(row.created_at) }}</div>
|
||||
<div v-if="row.finished_at">→ {{ formatTime(row.finished_at) }}</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="!rows.length && !loading" class="p-8 text-center text-sm text-gray-500">
|
||||
{{ t('admin.legacyStpJobs.empty') }}
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex items-center justify-between px-4 py-2 border-t text-sm">
|
||||
<span class="text-gray-500">{{ t('common.pageOf', { page, total: Math.max(1, Math.ceil(total / pageSize)) }) }}</span>
|
||||
<div class="flex items-center gap-1">
|
||||
<button
|
||||
class="px-2 py-1 rounded border disabled:opacity-50"
|
||||
:disabled="page <= 1"
|
||||
type="button"
|
||||
@click="page -= 1"
|
||||
>{{ t('common.prev') }}</button>
|
||||
<button
|
||||
class="px-2 py-1 rounded border disabled:opacity-50"
|
||||
:disabled="page * pageSize >= total"
|
||||
type="button"
|
||||
@click="page += 1"
|
||||
>{{ t('common.next') }}</button>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- 右侧详情 -->
|
||||
<section class="flex flex-col min-h-0 border rounded bg-white/60">
|
||||
<div class="flex items-center justify-between px-4 py-2 border-b">
|
||||
<span class="text-sm font-medium">{{ t('admin.legacyStpJobs.detailTitle') }}</span>
|
||||
<span v-if="detailLoading" class="text-xs text-gray-500">{{ t('common.loading') }}</span>
|
||||
</div>
|
||||
<div v-if="!detail && !detailLoading" class="p-8 text-center text-sm text-gray-500">
|
||||
{{ t('admin.legacyStpJobs.detailEmpty') }}
|
||||
</div>
|
||||
<div v-else-if="detail" class="overflow-auto min-h-0 max-h-[72vh] px-5 py-4 space-y-5">
|
||||
<!-- 摘要行 -->
|
||||
<div class="grid grid-cols-1 md:grid-cols-3 gap-3 text-sm">
|
||||
<div class="border rounded p-3">
|
||||
<div class="text-xs text-gray-500 mb-1">{{ t('admin.legacyStpJobs.job') }}</div>
|
||||
<div class="font-mono">#{{ detail.job.job_id }} · {{ codeLabel(detail.job.status) }}</div>
|
||||
<div class="mt-1 text-xs text-gray-500">attempts: {{ detail.job.attempts }}/{{ detail.job.max_attempts }}</div>
|
||||
</div>
|
||||
<div class="border rounded p-3">
|
||||
<div class="text-xs text-gray-500 mb-1">{{ t('admin.legacyStpJobs.reviewCase') }}</div>
|
||||
<button
|
||||
v-if="detail.job.case_no"
|
||||
class="text-indigo-600 hover:underline font-mono"
|
||||
type="button"
|
||||
@click="openCaseInWorkspace(detail.job.case_no!)"
|
||||
>{{ detail.job.case_no }}</button>
|
||||
<span v-else class="text-gray-400">—</span>
|
||||
<div class="mt-1 text-xs text-gray-500 truncate">{{ detail.job.business_ref || '—' }}</div>
|
||||
</div>
|
||||
<div class="border rounded p-3">
|
||||
<div class="text-xs text-gray-500 mb-1">{{ t('admin.legacyStpJobs.blocking') }}</div>
|
||||
<div class="font-medium">{{ codeLabel(detail.job.blocking_reason || detail.job.error_code || '', 'admin.legacyStpJobs.reasonCodes') }}</div>
|
||||
<div class="mt-1 text-xs text-gray-500 truncate">{{ detail.job.message || detail.job.error_message || '—' }}</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 回链 Case:若存在则展示 8 字段 -->
|
||||
<div v-if="detail.case" class="border rounded p-4">
|
||||
<div class="text-sm font-medium mb-2">{{ t('admin.legacyStpJobs.linkedCase') }}</div>
|
||||
<dl class="grid grid-cols-2 md:grid-cols-4 gap-3 text-sm">
|
||||
<div><dt class="text-xs text-gray-500">case_id</dt><dd class="font-mono">{{ detail.case.case_id }}</dd></div>
|
||||
<div><dt class="text-xs text-gray-500">{{ t('admin.legacyStpJobs.caseStatus') }}</dt><dd>{{ detail.case.status }}</dd></div>
|
||||
<div><dt class="text-xs text-gray-500">candidate_id</dt><dd class="font-mono">{{ detail.case.candidate_id ?? '—' }}</dd></div>
|
||||
<div><dt class="text-xs text-gray-500">confirmed_task_id</dt><dd class="font-mono">{{ detail.case.confirmed_task_id ?? '—' }}</dd></div>
|
||||
<div><dt class="text-xs text-gray-500">document_id</dt><dd class="font-mono">{{ detail.case.document_id ?? '—' }}</dd></div>
|
||||
<div><dt class="text-xs text-gray-500">owner_user_id</dt><dd class="font-mono">{{ detail.case.owner_user_id ?? '—' }}</dd></div>
|
||||
<div><dt class="text-xs text-gray-500">{{ t('common.createdAt') }}</dt><dd>{{ formatTime(detail.case.created_at) }}</dd></div>
|
||||
<div><dt class="text-xs text-gray-500">{{ t('common.updatedAt') }}</dt><dd>{{ formatTime(detail.case.updated_at) }}</dd></div>
|
||||
</dl>
|
||||
</div>
|
||||
|
||||
<!-- 回放计划:推荐动作 + 回放按钮 -->
|
||||
<div class="border rounded p-4 bg-amber-50/60">
|
||||
<div class="text-sm font-medium mb-2">{{ t('admin.legacyStpJobs.replayPlan') }}</div>
|
||||
<div class="grid grid-cols-1 md:grid-cols-2 gap-4 items-center">
|
||||
<div class="text-sm space-y-1">
|
||||
<div>
|
||||
<span class="text-gray-500 mr-2">{{ t('admin.legacyStpJobs.recommendedAction') }}:</span>
|
||||
<span class="px-2 py-0.5 rounded bg-white border text-sm">
|
||||
{{ actionLabel(detail.replay_plan.recommended_user_action) }}
|
||||
</span>
|
||||
</div>
|
||||
<div>
|
||||
<span class="text-gray-500 mr-2">{{ t('admin.legacyStpJobs.needsReplayMode') }}:</span>
|
||||
<span :class="detail.replay_plan.needs_replay_mode ? 'text-amber-700 font-medium' : 'text-gray-500'">
|
||||
{{ detail.replay_plan.needs_replay_mode ? t('common.yes') : t('common.no') }}
|
||||
</span>
|
||||
</div>
|
||||
<div v-if="detail.replay_plan.reconcile_and_progress_endpoint" class="font-mono text-xs text-gray-500 break-all">
|
||||
POST {{ detail.replay_plan.reconcile_and_progress_endpoint }}
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex flex-col gap-2 md:items-end">
|
||||
<label class="flex items-center gap-2 text-sm md:justify-end">
|
||||
<span class="text-gray-600 w-32">{{ t('admin.legacyStpJobs.userAction') }}</span>
|
||||
<select v-model="replayUserAction" class="px-3 py-1.5 border rounded text-sm">
|
||||
<option value="auto">{{ actionLabel('auto') }}</option>
|
||||
<option value="reuse_existing">{{ actionLabel('reuse_existing') }}</option>
|
||||
<option value="create_revision">{{ actionLabel('create_revision') }}</option>
|
||||
<option value="force_create">{{ actionLabel('force_create') }}</option>
|
||||
<option value="adjudicate">{{ actionLabel('adjudicate') }}</option>
|
||||
</select>
|
||||
</label>
|
||||
<button
|
||||
class="px-4 py-2 rounded bg-indigo-600 text-white hover:bg-indigo-700 disabled:opacity-60 max-w-xs"
|
||||
type="button"
|
||||
:disabled="replaying || !detail.job.case_no"
|
||||
@click="replaySelected"
|
||||
>
|
||||
{{ replaying ? t('common.loading') : t('admin.legacyStpJobs.replayButton') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="replayLastResult" class="mt-3 text-sm border-t pt-3">
|
||||
<div class="flex items-center gap-2">
|
||||
<span
|
||||
class="text-xs px-2 py-0.5 rounded"
|
||||
:class="replayLastResult.ok ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-700'"
|
||||
>
|
||||
{{ replayLastResult.ok ? t('common.ok') : t('common.error') }}
|
||||
</span>
|
||||
<span class="font-mono text-xs bg-white border rounded px-2 py-0.5">{{ replayLastResult.outcome ?? '—' }}</span>
|
||||
</div>
|
||||
<div v-if="replayLastResult.message" class="mt-1.5 text-xs text-gray-600 whitespace-pre-wrap break-all">
|
||||
{{ replayLastResult.message }}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 原始 JSON:payload / result(masked) -->
|
||||
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<div class="border rounded p-3">
|
||||
<div class="text-xs text-gray-500 mb-1">{{ t('admin.legacyStpJobs.payloadJson') }}</div>
|
||||
<pre class="text-xs whitespace-pre-wrap break-all bg-gray-50 p-2 rounded max-h-64 overflow-auto">{{ jsonFormat(detail.job.payload_json_masked) }}</pre>
|
||||
</div>
|
||||
<div class="border rounded p-3">
|
||||
<div class="text-xs text-gray-500 mb-1">{{ t('admin.legacyStpJobs.resultJson') }}</div>
|
||||
<pre class="text-xs whitespace-pre-wrap break-all bg-gray-50 p-2 rounded max-h-64 overflow-auto">{{ jsonFormat(detail.job.result_json_masked) }}</pre>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
+3
-2
@@ -178,7 +178,8 @@ function stopUploadPolling(): void {
|
||||
async function pollUploadedSample(intakeNo: string): Promise<void> {
|
||||
try {
|
||||
const result = await getOrderProfileSampleStatus(intakeNo);
|
||||
if (result.parse_status === 'parsed' && result.document_count > 0) {
|
||||
// 与样本列表的可见条件一致:文档物化且 Layout ready 后才进入候选列表。
|
||||
if (result.parse_status === 'parsed' && result.document_count > 0 && result.layout_status === 'ready') {
|
||||
await loadAvailableSamples(true);
|
||||
const selected = availableSamples.value.find((item) => (result.document_ids || []).includes(item.document_id));
|
||||
if (selected) {
|
||||
@@ -192,7 +193,7 @@ async function pollUploadedSample(intakeNo: string): Promise<void> {
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (['failed', 'error'].includes(result.parse_status)) {
|
||||
if (['failed', 'error'].includes(result.parse_status) || result.layout_status === 'failed') {
|
||||
await loadAvailableSamples(true);
|
||||
const selected = availableSamples.value.find((item) => (result.document_ids || []).includes(item.document_id));
|
||||
if (selected) {
|
||||
|
||||
+711
-184
File diff suppressed because it is too large.
Load diff
+62
@@ -6,13 +6,66 @@
|
||||
*/
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import {
|
||||
filterRegionsAfterRemoval,
|
||||
resolveSelectedOrderAnchorId,
|
||||
resolveCanvasActions,
|
||||
resolveDeskAdapter,
|
||||
resolveMainTableIdForPageChange,
|
||||
resolveSharedCanvasDocument,
|
||||
resolveValueAdapterKey,
|
||||
shouldKeepUnreadableOrderField,
|
||||
type OrderProfileCanvasActions,
|
||||
} from './canvasActions.utils';
|
||||
|
||||
describe('filterRegionsAfterRemoval', () => {
|
||||
it('deletes only the selected ordinary top-level region', () => {
|
||||
const regions = [
|
||||
{ id: 'green-1', kind: 'header_field', label: 'A', region: { x0: 0, y0: 0, x1: .1, y1: .1 }, pageNo: 1 },
|
||||
{ id: 'green-2', kind: 'header_field', label: 'B', region: { x0: 0, y0: .2, x1: .1, y1: .3 }, pageNo: 1 },
|
||||
] as any;
|
||||
|
||||
expect(filterRegionsAfterRemoval(regions, 'green-1')).toEqual([regions[1]]);
|
||||
});
|
||||
|
||||
it('keeps ordinary top-level regions while deleting a document-anchor family', () => {
|
||||
const regions = [
|
||||
{ id: 'green-1', kind: 'header_field', label: 'A', region: { x0: 0, y0: 0, x1: .1, y1: .1 }, pageNo: 1 },
|
||||
{ id: 'anchor-label', kind: 'document_anchor_label', label: 'Label', parentId: 'anchor-1', region: { x0: 0, y0: .2, x1: .1, y1: .3 }, pageNo: 1 },
|
||||
{ id: 'anchor-value', kind: 'document_anchor_value', label: 'Value', parentId: 'anchor-1', region: { x0: 0, y0: .3, x1: .1, y1: .4 }, pageNo: 1 },
|
||||
] as any;
|
||||
|
||||
expect(filterRegionsAfterRemoval(regions, 'anchor-label', 'anchor-1').map((item) => item.id)).toEqual(['green-1']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('resolveSelectedOrderAnchorId', () => {
|
||||
it('only returns an explicitly selected order anchor', () => {
|
||||
const selectedAnchor = {
|
||||
id: 'ship_to_anchor', kind: 'order_anchor', label: 'Ship to',
|
||||
region: { x0: 0, y0: 0, x1: .1, y1: .1 }, pageNo: 1,
|
||||
} as any;
|
||||
const selectedValue = {
|
||||
id: 'ship_to_value', kind: 'order_field', parentId: 'ship_to_anchor',
|
||||
label: 'Example', region: { x0: 0, y0: .1, x1: .1, y1: .2 }, pageNo: 1,
|
||||
} as any;
|
||||
|
||||
expect(resolveSelectedOrderAnchorId(selectedAnchor)).toBe('ship_to_anchor');
|
||||
expect(resolveSelectedOrderAnchorId(selectedValue)).toBeNull();
|
||||
expect(resolveSelectedOrderAnchorId(null)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('shouldKeepUnreadableOrderField', () => {
|
||||
it('keeps an XFA value box when visual readback remains unavailable', () => {
|
||||
// OCR/Widget 回读失败必须可诊断,但不能让管理员已框选的 XFA 值框消失。
|
||||
expect(shouldKeepUnreadableOrderField('xfa_dataset', 'order_field', false)).toBe(true);
|
||||
});
|
||||
|
||||
it('keeps the ordinary-PDF empty-value guard unchanged', () => {
|
||||
expect(shouldKeepUnreadableOrderField('coordinate_ocr', 'order_field', false)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
function actions(): OrderProfileCanvasActions {
|
||||
return {
|
||||
create: vi.fn(), select: vi.fn(), dragStart: vi.fn(), dragEnd: vi.fn(), change: vi.fn(),
|
||||
@@ -98,3 +151,12 @@ describe('resolveCanvasActions', () => {
|
||||
expect(resolveValueAdapterKey({ template_mode: 'coordinate' } as any)).toBe('coordinate_ocr');
|
||||
});
|
||||
});
|
||||
|
||||
describe('resolveMainTableIdForPageChange', () => {
|
||||
it('keeps the frozen main table when PDF navigation selects another table on the same page', () => {
|
||||
expect(resolveMainTableIdForPageChange({
|
||||
frozenMainTableId: 'order-lines-table',
|
||||
pagePreviewTableId: 'total-amount-table',
|
||||
})).toBe('order-lines-table');
|
||||
});
|
||||
});
|
||||
+54
-1
@@ -24,6 +24,58 @@ export interface OrderProfileCanvasActions {
|
||||
draw(kind: OrderProfileCanvasRegion['kind']): void;
|
||||
}
|
||||
|
||||
/**
|
||||
* 计算删除画布区域后的区域集合。
|
||||
* 普通区域只删除自身及其直接子区域;文档锚点仅在明确传入锚点 ID 时级联删除。
|
||||
*/
|
||||
export function filterRegionsAfterRemoval(
|
||||
regions: OrderProfileCanvasRegion[],
|
||||
removedId: string,
|
||||
documentAnchorId: string | null = null,
|
||||
): OrderProfileCanvasRegion[] {
|
||||
return regions.filter((item) => (
|
||||
item.id !== removedId
|
||||
&& item.parentId !== removedId
|
||||
&& (documentAnchorId === null || item.parentId !== documentAnchorId)
|
||||
));
|
||||
}
|
||||
|
||||
/**
|
||||
* 返回当前明确选中的订单字段标签 ID。
|
||||
* 核心逻辑:订单字段值框只能继承用户当前选中的标签,绝不回退到页面第一个标签。
|
||||
* @param selectedRegion - 当前画布选区;非订单字段标签或未选中时返回 null。
|
||||
* @returns 可作为订单字段父节点的标签 ID,或 null。
|
||||
*/
|
||||
export function resolveSelectedOrderAnchorId(
|
||||
selectedRegion: Pick<OrderProfileCanvasRegion, 'id' | 'kind'> | null,
|
||||
): string | null {
|
||||
return selectedRegion?.kind === 'order_anchor' ? selectedRegion.id : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 保持模板主表身份与 PDF 页内预览表分离。
|
||||
* 核心逻辑:翻页是画布导航,不能把同页第一张表(例如合计区)写回已冻结的主表身份。
|
||||
*/
|
||||
export function resolveMainTableIdForPageChange(options: {
|
||||
frozenMainTableId: string;
|
||||
pagePreviewTableId: string;
|
||||
}): string {
|
||||
return options.frozenMainTableId || options.pagePreviewTableId;
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断 XFA 视觉回读为空时是否应保留用户刚圈选的值框。
|
||||
* 核心逻辑:空回读是待诊断的视觉证据失败,不得吞掉管理员已经完成的 XFA 位置标注;
|
||||
* 普通 PDF 仍维持原有的空文本拒绝规则。
|
||||
*/
|
||||
export function shouldKeepUnreadableOrderField(
|
||||
adapterKey: string,
|
||||
kind: OrderProfileCanvasRegion['kind'] | null,
|
||||
hasVisualText: boolean,
|
||||
): boolean {
|
||||
return hasVisualText || (adapterKey === 'xfa_dataset' && kind === 'order_field');
|
||||
}
|
||||
|
||||
/**
|
||||
* 共享 Editor 消费的视觉画布状态。
|
||||
*
|
||||
@@ -35,6 +87,7 @@ export interface OrderProfileVisualCanvasAdapter {
|
||||
actions: OrderProfileCanvasActions;
|
||||
documentReady: boolean;
|
||||
preview: { document_id: number; preview_token: string; expires_in_seconds: number } | null;
|
||||
grant: { page_no: number; preview_token: string } | null;
|
||||
previewPagePath: string;
|
||||
regions: OrderProfileCanvasRegion[];
|
||||
selectedRegionId: string | null;
|
||||
@@ -130,7 +183,7 @@ export function resolveDeskAdapter<T>(options: {
|
||||
/**
|
||||
* 返回唯一由 Editor 消费的 PDF 画布文档上下文。
|
||||
* 核心逻辑:所有 Profile 先使用共同冻结的 annotation document + main_table_id;
|
||||
* 历史草稿缺失 main_table_id 时才回退样本 table_id。预览授权、页码和 PDF.js 渲染始终
|
||||
* 历史草稿缺失 main_table_id 时才回退样本 table_id。预览授权、页码和 PDFium/PDF.js 渲染始终
|
||||
* 由共享 Editor 持有,值源 adapter 不得参与上下文选择。
|
||||
* @param options.documentId - 共同 annotation 文档身份。
|
||||
* @param options.mainTableId - definition 中冻结的共同视觉主表。
|
||||
|
||||
+48
@@ -82,4 +82,52 @@ describe('OrderProfileDocumentCanvas PDF preview', () => {
|
||||
expect(wrapper.find('.canvas-stage').attributes('style')).toContain('width: 750px');
|
||||
expect(wrapper.find('.region').attributes('style')).toContain('left: 50%');
|
||||
});
|
||||
|
||||
it('uses the server-rendered PNG page for an ordinary PDF instead of PDF.js', async () => {
|
||||
const wrapper = mount(OrderProfileDocumentCanvas, {
|
||||
props: {
|
||||
profileId: 71,
|
||||
grant: { page_no: 1, preview_token: 'page-token' },
|
||||
previewPagePath: '/api/admin/shipping-notice/order-document-profiles/71/preview-pages',
|
||||
regions: [], pageNo: 1, pageCount: 1,
|
||||
},
|
||||
global: { plugins: [createI18n({ legacy: false, locale: 'zh', messages: { zh: {} } })] },
|
||||
});
|
||||
await flushPromises();
|
||||
|
||||
// 普通 PDF 底图由后端 PDFium 输出,避免前端 PDF.js 对特定繁体内嵌字体的渲染差异。
|
||||
expect(getDocumentMock).not.toHaveBeenCalled();
|
||||
expect(wrapper.find('img').exists()).toBe(true);
|
||||
expect(fetch).toHaveBeenCalledWith(
|
||||
'/api/admin/shipping-notice/order-document-profiles/71/preview-pages/1?preview_token=page-token',
|
||||
expect.objectContaining({ cache: 'no-store' }),
|
||||
);
|
||||
});
|
||||
|
||||
it('captures the selected XFA appearance from the unscaled PDF.js canvas', async () => {
|
||||
const drawImage = vi.fn();
|
||||
const toDataURL = vi.fn(() => 'data:image/png;base64,canvas-crop');
|
||||
const nativeCreateElement = document.createElement.bind(document);
|
||||
vi.spyOn(document, 'createElement').mockImplementation((tagName: string) => {
|
||||
const element = nativeCreateElement(tagName) as HTMLCanvasElement;
|
||||
if (tagName === 'canvas') {
|
||||
Object.defineProperty(element, 'getContext', { value: vi.fn(() => ({ drawImage })) });
|
||||
Object.defineProperty(element, 'toDataURL', { value: toDataURL });
|
||||
}
|
||||
return element;
|
||||
});
|
||||
const wrapper = mount(OrderProfileDocumentCanvas, {
|
||||
props: { profileId: 71, pdfPreview: { preview_token: 'single-use-token' }, regions: [], pageNo: 1, pageCount: 1 },
|
||||
global: { plugins: [createI18n({ legacy: false, locale: 'zh', messages: { zh: {} } })] },
|
||||
});
|
||||
await flushPromises();
|
||||
await flushPromises();
|
||||
const source = wrapper.find('canvas.pdf-page').element as HTMLCanvasElement;
|
||||
Object.defineProperties(source, { width: { value: 600 }, height: { value: 800 } });
|
||||
|
||||
expect((wrapper.vm as { captureRegion: (region: object) => string | null }).captureRegion({ x0: .1, y0: .2, x1: .4, y1: .5 }))
|
||||
.toBe('data:image/png;base64,canvas-crop');
|
||||
// 使用 PDF.js 原始像素而不是 CSS 缩放后的大小,保证回读与用户框选区域一致。
|
||||
expect(drawImage).toHaveBeenCalledWith(source, 60, 160, 181, 240, 0, 0, 181, 240);
|
||||
});
|
||||
});
|
||||
+37
-9
@@ -8,7 +8,7 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, nextTick, onBeforeUnmount, ref, watch } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { Anchor, ArrowLeft, ArrowRight, Columns3, Copy, Eraser, Minus, Plus, Redo2, RotateCcw, Rows3, Save, TableProperties, Tag, TextCursorInput, Trash2, WandSparkles } from 'lucide-vue-next';
|
||||
import { Anchor, ArrowLeft, ArrowRight, Columns3, Copy, Eraser, MessageSquareText, Minus, Plus, Redo2, RotateCcw, Rows3, Save, TableProperties, Tag, TextCursorInput, Trash2, WandSparkles } from 'lucide-vue-next';
|
||||
import { getAuthHeaders } from '@/shared/utils/auth';
|
||||
import type { OrderProfileCanvasRegion, OrderProfilePreviewPageGrant } from '@/features/admin/types/shipping-order-document-profile.types';
|
||||
import type { PDFDocumentProxy } from 'pdfjs-dist';
|
||||
@@ -55,6 +55,8 @@ const props = defineProps<{
|
||||
pendingSuggestionCount?: number;
|
||||
orderFieldValues?: Record<string, string | null>;
|
||||
orderFieldValueState?: 'idle' | 'loading' | 'ready' | 'failed';
|
||||
/** 当前样本坐标重建的首条明细行值,按画布字段区域 ID 索引。 */
|
||||
lineFieldValues?: Record<string, string | null>;
|
||||
/** 无图时空态文案;缺省为「选择已绑定的 PDF 样本」。 */
|
||||
emptyHint?: string | null;
|
||||
/** 外部注入的页加载错误(如 XFA page_unavailable);优先于空态提示。 */
|
||||
@@ -215,7 +217,7 @@ const move = (event: PointerEvent) => {
|
||||
const beginDrag = (event: PointerEvent, region: OrderProfileCanvasRegion, mode: DragMode) => {
|
||||
event.preventDefault();
|
||||
emit('select', region.id);
|
||||
if (readonlyMode.value) return;
|
||||
if (readonlyMode.value || region.isPreview) return;
|
||||
emit('start', region.id);
|
||||
activeDrag = { id: region.id, mode, startX: event.clientX, startY: event.clientY, region: { ...region.region } };
|
||||
window.addEventListener('pointermove', move);
|
||||
@@ -275,6 +277,9 @@ const displayRegionLabel = (region: OrderProfileCanvasRegion): string => {
|
||||
return `${region.label} · ${region.recognizedValue || t('admin.shippingOrderProfiles.workbench.sampleValueUnavailable')}`;
|
||||
}
|
||||
if (region.kind !== 'order_field') {
|
||||
if (region.kind === 'field') {
|
||||
return `${region.label} · ${props.lineFieldValues?.[region.id] || t('admin.shippingOrderProfiles.workbench.sampleValueUnavailable')}`;
|
||||
}
|
||||
return region.label;
|
||||
}
|
||||
const state = props.orderFieldValueState || 'idle';
|
||||
@@ -283,7 +288,8 @@ const displayRegionLabel = (region: OrderProfileCanvasRegion): string => {
|
||||
? t('admin.shippingOrderProfiles.workbench.orderFieldValueReading')
|
||||
: state === 'failed'
|
||||
? t('admin.shippingOrderProfiles.workbench.orderFieldValueFailed')
|
||||
: value || t('admin.shippingOrderProfiles.workbench.sampleValueUnavailable');
|
||||
// 新圈选的 XFA 值框先显示同次受控视觉回读;整页 PDFium/OCR 预览完成后再覆盖。
|
||||
: value || region.suggestedValue || t('admin.shippingOrderProfiles.workbench.sampleValueUnavailable');
|
||||
return `${region.label} · ${suffix}`;
|
||||
};
|
||||
/** 以固定步进调整页面倍率;区域采用相对坐标,缩放后仍与图像精确对齐。 */
|
||||
@@ -298,7 +304,24 @@ const goToPage = () => {
|
||||
pageInput.value = nextPage;
|
||||
if (nextPage !== props.pageNo) emit('page', nextPage);
|
||||
};
|
||||
defineExpose({ zoomIn: () => adjustZoom(.25), zoomOut: () => adjustZoom(-.25), resetZoom });
|
||||
/** 导出当前 PDF.js 画布中框选区域的 PNG;XFA 外观值可能只存在于浏览器渲染结果。 */
|
||||
const captureRegion = (region: OrderProfileCanvasRegion['region']): string | null => {
|
||||
const source = pdfCanvas.value;
|
||||
if (!source || source.width < 1 || source.height < 1) return null;
|
||||
const x = Math.max(0, Math.floor(region.x0 * source.width));
|
||||
const y = Math.max(0, Math.floor(region.y0 * source.height));
|
||||
const width = Math.max(1, Math.ceil((region.x1 - region.x0) * source.width));
|
||||
const height = Math.max(1, Math.ceil((region.y1 - region.y0) * source.height));
|
||||
const clippedWidth = Math.min(width, source.width - x);
|
||||
const clippedHeight = Math.min(height, source.height - y);
|
||||
if (clippedWidth < 1 || clippedHeight < 1) return null;
|
||||
const crop = document.createElement('canvas');
|
||||
crop.width = clippedWidth;
|
||||
crop.height = clippedHeight;
|
||||
crop.getContext('2d')?.drawImage(source, x, y, clippedWidth, clippedHeight, 0, 0, clippedWidth, clippedHeight);
|
||||
return crop.toDataURL('image/png');
|
||||
};
|
||||
defineExpose({ zoomIn: () => adjustZoom(.25), zoomOut: () => adjustZoom(-.25), resetZoom, captureRegion });
|
||||
watch(() => [props.grant?.preview_token, props.pdfPreview?.preview_token], () => { void loadPage(); }, { immediate: true });
|
||||
watch(() => props.pageNo, async (value) => {
|
||||
pageInput.value = value;
|
||||
@@ -330,8 +353,7 @@ onBeforeUnmount(() => { endMove(); endPan(); endCreation(); URL.revokeObjectURL(
|
||||
<template v-if="pendingSuggestionCount">
|
||||
<span class="toolbar-divider" aria-hidden="true" />
|
||||
<span class="suggestion-count">{{ pendingSuggestionCount }}</span>
|
||||
<button type="button" class="suggestion-action" @click="emit('acceptSuggestion')">{{ t('admin.shippingOrderProfiles.workbench.acceptSuggestion') }}</button>
|
||||
<button type="button" class="suggestion-action suggestion-action--reject" @click="emit('rejectSuggestion')">{{ t('admin.shippingOrderProfiles.workbench.rejectSuggestion') }}</button>
|
||||
<span class="suggestion-preview-badge">{{ t('admin.shippingOrderProfiles.workbench.suggestionPreviewBadge') }}</span>
|
||||
</template>
|
||||
</template>
|
||||
<span v-else class="readonly-badge">{{ t('admin.shippingOrderProfiles.versionCenter.readonlyCanvasBadge') }}</span>
|
||||
@@ -365,6 +387,7 @@ onBeforeUnmount(() => { endMove(); endPan(); endCreation(); URL.revokeObjectURL(
|
||||
<button type="button" :aria-label="t('admin.shippingOrderProfiles.workbench.drawLineShortcut')" :title="t('admin.shippingOrderProfiles.workbench.drawLineShortcut')" :class="{ active: creationKind === 'line' }" @click="emit('draw', 'line')"><Rows3 /></button>
|
||||
<button type="button" :aria-label="t('admin.shippingOrderProfiles.workbench.drawFieldShortcut')" :title="t('admin.shippingOrderProfiles.workbench.drawFieldShortcut')" :class="{ active: creationKind === 'field' }" @click="emit('draw', 'field')"><Columns3 /></button>
|
||||
<button type="button" :aria-label="t('admin.shippingOrderProfiles.workbench.drawExclusionShortcut')" :title="t('admin.shippingOrderProfiles.workbench.drawExclusionShortcut')" :class="{ active: creationKind === 'exclusion' }" @click="emit('draw', 'exclusion')"><Eraser /></button>
|
||||
<button type="button" :aria-label="t('admin.shippingOrderProfiles.workbench.drawReservationIdRegionShortcut')" :title="t('admin.shippingOrderProfiles.workbench.drawReservationIdRegionShortcut')" :class="{ active: creationKind === 'reservation_id_region' }" @click="emit('draw', 'reservation_id_region')"><MessageSquareText /></button>
|
||||
<button type="button" class="suggest" :aria-label="t('admin.shippingOrderProfiles.workbench.autoSuggestShortcut')" :title="t('admin.shippingOrderProfiles.workbench.autoSuggestShortcut')" :disabled="autoSuggestDisabled || suggesting" @click="emit('suggest')"><WandSparkles /></button>
|
||||
<p v-if="suggestionProgress" class="suggestion-progress" :class="{ failed: !suggesting }">{{ suggestionProgress }}</p>
|
||||
</aside>
|
||||
@@ -386,7 +409,7 @@ onBeforeUnmount(() => { endMove(); endPan(); endCreation(); URL.revokeObjectURL(
|
||||
role="button"
|
||||
tabindex="0"
|
||||
class="region"
|
||||
:class="[`region-${region.kind}`, { selected: selected.has(region.id) }, region.visualBindingStatus ? `region-visual--${region.visualBindingStatus}` : '']"
|
||||
:class="[`region-${region.kind}`, { selected: selected.has(region.id), 'region-preview': region.isPreview }, region.visualBindingStatus ? `region-visual--${region.visualBindingStatus}` : '']"
|
||||
:style="{ left: `${region.region.x0 * 100}%`, top: `${region.region.y0 * 100}%`, width: `${(region.region.x1 - region.region.x0) * 100}%`, height: `${(region.region.y1 - region.region.y0) * 100}%` }"
|
||||
:aria-label="displayRegionLabel(region)"
|
||||
@pointerdown.stop="beginDrag($event, region, 'move')"
|
||||
@@ -394,10 +417,10 @@ onBeforeUnmount(() => { endMove(); endPan(); endCreation(); URL.revokeObjectURL(
|
||||
@keydown.space.prevent="emit('select', region.id)"
|
||||
>
|
||||
<span class="region-label" :title="displayRegionLabel(region)" @pointerdown.stop="beginDrag($event, region, 'move')">{{ displayRegionLabel(region) }}</span>
|
||||
<template v-if="region.kind === 'line' && !readonlyMode">
|
||||
<template v-if="region.kind === 'line' && !readonlyMode && !region.isPreview">
|
||||
<span v-for="edge in ['n', 'e', 's', 'w']" :key="edge" class="line-hit-edge" :class="`line-hit-${edge}`" @pointerdown.stop="beginDrag($event, region, 'move')" />
|
||||
</template>
|
||||
<button v-if="!readonlyMode" v-for="handle in ['n', 'ne', 'e', 'se', 's', 'sw', 'w', 'nw'] as ResizeHandle[]" :key="handle" type="button" class="resize-handle" :class="`handle-${handle}`" :aria-label="t('admin.shippingOrderProfiles.workbench.resizeHandle', { direction: handle })" @pointerdown.stop="beginDrag($event, region, handle)" />
|
||||
<button v-if="!readonlyMode && !region.isPreview" v-for="handle in ['n', 'ne', 'e', 'se', 's', 'sw', 'w', 'nw'] as ResizeHandle[]" :key="handle" type="button" class="resize-handle" :class="`handle-${handle}`" :aria-label="t('admin.shippingOrderProfiles.workbench.resizeHandle', { direction: handle })" @pointerdown.stop="beginDrag($event, region, handle)" />
|
||||
</div>
|
||||
<div v-if="creationRegion" class="creation-region" :style="{ left: `${creationRegion.x0 * 100}%`, top: `${creationRegion.y0 * 100}%`, width: `${(creationRegion.x1 - creationRegion.x0) * 100}%`, height: `${(creationRegion.y1 - creationRegion.y0) * 100}%` }" />
|
||||
</div>
|
||||
@@ -462,6 +485,7 @@ onBeforeUnmount(() => { endMove(); endPan(); endCreation(); URL.revokeObjectURL(
|
||||
.annotation-tools button:disabled { cursor: not-allowed; opacity: .45; }
|
||||
.suggestion-progress { margin: .1rem; color: #bae6fd; font-size: .66rem; line-height: 1.35; }
|
||||
.suggestion-progress.failed { color: #fca5a5; }
|
||||
.suggestion-preview-badge { color: #fbbf24; font-size: .68rem; }
|
||||
.region { position: absolute; box-sizing: border-box; z-index: 2; border: 2px solid #38bdf8; background: rgb(14 165 233 / .10); color: #e0f2fe; cursor: move; text-align: left; touch-action: none; }
|
||||
.region:focus-visible { outline: 3px solid white; outline-offset: 2px; }
|
||||
.region-label { position: absolute; top: -1.65rem; left: -2px; max-width: min(18rem, 100%); overflow: hidden; border: 1px solid rgb(255 255 255 / .7); border-radius: .25rem .25rem 0 0; background: #0369a1; padding: .2rem .45rem; color: white; font: 700 .7rem/1.15 ui-monospace, SFMono-Regular, Menlo, monospace; text-overflow: ellipsis; white-space: nowrap; }
|
||||
@@ -496,6 +520,8 @@ onBeforeUnmount(() => { endMove(); endPan(); endCreation(); URL.revokeObjectURL(
|
||||
.line-hit-w { left: -6px; }
|
||||
.region-exclusion { z-index: 3; border-style: dashed; border-color: #f87171; background: rgb(248 113 113 / .1); }
|
||||
.region-exclusion .region-label, .region-exclusion .resize-handle { background: #b91c1c; }
|
||||
.region-reservation_id_region { z-index: 3; border: 2px solid #f43f5e; background: rgb(244 63 94 / .10); }
|
||||
.region-reservation_id_region .region-label, .region-reservation_id_region .resize-handle { background: #be123c; }
|
||||
.region-visual--suggested { border-style: dashed; border-color: #f59e0b; background: rgb(245 158 11 / .14); }
|
||||
.region-visual--suggested .region-label { background: #b45309; }
|
||||
.region-visual--confirmed { border-color: #22c55e; background: rgb(34 197 94 / .12); }
|
||||
@@ -505,6 +531,8 @@ onBeforeUnmount(() => { endMove(); endPan(); endCreation(); URL.revokeObjectURL(
|
||||
.region:not(.selected) .resize-handle { display: none; }
|
||||
.region.selected { outline: 3px solid white; outline-offset: 2px; }
|
||||
.region.selected:not(.region-line) { z-index: 4; }
|
||||
.region-preview { z-index: 5; border-style: dashed; border-width: 2px; border-color: #fbbf24; background: rgb(245 158 11 / .18); color: #fef3c7; cursor: default; pointer-events: auto; }
|
||||
.region-preview .region-label { background: #a16207; }
|
||||
.canvas-stage.drawing .region { pointer-events: none; }
|
||||
@media (max-width: 900px) {
|
||||
.canvas-shell { height: auto; min-height: 36rem; }
|
||||
|
||||
+4
-2
@@ -55,14 +55,16 @@ watch(() => props.samples, () => {
|
||||
async function pollIntake(intakeNo: string): Promise<void> {
|
||||
try {
|
||||
const result = await getOrderProfileSampleStatus(intakeNo);
|
||||
if (result.parse_status === 'parsed' && result.document_count > 0) {
|
||||
// 文档记录已落库不等于样本可选;列表接口还要求当前 Layout ready。
|
||||
// 等待同一状态后再刷新,避免把尚未建好表格的文档误报为已完成。
|
||||
if (result.parse_status === 'parsed' && result.document_count > 0 && result.layout_status === 'ready') {
|
||||
pendingIntake.value = { intakeNo, filename: pendingIntake.value?.filename || '', state: 'syncing' };
|
||||
emit('uploaded', intakeNo);
|
||||
// 列表可能比状态接口晚一个轮询周期可见,保持轮询直到父级刷新后精确选中。
|
||||
pollingTimer = window.setTimeout(() => void pollIntake(intakeNo), 1000);
|
||||
return;
|
||||
}
|
||||
if (['failed', 'error'].includes(result.parse_status)) {
|
||||
if (['failed', 'error'].includes(result.parse_status) || result.layout_status === 'failed') {
|
||||
pendingIntake.value = {
|
||||
intakeNo, filename: pendingIntake.value?.filename || '', state: 'failed', errorCode: result.error_code,
|
||||
};
|
||||
|
||||
-280
@@ -1,280 +0,0 @@
|
||||
<!--
|
||||
features/admin/modules/shipping-order-document-profiles/components/VcMergePreviewTable.vue
|
||||
用途:三来源候选合并预览表。严格后端决定 UI,只按后端返回的 resolution/decision_status 着色,
|
||||
绝不 if/else 推导合并结果。
|
||||
依赖:shipping-order-document-profile.vc.types.ts Section E(VCMergedObservationCandidate);
|
||||
所有着色规则由 resolutionClass 查表映射,禁止前端自行推导业务状态。
|
||||
逻辑:只读展示,无 emit。空态显示「暂无预览数据,请点击预览按钮」。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import type { VCMergedObservationCandidate } from '@/features/admin/types/shipping-order-document-profile.vc.types';
|
||||
|
||||
defineProps<{
|
||||
candidates: VCMergedObservationCandidate[];
|
||||
loading?: boolean;
|
||||
}>();
|
||||
|
||||
function sourceColorClass(source: string): string {
|
||||
if (source === 'header_region') return 'vc-map__src-header';
|
||||
if (source === 'table_column') return 'vc-map__src-table';
|
||||
if (source === 'vendor_comments') return 'vc-map__src-vc';
|
||||
return '';
|
||||
}
|
||||
|
||||
function resolutionClass(resolution: string, decisionStatus: string): string {
|
||||
const key = `${resolution}|${decisionStatus}`;
|
||||
const classMap: Record<string, string> = {
|
||||
'needs_review|pending': 'bg-red-50 text-red-700 border-red-200',
|
||||
'needs_review|needs_review': 'bg-red-50 text-red-700 border-red-200',
|
||||
'same_value_merged|accepted': 'bg-emerald-50 text-emerald-700 border-emerald-200',
|
||||
'single_source_direct|accepted': 'bg-green-50 text-green-700 border-green-200',
|
||||
'fill_missing|accepted': 'bg-sky-50 text-sky-700 border-sky-200',
|
||||
'annotation_only_dropped|accepted': 'bg-gray-50 text-gray-500 line-through',
|
||||
'annotation_only_dropped|missing': 'bg-gray-50 text-gray-500 line-through',
|
||||
'invalid_line_reference|blocked': 'bg-gray-50 text-gray-500 line-through',
|
||||
'no_value|missing': 'bg-gray-50 text-gray-500 line-through',
|
||||
};
|
||||
return classMap[key] ?? '';
|
||||
}
|
||||
|
||||
function resolutionBadge(resolution: string): string {
|
||||
const labelMap: Record<string, string> = {
|
||||
same_value_merged: '同值合并',
|
||||
fill_missing: '补空',
|
||||
needs_review: '需复核',
|
||||
no_value: '无值',
|
||||
single_source_direct: '单源直达',
|
||||
annotation_only_dropped: '仅备注(丢弃)',
|
||||
};
|
||||
return labelMap[resolution] ?? resolution;
|
||||
}
|
||||
|
||||
function conflictGroupKey(cand: VCMergedObservationCandidate): string {
|
||||
return `[${cand.target_scope}] ${cand.target_field_code} #${cand.effective_line_no ?? 'H'}`;
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="vc-merge-preview">
|
||||
<div v-if="candidates.length === 0" class="vc-merge-preview__empty">
|
||||
<p v-if="loading">预览加载中…</p>
|
||||
<p v-else>暂无预览数据,请点击预览按钮</p>
|
||||
</div>
|
||||
<div v-else class="vc-merge-preview__body">
|
||||
<div
|
||||
v-for="(cand, i) in candidates"
|
||||
:key="i"
|
||||
class="vc-merge-preview__row"
|
||||
:class="resolutionClass(cand.resolution, cand.decision_status)"
|
||||
>
|
||||
<div class="vc-merge-preview__row-main">
|
||||
<div class="vc-merge-preview__key">
|
||||
<strong>{{ conflictGroupKey(cand) }}</strong>
|
||||
</div>
|
||||
<div class="vc-merge-preview__badge">
|
||||
<span class="vc-merge-preview__resolution" :class="`vc-merge-preview__resolution--${cand.resolution}`">
|
||||
{{ resolutionBadge(cand.resolution) }}
|
||||
</span>
|
||||
<span class="vc-merge-preview__status">
|
||||
{{ cand.decision_status }}
|
||||
</span>
|
||||
</div>
|
||||
<div class="vc-merge-preview__accepted">
|
||||
<template v-if="cand.decision_status === 'needs_review' || cand.resolution === 'needs_review'">
|
||||
<span class="vc-merge-preview__needs-review">
|
||||
⚠ 需人工复核
|
||||
</span>
|
||||
</template>
|
||||
<template v-else>
|
||||
<span v-if="cand.accepted_value !== null && cand.accepted_value !== undefined">
|
||||
accepted_value:<code>{{ cand.accepted_value }}</code>
|
||||
</span>
|
||||
<span v-else class="vc-merge-preview__muted">
|
||||
accepted_value:—
|
||||
</span>
|
||||
</template>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="vc-merge-preview__conflicts">
|
||||
<div class="vc-merge-preview__conflicts-title">
|
||||
来源快照 ({{ cand.source_observations.length }})
|
||||
</div>
|
||||
<ul class="vc-map__src-list">
|
||||
<li
|
||||
v-for="(obs, j) in cand.source_observations"
|
||||
:key="j"
|
||||
:class="sourceColorClass(obs.source)"
|
||||
>
|
||||
<span class="vc-map__src-tag">{{ obs.source }}</span>
|
||||
<code>{{ obs.normalized_value }}</code>
|
||||
<small v-if="obs.format_valid === false" class="vc-map__format-invalid">
|
||||
(format: {{ obs.format_reason_code }})
|
||||
</small>
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
<div v-if="cand.conflicts && cand.conflicts.length > 0" class="vc-merge-preview__conflicts-detail">
|
||||
<details>
|
||||
<summary>冲突详情 ({{ cand.conflicts.length }})</summary>
|
||||
<pre>{{ JSON.stringify(cand.conflicts, null, 2) }}</pre>
|
||||
</details>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.vc-merge-preview {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
}
|
||||
.vc-merge-preview__empty {
|
||||
padding: 20px 10px;
|
||||
text-align: center;
|
||||
color: var(--text-muted);
|
||||
font-size: 0.82rem;
|
||||
border: 1px dashed var(--border-default);
|
||||
border-radius: 6px;
|
||||
}
|
||||
.vc-merge-preview__body {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
}
|
||||
.vc-merge-preview__row {
|
||||
border: 1px solid var(--border-default);
|
||||
border-radius: 8px;
|
||||
padding: 10px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
background: var(--bg-primary);
|
||||
}
|
||||
.vc-merge-preview__row-main {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 10px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.vc-merge-preview__key {
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
.vc-merge-preview__badge {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
}
|
||||
.vc-merge-preview__resolution {
|
||||
display: inline-block;
|
||||
padding: 2px 8px;
|
||||
border-radius: 10px;
|
||||
font-size: 0.72rem;
|
||||
font-weight: 600;
|
||||
border: 1px solid;
|
||||
}
|
||||
.vc-merge-preview__resolution--same_value_merged {
|
||||
background: rgba(16, 185, 129, 0.1);
|
||||
border-color: rgba(16, 185, 129, 0.3);
|
||||
color: #047857;
|
||||
}
|
||||
.vc-merge-preview__resolution--single_source_direct {
|
||||
background: rgba(34, 197, 94, 0.1);
|
||||
border-color: rgba(34, 197, 94, 0.3);
|
||||
color: #15803d;
|
||||
}
|
||||
.vc-merge-preview__resolution--fill_missing {
|
||||
background: rgba(14, 165, 233, 0.1);
|
||||
border-color: rgba(14, 165, 233, 0.3);
|
||||
color: #0369a1;
|
||||
}
|
||||
.vc-merge-preview__resolution--needs_review {
|
||||
background: rgba(239, 68, 68, 0.1);
|
||||
border-color: rgba(239, 68, 68, 0.3);
|
||||
color: #b91c1c;
|
||||
}
|
||||
.vc-merge-preview__resolution--annotation_only_dropped,
|
||||
.vc-merge-preview__resolution--no_value {
|
||||
background: rgba(107, 114, 128, 0.1);
|
||||
border-color: rgba(107, 114, 128, 0.3);
|
||||
color: #4b5563;
|
||||
}
|
||||
.vc-merge-preview__status {
|
||||
font-size: 0.72rem;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
.vc-merge-preview__accepted {
|
||||
font-size: 0.82rem;
|
||||
}
|
||||
.vc-merge-preview__needs-review {
|
||||
color: #b91c1c;
|
||||
font-weight: 600;
|
||||
}
|
||||
.vc-merge-preview__muted {
|
||||
color: var(--text-muted);
|
||||
}
|
||||
.vc-merge-preview__conflicts {
|
||||
padding-top: 6px;
|
||||
border-top: 1px dashed var(--border-default);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
}
|
||||
.vc-merge-preview__conflicts-title {
|
||||
font-size: 0.78rem;
|
||||
font-weight: 600;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
.vc-map__src-list {
|
||||
list-style: none;
|
||||
padding: 0;
|
||||
margin: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
}
|
||||
.vc-map__src-tag {
|
||||
display: inline-block;
|
||||
padding: 1px 6px;
|
||||
border-radius: 10px;
|
||||
font-size: 0.7rem;
|
||||
margin-right: 4px;
|
||||
color: white;
|
||||
}
|
||||
.vc-map__src-header .vc-map__src-tag { background: #3b82f6; }
|
||||
.vc-map__src-table .vc-map__src-tag { background: #10b981; }
|
||||
.vc-map__src-vc .vc-map__src-tag { background: #f59e0b; }
|
||||
.vc-map__format-invalid {
|
||||
color: var(--text-danger);
|
||||
margin-left: 4px;
|
||||
}
|
||||
code {
|
||||
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
|
||||
background: var(--bg-elevated);
|
||||
padding: 1px 4px;
|
||||
border-radius: 3px;
|
||||
font-size: 0.78rem;
|
||||
}
|
||||
.vc-merge-preview__conflicts-detail {
|
||||
margin-top: 4px;
|
||||
}
|
||||
.vc-merge-preview__conflicts-detail summary {
|
||||
cursor: pointer;
|
||||
font-size: 0.75rem;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
.vc-merge-preview__conflicts-detail pre {
|
||||
margin: 6px 0 0 0;
|
||||
padding: 6px;
|
||||
border: 1px solid var(--border-default);
|
||||
border-radius: 4px;
|
||||
background: var(--bg-elevated);
|
||||
font-size: 0.72rem;
|
||||
max-height: 160px;
|
||||
overflow: auto;
|
||||
}
|
||||
</style>
|
||||
-431
@@ -1,431 +0,0 @@
|
||||
<!--
|
||||
features/admin/modules/shipping-order-document-profiles/components/VcNamedRegionBox.vue
|
||||
用途:Vendor Comments 命名区域圈选框——薄封装 OrderProfileDocumentCanvas,维护 dedicated regions。
|
||||
依赖:shipping-order-document-profile.vc.types.ts Section A/H、OrderProfileDocumentCanvas。
|
||||
逻辑:不做任何 save,所有写操作走 emit 父级;region/page_scope/selection_mode 四元组变更触发
|
||||
VCProfileDraftTrigger(reasons: named_region_*),仅负责前端门禁,真实判定在后端。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, ref, watch } from 'vue';
|
||||
import OrderProfileDocumentCanvas from './OrderProfileDocumentCanvas.vue';
|
||||
import type {
|
||||
OrderProfileCanvasRegion,
|
||||
OrderProfilePreviewPageGrant,
|
||||
OrderProfileRelativeRegion,
|
||||
} from '@/features/admin/types/shipping-order-document-profile.types';
|
||||
import type {
|
||||
VCNamedRegion,
|
||||
VCNamedRegionPageScope,
|
||||
VCNamedRegionSelectionMode,
|
||||
VCProfileDraftTrigger,
|
||||
} from '@/features/admin/types/shipping-order-document-profile.vc.types';
|
||||
|
||||
type VCNamedRegionCreatePartial = {
|
||||
label: string;
|
||||
page_scope: VCNamedRegionPageScope;
|
||||
selection_mode: VCNamedRegionSelectionMode;
|
||||
region: OrderProfileRelativeRegion;
|
||||
};
|
||||
|
||||
const props = withDefaults(defineProps<{
|
||||
profileId: number | null;
|
||||
grant?: OrderProfilePreviewPageGrant | null;
|
||||
pageNo: number;
|
||||
pageCount: number;
|
||||
previewPagePath?: string | null;
|
||||
namedRegions: Record<string, VCNamedRegion>;
|
||||
selectedRegionId: string | null;
|
||||
regionOptions?: {
|
||||
page_scope_options?: { value: string; label: string }[];
|
||||
};
|
||||
readonly?: boolean;
|
||||
}>(), {
|
||||
regionOptions: () => ({}),
|
||||
readonly: false,
|
||||
});
|
||||
|
||||
const emit = defineEmits<{
|
||||
'update:namedRegions': [regions: Record<string, VCNamedRegion>];
|
||||
select: [regionId: string];
|
||||
create: [partial: VCNamedRegionCreatePartial];
|
||||
change: [regionId: string, patch: Partial<VCNamedRegion>];
|
||||
delete: [regionId: string];
|
||||
draftRequired: [trigger: VCProfileDraftTrigger];
|
||||
}>();
|
||||
|
||||
const defaultPageScopeOptions = computed(() => {
|
||||
if (props.regionOptions?.page_scope_options?.length) {
|
||||
return props.regionOptions.page_scope_options;
|
||||
}
|
||||
return [
|
||||
{ value: 'first_page', label: '首页' },
|
||||
{ value: 'last_page', label: '末页' },
|
||||
{ value: 'exact_page', label: '指定页' },
|
||||
];
|
||||
});
|
||||
|
||||
const selectionModeOptions: { value: VCNamedRegionSelectionMode; label: string }[] = [
|
||||
{ value: 'fixed_region', label: '固定区域 (box)' },
|
||||
{ value: 'auto_take_last_qualified', label: '取末段合格 (paragraph)' },
|
||||
];
|
||||
|
||||
const selectedOrderRegionId = computed(() => {
|
||||
return props.selectedRegionId ? `vc:${props.selectedRegionId}` : null;
|
||||
});
|
||||
|
||||
const canvasRegions = computed<OrderProfileCanvasRegion[]>(() => {
|
||||
const regions: OrderProfileCanvasRegion[] = [];
|
||||
Object.values(props.namedRegions || {}).forEach((nr) => {
|
||||
let pageNo = props.pageNo;
|
||||
if (nr.page_scope === 'exact_page' && nr.page_no) {
|
||||
pageNo = nr.page_no;
|
||||
}
|
||||
regions.push({
|
||||
id: `vc:${nr.region_id}`,
|
||||
kind: 'order_field',
|
||||
label: nr.label,
|
||||
region: { ...nr.region },
|
||||
pageNo,
|
||||
});
|
||||
});
|
||||
return regions;
|
||||
});
|
||||
|
||||
const priorSnapshot = ref<string>('');
|
||||
|
||||
function snapshotRegions(): string {
|
||||
const entries = Object.entries(props.namedRegions || {})
|
||||
.sort(([a], [b]) => a.localeCompare(b))
|
||||
.map(([id, r]) => `${id}|${r.label}|${r.page_scope}|${r.selection_mode}|${JSON.stringify(r.region)}`);
|
||||
return entries.join('||');
|
||||
}
|
||||
|
||||
watch(() => snapshotRegions(), (next, prev) => {
|
||||
if (!prev || !next || next === prev) return;
|
||||
const prevMap = props.namedRegions || {};
|
||||
const reasons: VCProfileDraftTrigger['reasons'] = [];
|
||||
const prevIds = new Set(Object.keys(prevMap));
|
||||
const nextIds = new Set(Object.keys(prevMap));
|
||||
prevIds.forEach((id) => {
|
||||
if (!nextIds.has(id)) {
|
||||
reasons.push({ kind: 'named_region_removed', region_id: id });
|
||||
}
|
||||
});
|
||||
nextIds.forEach((id) => {
|
||||
if (!prevIds.has(id)) {
|
||||
reasons.push({ kind: 'named_region_added', region_id: id });
|
||||
}
|
||||
});
|
||||
nextIds.forEach((id) => {
|
||||
if (!prevIds.has(id)) return;
|
||||
const prev = prevMap[id];
|
||||
const nextR = prevMap[id];
|
||||
if (!prev || !nextR) return;
|
||||
if (prev.page_scope !== nextR.page_scope) {
|
||||
reasons.push({ kind: 'named_region_scope', region_id: id });
|
||||
}
|
||||
const prevGeo = `${prev.region.x0},${prev.region.y0},${prev.region.x1},${prev.region.y1}`;
|
||||
const nextGeo = `${nextR.region.x0},${nextR.region.y0},${nextR.region.x1},${nextR.region.y1}`;
|
||||
if (prevGeo !== nextGeo) {
|
||||
reasons.push({ kind: 'named_region_geometry', region_id: id });
|
||||
}
|
||||
});
|
||||
if (reasons.length > 0) {
|
||||
emit('draftRequired', {
|
||||
named_regions_changed: true,
|
||||
field_source_mappings_changed: false,
|
||||
requires_draft_reset: true,
|
||||
reasons,
|
||||
});
|
||||
}
|
||||
}, { flush: 'post' });
|
||||
|
||||
priorSnapshot.value = snapshotRegions();
|
||||
|
||||
function onCanvasSelect(regionId: string): void {
|
||||
if (!regionId.startsWith('vc:')) return;
|
||||
emit('select', regionId.slice(3));
|
||||
}
|
||||
|
||||
function onCanvasCreate(region: OrderProfileCanvasRegion['region']): void {
|
||||
const count = Object.keys(props.namedRegions || {}).length;
|
||||
emit('create', {
|
||||
label: `Vendor Comments ${count + 1}`,
|
||||
page_scope: 'first_page',
|
||||
selection_mode: 'fixed_region',
|
||||
region,
|
||||
});
|
||||
}
|
||||
|
||||
function onCanvasChange(regionId: string, region: OrderProfileCanvasRegion['region']): void {
|
||||
if (!regionId.startsWith('vc:')) return;
|
||||
const id = regionId.slice(3);
|
||||
emit('change', id, { region });
|
||||
}
|
||||
|
||||
function updateLabel(regionId: string, label: string): void {
|
||||
emit('change', regionId, { label });
|
||||
}
|
||||
|
||||
function updatePageScope(regionId: string, pageScope: VCNamedRegionPageScope): void {
|
||||
emit('change', regionId, { page_scope: pageScope });
|
||||
}
|
||||
|
||||
function updateSelectionMode(regionId: string, mode: VCNamedRegionSelectionMode): void {
|
||||
emit('change', regionId, { selection_mode: mode });
|
||||
}
|
||||
|
||||
function updatePageNo(regionId: string, pageNo: number | null): void {
|
||||
emit('change', regionId, { page_no: pageNo });
|
||||
}
|
||||
|
||||
function addRegion(): void {
|
||||
const count = Object.keys(props.namedRegions || {}).length;
|
||||
emit('create', {
|
||||
label: `Vendor Comments ${count + 1}`,
|
||||
page_scope: 'first_page',
|
||||
selection_mode: 'fixed_region',
|
||||
region: { x0: 0.1, y0: 0.1, x1: 0.9, y1: 0.15 },
|
||||
});
|
||||
}
|
||||
|
||||
const orderedRegions = computed(() => {
|
||||
return Object.values(props.namedRegions || {}).sort((a, b) => (
|
||||
a.label.localeCompare(b.label)
|
||||
));
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="vc-named-region-box">
|
||||
<div class="vc-named-region-box__toolbar">
|
||||
<button
|
||||
type="button"
|
||||
:disabled="readonly"
|
||||
class="vc-named-region-box__add-btn"
|
||||
@click="addRegion"
|
||||
>
|
||||
新增 Vendor Comments 区域
|
||||
</button>
|
||||
</div>
|
||||
<div class="vc-named-region-box__body">
|
||||
<aside class="vc-named-region-box__sidebar">
|
||||
<ul v-if="orderedRegions.length" class="vc-named-region-box__list">
|
||||
<li
|
||||
v-for="nr in orderedRegions"
|
||||
:key="nr.region_id"
|
||||
class="vc-named-region-box__item"
|
||||
:class="{ 'is-selected': selectedRegionId === nr.region_id }"
|
||||
@click="emit('select', nr.region_id)"
|
||||
>
|
||||
<div class="vc-named-region-box__item-header">
|
||||
<input
|
||||
class="vc-named-region-box__label-input"
|
||||
:disabled="readonly"
|
||||
:value="nr.label"
|
||||
@input="updateLabel(nr.region_id, ($event.target as HTMLInputElement).value)"
|
||||
@click.stop
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
class="vc-named-region-box__delete-btn"
|
||||
:disabled="readonly"
|
||||
@click.stop="emit('delete', nr.region_id)"
|
||||
>
|
||||
×
|
||||
</button>
|
||||
</div>
|
||||
<div class="vc-named-region-box__item-fields">
|
||||
<label>
|
||||
页范围
|
||||
<select
|
||||
:disabled="readonly"
|
||||
:value="nr.page_scope"
|
||||
@change.stop="updatePageScope(nr.region_id, ($event.target as HTMLSelectElement).value as VCNamedRegionPageScope)"
|
||||
>
|
||||
<option
|
||||
v-for="opt in defaultPageScopeOptions"
|
||||
:key="opt.value"
|
||||
:value="opt.value"
|
||||
>
|
||||
{{ opt.label }}
|
||||
</option>
|
||||
</select>
|
||||
</label>
|
||||
<label v-if="nr.page_scope === 'exact_page'">
|
||||
页码
|
||||
<input
|
||||
type="number"
|
||||
min="1"
|
||||
:max="pageCount || undefined"
|
||||
:disabled="readonly"
|
||||
:value="nr.page_no ?? ''"
|
||||
@input.stop="updatePageNo(nr.region_id, ($event.target as HTMLInputElement).value === '' ? null : Number(($event.target as HTMLInputElement).value))"
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
选择模式
|
||||
<select
|
||||
:disabled="readonly"
|
||||
:value="nr.selection_mode"
|
||||
@change.stop="updateSelectionMode(nr.region_id, ($event.target as HTMLSelectElement).value as VCNamedRegionSelectionMode)"
|
||||
>
|
||||
<option
|
||||
v-for="opt in selectionModeOptions"
|
||||
:key="opt.value"
|
||||
:value="opt.value"
|
||||
>
|
||||
{{ opt.label }}
|
||||
</option>
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
</li>
|
||||
</ul>
|
||||
<p v-else class="vc-named-region-box__empty">
|
||||
暂无命名区域,点击上方按钮新增或在画布上拖动圈选。
|
||||
</p>
|
||||
</aside>
|
||||
<div class="vc-named-region-box__canvas">
|
||||
<OrderProfileDocumentCanvas
|
||||
:profile-id="profileId"
|
||||
:grant="grant"
|
||||
:preview-page-path="previewPagePath"
|
||||
:mode="readonly ? 'readonly' : 'edit'"
|
||||
:regions="canvasRegions"
|
||||
:selected-region-id="selectedOrderRegionId"
|
||||
:creation-kind="readonly ? null : 'order_field'"
|
||||
:page-no="pageNo"
|
||||
:page-count="pageCount"
|
||||
@select="onCanvasSelect"
|
||||
@create="onCanvasCreate"
|
||||
@change="onCanvasChange"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.vc-named-region-box {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
min-height: 0;
|
||||
height: 100%;
|
||||
}
|
||||
.vc-named-region-box__toolbar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
.vc-named-region-box__add-btn {
|
||||
padding: 6px 12px;
|
||||
border: 1px solid var(--border-default);
|
||||
border-radius: 6px;
|
||||
background: var(--bg-primary);
|
||||
cursor: pointer;
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
.vc-named-region-box__add-btn:disabled {
|
||||
opacity: 0.6;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
.vc-named-region-box__body {
|
||||
display: grid;
|
||||
grid-template-columns: 280px 1fr;
|
||||
gap: 8px;
|
||||
min-height: 0;
|
||||
flex: 1;
|
||||
}
|
||||
.vc-named-region-box__sidebar {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
overflow: auto;
|
||||
border: 1px solid var(--border-default);
|
||||
border-radius: 6px;
|
||||
padding: 8px;
|
||||
background: var(--bg-elevated);
|
||||
}
|
||||
.vc-named-region-box__list {
|
||||
list-style: none;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
}
|
||||
.vc-named-region-box__item {
|
||||
border: 1px solid var(--border-default);
|
||||
border-radius: 6px;
|
||||
padding: 8px;
|
||||
cursor: pointer;
|
||||
background: var(--bg-primary);
|
||||
}
|
||||
.vc-named-region-box__item.is-selected {
|
||||
border-color: var(--accent-primary);
|
||||
box-shadow: 0 0 0 1px var(--accent-primary);
|
||||
}
|
||||
.vc-named-region-box__item-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
margin-bottom: 6px;
|
||||
}
|
||||
.vc-named-region-box__label-input {
|
||||
flex: 1;
|
||||
padding: 4px 6px;
|
||||
border: 1px solid var(--border-default);
|
||||
border-radius: 4px;
|
||||
font-size: 0.85rem;
|
||||
min-width: 0;
|
||||
}
|
||||
.vc-named-region-box__delete-btn {
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
border: 1px solid var(--border-default);
|
||||
border-radius: 4px;
|
||||
background: var(--bg-primary);
|
||||
cursor: pointer;
|
||||
color: var(--text-danger);
|
||||
}
|
||||
.vc-named-region-box__delete-btn:disabled {
|
||||
opacity: 0.6;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
.vc-named-region-box__item-fields {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
font-size: 0.78rem;
|
||||
}
|
||||
.vc-named-region-box__item-fields label {
|
||||
display: grid;
|
||||
grid-template-columns: 56px 1fr;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
}
|
||||
.vc-named-region-box__item-fields select,
|
||||
.vc-named-region-box__item-fields input {
|
||||
padding: 3px 6px;
|
||||
border: 1px solid var(--border-default);
|
||||
border-radius: 4px;
|
||||
font-size: 0.78rem;
|
||||
min-width: 0;
|
||||
}
|
||||
.vc-named-region-box__empty {
|
||||
margin: 0;
|
||||
color: var(--text-muted);
|
||||
font-size: 0.8rem;
|
||||
text-align: center;
|
||||
padding: 16px 8px;
|
||||
}
|
||||
.vc-named-region-box__canvas {
|
||||
min-height: 0;
|
||||
border: 1px solid var(--border-default);
|
||||
border-radius: 6px;
|
||||
overflow: hidden;
|
||||
background: var(--bg-primary);
|
||||
}
|
||||
</style>
|
||||
-544
@@ -1,544 +0,0 @@
|
||||
<!--
|
||||
features/admin/modules/shipping-order-document-profiles/components/VcSourceMappingPanel.vue
|
||||
用途:薄编排主面板——只做顶层三开关 + 引入 VcSourceMappingSection * 3 + VcSplitRuleEditor
|
||||
(抽屉/modal)+ VcMergePreviewTable。
|
||||
依赖:shipping-order-document-profile.vc.types.ts Section B/C/D/E/H/I;
|
||||
子组件:VcSourceMappingSection、VcSplitRuleEditor、VcMergePreviewTable。
|
||||
逻辑:emit update:definition 写回完整 patch;field_source_mappings 任何改动 + split_rules
|
||||
改动触发 VCProfileDraftTrigger(聚合所有子 trigger)。
|
||||
Props / Emits 保留原来的契约,确保父级零修改可切换。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, ref, watch } from 'vue';
|
||||
import type {
|
||||
VCMergedObservationCandidate,
|
||||
VCProfileDefinitionExtensions,
|
||||
VCProfileDraftTrigger,
|
||||
VCProfileFieldSourceMapping,
|
||||
VCSplitRuleSet,
|
||||
} from '@/features/admin/types/shipping-order-document-profile.vc.types';
|
||||
import VcSourceMappingSection from './VcSourceMappingSection.vue';
|
||||
import VcSplitRuleEditor from './VcSplitRuleEditor.vue';
|
||||
import VcMergePreviewTable from './VcMergePreviewTable.vue';
|
||||
|
||||
type VCProfileFieldSourceMappingPatch = Partial<VCProfileFieldSourceMapping>;
|
||||
|
||||
const props = withDefaults(defineProps<{
|
||||
definition: VCProfileDefinitionExtensions;
|
||||
selectedFieldCode: string;
|
||||
targetScopes?: Array<'header' | 'line'>;
|
||||
readonly?: boolean;
|
||||
documentId: number;
|
||||
profileId: number;
|
||||
dirtyUnsaved?: boolean;
|
||||
persistedConfirmed?: boolean;
|
||||
canPreview?: boolean;
|
||||
}>(), {
|
||||
selectedFieldCode: 'reservation_id',
|
||||
targetScopes: () => ['header', 'line'],
|
||||
readonly: false,
|
||||
dirtyUnsaved: false,
|
||||
persistedConfirmed: false,
|
||||
canPreview: true,
|
||||
});
|
||||
|
||||
const emit = defineEmits<{
|
||||
'update:definition': [patch: VCProfileDefinitionExtensions];
|
||||
draftRequired: [trigger: VCProfileDraftTrigger];
|
||||
'vc:split-panel-confirmed': [
|
||||
rules: VCSplitRuleSet[],
|
||||
confirmationTokens: Record<string, string>,
|
||||
fieldCode: string,
|
||||
];
|
||||
}>();
|
||||
|
||||
function newClientId(): string {
|
||||
return `map-${crypto.randomUUID().replace(/-/g, '')}`;
|
||||
}
|
||||
|
||||
const DEFAULT_FORMAT_POLICY = {
|
||||
mode: 'inherit_global' as const,
|
||||
pattern: null,
|
||||
max_capture_groups: 1,
|
||||
timeout_ms: 500,
|
||||
case_sensitive: false,
|
||||
};
|
||||
|
||||
const EMPTY_MAPPING_BASE = (fieldCode: string, targetScope: 'header' | 'line'): VCProfileFieldSourceMapping => ({
|
||||
mapping_id: newClientId(),
|
||||
target_scope: targetScope,
|
||||
target_field_code: fieldCode,
|
||||
target_field_id: '',
|
||||
header_source_enabled: false,
|
||||
header_source_ref: null,
|
||||
header_normalizer_key: null,
|
||||
table_source_enabled: false,
|
||||
table_column_code: null,
|
||||
vendor_comments_enabled: false,
|
||||
vendor_comments_region_ref: null,
|
||||
vendor_comments_split_rule_set: null,
|
||||
relation_policy: 'bind_target_line',
|
||||
missing_relation_policy: 'default_all_lines',
|
||||
line_reference_basis: 'classified_logical_line_no',
|
||||
fill_missing_from_other_sources: true,
|
||||
format_policy: { ...DEFAULT_FORMAT_POLICY },
|
||||
});
|
||||
|
||||
const activeMappings = computed(() => {
|
||||
const list = props.definition?.field_source_mappings || [];
|
||||
return list.filter((m) => m.target_field_code === props.selectedFieldCode);
|
||||
});
|
||||
|
||||
const headerMapping = computed(() => activeMappings.value.find((m) => m.target_scope === 'header') || null);
|
||||
const lineMapping = computed(() => activeMappings.value.find((m) => m.target_scope === 'line') || null);
|
||||
|
||||
const scopeOptions = computed(() => (
|
||||
props.targetScopes.map((s) => ({
|
||||
value: s,
|
||||
label: s === 'header' ? 'Header (订单头)' : 'Line (明细行)',
|
||||
}))
|
||||
));
|
||||
|
||||
const splitEditorVisible = ref(false);
|
||||
const splitEditorScope = ref<'header' | 'line'>('line');
|
||||
|
||||
const splitEditorRuleSet = computed<VCSplitRuleSet | null>(() => {
|
||||
const mapping = splitEditorScope.value === 'header' ? headerMapping.value : lineMapping.value;
|
||||
return mapping?.vendor_comments_split_rule_set ?? null;
|
||||
});
|
||||
|
||||
const mergeLoading = ref(false);
|
||||
const mergePreviewResults = ref<VCMergedObservationCandidate[]>([]);
|
||||
|
||||
function cloneDefinitionForWrite(): VCProfileDefinitionExtensions {
|
||||
return {
|
||||
named_regions: props.definition?.named_regions ? { ...props.definition.named_regions } : null,
|
||||
field_source_mappings: props.definition?.field_source_mappings
|
||||
? props.definition.field_source_mappings.map((m) => ({ ...m }))
|
||||
: [],
|
||||
};
|
||||
}
|
||||
|
||||
function ensureMapping(scope: 'header' | 'line'): VCProfileFieldSourceMapping {
|
||||
const existing = scope === 'header' ? headerMapping.value : lineMapping.value;
|
||||
if (existing) return existing;
|
||||
const fresh = EMPTY_MAPPING_BASE(props.selectedFieldCode, scope);
|
||||
const patch = cloneDefinitionForWrite();
|
||||
patch.field_source_mappings = [...(patch.field_source_mappings || []), fresh];
|
||||
emit('update:definition', patch);
|
||||
emitDraftTriggerAggregated({
|
||||
reasons: [{ kind: 'field_source_mapping_added', mapping_id: fresh.mapping_id }],
|
||||
changed: true,
|
||||
});
|
||||
return fresh;
|
||||
}
|
||||
|
||||
function updateMapping(mappingId: string, patchFields: VCProfileFieldSourceMappingPatch): void {
|
||||
const patch = cloneDefinitionForWrite();
|
||||
const list = patch.field_source_mappings || [];
|
||||
const idx = list.findIndex((m) => m.mapping_id === mappingId);
|
||||
if (idx < 0) return;
|
||||
const current = list[idx];
|
||||
if (!current) return;
|
||||
const before = JSON.stringify(current);
|
||||
list[idx] = { ...current, ...patchFields };
|
||||
patch.field_source_mappings = list;
|
||||
emit('update:definition', patch);
|
||||
const after = JSON.stringify(list[idx]);
|
||||
if (before === after) return;
|
||||
|
||||
const beforeObj = JSON.parse(before) as VCProfileFieldSourceMapping;
|
||||
const afterObj = JSON.parse(after) as VCProfileFieldSourceMapping;
|
||||
const reasons: VCProfileDraftTrigger['reasons'] = [];
|
||||
|
||||
if (
|
||||
beforeObj.format_policy?.mode !== afterObj.format_policy?.mode
|
||||
|| beforeObj.format_policy?.pattern !== afterObj.format_policy?.pattern
|
||||
|| beforeObj.format_policy?.max_capture_groups !== afterObj.format_policy?.max_capture_groups
|
||||
) {
|
||||
reasons.push({
|
||||
kind: 'field_source_mapping_format_policy_changed',
|
||||
mapping_id: mappingId,
|
||||
});
|
||||
}
|
||||
|
||||
const enabledKeys = [
|
||||
'header_source_enabled',
|
||||
'table_source_enabled',
|
||||
'vendor_comments_enabled',
|
||||
] as const;
|
||||
let hasEnabledChange = false;
|
||||
for (const k of enabledKeys) {
|
||||
if (beforeObj[k] !== afterObj[k]) {
|
||||
hasEnabledChange = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (hasEnabledChange) {
|
||||
reasons.push({
|
||||
kind: 'field_source_mapping_format_policy_changed',
|
||||
mapping_id: mappingId,
|
||||
});
|
||||
}
|
||||
|
||||
if (
|
||||
beforeObj.vendor_comments_region_ref !== afterObj.vendor_comments_region_ref
|
||||
|| beforeObj.table_column_code !== afterObj.table_column_code
|
||||
) {
|
||||
reasons.push({
|
||||
kind: 'field_source_mapping_format_policy_changed',
|
||||
mapping_id: mappingId,
|
||||
});
|
||||
}
|
||||
|
||||
if (reasons.length === 0) {
|
||||
reasons.push({
|
||||
kind: 'field_source_mapping_format_policy_changed',
|
||||
mapping_id: mappingId,
|
||||
});
|
||||
}
|
||||
|
||||
emitDraftTriggerAggregated({ reasons, changed: true });
|
||||
}
|
||||
|
||||
function emitDraftTriggerAggregated(opts: {
|
||||
reasons: VCProfileDraftTrigger['reasons'];
|
||||
changed: boolean;
|
||||
}): void {
|
||||
emit('draftRequired', {
|
||||
named_regions_changed: false,
|
||||
field_source_mappings_changed: opts.changed,
|
||||
requires_draft_reset: true,
|
||||
reasons: opts.reasons,
|
||||
});
|
||||
}
|
||||
|
||||
function handleSectionMappingUpdate(
|
||||
scope: 'header' | 'line',
|
||||
updatedMapping: VCProfileFieldSourceMapping,
|
||||
): void {
|
||||
const patch = cloneDefinitionForWrite();
|
||||
const list = patch.field_source_mappings || [];
|
||||
const idx = list.findIndex((m) => m.mapping_id === updatedMapping.mapping_id);
|
||||
if (idx < 0) {
|
||||
ensureMapping(scope);
|
||||
return;
|
||||
}
|
||||
const before = JSON.stringify(list[idx]);
|
||||
list[idx] = { ...updatedMapping };
|
||||
patch.field_source_mappings = list;
|
||||
emit('update:definition', patch);
|
||||
const after = JSON.stringify(list[idx]);
|
||||
if (before === after) return;
|
||||
|
||||
const beforeObj = JSON.parse(before) as VCProfileFieldSourceMapping;
|
||||
const afterObj = JSON.parse(after) as VCProfileFieldSourceMapping;
|
||||
const reasons: VCProfileDraftTrigger['reasons'] = [];
|
||||
|
||||
if (
|
||||
beforeObj.format_policy?.mode !== afterObj.format_policy?.mode
|
||||
|| beforeObj.format_policy?.pattern !== afterObj.format_policy?.pattern
|
||||
|| beforeObj.format_policy?.max_capture_groups !== afterObj.format_policy?.max_capture_groups
|
||||
) {
|
||||
reasons.push({
|
||||
kind: 'field_source_mapping_format_policy_changed',
|
||||
mapping_id: updatedMapping.mapping_id,
|
||||
});
|
||||
}
|
||||
|
||||
const enabledKeys = [
|
||||
'header_source_enabled',
|
||||
'table_source_enabled',
|
||||
'vendor_comments_enabled',
|
||||
] as const;
|
||||
for (const k of enabledKeys) {
|
||||
if (beforeObj[k] !== afterObj[k]) {
|
||||
reasons.push({
|
||||
kind: 'field_source_mapping_format_policy_changed',
|
||||
mapping_id: updatedMapping.mapping_id,
|
||||
});
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (
|
||||
beforeObj.vendor_comments_region_ref !== afterObj.vendor_comments_region_ref
|
||||
|| beforeObj.table_column_code !== afterObj.table_column_code
|
||||
) {
|
||||
reasons.push({
|
||||
kind: 'field_source_mapping_format_policy_changed',
|
||||
mapping_id: updatedMapping.mapping_id,
|
||||
});
|
||||
}
|
||||
|
||||
if (reasons.length === 0) {
|
||||
reasons.push({
|
||||
kind: 'field_source_mapping_format_policy_changed',
|
||||
mapping_id: updatedMapping.mapping_id,
|
||||
});
|
||||
}
|
||||
|
||||
emitDraftTriggerAggregated({ reasons, changed: true });
|
||||
}
|
||||
|
||||
function openSplitEditor(scope: 'header' | 'line'): void {
|
||||
ensureMapping(scope);
|
||||
splitEditorScope.value = scope;
|
||||
splitEditorVisible.value = true;
|
||||
}
|
||||
|
||||
function handleSplitRuleSetUpdate(updated: VCSplitRuleSet): void {
|
||||
const scope = splitEditorScope.value;
|
||||
const mapping = scope === 'header' ? headerMapping.value : lineMapping.value;
|
||||
if (!mapping) return;
|
||||
updateMapping(mapping.mapping_id, { vendor_comments_split_rule_set: updated });
|
||||
}
|
||||
|
||||
function handleSplitEditorConfirmed(ruleSet: VCSplitRuleSet, previewToken: string): void {
|
||||
emit('vc:split-panel-confirmed',
|
||||
[ruleSet],
|
||||
{ [ruleSet.rule_set_id]: previewToken },
|
||||
props.selectedFieldCode,
|
||||
);
|
||||
splitEditorVisible.value = false;
|
||||
}
|
||||
|
||||
function handleSplitEditorDraftRequired(trigger: VCProfileDraftTrigger): void {
|
||||
emit('draftRequired', {
|
||||
...trigger,
|
||||
reasons: trigger.reasons.map((r) => ({ ...r })),
|
||||
});
|
||||
}
|
||||
|
||||
async function runMergePreview(): Promise<void> {
|
||||
if (props.canPreview === false) return;
|
||||
mergeLoading.value = true;
|
||||
try {
|
||||
// TODO: 后端 API stub,后续接入实际 endpoint
|
||||
// 预期:POST /admin/shipping/document-profiles/{profileId}/documents/{documentId}/preview-merge
|
||||
// 请求体:{ field_code: selectedFieldCode, definition }
|
||||
// 响应:VCMergedObservationCandidate[]
|
||||
mergePreviewResults.value = [];
|
||||
} finally {
|
||||
mergeLoading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
watch(splitEditorVisible, (v) => {
|
||||
if (!v) {
|
||||
// 关闭编辑器时无需特殊处理,ruleSet 已通过 update:ruleSet 实时同步
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="vc-source-mapping">
|
||||
<header class="vc-map__header">
|
||||
<h3 class="vc-map__title">字段来源映射 · {{ selectedFieldCode }}</h3>
|
||||
<div class="vc-map__scope-tabs">
|
||||
<span
|
||||
v-for="s in scopeOptions"
|
||||
:key="s.value"
|
||||
class="vc-map__scope-tab"
|
||||
:class="{ active: (s.value === 'header' ? headerMapping : lineMapping) != null }"
|
||||
>
|
||||
{{ s.label }}
|
||||
</span>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div class="vc-map__scopes">
|
||||
<div
|
||||
v-for="scope in scopeOptions"
|
||||
:key="scope.value"
|
||||
class="vc-map__scope-panel"
|
||||
>
|
||||
<div class="vc-map__scope-header">
|
||||
<strong>{{ scope.label }}</strong>
|
||||
<small v-if="!(scope.value === 'header' ? headerMapping : lineMapping)">
|
||||
(未启用——开启任一来源将自动创建)
|
||||
</small>
|
||||
</div>
|
||||
|
||||
<div class="vc-map__source-groups">
|
||||
<VcSourceMappingSection
|
||||
kind="header_region"
|
||||
:mapping="scope.value === 'header' ? headerMapping : lineMapping"
|
||||
:definition="definition"
|
||||
:readonly="readonly"
|
||||
:mapping-id="(scope.value === 'header' ? headerMapping : lineMapping)?.mapping_id || 'pending'"
|
||||
@update:mapping="(m) => handleSectionMappingUpdate(scope.value, m)"
|
||||
/>
|
||||
|
||||
<VcSourceMappingSection
|
||||
kind="table_column"
|
||||
:mapping="scope.value === 'header' ? headerMapping : lineMapping"
|
||||
:definition="definition"
|
||||
:readonly="readonly"
|
||||
:mapping-id="(scope.value === 'header' ? headerMapping : lineMapping)?.mapping_id || 'pending'"
|
||||
@update:mapping="(m) => handleSectionMappingUpdate(scope.value, m)"
|
||||
/>
|
||||
|
||||
<VcSourceMappingSection
|
||||
kind="vendor_comments"
|
||||
:mapping="scope.value === 'header' ? headerMapping : lineMapping"
|
||||
:definition="definition"
|
||||
:readonly="readonly"
|
||||
:show-split-rules="true"
|
||||
:mapping-id="(scope.value === 'header' ? headerMapping : lineMapping)?.mapping_id || 'pending'"
|
||||
@update:mapping="(m) => handleSectionMappingUpdate(scope.value, m)"
|
||||
@split-editor-open="openSplitEditor(scope.value)"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="splitEditorVisible" class="vc-map__split-editor-wrapper">
|
||||
<VcSplitRuleEditor
|
||||
:rule-set="splitEditorRuleSet"
|
||||
:selected-field-code="selectedFieldCode"
|
||||
:document-id="documentId"
|
||||
:profile-id="profileId"
|
||||
:readonly="readonly"
|
||||
:dirty-unsaved="dirtyUnsaved"
|
||||
:persisted-confirmed="persistedConfirmed"
|
||||
:visible="splitEditorVisible"
|
||||
@update:rule-set="handleSplitRuleSetUpdate"
|
||||
@confirmed="handleSplitEditorConfirmed"
|
||||
@draft-required="handleSplitEditorDraftRequired"
|
||||
/>
|
||||
<div class="vc-map__split-editor-close">
|
||||
<button type="button" @click="splitEditorVisible = false">
|
||||
关闭编辑器
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="vc-map__merge-preview">
|
||||
<div class="vc-map__merge-toolbar">
|
||||
<h4>合并预览(后端决定 UI,禁止前端 if/else 推导)</h4>
|
||||
<button
|
||||
type="button"
|
||||
:disabled="!canPreview || mergeLoading"
|
||||
@click="runMergePreview"
|
||||
>
|
||||
{{ mergeLoading ? '预览中…' : '拉取合并裁决 (stub)' }}
|
||||
</button>
|
||||
</div>
|
||||
<VcMergePreviewTable
|
||||
:candidates="mergePreviewResults"
|
||||
:loading="mergeLoading"
|
||||
/>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.vc-source-mapping {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
min-height: 0;
|
||||
overflow: auto;
|
||||
}
|
||||
.vc-map__header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 8px;
|
||||
}
|
||||
.vc-map__title {
|
||||
margin: 0;
|
||||
font-size: 1rem;
|
||||
font-weight: 600;
|
||||
}
|
||||
.vc-map__scope-tabs {
|
||||
display: flex;
|
||||
gap: 6px;
|
||||
}
|
||||
.vc-map__scope-tab {
|
||||
padding: 4px 10px;
|
||||
border-radius: 12px;
|
||||
border: 1px solid var(--border-default);
|
||||
font-size: 0.78rem;
|
||||
background: var(--bg-elevated);
|
||||
}
|
||||
.vc-map__scope-tab.active {
|
||||
border-color: var(--accent-primary);
|
||||
color: var(--accent-primary);
|
||||
}
|
||||
.vc-map__scopes {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(480px, 1fr));
|
||||
gap: 10px;
|
||||
}
|
||||
.vc-map__scope-panel {
|
||||
border: 1px solid var(--border-default);
|
||||
border-radius: 8px;
|
||||
padding: 10px;
|
||||
background: var(--bg-primary);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
}
|
||||
.vc-map__scope-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
}
|
||||
.vc-map__scope-header small {
|
||||
color: var(--text-muted);
|
||||
}
|
||||
.vc-map__source-groups {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
}
|
||||
.vc-map__split-editor-wrapper {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
padding: 10px;
|
||||
border: 2px solid var(--accent-primary);
|
||||
border-radius: 8px;
|
||||
background: var(--bg-elevated);
|
||||
}
|
||||
.vc-map__split-editor-close {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
}
|
||||
.vc-map__split-editor-close button {
|
||||
padding: 4px 12px;
|
||||
border: 1px solid var(--border-default);
|
||||
border-radius: 4px;
|
||||
background: var(--bg-primary);
|
||||
cursor: pointer;
|
||||
font-size: 0.8rem;
|
||||
}
|
||||
.vc-map__merge-preview {
|
||||
border: 1px solid var(--border-default);
|
||||
border-radius: 8px;
|
||||
padding: 10px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
}
|
||||
.vc-map__merge-toolbar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 8px;
|
||||
}
|
||||
.vc-map__merge-toolbar h4 {
|
||||
margin: 0;
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
.vc-map__merge-toolbar button {
|
||||
padding: 6px 12px;
|
||||
border: 1px solid var(--border-default);
|
||||
border-radius: 6px;
|
||||
background: var(--bg-primary);
|
||||
cursor: pointer;
|
||||
}
|
||||
.vc-map__merge-toolbar button:disabled { opacity: 0.6; cursor: not-allowed; }
|
||||
</style>
|
||||
-393
@@ -1,393 +0,0 @@
|
||||
<!--
|
||||
features/admin/modules/shipping-order-document-profiles/components/VcSourceMappingSection.vue
|
||||
用途:三来源通用配置区(Header/Table/Vendor Comments 每来源的开关+target_scope+relation_policy+missing_relation+format_policy),
|
||||
不包含拆分规则编辑器(Vendor Comments 区的拆分规则编辑按钮仅触发 emit)。
|
||||
依赖:shipping-order-document-profile.vc.types.ts Section B/D/I;
|
||||
由 VcSourceMappingPanel.vue 薄编排主面板统一编排事件。
|
||||
逻辑:任何字段变化通过 update:mapping 发射完整 mapping 对象;
|
||||
Vendor Comments 点击「编辑拆分规则」时触发 split-editor-open。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue';
|
||||
import type {
|
||||
VCLineReferenceBasis,
|
||||
VCMissingRelationPolicy,
|
||||
VCProfileDefinitionExtensions,
|
||||
VCProfileFieldSourceMapping,
|
||||
VCRelationPolicy,
|
||||
VCReservationFormatPolicy,
|
||||
} from '@/features/admin/types/shipping-order-document-profile.vc.types';
|
||||
|
||||
const props = withDefaults(defineProps<{
|
||||
kind: 'header_region' | 'table_column' | 'vendor_comments';
|
||||
mapping: VCProfileFieldSourceMapping | null;
|
||||
definition: VCProfileDefinitionExtensions;
|
||||
readonly?: boolean;
|
||||
showSplitRules?: boolean;
|
||||
mappingId: string;
|
||||
}>(), {
|
||||
readonly: false,
|
||||
showSplitRules: false,
|
||||
});
|
||||
|
||||
const emit = defineEmits<{
|
||||
'update:mapping': [mapping: VCProfileFieldSourceMapping];
|
||||
'split-editor-open': [];
|
||||
}>();
|
||||
|
||||
const enabledKey = computed<'header_source_enabled' | 'table_source_enabled' | 'vendor_comments_enabled'>(() => {
|
||||
if (props.kind === 'header_region') return 'header_source_enabled';
|
||||
if (props.kind === 'table_column') return 'table_source_enabled';
|
||||
return 'vendor_comments_enabled';
|
||||
});
|
||||
|
||||
const isEnabled = computed(() => props.mapping?.[enabledKey.value] ?? false);
|
||||
|
||||
function emitPatch(patch: Partial<VCProfileFieldSourceMapping>): void {
|
||||
if (!props.mapping) return;
|
||||
emit('update:mapping', { ...props.mapping, ...patch });
|
||||
}
|
||||
|
||||
function toggleEnabled(enabled: boolean): void {
|
||||
emitPatch({ [enabledKey.value]: enabled } as Partial<VCProfileFieldSourceMapping>);
|
||||
}
|
||||
|
||||
const namedRegionOptions = computed(() => {
|
||||
const map = props.definition?.named_regions || {};
|
||||
return Object.values(map).map((nr) => ({
|
||||
value: nr.region_id,
|
||||
label: nr.label,
|
||||
}));
|
||||
});
|
||||
|
||||
const scopeOptions = [
|
||||
{ value: 'header' as const, label: 'Header (订单头)' },
|
||||
{ value: 'line' as const, label: 'Line (明细行)' },
|
||||
];
|
||||
|
||||
const relationPolicyOptions: { value: VCRelationPolicy; label: string }[] = [
|
||||
{ value: 'bind_target_line', label: '绑定目标行 (bind_target_line)' },
|
||||
{ value: 'annotation_only', label: '仅备注 (annotation_only)' },
|
||||
{ value: 'no_relation', label: '无关联 (no_relation)' },
|
||||
];
|
||||
|
||||
const missingRelationPolicyOptions: { value: VCMissingRelationPolicy; label: string }[] = [
|
||||
{ value: 'default_all_lines', label: '默认所有行 (default_all_lines)' },
|
||||
{ value: 'default_header_only', label: '默认仅 Header (default_header_only)' },
|
||||
{ value: 'fallback_single_line_when_no_reference', label: '无参考回退单行 (fallback_single_line_when_no_reference)' },
|
||||
];
|
||||
|
||||
const lineReferenceBasisOptions: { value: VCLineReferenceBasis; label: string }[] = [
|
||||
{ value: 'explicit_line_column', label: '显式行列号 (explicit)' },
|
||||
{ value: 'profile_business_line_no', label: '业务行号 (profile_business_line_no)' },
|
||||
{ value: 'classified_logical_line_no', label: '分类逻辑行号 (classified_logical_line_no)' },
|
||||
];
|
||||
|
||||
const kindLabel = computed(() => {
|
||||
if (props.kind === 'header_region') return 'Header 来源';
|
||||
if (props.kind === 'table_column') return 'Table 来源';
|
||||
return 'Vendor Comments 来源';
|
||||
});
|
||||
|
||||
const sourceClass = computed(() => {
|
||||
if (props.kind === 'header_region') return 'vc-map__source--header';
|
||||
if (props.kind === 'table_column') return 'vc-map__source--table';
|
||||
return 'vc-map__source--vc';
|
||||
});
|
||||
|
||||
function updateFormatPolicy(policy: Partial<VCReservationFormatPolicy>): void {
|
||||
if (!props.mapping) return;
|
||||
const next: VCReservationFormatPolicy = {
|
||||
...props.mapping.format_policy,
|
||||
...policy,
|
||||
};
|
||||
emitPatch({ format_policy: next });
|
||||
}
|
||||
|
||||
const targetScopeDisabled = computed(() => {
|
||||
if (props.kind === 'table_column' || props.kind === 'vendor_comments') return true;
|
||||
return false;
|
||||
});
|
||||
|
||||
const showLineReferenceBasis = computed(() => {
|
||||
return props.kind === 'table_column' || props.kind === 'vendor_comments';
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<fieldset class="vc-map__source" :class="sourceClass">
|
||||
<legend>
|
||||
<label class="vc-map__toggle-label">
|
||||
<input
|
||||
type="checkbox"
|
||||
:disabled="readonly"
|
||||
:checked="isEnabled"
|
||||
@change="toggleEnabled(($event.target as HTMLInputElement).checked)"
|
||||
/>
|
||||
{{ kindLabel }}
|
||||
</label>
|
||||
</legend>
|
||||
<template v-if="isEnabled && mapping">
|
||||
<template v-if="kind === 'header_region'">
|
||||
<label>
|
||||
Header 引用键
|
||||
<input
|
||||
:disabled="readonly"
|
||||
:value="mapping.header_source_ref ?? ''"
|
||||
placeholder="header_ref / 留空走自动检测"
|
||||
@input="emitPatch({ header_source_ref: ($event.target as HTMLInputElement).value || null })"
|
||||
/>
|
||||
</label>
|
||||
</template>
|
||||
<template v-else-if="kind === 'table_column'">
|
||||
<label>
|
||||
列 column_code
|
||||
<input
|
||||
:disabled="readonly"
|
||||
:value="mapping.table_column_code ?? ''"
|
||||
placeholder="例如:reservation_id"
|
||||
@input="emitPatch({ table_column_code: ($event.target as HTMLInputElement).value || null })"
|
||||
/>
|
||||
</label>
|
||||
</template>
|
||||
<template v-else-if="kind === 'vendor_comments'">
|
||||
<label>
|
||||
命名区域
|
||||
<select
|
||||
:disabled="readonly"
|
||||
:value="mapping.vendor_comments_region_ref ?? ''"
|
||||
@change="emitPatch({ vendor_comments_region_ref: ($event.target as HTMLSelectElement).value || null })"
|
||||
>
|
||||
<option value="">— 请选择命名区域 —</option>
|
||||
<option v-for="opt in namedRegionOptions" :key="opt.value" :value="opt.value">{{ opt.label }}</option>
|
||||
</select>
|
||||
</label>
|
||||
<div v-if="showSplitRules" class="vc-map__split-open-row">
|
||||
<button
|
||||
type="button"
|
||||
:disabled="readonly"
|
||||
class="vc-map__split-open-btn"
|
||||
@click="emit('split-editor-open')"
|
||||
>
|
||||
编辑拆分规则…
|
||||
</button>
|
||||
<span v-if="mapping.vendor_comments_split_rule_set" class="vc-map__split-status-inline">
|
||||
规则集:v{{ mapping.vendor_comments_split_rule_set.rule_version }}
|
||||
· {{ mapping.vendor_comments_split_rule_set.status || 'draft' }}
|
||||
</span>
|
||||
<span v-else class="vc-map__split-status-inline vc-map__split-status--muted">
|
||||
尚未配置规则集
|
||||
</span>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<label>
|
||||
目标作用域
|
||||
<select
|
||||
:disabled="readonly || targetScopeDisabled"
|
||||
:value="targetScopeDisabled ? 'line' : mapping.target_scope"
|
||||
@change="emitPatch({ target_scope: ($event.target as HTMLSelectElement).value as 'header' | 'line' })"
|
||||
>
|
||||
<option v-for="opt in scopeOptions" :key="opt.value" :value="opt.value">
|
||||
{{ opt.label }}{{ targetScopeDisabled && opt.value === 'line' ? ' (默认)' : '' }}
|
||||
</option>
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
关联策略
|
||||
<select
|
||||
:disabled="readonly"
|
||||
:value="mapping.relation_policy"
|
||||
@change="emitPatch({ relation_policy: ($event.target as HTMLSelectElement).value as VCRelationPolicy })"
|
||||
>
|
||||
<option v-for="opt in relationPolicyOptions" :key="opt.value" :value="opt.value">{{ opt.label }}</option>
|
||||
</select>
|
||||
</label>
|
||||
<template v-if="showLineReferenceBasis">
|
||||
<label>
|
||||
行参考基准
|
||||
<select
|
||||
:disabled="readonly"
|
||||
:value="mapping.line_reference_basis"
|
||||
@change="emitPatch({ line_reference_basis: ($event.target as HTMLSelectElement).value as VCLineReferenceBasis })"
|
||||
>
|
||||
<option v-for="opt in lineReferenceBasisOptions" :key="opt.value" :value="opt.value">{{ opt.label }}</option>
|
||||
</select>
|
||||
</label>
|
||||
</template>
|
||||
<label>
|
||||
缺关联策略
|
||||
<select
|
||||
:disabled="readonly"
|
||||
:value="mapping.missing_relation_policy"
|
||||
@change="emitPatch({ missing_relation_policy: ($event.target as HTMLSelectElement).value as VCMissingRelationPolicy })"
|
||||
>
|
||||
<option v-for="opt in missingRelationPolicyOptions" :key="opt.value" :value="opt.value">{{ opt.label }}</option>
|
||||
</select>
|
||||
</label>
|
||||
<label class="vc-map__checkbox">
|
||||
<input
|
||||
type="checkbox"
|
||||
:disabled="readonly"
|
||||
:checked="mapping.fill_missing_from_other_sources ?? true"
|
||||
@change="emitPatch({ fill_missing_from_other_sources: ($event.target as HTMLInputElement).checked })"
|
||||
/>
|
||||
fill_missing_from_other_sources(从其他来源补空)
|
||||
</label>
|
||||
|
||||
<div class="vc-map__format-block">
|
||||
<div class="vc-map__format-title">格式策略</div>
|
||||
<div class="vc-map__format-radios">
|
||||
<label class="vc-map__radio">
|
||||
<input
|
||||
type="radio"
|
||||
:disabled="readonly"
|
||||
:name="`format-mode-${kind}-${mappingId}`"
|
||||
value="inherit_global"
|
||||
:checked="mapping.format_policy.mode === 'inherit_global'"
|
||||
@change="updateFormatPolicy({ mode: 'inherit_global' })"
|
||||
/>
|
||||
inherit_global(使用 Profile 全局设置)
|
||||
</label>
|
||||
<label class="vc-map__radio">
|
||||
<input
|
||||
type="radio"
|
||||
:disabled="readonly"
|
||||
:name="`format-mode-${kind}-${mappingId}`"
|
||||
value="numeric_5_or_10"
|
||||
:checked="mapping.format_policy.mode === 'numeric_5_or_10'"
|
||||
@change="updateFormatPolicy({ mode: 'numeric_5_or_10' })"
|
||||
/>
|
||||
numeric_5_or_10(单号 5 或 10 位数字)
|
||||
</label>
|
||||
<label class="vc-map__radio">
|
||||
<input
|
||||
type="radio"
|
||||
:disabled="readonly"
|
||||
:name="`format-mode-${kind}-${mappingId}`"
|
||||
value="custom_safe_regex"
|
||||
:checked="mapping.format_policy.mode === 'custom_safe_regex'"
|
||||
@change="updateFormatPolicy({ mode: 'custom_safe_regex' })"
|
||||
/>
|
||||
custom_safe_regex(自定义安全正则)
|
||||
</label>
|
||||
</div>
|
||||
<template v-if="mapping.format_policy.mode === 'custom_safe_regex'">
|
||||
<label>
|
||||
pattern
|
||||
<input
|
||||
:disabled="readonly"
|
||||
:value="mapping.format_policy.pattern ?? ''"
|
||||
placeholder="例如:^[A-Z]?\d{5,10}$"
|
||||
@input="updateFormatPolicy({ pattern: ($event.target as HTMLInputElement).value || null })"
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
max_capture_groups
|
||||
<input
|
||||
type="number"
|
||||
min="0"
|
||||
:disabled="readonly"
|
||||
:value="mapping.format_policy.max_capture_groups ?? 1"
|
||||
@input="updateFormatPolicy({ max_capture_groups: Number(($event.target as HTMLInputElement).value) || 0 })"
|
||||
/>
|
||||
</label>
|
||||
</template>
|
||||
</div>
|
||||
</template>
|
||||
</fieldset>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.vc-map__source {
|
||||
border: 1px solid var(--border-default);
|
||||
border-radius: 6px;
|
||||
padding: 8px 10px;
|
||||
margin: 0;
|
||||
display: grid;
|
||||
gap: 6px;
|
||||
}
|
||||
.vc-map__source--header { border-left: 4px solid #3b82f6; }
|
||||
.vc-map__source--table { border-left: 4px solid #10b981; }
|
||||
.vc-map__source--vc { border-left: 4px solid #f59e0b; }
|
||||
.vc-map__source legend {
|
||||
font-size: 0.82rem;
|
||||
font-weight: 600;
|
||||
padding: 0 4px;
|
||||
}
|
||||
.vc-map__toggle-label {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
cursor: pointer;
|
||||
font-weight: 600;
|
||||
}
|
||||
.vc-map__source label {
|
||||
display: grid;
|
||||
grid-template-columns: 110px 1fr;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
font-size: 0.8rem;
|
||||
}
|
||||
.vc-map__checkbox {
|
||||
grid-template-columns: auto 1fr !important;
|
||||
align-items: center;
|
||||
}
|
||||
.vc-map__radio {
|
||||
grid-template-columns: auto 1fr !important;
|
||||
align-items: center;
|
||||
}
|
||||
.vc-map__format-block {
|
||||
grid-column: 1 / -1;
|
||||
display: grid;
|
||||
gap: 4px;
|
||||
padding: 6px;
|
||||
border: 1px dashed var(--border-default);
|
||||
border-radius: 6px;
|
||||
background: var(--bg-elevated);
|
||||
}
|
||||
.vc-map__format-title {
|
||||
font-size: 0.8rem;
|
||||
font-weight: 600;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
.vc-map__format-radios {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
}
|
||||
.vc-map__source select,
|
||||
.vc-map__source input {
|
||||
padding: 4px 6px;
|
||||
border: 1px solid var(--border-default);
|
||||
border-radius: 4px;
|
||||
font-size: 0.8rem;
|
||||
min-width: 0;
|
||||
}
|
||||
.vc-map__split-open-row {
|
||||
grid-column: 1 / -1;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.vc-map__split-open-btn {
|
||||
padding: 4px 12px;
|
||||
border: 1px solid var(--border-default);
|
||||
border-radius: 4px;
|
||||
background: var(--bg-primary);
|
||||
cursor: pointer;
|
||||
font-size: 0.8rem;
|
||||
}
|
||||
.vc-map__split-open-btn:disabled {
|
||||
opacity: 0.6;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
.vc-map__split-status-inline {
|
||||
font-size: 0.75rem;
|
||||
color: var(--text-primary);
|
||||
}
|
||||
.vc-map__split-status--muted {
|
||||
color: var(--text-muted);
|
||||
}
|
||||
</style>
|
||||
-921
@@ -1,921 +0,0 @@
|
||||
<!--
|
||||
features/admin/modules/shipping-order-document-profiles/components/VcSplitRuleEditor.vue
|
||||
用途:VC 专用拆分规则编辑器(只处理 Section C VCSplit* 类型,不引入任何 XfaSplit*)。
|
||||
复用 XfaSplitRulePanel 的 addRule/matcherFromExtraction/preview/dirty banner 交互模式,
|
||||
但所有类型、常量、stages 全部本地化,类型只用 vc.types.ts Section C。
|
||||
依赖:shipping-order-document-profile.vc.types.ts Section C/J;
|
||||
preview API 为本地 stub,标注后续接入 endpoint。
|
||||
逻辑:split_rules 变化时 emit draftRequired,reason=split_rule_changed;
|
||||
确认前必须先预览(needs_preview → diagnostics → confirm dialog → emit confirmed)。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { ref, watch, computed } from 'vue';
|
||||
import { BusinessError } from '@/shared/api/client';
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
import type {
|
||||
VCProfileDraftTrigger,
|
||||
VCSplitEnginePreviewResult,
|
||||
VCSplitMatcher,
|
||||
VCSplitNormalization,
|
||||
VCSplitRule,
|
||||
VCSplitRuleSet,
|
||||
VCSplitSegment,
|
||||
} from '@/features/admin/types/shipping-order-document-profile.vc.types';
|
||||
|
||||
type ExtractionMode = 'select_line' | 'select_line_range' | 'extract_prefix' | 'regex_capture' | 'substring';
|
||||
|
||||
type VCSplitStageType =
|
||||
| 'split_lines'
|
||||
| 'select_line'
|
||||
| 'select_line_range'
|
||||
| 'extract_prefix'
|
||||
| 'regex_capture'
|
||||
| 'replace'
|
||||
| 'substring'
|
||||
| 'normalize';
|
||||
|
||||
interface VCSplitStage {
|
||||
stage_id: string;
|
||||
type: VCSplitStageType;
|
||||
trim?: boolean;
|
||||
remove_empty_lines?: boolean;
|
||||
line_breaks?: string[];
|
||||
line_index?: number;
|
||||
line_start?: number;
|
||||
line_end?: number;
|
||||
join_with?: 'newline' | 'space' | 'comma';
|
||||
value?: string;
|
||||
separators?: string[];
|
||||
case_sensitive?: boolean;
|
||||
pattern?: string;
|
||||
capture_group?: number;
|
||||
find?: string;
|
||||
replace_with?: string;
|
||||
start?: number;
|
||||
end?: number | null;
|
||||
}
|
||||
|
||||
interface VCSplitRulePatch {
|
||||
order?: number;
|
||||
matcher?: VCSplitMatcher | null;
|
||||
segment?: Partial<VCSplitSegment>;
|
||||
}
|
||||
|
||||
const props = withDefaults(defineProps<{
|
||||
ruleSet: VCSplitRuleSet | null;
|
||||
selectedFieldCode: string;
|
||||
documentId: number;
|
||||
profileId: number;
|
||||
readonly?: boolean;
|
||||
dirtyUnsaved?: boolean;
|
||||
persistedConfirmed?: boolean;
|
||||
visible: boolean;
|
||||
}>(), {
|
||||
selectedFieldCode: 'reservation_id',
|
||||
readonly: false,
|
||||
dirtyUnsaved: false,
|
||||
persistedConfirmed: false,
|
||||
visible: false,
|
||||
});
|
||||
|
||||
const emit = defineEmits<{
|
||||
'update:ruleSet': [ruleSet: VCSplitRuleSet];
|
||||
confirmed: [ruleSet: VCSplitRuleSet, previewToken: string];
|
||||
draftRequired: [trigger: VCProfileDraftTrigger];
|
||||
}>();
|
||||
|
||||
const message = useMessage();
|
||||
|
||||
function newClientId(prefix: 'rs' | 'rule' | 'seg' | 'stage'): string {
|
||||
return `${prefix}-${crypto.randomUUID().replace(/-/g, '')}`;
|
||||
}
|
||||
|
||||
const splitLoading = ref(false);
|
||||
const splitPreview = ref<VCSplitEnginePreviewResult | null>(null);
|
||||
const splitPreviewRuleSetHash = ref<string | null>(null);
|
||||
const splitPreviewConfirmationToken = ref<string | null>(null);
|
||||
const splitCollapsedRules = ref(new Set<string>());
|
||||
const splitAdvancedRules = ref(new Set<string>());
|
||||
|
||||
const showUnsavedConfirmBanner = computed(() => props.dirtyUnsaved && props.persistedConfirmed === false);
|
||||
|
||||
function createDefaultStage(type: VCSplitStageType): VCSplitStage {
|
||||
const stageId = newClientId('stage');
|
||||
if (type === 'split_lines') {
|
||||
return {
|
||||
stage_id: stageId,
|
||||
type,
|
||||
trim: true,
|
||||
remove_empty_lines: true,
|
||||
line_breaks: ['\r\n', '\r', '\n'],
|
||||
};
|
||||
}
|
||||
if (type === 'select_line') return { stage_id: stageId, type, line_index: 1 };
|
||||
if (type === 'select_line_range') return { stage_id: stageId, type, line_start: 1, line_end: 2, join_with: 'newline' };
|
||||
if (type === 'extract_prefix') return {
|
||||
stage_id: stageId,
|
||||
type,
|
||||
value: '',
|
||||
separators: [':', ':'],
|
||||
case_sensitive: false,
|
||||
};
|
||||
if (type === 'regex_capture') return { stage_id: stageId, type, pattern: '', capture_group: 1 };
|
||||
if (type === 'replace') return { stage_id: stageId, type, find: '', replace_with: '' };
|
||||
if (type === 'substring') return { stage_id: stageId, type, start: 0, end: null };
|
||||
return { stage_id: stageId, type: 'normalize', trim: true, remove_empty_lines: true };
|
||||
}
|
||||
|
||||
function createDefaultPipelineStages(lineIndex = 1): VCSplitStage[] {
|
||||
return [
|
||||
createDefaultStage('split_lines'),
|
||||
{ ...createDefaultStage('select_line'), line_index: lineIndex },
|
||||
];
|
||||
}
|
||||
|
||||
function matcherFromExtraction(mode: ExtractionMode, stage: Partial<VCSplitStage>, order: number): VCSplitMatcher {
|
||||
if (mode === 'extract_prefix') {
|
||||
return {
|
||||
type: 'prefix',
|
||||
value: String(stage.value || ''),
|
||||
separators: (stage.separators && stage.separators.length) ? stage.separators : [':', ':'],
|
||||
case_sensitive: Boolean(stage.case_sensitive),
|
||||
};
|
||||
}
|
||||
if (mode === 'regex_capture') {
|
||||
return {
|
||||
type: 'regex',
|
||||
pattern: String(stage.pattern || ''),
|
||||
capture_group: stage.capture_group ?? 1,
|
||||
case_sensitive: Boolean(stage.case_sensitive),
|
||||
};
|
||||
}
|
||||
return {
|
||||
type: 'position',
|
||||
line_index: Number(stage.line_index || stage.line_start || order || 1),
|
||||
};
|
||||
}
|
||||
|
||||
function hashRuleSet(ruleSet: VCSplitRuleSet | null | undefined): string {
|
||||
if (!ruleSet) return '';
|
||||
return JSON.stringify(ruleSet);
|
||||
}
|
||||
|
||||
function invalidatePreview(): void {
|
||||
splitPreview.value = null;
|
||||
splitPreviewRuleSetHash.value = null;
|
||||
splitPreviewConfirmationToken.value = null;
|
||||
}
|
||||
|
||||
function ensureRuleSet(): VCSplitRuleSet {
|
||||
if (props.ruleSet) return props.ruleSet;
|
||||
const ruleSet: VCSplitRuleSet = {
|
||||
rule_set_id: newClientId('rs'),
|
||||
rule_version: 1,
|
||||
normalization: { trim: true, remove_empty_lines: true, line_breaks: ['\r\n', '\r', '\n'] },
|
||||
rules: [],
|
||||
unmatched_line_policy: 'evidence_only',
|
||||
duplicate_match_policy: 'needs_review',
|
||||
same_field_multiple_segment_policy: 'needs_review',
|
||||
source: 'user',
|
||||
status: 'draft',
|
||||
requires_confirmation: true,
|
||||
};
|
||||
emit('update:ruleSet', ruleSet);
|
||||
invalidatePreview();
|
||||
emitDraftTriggerForSplitChanged();
|
||||
return ruleSet;
|
||||
}
|
||||
|
||||
function markRuleSetDirty(ruleSet: VCSplitRuleSet): VCSplitRuleSet {
|
||||
const wasConfirmed = ruleSet.status === 'confirmed' || ruleSet.status === 'published';
|
||||
return {
|
||||
...ruleSet,
|
||||
status: 'draft',
|
||||
requires_confirmation: true,
|
||||
rule_version: wasConfirmed ? ruleSet.rule_version + 1 : ruleSet.rule_version,
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeRuleOrders(rules: VCSplitRule[]): VCSplitRule[] {
|
||||
return [...rules]
|
||||
.sort((a, b) => (a.order ?? 0) - (b.order ?? 0))
|
||||
.map((rule, index) => ({ ...rule, order: index + 1 }));
|
||||
}
|
||||
|
||||
function writeRuleSet(ruleSet: VCSplitRuleSet, emitDraft = true): void {
|
||||
emit('update:ruleSet', ruleSet);
|
||||
invalidatePreview();
|
||||
if (emitDraft) {
|
||||
emitDraftTriggerForSplitChanged();
|
||||
}
|
||||
}
|
||||
|
||||
function applyRuleSetChange(updater: (ruleSet: VCSplitRuleSet) => VCSplitRuleSet): void {
|
||||
const current = ensureRuleSet();
|
||||
writeRuleSet(markRuleSetDirty(updater(current)));
|
||||
}
|
||||
|
||||
function emitDraftTriggerForSplitChanged(): void {
|
||||
const trigger: VCProfileDraftTrigger = {
|
||||
named_regions_changed: false,
|
||||
field_source_mappings_changed: true,
|
||||
requires_draft_reset: true,
|
||||
reasons: [{ kind: 'field_source_mapping_split_rule_changed' }],
|
||||
};
|
||||
emit('draftRequired', trigger);
|
||||
}
|
||||
|
||||
function addRule(): void {
|
||||
if (props.readonly) return;
|
||||
const ruleSet = ensureRuleSet();
|
||||
const order = (ruleSet.rules?.length || 0) + 1;
|
||||
const stages = createDefaultPipelineStages(order);
|
||||
const nextRule: VCSplitRule = {
|
||||
rule_id: newClientId('rule'),
|
||||
order,
|
||||
matcher: matcherFromExtraction('select_line', stages[1] || {}, order),
|
||||
segment: {
|
||||
segment_id: newClientId('seg'),
|
||||
segment_code: '',
|
||||
display_name: '',
|
||||
handling: 'evidence_only',
|
||||
target_field_id: null,
|
||||
target_field_code: props.selectedFieldCode,
|
||||
note: null,
|
||||
},
|
||||
};
|
||||
writeRuleSet(markRuleSetDirty({
|
||||
...ruleSet,
|
||||
rules: normalizeRuleOrders([...(ruleSet.rules || []), nextRule]),
|
||||
}));
|
||||
const next = new Set(splitCollapsedRules.value);
|
||||
next.delete(nextRule.rule_id);
|
||||
splitCollapsedRules.value = next;
|
||||
}
|
||||
|
||||
function deleteRule(ruleId: string): void {
|
||||
applyRuleSetChange((current) => ({
|
||||
...current,
|
||||
rules: normalizeRuleOrders(current.rules.filter((r) => r.rule_id !== ruleId)),
|
||||
}));
|
||||
const next = new Set(splitCollapsedRules.value);
|
||||
next.delete(ruleId);
|
||||
splitCollapsedRules.value = next;
|
||||
}
|
||||
|
||||
function moveRule(ruleId: string, direction: 'up' | 'down'): void {
|
||||
const current = ensureRuleSet();
|
||||
const rules = [...current.rules];
|
||||
const idx = rules.findIndex((r) => r.rule_id === ruleId);
|
||||
if (idx < 0) return;
|
||||
const swapIdx = direction === 'up' ? idx - 1 : idx + 1;
|
||||
if (swapIdx < 0 || swapIdx >= rules.length) return;
|
||||
const currentRule = rules[idx];
|
||||
const swapRule = rules[swapIdx];
|
||||
if (!currentRule || !swapRule) return;
|
||||
[rules[idx], rules[swapIdx]] = [swapRule, currentRule];
|
||||
applyRuleSetChange((rs) => ({ ...rs, rules: normalizeRuleOrders(rules) }));
|
||||
}
|
||||
|
||||
function toggleRule(ruleId: string): void {
|
||||
const next = new Set(splitCollapsedRules.value);
|
||||
if (next.has(ruleId)) next.delete(ruleId);
|
||||
else next.add(ruleId);
|
||||
splitCollapsedRules.value = next;
|
||||
}
|
||||
|
||||
function toggleAdvanced(ruleId: string): void {
|
||||
const next = new Set(splitAdvancedRules.value);
|
||||
if (next.has(ruleId)) next.delete(ruleId);
|
||||
else next.add(ruleId);
|
||||
splitAdvancedRules.value = next;
|
||||
}
|
||||
|
||||
function extractionStage(rule: VCSplitRule): VCSplitStage {
|
||||
if (rule.matcher?.type === 'prefix') {
|
||||
return {
|
||||
...createDefaultStage('extract_prefix'),
|
||||
value: rule.matcher.value ?? undefined,
|
||||
separators: rule.matcher.separators,
|
||||
case_sensitive: rule.matcher.case_sensitive,
|
||||
};
|
||||
}
|
||||
if (rule.matcher?.type === 'regex') {
|
||||
return {
|
||||
...createDefaultStage('regex_capture'),
|
||||
pattern: rule.matcher.pattern ?? undefined,
|
||||
capture_group: rule.matcher.capture_group ?? undefined,
|
||||
case_sensitive: rule.matcher.case_sensitive,
|
||||
};
|
||||
}
|
||||
if (rule.matcher?.type === 'position') {
|
||||
return {
|
||||
...createDefaultStage('select_line'),
|
||||
line_index: rule.matcher.line_index ?? rule.order ?? 1,
|
||||
};
|
||||
}
|
||||
return { ...createDefaultStage('select_line'), line_index: rule.order ?? 1 };
|
||||
}
|
||||
|
||||
function extractionMode(rule: VCSplitRule): ExtractionMode {
|
||||
if (rule.matcher?.type === 'prefix') return 'extract_prefix';
|
||||
if (rule.matcher?.type === 'regex') return 'regex_capture';
|
||||
if (rule.matcher?.type === 'position') return 'select_line';
|
||||
return 'select_line';
|
||||
}
|
||||
|
||||
function updateRule(ruleId: string, patch: VCSplitRulePatch): void {
|
||||
applyRuleSetChange((current) => ({
|
||||
...current,
|
||||
rules: current.rules.map((rule) => {
|
||||
if (rule.rule_id !== ruleId) return rule;
|
||||
return {
|
||||
...rule,
|
||||
...patch,
|
||||
segment: patch.segment ? { ...rule.segment, ...patch.segment } : rule.segment,
|
||||
matcher: patch.matcher !== undefined ? patch.matcher : rule.matcher,
|
||||
};
|
||||
}),
|
||||
}));
|
||||
}
|
||||
|
||||
function changeExtractionMode(rule: VCSplitRule, mode: ExtractionMode): void {
|
||||
const extraction = createDefaultStage(mode);
|
||||
if (mode === 'select_line') extraction.line_index = rule.order ?? 1;
|
||||
if (mode === 'select_line_range') {
|
||||
extraction.line_start = rule.order ?? 1;
|
||||
extraction.line_end = (rule.order ?? 1) + 1;
|
||||
}
|
||||
updateRule(rule.rule_id, {
|
||||
matcher: matcherFromExtraction(mode, extraction, rule.order ?? 1),
|
||||
});
|
||||
}
|
||||
|
||||
function updateExtraction(rule: VCSplitRule, patch: Partial<VCSplitStage>): void {
|
||||
const current = extractionStage(rule);
|
||||
const nextStage = { ...current, ...patch };
|
||||
const mode = extractionMode(rule);
|
||||
updateRule(rule.rule_id, {
|
||||
matcher: matcherFromExtraction(mode, nextStage, rule.order ?? 1),
|
||||
});
|
||||
}
|
||||
|
||||
function updateUnmatchedPolicy(policy: 'evidence_only' | 'needs_review'): void {
|
||||
applyRuleSetChange((current) => ({ ...current, unmatched_line_policy: policy }));
|
||||
}
|
||||
|
||||
function updateNormalization(patch: Partial<VCSplitNormalization>): void {
|
||||
applyRuleSetChange((current) => ({
|
||||
...current,
|
||||
normalization: { ...(current.normalization || {}), ...patch },
|
||||
}));
|
||||
}
|
||||
|
||||
function previewValueFor(rule: VCSplitRule): string | null {
|
||||
const segment = splitPreview.value?.segments?.find((s) => s.rule_id === rule.rule_id);
|
||||
return segment ? (segment.normalized_text || segment.raw_text) : null;
|
||||
}
|
||||
|
||||
function previewLineLabel(lineStart?: number | null, lineEnd?: number | null): string {
|
||||
if (!lineStart) return '—';
|
||||
return lineEnd && lineEnd !== lineStart ? `${lineStart}–${lineEnd}` : String(lineStart);
|
||||
}
|
||||
|
||||
async function runPreview(): Promise<void> {
|
||||
const ruleSet = ensureRuleSet();
|
||||
splitLoading.value = true;
|
||||
try {
|
||||
// TODO: 后端 API stub,后续接入实际 endpoint
|
||||
// 预期:POST /admin/shipping/document-profiles/{profileId}/documents/{documentId}/preview-split
|
||||
// 请求体:{ rule_set: ruleSet, field_code: selectedFieldCode }
|
||||
splitPreview.value = {
|
||||
status: 'parsed',
|
||||
rule_set_id: ruleSet.rule_set_id,
|
||||
rule_version: ruleSet.rule_version,
|
||||
mapped_fields: {},
|
||||
segments: [],
|
||||
evidence_only_segments: [],
|
||||
diagnostics: [],
|
||||
};
|
||||
splitPreviewRuleSetHash.value = hashRuleSet(ruleSet);
|
||||
splitPreviewConfirmationToken.value = `stub-${Date.now()}`;
|
||||
} catch (error) {
|
||||
message.error(error instanceof BusinessError ? error.message : '预览失败');
|
||||
} finally {
|
||||
splitLoading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
function confirmRules(): void {
|
||||
const ruleSet = ensureRuleSet();
|
||||
const currentHash = hashRuleSet(ruleSet);
|
||||
if (!splitPreview.value || splitPreviewRuleSetHash.value !== currentHash || !splitPreviewConfirmationToken.value) {
|
||||
message.error('确认前请先预览当前规则集');
|
||||
return;
|
||||
}
|
||||
if (splitPreview.value.status === 'needs_review' || (splitPreview.value.diagnostics || []).length > 0) {
|
||||
message.error('存在 needs_review 或诊断错误,无法确认');
|
||||
return;
|
||||
}
|
||||
const confirmedRuleSet: VCSplitRuleSet = {
|
||||
...ruleSet,
|
||||
source: 'user',
|
||||
status: 'confirmed',
|
||||
requires_confirmation: false,
|
||||
};
|
||||
emit('update:ruleSet', confirmedRuleSet);
|
||||
emit('confirmed', confirmedRuleSet, splitPreviewConfirmationToken.value);
|
||||
}
|
||||
|
||||
function lineBreaksToDisplay(breaks: string[] | undefined): string {
|
||||
return (breaks || []).map((item) => item
|
||||
.replace(/\\/g, '\\\\')
|
||||
.replace(/\r/g, '\\r')
|
||||
.replace(/\n/g, '\\n')
|
||||
.replace(/\t/g, '\\t')).join(', ');
|
||||
}
|
||||
|
||||
function parseLineBreaks(value: string): string[] {
|
||||
return value.split(',')
|
||||
.map((item) => item.trim())
|
||||
.filter(Boolean)
|
||||
.map((token) => token
|
||||
.replace(/\\r\\n/g, '\r\n')
|
||||
.replace(/\\n/g, '\n')
|
||||
.replace(/\\r/g, '\r')
|
||||
.replace(/\\t/g, '\t')
|
||||
.replace(/\\\\/g, '\\'));
|
||||
}
|
||||
|
||||
function separatorsToString(separators: string[] | undefined): string {
|
||||
return (separators || []).join(', ');
|
||||
}
|
||||
|
||||
function parseSeparators(value: string): string[] {
|
||||
return value.split(',').map((item) => item.trim()).filter(Boolean);
|
||||
}
|
||||
|
||||
watch(() => props.visible, (v) => {
|
||||
if (v) {
|
||||
ensureRuleSet();
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div v-if="visible" class="vc-split-editor">
|
||||
<div v-if="showUnsavedConfirmBanner" class="vc-map__banner" role="status">
|
||||
已确认的规则集有未保存改动,保存后将重置为 Draft。
|
||||
</div>
|
||||
|
||||
<div class="vc-split-editor__header">
|
||||
<h4>拆分规则编辑器 · {{ selectedFieldCode }}</h4>
|
||||
<div class="vc-split-editor__toolbar">
|
||||
<button
|
||||
type="button"
|
||||
:disabled="readonly"
|
||||
@click="addRule()"
|
||||
>
|
||||
新增拆分规则
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
:disabled="splitLoading"
|
||||
@click="runPreview()"
|
||||
>
|
||||
{{ splitLoading ? '预览中…' : '预览拆分' }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
:disabled="readonly || !splitPreview || !splitPreviewConfirmationToken"
|
||||
@click="confirmRules()"
|
||||
>
|
||||
确认规则
|
||||
</button>
|
||||
<span class="vc-map__split-status">
|
||||
状态:{{ ruleSet?.status || 'draft' }}
|
||||
· v{{ ruleSet?.rule_version || 1 }}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<fieldset class="vc-map__split-ruleset">
|
||||
<legend>规则集设置</legend>
|
||||
<label>
|
||||
未匹配策略
|
||||
<select
|
||||
:disabled="readonly"
|
||||
:value="ruleSet?.unmatched_line_policy || 'evidence_only'"
|
||||
@change="updateUnmatchedPolicy(($event.target as HTMLSelectElement).value as 'evidence_only' | 'needs_review')"
|
||||
>
|
||||
<option value="evidence_only">仅留证据 (evidence_only)</option>
|
||||
<option value="needs_review">需复核 (needs_review)</option>
|
||||
</select>
|
||||
</label>
|
||||
<div class="vc-map__split-normalization">
|
||||
<label class="vc-map__checkbox">
|
||||
<input
|
||||
type="checkbox"
|
||||
:disabled="readonly"
|
||||
:checked="ruleSet?.normalization?.trim ?? true"
|
||||
@change="updateNormalization({ trim: ($event.target as HTMLInputElement).checked })"
|
||||
/>
|
||||
trim
|
||||
</label>
|
||||
<label class="vc-map__checkbox">
|
||||
<input
|
||||
type="checkbox"
|
||||
:disabled="readonly"
|
||||
:checked="ruleSet?.normalization?.remove_empty_lines ?? true"
|
||||
@change="updateNormalization({ remove_empty_lines: ($event.target as HTMLInputElement).checked })"
|
||||
/>
|
||||
去空行
|
||||
</label>
|
||||
<label>
|
||||
换行
|
||||
<input
|
||||
:disabled="readonly"
|
||||
:value="lineBreaksToDisplay(ruleSet?.normalization?.line_breaks)"
|
||||
:placeholder="'\r\n, \r, \n'"
|
||||
@change="updateNormalization({ line_breaks: parseLineBreaks(($event.target as HTMLInputElement).value) })"
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
</fieldset>
|
||||
|
||||
<div v-if="splitPreview" class="vc-map__split-preview">
|
||||
<h5>拆分预览(stub,后端 API 待接入)</h5>
|
||||
<p>status: {{ splitPreview.status }}</p>
|
||||
<table v-if="splitPreview.segments?.length" class="vc-map__table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>行</th><th>segment_code</th><th>提取方式</th><th>识别值</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-for="seg in splitPreview.segments" :key="seg.segment_id">
|
||||
<td>{{ previewLineLabel(seg.line_no, seg.line_end_no) }}</td>
|
||||
<td>{{ seg.segment_code }}</td>
|
||||
<td>{{ seg.matcher_type }}</td>
|
||||
<td>{{ seg.normalized_text || seg.raw_text }}</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<ul v-if="splitPreview.diagnostics?.length" class="vc-map__diagnostics">
|
||||
<li v-for="(d, i) in splitPreview.diagnostics" :key="i">
|
||||
<strong>{{ d.code }}</strong>: {{ d.message }}
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<ul class="vc-map__split-rules">
|
||||
<li
|
||||
v-for="(rule, idx) in (ruleSet?.rules || [])"
|
||||
:key="rule.rule_id"
|
||||
>
|
||||
<div class="vc-map__split-rule-header">
|
||||
<button type="button" class="vc-map__split-rule-title" @click="toggleRule(rule.rule_id)">
|
||||
<span>{{ splitCollapsedRules.has(rule.rule_id) ? '›' : '⌄' }}</span>
|
||||
<strong>规则 {{ idx + 1 }}</strong>
|
||||
<span>{{ rule.segment.display_name || rule.segment.segment_code || '未命名' }}</span>
|
||||
</button>
|
||||
<div class="vc-map__split-rule-actions">
|
||||
<button
|
||||
type="button"
|
||||
:disabled="readonly || idx === 0"
|
||||
@click="moveRule(rule.rule_id, 'up')"
|
||||
>
|
||||
↑
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
:disabled="readonly || idx === (ruleSet?.rules?.length || 0) - 1"
|
||||
@click="moveRule(rule.rule_id, 'down')"
|
||||
>
|
||||
↓
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
:disabled="readonly"
|
||||
@click="toggleAdvanced(rule.rule_id)"
|
||||
>
|
||||
{{ splitAdvancedRules.has(rule.rule_id) ? '高级 ▾' : '高级 ▸' }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="danger"
|
||||
:disabled="readonly"
|
||||
@click="deleteRule(rule.rule_id)"
|
||||
>
|
||||
删除
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="!splitCollapsedRules.has(rule.rule_id)" class="vc-map__split-rule-detail">
|
||||
<label>
|
||||
segment_code
|
||||
<input
|
||||
:disabled="readonly"
|
||||
:value="rule.segment.segment_code"
|
||||
@input="updateRule(rule.rule_id, { segment: { segment_code: ($event.target as HTMLInputElement).value } })"
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
display_name
|
||||
<input
|
||||
:disabled="readonly"
|
||||
:value="rule.segment.display_name"
|
||||
@input="updateRule(rule.rule_id, { segment: { display_name: ($event.target as HTMLInputElement).value } })"
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
提取方式
|
||||
<select
|
||||
:disabled="readonly"
|
||||
:value="extractionMode(rule)"
|
||||
@change="changeExtractionMode(rule, ($event.target as HTMLSelectElement).value as ExtractionMode)"
|
||||
>
|
||||
<option value="select_line">按行号 (position)</option>
|
||||
<option value="extract_prefix">按前缀标签 (prefix)</option>
|
||||
<option value="regex_capture">按正则捕获 (regex)</option>
|
||||
</select>
|
||||
</label>
|
||||
<label v-if="extractionMode(rule) === 'select_line'">
|
||||
行号
|
||||
<input
|
||||
type="number"
|
||||
min="1"
|
||||
:disabled="readonly"
|
||||
:value="extractionStage(rule).line_index ?? (rule.order ?? 1)"
|
||||
@input="updateExtraction(rule, { line_index: Number(($event.target as HTMLInputElement).value) || 1 })"
|
||||
/>
|
||||
</label>
|
||||
<template v-if="extractionMode(rule) === 'extract_prefix'">
|
||||
<label>
|
||||
前缀
|
||||
<input
|
||||
:disabled="readonly"
|
||||
:value="extractionStage(rule).value || ''"
|
||||
@input="updateExtraction(rule, { value: ($event.target as HTMLInputElement).value })"
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
分隔符
|
||||
<input
|
||||
:disabled="readonly"
|
||||
:value="separatorsToString(extractionStage(rule).separators)"
|
||||
@input="updateExtraction(rule, { separators: parseSeparators(($event.target as HTMLInputElement).value) })"
|
||||
/>
|
||||
</label>
|
||||
</template>
|
||||
<template v-if="extractionMode(rule) === 'regex_capture'">
|
||||
<label>
|
||||
正则
|
||||
<input
|
||||
:disabled="readonly"
|
||||
:value="extractionStage(rule).pattern || ''"
|
||||
@input="updateExtraction(rule, { pattern: ($event.target as HTMLInputElement).value })"
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
捕获组
|
||||
<input
|
||||
type="number"
|
||||
min="0"
|
||||
:disabled="readonly"
|
||||
:value="extractionStage(rule).capture_group ?? 1"
|
||||
@input="updateExtraction(rule, { capture_group: Number(($event.target as HTMLInputElement).value) || 0 })"
|
||||
/>
|
||||
</label>
|
||||
</template>
|
||||
<div v-if="splitAdvancedRules.has(rule.rule_id)" class="vc-map__split-rule-advanced">
|
||||
<label>
|
||||
handling
|
||||
<select
|
||||
:disabled="readonly"
|
||||
:value="rule.segment.handling"
|
||||
@change="updateRule(rule.rule_id, { segment: { handling: ($event.target as HTMLSelectElement).value as 'mapped' | 'evidence_only' } })"
|
||||
>
|
||||
<option value="evidence_only">仅证据 (evidence_only)</option>
|
||||
<option value="mapped">映射字段 (mapped)</option>
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
note
|
||||
<input
|
||||
:disabled="readonly"
|
||||
:value="rule.segment.note || ''"
|
||||
@input="updateRule(rule.rule_id, { segment: { note: ($event.target as HTMLInputElement).value || null } })"
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
<div class="vc-map__split-inline-preview">
|
||||
<span>识别值:</span>
|
||||
<strong v-if="previewValueFor(rule)">{{ previewValueFor(rule) }}</strong>
|
||||
<span v-else>需预览</span>
|
||||
</div>
|
||||
</div>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.vc-split-editor {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
padding: 10px;
|
||||
border: 1px solid var(--border-default);
|
||||
border-radius: 8px;
|
||||
background: var(--bg-primary);
|
||||
}
|
||||
.vc-split-editor__header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 10px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.vc-split-editor__header h4 {
|
||||
margin: 0;
|
||||
font-size: 0.95rem;
|
||||
}
|
||||
.vc-split-editor__toolbar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.vc-split-editor__toolbar button {
|
||||
padding: 4px 10px;
|
||||
border: 1px solid var(--border-default);
|
||||
border-radius: 4px;
|
||||
background: var(--bg-primary);
|
||||
cursor: pointer;
|
||||
font-size: 0.78rem;
|
||||
}
|
||||
.vc-split-editor__toolbar button:disabled {
|
||||
opacity: 0.6;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
.vc-map__banner {
|
||||
padding: 8px 10px;
|
||||
border-radius: 6px;
|
||||
background: var(--status-warning-bg);
|
||||
color: var(--status-warning-fg);
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
.vc-map__split-status {
|
||||
margin-left: auto;
|
||||
font-size: 0.75rem;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
.vc-map__split-ruleset {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
padding: 6px;
|
||||
border: 1px solid var(--border-default);
|
||||
border-radius: 6px;
|
||||
}
|
||||
.vc-map__split-ruleset legend {
|
||||
font-size: 0.8rem;
|
||||
font-weight: 600;
|
||||
padding: 0 4px;
|
||||
}
|
||||
.vc-map__split-normalization {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
}
|
||||
.vc-map__checkbox {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
font-size: 0.8rem;
|
||||
}
|
||||
.vc-map__split-preview {
|
||||
padding: 6px;
|
||||
border: 1px solid var(--border-default);
|
||||
border-radius: 6px;
|
||||
font-size: 0.78rem;
|
||||
background: var(--bg-primary);
|
||||
}
|
||||
.vc-map__split-preview h5 {
|
||||
margin: 0 0 6px 0;
|
||||
font-size: 0.82rem;
|
||||
}
|
||||
.vc-map__table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
font-size: 0.78rem;
|
||||
}
|
||||
.vc-map__table th,
|
||||
.vc-map__table td {
|
||||
border: 1px solid var(--border-default);
|
||||
padding: 4px 6px;
|
||||
text-align: left;
|
||||
vertical-align: top;
|
||||
}
|
||||
.vc-map__table th {
|
||||
background: var(--bg-elevated);
|
||||
}
|
||||
.vc-map__diagnostics {
|
||||
list-style: none;
|
||||
padding: 0;
|
||||
margin: 6px 0 0 0;
|
||||
color: var(--text-danger);
|
||||
}
|
||||
.vc-map__split-rules {
|
||||
list-style: none;
|
||||
padding: 0;
|
||||
margin: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
}
|
||||
.vc-map__split-rules > li {
|
||||
border: 1px solid var(--border-default);
|
||||
border-radius: 6px;
|
||||
background: var(--bg-primary);
|
||||
}
|
||||
.vc-map__split-rule-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 6px;
|
||||
padding: 6px 8px;
|
||||
}
|
||||
.vc-map__split-rule-title {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
background: none;
|
||||
border: none;
|
||||
cursor: pointer;
|
||||
padding: 2px 4px;
|
||||
font-size: 0.82rem;
|
||||
}
|
||||
.vc-map__split-rule-title span {
|
||||
font-family: monospace;
|
||||
}
|
||||
.vc-map__split-rule-actions {
|
||||
display: flex;
|
||||
gap: 4px;
|
||||
}
|
||||
.vc-map__split-rule-actions button {
|
||||
padding: 2px 8px;
|
||||
border: 1px solid var(--border-default);
|
||||
border-radius: 4px;
|
||||
background: var(--bg-primary);
|
||||
cursor: pointer;
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
.vc-map__split-rule-actions button:disabled {
|
||||
opacity: 0.5;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
.vc-map__split-rule-actions .danger {
|
||||
color: var(--text-danger);
|
||||
}
|
||||
.vc-map__split-rule-detail {
|
||||
padding: 6px 8px;
|
||||
border-top: 1px dashed var(--border-default);
|
||||
display: grid;
|
||||
gap: 6px;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
}
|
||||
.vc-map__split-rule-detail label {
|
||||
display: grid;
|
||||
grid-template-columns: 100px 1fr;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
font-size: 0.78rem;
|
||||
}
|
||||
.vc-map__split-rule-detail select,
|
||||
.vc-map__split-rule-detail input,
|
||||
.vc-map__split-ruleset select,
|
||||
.vc-map__split-ruleset input {
|
||||
padding: 4px 6px;
|
||||
border: 1px solid var(--border-default);
|
||||
border-radius: 4px;
|
||||
font-size: 0.78rem;
|
||||
}
|
||||
.vc-map__split-rule-advanced {
|
||||
grid-column: 1 / -1;
|
||||
display: grid;
|
||||
gap: 6px;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
padding: 6px;
|
||||
border: 1px dashed var(--border-default);
|
||||
border-radius: 4px;
|
||||
background: var(--bg-elevated);
|
||||
}
|
||||
.vc-map__split-inline-preview {
|
||||
grid-column: 1 / -1;
|
||||
font-size: 0.78rem;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
.danger { color: var(--text-danger); }
|
||||
</style>
|
||||
+89
@@ -546,6 +546,28 @@ describe('XfaSplitRulePanel', () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it('keeps advanced processing attached to a position matcher rule', async () => {
|
||||
const ruleSet = makePipelineRuleSet({
|
||||
rules: [{
|
||||
...makePipelineRuleSet().rules[0],
|
||||
matcher: { type: 'position', line_index: 3 },
|
||||
}],
|
||||
});
|
||||
const wrapper = mountPanel({
|
||||
definition: { ...baseDefinition, split_rules: [ruleSet] },
|
||||
});
|
||||
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,
|
||||
@@ -577,6 +599,73 @@ describe('XfaSplitRulePanel', () => {
|
||||
expect(previewMock).toHaveBeenCalledWith(85, expect.not.objectContaining({ reveal: expect.anything() }));
|
||||
});
|
||||
|
||||
it('sends formal matcher post-processors instead of UI-only pipeline fields to preview', async () => {
|
||||
previewMock.mockResolvedValue({
|
||||
preview: { status: 'ok', mapped_fields: {}, segments: [], evidence_only_segments: [], diagnostics: [] },
|
||||
});
|
||||
const wrapper = mountPanel({
|
||||
definition: {
|
||||
...baseDefinition,
|
||||
split_rules: [makePipelineRuleSet({
|
||||
strategy: 'pipeline',
|
||||
rules: [{
|
||||
...makePipelineRuleSet().rules[0],
|
||||
order: 3,
|
||||
matcher: { type: 'position', line_index: 3 },
|
||||
stages: [
|
||||
{ stage_id: 'split', type: 'split_lines', line_breaks: ['\\n'] },
|
||||
{ stage_id: 'line', type: 'select_line', line_index: 3 },
|
||||
{ stage_id: 'mpn', type: 'extract_prefix', value: 'MPN', separators: [':', ':'] },
|
||||
],
|
||||
}],
|
||||
})],
|
||||
},
|
||||
});
|
||||
|
||||
await exposedActions(wrapper).runPreview();
|
||||
await flushPromises();
|
||||
|
||||
expect(previewMock).toHaveBeenCalledWith(85, expect.objectContaining({
|
||||
rule_set: expect.objectContaining({
|
||||
rules: [expect.objectContaining({
|
||||
matcher: expect.objectContaining({
|
||||
type: 'position',
|
||||
line_index: 3,
|
||||
post_processors: [{ type: 'prefix', value: 'MPN', separators: [':', ':'], case_sensitive: false }],
|
||||
}),
|
||||
})],
|
||||
}),
|
||||
}));
|
||||
const request = previewMock.mock.calls[0]?.[1] as { rule_set: Record<string, unknown> };
|
||||
expect(request.rule_set).not.toHaveProperty('strategy');
|
||||
expect(request.rule_set.rules[0]).not.toHaveProperty('order');
|
||||
expect(request.rule_set.rules[0]).not.toHaveProperty('stages');
|
||||
});
|
||||
|
||||
it('reprojects saved formal post-processors into the advanced editor', async () => {
|
||||
const wrapper = mountPanel({
|
||||
definition: {
|
||||
...baseDefinition,
|
||||
split_rules: [makePipelineRuleSet({
|
||||
rules: [{
|
||||
...makePipelineRuleSet().rules[0],
|
||||
stages: [],
|
||||
matcher: {
|
||||
type: 'position',
|
||||
line_index: 3,
|
||||
post_processors: [{ type: 'prefix', value: 'MPN', separators: [':', ':'] }],
|
||||
},
|
||||
}],
|
||||
})],
|
||||
},
|
||||
});
|
||||
|
||||
const advancedButton = wrapper.findAll('button').find((btn) => btn.text().includes('高级处理'));
|
||||
await advancedButton!.trigger('click');
|
||||
|
||||
expect(wrapper.findAll('input').some((input) => input.element.value === 'MPN')).toBe(true);
|
||||
});
|
||||
|
||||
it('ignores exposed edit actions when canEdit is false', () => {
|
||||
const wrapper = mountPanel({ canEdit: false });
|
||||
exposedActions(wrapper).addRule();
|
||||
|
||||
+89
-27
@@ -2,8 +2,8 @@
|
||||
features/admin/modules/shipping-order-document-profiles/components/XfaSplitRulePanel.vue
|
||||
用途:XFA 字段拆分规则编辑——matcher 优先(prefix/regex/position),兼容历史 stages[] 投影。
|
||||
依赖:shipping-order-document-profile API、vue-i18n、Schema 字段列表。
|
||||
逻辑:编辑 definition.split_rules;新增/改提取方式同步写入 matcher;stages 保留供 UI 与兼容预览;
|
||||
确认前须预览当前 rule_set 哈希;预览直接返回完整识别值。
|
||||
逻辑:编辑 definition.split_rules;新增/改提取方式同步写入 matcher;stages 仅保留编辑态;
|
||||
预览和确认统一投影为正式 matcher DTO,确认前须校验同一正式 DTO 哈希。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref, watch } from 'vue';
|
||||
@@ -106,8 +106,38 @@ function newClientId(prefix: 'seg' | 'rule' | 'stage'): string {
|
||||
* 对 rule_set 做 JSON 哈希,用于确认前校验预览是否针对当前规则集。
|
||||
*/
|
||||
function hashRuleSet(ruleSet: XfaSplitRuleSet | null | undefined): string {
|
||||
if (!ruleSet) return '';
|
||||
return JSON.stringify(ruleSet);
|
||||
return JSON.stringify(toFormalRuleSet(ruleSet));
|
||||
}
|
||||
|
||||
/**
|
||||
* 将编辑器的历史 pipeline 投影为后端正式规则;不把 UI 排序/阶段字段送入业务契约。
|
||||
* 当前已正式支持的高级语义只有“标签后取值”;其余高级阶段必须先在契约中实现,不能静默丢失。
|
||||
*/
|
||||
function toFormalRuleSet(ruleSet: XfaSplitRuleSet | null | undefined): Record<string, unknown> | null {
|
||||
if (!ruleSet) return null;
|
||||
const rules = (ruleSet.rules || []).map((rule) => {
|
||||
const unsupported = advancedStages(rule).find((stage) => stage.type !== 'extract_prefix');
|
||||
if (unsupported) {
|
||||
throw new Error(`Unsupported formal post processor: ${unsupported.type}`);
|
||||
}
|
||||
const postProcessors = advancedStages(rule).map((stage) => ({
|
||||
type: 'prefix' as const,
|
||||
value: String(stage.value || ''),
|
||||
separators: (stage.separators && stage.separators.length) ? stage.separators : [':', ':'],
|
||||
case_sensitive: Boolean(stage.case_sensitive),
|
||||
}));
|
||||
return {
|
||||
rule_id: rule.rule_id,
|
||||
matcher: { ...(rule.matcher || matcherFromExtraction(extractionMode(rule), extractionStage(rule), rule.order || 1)), ...(postProcessors.length ? { post_processors: postProcessors } : {}) },
|
||||
segment: rule.segment,
|
||||
};
|
||||
});
|
||||
const { strategy: _strategy, rule_id, rule_set_id, ...formal } = ruleSet;
|
||||
return {
|
||||
...formal,
|
||||
rule_set_id: rule_set_id || rule_id,
|
||||
rules,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -275,9 +305,10 @@ async function runPreview(): Promise<void> {
|
||||
if (!props.selectedPathId || !activeRuleSet.value || props.canPreview === false) return;
|
||||
loading.value = true;
|
||||
try {
|
||||
const formalRuleSet = toFormalRuleSet(activeRuleSet.value);
|
||||
const result = await previewOrderProfileSampleXfaSplitRules(props.documentId, {
|
||||
path_id: props.selectedPathId,
|
||||
rule_set: activeRuleSet.value as unknown as Record<string, unknown>,
|
||||
rule_set: formalRuleSet || {},
|
||||
profile_id: props.profileId,
|
||||
});
|
||||
preview.value = result.preview;
|
||||
@@ -321,16 +352,16 @@ function confirmRules(): void {
|
||||
diagnostics: diagCount,
|
||||
});
|
||||
if (!window.confirm(summary)) return;
|
||||
const confirmedRuleSet: XfaSplitRuleSet = {
|
||||
...activeRuleSet.value,
|
||||
const confirmedRuleSet = {
|
||||
...(toFormalRuleSet(activeRuleSet.value) || {}),
|
||||
source: 'user',
|
||||
status: 'confirmed',
|
||||
requires_confirmation: false,
|
||||
};
|
||||
} as XfaSplitRuleSet;
|
||||
const confirmedRules = [
|
||||
...(props.definition.split_rules || []).filter(
|
||||
(item) => item.source_path_id !== confirmedRuleSet.source_path_id,
|
||||
),
|
||||
...(props.definition.split_rules || [])
|
||||
.filter((item) => item.source_path_id !== confirmedRuleSet.source_path_id)
|
||||
.map((item) => toFormalRuleSet(item) as unknown as XfaSplitRuleSet),
|
||||
confirmedRuleSet,
|
||||
];
|
||||
const tokens = { [confirmedRuleSet.source_path_id]: previewConfirmationToken.value };
|
||||
@@ -403,6 +434,17 @@ function toggleAdvanced(ruleId: string): void {
|
||||
|
||||
/** 返回规则的业务提取步骤;优先由 matcher 合成,兼容历史 pipeline stages。 */
|
||||
function extractionStage(rule: XfaSplitRule): XfaSplitStage {
|
||||
// 优先使用持久化 stages 中的真实主提取阶段;position matcher 的兼容投影
|
||||
// 不能通过临时 stage_id 定位,否则高级处理无法挂接到规则 2。
|
||||
const stages = rule.stages || [];
|
||||
const persisted = stages.find((stage) => (
|
||||
stage.type === 'select_line'
|
||||
|| stage.type === 'select_line_range'
|
||||
|| stage.type === 'extract_prefix'
|
||||
|| stage.type === 'regex_capture'
|
||||
|| stage.type === 'substring'
|
||||
));
|
||||
if (persisted && (!rule.matcher || rule.matcher.type === 'position')) return persisted;
|
||||
if (rule.matcher?.type === 'prefix') {
|
||||
return {
|
||||
...createDefaultStage('extract_prefix'),
|
||||
@@ -425,14 +467,7 @@ function extractionStage(rule: XfaSplitRule): XfaSplitStage {
|
||||
line_index: rule.matcher.line_index ?? rule.order ?? 1,
|
||||
};
|
||||
}
|
||||
const stages = rule.stages || [];
|
||||
return stages.find((stage) => (
|
||||
stage.type === 'select_line'
|
||||
|| stage.type === 'select_line_range'
|
||||
|| stage.type === 'extract_prefix'
|
||||
|| stage.type === 'regex_capture'
|
||||
|| stage.type === 'substring'
|
||||
)) || { ...createDefaultStage('select_line'), line_index: rule.order ?? 1 };
|
||||
return { ...createDefaultStage('select_line'), line_index: rule.order ?? 1 };
|
||||
}
|
||||
|
||||
function extractionMode(rule: XfaSplitRule): ExtractionMode {
|
||||
@@ -449,15 +484,41 @@ function extractionMode(rule: XfaSplitRule): ExtractionMode {
|
||||
/** 返回主提取之后顺序执行的高级处理步骤。 */
|
||||
function advancedStages(rule: XfaSplitRule): XfaSplitStage[] {
|
||||
const stages = rule.stages || [];
|
||||
if (!stages.length) {
|
||||
return (rule.matcher?.post_processors || []).map((processor, index) => ({
|
||||
stage_id: `formal-${rule.rule_id}-post-${index}`,
|
||||
type: 'extract_prefix' as const,
|
||||
value: processor.value,
|
||||
separators: processor.separators,
|
||||
case_sensitive: processor.case_sensitive,
|
||||
}));
|
||||
}
|
||||
const primary = extractionStage(rule);
|
||||
const primaryIndex = stages.findIndex((stage) => stage.stage_id === primary.stage_id);
|
||||
if (primaryIndex < 0) return [];
|
||||
return stages.slice(primaryIndex + 1);
|
||||
}
|
||||
|
||||
/** 将已保存的正式规则按需投影为可编辑 pipeline;只有用户编辑时才写回 stages。 */
|
||||
function editableStages(rule: XfaSplitRule): XfaSplitStage[] {
|
||||
if ((rule.stages || []).length) return rule.stages;
|
||||
const primary = extractionStage(rule);
|
||||
return [
|
||||
{
|
||||
stage_id: `formal-${rule.rule_id}-split`,
|
||||
type: 'split_lines',
|
||||
trim: true,
|
||||
remove_empty_lines: true,
|
||||
line_breaks: ['\r\n', '\r', '\n'],
|
||||
},
|
||||
{ ...primary, stage_id: `formal-${rule.rule_id}-primary` },
|
||||
...advancedStages(rule),
|
||||
];
|
||||
}
|
||||
|
||||
/** 更换提取方式,同时同步正式 matcher 与兼容 stages。 */
|
||||
function changeExtractionMode(rule: XfaSplitRule, mode: ExtractionMode): void {
|
||||
const stages = rule.stages || [];
|
||||
const stages = editableStages(rule);
|
||||
const split = stages.find((stage) => stage.type === 'split_lines') || createDefaultStage('split_lines');
|
||||
const advanced = advancedStages(rule);
|
||||
const extraction = createDefaultStage(mode);
|
||||
@@ -484,8 +545,8 @@ function updateExtraction(rule: XfaSplitRule, patch: XfaSplitStagePatch): void {
|
||||
const nextStage = { ...current, ...patch };
|
||||
const mode = extractionMode(rule);
|
||||
updateRule(rule.rule_id, {
|
||||
stages: (rule.stages || []).map((stage) => (
|
||||
stage.stage_id === current.stage_id ? nextStage : stage
|
||||
stages: editableStages(rule).map((stage) => (
|
||||
stage.stage_id === current.stage_id || stage.type === current.type ? { ...nextStage, stage_id: stage.stage_id } : stage
|
||||
)),
|
||||
matcher: matcherFromExtraction(mode, nextStage, rule.order ?? 1),
|
||||
});
|
||||
@@ -587,7 +648,7 @@ function updateNormalization(patch: Partial<XfaSplitNormalization>): void {
|
||||
function addStage(ruleId: string, type: XfaSplitStageType): void {
|
||||
const rule = activeRuleSet.value?.rules.find((item) => item.rule_id === ruleId);
|
||||
if (!rule) return;
|
||||
updateRule(ruleId, { stages: [...(rule.stages || []), createDefaultStage(type)] });
|
||||
updateRule(ruleId, { stages: [...editableStages(rule), createDefaultStage(type)] });
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -595,8 +656,9 @@ function addStage(ruleId: string, type: XfaSplitStageType): void {
|
||||
*/
|
||||
function deleteStage(ruleId: string, stageId: string): void {
|
||||
const rule = activeRuleSet.value?.rules.find((item) => item.rule_id === ruleId);
|
||||
if (!rule || (rule.stages || []).length <= 1) return;
|
||||
updateRule(ruleId, { stages: rule.stages.filter((item) => item.stage_id !== stageId) });
|
||||
const stages = rule ? editableStages(rule) : [];
|
||||
if (!rule || stages.length <= 1) return;
|
||||
updateRule(ruleId, { stages: stages.filter((item) => item.stage_id !== stageId) });
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -605,7 +667,7 @@ function deleteStage(ruleId: string, stageId: string): void {
|
||||
function moveStage(ruleId: string, stageId: string, direction: -1 | 1): void {
|
||||
const rule = activeRuleSet.value?.rules.find((item) => item.rule_id === ruleId);
|
||||
if (!rule) return;
|
||||
const stages = [...(rule.stages || [])];
|
||||
const stages = [...editableStages(rule)];
|
||||
const index = stages.findIndex((item) => item.stage_id === stageId);
|
||||
const target = index + direction;
|
||||
if (index < 0 || target < 0 || target >= stages.length) return;
|
||||
@@ -624,7 +686,7 @@ function updateStage(ruleId: string, stageId: string, patch: XfaSplitStagePatch)
|
||||
const rule = activeRuleSet.value?.rules.find((item) => item.rule_id === ruleId);
|
||||
if (!rule) return;
|
||||
updateRule(ruleId, {
|
||||
stages: (rule.stages || []).map((stage) => (
|
||||
stages: editableStages(rule).map((stage) => (
|
||||
stage.stage_id === stageId ? { ...stage, ...patch } : stage
|
||||
)),
|
||||
});
|
||||
|
||||
+21
-3
@@ -365,7 +365,7 @@ describe('useOrderProfileValueAdapter', () => {
|
||||
expect(payload?.definition.bindings.map((item) => item.binding_id)).toEqual(['customer-part', 'internal-part']);
|
||||
});
|
||||
|
||||
it('blocks saving when an existing formal datasets binding has no shared visual layout', async () => {
|
||||
it('restores a missing formal datasets visual layout from the last saved definition', async () => {
|
||||
const enabled = ref(false);
|
||||
const state = ref<'saved' | 'saving' | 'failed' | 'readonly'>('saved');
|
||||
let desk: ReturnType<typeof useOrderProfileValueAdapter> | null = null;
|
||||
@@ -378,6 +378,19 @@ describe('useOrderProfileValueAdapter', () => {
|
||||
|
||||
mount(Harness, { global: { plugins: [i18n] } });
|
||||
await desk?.load();
|
||||
await desk!.applySavedDraft({
|
||||
id: 9,
|
||||
lock_version: 2,
|
||||
definition: {
|
||||
...desk!.definition.value!,
|
||||
order_field_layouts: [{
|
||||
layout_id: 'xfa_header_currency', field_id: 'field-currency', field_code: 'currency', scope: 'header',
|
||||
page_scope: 'exact_page', page_no: 1,
|
||||
anchor_region: { x0: .1, y0: .1, x1: .2, y1: .15 },
|
||||
fallback_value_region: { x0: .2, y0: .1, x1: .4, y1: .15 },
|
||||
}],
|
||||
},
|
||||
} as unknown as import('@/features/admin/types/shipping-order-document-profile.types').ShippingOrderDocumentProfile);
|
||||
desk!.authoritativePathId.value = 'root';
|
||||
desk!.definition.value = {
|
||||
...desk!.definition.value!,
|
||||
@@ -394,8 +407,13 @@ describe('useOrderProfileValueAdapter', () => {
|
||||
|
||||
const payload = desk!.buildDraftPayload(visualDefinition);
|
||||
|
||||
// 关键断言:正式 datasets binding 不得因本次画布缺少其共同框而被静默删除。
|
||||
expect(payload).toBeNull();
|
||||
// 关键断言:正式 datasets binding 的共享框从已保存定义恢复,不再阻断或静默删除。
|
||||
expect(payload?.definition.order_field_layouts).toEqual(expect.arrayContaining([
|
||||
expect.objectContaining({ layout_id: 'xfa_header_currency', field_code: 'currency' }),
|
||||
]));
|
||||
expect(payload?.definition.bindings).toEqual(expect.arrayContaining([
|
||||
expect.objectContaining({ binding_id: 'currency-binding', field_layout_id: 'xfa_header_currency' }),
|
||||
]));
|
||||
});
|
||||
|
||||
it('carries an explicit formal binding deletion through the save payload', async () => {
|
||||
|
||||
+19
@@ -487,6 +487,25 @@ export function useOrderProfileValueAdapter(options: UseOrderProfileValueAdapter
|
||||
header_layouts: (table.header_layouts || []).map(restoreTableLayoutFields),
|
||||
line_layouts: (table.line_layouts || []).map(restoreTableLayoutFields),
|
||||
}));
|
||||
// 正式 datasets binding 的 field_layout_id 是视觉框的稳定身份。当前画布可能因
|
||||
// 自动标注替换、短暂渲染状态或误删遗漏该框;此时恢复最后成功保存的同 ID 订单字段框,
|
||||
// 而不是每次自动保存都报错。显式解绑会先移除 binding,不会走此恢复路径。
|
||||
const savedOrderFieldLayouts = savedSnapshot.value?.order_field_layouts || [];
|
||||
const currentOrderFieldLayoutIds = new Set(
|
||||
restoredOrderFieldLayouts.map((layout) => String(layout.layout_id || '')),
|
||||
);
|
||||
const missingBoundOrderFieldLayoutIds = new Set(
|
||||
(definition.value.bindings || [])
|
||||
.filter((binding) => Boolean(binding.value_binding?.path_id?.trim()))
|
||||
.map((binding) => String(binding.field_layout_id || '').trim())
|
||||
.filter((layoutId) => layoutId && !currentOrderFieldLayoutIds.has(layoutId)),
|
||||
);
|
||||
for (const layout of savedOrderFieldLayouts) {
|
||||
const layoutId = String(layout.layout_id || '').trim();
|
||||
if (!layoutId || !missingBoundOrderFieldLayoutIds.has(layoutId)) continue;
|
||||
restoredOrderFieldLayouts.push(cloneXfaData(layout));
|
||||
currentOrderFieldLayoutIds.add(layoutId);
|
||||
}
|
||||
// 共同视觉身份既包含订单字段,也包含每个明细行布局中的字段;XFA 只能在这份
|
||||
// 既有身份上追加 datasets path,不能只保存订单字段而让明细 binding 静默丢失。
|
||||
const sharedLayouts = [
|
||||
|
||||
+183
@@ -6,6 +6,7 @@
|
||||
*/
|
||||
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { reactive } from 'vue';
|
||||
import {
|
||||
mergeOrderProfileHeaderLabels,
|
||||
restoreOrderProfileRegionPageNo,
|
||||
@@ -13,19 +14,76 @@ import {
|
||||
shouldShowStandardOrderProfilePreview,
|
||||
toOrderProfileAnchorId,
|
||||
buildOrderProfileRecognitionResults,
|
||||
buildOrderProfileCanvasLineFieldValues,
|
||||
selectCurrentDatasetsValidationEvidence,
|
||||
normalizeOrderProfileRelativeRegion,
|
||||
restoreReservationIdRegion,
|
||||
groupUniqueOrderProfileLineFields,
|
||||
restoreFormalBindingFieldCodes,
|
||||
reconcileAutomarkOrderFieldRegions,
|
||||
buildAutomarkSuggestedRegions,
|
||||
normalizeAutomarkFieldCandidates,
|
||||
preferredAutomarkTableSource,
|
||||
selectAutomarkReconstruction,
|
||||
summarizeAutomarkTableCandidates,
|
||||
toOrderProfileHeaderFieldRegion,
|
||||
resolveCoordinateFieldScope,
|
||||
isOrderProfileVisualFieldEligible,
|
||||
buildAutomarkSuggestionSummary,
|
||||
} from './orderProfileForm.utils';
|
||||
|
||||
describe('order profile form rules', () => {
|
||||
it('restores a Reservation ID region from a Vue reactive profile without structured-clone failure', () => {
|
||||
const persisted = reactive({
|
||||
region: { x0: .05, y0: .71, x1: .28, y1: .73 },
|
||||
page_scope: 'exact_page' as const,
|
||||
page_no: 1,
|
||||
});
|
||||
|
||||
const restored = restoreReservationIdRegion(persisted);
|
||||
|
||||
// 关键断言:接口列表响应被 Vue 包装为 Proxy 后,重新打开草稿仍须恢复为可编辑的普通坐标对象。
|
||||
expect(restored).toEqual({
|
||||
region: { x0: .05, y0: .71, x1: .28, y1: .73 },
|
||||
page_scope: 'exact_page',
|
||||
page_no: 1,
|
||||
});
|
||||
});
|
||||
|
||||
it('keeps an automark suggestion audit identity frozen after the canvas page changes', () => {
|
||||
const frozenContext = {
|
||||
documentId: 285,
|
||||
tableId: 'mineru-table-84a701e5693e0907',
|
||||
pageNo: 1,
|
||||
automarkJobId: 7267,
|
||||
};
|
||||
|
||||
const summary = buildAutomarkSuggestionSummary(frozenContext, {
|
||||
regionCount: 3,
|
||||
regionKinds: ['line', 'field', 'field'],
|
||||
evidenceSourceRequired: false,
|
||||
selectedEvidenceSource: 'pdf_coordinate',
|
||||
selectedFieldEvidenceSources: {},
|
||||
});
|
||||
|
||||
// 翻页会更新当前画布状态,但接受建议必须仍携带入队时冻结的 Job 身份。
|
||||
expect(summary).toMatchObject({
|
||||
document_id: 285,
|
||||
table_id: 'mineru-table-84a701e5693e0907',
|
||||
page_no: 1,
|
||||
automark_job_id: 7267,
|
||||
});
|
||||
});
|
||||
|
||||
it('preselects native PDF evidence while allowing OCR fallback', () => {
|
||||
// 关键断言:PDF 只是默认建议;候选列表仍保留 OCR,供人工切换复核。
|
||||
expect(preferredAutomarkTableSource([
|
||||
{ source: 'ocr_coordinate' }, { source: 'pdf_coordinate' },
|
||||
])).toBe('pdf_coordinate');
|
||||
expect(preferredAutomarkTableSource([{ source: 'ocr_coordinate' }])).toBe('ocr_coordinate');
|
||||
expect(preferredAutomarkTableSource([])).toBe('');
|
||||
});
|
||||
|
||||
it('keeps datasets-only Schema fields available for XFA visual positioning only', () => {
|
||||
const datasetsOnly = { enabled: true, allowed_sources: ['xfa_dataset'] };
|
||||
|
||||
@@ -372,6 +430,131 @@ describe('order profile form rules', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('projects Reservation evidence to the header or its referenced logical line', () => {
|
||||
const results = buildOrderProfileRecognitionResults([], [], {
|
||||
table_id: 'table-1', row_count: 3, column_count: 1,
|
||||
rows: [['part_number'], ['PN-1'], ['PN-2']],
|
||||
row_roles: ['header', 'data', 'data'], source_row_indices: [[], [1], [2]], status: 'needs_review',
|
||||
}, 'ready', null, [
|
||||
{ value: '33008', line_no: null, scope: 'header', raw_text: 'Reservation#33008', status: 'header' },
|
||||
{ value: '3000098851', line_no: 1, scope: 'line', raw_text: 'Reservation#3000098851 for line#1', status: 'mapped' },
|
||||
]);
|
||||
|
||||
// 无行号值必须显示在订单表头;带行号值只显示在对应的逻辑明细行。
|
||||
expect(results.header).toContainEqual(expect.objectContaining({
|
||||
fieldCode: 'reservation_id', value: '33008', status: 'read',
|
||||
}));
|
||||
expect(results.line).toContainEqual(expect.objectContaining({
|
||||
fieldCode: 'reservation_id', value: '3000098851', rowNo: 1, status: 'read',
|
||||
}));
|
||||
expect(results.line).not.toContainEqual(expect.objectContaining({
|
||||
fieldCode: 'reservation_id', rowNo: 2,
|
||||
}));
|
||||
});
|
||||
|
||||
it('does not project a Widget row that overlaps the fused table header as a line field', () => {
|
||||
const regions = buildAutomarkSuggestedRegions({
|
||||
reconstruction: {
|
||||
table_id: 'table-1', status: 'needs_review',
|
||||
header_regions: [{
|
||||
region: { x0: .1, y0: .15, x1: .9, y1: .2 },
|
||||
fields: [{
|
||||
text: 'ITEM', field_code: 'line_no',
|
||||
region: { x0: .1, y0: .15, x1: .3, y1: .2 },
|
||||
}],
|
||||
}],
|
||||
// 动态 XFA 的表头控件带有展示值时,Widget 几何会把它误聚为首条明细行。
|
||||
subrow_layouts: [{
|
||||
row_offset: 0, column_boundaries: [0, .25, 1],
|
||||
region: { x0: .1, y0: .15, x1: .9, y1: .2 },
|
||||
suggested_field_codes: ['line_no', null],
|
||||
}],
|
||||
},
|
||||
orderFieldCandidates: [], pageNo: 1,
|
||||
unboundColumnLabel: (count) => `Unbound ${count}`,
|
||||
lineLabel: (count) => `Line ${count}`,
|
||||
});
|
||||
|
||||
// 表头视觉证据已存在时,同一 y 带不能再成为可保存的明细布局。
|
||||
expect(regions.filter((region) => region.kind === 'header_field')).toHaveLength(1);
|
||||
expect(regions.some((region) => region.kind === 'line' || region.kind === 'field')).toBe(false);
|
||||
});
|
||||
|
||||
it('maps reconstructed line values to canvas field region ids', () => {
|
||||
const values = buildOrderProfileCanvasLineFieldValues([
|
||||
{ id: 'line_1_1-field-0', kind: 'field', label: 'customer_po_line_no', fieldCode: 'customer_po_line_no', pageNo: 1, parentId: 'line_1_1', region: { x0: .1, y0: .3, x1: .2, y1: .4 } },
|
||||
{ id: 'line_1_1-field-1', kind: 'field', label: 'qty', fieldCode: 'qty', pageNo: 1, parentId: 'line_1_1', region: { x0: .2, y0: .3, x1: .3, y1: .4 } },
|
||||
], {
|
||||
table_id: 'table-1', row_count: 2, column_count: 2,
|
||||
rows: [['customer_po_line_no', 'qty'], ['10', '3.000']],
|
||||
row_roles: ['header', 'data'], source_row_indices: [[], [1]], status: 'needs_review',
|
||||
});
|
||||
|
||||
expect(values).toEqual({
|
||||
'line_1_1-field-0': '10',
|
||||
'line_1_1-field-1': '3.000',
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
it('restores a formal datasets field only for the same automark line and column', () => {
|
||||
const existing = [{
|
||||
id: 'line_1_1-field-2', kind: 'field' as const, parentId: 'line_1_1',
|
||||
fieldCode: 'qty', label: 'qty', pageNo: 1,
|
||||
region: { x0: .3, y0: .3, x1: .4, y1: .4 },
|
||||
}];
|
||||
const suggested = [{
|
||||
id: 'line_1_1-field-2', kind: 'field' as const, parentId: 'line_1_1',
|
||||
fieldCode: null, label: 'Unbound 2', pageNo: 1,
|
||||
region: { x0: .3, y0: .3, x1: .4, y1: .4 },
|
||||
}, {
|
||||
id: 'line_1_1-field-3', kind: 'field' as const, parentId: 'line_1_1',
|
||||
fieldCode: null, label: 'Unbound 3', pageNo: 1,
|
||||
region: { x0: .4, y0: .3, x1: .5, y1: .4 },
|
||||
}];
|
||||
|
||||
const restored = restoreFormalBindingFieldCodes(existing, suggested, new Set(['line_1_1:qty']));
|
||||
|
||||
// 关键断言:同一稳定区域才可恢复字段身份,新增列仍保持待人工绑定。
|
||||
expect(restored.map((region) => region.fieldCode)).toEqual(['qty', null]);
|
||||
});
|
||||
|
||||
it('reuses an existing formal XFA order-field identity instead of adding a duplicate', () => {
|
||||
const existing = [{
|
||||
id: 'order_field_1_7', kind: 'order_field' as const, label: 'PO', pageNo: 1,
|
||||
orderFieldId: 'order_field_1_7', fieldCode: 'customer_po_number',
|
||||
region: { x0: .4, y0: .1, x1: .8, y1: .16 },
|
||||
}];
|
||||
const suggested = [{
|
||||
id: 'order_field_1_customer_po_number_1', kind: 'order_field' as const, label: 'PO', pageNo: 1,
|
||||
orderFieldId: 'order_field_1_customer_po_number_1', fieldCode: 'customer_po_number',
|
||||
region: { x0: .4, y0: .1, x1: .8, y1: .16 },
|
||||
}];
|
||||
|
||||
const reconciled = reconcileAutomarkOrderFieldRegions(existing, suggested);
|
||||
|
||||
// 关键断言:同页、同字段、同视觉框必须继续使用正式 datasets 引用的 layout ID。
|
||||
expect(reconciled[0]).toMatchObject({ id: 'order_field_1_7', orderFieldId: 'order_field_1_7' });
|
||||
});
|
||||
|
||||
it('does not reuse a formal identity when the same field moved to a different visual box', () => {
|
||||
const existing = [{
|
||||
id: 'order_field_1_7', kind: 'order_field' as const, label: 'PO', pageNo: 1,
|
||||
orderFieldId: 'order_field_1_7', fieldCode: 'customer_po_number',
|
||||
region: { x0: .4, y0: .1, x1: .8, y1: .16 },
|
||||
}];
|
||||
const suggested = [{
|
||||
id: 'order_field_1_customer_po_number_1', kind: 'order_field' as const, label: 'PO', pageNo: 1,
|
||||
orderFieldId: 'order_field_1_customer_po_number_1', fieldCode: 'customer_po_number',
|
||||
region: { x0: .4, y0: .3, x1: .8, y1: .36 },
|
||||
}];
|
||||
|
||||
const reconciled = reconcileAutomarkOrderFieldRegions(existing, suggested);
|
||||
|
||||
// 关键断言:视觉位置发生实质变化时保留新候选,避免把正式绑定静默迁移到错误区域。
|
||||
expect(reconciled[0]?.id).toBe('order_field_1_customer_po_number_1');
|
||||
});
|
||||
|
||||
it('preserves the backend evidence source when projecting automark field candidates', () => {
|
||||
const candidates = normalizeAutomarkFieldCandidates([{
|
||||
candidate_kind: 'field_binding',
|
||||
|
||||
+281
-10
@@ -112,6 +112,88 @@ export const groupUniqueOrderProfileLineFields = (
|
||||
return { fieldsByLayout, boundRegionIds };
|
||||
};
|
||||
|
||||
/**
|
||||
* 在接受新自动标注前恢复已有 XFA 正式绑定的共同视觉字段身份。
|
||||
* 核心逻辑:只允许同一行布局、同一自动列序号的候选继承字段码;缺少该严格对应关系时
|
||||
* 保持未绑定,避免把 datasets 正式路径错误迁移到另一列。
|
||||
* @param existingRegions - 当前已保存或待保存的画布区域。
|
||||
* @param suggestedRegions - 当前待接受的自动标注区域。
|
||||
* @param formalBindingLayoutIds - 已存在正式 datasets binding 的 field_layout_id 集合。
|
||||
* @returns 仅补回可严格证明身份的候选字段码。
|
||||
*/
|
||||
export const restoreFormalBindingFieldCodes = (
|
||||
existingRegions: OrderProfileCanvasRegion[],
|
||||
suggestedRegions: OrderProfileCanvasRegion[],
|
||||
formalBindingLayoutIds: ReadonlySet<string>,
|
||||
): OrderProfileCanvasRegion[] => {
|
||||
const fieldCodeByRegionId = new Map<string, string>();
|
||||
for (const region of existingRegions) {
|
||||
if (region.kind !== 'field' || !region.parentId || !region.fieldCode) continue;
|
||||
const layoutId = `${region.parentId}:${region.fieldCode}`;
|
||||
if (formalBindingLayoutIds.has(layoutId)) fieldCodeByRegionId.set(region.id, region.fieldCode);
|
||||
}
|
||||
return suggestedRegions.map((region) => {
|
||||
if (region.kind !== 'field' || region.fieldCode) return region;
|
||||
const fieldCode = fieldCodeByRegionId.get(region.id);
|
||||
return fieldCode ? { ...region, fieldCode } : region;
|
||||
});
|
||||
};
|
||||
|
||||
/** 自动候选与既有共同订单字段框被视为同一视觉证据的最小 IoU。 */
|
||||
const AUTOMARK_ORDER_FIELD_IDENTITY_IOU = 0.98;
|
||||
|
||||
/**
|
||||
* 将自动标注的共同订单字段对账到已有画布视觉身份。
|
||||
* 核心逻辑:datasets binding 以 field_layout_id 引用视觉框。自动候选的临时 ID 不可
|
||||
* 替代该身份;只有同页、同字段码且几何几乎完全一致时,才继承既有 layout ID。
|
||||
* @param existingRegions - 当前画布中已保存的区域。
|
||||
* @param suggestedRegions - 自动标注产生的待接受区域。
|
||||
* @returns 复用既有 order_field ID 后的候选;坐标变化的候选保持原 ID 供人工复核。
|
||||
*/
|
||||
export const reconcileAutomarkOrderFieldRegions = (
|
||||
existingRegions: OrderProfileCanvasRegion[],
|
||||
suggestedRegions: OrderProfileCanvasRegion[],
|
||||
): OrderProfileCanvasRegion[] => {
|
||||
const usedExistingIds = new Set<string>();
|
||||
const matchingExistingId = (suggested: OrderProfileCanvasRegion): string | null => {
|
||||
if (suggested.kind !== 'order_field' || !suggested.fieldCode) return null;
|
||||
const candidates = existingRegions.filter((existing) => {
|
||||
if (usedExistingIds.has(existing.id) || existing.kind !== 'order_field') return false;
|
||||
if (existing.pageNo !== suggested.pageNo || existing.fieldCode !== suggested.fieldCode) return false;
|
||||
const left = Math.max(existing.region.x0, suggested.region.x0);
|
||||
const top = Math.max(existing.region.y0, suggested.region.y0);
|
||||
const right = Math.min(existing.region.x1, suggested.region.x1);
|
||||
const bottom = Math.min(existing.region.y1, suggested.region.y1);
|
||||
const intersection = Math.max(0, right - left) * Math.max(0, bottom - top);
|
||||
const existingArea = Math.max(0, existing.region.x1 - existing.region.x0) * Math.max(0, existing.region.y1 - existing.region.y0);
|
||||
const suggestedArea = Math.max(0, suggested.region.x1 - suggested.region.x0) * Math.max(0, suggested.region.y1 - suggested.region.y0);
|
||||
const union = existingArea + suggestedArea - intersection;
|
||||
return union > 0 && intersection / union >= AUTOMARK_ORDER_FIELD_IDENTITY_IOU;
|
||||
});
|
||||
if (candidates.length !== 1) return null;
|
||||
usedExistingIds.add(candidates[0]!.id);
|
||||
return candidates[0]!.id;
|
||||
};
|
||||
const layoutIds = new Map<string, string>();
|
||||
suggestedRegions.forEach((region) => {
|
||||
if (region.kind === 'order_field') {
|
||||
const existingId = matchingExistingId(region);
|
||||
if (existingId) layoutIds.set(region.id, existingId);
|
||||
}
|
||||
});
|
||||
return suggestedRegions.map((region) => {
|
||||
if (region.kind === 'order_field' && layoutIds.has(region.id)) {
|
||||
const orderFieldId = layoutIds.get(region.id)!;
|
||||
return { ...region, id: orderFieldId, orderFieldId };
|
||||
}
|
||||
if (region.kind === 'order_anchor' && region.orderFieldId && layoutIds.has(region.orderFieldId)) {
|
||||
const orderFieldId = layoutIds.get(region.orderFieldId)!;
|
||||
return { ...region, id: `${orderFieldId}_anchor`, orderFieldId };
|
||||
}
|
||||
return region;
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* 将画布或历史草稿的区域限制为页面归一化坐标。
|
||||
* @param region - 可能来自拖拽、自动建议或历史模板的页面区域。
|
||||
@@ -129,6 +211,65 @@ export const normalizeOrderProfileRelativeRegion = (
|
||||
return x0 < x1 && y0 < y1 ? { x0, y0, x1, y1 } : null;
|
||||
};
|
||||
|
||||
/**
|
||||
* 从持久化定义恢复 Reservation ID 专用区域。
|
||||
* 核心逻辑:Profile 列表被 Vue 包装后内部对象是 Proxy,不能直接传入 structuredClone;
|
||||
* 此处只读取四个坐标值并构造普通对象,避免草稿重新打开时抛出 DataCloneError。
|
||||
* @param rawRegion - 接口返回的 Reservation 区域,可为 Vue Proxy 或缺省值。
|
||||
* @returns 可编辑的普通区域;定义缺失或坐标无效时返回 null。
|
||||
*/
|
||||
export const restoreReservationIdRegion = (rawRegion: unknown): {
|
||||
region: OrderProfileRelativeRegion;
|
||||
page_scope: 'exact_page';
|
||||
page_no: number;
|
||||
} | null => {
|
||||
if (!rawRegion || typeof rawRegion !== 'object') return null;
|
||||
const record = rawRegion as { region?: OrderProfileRelativeRegion; page_no?: unknown };
|
||||
const region = record.region ? normalizeOrderProfileRelativeRegion(record.region) : null;
|
||||
const pageNo = Number(record.page_no);
|
||||
if (!region || !Number.isInteger(pageNo) || pageNo < 1) return null;
|
||||
return { region, page_scope: 'exact_page', page_no: pageNo };
|
||||
};
|
||||
|
||||
/** 自动标注任务启动时冻结的样本身份;候选在跨页浏览期间不得重新读取可变画布状态。 */
|
||||
export interface AutomarkSuggestionContext {
|
||||
documentId: number;
|
||||
tableId: string;
|
||||
pageNo: number;
|
||||
automarkJobId: number | string;
|
||||
}
|
||||
|
||||
/**
|
||||
* 构造待确认自动标注的审计摘要。
|
||||
* 核心逻辑:Job 已按 document/table/page 冻结证据身份;摘要必须复用同一身份,
|
||||
* 防止管理员翻页或切换表格后,接受请求被服务端判定为另一份 Job 的候选。
|
||||
* @param context - 自动标注入队并成功完成后冻结的样本、页面和 Job 身份。
|
||||
* @param details - 可随管理员选择证据来源而更新的候选描述。
|
||||
* @returns 后端 suggestion decision 契约所需的完整且稳定摘要。
|
||||
*/
|
||||
export const buildAutomarkSuggestionSummary = (
|
||||
context: AutomarkSuggestionContext,
|
||||
details: {
|
||||
regionCount: number;
|
||||
regionKinds: string[];
|
||||
evidenceSourceRequired: boolean;
|
||||
selectedEvidenceSource: string | null;
|
||||
selectedFieldEvidenceSources: Record<string, string>;
|
||||
},
|
||||
): Record<string, unknown> => ({
|
||||
algorithm_version: 'coordinate-suggest-v1',
|
||||
kind: 'page_regions',
|
||||
page_no: context.pageNo,
|
||||
document_id: context.documentId,
|
||||
table_id: context.tableId,
|
||||
automark_job_id: context.automarkJobId,
|
||||
region_count: details.regionCount,
|
||||
region_kinds: details.regionKinds,
|
||||
evidence_source_required: details.evidenceSourceRequired,
|
||||
selected_evidence_source: details.selectedEvidenceSource,
|
||||
selected_field_evidence_sources: details.selectedFieldEvidenceSources,
|
||||
});
|
||||
|
||||
/**
|
||||
* 将统一自动标记结果投影为画布区域。
|
||||
* 核心逻辑:字段视觉候选与行重建是并行证据;行重建缺失时仍保留抬头字段框供人工复核,
|
||||
@@ -146,6 +287,9 @@ export const buildAutomarkSuggestedRegions = (options: {
|
||||
}): OrderProfileCanvasRegion[] => {
|
||||
const { reconstruction, orderFieldCandidates, pageNo, unboundColumnLabel, lineLabel } = options;
|
||||
const suggestedRegions: OrderProfileCanvasRegion[] = [];
|
||||
const headerRegions = (reconstruction?.header_regions || [])
|
||||
.map((header) => header.region)
|
||||
.filter((region): region is OrderProfileRelativeRegion => Boolean(region));
|
||||
for (const [index, header] of (reconstruction?.header_regions || []).entries()) {
|
||||
const headerId = `header_${pageNo}_${index + 1}`;
|
||||
for (const [fieldIndex, field] of (header.fields || []).entries()) {
|
||||
@@ -177,7 +321,21 @@ export const buildAutomarkSuggestedRegions = (options: {
|
||||
}
|
||||
const layouts = (reconstruction?.subrow_layouts || []).slice().sort(
|
||||
(left, right) => left.row_offset - right.row_offset,
|
||||
);
|
||||
).filter((layout) => {
|
||||
const region = layout.region;
|
||||
if (!region) return true;
|
||||
return !headerRegions.some((headerRegion) => {
|
||||
const horizontalOverlap = Math.max(0, Math.min(region.x1, headerRegion.x1) - Math.max(region.x0, headerRegion.x0));
|
||||
const verticalOverlap = Math.max(0, Math.min(region.y1, headerRegion.y1) - Math.max(region.y0, headerRegion.y0));
|
||||
const layoutWidth = region.x1 - region.x0;
|
||||
const headerWidth = headerRegion.x1 - headerRegion.x0;
|
||||
const layoutHeight = region.y1 - region.y0;
|
||||
const headerHeight = headerRegion.y1 - headerRegion.y0;
|
||||
return layoutWidth > 0 && headerWidth > 0 && layoutHeight > 0 && headerHeight > 0
|
||||
&& horizontalOverlap / Math.min(layoutWidth, headerWidth) >= 0.8
|
||||
&& verticalOverlap / Math.min(layoutHeight, headerHeight) >= 0.8;
|
||||
});
|
||||
});
|
||||
for (const layout of layouts) {
|
||||
const lineId = `line_${pageNo}_${layout.row_offset + 1}`;
|
||||
const region = layout.region || {
|
||||
@@ -273,6 +431,19 @@ export const summarizeAutomarkTableCandidates = (
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* 为多来源自动标注候选提供可审阅的默认来源。
|
||||
* 原生 PDF 坐标是首选建议,但这只是预选,不绕过人工接受和 Review 门禁;
|
||||
* 没有原生候选时才使用候选列表中的第一来源。
|
||||
*/
|
||||
export const preferredAutomarkTableSource = (
|
||||
candidates: Array<{ source: string }>,
|
||||
): string => (
|
||||
candidates.find((candidate) => candidate.source === 'pdf_coordinate')?.source
|
||||
|| candidates[0]?.source
|
||||
|| ''
|
||||
);
|
||||
|
||||
/**
|
||||
* 将后端统一 field_binding DTO 转为旧页面候选形状,并保留真实证据来源。
|
||||
* 核心逻辑:只接受视觉 binding;evidence_sources 为空时按不可确认处理,禁止默认宣称 native。
|
||||
@@ -282,9 +453,11 @@ export const summarizeAutomarkTableCandidates = (
|
||||
*/
|
||||
export const normalizeAutomarkFieldCandidates = (
|
||||
candidates: Array<Record<string, unknown>>,
|
||||
): OrderFieldLayoutSuggestion[] => candidates
|
||||
): OrderFieldLayoutSuggestion[] => {
|
||||
const merged = new Map<string, OrderFieldLayoutSuggestion>();
|
||||
candidates
|
||||
.filter((item) => item.candidate_kind === 'field_binding' && item.binding && typeof item.binding === 'object')
|
||||
.map((item) => {
|
||||
.forEach((item) => {
|
||||
const binding = item.binding as Record<string, unknown>;
|
||||
const visual = binding.visual_binding && typeof binding.visual_binding === 'object'
|
||||
? binding.visual_binding as Record<string, unknown> : {};
|
||||
@@ -294,7 +467,7 @@ export const normalizeAutomarkFieldCandidates = (
|
||||
const source = sources[0] === 'ocr_coordinate' || sources[0] === 'acroform_widget'
|
||||
? sources[0] : 'pdf_coordinate';
|
||||
const needsReview = item.needs_review === true || !sources.length;
|
||||
return {
|
||||
const next = {
|
||||
field_id: String(binding.field_id || ''),
|
||||
field_code: String(binding.field_code || ''),
|
||||
// 未匹配的 XFA/AcroForm Widget 只有技术控件名和几何;它必须作为
|
||||
@@ -308,7 +481,17 @@ export const normalizeAutomarkFieldCandidates = (
|
||||
anchor_region: undefined,
|
||||
value_region: visual.normalized_bbox as OrderProfileRelativeRegion | undefined,
|
||||
} satisfies OrderFieldLayoutSuggestion;
|
||||
const bbox = next.value_region;
|
||||
const key = `${next.field_id}|${next.scope}|${JSON.stringify(bbox || {})}`;
|
||||
const previous = merged.get(key);
|
||||
if (previous) {
|
||||
previous.issue = previous.issue || next.issue;
|
||||
return;
|
||||
}
|
||||
merged.set(key, next);
|
||||
});
|
||||
return [...merged.values()];
|
||||
};
|
||||
|
||||
/**
|
||||
* 判断是否显示普通表格预览;可直接创建 Profile 的表格不受上一张表多物理行状态影响。
|
||||
@@ -384,6 +567,48 @@ export interface OrderProfileRecognitionResult {
|
||||
rowNo?: number;
|
||||
}
|
||||
|
||||
/** Reservation 专用证据区域的后端统一候选;前端只按已给出的 scope 投影展示。 */
|
||||
export interface ReservationRegionRecognitionCandidate {
|
||||
value: string;
|
||||
line_no: number | null;
|
||||
scope: 'header' | 'line';
|
||||
raw_text: string;
|
||||
status: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* 将坐标重建的首条数据行映射到画布上的明细字段框。
|
||||
* @param pageRegions - 当前页画布区域。
|
||||
* @param reconstruction - 坐标重建接口返回的表头与数据行。
|
||||
* @returns region id 到当前样本明细值的映射;无值或无匹配框时不返回该项。
|
||||
*/
|
||||
export const buildOrderProfileCanvasLineFieldValues = (
|
||||
pageRegions: OrderProfileCanvasRegion[],
|
||||
reconstruction: CoordinateReconstructionPreview | null,
|
||||
): Record<string, string> => {
|
||||
const regionsByCode = new Map(
|
||||
pageRegions
|
||||
.filter((item) => item.kind === 'field' && item.fieldCode)
|
||||
.reduce<[string, string][]>((entries, item) => {
|
||||
if (!entries.some(([fieldCode]) => fieldCode === item.fieldCode)) {
|
||||
entries.push([item.fieldCode!, item.id]);
|
||||
}
|
||||
return entries;
|
||||
}, []),
|
||||
);
|
||||
if (!reconstruction) return {};
|
||||
const fieldCodes = reconstruction.rows[0] || [];
|
||||
const dataIndex = reconstruction.row_roles.findIndex((role, index) => index > 0 && role === 'data');
|
||||
if (dataIndex < 0) return {};
|
||||
return Object.fromEntries(
|
||||
fieldCodes.flatMap((fieldCode, columnIndex) => {
|
||||
const regionId = regionsByCode.get(fieldCode);
|
||||
const value = reconstruction.rows[dataIndex]?.[columnIndex] || '';
|
||||
return regionId && value ? [[regionId, value] as const] : [];
|
||||
}),
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* 将已有坐标预览和值读取结果变为可反向定位的结构化复核项。
|
||||
* @param pageRegions - 当前页画布区域;未标注字段不会伪装成可定位项。
|
||||
@@ -397,6 +622,7 @@ export const buildOrderProfileRecognitionResults = (
|
||||
reconstruction: CoordinateReconstructionPreview | null,
|
||||
fieldValueState: 'idle' | 'loading' | 'ready' | 'failed' = 'idle',
|
||||
datasetsEvidence: OrderProfileValidationEvidence | null = null,
|
||||
reservationCandidates: ReservationRegionRecognitionCandidate[] = [],
|
||||
): { header: OrderProfileRecognitionResult[]; line: OrderProfileRecognitionResult[] } => {
|
||||
const valuesByCode = new Map(fieldValues.map((item) => [item.field_code, item]));
|
||||
const header = pageRegions
|
||||
@@ -434,9 +660,13 @@ export const buildOrderProfileRecognitionResults = (
|
||||
rowNo: row.row_index + 1,
|
||||
}))
|
||||
));
|
||||
return { header, line };
|
||||
return applyReservationRegionRecognitionResults(
|
||||
header, line, reservationCandidates, datasetsEvidence.lines.length,
|
||||
);
|
||||
}
|
||||
if (!reconstruction) {
|
||||
return applyReservationRegionRecognitionResults(header, [], reservationCandidates, 0);
|
||||
}
|
||||
if (!reconstruction) return { header, line: [] };
|
||||
const fieldCodes = reconstruction.rows[0] || [];
|
||||
const line = reconstruction.rows.slice(1).flatMap((row, rowIndex) => {
|
||||
const sourceIndex = rowIndex + 1;
|
||||
@@ -447,13 +677,54 @@ export const buildOrderProfileRecognitionResults = (
|
||||
key: `${sourceIndex}-${fieldCode}`,
|
||||
fieldCode,
|
||||
value: row[columnIndex] || null,
|
||||
status: role === 'deleted'
|
||||
? 'deleted' as const
|
||||
: row[columnIndex] ? 'read' as const : 'unavailable' as const,
|
||||
status: role === 'deleted'
|
||||
? 'deleted' as const
|
||||
: row[columnIndex] ? 'read' as const : 'unavailable' as const,
|
||||
rowNo: rowIndex + 1,
|
||||
}));
|
||||
});
|
||||
return { header, line };
|
||||
return applyReservationRegionRecognitionResults(
|
||||
header, line, reservationCandidates,
|
||||
reconstruction.row_roles.filter((role) => role === 'data').length,
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* 将服务端已归属的 Reservation 候选投影到右侧正式结果区。
|
||||
*
|
||||
* 这里不解析文本、不猜测行号:无行号候选只进订单表头,带行号候选只进对应
|
||||
* 逻辑明细行。专用区域没有普通字段框,因此条目不可点击定位到字段框。
|
||||
*/
|
||||
const applyReservationRegionRecognitionResults = (
|
||||
header: OrderProfileRecognitionResult[],
|
||||
line: OrderProfileRecognitionResult[],
|
||||
candidates: ReservationRegionRecognitionCandidate[],
|
||||
logicalLineCount: number,
|
||||
): { header: OrderProfileRecognitionResult[]; line: OrderProfileRecognitionResult[] } => {
|
||||
const reservationHeaders = candidates
|
||||
.filter((item) => item.scope === 'header' && item.value)
|
||||
.map((item, index) => ({
|
||||
id: null,
|
||||
key: `reservation-region-header-${index}-${item.value}`,
|
||||
fieldCode: 'reservation_id',
|
||||
value: item.value,
|
||||
status: 'read' as const,
|
||||
}));
|
||||
const reservationLines = candidates.flatMap((item, index) => {
|
||||
if (
|
||||
item.scope !== 'line' || item.line_no === null || !item.value
|
||||
|| item.line_no < 1 || item.line_no > logicalLineCount
|
||||
) return [];
|
||||
return [{
|
||||
id: null,
|
||||
key: `reservation-region-line-${item.line_no}-${index}-${item.value}`,
|
||||
fieldCode: 'reservation_id',
|
||||
value: item.value,
|
||||
status: 'read' as const,
|
||||
rowNo: item.line_no,
|
||||
}];
|
||||
});
|
||||
return { header: [...header, ...reservationHeaders], line: [...line, ...reservationLines] };
|
||||
};
|
||||
|
||||
/**
|
||||
|
||||
@@ -32,7 +32,6 @@ export type ShippingConfigSubModuleId =
|
||||
| 'order_extraction_runs'
|
||||
| 'shipping_audit'
|
||||
| 'process_gates'
|
||||
| 'legacy_stp_jobs'
|
||||
| 'inventory_fields'
|
||||
| 'connections'
|
||||
| 'inventory_sites'
|
||||
|
||||
@@ -60,6 +60,13 @@ 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; }
|
||||
export interface OrderProfileAnchorRule { anchor_id: string; text: string; aliases?: string[]; match_mode: 'exact' | 'contains'; region?: OrderProfileRelativeRegion | null; position_locked?: boolean; minimum_evidence_level: OrderProfileEvidenceLevel; }
|
||||
export type OrderProfileCoordinateModelType = 'legacy' | 'anchor_frame';
|
||||
export interface OrderProfileCoordinateModel {
|
||||
type?: OrderProfileCoordinateModelType;
|
||||
anchors?: OrderProfileAnchorRule[];
|
||||
max_translate_x?: number;
|
||||
max_translate_y?: number;
|
||||
}
|
||||
export interface OrderProfileFieldRegion { field_id: string; field_code: string; scope: 'header' | 'line'; region: OrderProfileRelativeRegion; extractor_key: OrderProfileExtractorKey; allowed_sources: OrderProfileAllowedSource[]; minimum_evidence_level: OrderProfileEvidenceLevel; target_fields?: Array<{ field_id: string; field_code: string; scope: 'header' | 'line' }>; }
|
||||
export interface OrderProfileOrderFieldLayout { layout_id: string; field_id: string; field_code: string; scope: 'header'; page_scope: 'first_page' | 'all_pages' | 'exact_page'; page_no?: number | null; anchor?: OrderProfileAnchorRule | null; value_region?: OrderProfileAnchorRelativeRegion | null; absolute_value_region?: OrderProfileRelativeRegion | null; fallback_value_region?: OrderProfileRelativeRegion | null; value_mode: 'single_line' | 'multi_line' | 'right_of_anchor' | 'below_anchor'; stop_anchors: OrderProfileAnchorRule[]; normalizer_key?: string | null; required: boolean; minimum_evidence_level: OrderProfileEvidenceLevel; }
|
||||
export interface OrderProfileDraftUnboundOrderFieldLayout { layout_id: string; label: string; page_scope: 'first_page' | 'all_pages' | 'exact_page'; page_no?: number | null; anchor?: OrderProfileAnchorRule | null; value_region?: OrderProfileAnchorRelativeRegion | null; absolute_value_region?: OrderProfileRelativeRegion | null; fallback_value_region?: OrderProfileRelativeRegion | null; value_mode: 'single_line' | 'multi_line' | 'right_of_anchor' | 'below_anchor'; stop_anchors: OrderProfileAnchorRule[]; minimum_evidence_level: OrderProfileEvidenceLevel; }
|
||||
@@ -80,11 +87,19 @@ export interface OrderProfileVisualDefinition {
|
||||
table_regions: OrderProfileTableRegion[];
|
||||
order_field_layouts?: OrderProfileOrderFieldLayout[];
|
||||
draft_unbound_order_field_layouts?: OrderProfileDraftUnboundOrderFieldLayout[];
|
||||
/** 扁平坐标框架契约;legacy 不提交该配置,anchor_frame 由管理员显式启用。 */
|
||||
coordinate_model?: OrderProfileCoordinateModel;
|
||||
}
|
||||
|
||||
/** coordinate/OCR adapter 仅复用共同视觉定义,不增加独立生命周期字段。 */
|
||||
export interface OrderCoordinateProfileDefinition extends OrderProfileVisualDefinition {
|
||||
template_mode?: 'coordinate';
|
||||
/** Reservation ID 专用证据区域;解析器从该区域统一提取并由 Schema 决定落点。 */
|
||||
reservation_id_region?: {
|
||||
region: OrderProfileRelativeRegion;
|
||||
page_scope: 'exact_page';
|
||||
page_no: number;
|
||||
} | null;
|
||||
}
|
||||
|
||||
export interface XfaSourceContract {
|
||||
@@ -224,6 +239,13 @@ export interface XfaSplitMatcher {
|
||||
case_sensitive?: boolean;
|
||||
pattern?: string | null;
|
||||
capture_group?: number | null;
|
||||
/** 受限正式后处理:当前仅支持在已定位行中提取指定标签后的值。 */
|
||||
post_processors?: Array<{
|
||||
type: 'prefix';
|
||||
value: string;
|
||||
separators?: string[];
|
||||
case_sensitive?: boolean;
|
||||
}>;
|
||||
}
|
||||
|
||||
/** @deprecated 仅兼容未迁移草稿的 stages[] UI。 */
|
||||
@@ -919,7 +941,7 @@ export interface OrderProfileBlindTestCandidate {
|
||||
/** 工作台的本地几何状态;保存前转为 v2 相对区域定义。 */
|
||||
export interface OrderProfileCanvasRegion {
|
||||
id: string;
|
||||
kind: 'header' | 'header_field' | 'line' | 'field' | 'order_anchor' | 'order_field' | 'exclusion' | 'document_anchor_label' | 'document_anchor_value';
|
||||
kind: 'header' | 'header_field' | 'line' | 'field' | 'order_anchor' | 'order_field' | 'exclusion' | 'document_anchor_label' | 'document_anchor_value' | 'reservation_id_region';
|
||||
label: string;
|
||||
region: OrderProfileRelativeRegion;
|
||||
fieldCode?: string | null;
|
||||
@@ -943,6 +965,8 @@ export interface OrderProfileCanvasRegion {
|
||||
pageNo: number;
|
||||
/** datasets adapter 可附加的视觉证据确认状态,不影响共同画布区域种类。 */
|
||||
visualBindingStatus?: XfaVisualBindingStatus;
|
||||
/** 工作台待确认候选的临时视觉标记;不会进入 Profile 保存 payload。 */
|
||||
isPreview?: boolean;
|
||||
}
|
||||
|
||||
export interface OrderProfileSampleDocument {
|
||||
@@ -1065,6 +1089,24 @@ export interface OrderProfileSampleIntake {
|
||||
document_count: number;
|
||||
document_ids?: number[];
|
||||
error_code?: string | null;
|
||||
/** 文档当前 Layout 状态;与上传物化状态独立。 */
|
||||
layout_status?: 'pending' | 'ready' | 'failed' | 'missing' | string;
|
||||
/** 当前 Profile 样本证据冻结状态;没有 Profile 绑定时为 pending。 */
|
||||
evidence_status?: 'pending' | 'frozen' | 'stale' | 'unavailable' | string;
|
||||
/** 仅当 Layout、主表和冻结身份全部满足时才允许入队自动标注。 */
|
||||
automark_ready?: boolean;
|
||||
automark_reason_code?: string | null;
|
||||
sample_readiness?: Array<{
|
||||
profile_id: number;
|
||||
sample_id: number;
|
||||
document_id: number;
|
||||
table_id?: string;
|
||||
layout_status: string;
|
||||
main_table_status: string;
|
||||
evidence_status: string;
|
||||
automark_ready: boolean;
|
||||
reason_code?: string | null;
|
||||
}>;
|
||||
}
|
||||
|
||||
export interface CreateOrderProfileFromSampleInput {
|
||||
@@ -1142,7 +1184,7 @@ export interface OrderFieldValuePreview {
|
||||
field_code: string;
|
||||
value: string | null;
|
||||
status: 'confirmed' | 'needs_review' | 'unavailable';
|
||||
source?: 'pdf_coordinate' | 'ocr_coordinate' | 'acroform_widget' | null;
|
||||
source?: 'pdf_coordinate' | 'ocr_coordinate' | 'acroform_widget' | 'xfa_rendered_ocr' | null;
|
||||
page_no: number | null;
|
||||
issues: string[];
|
||||
}
|
||||
|
||||
@@ -1,365 +0,0 @@
|
||||
/**
|
||||
* features/admin/types/shipping-order-document-profile.vc.types.ts
|
||||
* 用途:Vendor Comments(普通 PDF 物理区域 + 三来源合并)阶段 2/3 前端契约类型定义。
|
||||
* 不修改既有 shipping-order-document-profile.types.ts(单文件不超 1000 行红线)。
|
||||
* 依赖:BaseSplit* 对齐 field_split_core.py;NamedRegion / FieldSourceMapping 严格对齐
|
||||
* profile_vendor_comments_contract.py;format_policy 对齐 reservation_format_policy_service.py。
|
||||
* 逻辑:后端决定 UI —— 所有稳定诊断码、合并决议枚举、冲突分组键、回 Draft 标志位
|
||||
* 全部通过后端 API 返回,前端不得自行 if/else 推导业务状态。
|
||||
*/
|
||||
|
||||
import type { OrderProfileRelativeRegion } from './shipping-order-document-profile.types';
|
||||
|
||||
// =========================================================================
|
||||
// Section A: named_regions 契约(Q14)——Profile 顶层命名区域
|
||||
// =========================================================================
|
||||
|
||||
export type VCNamedRegionPageScope =
|
||||
| 'first_page'
|
||||
| 'last_page'
|
||||
| 'all_pages'
|
||||
| 'exact_page';
|
||||
|
||||
export type VCNamedRegionSelectionMode =
|
||||
| 'fixed_region'
|
||||
| 'auto_take_last_qualified';
|
||||
|
||||
export interface VCNamedRegion {
|
||||
region_id: string;
|
||||
label: string;
|
||||
region: OrderProfileRelativeRegion;
|
||||
page_scope: VCNamedRegionPageScope;
|
||||
page_no?: number | null;
|
||||
selection_mode: VCNamedRegionSelectionMode;
|
||||
}
|
||||
|
||||
export type VCNamedRegionsMap = Record<string, VCNamedRegion>;
|
||||
|
||||
// =========================================================================
|
||||
// Section B: Reservation format_policy 契约(Q15)——Profile 级校验策略
|
||||
// =========================================================================
|
||||
|
||||
export type VCFormatPolicyMode =
|
||||
| 'inherit_global'
|
||||
| 'numeric_5_or_10'
|
||||
| 'custom_safe_regex';
|
||||
|
||||
export interface VCReservationFormatPolicy {
|
||||
mode: VCFormatPolicyMode;
|
||||
pattern?: string | null;
|
||||
/** custom_safe_regex 发布前必须过 Pydantic 的捕获组限制门禁 */
|
||||
max_capture_groups: number;
|
||||
timeout_ms: number;
|
||||
case_sensitive: boolean;
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// Section C: Base Split Core(共享引擎)契约——对齐 field_split_core.py
|
||||
// 前端类型必须完全复用 XfaSplit*;为避免引入 XFA 专属 path_id 歧义,
|
||||
// 这里新建轻量别名。未来与 XfaSplit 统一后移除别名。
|
||||
// =========================================================================
|
||||
|
||||
export type VCSplitMatcherType = 'prefix' | 'regex' | 'position';
|
||||
export type VCSplitHandling = 'mapped' | 'evidence_only';
|
||||
|
||||
export interface VCSplitRelationCaptureDef {
|
||||
type: 'line_reference' | string;
|
||||
capture_group: number;
|
||||
labels?: string[] | null;
|
||||
}
|
||||
|
||||
export interface VCSplitMatcher {
|
||||
type: VCSplitMatcherType;
|
||||
line_index?: number | null;
|
||||
value?: string | null;
|
||||
separators?: string[];
|
||||
case_sensitive?: boolean;
|
||||
pattern?: string | null;
|
||||
capture_group?: number | null;
|
||||
relation_capture?: VCSplitRelationCaptureDef | null;
|
||||
}
|
||||
|
||||
export interface VCSplitSegment {
|
||||
segment_id: string;
|
||||
segment_code: string;
|
||||
display_name: string;
|
||||
handling: VCSplitHandling;
|
||||
target_field_id?: string | null;
|
||||
target_field_code?: string | null;
|
||||
note?: string | null;
|
||||
}
|
||||
|
||||
export interface VCSplitRule {
|
||||
rule_id: string;
|
||||
matcher?: VCSplitMatcher | null;
|
||||
segment: VCSplitSegment;
|
||||
order: number;
|
||||
}
|
||||
|
||||
export interface VCSplitNormalization {
|
||||
trim?: boolean;
|
||||
remove_empty_lines?: boolean;
|
||||
line_breaks?: string[];
|
||||
}
|
||||
|
||||
export interface VCSplitRuleSet {
|
||||
rule_set_id: string;
|
||||
rule_version: number;
|
||||
normalization?: VCSplitNormalization;
|
||||
rules: VCSplitRule[];
|
||||
unmatched_line_policy?: 'evidence_only' | 'needs_review';
|
||||
duplicate_match_policy?: 'needs_review';
|
||||
same_field_multiple_segment_policy?: 'needs_review';
|
||||
source?: 'system_suggestion' | 'user' | 'imported';
|
||||
status?: 'draft' | 'confirmed' | 'published';
|
||||
requires_confirmation?: boolean;
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// Section D: field_source_mappings 契约(Q9/Q18)——三来源字段来源映射
|
||||
// =========================================================================
|
||||
|
||||
export type VCRelationPolicy =
|
||||
| 'no_relation'
|
||||
| 'bind_target_line'
|
||||
| 'annotation_only';
|
||||
|
||||
export type VCMissingRelationPolicy =
|
||||
| 'default_all_lines'
|
||||
| 'default_header_only'
|
||||
| 'fallback_single_line_when_no_reference';
|
||||
|
||||
export type VCLineReferenceBasis =
|
||||
| 'explicit_line_column'
|
||||
| 'profile_business_line_no'
|
||||
| 'classified_logical_line_no';
|
||||
|
||||
export interface VCProfileFieldSourceMapping {
|
||||
mapping_id: string;
|
||||
target_scope: 'header' | 'line';
|
||||
target_field_code: string;
|
||||
target_field_id: string;
|
||||
|
||||
header_source_enabled: boolean;
|
||||
header_source_ref?: string | null;
|
||||
header_normalizer_key?: string | null;
|
||||
|
||||
table_source_enabled: boolean;
|
||||
table_column_code?: string | null;
|
||||
|
||||
vendor_comments_enabled: boolean;
|
||||
vendor_comments_region_ref?: string | null;
|
||||
vendor_comments_split_rule_set?: VCSplitRuleSet | null;
|
||||
|
||||
relation_policy: VCRelationPolicy;
|
||||
missing_relation_policy: VCMissingRelationPolicy;
|
||||
line_reference_basis: VCLineReferenceBasis;
|
||||
|
||||
fill_missing_from_other_sources: boolean;
|
||||
format_policy: VCReservationFormatPolicy;
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// Section E: 三来源候选 + 合并结果(SourceMergeService)——后端决定 UI
|
||||
// 后端返回结构化决议,前端只负责渲染按钮/高亮,不推导状态。
|
||||
// =========================================================================
|
||||
|
||||
export type VCFieldSourceKind =
|
||||
| 'header_region'
|
||||
| 'table_column'
|
||||
| 'vendor_comments';
|
||||
|
||||
export type VCMergeResolution =
|
||||
| 'same_value_merged'
|
||||
| 'fill_missing'
|
||||
| 'needs_review'
|
||||
| 'no_value'
|
||||
| 'single_source_direct'
|
||||
| 'annotation_only_dropped';
|
||||
|
||||
export type VCObservationDecisionStatus =
|
||||
| 'accepted'
|
||||
| 'needs_review'
|
||||
| 'blocked'
|
||||
| 'missing';
|
||||
|
||||
export interface VCSourceObservationSnapshot {
|
||||
source: VCFieldSourceKind;
|
||||
value: string;
|
||||
normalized_value: string;
|
||||
evidence_ref: string | null;
|
||||
evidence_quote: string | null;
|
||||
line_no_in_source: number | null;
|
||||
format_valid: boolean | null;
|
||||
format_reason_code: string | null;
|
||||
extra: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export interface VCMergedObservationCandidate {
|
||||
target_scope: 'header' | 'line';
|
||||
target_field_code: string;
|
||||
target_field_id: string;
|
||||
effective_line_no: number | null;
|
||||
accepted_value: string | null;
|
||||
decision_status: VCObservationDecisionStatus;
|
||||
resolution: VCMergeResolution;
|
||||
source_observations: VCSourceObservationSnapshot[];
|
||||
conflicts: Array<Record<string, unknown>>;
|
||||
evidence_quote: string | null;
|
||||
evidence_ref: string | null;
|
||||
evidence_metadata: {
|
||||
source_observations: VCSourceObservationSnapshot[];
|
||||
resolution: VCMergeResolution;
|
||||
accepted_value: string | null;
|
||||
conflicts: Array<Record<string, unknown>>;
|
||||
resolution_meta: Record<string, unknown>;
|
||||
primary?: {
|
||||
source: VCFieldSourceKind;
|
||||
evidence_ref: string | null;
|
||||
line_no: number | null;
|
||||
} | null;
|
||||
};
|
||||
source_type: string;
|
||||
extractor: string;
|
||||
/** 前端只读门禁:是否允许作为有效 Observation 落库 */
|
||||
should_persist_observation: boolean;
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// Section F: 关系投影诊断码(Q2/Q12)——invalid_line_reference 独立审计链
|
||||
// =========================================================================
|
||||
|
||||
export type VCRelationProjectionResolution =
|
||||
| 'bound_to_line'
|
||||
| 'annotation_only'
|
||||
| 'default_all_lines'
|
||||
| 'default_header_only'
|
||||
| 'invalid_line_reference'
|
||||
| 'conflict_unresolved';
|
||||
|
||||
export interface VCRelationProjectionResult {
|
||||
line_reference_basis: VCLineReferenceBasis;
|
||||
resolution: VCRelationProjectionResolution;
|
||||
resolved_logical_line_no: number | null;
|
||||
annotation_reason: string | null;
|
||||
invalid_reference_raw_value: string | null;
|
||||
invalid_reference_line_no: number | null;
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// Section G: 区域预览诊断(CoordinateRegionSourceAdapter)
|
||||
// =========================================================================
|
||||
|
||||
export type VCCoordinateRegionStatus = 'available' | 'unavailable';
|
||||
|
||||
export interface VCCoordinateRegionEvidenceToken {
|
||||
page_no: number;
|
||||
text: string;
|
||||
x0: number;
|
||||
y0: number;
|
||||
x1: number;
|
||||
y1: number;
|
||||
}
|
||||
|
||||
export interface VCCoordinateRegionSourceResult {
|
||||
region_id: string;
|
||||
label: string;
|
||||
status: VCCoordinateRegionStatus;
|
||||
page_no: number | null;
|
||||
raw_text: string;
|
||||
lines: string[];
|
||||
evidence_tokens: VCCoordinateRegionEvidenceToken[];
|
||||
diagnostic_code: string | null;
|
||||
diagnostic_message: string | null;
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// Section H: Profile 变更回 Draft 判定(前端门禁标志位,真实判定在后端)
|
||||
// 前端只展示警告,不阻断保存(最终拦截在 service 层)。
|
||||
// =========================================================================
|
||||
|
||||
export interface VCProfileDraftTrigger {
|
||||
named_regions_changed: boolean;
|
||||
field_source_mappings_changed: boolean;
|
||||
requires_draft_reset: boolean;
|
||||
/** 前端展示给管理员的中文/英文说明;实际文案通过 t() 取 i18n */
|
||||
reasons: Array<{
|
||||
kind:
|
||||
| 'named_region_added'
|
||||
| 'named_region_removed'
|
||||
| 'named_region_geometry'
|
||||
| 'named_region_scope'
|
||||
| 'field_source_mapping_added'
|
||||
| 'field_source_mapping_removed'
|
||||
| 'field_source_mapping_split_rule_changed'
|
||||
| 'field_source_mapping_format_policy_changed';
|
||||
region_id?: string;
|
||||
mapping_id?: string;
|
||||
}>;
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// Section I: definition_json 顶层 VC 扩展(OrderCoordinateProfileDefinition
|
||||
// 和 OrderXfaDatasetProfileDefinition 都通过交叉引用)。
|
||||
// 不修改既有 definition 接口,单独 export 用于 patch 合并。
|
||||
// =========================================================================
|
||||
|
||||
export interface VCProfileDefinitionExtensions {
|
||||
named_regions?: VCNamedRegionsMap | null;
|
||||
field_source_mappings?: VCProfileFieldSourceMapping[] | null;
|
||||
}
|
||||
|
||||
export type VCProfileDefinitionWithExtensions =
|
||||
& { named_regions?: VCNamedRegionsMap | null; field_source_mappings?: VCProfileFieldSourceMapping[] | null }
|
||||
& Record<string, unknown>;
|
||||
|
||||
// =========================================================================
|
||||
// Section J: 合成预览 DTO(后端返回,前端只读)
|
||||
// =========================================================================
|
||||
|
||||
export interface VCSplitEngineSegmentPreview {
|
||||
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: VCSplitHandling;
|
||||
target_field_id?: string | null;
|
||||
target_field_code?: string | null;
|
||||
rule_id: string;
|
||||
status: string;
|
||||
matcher_type: string;
|
||||
captured_relation?: {
|
||||
type: string;
|
||||
line_no: number | null;
|
||||
raw_text: string | null;
|
||||
} | null;
|
||||
}
|
||||
|
||||
export interface VCSplitEnginePreviewResult {
|
||||
status: 'parsed' | 'needs_review' | 'unavailable';
|
||||
rule_set_id: string | null;
|
||||
rule_version: number | null;
|
||||
mapped_fields: Record<string, string>;
|
||||
segments: VCSplitEngineSegmentPreview[];
|
||||
evidence_only_segments: VCSplitEngineSegmentPreview[];
|
||||
diagnostics: Array<{
|
||||
code: string;
|
||||
message: string;
|
||||
line_no?: number | null;
|
||||
field_code?: string | null;
|
||||
rule_ids?: string[];
|
||||
}>;
|
||||
}
|
||||
|
||||
export interface VCMergePreviewResponse {
|
||||
document_id: number;
|
||||
region_id: string;
|
||||
mapping_id: string;
|
||||
region_result: VCCoordinateRegionSourceResult | null;
|
||||
split_preview: VCSplitEnginePreviewResult | null;
|
||||
relation_projection: VCRelationProjectionResult | null;
|
||||
merged_observation: VCMergedObservationCandidate | null;
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
/**
|
||||
* features/chat/api/shipping.api.request-dedupe.spec.ts
|
||||
* 用途:锁定重型订单抽取 Run 读取的同 key 在途请求合并契约。
|
||||
* 依赖:Vitest、shipping.api、统一 requestJson。
|
||||
* 逻辑:两个消费者同时读取同一 Run 时必须复用一个 HTTP 请求;请求结束后才允许下一次读取。
|
||||
*/
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
const requestJson = vi.hoisted(() => vi.fn());
|
||||
|
||||
vi.mock('@/shared/api/client', () => ({
|
||||
BusinessError: class BusinessError extends Error {},
|
||||
requestJson,
|
||||
}));
|
||||
|
||||
import {
|
||||
getWorkspaceShippingOrderExtractionRun,
|
||||
getWorkspaceShippingProcessing,
|
||||
} from './shipping.api';
|
||||
|
||||
describe('getWorkspaceShippingOrderExtractionRun', () => {
|
||||
beforeEach(() => {
|
||||
requestJson.mockReset();
|
||||
// 模块级短缓存会跨用例保留;本文件的会话 ID 均唯一,避免上一用例污染下一用例。
|
||||
});
|
||||
|
||||
it('coalesces concurrent reads of the same Run into one HTTP request', async () => {
|
||||
let resolveRequest!: (value: { run_no: string }) => void;
|
||||
requestJson.mockImplementationOnce(() => new Promise((resolve) => {
|
||||
resolveRequest = resolve;
|
||||
}));
|
||||
|
||||
const first = getWorkspaceShippingOrderExtractionRun('SNER-SAME');
|
||||
const second = getWorkspaceShippingOrderExtractionRun('SNER-SAME');
|
||||
|
||||
// 关键断言:慢 Run 投影在途时,同一文件的第二个消费者不得再创建独立网络请求。
|
||||
expect(requestJson).toHaveBeenCalledTimes(1);
|
||||
resolveRequest({ run_no: 'SNER-SAME' });
|
||||
await expect(Promise.all([first, second])).resolves.toEqual([
|
||||
{ run_no: 'SNER-SAME' },
|
||||
{ run_no: 'SNER-SAME' },
|
||||
]);
|
||||
});
|
||||
|
||||
it('lets one caller stop waiting without aborting a shared Run request', async () => {
|
||||
let resolveRequest!: (value: { run_no: string }) => void;
|
||||
requestJson.mockImplementationOnce(() => new Promise((resolve) => {
|
||||
resolveRequest = resolve;
|
||||
}));
|
||||
const controller = new AbortController();
|
||||
|
||||
const cancelledCaller = getWorkspaceShippingOrderExtractionRun('SNER-SHARED', controller.signal);
|
||||
const activeCaller = getWorkspaceShippingOrderExtractionRun('SNER-SHARED');
|
||||
controller.abort();
|
||||
|
||||
// 关键断言:路由离开只结束当前消费者等待,不能中止其他组件复用的重型读取。
|
||||
await expect(cancelledCaller).rejects.toMatchObject({ name: 'AbortError' });
|
||||
expect(requestJson).toHaveBeenCalledTimes(1);
|
||||
resolveRequest({ run_no: 'SNER-SHARED' });
|
||||
await expect(activeCaller).resolves.toEqual({ run_no: 'SNER-SHARED' });
|
||||
});
|
||||
|
||||
it('reuses a successful conversation summary during the short refresh burst', async () => {
|
||||
requestJson.mockResolvedValue({
|
||||
conversation_id: 'conversation-summary-cache',
|
||||
work_items: [],
|
||||
conversation_processing: null,
|
||||
});
|
||||
|
||||
await getWorkspaceShippingProcessing('conversation-summary-cache');
|
||||
await getWorkspaceShippingProcessing('conversation-summary-cache');
|
||||
|
||||
// 关键断言:首屏 watcher 连续触发时必须复用刚完成的摘要,避免重复慢查询。
|
||||
expect(requestJson).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('binds every summary leaf to its status-group task for batch rendering', async () => {
|
||||
requestJson.mockResolvedValue({
|
||||
conversation_id: 'conversation-leaf-binding-20260822',
|
||||
conversation_processing: {
|
||||
summary: { total_tasks: 1, total_files: 1, processing: 0, needs_action: 1, completed: 0, history: 0 },
|
||||
status_groups: {
|
||||
failed: [],
|
||||
waiting_human: [{
|
||||
user_task_no: 'INTAKE:SNI-1', group: 'needs_action', status_label: 'waiting_human',
|
||||
file_count: 1, can_append: false,
|
||||
aggregate_children: [{
|
||||
work_item_type: 'order_task', work_item_no: 'DOCUMENT:1', source_type: 'eml',
|
||||
conversation_id: 'conversation-leaf-binding-20260822', intake_no: 'SNI-1', submission_no: 'SUB-1',
|
||||
// 同一邮件内另一 Candidate 的原始 OT 不能用作父卡关联键。
|
||||
root_order_task_no: 'OT-OTHER-CANDIDATE',
|
||||
status: 'waiting_human', stage: 'candidate_creating', progress_version: 1,
|
||||
source_summary: { document_id: 1, filename: 'order.pdf' },
|
||||
}],
|
||||
}],
|
||||
processing: [], completed: [], cancelled: [], archived: [],
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const response = await getWorkspaceShippingProcessing('conversation-leaf-binding-20260822');
|
||||
|
||||
// 关键断言:批次卡按父任务查实时叶子时,必须能找到本摘要组的文件。
|
||||
expect(response.conversation_processing?.status_groups?.waiting_human[0]?.aggregateChildren?.[0]).toMatchObject({
|
||||
workItemNo: 'DOCUMENT:1',
|
||||
});
|
||||
expect(response.conversation_processing?.status_groups?.waiting_human[0]?.aggregateChildren).toHaveLength(1);
|
||||
expect(response.work_items).toHaveLength(1);
|
||||
expect(response.work_items[0]?.rootOrderTaskNo).toBe('INTAKE:SNI-1');
|
||||
expect(response.work_items[0]?.sourceSummary.documentId).toBe(1);
|
||||
});
|
||||
});
|
||||
@@ -23,11 +23,13 @@ import type {
|
||||
ShippingNoticeIntakeResponse,
|
||||
ShippingTaskCreateResponse,
|
||||
ShippingTaskDetail,
|
||||
ShippingFreightNoticeGroupsResponse,
|
||||
ShippingTaskBatchDispositionResponse,
|
||||
ShippingTaskPage,
|
||||
ShippingCustomerOption,
|
||||
ShippingOrderExtractionDocumentResult,
|
||||
ShippingOrderExtractionRun,
|
||||
ShippingOrderExtractionRunListItem,
|
||||
ShippingOrderExtractionProgressEvent,
|
||||
ShippingOrderExtractionRunCreateResponse,
|
||||
ShippingOrderReviewQueue,
|
||||
@@ -69,11 +71,6 @@ type ShippingApiStatusPayload = {
|
||||
code?: string;
|
||||
details?: Record<string, unknown>;
|
||||
request_id?: string;
|
||||
/** 批次重试等接口返回的已发起任务数 */
|
||||
started?: number;
|
||||
/** 批次重试等接口返回的跳过任务数 */
|
||||
skipped?: number;
|
||||
batch_no?: string;
|
||||
/** 后端返回的语义化原因码(对齐 noop / needs_human / already_running 等状态分支) */
|
||||
reason_code?: ConversationProcessingAppendBlockReason | string | null;
|
||||
};
|
||||
@@ -125,6 +122,12 @@ export const listShippingChatAgents = () => requestJson<ShippingChatAgentOption[
|
||||
export const getWorkspaceShippingTask = (taskNo: string) =>
|
||||
requestJson<ShippingTaskDetail>(`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}`);
|
||||
|
||||
/** 读取当前 PO 下按 business_no 聚合的货代上传 Notice。 */
|
||||
export const getWorkspaceShippingFreightNoticeGroups = (taskNo: string) =>
|
||||
requestJson<ShippingFreightNoticeGroupsResponse>(
|
||||
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/freight-notice-groups`,
|
||||
);
|
||||
|
||||
/**
|
||||
* 分页拉取任务工作台统一审计时间线(ShippingAuditEvent 单源)。
|
||||
*/
|
||||
@@ -145,10 +148,14 @@ export const listWorkspaceShippingTaskAuditTimeline = (
|
||||
export const getWorkspaceShippingTaskUiState = (taskNo: string) =>
|
||||
requestJson<ShippingTaskUiState>(`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/ui-state`);
|
||||
|
||||
/** 生成任务导出文件的前端下载 URL。 */
|
||||
/** 旧任务号 Excel 下载 URL;仅供未迁移页面兼容,新货代操作必须使用 business_no。 */
|
||||
export const workspaceShippingExportUrl = (taskNo: string) =>
|
||||
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/export`;
|
||||
|
||||
/** 按发货通知单号下载唯一正式 Excel。 */
|
||||
export const workspaceShippingNoticeExportUrl = (businessNo: string) =>
|
||||
`/api/workspace/shipping-notices/${encodeURIComponent(businessNo)}/export`;
|
||||
|
||||
/** 当前任务已关联库存快照的受控下载 URL;后端会再次校验任务归属与活动 link。 */
|
||||
export const workspaceShippingInventoryFileUrl = (taskNo: string) =>
|
||||
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/inventory-file`;
|
||||
@@ -158,7 +165,7 @@ export const workspaceShippingLineInventoryFileUrl = (taskNo: string, inventoryF
|
||||
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/inventory-files/${encodeURIComponent(inventoryFileNo)}`;
|
||||
|
||||
/** 下载一个批次或显式任务集合的当前 ready 发货 Excel ZIP。 */
|
||||
export async function downloadWorkspaceShippingExportArchive(payload: { batch_no?: string; task_nos?: string[] }) {
|
||||
export async function downloadWorkspaceShippingExportArchive(payload: { task_nos?: string[] }) {
|
||||
const response = await fetch('/api/workspace/shipping-exports/archive', {
|
||||
method: 'POST', headers: { 'Content-Type': 'application/json', ...getAuthHeaders() }, body: JSON.stringify(payload),
|
||||
});
|
||||
@@ -198,9 +205,9 @@ export const createWorkspaceOrderExtractionSubmission = (
|
||||
);
|
||||
|
||||
/**
|
||||
* 拉取统一 ShippingProcessingProjection(唯一进度读源;含 order_intake / order_task)。
|
||||
* 核心逻辑:内嵌 conversation_processing.status_groups 是新版批次列表唯一读源;
|
||||
* 仅旧服务端未返回该字段时才由 work_items 合成兼容分组;旧 GET 已移除。
|
||||
* 拉取会话首屏摘要(唯一进度读源)。
|
||||
* 核心逻辑:首屏只消费后端裁决的 status_groups;完整 work_items/Gate 详情不进入
|
||||
* 轮询请求,按需通过 work-item 接口读取;旧服务端才允许 work_items 兼容。
|
||||
*/
|
||||
type WorkspaceShippingProcessingResponse = {
|
||||
conversation_id: string;
|
||||
@@ -210,18 +217,38 @@ type WorkspaceShippingProcessingResponse = {
|
||||
|
||||
/** 同一会话跨组件实例共享在途请求,避免历史路由恢复重挂载造成重复慢查询。 */
|
||||
const shippingProcessingRequests = new Map<string, Promise<WorkspaceShippingProcessingResponse>>();
|
||||
const SHIPPING_PROCESSING_REQUEST_TIMEOUT_MS = 10_000;
|
||||
/** 成功摘要短暂复用,覆盖同一渲染周期内的重复触发而不延迟后续轮询更新。 */
|
||||
const shippingProcessingSnapshots = new Map<string, {
|
||||
expiresAt: number;
|
||||
value: WorkspaceShippingProcessingResponse;
|
||||
}>();
|
||||
const SHIPPING_PROCESSING_SNAPSHOT_TTL_MS = 3_000;
|
||||
// 会话投影包含 Gate/Review 的只读裁决;真实大批次在服务端已完成附件批量预取后
|
||||
// 仍可能超过 10 秒。超时必须覆盖最坏合法读取,不能将未完成投影误显示为 0 文件。
|
||||
const SHIPPING_PROCESSING_REQUEST_TIMEOUT_MS = 30_000;
|
||||
|
||||
export const getWorkspaceShippingProcessing = async (
|
||||
conversationId: string,
|
||||
signal?: AbortSignal,
|
||||
) => {
|
||||
const normalized = String(conversationId || '').trim();
|
||||
if (!normalized) {
|
||||
throw new BusinessError({
|
||||
message: 'conversation_id is required',
|
||||
code: 'SHIPPING.PROCESSING_CONVERSATION_REQUIRED',
|
||||
status: 400,
|
||||
});
|
||||
}
|
||||
const existing = shippingProcessingRequests.get(normalized);
|
||||
if (existing) return existing;
|
||||
|
||||
// 不把单个组件的 AbortSignal 传给共享网络请求:卸载旧实例不能取消新实例仍需的首屏数据。
|
||||
if (signal?.aborted) throw new DOMException('Aborted', 'AbortError');
|
||||
const snapshot = shippingProcessingSnapshots.get(normalized);
|
||||
if (snapshot) {
|
||||
if (snapshot.expiresAt > Date.now()) return Promise.resolve(snapshot.value);
|
||||
shippingProcessingSnapshots.delete(normalized);
|
||||
}
|
||||
const controller = new AbortController();
|
||||
const timeout = setTimeout(
|
||||
() => controller.abort(),
|
||||
@@ -232,18 +259,43 @@ export const getWorkspaceShippingProcessing = async (
|
||||
work_items?: unknown[];
|
||||
conversation_processing?: ConversationProcessingProjection | null;
|
||||
}>(
|
||||
`/api/workspace/shipping-processing/conversations/${encodeURIComponent(normalized)}`,
|
||||
`/api/workspace/shipping-processing/conversations/${encodeURIComponent(normalized)}?view=summary`,
|
||||
{ signal: controller.signal },
|
||||
)
|
||||
.then((raw): WorkspaceShippingProcessingResponse => ({
|
||||
conversation_id: String(raw?.conversation_id || normalized),
|
||||
work_items: normalizeShippingProcessingWorkItems(raw?.work_items),
|
||||
// 会话级 status_groups / 四阶段 / 产物均已由后端裁决;在 API 边界一次规范任务字段,
|
||||
// 保证对话卡与批次中心消费同一份 DTO,后续组件不得再做 snake/camel 兼容分支。
|
||||
conversation_processing: raw?.conversation_processing
|
||||
.then((raw): WorkspaceShippingProcessingResponse => {
|
||||
const conversationProcessing = raw?.conversation_processing
|
||||
? normalizeConversationProcessingProjection(raw.conversation_processing)
|
||||
: null,
|
||||
}))
|
||||
: null;
|
||||
// summary 读模型只传状态→EML→PDF树。为既有批次中心提供最小实时叶子,
|
||||
// 禁止回退到完整 Run/Gate 详情或历史快照。
|
||||
// normalizeConversationProcessingProjection 已把 aggregate_children 转成 camelCase。
|
||||
// 为避免“后端 DTO 已规范化、再按 snake_case 读取”的二次断裂,直接透传
|
||||
// 已规范化叶子后仅覆写本次展示关联键。
|
||||
const normalizedSummaryLeaves = conversationProcessing?.status_groups
|
||||
? Object.values(conversationProcessing.status_groups).flatMap((tasks) => tasks.flatMap((task) => (
|
||||
(task.aggregateChildren || []).map((child) => ({
|
||||
...child,
|
||||
rootOrderTaskNo: task.user_task_no,
|
||||
}))
|
||||
)))
|
||||
: [];
|
||||
const value: WorkspaceShippingProcessingResponse = {
|
||||
conversation_id: String(raw?.conversation_id || normalized),
|
||||
work_items: Array.isArray(raw?.work_items) && raw.work_items.length
|
||||
? normalizeShippingProcessingWorkItems(raw.work_items)
|
||||
// 摘要接口返回空数组是合法形态;此时已完成 API 规范化的叶子直接作为
|
||||
// 批次展示索引,不能再送入 snake_case 规范器导致叶子被丢弃。
|
||||
: normalizedSummaryLeaves,
|
||||
// 会话级 status_groups / 五阶段 / 产物均已由后端裁决;在 API 边界一次规范任务字段,
|
||||
// 保证对话卡与批次中心消费同一份 DTO,后续组件不得再做 snake/camel 兼容分支。
|
||||
conversation_processing: conversationProcessing,
|
||||
};
|
||||
shippingProcessingSnapshots.set(normalized, {
|
||||
expiresAt: Date.now() + SHIPPING_PROCESSING_SNAPSHOT_TTL_MS,
|
||||
value,
|
||||
});
|
||||
return value;
|
||||
})
|
||||
.finally(() => {
|
||||
clearTimeout(timeout);
|
||||
if (shippingProcessingRequests.get(normalized) === request) {
|
||||
@@ -304,11 +356,66 @@ export const markWorkspaceConversationTaskViewed = (
|
||||
* @param runNo - Run 业务编号。
|
||||
* @param signal - 切会话或超时时取消当前 GET,不取消后台 Run。
|
||||
*/
|
||||
export const getWorkspaceShippingOrderExtractionRun = (runNo: string, signal?: AbortSignal) =>
|
||||
requestJson<ShippingOrderExtractionRun>(
|
||||
`/api/workspace/shipping-notice/order-extraction-runs/${encodeURIComponent(runNo)}`,
|
||||
{ signal },
|
||||
/**
|
||||
* 同一 Run 的完整工作台投影可能较重;跨组件并发读取时只保留一个在途 HTTP 请求。
|
||||
* 单个消费者取消不取消共享请求,避免路由切换或轮询重叠重复触发服务端投影。
|
||||
*/
|
||||
const shippingOrderExtractionRunRequests = new Map<string, Promise<ShippingOrderExtractionRun>>();
|
||||
const SHIPPING_ORDER_EXTRACTION_RUN_REQUEST_TIMEOUT_MS = 10_000;
|
||||
|
||||
/**
|
||||
* 为共享的 Run HTTP Promise 绑定单个消费者的取消边界。
|
||||
* 核心逻辑:消费者离开时立即拒绝该消费者,但绝不取消仍可能被其他组件复用的底层请求。
|
||||
* @param request - 已由同一 Run 消费者共享的底层 HTTP Promise。
|
||||
* @param signal - 当前消费者的可选取消信号。
|
||||
* @returns 仅代表当前消费者生命周期的 Promise。
|
||||
*/
|
||||
const withCallerAbort = <T>(request: Promise<T>, signal?: AbortSignal): Promise<T> => {
|
||||
if (!signal) return request;
|
||||
if (signal.aborted) return Promise.reject(new DOMException('Aborted', 'AbortError'));
|
||||
return new Promise<T>((resolve, reject) => {
|
||||
const cleanup = () => signal.removeEventListener('abort', onAbort);
|
||||
const onAbort = () => {
|
||||
cleanup();
|
||||
reject(new DOMException('Aborted', 'AbortError'));
|
||||
};
|
||||
signal.addEventListener('abort', onAbort, { once: true });
|
||||
request.then(
|
||||
(value) => {
|
||||
cleanup();
|
||||
resolve(value);
|
||||
},
|
||||
(error) => {
|
||||
cleanup();
|
||||
reject(error);
|
||||
},
|
||||
);
|
||||
});
|
||||
};
|
||||
|
||||
export const getWorkspaceShippingOrderExtractionRun = async (runNo: string, signal?: AbortSignal) => {
|
||||
const normalized = String(runNo || '').trim();
|
||||
if (signal?.aborted) throw new DOMException('Aborted', 'AbortError');
|
||||
const existing = shippingOrderExtractionRunRequests.get(normalized);
|
||||
if (existing) return withCallerAbort(existing, signal);
|
||||
|
||||
const controller = new AbortController();
|
||||
const timeout = setTimeout(
|
||||
() => controller.abort(),
|
||||
SHIPPING_ORDER_EXTRACTION_RUN_REQUEST_TIMEOUT_MS,
|
||||
);
|
||||
const request = requestJson<ShippingOrderExtractionRun>(
|
||||
`/api/workspace/shipping-notice/order-extraction-runs/${encodeURIComponent(normalized)}`,
|
||||
{ signal: controller.signal },
|
||||
).finally(() => {
|
||||
clearTimeout(timeout);
|
||||
if (shippingOrderExtractionRunRequests.get(normalized) === request) {
|
||||
shippingOrderExtractionRunRequests.delete(normalized);
|
||||
}
|
||||
});
|
||||
shippingOrderExtractionRunRequests.set(normalized, request);
|
||||
return withCallerAbort(request, signal);
|
||||
};
|
||||
|
||||
/** 复用原附件与冻结快照,重新入队一次失败的订单抽取 Run。 */
|
||||
export const retryWorkspaceShippingOrderExtractionRun = (runNo: string) =>
|
||||
@@ -380,10 +487,11 @@ export const getWorkspaceShippingOrderReviewRun = (runNo: string) =>
|
||||
`/api/workspace/shipping-notice/order-extraction-runs/${encodeURIComponent(runNo)}/review`,
|
||||
);
|
||||
|
||||
/** 获取一份 PDF 的冻结 Schema 与只读机器/草稿投影。 */
|
||||
export const getWorkspaceShippingOrderReviewCase = (caseNo: string) =>
|
||||
/** 获取一份 PDF 的冻结 Schema 与只读机器/草稿投影;signal 只取消本次浏览器读取。 */
|
||||
export const getWorkspaceShippingOrderReviewCase = (caseNo: string, signal?: AbortSignal) =>
|
||||
requestJson<ShippingOrderReviewCaseSnapshot>(
|
||||
`/api/workspace/shipping-notice/order-review-cases/${encodeURIComponent(caseNo)}`,
|
||||
{ signal },
|
||||
);
|
||||
|
||||
/** 保存一个复核订单头字段;后端以 expected_draft_version 拒绝过期窗口覆盖。 */
|
||||
@@ -421,7 +529,10 @@ export const deleteWorkspaceShippingOrderReviewLine = (caseNo: string, lineKey:
|
||||
);
|
||||
|
||||
export const validateWorkspaceShippingOrderReviewDraft = (caseNo: string, expectedDraftVersion: number) =>
|
||||
requestJson<{ case: ShippingOrderReviewCase }>(
|
||||
requestJson<{
|
||||
case: ShippingOrderReviewCase;
|
||||
resume_outcome?: ShippingOrderReviewResumeOutcome;
|
||||
}>(
|
||||
`/api/workspace/shipping-notice/order-review-cases/${encodeURIComponent(caseNo)}/draft/validate`,
|
||||
{ method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ expected_draft_version: expectedDraftVersion }) },
|
||||
);
|
||||
@@ -638,9 +749,10 @@ export const reparseWorkspaceShippingOrderReviewDocument = (caseNo: string, reas
|
||||
* 获取复核字段的安全证据摘要(含 highlight_quality / highlight_bbox 契约字段)。
|
||||
* PDF 二进制继续由受控同源预览接口提供;坐标缺失不影响字段值。
|
||||
*/
|
||||
export const getWorkspaceShippingOrderReviewEvidence = (caseNo: string) =>
|
||||
export const getWorkspaceShippingOrderReviewEvidence = (caseNo: string, signal?: AbortSignal) =>
|
||||
requestJson<{ case_no: string; items: ShippingOrderReviewEvidence[] }>(
|
||||
`/api/workspace/shipping-notice/order-review-cases/${encodeURIComponent(caseNo)}/evidence`,
|
||||
{ signal },
|
||||
);
|
||||
|
||||
/**
|
||||
@@ -770,7 +882,7 @@ export const decideWorkspaceShippingOrderReviewLineFulfillment = (
|
||||
);
|
||||
|
||||
/**
|
||||
* 为选中完整明细行创建履约波次 Task。
|
||||
* 为选中完整明细行创建独立发货通知和 Excel。
|
||||
*/
|
||||
export const waveWorkspaceShippingOrderReviewLineFulfillment = (
|
||||
caseNo: string,
|
||||
@@ -786,6 +898,7 @@ export const waveWorkspaceShippingOrderReviewLineFulfillment = (
|
||||
resume_outcome?: ShippingOrderReviewResumeOutcome;
|
||||
task_no?: string | null;
|
||||
wave_no?: number | null;
|
||||
notice_no?: string | null;
|
||||
}>(
|
||||
`/api/workspace/shipping-notice/order-review-cases/${encodeURIComponent(caseNo)}/line-fulfillment/wave`,
|
||||
{
|
||||
@@ -882,7 +995,7 @@ export const listWorkspaceShippingOrderExtractionRuns = (
|
||||
) => {
|
||||
const params = new URLSearchParams({ limit: String(limit) });
|
||||
if (conversationId) params.set('conversation_id', conversationId);
|
||||
return requestJson<{ items: ShippingOrderExtractionRun[] }>(
|
||||
return requestJson<{ items: ShippingOrderExtractionRunListItem[] }>(
|
||||
`/api/workspace/shipping-notice/order-extraction-runs?${params.toString()}`,
|
||||
{ signal },
|
||||
);
|
||||
@@ -994,37 +1107,6 @@ export async function replaceWorkspaceShippingTaskNotice(taskNo: string, file: F
|
||||
return assertShippingOk(body);
|
||||
}
|
||||
|
||||
/**
|
||||
* 重试当前发货任务。
|
||||
* @param taskNo - 发货任务编号
|
||||
* @param comment - 可选重试备注
|
||||
* @returns 重试结果
|
||||
*/
|
||||
export async function retryWorkspaceShippingTask(taskNo: string, comment?: string) {
|
||||
const body = await requestJson<ShippingDecisionResponse & ShippingApiStatusPayload>(
|
||||
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/retry`,
|
||||
jsonPost(comment ? { comment, reason: comment } : { reason: 'user_retry' }),
|
||||
);
|
||||
return assertShippingOk(body);
|
||||
}
|
||||
|
||||
/**
|
||||
* 行级统一「重试」:后端决策器选择 fetch/rematch/needs_human。
|
||||
* 核心逻辑:前端不传内部动作码。
|
||||
* @param taskNo - 正式任务号
|
||||
* @param lineKey - 行键
|
||||
*/
|
||||
export async function retryWorkspaceShippingTaskLine(
|
||||
taskNo: string,
|
||||
lineKey: string,
|
||||
) {
|
||||
const body = await requestJson<ShippingDecisionResponse & ShippingApiStatusPayload>(
|
||||
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/lines/${encodeURIComponent(lineKey)}/retry`,
|
||||
jsonPost({ reason: 'user_retry_inventory' }),
|
||||
);
|
||||
return assertShippingOk(body);
|
||||
}
|
||||
|
||||
/** 人工复核证据只允许已绑定文档单元格或具名人工输入。 */
|
||||
export type ShippingReviewEvidence =
|
||||
| { evidence_type: 'document_cell'; document_id: number; observation_id: number; page_no: number; table_id: string; cell_id: string }
|
||||
@@ -1212,22 +1294,38 @@ export async function autoProgressWorkspaceShippingTask(taskNo: string, lang?: s
|
||||
}
|
||||
|
||||
/**
|
||||
* 标记货代系统已人工上传完成。
|
||||
* @param taskNo - 发货任务编号
|
||||
* @param payload - 当前 Artifact、人工回执 FileAsset 编号及可选货代参考号;回执编号必填。
|
||||
* 按发货通知单号确认货代系统已人工上传完成。
|
||||
* @param businessNo - 对外发货通知单号
|
||||
* @param payload - 当前通知唯一 Excel 的可选 Artifact 编号。
|
||||
* @returns 上传确认结果
|
||||
*/
|
||||
export async function markWorkspaceShippingManualUploaded(
|
||||
taskNo: string,
|
||||
payload: { evidence_asset_no: string; artifact_id?: number; freight_ref_no?: string },
|
||||
businessNo: string,
|
||||
payload: { artifact_id?: number } = {},
|
||||
) {
|
||||
const body = await requestJson<ShippingDecisionResponse & ShippingApiStatusPayload>(
|
||||
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/mark-manual-uploaded`,
|
||||
`/api/workspace/shipping-notices/${encodeURIComponent(businessNo)}/confirm-uploaded`,
|
||||
jsonPost(payload),
|
||||
);
|
||||
return assertShippingOk(body);
|
||||
}
|
||||
|
||||
/** 按多个发货通知单号批量确认人工上传;后端逐单裁决并返回逐单结果。 */
|
||||
export async function batchConfirmWorkspaceShippingNoticesUploaded(businessNos: string[]) {
|
||||
return requestJson<{ results: Array<Record<string, unknown>> }>(
|
||||
'/api/workspace/shipping-notices/batch/confirm-uploaded',
|
||||
jsonPost({ business_nos: businessNos }),
|
||||
);
|
||||
}
|
||||
|
||||
/** 按多个发货通知单号批量受理货代 RPA 上传;RPA 成功仍以回调为准。 */
|
||||
export async function batchStartWorkspaceShippingNoticeRpaUpload(businessNos: string[]) {
|
||||
return requestJson<{ results: Array<Record<string, unknown>> }>(
|
||||
'/api/workspace/shipping-notices/batch/rpa-upload',
|
||||
jsonPost({ business_nos: businessNos }),
|
||||
);
|
||||
}
|
||||
|
||||
/** 发货通知 Agent 应用类型标识(运行时识别)。 */
|
||||
export const SHIPPING_NOTICE_AGENT_CODE = 'shipping_notice';
|
||||
|
||||
@@ -1348,9 +1446,6 @@ export const resolveShippingNoticeCandidateDuplicate = (
|
||||
|
||||
export type {
|
||||
ShippingChatAction,
|
||||
ShippingConversationBatch,
|
||||
ShippingConversationWorkspace,
|
||||
ShippingConversationWorkspaceSummary,
|
||||
ShippingCurrentStepProgress,
|
||||
ShippingDecisionResponse,
|
||||
ShippingMatchLineResult,
|
||||
|
||||
@@ -94,64 +94,23 @@ const shippingProcessing = useShippingNoticeWorkflow({
|
||||
});
|
||||
provide(SHIPPING_WORKFLOW_KEY, shippingProcessing);
|
||||
|
||||
/**
|
||||
* 当前货代工作台的会话身份。
|
||||
*
|
||||
* 核心逻辑:历史会话首帧时 page.conversationId 尚未由消息恢复链路回填,
|
||||
* 但 route.query.conversation_id 已是用户明确打开的会话。所有批次中心
|
||||
* 显隐、传参和会话切换边界必须使用同一个优先级,避免中心带空 ID 初始化。
|
||||
*/
|
||||
const activeShippingConversationId = computed(() => (
|
||||
String(route.query.conversation_id || page.conversationId || '').trim()
|
||||
));
|
||||
|
||||
const isOrderReviewMode = computed(() => route.query.mode === 'order-review' && typeof route.query.run_no === 'string' && route.query.run_no.length > 0);
|
||||
|
||||
const isTrainingAgentPage = computed(() => matchesTrainingAgent(page.currentAgent));
|
||||
|
||||
const isMaintenanceAgentPage = computed(() => agentHasIntentUiProfile(page.currentAgent, 'maintenance'));
|
||||
|
||||
const activeExtractionRunNo = computed(() => {
|
||||
|
||||
// [STEP 1] 优先从消息流中的抽取状态卡取 run_no(终态后仍在消息里)。
|
||||
// page 经 reactive provide 后 messages 已解包为数组,禁止再读 .value。
|
||||
const messages = Array.isArray(page.messages) ? page.messages : [];
|
||||
|
||||
for (let i = messages.length - 1; i >= 0; i -= 1) {
|
||||
|
||||
const item = messages[i];
|
||||
|
||||
if (!item || item.role !== 'assistant') continue;
|
||||
|
||||
const payload = item.payload && typeof item.payload === 'object' ? item.payload : null;
|
||||
|
||||
const fromPayload = payload && typeof (payload as { order_extraction_run_no?: unknown }).order_extraction_run_no === 'string'
|
||||
|
||||
? String((payload as { order_extraction_run_no: string }).order_extraction_run_no).trim()
|
||||
|
||||
: '';
|
||||
|
||||
if (fromPayload) return fromPayload;
|
||||
|
||||
if (item.shipping_order_extraction_state) {
|
||||
|
||||
const fromGetter = String(page.getActiveOrderExtractionRunNo?.() || '').trim();
|
||||
|
||||
if (fromGetter) return fromGetter;
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// [STEP 2] 回退活动 Run(轮询中)与路由深链。
|
||||
|
||||
try {
|
||||
|
||||
const fromActive = String(page.getActiveOrderExtractionRunNo?.() || '').trim();
|
||||
|
||||
if (fromActive) return fromActive;
|
||||
|
||||
} catch {
|
||||
|
||||
/* ignore */
|
||||
|
||||
}
|
||||
|
||||
const fromQuery = typeof route.query.run_no === 'string' ? route.query.run_no.trim() : '';
|
||||
|
||||
return fromQuery;
|
||||
|
||||
});
|
||||
|
||||
/** 批次进度工作台按需打开;关闭时不占用对话区右侧布局。 */
|
||||
const batchWorkbenchOpen = ref(false);
|
||||
|
||||
@@ -160,7 +119,7 @@ const batchWorkbenchOpen = ref(false);
|
||||
const showShippingWorkflowTimeline = computed(() => (
|
||||
page.isShippingNoticeAgent
|
||||
&& batchWorkbenchOpen.value
|
||||
&& Boolean(page.conversationId || activeExtractionRunNo.value)
|
||||
&& Boolean(activeShippingConversationId.value)
|
||||
));
|
||||
|
||||
const compactShippingProgress = computed(() => batchWorkbenchOpen.value);
|
||||
@@ -178,7 +137,7 @@ function closeBatchWorkbench() {
|
||||
* 否则旧会话的右侧投影会短暂占用新会话的对话区并造成“本次处理”串批错觉。
|
||||
*/
|
||||
watch(
|
||||
() => [String(page.conversationId || ''), Number(page.currentAgentId || 0)] as const,
|
||||
() => [activeShippingConversationId.value, Number(page.currentAgentId || 0)] as const,
|
||||
(next, previous) => {
|
||||
if (!previous || next[0] === previous[0] && next[1] === previous[1]) return;
|
||||
batchWorkbenchOpen.value = false;
|
||||
@@ -694,7 +653,7 @@ watch(() => page.currentAgentId, () => {
|
||||
|
||||
<ShippingWorkflowTimeline
|
||||
v-if="showShippingWorkflowTimeline"
|
||||
:conversation-id="page.conversationId"
|
||||
:conversation-id="activeShippingConversationId"
|
||||
:refresh-trigger="page.workflowRefreshTrigger"
|
||||
:controller="shippingProcessing"
|
||||
|
||||
|
||||
@@ -112,16 +112,6 @@ async function handleQueryPreviewAssetImage(assetId: string, assetName: string)
|
||||
@confirm="page.handleDeleteConfirm"
|
||||
@cancel="page.closeDeleteConfirmDialog"
|
||||
/>
|
||||
<DeleteConfirmDialog
|
||||
v-model="page.showRetryFailedConfirmDialog"
|
||||
:title="page.t('chat.shippingNoticeUi.retryFailedConfirmTitle')"
|
||||
:message="page.t('chat.shippingNoticeUi.retryFailedConfirmMessage')"
|
||||
:confirm-text="page.t('chat.shippingNoticeUi.retryFailedConfirmAction')"
|
||||
:confirm-loading="page.retryingShippingPendingTasks"
|
||||
confirm-tone="primary"
|
||||
@confirm="page.handleRetryFailedConfirm"
|
||||
@cancel="page.closeRetryFailedConfirm"
|
||||
/>
|
||||
<div
|
||||
v-if="page.shippingToastMessage"
|
||||
class="pointer-events-none fixed inset-x-0 top-20 z-[145] flex justify-center px-4"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
/**
|
||||
* features/chat/components/ShippingWorkflowStepper.vue
|
||||
* 用途:货代发货四阶段 Stepper 展示组件。
|
||||
* 用途:货代发货五阶段 Stepper 展示组件。
|
||||
* 依赖:shipping/shippingStepper、vue-i18n。
|
||||
* 逻辑:Chat 与工作台传入 steps 数组;本组件只负责步骤高亮与标签渲染。
|
||||
*/
|
||||
@@ -33,7 +33,7 @@ const dotClass = (status: ShippingWorkflowStepItem['status']) => {
|
||||
<template>
|
||||
<div class="space-y-2">
|
||||
<div class="text-[11px] font-semibold uppercase tracking-[0.18em] text-muted">{{ t('chat.shippingNoticeUi.stepperTitle') }}</div>
|
||||
<div class="grid gap-2" :class="compact ? 'sm:grid-cols-4' : 'md:grid-cols-4'">
|
||||
<div class="grid gap-2" :class="compact ? 'sm:grid-cols-5' : 'md:grid-cols-5'">
|
||||
<div
|
||||
v-for="(step, index) in steps"
|
||||
:key="step.id"
|
||||
|
||||
+7
-3
@@ -167,7 +167,9 @@ const hasDiagnosticDetails = computed(() => Boolean(
|
||||
<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
|
||||
:class="eligibility.can_build === null
|
||||
? 'border-slate-200 bg-slate-50 text-slate-800 dark:border-slate-700 dark:bg-slate-900 dark:text-slate-100'
|
||||
: 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"
|
||||
@@ -175,8 +177,10 @@ const hasDiagnosticDetails = computed(() => Boolean(
|
||||
<div class="flex flex-wrap items-center justify-between gap-2">
|
||||
<span class="font-semibold">{{ t('chat.shippingOrderReview.buildEligibility.overallResult') }}</span>
|
||||
<span class="text-slate-600 dark:text-slate-300">{{ t('chat.shippingOrderReview.buildEligibility.manualBuildLabel') }}</span>
|
||||
<span class="rounded-full px-2 py-0.5 font-medium" :class="eligibility.can_build ? 'bg-emerald-100 text-emerald-800 dark:bg-emerald-900/60 dark:text-emerald-100' : 'bg-amber-100 text-amber-900 dark:bg-amber-900/60 dark:text-amber-100'">
|
||||
<span data-testid="review-eligibility-manual-status">{{ eligibility.can_build
|
||||
<span class="rounded-full px-2 py-0.5 font-medium" :class="eligibility.can_build === null ? 'bg-slate-100 text-slate-700 dark:bg-slate-800 dark:text-slate-100' : 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'">
|
||||
<span data-testid="review-eligibility-manual-status">{{ eligibility.can_build === null
|
||||
? t('chat.shippingOrderReview.buildEligibility.notValidated')
|
||||
: eligibility.can_build
|
||||
? t('chat.shippingOrderReview.buildEligibility.canBuildYes')
|
||||
: t('chat.shippingOrderReview.buildEligibility.canBuildNo') }}</span>
|
||||
</span>
|
||||
|
||||
+7
-2
@@ -153,6 +153,7 @@ const lowConfidenceFields = computed(() => props.eligibility?.issues?.flatMap((i
|
||||
) || []);
|
||||
const unexplainedBlocked = computed(() => Boolean(
|
||||
props.eligibility
|
||||
&& props.eligibility.status !== 'not_validated'
|
||||
&& props.eligibility.can_build === false
|
||||
&& !props.eligibility.issues?.length
|
||||
&& !props.eligibility.failed_gates?.length
|
||||
@@ -212,13 +213,17 @@ const gateChecklist = computed(() => {
|
||||
<h2 class="text-sm font-semibold">{{ t('chat.shippingOrderReview.buildEligibility.title') }}</h2>
|
||||
<span
|
||||
class="rounded-full px-2.5 py-1 text-xs font-medium"
|
||||
:class="eligibility.can_build
|
||||
:class="eligibility.can_build === null
|
||||
? 'bg-slate-100 text-slate-700 dark:bg-slate-800 dark:text-slate-200'
|
||||
: eligibility.can_build
|
||||
? 'bg-emerald-100 text-emerald-800 dark:bg-emerald-950 dark:text-emerald-100'
|
||||
: 'bg-amber-100 text-amber-900 dark:bg-amber-950 dark:text-amber-100'"
|
||||
data-testid="review-build-eligibility-badge"
|
||||
>
|
||||
{{
|
||||
eligibility.can_build
|
||||
eligibility.status === 'not_validated'
|
||||
? t('chat.shippingOrderReview.buildEligibility.notValidated')
|
||||
: eligibility.can_build
|
||||
? t('chat.shippingOrderReview.buildEligibility.canBuildYes')
|
||||
: t('chat.shippingOrderReview.buildEligibility.canBuildNo')
|
||||
}}
|
||||
|
||||
+23
-6
@@ -19,9 +19,11 @@ const i18n = createI18n({
|
||||
shippingNotice: {
|
||||
processGate: {
|
||||
actionCodes: {
|
||||
reload_inventory_result: '重新读取库存结果',
|
||||
retry_inventory_preparation: '重新获取库存',
|
||||
},
|
||||
inventoryActions: {
|
||||
reloadInventoryResult: '重新读取库存结果',
|
||||
retryInventoryMatching: '重新库存匹配',
|
||||
retryInventoryPreparation: '重新获取库存',
|
||||
},
|
||||
@@ -33,7 +35,7 @@ const i18n = createI18n({
|
||||
},
|
||||
chat: {
|
||||
shippingOrderReview: {
|
||||
saveOrderAndValidate: '保存订单并校验',
|
||||
saveOrderAndValidate: '提交订单',
|
||||
currentProcessing: {
|
||||
waitingStart: '等待系统启动',
|
||||
},
|
||||
@@ -69,7 +71,10 @@ describe('ReviewCurrentProcessingCard', () => {
|
||||
|
||||
it('keeps the retry action for retryable states', () => {
|
||||
const wrapper = mount(ReviewCurrentProcessingCard, {
|
||||
props: { stageCode: 'inventory_preparation', userStatus: 'retryable', retryable: true },
|
||||
props: {
|
||||
stageCode: 'inventory_preparation', userStatus: 'retryable', retryable: true,
|
||||
primaryAction: { code: 'retry_inventory_preparation', i18nKey: 'workspace.shippingNotice.processGate.inventoryActions.retryInventoryPreparation' },
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
|
||||
@@ -77,6 +82,18 @@ describe('ReviewCurrentProcessingCard', () => {
|
||||
expect(wrapper.find('[data-testid="review-current-processing-retry"]').exists()).toBe(true);
|
||||
});
|
||||
|
||||
it('renders reload inventory result as the timeout primary action', () => {
|
||||
const wrapper = mount(ReviewCurrentProcessingCard, {
|
||||
props: {
|
||||
stageCode: 'inventory_preparation', userStatus: 'retryable', retryable: true,
|
||||
primaryAction: { code: 'reload_inventory_result' },
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
|
||||
expect(wrapper.find('[data-testid="review-current-task-primary-action"]').text()).toBe('重新读取库存结果');
|
||||
});
|
||||
|
||||
it('hides the order-review entry when the user is already in the lifecycle workbench', () => {
|
||||
const wrapper = mount(ReviewCurrentProcessingCard, {
|
||||
props: {
|
||||
@@ -104,7 +121,7 @@ describe('ReviewCurrentProcessingCard', () => {
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
|
||||
expect(wrapper.find('[data-testid="review-current-task-primary-action"]').text()).toBe('重新库存匹配');
|
||||
expect(wrapper.find('[data-testid="review-current-processing-retry"]').text()).toBe('重新库存匹配');
|
||||
});
|
||||
|
||||
it('does not render save and validate as a current-task action', () => {
|
||||
@@ -116,9 +133,9 @@ describe('ReviewCurrentProcessingCard', () => {
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
|
||||
// 保存订单并校验是底栏唯一动作;未提交校验必须给出明确交接提示,不能显示系统处理中。
|
||||
// 提交订单是底栏唯一动作;未提交前必须给出明确交接提示,不能显示系统处理中。
|
||||
expect(wrapper.find('[data-testid="review-current-task-primary-action"]').exists()).toBe(false);
|
||||
expect(wrapper.get('[data-testid="review-current-task-next-step-text"]').text()).toBe('保存订单并校验');
|
||||
expect(wrapper.get('[data-testid="review-current-task-next-step-text"]').text()).toBe('提交订单');
|
||||
});
|
||||
|
||||
it('labels an unqueued automatic Gate as waiting for system start', () => {
|
||||
@@ -207,7 +224,7 @@ describe('ReviewCurrentProcessingCard', () => {
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
|
||||
await wrapper.get('[data-testid="review-current-task-primary-action"]').trigger('click');
|
||||
await wrapper.get('[data-testid="review-current-processing-retry"]').trigger('click');
|
||||
await wrapper.get('[data-testid="review-current-task-recovery-retry_inventory_preparation"]').trigger('click');
|
||||
|
||||
// 两个稳定 action 码分别进入 Gate API:重匹配不可误触 RPA,重新获取库存才会触发 RPA。
|
||||
|
||||
+16
-21
@@ -62,7 +62,6 @@ const props = defineProps<{
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
retry: [];
|
||||
locate: [lineKey?: string | null, fieldId?: string | null];
|
||||
action: [code: string, parameters?: Record<string, unknown>];
|
||||
}>();
|
||||
@@ -219,8 +218,7 @@ function isNonTaskCapabilityAction(code: string): boolean {
|
||||
}
|
||||
|
||||
/**
|
||||
* 业务动作按钮:后端确认 retryable=true → 主按钮为「重试」;
|
||||
* 否则若 primary_action.code 非 retry 且不是工作台内自跳转 → 渲染对应人工动作。
|
||||
* 业务动作按钮只消费 primary_action;retryable 是状态,不是授权。
|
||||
*/
|
||||
const showBusinessAction = computed(() => {
|
||||
if (props.loading) return false;
|
||||
@@ -228,13 +226,12 @@ const showBusinessAction = computed(() => {
|
||||
// [STEP] 自动处理期间没有人工业务动作;只保留外层的刷新进度入口。
|
||||
// 防止正式任务编辑等历史 primary_action 穿透到库存获取运行态。
|
||||
if (props.userStatus === 'running') return false;
|
||||
if (props.retryable) return true;
|
||||
const code = String(props.primaryAction?.code || '').trim();
|
||||
if (isInternalInventoryAction(code)) return false;
|
||||
if (!code) return false;
|
||||
if (isNonTaskCapabilityAction(code)) return false;
|
||||
if (isHiddenWorkbenchNavigationAction(code)) return false;
|
||||
// retry 仅当 retryable=true 时展示(避免按钮闪烁矛盾)
|
||||
// 无对象边界的泛化 retry 永不展示。
|
||||
if (code === 'retry') return false;
|
||||
return true;
|
||||
});
|
||||
@@ -243,7 +240,6 @@ const businessActionLabel = computed(() => {
|
||||
const code = String(props.primaryAction?.code || '').trim();
|
||||
const inventoryKey = inventoryActionLabelKey(code);
|
||||
if (inventoryKey && te(inventoryKey)) return t(inventoryKey);
|
||||
if (props.retryable) return t('chat.shippingOrderReview.currentTask.actionRetry');
|
||||
const pa = props.primaryAction;
|
||||
if (!pa) return '';
|
||||
if (isNonTaskCapabilityAction(String(pa.code || ''))) return '';
|
||||
@@ -257,11 +253,6 @@ const businessActionLabel = computed(() => {
|
||||
if (i18nKey && te(i18nKey)) {
|
||||
return t(i18nKey);
|
||||
}
|
||||
// fallback 到 legacy chat.shippingProcessing.action
|
||||
const legacyKey = `chat.shippingProcessing.action.${pa.code}`;
|
||||
if (te(legacyKey)) {
|
||||
return t(legacyKey);
|
||||
}
|
||||
// 当前任务按钮没有受控文案时 fail-closed,禁止泄漏内部 action code。
|
||||
return '';
|
||||
});
|
||||
@@ -274,7 +265,7 @@ const businessActionTitle = computed(() => {
|
||||
return '';
|
||||
});
|
||||
|
||||
const actionIsRetry = computed(() => Boolean(props.retryable) || String(props.primaryAction?.code || '') === 'retry');
|
||||
const actionIsRetry = computed(() => String(props.primaryAction?.code || '').trim().startsWith('retry_'));
|
||||
const actionIsInventoryRpa = computed(() => String(props.primaryAction?.code || '').trim() === 'retry_inventory_preparation');
|
||||
const recoveryActions = computed(() => (props.recoveryActions || []).filter((action) => {
|
||||
const code = String(action.code || '').trim();
|
||||
@@ -301,14 +292,7 @@ function recoveryActionLabel(action: (typeof recoveryActions.value)[number]): st
|
||||
|
||||
function handleBusinessActionClick() {
|
||||
const primaryActionCode = String(props.primaryAction?.code || '').trim();
|
||||
if (props.retryable && primaryActionCode && primaryActionCode !== 'retry') {
|
||||
emit('action', primaryActionCode, props.primaryAction?.parameters ?? {});
|
||||
return;
|
||||
}
|
||||
if (actionIsRetry.value) {
|
||||
emit('retry');
|
||||
return;
|
||||
}
|
||||
if (!primaryActionCode || primaryActionCode === 'retry') return;
|
||||
emit('action', primaryActionCode, props.primaryAction?.parameters ?? {});
|
||||
}
|
||||
|
||||
@@ -368,7 +352,18 @@ type ReviewCurrentUserStatus =
|
||||
</div>
|
||||
<div class="flex flex-wrap gap-x-2">
|
||||
<dt class="text-muted">{{ t('chat.shippingOrderReview.currentProcessing.status') }}</dt>
|
||||
<dd data-testid="review-current-task-status" :class="loading ? 'animate-pulse' : ''">{{ statusLabel }}</dd>
|
||||
<dd
|
||||
class="inline-flex items-center gap-1"
|
||||
data-testid="review-current-task-status"
|
||||
:class="loading ? 'animate-pulse' : ''"
|
||||
>
|
||||
<RefreshCw
|
||||
v-if="userStatus === 'running' && !loading"
|
||||
class="h-3 w-3 animate-spin"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
{{ statusLabel }}
|
||||
</dd>
|
||||
</div>
|
||||
<div
|
||||
v-if="hasFormalOt && shippingNoticeNo"
|
||||
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
/**
|
||||
* features/chat/components/shipping-review/ReviewCustomerResolutionPanel.spec.ts
|
||||
* 用途:锁定唯一标准客户候选的工作台提示,避免将可自动确认状态误报为未识别。
|
||||
* 依赖:vitest、@vue/test-utils、vue-i18n、ReviewCustomerResolutionPanel。
|
||||
* 逻辑:unique_candidate 显示自动确认说明和明确按钮;其他未确认状态维持人工选择入口。
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { mount } from '@vue/test-utils';
|
||||
import { createI18n } from 'vue-i18n';
|
||||
import ReviewCustomerResolutionPanel from './ReviewCustomerResolutionPanel.vue';
|
||||
|
||||
const i18n = createI18n({
|
||||
legacy: false,
|
||||
locale: 'zh-CN',
|
||||
messages: {
|
||||
'zh-CN': {
|
||||
chat: {
|
||||
shippingCustomer: { loadFailed: '加载失败', confirmFailed: '确认失败' },
|
||||
shippingOrderReview: {
|
||||
customerResolution: {
|
||||
title: '客户确认', subtitle: '请选择标准客户', uniqueCandidateHint: '已找到唯一标准客户候选;保存校验时系统会自动确认,也可手动确认。',
|
||||
confirmUniqueCandidate: '确认唯一候选', selectCustomer: '选择标准客户', retrying: '识别中…', retryCustomer: '重新识别客户',
|
||||
retryDone: '已重新识别客户', retryFailed: '重新识别客户失败', confirmed: '客户已确认', confirmReason: '人工确认',
|
||||
standardCustomer: '标准客户', customerCode: '客户编码', matchedInputs: '匹配输入', candidates: '候选客户', pdfReparseHint: '请重新识别 PDF',
|
||||
inputLabels: { customerCode: '客户编码', customerName: '客户名称', address: '地址', email: '邮箱', domain: '域名', other: '其他' },
|
||||
status: { unique_candidate: '唯一候选', unmatched: '未匹配', confirmed: '已确认' },
|
||||
},
|
||||
resume: { autoCreated: '已自动建单', waitingManualConfirm: '等待人工确认' },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
function mountPanel(status: string) {
|
||||
return mount(ReviewCustomerResolutionPanel, {
|
||||
props: {
|
||||
caseNo: 'CASE-CUSTOMER-1',
|
||||
editable: true,
|
||||
resolution: { resolved: false, status, raw_name: 'ACME' },
|
||||
},
|
||||
global: {
|
||||
plugins: [i18n],
|
||||
stubs: { ShippingCustomerConfirmDialog: true },
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
describe('ReviewCustomerResolutionPanel', () => {
|
||||
it('唯一候选展示自动确认说明和明确确认入口', () => {
|
||||
const wrapper = mountPanel('unique_candidate');
|
||||
|
||||
expect(wrapper.text()).toContain('保存校验时系统会自动确认');
|
||||
expect(wrapper.get('[data-testid="review-select-customer"]').text()).toContain('确认唯一候选');
|
||||
});
|
||||
|
||||
it('非唯一未确认状态维持人工选择客户入口', () => {
|
||||
const wrapper = mountPanel('unmatched');
|
||||
|
||||
expect(wrapper.text()).not.toContain('保存校验时系统会自动确认');
|
||||
expect(wrapper.get('[data-testid="review-select-customer"]').text()).toContain('选择标准客户');
|
||||
});
|
||||
});
|
||||
+12
-2
@@ -41,6 +41,10 @@ const options = ref<ShippingCustomerOption[]>([]);
|
||||
const loadingOptions = ref(false);
|
||||
|
||||
const resolved = computed(() => Boolean(props.resolution?.resolved));
|
||||
const hasUniqueCandidate = computed(() => (
|
||||
!resolved.value
|
||||
&& String(props.resolution?.status || '').trim() === 'unique_candidate'
|
||||
));
|
||||
const statusLabel = computed(() => {
|
||||
const status = String(props.resolution?.status || '').trim();
|
||||
if (!status) {
|
||||
@@ -198,7 +202,11 @@ async function onRetry() {
|
||||
<header class="flex flex-wrap items-start justify-between gap-2">
|
||||
<div>
|
||||
<h2 class="text-sm font-semibold">{{ t('chat.shippingOrderReview.customerResolution.title') }}</h2>
|
||||
<p class="mt-0.5 text-xs text-muted">{{ t('chat.shippingOrderReview.customerResolution.subtitle') }}</p>
|
||||
<p class="mt-0.5 text-xs text-muted">
|
||||
{{ hasUniqueCandidate
|
||||
? t('chat.shippingOrderReview.customerResolution.uniqueCandidateHint')
|
||||
: t('chat.shippingOrderReview.customerResolution.subtitle') }}
|
||||
</p>
|
||||
</div>
|
||||
<span
|
||||
class="rounded-full px-2.5 py-1 text-xs font-medium"
|
||||
@@ -244,7 +252,9 @@ async function onRetry() {
|
||||
:disabled="busy"
|
||||
@click="openSelectDialog"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.customerResolution.selectCustomer') }}
|
||||
{{ hasUniqueCandidate
|
||||
? t('chat.shippingOrderReview.customerResolution.confirmUniqueCandidate')
|
||||
: t('chat.shippingOrderReview.customerResolution.selectCustomer') }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
|
||||
@@ -30,7 +30,7 @@ export type ReviewDocumentNavItem = {
|
||||
lifecycle_stage?: ReviewLifecycleStageCode | null;
|
||||
};
|
||||
|
||||
type ReviewLifecycleStageCode = 'intake_parse' | 'order_review' | 'fulfillment_prep' | 'upload_complete';
|
||||
type ReviewLifecycleStageCode = 'intake_parse' | 'order_review' | 'fulfillment_prep' | 'freight_upload' | 'upload_complete';
|
||||
|
||||
export type ReviewDocumentNavMode = 'hidden' | 'tabs' | 'sidebar' | 'sidebar_search' | 'narrow';
|
||||
|
||||
@@ -112,7 +112,7 @@ function caseStatusLabel(status: string): string {
|
||||
/** 后端阶段码只做 i18n 投影;缺失时保留空白,禁止按 Case 状态补造阶段。 */
|
||||
function lifecycleStageLabel(item: ReviewDocumentNavItem): string | null {
|
||||
const code = String(item.lifecycle_stage || '').trim() as ReviewLifecycleStageCode;
|
||||
if (!['intake_parse', 'order_review', 'fulfillment_prep', 'upload_complete'].includes(code)) return null;
|
||||
if (!['intake_parse', 'order_review', 'fulfillment_prep', 'freight_upload', 'upload_complete'].includes(code)) return null;
|
||||
const key = `chat.shippingOrderReview.lifecycle.stages.${code}`;
|
||||
return te(key) ? t(key) : null;
|
||||
}
|
||||
|
||||
+16
-1
@@ -31,7 +31,8 @@ const i18n = createI18n({
|
||||
customValue: '手工值', customPlaceholder: '请输入', submitCustom: '确认手工值',
|
||||
resolveReason: '人工裁决', resolveFailed: '提交失败', resolveSuccess: '已处理',
|
||||
fields: { part_number: '料号' }, reasons: { field_conflict: '字段冲突' },
|
||||
evidenceRole: {}, optionLabel: '候选 {index}', adoptOption: '采用候选值',
|
||||
evidenceRole: {}, recoveryAction: { reparse_current_pdf: '建议操作:重新识别此 PDF' },
|
||||
optionLabel: '候选 {index}', adoptOption: '采用候选值',
|
||||
},
|
||||
resume: { autoCreated: '已自动建单', waitingManualConfirm: '待人工确认' },
|
||||
} },
|
||||
@@ -57,6 +58,20 @@ describe('ReviewFieldConflictPanel', () => {
|
||||
expect(wrapper.find('[data-testid="review-field-conflict-custom-toggle"]').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it('shows the server-provided recovery action for a historical evidence gap', () => {
|
||||
const wrapper = mount(ReviewFieldConflictPanel, {
|
||||
props: {
|
||||
caseNo: 'SORC-1', draftVersion: 1, editable: true, conflicts: [],
|
||||
evidenceIssues: [{
|
||||
conflict_key: '-1:unit_price', field_code: 'unit_price', reason: 'supplement_conflict_evidence_insufficient',
|
||||
options: [], recovery_action: 'reparse_current_pdf',
|
||||
}],
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
expect(wrapper.get('[data-testid="review-evidence-issue-recovery-action"]').text()).toContain('重新识别此 PDF');
|
||||
});
|
||||
|
||||
it('refreshes the case when confirming a stale manual value returns conflict-not-found', async () => {
|
||||
resolveFieldConflict.mockRejectedValueOnce(new BusinessError({
|
||||
message: 'Field conflict not found',
|
||||
|
||||
@@ -73,6 +73,16 @@ function evidenceRoleLabel(role: string | undefined | null): string {
|
||||
return te(key) ? t(key) : code;
|
||||
}
|
||||
|
||||
/**
|
||||
* 显示服务端指定的恢复动作;页面只解释并复用既有顶部操作,不自行发起重识别。
|
||||
*/
|
||||
function recoveryActionLabel(action: string | undefined | null): string {
|
||||
const code = String(action || '').trim();
|
||||
if (!code) return '';
|
||||
const key = `chat.shippingOrderReview.fieldConflict.recoveryAction.${code}`;
|
||||
return te(key) ? t(key) : code;
|
||||
}
|
||||
|
||||
/**
|
||||
* 定位冲突字段到草稿/证据区。
|
||||
*/
|
||||
@@ -311,6 +321,13 @@ async function submitCustom(conflict: ShippingOrderReviewFieldConflict) {
|
||||
<span class="text-muted">{{ scopeLabel(issue.scope) }} · </span>
|
||||
<span class="font-mono">{{ fieldLabel(issue.field_code) }}</span>
|
||||
</span>
|
||||
<span
|
||||
v-if="recoveryActionLabel(issue.recovery_action)"
|
||||
class="text-[11px] text-amber-800 dark:text-amber-200"
|
||||
data-testid="review-evidence-issue-recovery-action"
|
||||
>
|
||||
{{ recoveryActionLabel(issue.recovery_action) }}
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
class="text-[11px] text-primary underline-offset-2 hover:underline"
|
||||
|
||||
+18
-263
@@ -1,275 +1,30 @@
|
||||
<!--
|
||||
features/chat/components/shipping-review/ReviewFulfillmentDecisionPanel.vue
|
||||
用途:复核工作台行级履约决定(等待补货 / 完整行先行 / 关闭)。
|
||||
依赖:vue-i18n、decide/wave line-fulfillment API、showReviewResumeOutcome。
|
||||
逻辑:分列展示料号/需求数量/可用数量/预约单号/状态;禁止 part_number 回退预约单号;
|
||||
逐行决定;选中 fulfill 行可确认波次;关闭 emit open-close-dialog。
|
||||
-->
|
||||
<!-- 履约摘要侧栏;完整明细与批量出单统一由主库存表承载。 -->
|
||||
<script setup lang="ts">
|
||||
import { computed, ref } from 'vue';
|
||||
import { computed } 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);
|
||||
import type { ShippingOrderReviewLineFulfillment } 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 } = useI18n();
|
||||
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);
|
||||
}
|
||||
const openLines = computed(() => (props.lineFulfillment?.lines || []).filter((line) => !TERMINAL_STATUSES.has(String(line.line_status || ''))));
|
||||
const visible = computed(() => Boolean(props.lineFulfillment?.has_open_lines || props.lineFulfillment?.has_shortage));
|
||||
function onCloseRemaining() { emit('open-close-dialog', openLines.value.map((line) => line.line_key)); }
|
||||
</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"
|
||||
>
|
||||
<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>
|
||||
<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.railHint') }}</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.requiredQty') }}</th>
|
||||
<th class="px-1 py-1 font-medium">{{ t('chat.shippingOrderReview.fulfillmentDecision.availableQty') }}</th>
|
||||
<th class="px-1 py-1 font-medium">{{ t('chat.shippingOrderReview.fulfillmentDecision.reservationId') }}</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" data-testid="review-fulfill-part-number">
|
||||
{{ line.part_number || t('chat.shippingOrderReview.fulfillmentDecision.partUnrecognized') }}
|
||||
</td>
|
||||
<td class="px-1 py-1">{{ line.required_qty ?? '—' }}</td>
|
||||
<td class="px-1 py-1">{{ line.available_qty ?? '—' }}</td>
|
||||
<td class="px-1 py-1 font-mono">{{ line.reservation_id || '—' }}</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 class="mt-2 grid grid-cols-2 gap-2 text-xs sm:grid-cols-4">
|
||||
<div class="rounded-lg bg-white/70 px-2.5 py-2 dark:bg-slate-900/50">{{ t('chat.shippingOrderReview.fulfillmentDecision.readyCount', { count: lineFulfillment?.ready_count ?? 0 }) }}</div>
|
||||
<div class="rounded-lg bg-white/70 px-2.5 py-2 dark:bg-slate-900/50">{{ t('chat.shippingOrderReview.fulfillmentDecision.shortageCount', { count: lineFulfillment?.manual_pending_count ?? 0 }) }}</div>
|
||||
<div class="rounded-lg bg-white/70 px-2.5 py-2 dark:bg-slate-900/50">{{ t('chat.shippingOrderReview.fulfillmentDecision.autoProgressCount', { count: lineFulfillment?.auto_progress_count ?? 0 }) }}</div>
|
||||
<div class="rounded-lg bg-white/70 px-2.5 py-2 dark:bg-slate-900/50">{{ t('chat.shippingOrderReview.fulfillmentDecision.summaryHint') }}</div>
|
||||
</div>
|
||||
<div v-if="editable && openLines.length" class="mt-3"><button 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 dark:border-rose-800 dark:bg-slate-900 dark:text-rose-200" data-testid="review-fulfillment-close-remaining" @click="onCloseRemaining">{{ t('chat.shippingOrderReview.fulfillmentDecision.closeRemaining') }}</button></div>
|
||||
</section>
|
||||
</template>
|
||||
+38
-2
@@ -17,10 +17,12 @@ const i18n = createI18n({
|
||||
messages: {
|
||||
'zh-CN': {
|
||||
chat: {
|
||||
shippingNoticeRetryParse: '重试解析',
|
||||
shippingOrderReview: {
|
||||
lifecycle: {
|
||||
navigation: '订单生命周期阶段',
|
||||
current: '当前可处理',
|
||||
processing: '处理中',
|
||||
completed: '已完成,可查看',
|
||||
blocked: '前置未完成',
|
||||
},
|
||||
@@ -33,18 +35,43 @@ const i18n = createI18n({
|
||||
const stages: ReviewLifecycleStageItem[] = [
|
||||
{ code: 'order_review', label: '订单复核', state: 'completed' },
|
||||
{ code: 'fulfillment_prep', label: '通知准备', state: 'current' },
|
||||
{ code: 'freight_upload', label: '货代上传', state: 'blocked', reason: '请先完成通知准备' },
|
||||
{ code: 'upload_complete', label: '通知完成', state: 'blocked', reason: '请先完成通知准备' },
|
||||
];
|
||||
|
||||
/** 挂载导航,复用真实 i18n 以覆盖状态文案渲染。 */
|
||||
function mountNavigation() {
|
||||
return mount(ReviewLifecycleStageNavigation, {
|
||||
props: { stages, activeCode: 'fulfillment_prep' },
|
||||
props: { stages, activeCode: 'fulfillment_prep', processingCode: 'fulfillment_prep' },
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
}
|
||||
|
||||
describe('ReviewLifecycleStageNavigation', () => {
|
||||
it('only exposes retry_parse on the current intake stage when the server authorizes it', async () => {
|
||||
const wrapper = mount(ReviewLifecycleStageNavigation, {
|
||||
props: {
|
||||
stages: [
|
||||
{ code: 'intake_parse', label: '接收解析', state: 'current' },
|
||||
...stages,
|
||||
],
|
||||
activeCode: 'intake_parse',
|
||||
availableActions: ['retry_parse'],
|
||||
retrying: false,
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
|
||||
// 关键断言:重试入口必须位于已发送文件的当前阶段卡,且完全由后端动作授权。
|
||||
const retry = wrapper.get('[data-testid="review-lifecycle-stage-retry-parse"]');
|
||||
expect(retry.text()).toContain('重试解析');
|
||||
await retry.trigger('click');
|
||||
expect(wrapper.emitted('retry-parse')).toEqual([[]]);
|
||||
|
||||
await wrapper.setProps({ availableActions: [] });
|
||||
expect(wrapper.find('[data-testid="review-lifecycle-stage-retry-parse"]').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it('renders intake_parse as the first lifecycle stage', () => {
|
||||
const wrapper = mount(ReviewLifecycleStageNavigation, {
|
||||
props: {
|
||||
@@ -63,9 +90,10 @@ describe('ReviewLifecycleStageNavigation', () => {
|
||||
'review-lifecycle-stage-intake_parse',
|
||||
'review-lifecycle-stage-order_review',
|
||||
'review-lifecycle-stage-fulfillment_prep',
|
||||
'review-lifecycle-stage-freight_upload',
|
||||
'review-lifecycle-stage-upload_complete',
|
||||
]);
|
||||
expect(wrapper.find('[data-testid="review-lifecycle-stage-navigation"] > div').classes()).toContain('sm:grid-cols-4');
|
||||
expect(wrapper.find('[data-testid="review-lifecycle-stage-navigation"] > div').classes()).toContain('sm:grid-cols-5');
|
||||
});
|
||||
|
||||
it('allows opening a completed stage for inspection', async () => {
|
||||
@@ -75,6 +103,14 @@ describe('ReviewLifecycleStageNavigation', () => {
|
||||
expect(wrapper.emitted('select')).toEqual([['order_review']]);
|
||||
});
|
||||
|
||||
it('shows a spinner and processing label on the active stage while automation runs', () => {
|
||||
const wrapper = mountNavigation();
|
||||
const stage = wrapper.get('[data-testid="review-lifecycle-stage-fulfillment_prep"]');
|
||||
expect(stage.attributes('data-processing')).toBe('1');
|
||||
expect(stage.text()).toContain('处理中');
|
||||
expect(stage.find('[data-testid="review-lifecycle-stage-spinner"]').exists()).toBe(true);
|
||||
});
|
||||
|
||||
it('disables a future stage and does not emit a selection', async () => {
|
||||
const wrapper = mountNavigation();
|
||||
const future = wrapper.get('[data-testid="review-lifecycle-stage-upload_complete"]');
|
||||
|
||||
+38
-5
@@ -1,13 +1,13 @@
|
||||
<!--
|
||||
features/chat/components/shipping-review/ReviewLifecycleStageNavigation.vue
|
||||
用途:订单生命周期工作台的四阶段导航,只呈现父级已裁决的阶段状态。
|
||||
用途:订单生命周期工作台的五阶段导航,只呈现父级已裁决的阶段状态。
|
||||
依赖:父级 ShippingOrderReviewView 提供阶段、状态和阻断原因;lucide-vue-next 图标。
|
||||
逻辑:用户可打开当前或已完成阶段查看;后续阶段由父级传入 blocked 并禁用,本组件不写业务状态。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { Check, LockKeyhole } from 'lucide-vue-next';
|
||||
import { Check, LockKeyhole, RefreshCw } from 'lucide-vue-next';
|
||||
|
||||
export type ReviewLifecycleStageCode = 'intake_parse' | 'order_review' | 'fulfillment_prep' | 'upload_complete';
|
||||
export type ReviewLifecycleStageCode = 'intake_parse' | 'order_review' | 'fulfillment_prep' | 'freight_upload' | 'upload_complete';
|
||||
export type ReviewLifecycleStageState = 'current' | 'completed' | 'blocked';
|
||||
|
||||
export interface ReviewLifecycleStageItem {
|
||||
@@ -21,13 +21,27 @@ const props = defineProps<{
|
||||
stages: ReviewLifecycleStageItem[];
|
||||
/** 后端尚未下发入口时为空;导航只能展示加载/未授权态,不能自行指定订单复核。 */
|
||||
activeCode: ReviewLifecycleStageCode | null;
|
||||
/** 仅消费当前对象后端下发的恢复动作,禁止按阶段或状态由前端猜测。 */
|
||||
availableActions?: string[];
|
||||
/** 当前阶段正在执行自动推进时的技术阶段码;只影响展示,不授权动作。 */
|
||||
processingCode?: ReviewLifecycleStageCode | null;
|
||||
/** retry_parse 请求中的互斥状态,避免用户重复提交。 */
|
||||
retrying?: boolean;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
select: [code: ReviewLifecycleStageCode];
|
||||
'open-detail': [code: ReviewLifecycleStageCode];
|
||||
'retry-parse': [];
|
||||
}>();
|
||||
|
||||
/** 接收解析的恢复只在后端明确授权且该阶段为当前阶段时展示。 */
|
||||
function canRetryParse(stage: ReviewLifecycleStageItem): boolean {
|
||||
return stage.code === 'intake_parse'
|
||||
&& stage.state === 'current'
|
||||
&& (props.availableActions || []).includes('retry_parse');
|
||||
}
|
||||
|
||||
/**
|
||||
* 阶段导航只允许进入当前或已完成阶段;blocked 仅说明前置条件,不替代后端 Gate 判定。
|
||||
*/
|
||||
@@ -43,7 +57,7 @@ function selectStage(stage: ReviewLifecycleStageItem) {
|
||||
:aria-label="$t('chat.shippingOrderReview.lifecycle.navigation')"
|
||||
data-testid="review-lifecycle-stage-navigation"
|
||||
>
|
||||
<div class="grid gap-2 sm:grid-cols-4">
|
||||
<div class="grid gap-2 sm:grid-cols-5">
|
||||
<div
|
||||
v-for="stage in props.stages"
|
||||
:key="stage.code"
|
||||
@@ -55,8 +69,15 @@ function selectStage(stage: ReviewLifecycleStageItem) {
|
||||
stage.state === 'blocked' ? 'opacity-60' : '',
|
||||
]"
|
||||
:data-testid="`review-lifecycle-stage-${stage.code}`"
|
||||
:data-processing="stage.code === props.processingCode ? '1' : '0'"
|
||||
>
|
||||
<span class="flex items-center gap-2 text-sm font-semibold">
|
||||
<RefreshCw
|
||||
v-if="stage.code === props.processingCode"
|
||||
class="h-4 w-4 shrink-0 animate-spin text-brand-600"
|
||||
data-testid="review-lifecycle-stage-spinner"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
<Check v-if="stage.state === 'completed'" class="h-4 w-4 shrink-0 text-emerald-600" />
|
||||
<LockKeyhole v-else-if="stage.state === 'blocked'" class="h-4 w-4 shrink-0 text-muted" />
|
||||
<span v-else class="h-2 w-2 shrink-0 rounded-full bg-brand-600" aria-hidden="true" />
|
||||
@@ -76,11 +97,23 @@ function selectStage(stage: ReviewLifecycleStageItem) {
|
||||
@click="selectStage(stage)"
|
||||
>
|
||||
{{ stage.state === 'current'
|
||||
? $t('chat.shippingOrderReview.lifecycle.current')
|
||||
? (stage.code === props.processingCode
|
||||
? $t('chat.shippingOrderReview.lifecycle.processing')
|
||||
: $t('chat.shippingOrderReview.lifecycle.current'))
|
||||
: stage.state === 'completed'
|
||||
? $t('chat.shippingOrderReview.lifecycle.completed')
|
||||
: (stage.reason || $t('chat.shippingOrderReview.lifecycle.blocked')) }}
|
||||
</button>
|
||||
<button
|
||||
v-if="canRetryParse(stage)"
|
||||
type="button"
|
||||
class="mt-2 rounded border border-brand-300 px-2 py-1 text-xs font-medium text-brand-700 hover:bg-brand-50 disabled:cursor-not-allowed disabled:opacity-60 dark:border-brand-700 dark:text-brand-200 dark:hover:bg-brand-950/40"
|
||||
data-testid="review-lifecycle-stage-retry-parse"
|
||||
:disabled="props.retrying === true"
|
||||
@click="emit('retry-parse')"
|
||||
>
|
||||
{{ $t('chat.shippingNoticeRetryParse') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</nav>
|
||||
|
||||
@@ -18,6 +18,11 @@ const i18n = createI18n({
|
||||
title: '文档模板匹配', subtitle: '摘要', selected: '命中模板', noSelected: '未选定模板',
|
||||
expandCandidates: '查看候选模板({count})', collapseCandidates: '收起候选模板',
|
||||
routeType: '路由类型', executionMode: '执行模式',
|
||||
extractionBlocked: '模板已命中,但字段提取仍被安全门禁阻断', extractionBlockedReason: '阻断原因:{reasons}',
|
||||
coordinateModel: {
|
||||
anchorFrame: '锚点坐标框架', status: '变换状态', translateX: '横向平移',
|
||||
translateY: '纵向平移', reasonCodes: '原因码',
|
||||
},
|
||||
status: { matched: '已匹配', ambiguous: '多个候选' },
|
||||
} } },
|
||||
},
|
||||
@@ -44,6 +49,34 @@ function mountPanel(needsReview = false) {
|
||||
});
|
||||
}
|
||||
|
||||
function mountAnchorFramePanel(visibility: 'admin' | 'admin_only' = 'admin') {
|
||||
return mount(ReviewProfileMatchPanel, {
|
||||
props: {
|
||||
profileMatch: {
|
||||
available: true,
|
||||
visibility,
|
||||
status: 'unique_match',
|
||||
needs_review: false,
|
||||
selected_profile: { profile_code: 'ODP-A', display_name: '客户订单模板', version: 1 },
|
||||
candidates: [{
|
||||
profile_code: 'ODP-A',
|
||||
version: 1,
|
||||
display_name: '客户订单模板',
|
||||
score: 0.99,
|
||||
coordinate_transform: {
|
||||
status: 'applied',
|
||||
translate_x: 0.001,
|
||||
translate_y: 0.03,
|
||||
reason_codes: [],
|
||||
},
|
||||
}],
|
||||
fallback_reason_codes: [],
|
||||
},
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
}
|
||||
|
||||
describe('ReviewProfileMatchPanel', () => {
|
||||
it('默认收起无需关注的候选列表', () => {
|
||||
const wrapper = mountPanel(false);
|
||||
@@ -69,4 +102,44 @@ describe('ReviewProfileMatchPanel', () => {
|
||||
expect(wrapper.get('[data-testid="review-profile-match-candidates"]').text()).toContain('客户订单模板');
|
||||
expect(wrapper.get('[data-testid="review-profile-match-candidates"]').text()).not.toContain('ODP-A');
|
||||
});
|
||||
|
||||
it('唯一命中时仍展示下游字段提取门禁的阻断原因', () => {
|
||||
const wrapper = mount(ReviewProfileMatchPanel, {
|
||||
props: {
|
||||
profileMatch: {
|
||||
available: true,
|
||||
visibility: 'admin',
|
||||
status: 'unique_match',
|
||||
needs_review: true,
|
||||
selected_profile: { profile_code: 'ODP-A', display_name: '客户订单模板', version: 1 },
|
||||
candidates: [{ profile_code: 'ODP-A', display_name: '客户订单模板', score: 0.99 }],
|
||||
fallback_reason_codes: ['PARSE_STRATEGY_ROW_MODE_AMBIGUOUS'],
|
||||
},
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
|
||||
// 关键断言:唯一模板命中不等于字段已提取,必须明确暴露下游阻断原因。
|
||||
expect(wrapper.get('[data-testid="review-profile-match-extraction-blocked"]').text())
|
||||
.toContain('PARSE_STRATEGY_ROW_MODE_AMBIGUOUS');
|
||||
});
|
||||
|
||||
it('管理员技术详情展示锚点框架平移和稳定原因码,不展示原始正文或完整坐标', async () => {
|
||||
const wrapper = mountAnchorFramePanel();
|
||||
|
||||
await wrapper.get('[data-testid="review-profile-match-candidates-toggle"]').trigger('click');
|
||||
|
||||
const details = wrapper.get('[data-testid="review-profile-match-details"]');
|
||||
expect(details.text()).toContain('锚点坐标框架');
|
||||
expect(details.text()).toContain('纵向平移');
|
||||
expect(details.text()).toContain('0.03');
|
||||
expect(details.text()).not.toContain('ORDER NO.');
|
||||
expect(details.text()).not.toContain('x0');
|
||||
});
|
||||
|
||||
it('非管理员不可见锚点框架技术详情', async () => {
|
||||
const wrapper = mountAnchorFramePanel('admin_only');
|
||||
expect(wrapper.find('[data-testid="review-profile-match-panel"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="review-profile-match-coordinate-transform"]').exists()).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -30,6 +30,23 @@ const candidateCount = computed(() => (props.profileMatch?.candidates || []).len
|
||||
const defaultCandidatesExpanded = computed(() => false);
|
||||
const candidatesOpenOverride = ref<boolean | null>(null);
|
||||
const candidatesExpanded = computed(() => candidatesOpenOverride.value ?? defaultCandidatesExpanded.value);
|
||||
const selectedCoordinateTransform = computed(() => {
|
||||
if (!isAdminView.value) return null;
|
||||
const selectedCode = String(props.profileMatch?.selected_profile?.profile_code || '');
|
||||
const selectedVersion = props.profileMatch?.selected_profile?.version;
|
||||
const candidate = (props.profileMatch?.candidates || []).find((item) => (
|
||||
item.profile_code === selectedCode
|
||||
&& (selectedVersion == null || item.version === selectedVersion)
|
||||
));
|
||||
return candidate?.coordinate_transform || null;
|
||||
});
|
||||
const coordinateTransformReasonCodes = computed(() => (
|
||||
selectedCoordinateTransform.value?.reason_codes || []
|
||||
));
|
||||
/** 唯一命中仅证明版式身份;下游字段/明细恢复若受门禁阻断,必须在同卡明确说明。 */
|
||||
const extractionBlockReasons = computed(() => (
|
||||
(props.profileMatch?.fallback_reason_codes || []).filter((code) => String(code).trim())
|
||||
));
|
||||
|
||||
watch(
|
||||
() => `${props.profileMatch?.status || ''}:${props.profileMatch?.selected_profile?.profile_code || ''}:${candidateCount.value}`,
|
||||
@@ -95,6 +112,17 @@ const selectedLabel = computed(() => {
|
||||
</div>
|
||||
</dl>
|
||||
|
||||
<div
|
||||
v-if="extractionBlockReasons.length"
|
||||
class="mt-3 rounded-lg border border-amber-200 bg-amber-50 px-2.5 py-2 text-xs text-amber-900 dark:border-amber-900 dark:bg-amber-950/30 dark:text-amber-100"
|
||||
data-testid="review-profile-match-extraction-blocked"
|
||||
>
|
||||
<p class="font-medium">{{ t('chat.shippingOrderReview.profileMatch.extractionBlocked') }}</p>
|
||||
<p class="mt-1 text-amber-800 dark:text-amber-200">
|
||||
{{ t('chat.shippingOrderReview.profileMatch.extractionBlockedReason', { reasons: extractionBlockReasons.join(', ') }) }}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<template v-if="isAdminView && candidateCount">
|
||||
<button
|
||||
type="button"
|
||||
@@ -118,6 +146,17 @@ const selectedLabel = computed(() => {
|
||||
<dt class="text-muted">{{ t('chat.shippingOrderReview.profileMatch.executionMode') }}</dt>
|
||||
<dd class="font-mono">{{ profileMatch.execution_mode }}</dd>
|
||||
</div>
|
||||
<div v-if="selectedCoordinateTransform" data-testid="review-profile-match-coordinate-transform" class="mt-2 rounded-lg border border-sky-200 bg-sky-50 px-2.5 py-2 text-[11px] text-sky-950 dark:border-sky-900 dark:bg-sky-950/30 dark:text-sky-100">
|
||||
<div class="font-medium">{{ t('chat.shippingOrderReview.profileMatch.coordinateModel.anchorFrame') }}</div>
|
||||
<div class="mt-1 flex flex-wrap gap-x-3 gap-y-1">
|
||||
<span>{{ t('chat.shippingOrderReview.profileMatch.coordinateModel.status') }}: {{ selectedCoordinateTransform.status }}</span>
|
||||
<span v-if="selectedCoordinateTransform.translate_x != null">{{ t('chat.shippingOrderReview.profileMatch.coordinateModel.translateX') }}: {{ selectedCoordinateTransform.translate_x }}</span>
|
||||
<span v-if="selectedCoordinateTransform.translate_y != null">{{ t('chat.shippingOrderReview.profileMatch.coordinateModel.translateY') }}: {{ selectedCoordinateTransform.translate_y }}</span>
|
||||
</div>
|
||||
<div v-if="coordinateTransformReasonCodes.length" class="mt-1">
|
||||
{{ t('chat.shippingOrderReview.profileMatch.coordinateModel.reasonCodes') }}: {{ coordinateTransformReasonCodes.join(', ') }}
|
||||
</div>
|
||||
</div>
|
||||
</dl>
|
||||
<ul
|
||||
class="mt-2 max-h-48 space-y-1.5 overflow-y-auto pr-1"
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
/**
|
||||
* features/chat/components/shipping-review/ReviewReservationPanel.spec.ts
|
||||
* 用途:验证 Reservation 校验面板只展示问题与重新校验入口,不重复提供明细编辑入口。
|
||||
* 依赖:Vue Test Utils、vue-i18n、Reservation 重校验 API。
|
||||
* 逻辑:挂载存在异常的 Reservation 面板,确认问题文案与重新校验按钮保留,编辑按钮不再出现。
|
||||
*/
|
||||
import { mount } from '@vue/test-utils';
|
||||
import { createI18n } from 'vue-i18n';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import chatZhCn from '@/locales/zh-CN/chat.json';
|
||||
import ReviewReservationPanel from './ReviewReservationPanel.vue';
|
||||
|
||||
vi.mock('@/features/chat/api/shipping.api', () => ({
|
||||
revalidateWorkspaceShippingOrderReviewReservation: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('@/shared/composables/useMessage', () => ({
|
||||
useMessage: () => ({ success: vi.fn(), warning: vi.fn(), error: vi.fn(), info: vi.fn() }),
|
||||
}));
|
||||
|
||||
vi.mock('@/features/chat/shipping-review/showReviewResumeOutcome', () => ({
|
||||
showReviewResumeOutcome: vi.fn(),
|
||||
}));
|
||||
|
||||
const i18n = createI18n({
|
||||
legacy: false,
|
||||
locale: 'zh-CN',
|
||||
messages: { 'zh-CN': { chat: chatZhCn } },
|
||||
});
|
||||
|
||||
describe('ReviewReservationPanel', () => {
|
||||
it('只保留校验提示和重新校验入口,不重复提供明细编辑按钮', () => {
|
||||
const wrapper = mount(ReviewReservationPanel, {
|
||||
props: {
|
||||
caseNo: 'CASE-1',
|
||||
draftVersion: 3,
|
||||
editable: true,
|
||||
reservation: {
|
||||
needs_attention: true,
|
||||
status: 'needs_attention',
|
||||
issues: [{ code: 'reservation_missing', severity: 'blocking', line_index: 0 }],
|
||||
lines: [{
|
||||
line_key: 'line-1',
|
||||
line_index: 0,
|
||||
effective_reservation_id: null,
|
||||
needs_attention: true,
|
||||
block_reason: 'reservation_missing',
|
||||
}],
|
||||
},
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
|
||||
expect(wrapper.text()).toContain('缺少预约单号');
|
||||
expect(wrapper.get('[data-testid="review-reservation-revalidate"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="review-reservation-focus-line"]').exists()).toBe(false);
|
||||
expect(wrapper.text()).not.toContain('编辑此行');
|
||||
});
|
||||
});
|
||||
@@ -2,7 +2,7 @@
|
||||
features/chat/components/shipping-review/ReviewReservationPanel.vue
|
||||
用途:复核工作台 Reservation 校验摘要;展示行级有效预约号与阻断 issue。
|
||||
依赖:vue-i18n、revalidateWorkspaceShippingOrderReviewReservation、showReviewResumeOutcome。
|
||||
逻辑:needs_attention 时展示;编辑聚焦明细行;重校验后 emit refreshed 并展示 resume 提示。
|
||||
逻辑:needs_attention 时展示问题;左侧订单明细是唯一编辑位置;重校验后 emit refreshed 并展示 resume 提示。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, ref } from 'vue';
|
||||
@@ -20,10 +20,7 @@ const props = defineProps<{
|
||||
editable: boolean;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
refreshed: [];
|
||||
'focus-line': [lineIndex: number];
|
||||
}>();
|
||||
const emit = defineEmits<{ refreshed: [] }>();
|
||||
|
||||
const { t, te } = useI18n();
|
||||
const msg = useMessage();
|
||||
@@ -55,14 +52,6 @@ function issueLabel(code: string | null | undefined): string {
|
||||
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 / 建单资格。
|
||||
*/
|
||||
@@ -128,13 +117,16 @@ async function onRevalidate() {
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
<p v-if="editable" class="mt-2 text-xs text-violet-900 dark:text-violet-200">
|
||||
{{ t('chat.shippingOrderReview.reservation.editHint') }}
|
||||
</p>
|
||||
|
||||
<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>
|
||||
@@ -151,17 +143,6 @@ async function onRevalidate() {
|
||||
{{ 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>
|
||||
|
||||
+19
-2
@@ -2,7 +2,7 @@
|
||||
* features/chat/components/shipping-review/ReviewWorkbenchFooter.spec.ts
|
||||
* 用途:验证字段冲突的 Gate 主动作只由右栏当前任务卡承载,底栏不得重复展示。
|
||||
* 依赖:Vitest、Vue Test Utils、Vue I18n、ReviewWorkbenchFooter。
|
||||
* 逻辑:订单复核底栏只保留保存校验,不展示已由当前任务卡或阶段页承载的流程动作。
|
||||
* 逻辑:订单复核底栏只保留提交订单,不展示已由当前任务卡或阶段页承载的流程动作。
|
||||
*/
|
||||
import { mount } from '@vue/test-utils';
|
||||
import { createI18n } from 'vue-i18n';
|
||||
@@ -16,7 +16,11 @@ const i18n = createI18n({
|
||||
'zh-CN': {
|
||||
chat: {
|
||||
shippingProcessing: { action: { resolve_field_conflicts: '处理字段冲突', view_result: '查看结果', none: '无操作' } },
|
||||
shippingOrderReview: { unsavedSwitch: { unsavedCount: '未保存 {count} 项' } },
|
||||
shippingOrderReview: {
|
||||
saveOrderAndValidate: '提交订单',
|
||||
submitOrderHint: '提交后自动校验,满足条件将自动建单。',
|
||||
unsavedSwitch: { unsavedCount: '未保存 {count} 项' },
|
||||
},
|
||||
},
|
||||
workspace: { shippingNotice: { processGate: { actions: {} } } },
|
||||
},
|
||||
@@ -59,4 +63,17 @@ describe('ReviewWorkbenchFooter', () => {
|
||||
expect(wrapper.find('[data-testid="review-footer-flow-resolve_field_conflicts"]').exists()).toBe(false);
|
||||
expect(wrapper.find('[data-testid="review-footer-flow-view_result"]').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it('uses submit-order wording and explains the automatic creation policy', () => {
|
||||
const wrapper = mount(ReviewWorkbenchFooter, {
|
||||
props: {
|
||||
availableActions: ['validate'], canConfirmBuild: false, saving: false, isReadOnly: false, hasDraft: true,
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
|
||||
// 关键断言:唯一写入口完成提交语义;资格通过后的自动建单是系统行为,不要求第二次确认。
|
||||
expect(wrapper.text()).toContain('提交订单');
|
||||
expect(wrapper.get('[data-testid="review-submit-order-hint"]').text()).toBe('提交后自动校验,满足条件将自动建单。');
|
||||
});
|
||||
});
|
||||
@@ -3,7 +3,7 @@
|
||||
用途:订单处理工作台底部唯一写操作栏(处置 / 保存 / 统一流程动作)。
|
||||
依赖:vue-i18n、lucide-vue-next、ActionPresentation。
|
||||
逻辑:ShippingOrderReviewView 传入 available_actions 与流程动作投影;sticky bottom;
|
||||
订单复核只保留保存校验;流程动作由所属阶段或当前任务卡承载;写按钮受 actionsExecutable 约束;
|
||||
订单复核只保留提交订单;流程动作由所属阶段或当前任务卡承载;写按钮受 actionsExecutable 约束;
|
||||
流程写操作经 flow-action emit(与 Resolver 同链);flowBusy||saving 时禁用。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
@@ -76,7 +76,7 @@ function hasAction(action: string): boolean {
|
||||
/**
|
||||
* 订单复核底栏不承载流程投影动作。
|
||||
*
|
||||
* 核心逻辑:保存并校验是表单级提交,固定放在这里;字段裁决、重试、查看结果等
|
||||
* 核心逻辑:提交订单是表单级提交,固定放在这里;字段裁决、重试、查看结果等
|
||||
* Case/阶段级动作必须留在其业务上下文中,避免同一动作在顶栏、右栏和底栏重复出现。
|
||||
*/
|
||||
const footerFlowItems = computed((): ActionPresentationItem[] => []);
|
||||
@@ -171,6 +171,16 @@ const canWriteCaseActions = computed(() => props.actionsExecutable && !props.isR
|
||||
{{ autoGateHint || t('chat.shippingOrderReview.buildEligibility.autoGateWaitingHint') }}
|
||||
</p>
|
||||
<template v-if="!automating && canWriteCaseActions">
|
||||
<button
|
||||
v-if="showStpRetry && hasAction('retry_stp_auto_create')"
|
||||
type="button"
|
||||
:disabled="controlsBusy"
|
||||
class="inline-flex items-center gap-1 rounded border border-sky-300 px-3 py-2 text-sm text-sky-700 hover:bg-sky-50 disabled:opacity-50 dark:border-sky-700 dark:text-sky-300 dark:hover:bg-sky-950/40"
|
||||
data-testid="review-retry-stp-auto-create"
|
||||
@click="emit('retry-stp')"
|
||||
>
|
||||
<RefreshCw class="h-4 w-4" />{{ t('chat.shippingOrderReview.automation.retryStp') }}
|
||||
</button>
|
||||
<button
|
||||
v-if="showValidate && hasAction('validate')"
|
||||
type="button"
|
||||
@@ -180,6 +190,13 @@ const canWriteCaseActions = computed(() => props.actionsExecutable && !props.isR
|
||||
>
|
||||
<Save class="h-4 w-4" />{{ t('chat.shippingOrderReview.saveOrderAndValidate') }}
|
||||
</button>
|
||||
<p
|
||||
v-if="showValidate && hasAction('validate')"
|
||||
class="basis-full text-right text-xs text-muted"
|
||||
data-testid="review-submit-order-hint"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.submitOrderHint') }}
|
||||
</p>
|
||||
</template>
|
||||
</div>
|
||||
</footer>
|
||||
|
||||
+3
-3
@@ -23,9 +23,9 @@ const messages = {
|
||||
subtitle: 'Advances through freight upload',
|
||||
polling: 'Refreshing…',
|
||||
progressUnavailable: 'Progress unavailable — refresh the page.',
|
||||
openTaskWorkbench: 'Open Task Center to register',
|
||||
openTaskWorkbench: 'Open Task Center to confirm upload',
|
||||
nextStepsManualUpload:
|
||||
'Next: download Excel → upload on freight platform → submit evidence and receipt',
|
||||
'Next: download Excel → upload on freight platform → confirm uploaded',
|
||||
nextStepsGeneric: 'Manual action required — follow the system prompt.',
|
||||
},
|
||||
},
|
||||
@@ -194,7 +194,7 @@ describe('ReviewWorkflowProgressPanel', () => {
|
||||
});
|
||||
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 Center to register');
|
||||
expect(link.text()).toContain('Open Task Center to confirm upload');
|
||||
expect(link.attributes('href')).toContain('workspace-shipping-my-tasks');
|
||||
expect(link.attributes('href')).toContain('SN-1');
|
||||
});
|
||||
|
||||
+255
-143
@@ -22,65 +22,83 @@ const i18n = createI18n({
|
||||
});
|
||||
|
||||
function buildProjection(): ConversationProcessingProjection {
|
||||
const needsAction = {
|
||||
user_task_no: 'OT-NEED',
|
||||
group: 'needs_action' as const,
|
||||
status_label: 'pending_review',
|
||||
file_count: 2,
|
||||
run_no: 'RUN-NEED',
|
||||
can_append: false,
|
||||
recently_created: false,
|
||||
};
|
||||
const processing = {
|
||||
user_task_no: 'OT-PROC',
|
||||
submission_ordinal: 2,
|
||||
group: 'processing' as const,
|
||||
status_label: 'extracting',
|
||||
file_count: 1,
|
||||
run_no: 'RUN-PROC',
|
||||
can_append: true,
|
||||
recently_created: true,
|
||||
focused: true,
|
||||
};
|
||||
const completed = {
|
||||
user_task_no: 'OT-DONE',
|
||||
group: 'completed' as const,
|
||||
status_label: 'completed',
|
||||
title: 'done.pdf',
|
||||
file_count: 1,
|
||||
run_no: 'RUN-DONE',
|
||||
can_append: false,
|
||||
available_actions: ['view_details'],
|
||||
};
|
||||
const archived = {
|
||||
user_task_no: 'OT-HIST',
|
||||
group: 'history' as const,
|
||||
status_label: 'completed',
|
||||
file_count: 1,
|
||||
run_no: 'RUN-HIST',
|
||||
can_append: false,
|
||||
viewed: true,
|
||||
available_actions: ['view_details'],
|
||||
};
|
||||
const cancelled = {
|
||||
user_task_no: 'OT-CANCEL',
|
||||
group: 'history' as const,
|
||||
status_label: 'cancelled',
|
||||
file_count: 1,
|
||||
run_no: 'RUN-CANCEL',
|
||||
can_append: false,
|
||||
viewed: true,
|
||||
available_actions: ['view_details'],
|
||||
};
|
||||
return {
|
||||
summary: { total_tasks: 3, processing: 1, needs_action: 1, completed: 1, history: 2 },
|
||||
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,
|
||||
available_actions: ['view_details'],
|
||||
},
|
||||
{
|
||||
user_task_no: 'OT-CANCEL',
|
||||
group: 'history',
|
||||
status_label: 'cancelled',
|
||||
file_count: 1,
|
||||
run_no: 'RUN-CANCEL',
|
||||
can_append: false,
|
||||
viewed: true,
|
||||
available_actions: ['view_details'],
|
||||
},
|
||||
],
|
||||
status_groups: {
|
||||
failed: [needsAction], waiting_human: [], processing: [processing], completed: [completed],
|
||||
cancelled: [cancelled], archived: [archived],
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** 测试仅构造权威 status_groups;禁止再把旧四组作为组件输入。 */
|
||||
function setStatusGroup(
|
||||
projection: ConversationProcessingProjection,
|
||||
key: keyof NonNullable<ConversationProcessingProjection['status_groups']>,
|
||||
tasks: NonNullable<ConversationProcessingProjection['status_groups']>[keyof NonNullable<ConversationProcessingProjection['status_groups']>],
|
||||
) {
|
||||
projection.status_groups![key] = tasks;
|
||||
}
|
||||
|
||||
function projectionWithGroups(
|
||||
summary: ConversationProcessingProjection['summary'],
|
||||
groups: NonNullable<ConversationProcessingProjection['status_groups']>,
|
||||
): ConversationProcessingProjection {
|
||||
return { summary, status_groups: groups };
|
||||
}
|
||||
|
||||
/** 构造任务卡使用的权威统一进度。 */
|
||||
function buildWorkItem(
|
||||
taskNo: string,
|
||||
@@ -119,12 +137,12 @@ function buildWorkItem(
|
||||
describe('ShippingConversationProcessingCard', () => {
|
||||
it('only exposes file cancellation when the backend explicitly authorizes cancel_unit', async () => {
|
||||
const projection = buildProjection();
|
||||
projection.processing = [{
|
||||
setStatusGroup(projection, 'processing', [{
|
||||
user_task_no: 'OT-CANCEL-UNIT', group: 'processing', status_label: 'extracting',
|
||||
file_count: 1, run_no: 'RUN-CANCEL-UNIT', can_append: false,
|
||||
objects: [{ kind: 'document', object_key: 'DOC-9', label: 'cancel.pdf', filename: 'cancel.pdf',
|
||||
document_id: 9, root_document_id: 9, status_label: 'extracting' }],
|
||||
}];
|
||||
}]);
|
||||
const workItem = buildWorkItem('OT-CANCEL-UNIT', {
|
||||
availableActions: ['cancel_unit'],
|
||||
sourceSummary: { ...buildWorkItem('OT-CANCEL-UNIT').sourceSummary, documentId: 9 },
|
||||
@@ -151,12 +169,12 @@ describe('ShippingConversationProcessingCard', () => {
|
||||
|
||||
it('does not fall back to legacy cancellation when ui_state revokes it', async () => {
|
||||
const projection = buildProjection();
|
||||
projection.processing = [{
|
||||
setStatusGroup(projection, 'processing', [{
|
||||
user_task_no: 'OT-CANCEL-REVOKED', group: 'processing', status_label: 'extracting',
|
||||
file_count: 1, run_no: 'RUN-CANCEL-REVOKED', can_append: false,
|
||||
objects: [{ kind: 'document', object_key: 'DOC-10', label: 'revoked.pdf', filename: 'revoked.pdf',
|
||||
document_id: 10, root_document_id: 10, status_label: 'extracting' }],
|
||||
}];
|
||||
}]);
|
||||
const workItem = buildWorkItem('OT-CANCEL-REVOKED', {
|
||||
availableActions: ['cancel_unit'],
|
||||
sourceSummary: { ...buildWorkItem('OT-CANCEL-REVOKED').sourceSummary, documentId: 10 },
|
||||
@@ -181,11 +199,11 @@ describe('ShippingConversationProcessingCard', () => {
|
||||
|
||||
it('does not render legacy document_names as a batch file row without a live leaf projection', async () => {
|
||||
const projection = buildProjection();
|
||||
projection.processing = [{
|
||||
setStatusGroup(projection, 'processing', [{
|
||||
user_task_no: 'OT-HISTORICAL-SNAPSHOT', group: 'processing', status_label: 'extracting',
|
||||
title: 'legacy-run.pdf', document_names: ['legacy-run.pdf'], file_count: 1,
|
||||
run_no: 'RUN-HISTORICAL-SNAPSHOT', can_append: false,
|
||||
}];
|
||||
}]);
|
||||
const wrapper = mount(ShippingConversationProcessingCard, {
|
||||
props: { projection, workItems: [], workbenchMode: true },
|
||||
global: { plugins: [i18n] },
|
||||
@@ -199,7 +217,7 @@ describe('ShippingConversationProcessingCard', () => {
|
||||
|
||||
it('uses the live leaf summary instead of a stale task object in batch mode', async () => {
|
||||
const projection = buildProjection();
|
||||
projection.processing = [{
|
||||
setStatusGroup(projection, 'processing', [{
|
||||
user_task_no: 'OT-LIVE-LEAF', group: 'processing', status_label: 'extracting',
|
||||
title: 'snapshot-old-name.pdf', file_count: 1, run_no: 'RUN-LIVE-LEAF', can_append: false,
|
||||
objects: [{
|
||||
@@ -207,7 +225,7 @@ describe('ShippingConversationProcessingCard', () => {
|
||||
filename: 'snapshot-old-name.pdf', document_id: 88, root_document_id: 88,
|
||||
status_label: 'pending_review',
|
||||
}],
|
||||
}];
|
||||
}]);
|
||||
const live = buildWorkItem('OT-LIVE-LEAF', {
|
||||
runNo: 'RUN-LIVE-LEAF',
|
||||
sourceSummary: {
|
||||
@@ -235,12 +253,12 @@ describe('ShippingConversationProcessingCard', () => {
|
||||
|
||||
it('expands EML files only from the live aggregate work item', async () => {
|
||||
const projection = buildProjection();
|
||||
projection.processing = [{
|
||||
setStatusGroup(projection, 'processing', [{
|
||||
user_task_no: 'INTAKE:EML-LIVE', group: 'processing', status_label: 'extracting',
|
||||
title: 'snapshot-mail.eml', document_names: ['snapshot-attachment.pdf'],
|
||||
file_count: 1, run_no: 'RUN-EML-LIVE', can_append: false,
|
||||
aggregateChildren: [],
|
||||
}];
|
||||
}]);
|
||||
const liveChild = buildWorkItem('DOCUMENT:77', {
|
||||
sourceType: 'eml', rootOrderTaskNo: 'OT-EML-LIVE', runNo: 'RUN-EML-LIVE',
|
||||
sourceSummary: {
|
||||
@@ -275,12 +293,49 @@ describe('ShippingConversationProcessingCard', () => {
|
||||
expect(wrapper.text()).not.toContain('snapshot-attachment.pdf');
|
||||
});
|
||||
|
||||
it('counts only stage-filtered EML leaves in the batch status heading', async () => {
|
||||
const projection = buildProjection();
|
||||
setStatusGroup(projection, 'processing', [{
|
||||
user_task_no: 'INTAKE:MIXED-STAGES', group: 'processing', status_label: 'extracting',
|
||||
title: 'mixed-stages.eml', file_count: 2, run_no: 'RUN-MIXED-STAGES', can_append: false,
|
||||
}]);
|
||||
const orderReviewLeaf = buildWorkItem('DOCUMENT:401', {
|
||||
sourceType: 'eml', rootOrderTaskNo: 'OT-MIXED-STAGES',
|
||||
sourceSummary: { ...buildWorkItem('DOCUMENT:401').sourceSummary, documentId: 401, filename: 'review.pdf' },
|
||||
uiState: {
|
||||
status: 'waiting_human', stage: 'waiting_review', lifecycleStage: 'order_review',
|
||||
lifecycleEntries: [], blocking_reason: null, primary_action: null, secondary_actions: [],
|
||||
},
|
||||
});
|
||||
const freightLeaf = buildWorkItem('DOCUMENT:402', {
|
||||
sourceType: 'eml', rootOrderTaskNo: 'OT-MIXED-STAGES',
|
||||
sourceSummary: { ...buildWorkItem('DOCUMENT:402').sourceSummary, documentId: 402, filename: 'upload.xlsx' },
|
||||
uiState: {
|
||||
status: 'running', stage: 'freight_uploading', lifecycleStage: 'freight_upload',
|
||||
lifecycleEntries: [], blocking_reason: null, primary_action: null, secondary_actions: [],
|
||||
},
|
||||
});
|
||||
const root = buildWorkItem('INTAKE:MIXED-STAGES', {
|
||||
sourceType: 'eml', rootOrderTaskNo: 'OT-MIXED-STAGES',
|
||||
aggregateChildren: [orderReviewLeaf, freightLeaf],
|
||||
});
|
||||
const wrapper = mount(ShippingConversationProcessingCard, {
|
||||
props: { projection, workItems: [root], workbenchMode: true, lifecycleFilter: 'order_review' },
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
await flushPromises();
|
||||
|
||||
// 阶段卡与列表标题必须消费同一批可见叶子,不能把同一 EML 的其它阶段附件混入。
|
||||
expect(wrapper.get('[data-testid="shipping-processing-group-processing"]').text()).toContain('1 个文件');
|
||||
expect(wrapper.get('[data-testid="shipping-processing-group-processing"]').text()).not.toContain('2 个文件');
|
||||
});
|
||||
|
||||
it('keeps an EML attachment when it has a linked child order task', async () => {
|
||||
const projection = buildProjection();
|
||||
projection.processing = [{
|
||||
setStatusGroup(projection, 'processing', [{
|
||||
user_task_no: 'INTAKE:EML-WITH-CHILD-OT', group: 'processing', status_label: 'extracting',
|
||||
title: 'mail.eml', file_count: 2, run_no: 'RUN-EML-WITH-CHILD-OT', can_append: false,
|
||||
}];
|
||||
}]);
|
||||
const firstAttachment = buildWorkItem('OT-EML-WITH-CHILD-OT', {
|
||||
sourceType: 'eml', rootOrderTaskNo: 'OT-EML-WITH-CHILD-OT',
|
||||
sourceSummary: {
|
||||
@@ -416,9 +471,9 @@ describe('ShippingConversationProcessingCard', () => {
|
||||
it('uses expand-files as the only detail entry when canExpandFileDetails', async () => {
|
||||
const wrapper = mount(ShippingConversationProcessingCard, {
|
||||
props: {
|
||||
projection: {
|
||||
summary: { total_tasks: 1, processing: 0, needs_action: 1, completed: 0, history: 0 },
|
||||
needs_action: [{
|
||||
projection: projectionWithGroups(
|
||||
{ total_tasks: 1, processing: 0, needs_action: 1, completed: 0, history: 0 }, {
|
||||
failed: [{
|
||||
user_task_no: 'OT-MULTI',
|
||||
group: 'needs_action',
|
||||
status_label: 'pending_review',
|
||||
@@ -429,11 +484,8 @@ describe('ShippingConversationProcessingCard', () => {
|
||||
run_no: 'RUN-MULTI',
|
||||
can_append: false,
|
||||
available_actions: ['view_details', 'cancel_task'],
|
||||
}],
|
||||
processing: [],
|
||||
completed: [],
|
||||
history: [],
|
||||
},
|
||||
}], waiting_human: [], processing: [], completed: [], cancelled: [], archived: [],
|
||||
}),
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
@@ -455,9 +507,9 @@ describe('ShippingConversationProcessingCard', () => {
|
||||
it('shows view_details when task cannot expand file details, and keeps cancel as overflow', async () => {
|
||||
const wrapper = mount(ShippingConversationProcessingCard, {
|
||||
props: {
|
||||
projection: {
|
||||
summary: { total_tasks: 1, processing: 0, needs_action: 1, completed: 0, history: 0 },
|
||||
needs_action: [{
|
||||
projection: projectionWithGroups(
|
||||
{ total_tasks: 1, processing: 0, needs_action: 1, completed: 0, history: 0 }, {
|
||||
failed: [{
|
||||
user_task_no: 'OT-SINGLE',
|
||||
group: 'needs_action',
|
||||
status_label: 'pending_review',
|
||||
@@ -466,11 +518,8 @@ describe('ShippingConversationProcessingCard', () => {
|
||||
can_append: false,
|
||||
available_actions: ['view_details', 'cancel_task'],
|
||||
objects: [],
|
||||
}],
|
||||
processing: [],
|
||||
completed: [],
|
||||
history: [],
|
||||
},
|
||||
}], waiting_human: [], processing: [], completed: [], cancelled: [], archived: [],
|
||||
}),
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
@@ -485,9 +534,9 @@ describe('ShippingConversationProcessingCard', () => {
|
||||
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: [{
|
||||
projection: projectionWithGroups(
|
||||
{ total_tasks: 1, total_files: 2, processing: 0, needs_action: 1, completed: 0, history: 0 }, {
|
||||
failed: [{
|
||||
user_task_no: 'OT-MULTI',
|
||||
group: 'needs_action',
|
||||
status_label: 'pending_review',
|
||||
@@ -499,11 +548,8 @@ describe('ShippingConversationProcessingCard', () => {
|
||||
can_append: false,
|
||||
available_actions: ['view_details', 'cancel_task'],
|
||||
objects: [],
|
||||
}],
|
||||
processing: [],
|
||||
completed: [],
|
||||
history: [],
|
||||
},
|
||||
}], waiting_human: [], processing: [], completed: [], cancelled: [], archived: [],
|
||||
}),
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
@@ -518,10 +564,9 @@ describe('ShippingConversationProcessingCard', () => {
|
||||
it('uses unified order recognition title 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: [{
|
||||
projection: projectionWithGroups(
|
||||
{ total_tasks: 1, processing: 1, needs_action: 0, completed: 0, history: 0 }, {
|
||||
failed: [], waiting_human: [], processing: [{
|
||||
user_task_no: 'OT-20260803-A13F95D2',
|
||||
group: 'processing',
|
||||
status_label: 'processing',
|
||||
@@ -529,10 +574,8 @@ describe('ShippingConversationProcessingCard', () => {
|
||||
file_count: 1,
|
||||
run_no: 'SNER-X',
|
||||
can_append: false,
|
||||
}],
|
||||
completed: [],
|
||||
history: [],
|
||||
},
|
||||
}], completed: [], cancelled: [], archived: [],
|
||||
}),
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
@@ -558,16 +601,17 @@ describe('ShippingConversationProcessingCard', () => {
|
||||
const wrapper = mount(ShippingConversationProcessingCard, {
|
||||
props: {
|
||||
projection: {
|
||||
summary: { total_tasks: 1, processing: 0, needs_action: 0, completed: 1, history: 0 },
|
||||
...projectionWithGroups(
|
||||
{ total_tasks: 1, processing: 0, needs_action: 0, completed: 1, history: 0 }, {
|
||||
failed: [], waiting_human: [], processing: [], completed: [{
|
||||
user_task_no: 'OT-DETAIL', group: 'completed', status_label: 'completed',
|
||||
file_count: 1, run_no: 'RUN-DETAIL', can_append: false,
|
||||
available_actions: ['view_details'],
|
||||
}], cancelled: [], archived: [],
|
||||
},
|
||||
),
|
||||
focused_task_no: null,
|
||||
recent_task_no: null,
|
||||
needs_action: [],
|
||||
completed: [{
|
||||
user_task_no: 'OT-DETAIL', group: 'completed', status_label: 'completed',
|
||||
file_count: 1, run_no: 'RUN-DETAIL', can_append: false,
|
||||
available_actions: ['view_details'],
|
||||
}],
|
||||
processing: [], history: [],
|
||||
},
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
@@ -609,10 +653,13 @@ describe('ShippingConversationProcessingCard', () => {
|
||||
props: {
|
||||
projection: {
|
||||
...buildProjection(),
|
||||
needs_action: [{
|
||||
...buildProjection().needs_action[0],
|
||||
available_actions: ['view_details', 'open_review', 'cancel_task'],
|
||||
}],
|
||||
status_groups: {
|
||||
...buildProjection().status_groups!,
|
||||
failed: [{
|
||||
...buildProjection().status_groups!.failed[0],
|
||||
available_actions: ['view_details', 'open_review', 'cancel_task'],
|
||||
}],
|
||||
},
|
||||
},
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
@@ -632,12 +679,10 @@ describe('ShippingConversationProcessingCard', () => {
|
||||
}));
|
||||
const wrapper = mount(ShippingConversationProcessingCard, {
|
||||
props: {
|
||||
projection: {
|
||||
summary: { total_tasks: 20, processing: 20, needs_action: 0, history: 0 },
|
||||
needs_action: [],
|
||||
processing,
|
||||
history: [],
|
||||
},
|
||||
projection: projectionWithGroups(
|
||||
{ total_tasks: 20, processing: 20, needs_action: 0, history: 0 },
|
||||
{ failed: [], waiting_human: [], processing, completed: [], cancelled: [], archived: [] },
|
||||
),
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
@@ -649,9 +694,9 @@ describe('ShippingConversationProcessingCard', () => {
|
||||
it('renders an EML order_intake in the unified failed group rather than the removed intake side path', async () => {
|
||||
const wrapper = mount(ShippingConversationProcessingCard, {
|
||||
props: {
|
||||
projection: {
|
||||
summary: { total_tasks: 1, total_files: 1, processing: 0, needs_action: 1, completed: 0, history: 0 },
|
||||
needs_action: [{
|
||||
projection: projectionWithGroups(
|
||||
{ total_tasks: 1, total_files: 1, processing: 0, needs_action: 1, completed: 0, history: 0 }, {
|
||||
failed: [{
|
||||
user_task_no: 'SNI-1',
|
||||
group: 'needs_action',
|
||||
userGroup: 'failed',
|
||||
@@ -660,11 +705,8 @@ describe('ShippingConversationProcessingCard', () => {
|
||||
file_count: 1,
|
||||
run_no: null,
|
||||
can_append: false,
|
||||
}],
|
||||
processing: [],
|
||||
completed: [],
|
||||
history: [],
|
||||
},
|
||||
}], waiting_human: [], processing: [], completed: [], cancelled: [], archived: [],
|
||||
}),
|
||||
workItems: [{
|
||||
workItemType: 'order_intake',
|
||||
workItemNo: 'SNI-1',
|
||||
@@ -687,6 +729,15 @@ describe('ShippingConversationProcessingCard', () => {
|
||||
attemptNo: 2,
|
||||
},
|
||||
availableActions: ['view_details', 'retry_parse'],
|
||||
uiState: {
|
||||
status: 'failed',
|
||||
stage: 'document_parsing',
|
||||
lifecycleStage: 'intake_parse',
|
||||
lifecycleEntries: [],
|
||||
blocking_reason: { code: 'SHIPPING_NOTICE.INTAKE_PARSE_FAILED' },
|
||||
primary_action: { code: 'retry_parse', i18nKey: null, parameters: {}, executionMode: 'immediate' },
|
||||
secondary_actions: [],
|
||||
},
|
||||
sourceSummary: {
|
||||
emailSubject: null,
|
||||
filename: 'po.pdf',
|
||||
@@ -708,7 +759,9 @@ describe('ShippingConversationProcessingCard', () => {
|
||||
expect(wrapper.find('[data-testid="shipping-processing-group-failed"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="shipping-processing-task-SNI-1"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="shipping-processing-group-order-intake"]').exists()).toBe(false);
|
||||
expect(wrapper.text()).toContain('重试解析');
|
||||
// Intake retry_parse 与 Case reparse 对用户统一展示为“重新解析”;
|
||||
// 后端 action_code 仍保留不同对象边界与执行接口。
|
||||
expect(wrapper.text()).toContain('重新解析');
|
||||
});
|
||||
|
||||
it('keeps a human Gate action visible before and after selecting its task', async () => {
|
||||
@@ -726,6 +779,15 @@ describe('ShippingConversationProcessingCard', () => {
|
||||
blockingReasonCode: 'inventory_match_not_ready',
|
||||
},
|
||||
availableActions: ['open_inventory_match_review'],
|
||||
uiState: {
|
||||
status: 'waiting_human',
|
||||
stage: 'waiting_review',
|
||||
lifecycleStage: 'order_review',
|
||||
lifecycleEntries: [],
|
||||
blocking_reason: { code: 'inventory_match_not_ready' },
|
||||
primary_action: { code: 'open_inventory_match_review', i18nKey: null, parameters: {}, executionMode: 'immediate' },
|
||||
secondary_actions: [],
|
||||
},
|
||||
}),
|
||||
buildWorkItem('OT-PROC', {
|
||||
stage: 'inventory_matching',
|
||||
@@ -737,12 +799,12 @@ describe('ShippingConversationProcessingCard', () => {
|
||||
await flushPromises();
|
||||
|
||||
expect(wrapper.findAll('[data-testid="sidebar-progress-inline"]')).toHaveLength(2);
|
||||
expect(wrapper.find('[data-testid="shipping-processing-task-OT-NEED"]').text()).toContain('待复核');
|
||||
expect(wrapper.find('[data-testid="shipping-processing-task-OT-NEED"]').text()).toContain('待人工处理');
|
||||
expect(wrapper.find('[data-testid="shipping-processing-task-OT-PROC"]').text()).toContain('库存匹配');
|
||||
expect(wrapper.findAll('[data-testid="shipping-processing-task-actions"]')).toHaveLength(0);
|
||||
const task = wrapper.find('[data-testid="shipping-processing-task-OT-NEED"]');
|
||||
expect(task.find('[data-testid="unified-action-primary"]').exists()).toBe(true);
|
||||
expect(task.find('[data-testid="unified-action-primary"]').text()).toContain('库存');
|
||||
expect(task.find('[data-testid="unified-action-primary"]').text()).toContain('open_inventory_match_review');
|
||||
|
||||
await task.find('button').trigger('click');
|
||||
await flushPromises();
|
||||
@@ -754,10 +816,10 @@ describe('ShippingConversationProcessingCard', () => {
|
||||
|
||||
it('maps internal review_case_draft status to a user-facing review label', async () => {
|
||||
const projection = buildProjection();
|
||||
projection.needs_action = [{
|
||||
...projection.needs_action[0],
|
||||
setStatusGroup(projection, 'failed', [{
|
||||
...projection.status_groups!.failed[0],
|
||||
status_label: 'review_case_draft',
|
||||
}];
|
||||
}]);
|
||||
const wrapper = mount(ShippingConversationProcessingCard, {
|
||||
props: { projection },
|
||||
global: { plugins: [i18n] },
|
||||
@@ -771,12 +833,12 @@ describe('ShippingConversationProcessingCard', () => {
|
||||
|
||||
it('renders a compact V3 file row with named lifecycle entries', async () => {
|
||||
const projection = buildProjection();
|
||||
projection.processing = [{
|
||||
...projection.processing[0],
|
||||
setStatusGroup(projection, 'processing', [{
|
||||
...projection.status_groups!.processing[0],
|
||||
user_task_no: 'OT-LIFECYCLE',
|
||||
run_no: 'RUN-LIFECYCLE',
|
||||
file_count: 1,
|
||||
}];
|
||||
}]);
|
||||
const wrapper = mount(ShippingConversationProcessingCard, {
|
||||
props: {
|
||||
projection,
|
||||
@@ -798,9 +860,10 @@ describe('ShippingConversationProcessingCard', () => {
|
||||
status: 'running',
|
||||
stage: 'inventory_match',
|
||||
lifecycleStage: 'fulfillment_prep',
|
||||
lifecycleEntries: [
|
||||
lifecycle_entries: [
|
||||
{ code: 'order_review', state: 'available', targetSurface: 'order_lifecycle_workbench' },
|
||||
{ code: 'fulfillment_prep', state: 'current', targetSurface: 'order_lifecycle_workbench' },
|
||||
{ code: 'freight_upload', state: 'unavailable', targetSurface: 'order_lifecycle_workbench' },
|
||||
{ code: 'upload_complete', state: 'unavailable', targetSurface: 'order_lifecycle_workbench' },
|
||||
],
|
||||
blocking_reason: null,
|
||||
@@ -818,19 +881,71 @@ describe('ShippingConversationProcessingCard', () => {
|
||||
expect(row.text()).toContain('lifecycle.pdf');
|
||||
expect(row.text()).toContain('PO:PO-LIFECYCLE');
|
||||
expect(row.text()).toContain('通知准备');
|
||||
expect(row.text()).toContain('订单复核 · 可进入');
|
||||
expect(row.text()).toContain('通知准备 · 当前可处理');
|
||||
expect(row.text()).toContain('通知完成 · 前置未完成');
|
||||
expect(row.text()).toContain('当前阶段:通知准备');
|
||||
});
|
||||
|
||||
it('keeps the file action slot for a real action but not for duplicate lifecycle navigation', async () => {
|
||||
const projection = buildProjection();
|
||||
setStatusGroup(projection, 'processing', [{
|
||||
...projection.status_groups!.processing[0],
|
||||
user_task_no: 'OT-FILE-ACTION', run_no: 'RUN-FILE-ACTION', file_count: 1,
|
||||
}]);
|
||||
const navigationOnly = buildWorkItem('OT-FILE-ACTION', {
|
||||
runNo: 'RUN-FILE-ACTION',
|
||||
sourceSummary: { ...buildWorkItem('OT-FILE-ACTION').sourceSummary, documentId: 31 },
|
||||
uiState: {
|
||||
status: 'waiting_human', stage: 'order_review', lifecycleStage: 'order_review',
|
||||
lifecycleEntries: [{ code: 'order_review', state: 'current', targetSurface: 'order_lifecycle_workbench' }],
|
||||
blocking_reason: null,
|
||||
primary_action: {
|
||||
code: 'open_order_review', i18nKey: null, parameters: {}, executionMode: 'navigate',
|
||||
targetSurface: 'order_lifecycle_workbench', targetLifecycleStage: 'order_review',
|
||||
},
|
||||
secondary_actions: [],
|
||||
},
|
||||
});
|
||||
const wrapper = mount(ShippingConversationProcessingCard, {
|
||||
props: { projection, workItems: [navigationOnly], workbenchMode: true },
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
await flushPromises();
|
||||
|
||||
const row = wrapper.get('[data-testid="shipping-processing-file-DOC-31"]');
|
||||
expect(row.text()).not.toContain('进入订单复核');
|
||||
|
||||
await wrapper.setProps({
|
||||
workItems: [buildWorkItem('OT-FILE-ACTION', {
|
||||
runNo: 'RUN-FILE-ACTION',
|
||||
sourceSummary: { ...buildWorkItem('OT-FILE-ACTION').sourceSummary, documentId: 31 },
|
||||
uiState: {
|
||||
status: 'waiting_human', stage: 'order_review', lifecycleStage: 'order_review',
|
||||
lifecycleEntries: [{ code: 'order_review', state: 'current', targetSurface: 'order_lifecycle_workbench' }],
|
||||
blocking_reason: null,
|
||||
primary_action: {
|
||||
code: 'create_draft', i18nKey: null, parameters: {}, executionMode: 'navigate',
|
||||
targetSurface: 'order_lifecycle_workbench', targetLifecycleStage: 'order_review',
|
||||
},
|
||||
secondary_actions: [],
|
||||
},
|
||||
})],
|
||||
});
|
||||
await flushPromises();
|
||||
|
||||
expect(row.text()).toContain('创建草稿');
|
||||
await row.find('button').trigger('click');
|
||||
expect(wrapper.emitted('projectionAction')?.[0]?.[0]).toMatchObject({
|
||||
item: { actionCode: 'create_draft' },
|
||||
});
|
||||
});
|
||||
|
||||
it('fails closed when a lifecycle entry has an unknown backend state', async () => {
|
||||
const projection = buildProjection();
|
||||
projection.processing = [{
|
||||
...projection.processing[0],
|
||||
setStatusGroup(projection, 'processing', [{
|
||||
...projection.status_groups!.processing[0],
|
||||
user_task_no: 'OT-LIFECYCLE-UNKNOWN',
|
||||
run_no: 'RUN-LIFECYCLE-UNKNOWN',
|
||||
file_count: 1,
|
||||
}];
|
||||
}]);
|
||||
const wrapper = mount(ShippingConversationProcessingCard, {
|
||||
props: {
|
||||
projection,
|
||||
@@ -851,7 +966,7 @@ describe('ShippingConversationProcessingCard', () => {
|
||||
status: 'running',
|
||||
stage: 'inventory_match',
|
||||
lifecycleStage: 'fulfillment_prep',
|
||||
lifecycleEntries: [
|
||||
lifecycle_entries: [
|
||||
{ code: 'order_review', state: 'paused', targetSurface: 'order_lifecycle_workbench' },
|
||||
] as unknown as ShippingProcessingProjection['uiState']['lifecycleEntries'],
|
||||
blocking_reason: null,
|
||||
@@ -865,9 +980,6 @@ describe('ShippingConversationProcessingCard', () => {
|
||||
await flushPromises();
|
||||
|
||||
const row = wrapper.find('[data-testid="shipping-processing-file-DOC-10"]');
|
||||
const orderReview = row.findAll('button').find((button) => button.text().includes('订单复核'));
|
||||
expect(orderReview?.attributes('disabled')).toBeDefined();
|
||||
await orderReview?.trigger('click');
|
||||
expect(wrapper.emitted('openLifecycleStage')).toBeUndefined();
|
||||
expect(row.findAll('button')).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
+20
-17
@@ -36,7 +36,10 @@ import {
|
||||
resolveShippingProcessingStatusLabel,
|
||||
} from '@/features/chat/shipping/shippingProcessingLabels';
|
||||
import { flattenBusinessFileProjections } from '@/features/chat/shipping/conversationProcessingProjection';
|
||||
import { resolveConversationTaskActionPresentation, resolveProcessingActionPresentation } from '@/features/shipping-progress/actionPresentation';
|
||||
import {
|
||||
resolveConversationTaskActionPresentation,
|
||||
resolveFilePrimaryActionPresentation,
|
||||
} from '@/features/shipping-progress/actionPresentation';
|
||||
import SidebarProgressInline from '@/features/shipping-progress/components/SidebarProgressInline.vue';
|
||||
import type { ActionPresentation, ActionPresentationItem } from '@/features/shipping-progress/types';
|
||||
|
||||
@@ -50,8 +53,8 @@ const props = defineProps<{
|
||||
hasMoreHistory?: boolean;
|
||||
/** 批次中心按状态 → EML → 文件展示,不再嵌入任务级 15 节点进度。 */
|
||||
workbenchMode?: boolean;
|
||||
/** 批次四阶段筛选;保留状态/EML 分组,仅隐藏不属于当前阶段的任务。 */
|
||||
lifecycleFilter?: 'all' | 'intake_parse' | 'order_review' | 'fulfillment_prep' | 'upload_complete';
|
||||
/** 批次五阶段筛选;保留状态/EML 分组,仅隐藏不属于当前阶段的任务。 */
|
||||
lifecycleFilter?: 'all' | 'intake_parse' | 'order_review' | 'fulfillment_prep' | 'freight_upload' | 'upload_complete';
|
||||
/** 批次中心本地搜索:只筛叶子文件,父 EML 卡仍保留。 */
|
||||
fileSearchQuery?: string;
|
||||
/** 后端已授权下载的正式 Excel 对应 OT。 */
|
||||
@@ -94,12 +97,13 @@ type WorkbenchFileRow = {
|
||||
po_number?: string | null;
|
||||
projection?: ShippingProcessingProjection;
|
||||
};
|
||||
const LIFECYCLE_STAGE_CODES = ['intake_parse', 'order_review', 'fulfillment_prep', 'upload_complete'] as const;
|
||||
const LIFECYCLE_STAGE_CODES = ['intake_parse', 'order_review', 'fulfillment_prep', 'freight_upload', 'upload_complete'] as const;
|
||||
type LifecycleStageCode = typeof LIFECYCLE_STAGE_CODES[number];
|
||||
const LIFECYCLE_STAGE_LABEL_KEYS: Record<string, string> = {
|
||||
intake_parse: 'intakeParse',
|
||||
order_review: 'orderReview',
|
||||
fulfillment_prep: 'fulfillmentPrep',
|
||||
freight_upload: 'freightUpload',
|
||||
upload_complete: 'uploadComplete',
|
||||
};
|
||||
|
||||
@@ -113,16 +117,15 @@ const hasContent = computed(() => Boolean(
|
||||
));
|
||||
|
||||
const statusGroups = computed(() => activeProjection.value?.status_groups || null);
|
||||
const completedTasks = computed(() => statusGroups.value?.completed || activeProjection.value?.completed || []);
|
||||
const historyTasks = computed(() => statusGroups.value
|
||||
? [...statusGroups.value.cancelled, ...statusGroups.value.archived]
|
||||
: (activeProjection.value?.history || []));
|
||||
/** EML 卡必须由后端 userGroup 分入独立用户区;旧任务保留 needs_action 兼容归属。 */
|
||||
const failedTasks = computed(() => statusGroups.value?.failed
|
||||
|| (activeProjection.value?.needs_action || []).filter((task) => task.userGroup === 'failed' || !task.userGroup));
|
||||
const waitingHumanTasks = computed(() => statusGroups.value?.waiting_human
|
||||
|| (activeProjection.value?.needs_action || []).filter((task) => task.userGroup === 'waiting_human'));
|
||||
const processingTasks = computed(() => statusGroups.value?.processing || activeProjection.value?.processing || []);
|
||||
const completedTasks = computed(() => statusGroups.value?.completed || []);
|
||||
const historyTasks = computed(() => [
|
||||
...(statusGroups.value?.cancelled || []),
|
||||
...(statusGroups.value?.archived || []),
|
||||
]);
|
||||
/** EML 卡的状态分区必须完全遵循后端 status_groups,禁止旧四组回退重判。 */
|
||||
const failedTasks = computed(() => statusGroups.value?.failed || []);
|
||||
const waitingHumanTasks = computed(() => statusGroups.value?.waiting_human || []);
|
||||
const processingTasks = computed(() => statusGroups.value?.processing || []);
|
||||
|
||||
/** 任务只要含一个命中附件即保留,避免筛选后打散同一封 EML 的上下文。 */
|
||||
function taskMatchesLifecycleFilter(task: ConversationProcessingUserTask): boolean {
|
||||
@@ -426,7 +429,7 @@ function isDownloadSelected(taskNo: string): boolean {
|
||||
/** 状态组标题按文件计数,与批次总览保持同一口径。 */
|
||||
function groupFileCount(tasks: ConversationProcessingUserTask[]): number {
|
||||
const seen = new Set<string>();
|
||||
return tasks.reduce((total, task) => total + workbenchFileRows(task).reduce((count, file) => {
|
||||
return tasks.reduce((total, task) => total + visibleWorkbenchFileRows(task).reduce((count, file) => {
|
||||
const filename = String(file.filename || file.label || '').trim().toLowerCase();
|
||||
if (filename.endsWith('.eml')) return count;
|
||||
const key = String(('document_id' in file ? file.document_id : undefined)
|
||||
@@ -454,7 +457,7 @@ function workbenchFileReason(file: WorkbenchFileRow, task: ConversationProcessin
|
||||
return taskReasonLabel(task);
|
||||
}
|
||||
|
||||
/** 文件工作面显示四阶段业务语义;技术 stage 仍保留给进度诊断,不用于入口可达性。 */
|
||||
/** 文件工作面显示五阶段业务语义;技术 stage 仍保留给进度诊断,不用于入口可达性。 */
|
||||
function workbenchFileLifecycleStage(file: WorkbenchFileRow): string {
|
||||
const code = String(file.projection?.uiState?.lifecycleStage || '').trim();
|
||||
const key = LIFECYCLE_STAGE_LABEL_KEYS[code];
|
||||
@@ -494,7 +497,7 @@ function onOpenLifecycleStage(file: WorkbenchFileRow, lifecycleStage: LifecycleS
|
||||
/** 叶子文件动作由自身 ui_state 裁决;没有叶子投影时不伪造可操作按钮。 */
|
||||
function filePrimaryActionItem(file: WorkbenchFileRow): ActionPresentationItem | null {
|
||||
return file.projection
|
||||
? resolveProcessingActionPresentation(file.projection, { surface: 'right' }).primary
|
||||
? resolveFilePrimaryActionPresentation(file.projection)
|
||||
: null;
|
||||
}
|
||||
|
||||
|
||||
+52
-14
@@ -149,7 +149,7 @@ describe('ShippingOrderExtractionCard', () => {
|
||||
expect(wrapper.text()).toContain('处理中 1');
|
||||
});
|
||||
|
||||
it('uses the current three PDF rows instead of stale Run review totals', () => {
|
||||
it('keeps historical candidate-ready attachments under their EML instead of creating a candidate group', () => {
|
||||
const currentPdfRows = ['4210020274.pdf', '4210020272.pdf', '4210020273.pdf'].map((fileName, index) => ({
|
||||
unitId: index + 1,
|
||||
documentId: index + 101,
|
||||
@@ -181,10 +181,11 @@ describe('ShippingOrderExtractionCard', () => {
|
||||
global: { plugins: [i18n], provide: { [SHIPPING_WORKFLOW_KEY as symbol]: { processingWorkItems: ref([]) } } },
|
||||
});
|
||||
|
||||
// 当前卡片的总数、完成率和候选列表必须来自同一份有效 PDF 清单。
|
||||
// 旧快照缺少会话级用户状态;candidate_ready 只能作为附件阶段,不能升格为顶层分组。
|
||||
expect(wrapper.text()).toContain('共 3 个文件');
|
||||
expect(wrapper.text()).toContain('0/3 已处理');
|
||||
expect(wrapper.text()).toContain('已生成候选 3 个文件');
|
||||
expect(wrapper.text()).not.toContain('已生成候选 3 个文件');
|
||||
expect(wrapper.text()).toContain('4210020274.pdf');
|
||||
expect(wrapper.text()).not.toContain('23/20 已处理');
|
||||
expect(wrapper.text()).not.toContain('100% 完成');
|
||||
});
|
||||
@@ -234,6 +235,21 @@ describe('ShippingOrderExtractionCard', () => {
|
||||
expect(wrapper.text()).not.toContain('系统处理中');
|
||||
});
|
||||
|
||||
it('does not fall back to one Run file when the authoritative conversation projection has not returned', () => {
|
||||
const wrapper = mount(ShippingOrderExtractionCard, {
|
||||
props: { state: buildState({ summary: { ...buildState().summary, totalDocuments: 1 } }), runNo: 'SNER-SINGLE' },
|
||||
global: { plugins: [i18n], provide: { [SHIPPING_WORKFLOW_KEY as symbol]: {
|
||||
// 真实会话工作流已建立但读取超时/失败时,不能将最近 Run 的单文件当作整个批次。
|
||||
processing: ref(null),
|
||||
processingWorkItems: ref([]),
|
||||
initialLoading: ref(false),
|
||||
} } },
|
||||
});
|
||||
|
||||
expect(wrapper.find('[data-testid="shipping-order-extraction-projection-loading"]').exists()).toBe(true);
|
||||
expect(wrapper.text()).not.toContain('共 1 个文件');
|
||||
});
|
||||
|
||||
it('does not render message document rows while the authoritative projection is loading', () => {
|
||||
const wrapper = mount(ShippingOrderExtractionCard, {
|
||||
props: { state: buildState({
|
||||
@@ -337,6 +353,34 @@ describe('ShippingOrderExtractionCard', () => {
|
||||
expect(wrapper.text()).not.toContain('stale.pdf');
|
||||
});
|
||||
|
||||
it('uses the authoritative attachment total when a historical message only carries the EML task count', () => {
|
||||
const task = {
|
||||
user_task_no: 'INTAKE:SNI-MAILS', title: 'mail-batch.eml', file_count: 30,
|
||||
userGroup: 'waiting_human', group: 'needs_action', aggregateChildren: [],
|
||||
aggregateSummary: { intakeNo: 'SNI-MAILS', total: 30, completed: 0, processing: 0, needsAction: 30, failed: 0, stages: ['order_review'], reasonCodes: [] },
|
||||
} as any;
|
||||
const wrapper = mount(ShippingOrderExtractionCard, {
|
||||
props: {
|
||||
// 历史聊天消息记录的是 18 封 EML;不能把它当成 18 个业务附件。
|
||||
state: buildState({ summary: { ...buildState().summary, totalDocuments: 18 } }),
|
||||
runNo: 'SNER-ATTACHMENT-TOTAL',
|
||||
},
|
||||
global: { plugins: [i18n], provide: { [SHIPPING_WORKFLOW_KEY as symbol]: {
|
||||
processing: ref({
|
||||
summary: { total_files: 30, completed_files: 0, waiting_human_files: 30, failed_files: 0 },
|
||||
ui_state: { status: 'waiting_human' },
|
||||
status_groups: { failed: [], waiting_human: [task], processing: [], completed: [], cancelled: [], archived: [] },
|
||||
}),
|
||||
processingWorkItems: ref([]),
|
||||
} } },
|
||||
});
|
||||
|
||||
// 关键断言:有权威会话投影时,只能显示附件总数,禁止回退历史邮件任务数。
|
||||
expect(wrapper.text()).toContain('共 30 个文件');
|
||||
expect(wrapper.text()).toContain('0/30 已处理');
|
||||
expect(wrapper.text()).not.toContain('共 18 个文件');
|
||||
});
|
||||
|
||||
it('counts unique EML attachment children instead of task rows', async () => {
|
||||
const childA = { workItemType: 'order_task', workItemNo: 'OT-A', sourceType: 'eml', intakeNo: 'SNI-COUNT', sourceSummary: { filename: 'a.pdf', documentId: 101, documentCount: 1 }, status: 'processing', stage: 'document_parsing', userStatus: 'running', facts: { uploadState: 'not_created' } } as any;
|
||||
const childB = { ...childA, workItemNo: 'OT-B', sourceSummary: { filename: 'b.pdf', documentId: 102, documentCount: 1 } } as any;
|
||||
@@ -376,7 +420,7 @@ describe('ShippingOrderExtractionCard', () => {
|
||||
expect(wrapper.text()).toContain('4518838152.pdf');
|
||||
});
|
||||
|
||||
it('groups completed attachments under their EML intake instead of mixing unrelated files', async () => {
|
||||
it('keeps candidate-ready attachments under their EML instead of mixing unrelated files', () => {
|
||||
const wrapper = mount(ShippingOrderExtractionCard, {
|
||||
props: {
|
||||
state: buildState({
|
||||
@@ -390,7 +434,6 @@ describe('ShippingOrderExtractionCard', () => {
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
await wrapper.find('button').trigger('click');
|
||||
const text = wrapper.text();
|
||||
expect(text.indexOf('Forwarder_A.eml')).toBeLessThan(text.indexOf('Packing_List.pdf'));
|
||||
expect(text).toContain('Customs_Form.pdf');
|
||||
@@ -428,7 +471,7 @@ describe('ShippingOrderExtractionCard', () => {
|
||||
expect(wrapper.findAll('.animate-spin').length).toBe(0);
|
||||
});
|
||||
|
||||
it('does not render completed files again as standalone cards', async () => {
|
||||
it('renders candidate-ready standalone files once without creating a candidate group', () => {
|
||||
const wrapper = mount(ShippingOrderExtractionCard, {
|
||||
props: {
|
||||
state: buildState({
|
||||
@@ -450,12 +493,11 @@ describe('ShippingOrderExtractionCard', () => {
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
const accordion = wrapper.find('button');
|
||||
await accordion.trigger('click');
|
||||
expect(wrapper.text().match(/4518838152\.pdf/g)?.length).toBe(1);
|
||||
expect(wrapper.text()).not.toContain('已生成候选 2 个文件');
|
||||
});
|
||||
|
||||
it('aggregates a fully completed EML intake only inside the completed section', async () => {
|
||||
it('keeps an all-candidate EML in the system-processing fallback group', () => {
|
||||
const wrapper = mount(ShippingOrderExtractionCard, {
|
||||
props: {
|
||||
state: buildState({
|
||||
@@ -477,9 +519,6 @@ describe('ShippingOrderExtractionCard', () => {
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
expect(wrapper.text()).not.toContain('forwarder.eml');
|
||||
expect(wrapper.text()).not.toContain('packing.pdf');
|
||||
await wrapper.find('button').trigger('click');
|
||||
expect(wrapper.text()).toContain('forwarder.eml');
|
||||
expect(wrapper.text()).toContain('packing.pdf');
|
||||
expect(wrapper.text().match(/forwarder\.eml/g)?.length).toBe(1);
|
||||
@@ -487,7 +526,7 @@ describe('ShippingOrderExtractionCard', () => {
|
||||
expect(wrapper.text()).toContain('已提取');
|
||||
});
|
||||
|
||||
it('keeps a partially completed EML intake outside the completed section', async () => {
|
||||
it('keeps a mixed-stage EML in the system-processing fallback group', () => {
|
||||
const wrapper = mount(ShippingOrderExtractionCard, {
|
||||
props: {
|
||||
state: buildState({
|
||||
@@ -501,7 +540,6 @@ describe('ShippingOrderExtractionCard', () => {
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
await wrapper.find('button').trigger('click');
|
||||
expect(wrapper.text()).toContain('forwarder.eml');
|
||||
expect(wrapper.text()).toContain('invoice.pdf');
|
||||
expect(wrapper.text().match(/packing\.pdf/g)?.length).toBe(1);
|
||||
|
||||
@@ -62,9 +62,12 @@ type ConversationProcessing = import('../../types/shipping.api.types').Conversat
|
||||
const conversationProcessing = computed<ConversationProcessing | null>(() => (
|
||||
(shippingWorkflow as { processing?: { value?: ConversationProcessing | null } | null } | null)?.processing?.value || null
|
||||
));
|
||||
const hasAuthoritativeConversationProvider = computed(() => Boolean(
|
||||
shippingWorkflow && 'processing' in shippingWorkflow,
|
||||
));
|
||||
const conversationProjectionLoading = computed(() => Boolean(
|
||||
(shippingWorkflow as { initialLoading?: { value?: boolean } | null } | null)?.initialLoading?.value,
|
||||
));
|
||||
) || (hasAuthoritativeConversationProvider.value && !conversationProcessing.value));
|
||||
const conversationStatusGroups = computed<ConversationStatusGroups | null>(() => conversationProcessing.value?.status_groups || null);
|
||||
const hasConversationStatusGroups = computed(() => Boolean(conversationStatusGroups.value));
|
||||
const statusGroupDefs = [
|
||||
@@ -288,37 +291,19 @@ const childRows = (email: ShippingOrderExtractionFileState) => fileRows.value.fi
|
||||
&& row.intakeId === email.intakeId
|
||||
&& !isEmailRow(row)
|
||||
));
|
||||
const candidateEmailGroups = computed(() => emailRows.value
|
||||
.map((parent) => ({ parent, children: childRows(parent) }))
|
||||
.filter((group) => group.children.length > 0 && group.children.every((child) => child.status === 'candidate_ready')));
|
||||
const emailHasFailedChild = (email: ShippingOrderExtractionFileState) => childRows(email).some(isFailedParseRow);
|
||||
const emailIsCompleted = (email: ShippingOrderExtractionFileState) => {
|
||||
const children = childRows(email);
|
||||
return children.length > 0 && children.every((child) => child.status === 'candidate_ready');
|
||||
};
|
||||
const candidateEmailUnitIds = computed(() => new Set(
|
||||
candidateEmailGroups.value.flatMap((group) => [group.parent.unitId, ...group.children.map((child) => child.unitId)]),
|
||||
));
|
||||
const candidateStandaloneRows = computed(() => fileRows.value.filter((row) => (
|
||||
!isEmailRow(row)
|
||||
&& row.status === 'candidate_ready'
|
||||
&& !emailRows.value.some((email) => childRows(email).some((child) => child.unitId === row.unitId))
|
||||
)));
|
||||
const candidateFileCount = computed(() => (
|
||||
candidateEmailGroups.value.reduce((count, group) => count + group.children.length, 0)
|
||||
+ candidateStandaloneRows.value.length
|
||||
));
|
||||
const activeEmailRows = computed(() => emailRows.value.filter((row) => !candidateEmailUnitIds.value.has(row.unitId)));
|
||||
const activeEmailRows = computed(() => emailRows.value);
|
||||
const standaloneRows = computed(() => fileRows.value.filter((row) => (
|
||||
!isEmailRow(row)
|
||||
&& row.status !== 'candidate_ready'
|
||||
&& !isFailedParseRow(row)
|
||||
&& !candidateEmailUnitIds.value.has(row.unitId)
|
||||
&& !emailRows.value.some((email) => childRows(email).some((child) => child.unitId === row.unitId))
|
||||
)));
|
||||
const failedRows = computed(() => fileRows.value.filter((row) => (
|
||||
isFailedParseRow(row)
|
||||
&& !candidateEmailUnitIds.value.has(row.unitId)
|
||||
&& !emailRows.value.some((email) => childRows(email).some((child) => child.unitId === row.unitId))
|
||||
)));
|
||||
const processedCount = computed(() => {
|
||||
@@ -339,8 +324,6 @@ const progressPercent = computed(() => {
|
||||
const total = batchFileCount.value;
|
||||
return total > 0 ? Math.min(100, Math.round((processedCount.value / total) * 100)) : 0;
|
||||
});
|
||||
const completedExpanded = ref(false);
|
||||
|
||||
/** 新版会话批次的业务文件数由后端汇总;旧 Run 卡仍保留历史兼容计数。 */
|
||||
const batchFileCount = computed(() => {
|
||||
if (hasConversationStatusGroups.value) {
|
||||
@@ -486,15 +469,13 @@ const handlingSummaryLine = computed(() => {
|
||||
});
|
||||
|
||||
/**
|
||||
* 唯一主 CTA:失败→重试解析;需处理→继续处理;否则不展示。
|
||||
* 唯一主 CTA 只读取服务端明确下发的动作;失败数量和 Run 状态不能自行授权重试。
|
||||
*/
|
||||
const primaryChatAction = computed((): { kind: 'retry' | 'continue'; label: string } | null => {
|
||||
if (props.readonly || hasConversationStatusGroups.value) return null;
|
||||
const actions = props.state.availableActions || [];
|
||||
const canRetry = actions.includes('retry_failed_attachments')
|
||||
|| actions.includes('retry_failed_documents')
|
||||
|| displaySummary.value.failedDocuments > 0
|
||||
|| props.state.status === 'failed';
|
||||
|| actions.includes('retry_failed_documents');
|
||||
if (canRetry) {
|
||||
return {
|
||||
kind: 'retry',
|
||||
@@ -701,26 +682,32 @@ async function onPrimaryChatAction() {
|
||||
<ChevronDown class="h-4 w-4 transition-transform" :class="expandedStatusGroups.has(group.key) ? 'rotate-180' : ''" />
|
||||
</button>
|
||||
<div v-if="expandedStatusGroups.has(group.key)" class="space-y-2 border-t border-slate-200 p-2 dark:border-slate-700">
|
||||
<article v-for="task in statusGroupTasks(group.key)" :key="task.user_task_no" class="rounded-lg border border-slate-200 bg-slate-50 dark:border-slate-700 dark:bg-slate-950/30" :data-testid="`shipping-order-extraction-eml-${group.key}-${task.user_task_no}`">
|
||||
<div class="flex items-start gap-2">
|
||||
<Mail class="mt-0.5 h-4 w-4 text-blue-600" />
|
||||
<article v-for="task in statusGroupTasks(group.key)" :key="task.user_task_no" class="overflow-hidden rounded-lg border border-slate-300 bg-white shadow-sm dark:border-slate-700 dark:bg-slate-900" :data-testid="`shipping-order-extraction-eml-${group.key}-${task.user_task_no}`">
|
||||
<div class="flex items-start gap-3 border-b border-slate-200 bg-blue-50/50 p-3 dark:border-slate-700 dark:bg-blue-950/20">
|
||||
<Mail class="mt-0.5 h-5 w-5 text-blue-600" />
|
||||
<div class="min-w-0 flex-1">
|
||||
<button type="button" class="flex w-full items-center justify-between gap-2 text-left" @click="toggleEmlTask(task.user_task_no)">
|
||||
<span class="truncate text-sm font-medium">{{ task.title || task.user_task_no }}</span>
|
||||
<button type="button" class="flex w-full items-center justify-between gap-3 text-left" @click="toggleEmlTask(task.user_task_no)">
|
||||
<span class="truncate font-medium">{{ task.title || task.user_task_no }}</span>
|
||||
<ChevronDown class="h-4 w-4 shrink-0 transition-transform" :class="expandedEmlTasks.has(task.user_task_no) ? 'rotate-180' : ''" />
|
||||
</button>
|
||||
<div class="mt-1 text-xs text-slate-500">{{ t('chat.shippingProcessing.taskFiles', { count: taskFileCount(task) }) }}<span v-if="task.aggregateSummary"> · {{ aggregateStatusLabelFromSummary(task.aggregateSummary) }}</span></div>
|
||||
<div v-if="taskReason(task)" class="mt-1 text-xs text-rose-600">{{ displayReason(taskReason(task)) }}</div>
|
||||
<div v-if="expandedEmlTasks.has(task.user_task_no) && taskChildren(task).length" class="mt-2 space-y-1 border-t border-slate-200 pt-2 dark:border-slate-700" data-testid="shipping-order-extraction-eml-children">
|
||||
<div v-for="child in taskChildren(task).filter((item) => !String(item.sourceSummary?.filename || '').toLowerCase().endsWith('.eml'))" :key="child.workItemNo" class="flex items-start justify-between gap-3 rounded-md bg-white px-2 py-1.5 text-xs dark:bg-slate-900">
|
||||
<div class="min-w-0">
|
||||
<div class="truncate font-medium">{{ child.sourceSummary.filename || child.workItemNo }}</div>
|
||||
<div class="text-[11px] text-slate-500">{{ childStageLabel(child) }}</div>
|
||||
<div v-if="taskReason(child)" class="text-[11px] text-rose-600">{{ displayReason(taskReason(child)) }}</div>
|
||||
</div>
|
||||
<span :data-testid="`shipping-order-extraction-child-status-${child.workItemNo}`" class="shrink-0" :class="isFailedProjection(child) ? 'text-rose-600' : isWaitingProjection(child) ? 'text-amber-700' : isCompletedProjection(child) ? 'text-emerald-600' : 'text-blue-600'">{{ childStatusLabel(child) }}</span>
|
||||
<div class="mt-1 text-xs text-slate-600 dark:text-slate-300">{{ t('chat.shippingProcessing.taskFiles', { count: taskFileCount(task) }) }}<span v-if="task.aggregateSummary"> · {{ aggregateStatusLabelFromSummary(task.aggregateSummary) }}</span></div>
|
||||
<div v-if="taskReason(task)" class="mt-1 text-xs text-rose-600">{{ displayReason(taskReason(task)) }}</div>
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="expandedEmlTasks.has(task.user_task_no) && taskChildren(task).length" class="mx-4 my-2 space-y-1 border-l-2 border-blue-200 bg-slate-50 p-3 pl-4 dark:border-blue-800 dark:bg-blue-950/30" data-testid="shipping-order-extraction-eml-children">
|
||||
<div v-for="child in taskChildren(task).filter((item) => !String(item.sourceSummary?.filename || '').toLowerCase().endsWith('.eml'))" :key="child.workItemNo" class="flex items-start justify-between gap-3 py-1 text-sm">
|
||||
<div class="flex min-w-0 items-start gap-2">
|
||||
<LoaderCircle v-if="!isFailedProjection(child) && !isWaitingProjection(child) && !isCompletedProjection(child)" class="mt-0.5 h-4 w-4 shrink-0 animate-spin text-blue-500" />
|
||||
<AlertCircle v-else-if="isFailedProjection(child)" class="mt-0.5 h-4 w-4 shrink-0 text-rose-500" />
|
||||
<CheckCircle2 v-else-if="isCompletedProjection(child)" class="mt-0.5 h-4 w-4 shrink-0 text-emerald-500" />
|
||||
<TriangleAlert v-else class="mt-0.5 h-4 w-4 shrink-0 text-amber-500" />
|
||||
<div class="min-w-0">
|
||||
<div class="truncate">{{ child.sourceSummary.filename || child.workItemNo }}</div>
|
||||
<div class="text-xs text-slate-500">{{ childStageLabel(child) }}</div>
|
||||
<div v-if="taskReason(child)" class="text-xs text-rose-600">{{ displayReason(taskReason(child)) }}</div>
|
||||
</div>
|
||||
</div>
|
||||
<span :data-testid="`shipping-order-extraction-child-status-${child.workItemNo}`" class="shrink-0" :class="isFailedProjection(child) ? 'text-rose-600' : isWaitingProjection(child) ? 'text-amber-700' : isCompletedProjection(child) ? 'text-emerald-600' : 'text-blue-600'">{{ childStatusLabel(child) }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</article>
|
||||
@@ -756,19 +743,6 @@ async function onPrimaryChatAction() {
|
||||
</article>
|
||||
</div>
|
||||
<div v-else-if="!compactProgress" class="flex flex-col gap-2 bg-slate-50 p-2 dark:bg-slate-950/30">
|
||||
<button type="button" class="flex items-center justify-between rounded-lg border border-slate-200 bg-white px-3 py-3 text-left dark:border-slate-700 dark:bg-slate-900" @click="completedExpanded = !completedExpanded">
|
||||
<span class="flex items-center gap-3 text-base font-medium"><span class="flex h-7 w-7 items-center justify-center rounded-full bg-blue-100 text-blue-600"><CheckCircle2 class="h-4 w-4" /></span>{{ t('chat.shippingProcessing.candidateFiles', { count: candidateFileCount }) }}</span>
|
||||
<ChevronDown class="h-5 w-5 transition-transform" :class="completedExpanded ? 'rotate-180' : ''" />
|
||||
</button>
|
||||
<div v-if="completedExpanded && candidateFileCount" class="space-y-2 rounded-lg border border-slate-200 bg-white px-4 py-2 text-sm dark:border-slate-700 dark:bg-slate-900">
|
||||
<div v-for="group in candidateEmailGroups" :key="`candidate-email-${group.parent.unitId}`" class="rounded-md border border-blue-100 bg-blue-50/50 px-3 py-2 dark:border-blue-900 dark:bg-blue-950/20">
|
||||
<div class="flex items-center gap-2 font-medium text-slate-700 dark:text-slate-200"><Mail class="h-4 w-4 text-blue-600" />{{ t('chat.shippingProcessing.emailPrefix') }}{{ group.parent.fileName }}<span class="ml-auto text-emerald-500">{{ t('chat.shippingProcessing.batchExtracted') }}</span></div>
|
||||
<div class="mt-1 space-y-1 border-l-2 border-blue-200 pl-3 dark:border-blue-800">
|
||||
<div v-for="row in group.children" :key="`candidate-child-${row.unitId}`" class="flex items-center gap-2 py-1 text-slate-600 dark:text-slate-300"><CheckCircle2 class="h-4 w-4 text-blue-500" />{{ row.fileName }}<span class="ml-auto text-blue-500">{{ rowStatusLabel(row) }}</span></div>
|
||||
</div>
|
||||
</div>
|
||||
<div v-for="row in candidateStandaloneRows" :key="`candidate-${row.unitId}`" class="flex items-center gap-2 py-1 text-slate-600 dark:text-slate-300"><CheckCircle2 class="h-4 w-4 text-blue-500" />{{ row.fileName }}<span class="ml-auto text-blue-500">{{ rowStatusLabel(row) }}</span></div>
|
||||
</div>
|
||||
<div v-for="row in activeEmailRows" :key="row.unitId" class="overflow-hidden rounded-lg border border-slate-300 bg-white shadow-sm dark:border-slate-700 dark:bg-slate-900">
|
||||
<div class="flex items-start gap-3 border-b border-slate-200 bg-blue-50/50 p-3 dark:border-slate-700 dark:bg-blue-950/20"><Mail class="mt-0.5 h-5 w-5 text-blue-600" /><div class="min-w-0 flex-1"><div class="flex items-center justify-between gap-3"><span class="font-medium">{{ t('chat.shippingProcessing.emailPrefix') }}{{ row.fileName }}</span><span class="rounded border px-2 py-0.5 text-xs" :class="isFailedParseRow(row) || emailHasFailedChild(row) ? 'border-rose-200 bg-rose-100/70 text-rose-600' : emailIsCompleted(row) ? 'border-emerald-200 bg-emerald-100/70 text-emerald-600' : 'border-blue-200 bg-blue-100/70 text-blue-600'">{{ isFailedParseRow(row) || emailHasFailedChild(row) ? t('chat.shippingProcessing.batchException') : emailIsCompleted(row) ? t('chat.shippingProcessing.batchExtracted') : t('chat.shippingProcessing.parsingAttachments') }}</span></div><span class="mt-1 block font-mono text-xs text-slate-500">{{ t('chat.shippingProcessing.emailMeta') }}</span></div></div>
|
||||
<div class="mx-4 my-2 flex flex-col gap-2 border-l-2 border-blue-200 bg-slate-50 p-3 pl-4 dark:border-blue-800 dark:bg-blue-950/30"><div v-for="child in childRows(row)" :key="`child-${child.unitId}`" class="flex items-center justify-between gap-3 text-sm"><span class="flex min-w-0 items-center gap-2"><CheckCircle2 v-if="child.status === 'candidate_ready'" class="h-4 w-4 text-emerald-500" /><LoaderCircle v-else-if="!isFailedParseRow(child)" class="h-4 w-4 animate-spin text-blue-500" /><AlertCircle v-else class="h-4 w-4 text-rose-500" /><span class="truncate">{{ child.fileName }}</span></span><span :class="rowStatusClass(child)">{{ rowStatusLabel(child) }}</span></div></div>
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
* features/chat/components/shipping/ShippingWorkflowTimeline.spec.ts
|
||||
* 用途:验收批次进度中心只投影后端实时状态,不再保留文件详情抽屉。
|
||||
* 依赖:Vitest、Vue Test Utils、Timeline、ShippingConversationProcessingCard、shipping API。
|
||||
* 逻辑:四阶段、生命周期入口与单文件取消均由后端 Projection/availableActions 决定。
|
||||
* 逻辑:五阶段、生命周期入口与单文件取消均由后端 Projection/availableActions 决定。
|
||||
*/
|
||||
import { flushPromises, mount } from '@vue/test-utils';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
@@ -43,6 +43,12 @@ vi.mock('@/features/chat/api/shipping.api', () => ({
|
||||
vi.mock('@/shared/composables/useMessage', () => ({
|
||||
useMessage: () => ({ success: vi.fn(), error: vi.fn(), warning: vi.fn(), info: vi.fn() }),
|
||||
}));
|
||||
const gateRecovery = vi.hoisted(() => ({
|
||||
submitPrimaryAction: vi.fn(async () => ({ outcome: 'submitted' })),
|
||||
}));
|
||||
vi.mock('@/features/shipping-process-gates/composables/useShippingProcessGateRecovery', () => ({
|
||||
useShippingProcessGateRecovery: () => gateRecovery,
|
||||
}));
|
||||
|
||||
const i18n = createI18n({
|
||||
legacy: false,
|
||||
@@ -114,25 +120,31 @@ describe('ShippingWorkflowTimeline', () => {
|
||||
api.reparseCase.mockClear();
|
||||
api.reparseRun.mockClear();
|
||||
api.reparseBatch.mockClear();
|
||||
api.retryRun.mockClear();
|
||||
gateRecovery.submitPrimaryAction.mockClear();
|
||||
});
|
||||
|
||||
it('renders backend-owned four-stage summaries and the authorized download toolbar', async () => {
|
||||
it('prefers backend five-stage lifecycle nodes and shows the authorized download toolbar in freight upload', async () => {
|
||||
const processing = processingProjection({
|
||||
four_stage_nodes: [
|
||||
lifecycle_nodes: [
|
||||
{ code: 'intake_parse', status: 'passed', summary: { total: 1, completed: 1, needs_action: 0, processing: 0, failed: 0, blocking_reason: null } },
|
||||
{ code: 'order_review', status: 'passed', summary: { total: 1, completed: 1, needs_action: 0, processing: 0, failed: 0, blocking_reason: null } },
|
||||
{ code: 'fulfillment_prep', status: 'passed', summary: { total: 1, completed: 1, needs_action: 0, processing: 0, failed: 0, blocking_reason: null } },
|
||||
{ code: 'upload_complete', status: 'running', summary: { total: 1, completed: 0, needs_action: 1, processing: 0, failed: 0, blocking_reason: { code: 'manual_upload_pending' } } },
|
||||
{ code: 'freight_upload', status: 'running', summary: { total: 1, completed: 0, needs_action: 1, processing: 0, failed: 0, blocking_reason: { code: 'manual_upload_pending' } } },
|
||||
{ code: 'upload_complete', status: 'pending', summary: { total: 1, completed: 0, needs_action: 0, processing: 0, failed: 0, blocking_reason: null } },
|
||||
],
|
||||
output_artifacts: [{ order_task_no: 'OT-1', filename: 'notice.xlsx', type: 'xlsx', status: 'ready', action: { code: 'download_excel', enabled: true } }],
|
||||
} as Partial<ConversationProcessingProjection>);
|
||||
const wrapper = mountTimeline(processing, [fileProjection()]);
|
||||
await flushPromises();
|
||||
|
||||
expect(wrapper.get('[data-testid="shipping-workflow-four-stage-progress"]').text()).toContain('接收解析');
|
||||
const upload = wrapper.get('[data-testid="shipping-workflow-stage-filter-upload_complete"]');
|
||||
// 四阶段卡仅保留阶段名和后端统计数量,状态由卡片样式表达。
|
||||
expect(upload.text()).toBe('通知完成1');
|
||||
const progress = wrapper.get('[data-testid="shipping-workflow-lifecycle-progress"]');
|
||||
expect(progress.text()).toContain('接收解析');
|
||||
expect(progress.text()).toContain('货代上传');
|
||||
expect(progress.findAll('button')).toHaveLength(5);
|
||||
const upload = wrapper.get('[data-testid="shipping-workflow-stage-filter-freight_upload"]');
|
||||
// 五阶段卡仅保留阶段名和后端统计数量,状态由卡片样式表达。
|
||||
expect(upload.text()).toBe('货代上传1');
|
||||
await upload.trigger('click');
|
||||
expect(wrapper.find('[data-testid="shipping-workflow-download-toolbar"]').exists()).toBe(true);
|
||||
});
|
||||
@@ -286,7 +298,7 @@ describe('ShippingWorkflowTimeline', () => {
|
||||
|
||||
await wrapper.findComponent({ name: 'ShippingConversationProcessingCard' }).vm.$emit('projection-action', {
|
||||
projection: file,
|
||||
item: { intent: 'retry', actionCode: 'reparse', labelKey: 'chat.shippingProcessing.action.retry_parse' },
|
||||
item: { intent: 'reparse', actionCode: 'reparse', labelKey: 'chat.shippingProcessing.action.retry_parse' },
|
||||
});
|
||||
await flushPromises();
|
||||
|
||||
@@ -317,7 +329,7 @@ describe('ShippingWorkflowTimeline', () => {
|
||||
|
||||
await wrapper.findComponent({ name: 'ShippingConversationProcessingCard' }).vm.$emit('projection-action', {
|
||||
projection: file,
|
||||
item: { intent: 'retry', actionCode: 'reparse', labelKey: 'chat.shippingProcessing.action.retry_parse' },
|
||||
item: { intent: 'reparse', actionCode: 'reparse', labelKey: 'chat.shippingProcessing.action.retry_parse' },
|
||||
});
|
||||
await flushPromises();
|
||||
const input = document.querySelector<HTMLTextAreaElement>('[data-testid="shipping-workflow-reason-input"]');
|
||||
@@ -425,7 +437,7 @@ describe('ShippingWorkflowTimeline', () => {
|
||||
expect(wrapper.find('[data-testid="shipping-processing-batch-reparse"]').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it('retries a file generic-retry action by its backend run instead of silently treating it as intake retry', async () => {
|
||||
it('rejects a legacy generic-retry action instead of treating it as a Run retry', async () => {
|
||||
const file = fileProjection({
|
||||
uiState: {
|
||||
status: 'failed', stage: 'document_parsing', lifecycleStage: 'intake_parse',
|
||||
@@ -438,12 +450,40 @@ describe('ShippingWorkflowTimeline', () => {
|
||||
|
||||
await wrapper.findComponent({ name: 'ShippingConversationProcessingCard' }).vm.$emit('projection-action', {
|
||||
projection: file,
|
||||
item: { intent: 'retry', actionCode: 'retry', labelKey: 'chat.shippingProcessing.action.retry_parse' },
|
||||
item: { intent: 'retry_parse', actionCode: 'retry', labelKey: 'chat.shippingProcessing.action.retry_parse' },
|
||||
});
|
||||
await flushPromises();
|
||||
|
||||
// 后端只授予了 retry;附件层使用自己的 Run 执行,不能因 DOCUMENT 编号而吞掉操作。
|
||||
expect(api.retryRun).toHaveBeenCalledWith('RUN-1');
|
||||
// 泛化 retry 已退出契约;前端不得据 Run 编号擅自选择重试 API。
|
||||
expect(api.retryRun).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('submits an authorized freight-upload retry through its Gate instead of re-running extraction', async () => {
|
||||
const processGate = {
|
||||
execution_no: 'SPE-1',
|
||||
allowed_actions: ['retry_freight_upload_rpa'],
|
||||
recovery_targets: [],
|
||||
current_blocking_gate: {
|
||||
gate_code: 'freight_upload', evaluation_version: 1,
|
||||
},
|
||||
};
|
||||
const file = fileProjection({ processGate } as Partial<ShippingProcessingProjection>);
|
||||
const wrapper = mountTimeline(processingProjection(), [file]);
|
||||
await flushPromises();
|
||||
|
||||
await wrapper.findComponent({ name: 'ShippingConversationProcessingCard' }).vm.$emit('projection-action', {
|
||||
projection: file,
|
||||
item: {
|
||||
intent: 'retry_freight_upload_rpa', actionCode: 'retry_freight_upload_rpa',
|
||||
labelKey: 'chat.shippingProcessing.action.retry',
|
||||
},
|
||||
});
|
||||
await flushPromises();
|
||||
|
||||
expect(gateRecovery.submitPrimaryAction).toHaveBeenCalledWith(processGate, expect.objectContaining({
|
||||
actionCode: 'retry_freight_upload_rpa',
|
||||
}));
|
||||
expect(api.retryRun).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('opens manual upload with the backend root task number for a document file action', async () => {
|
||||
@@ -463,23 +503,6 @@ describe('ShippingWorkflowTimeline', () => {
|
||||
}));
|
||||
});
|
||||
|
||||
it('shows only title and total on four-stage cards', async () => {
|
||||
const processing = processingProjection({
|
||||
four_stage_nodes: [{
|
||||
code: 'order_review', status: 'blocked',
|
||||
summary: { total: 2, completed: 0, needs_action: 2, processing: 0, failed: 0, blocking_reason: { code: 'field_conflict' } },
|
||||
}],
|
||||
} as Partial<ConversationProcessingProjection>);
|
||||
const wrapper = mountTimeline(processing, [fileProjection()]);
|
||||
await flushPromises();
|
||||
|
||||
const card = wrapper.get('[data-testid="shipping-workflow-stage-filter-order_review"]');
|
||||
expect(card.text()).toContain('订单复核');
|
||||
expect(card.text()).toContain('2');
|
||||
expect(card.text()).not.toContain('待处理');
|
||||
expect(card.text()).not.toContain('field_conflict');
|
||||
});
|
||||
|
||||
it('does not navigate when a lifecycle entry has an unknown backend state', async () => {
|
||||
routerPush.mockClear();
|
||||
const wrapper = mountTimeline(processingProjection(), [fileProjection()]);
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
/**
|
||||
* features/chat/components/shipping/ShippingWorkflowTimeline.vue
|
||||
* 用途:聊天页右侧「批次进度中心」——后端批次投影、四阶段进度和文件行操作。
|
||||
* 用途:聊天页右侧「批次进度中心」——后端批次投影、五阶段进度和文件行操作。
|
||||
* 依赖:vue-i18n、useMessage、useShippingNoticeWorkflow、ShippingConversationProcessingCard、
|
||||
* ReasonDialog、ProcessGateRecoveryCard。
|
||||
* 逻辑:顶层以 OT / ShippingProcessing 为主路径;标题栏仅保留批次名称、加载与截断提示,
|
||||
@@ -115,25 +115,32 @@ const processing = computed(() => ctl.value.processing?.value ?? null);
|
||||
/** 展示投影:统一 ShippingProcessing / conversation_processing。 */
|
||||
const displayProcessing = computed(() => processing.value);
|
||||
const batchArtifacts = computed(() => displayProcessing.value?.output_artifacts || []);
|
||||
const batchFourStageNodes = computed(() => displayProcessing.value?.four_stage_nodes || []);
|
||||
const lifecycleFilter = ref<'all' | 'intake_parse' | 'order_review' | 'fulfillment_prep' | 'upload_complete'>('all');
|
||||
const batchLifecycleNodes = computed(() => displayProcessing.value?.lifecycle_nodes || []);
|
||||
const lifecycleFilter = ref<'all' | 'intake_parse' | 'order_review' | 'fulfillment_prep' | 'freight_upload' | 'upload_complete'>('all');
|
||||
const fileSearchQuery = ref('');
|
||||
const selectedDownloadTaskNos = ref<string[]>([]);
|
||||
/** 四阶段后端编码为 snake_case,语言资源键沿用 camelCase;映射仅做展示翻译,不参与状态裁决。 */
|
||||
const BATCH_FOUR_STAGE_I18N_KEYS: Record<string, string> = {
|
||||
type ConversationStatusGroup = 'failed' | 'waiting_human' | 'processing' | 'completed' | 'cancelled' | 'archived';
|
||||
function statusGroupTasks(...groups: ConversationStatusGroup[]): ConversationProcessingUserTask[] {
|
||||
const statusGroups = displayProcessing.value?.status_groups;
|
||||
if (!statusGroups) return [];
|
||||
return groups.flatMap((group) => statusGroups[group] || []);
|
||||
}
|
||||
/** 五阶段后端编码为 snake_case,语言资源键沿用 camelCase;映射仅做展示翻译,不参与状态裁决。 */
|
||||
const BATCH_LIFECYCLE_I18N_KEYS: Record<string, string> = {
|
||||
intake_parse: 'intakeParse',
|
||||
order_review: 'orderReview',
|
||||
fulfillment_prep: 'fulfillmentPrep',
|
||||
freight_upload: 'freightUpload',
|
||||
upload_complete: 'uploadComplete',
|
||||
};
|
||||
function batchFourStageLabelKey(code: string): string {
|
||||
return BATCH_FOUR_STAGE_I18N_KEYS[code] || code;
|
||||
function batchLifecycleLabelKey(code: string): string {
|
||||
return BATCH_LIFECYCLE_I18N_KEYS[code] || code;
|
||||
}
|
||||
function selectLifecycleFilter(code: 'intake_parse' | 'order_review' | 'fulfillment_prep' | 'upload_complete') {
|
||||
function selectLifecycleFilter(code: 'intake_parse' | 'order_review' | 'fulfillment_prep' | 'freight_upload' | 'upload_complete') {
|
||||
lifecycleFilter.value = lifecycleFilter.value === code ? 'all' : code;
|
||||
}
|
||||
/** 阶段卡仅展示后端统计总数;状态、阻塞和推进语义由颜色与边框表达。 */
|
||||
function stageTotalText(node: NonNullable<typeof batchFourStageNodes.value>[number]): string {
|
||||
function stageTotalText(node: NonNullable<typeof batchLifecycleNodes.value>[number]): string {
|
||||
return String(Number(node.summary?.total || 0));
|
||||
}
|
||||
/** 下载资格仅来自后端 output_artifacts 的授权动作;筛选仅影响展示,不缩减授权集合。 */
|
||||
@@ -190,87 +197,17 @@ async function downloadBatchArchive(taskNos: string[]) {
|
||||
msg.error(err instanceof Error ? err.message : t('chat.shippingProcessing.batchWorkbench.artifacts.downloadFailed', { count: taskNos.length }));
|
||||
}
|
||||
}
|
||||
/**
|
||||
* 批次总览一律按文件计数。会话 summary 中 processing/needs_action 是任务数,
|
||||
* 不能直接填入原型的“处理中/需处理”文件统计卡。
|
||||
*/
|
||||
function taskFileKeys(task: ConversationProcessingUserTask): string[] {
|
||||
const keys = new Set<string>();
|
||||
const collect = (children: ShippingProcessingProjection[]) => {
|
||||
for (const child of children) {
|
||||
const nested = child.aggregateChildren || [];
|
||||
if (nested.length) collect(nested);
|
||||
const filename = String(child.sourceSummary?.filename || '').trim();
|
||||
// 聚合父项/邮件容器只提供来源信息,叶子附件才计入业务文件。
|
||||
if (nested.length || filename.toLowerCase().endsWith('.eml')) continue;
|
||||
const id = Number(child.sourceSummary?.documentId || 0);
|
||||
const key = id > 0 ? `document:${id}` : filename ? `filename:${filename}` : '';
|
||||
if (key) keys.add(key);
|
||||
}
|
||||
};
|
||||
const children = task.aggregateChildren || [];
|
||||
if (children.length) {
|
||||
collect(children);
|
||||
return [...keys];
|
||||
}
|
||||
for (const object of task.objects || []) {
|
||||
if (object.kind !== 'document') continue;
|
||||
const id = Number(object.document_id || 0);
|
||||
const filename = String(object.filename || object.label || '').trim();
|
||||
if (filename.toLowerCase().endsWith('.eml')) continue;
|
||||
const key = id > 0
|
||||
? `document:${id}`
|
||||
: String(object.filename || object.object_key || '').trim();
|
||||
if (key) keys.add(key);
|
||||
}
|
||||
if (keys.size) return [...keys];
|
||||
// 无 EML 子附件明细时,直接文件可按自身 file_count 回退;EML 不允许伪造附件数。
|
||||
const taskName = String(task.title || '').trim().toLowerCase();
|
||||
if (taskName.endsWith('.eml') || task.aggregateSummary?.intakeNo) return [];
|
||||
const fallback = Math.max(0, Number(task.file_count || 0));
|
||||
return Array.from({ length: fallback }, (_, index) => `${task.user_task_no}:file:${index}`);
|
||||
}
|
||||
const batchOverview = computed(() => {
|
||||
const summary = displayProcessing.value?.summary;
|
||||
// [AUTHORITY] status_groups 表示新版批次投影。其 summary 是后端对完整批次
|
||||
// 一次裁决的文件事实,即使当前值为 0 也不得从局部展开行重算。
|
||||
if (displayProcessing.value?.status_groups && summary) {
|
||||
return {
|
||||
total: Number(summary.total_files || 0),
|
||||
processing: Number(summary.processing_files || 0),
|
||||
completed: Number(summary.completed_files || 0),
|
||||
needsAction: Number(summary.failed_files || 0) + Number(summary.waiting_human_files || 0),
|
||||
};
|
||||
}
|
||||
const groups = displayProcessing.value?.status_groups;
|
||||
const failed = groups?.failed || [];
|
||||
const waiting = groups?.waiting_human || [];
|
||||
const processingTasks = groups?.processing || displayProcessing.value?.processing || [];
|
||||
const completed = groups?.completed || displayProcessing.value?.completed || [];
|
||||
const seen = new Set<string>();
|
||||
const count = (tasks: ConversationProcessingUserTask[]) => tasks.reduce((total, task) => {
|
||||
let count = 0;
|
||||
for (const key of taskFileKeys(task)) {
|
||||
if (seen.has(key)) continue;
|
||||
seen.add(key);
|
||||
count += 1;
|
||||
}
|
||||
return total + count;
|
||||
}, 0);
|
||||
const needsAction = count([...failed, ...waiting]);
|
||||
const processingCount = count(processingTasks);
|
||||
const completedCount = count(completed);
|
||||
const computedTotal = needsAction + processingCount + completedCount;
|
||||
const summaryTotal = Number(displayProcessing.value?.summary?.total_files || 0);
|
||||
// [AUTHORITY] 摘要投影的统计与状态组同由服务端一次裁决;不能从展开行重算,
|
||||
// 否则 EML 聚合、历史版本去重与五阶段筛选会再次发生口径漂移。
|
||||
return {
|
||||
// status_groups 的去重文件集合优先;旧 summary.total_files 只在没有可枚举文件时回退。
|
||||
total: computedTotal > 0 ? computedTotal : summaryTotal,
|
||||
processing: processingCount,
|
||||
completed: completedCount,
|
||||
needsAction,
|
||||
total: Number(summary?.total_files || 0),
|
||||
processing: Number(summary?.processing_files || 0),
|
||||
completed: Number(summary?.completed_files || 0),
|
||||
needsAction: Number(summary?.failed_files || 0) + Number(summary?.waiting_human_files || 0),
|
||||
};
|
||||
});
|
||||
const loading = computed(() => ctl.value.loading.value);
|
||||
/** 初始加载:首次打开投影仍为空时显示摘要占位。 */
|
||||
const initialLoading = computed(() => Boolean(ctl.value.initialLoading?.value));
|
||||
/** 用户主动刷新(刷新按钮 / 重试 / 重解析等):驱动顶部刷新图标旋转。 */
|
||||
@@ -284,11 +221,7 @@ const error = computed(() => ctl.value.error.value);
|
||||
const hasPinnedProcessingTasks = computed(() => {
|
||||
const projection = displayProcessing.value;
|
||||
if (!projection) return false;
|
||||
return Boolean(
|
||||
projection.needs_action?.length
|
||||
|| projection.processing?.length
|
||||
|| projection.completed?.length,
|
||||
);
|
||||
return statusGroupTasks('failed', 'waiting_human', 'processing', 'completed').length > 0;
|
||||
});
|
||||
|
||||
/**
|
||||
@@ -489,7 +422,7 @@ async function onProcessingTaskAction(payload: {
|
||||
openReparseBatchDialog(runNo);
|
||||
return;
|
||||
}
|
||||
if (action === 'retry_parse' || action === 'retry') {
|
||||
if (action === 'retry_parse') {
|
||||
const intakeNo = String(task.user_task_no || '').replace(/^INTAKE:/i, '').trim();
|
||||
if (intakeNo.startsWith('SNI-')) {
|
||||
if (actionBusyItemNo.value) return;
|
||||
@@ -741,10 +674,8 @@ async function onTaskProjectionAction(payload: {
|
||||
return;
|
||||
}
|
||||
if (code === 'reparse') {
|
||||
const task = [
|
||||
...(displayProcessing.value?.needs_action || []),
|
||||
...(displayProcessing.value?.processing || []),
|
||||
].find((row) => String(row.user_task_no || '').trim() === taskNo);
|
||||
const task = statusGroupTasks('failed', 'waiting_human', 'processing')
|
||||
.find((row) => String(row.user_task_no || '').trim() === taskNo);
|
||||
if (task) {
|
||||
void onProcessingTaskAction({ task, action: 'reparse' });
|
||||
return;
|
||||
@@ -773,13 +704,16 @@ async function onTaskProjectionAction(payload: {
|
||||
openReparseBatchDialog(runNo);
|
||||
return;
|
||||
}
|
||||
if (code === 'retry_inventory_preparation') {
|
||||
const gateSummary = projection.processGate;
|
||||
if (!gateSummary) {
|
||||
msg.warning(t('workspace.shippingNotice.processGate.noAction'));
|
||||
return;
|
||||
}
|
||||
// Gate 执行器统一处理 execution_no、乐观锁与幂等键;批次卡不自行组装写请求。
|
||||
const gateSummary = projection.processGate;
|
||||
const gateAuthorized = Boolean(gateSummary && code && (
|
||||
(gateSummary.allowed_actions || []).some((action) => String(action).trim() === code)
|
||||
|| (gateSummary.recovery_targets || []).some((target) => (
|
||||
String(target.action_code || '').trim() === code
|
||||
))
|
||||
));
|
||||
if (gateAuthorized && gateSummary) {
|
||||
// Gate 执行器统一处理 execution_no、乐观锁与幂等键;不能因展示 intent=retry
|
||||
// 误将货代上传等 Gate 恢复动作路由为重新解析。
|
||||
const result = await submitGatePrimaryAction(gateSummary, {
|
||||
actionCode: code,
|
||||
navigationContext: gateNavigationContext.value,
|
||||
@@ -793,34 +727,13 @@ async function onTaskProjectionAction(payload: {
|
||||
void onProcessingIntakeAction({ item: projection, action: code });
|
||||
return;
|
||||
}
|
||||
if (code === 'retry' || item.intent === 'retry') {
|
||||
const runNo = String(projection.runNo || '').trim();
|
||||
if (!runNo) {
|
||||
msg.warning(t('chat.shippingProcessing.retryTaskMissingRun'));
|
||||
return;
|
||||
}
|
||||
if (actionBusyItemNo.value) return;
|
||||
actionBusyItemNo.value = runNo;
|
||||
try {
|
||||
await retryWorkspaceShippingOrderExtractionRun(runNo);
|
||||
await ctl.value.refresh();
|
||||
} catch (err) {
|
||||
msg.error(reparseErrorMessage(err));
|
||||
} finally {
|
||||
actionBusyItemNo.value = null;
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (item.intent === 'refresh') {
|
||||
void onRefresh();
|
||||
return;
|
||||
}
|
||||
if (item.intent === 'open_order_review' || code === 'open_order_review') {
|
||||
const task = [
|
||||
...(displayProcessing.value?.needs_action || []),
|
||||
...(displayProcessing.value?.processing || []),
|
||||
...(displayProcessing.value?.completed || []),
|
||||
].find((row) => String(row.user_task_no || '').trim() === taskNo);
|
||||
const task = statusGroupTasks('failed', 'waiting_human', 'processing', 'completed')
|
||||
.find((row) => String(row.user_task_no || '').trim() === taskNo);
|
||||
if (task) {
|
||||
void onProcessingTaskAction({ task, action: code || 'open_review' });
|
||||
return;
|
||||
@@ -841,11 +754,8 @@ async function onTaskProjectionAction(payload: {
|
||||
return;
|
||||
}
|
||||
if (item.intent === 'view_result' || code === 'focus_task') {
|
||||
const task = [
|
||||
...(displayProcessing.value?.needs_action || []),
|
||||
...(displayProcessing.value?.processing || []),
|
||||
...(displayProcessing.value?.completed || []),
|
||||
].find((row) => String(row.user_task_no || '').trim() === taskNo);
|
||||
const task = statusGroupTasks('failed', 'waiting_human', 'processing', 'completed')
|
||||
.find((row) => String(row.user_task_no || '').trim() === taskNo);
|
||||
if (task) {
|
||||
await onProcessingFocus(taskNo);
|
||||
return;
|
||||
@@ -879,12 +789,9 @@ watch(
|
||||
const focusedTaskExists = computed(() => {
|
||||
const taskNo = String(route.query.focus_task_no || '').trim();
|
||||
if (!taskNo || !displayProcessing.value) return false;
|
||||
const groups = [
|
||||
...(displayProcessing.value.needs_action || []),
|
||||
...(displayProcessing.value.processing || []),
|
||||
...(displayProcessing.value.completed || []),
|
||||
...(displayProcessing.value.history || []),
|
||||
];
|
||||
const groups = statusGroupTasks(
|
||||
'failed', 'waiting_human', 'processing', 'completed', 'cancelled', 'archived',
|
||||
);
|
||||
return groups.some((task) => String(task.user_task_no || '').trim() === taskNo);
|
||||
});
|
||||
|
||||
@@ -956,7 +863,7 @@ watch(
|
||||
</span>
|
||||
</div>
|
||||
<div class="mt-0.5 space-y-0.5 text-xs text-secondary" data-testid="shipping-workflow-panel-summary">
|
||||
<template v-if="loading && !displayProcessing">
|
||||
<template v-if="initialLoading && !displayProcessing">
|
||||
{{ t('chat.shippingProcessing.loading') }}
|
||||
</template>
|
||||
<template v-else-if="displayProcessing">
|
||||
@@ -968,11 +875,11 @@ watch(
|
||||
{{ t('chat.shippingProcessing.summaryTruncatedHint') }}
|
||||
</div>
|
||||
</template>
|
||||
<template v-else-if="error">
|
||||
{{ resolveShippingProcessingMessage('networkRecoverable', te, t) }}
|
||||
</template>
|
||||
<template v-else>
|
||||
{{ t('chat.shippingProcessing.compactSummary', {
|
||||
active: 0,
|
||||
total: 0,
|
||||
}) }}
|
||||
{{ t('chat.shippingProcessing.loading') }}
|
||||
</template>
|
||||
</div>
|
||||
</div>
|
||||
@@ -998,6 +905,26 @@ watch(
|
||||
</div>
|
||||
|
||||
<div v-if="!collapsed" class="min-h-0 flex-1 overflow-y-auto p-5">
|
||||
<div
|
||||
v-if="initialLoading && !displayProcessing"
|
||||
class="mb-4 space-y-3"
|
||||
data-testid="shipping-workflow-loading"
|
||||
>
|
||||
<div class="grid grid-cols-2 gap-3 xl:grid-cols-4">
|
||||
<div v-for="index in 4" :key="index" class="h-24 animate-pulse rounded-xl border border-default bg-surface-muted" />
|
||||
</div>
|
||||
<div class="h-32 animate-pulse rounded-xl border border-default bg-surface-muted" />
|
||||
</div>
|
||||
<div
|
||||
v-else-if="error && !displayProcessing"
|
||||
class="mb-4 rounded-xl border border-amber-200 bg-amber-50 p-4 text-sm text-amber-900"
|
||||
data-testid="shipping-workflow-load-error"
|
||||
>
|
||||
<p>{{ resolveShippingProcessingMessage('networkRecoverable', te, t) }}</p>
|
||||
<button type="button" class="mt-2 rounded-md border border-amber-300 px-2.5 py-1 text-xs font-medium" @click="onRefresh">
|
||||
{{ t('chat.shippingProcessing.actions.refresh') }}
|
||||
</button>
|
||||
</div>
|
||||
<div
|
||||
v-if="displayProcessing"
|
||||
class="mb-4 grid grid-cols-2 gap-3 xl:grid-cols-4"
|
||||
@@ -1024,15 +951,15 @@ watch(
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<section v-if="batchFourStageNodes.length" class="mb-4 border-b border-default pb-4" data-testid="shipping-workflow-four-stage-progress">
|
||||
<div class="grid grid-cols-4 gap-2">
|
||||
<button v-for="node in batchFourStageNodes" :key="node.code" type="button" class="rounded-lg border px-2 py-2 text-left text-xs transition-colors" :class="[node.status === 'passed' ? 'border-emerald-200 bg-emerald-50 text-emerald-800' : node.status === 'blocked' ? 'border-amber-300 bg-amber-50 text-amber-800' : node.status === 'running' ? 'border-brand-300 bg-brand-50 text-brand-800' : 'border-default bg-surface-muted text-secondary', lifecycleFilter === node.code ? 'ring-2 ring-brand-400 ring-offset-1' : 'hover:brightness-95']" :data-testid="`shipping-workflow-stage-filter-${node.code}`" @click="selectLifecycleFilter(node.code)">
|
||||
<span class="block font-semibold">{{ t(`chat.shippingNoticeUi.stage.${batchFourStageLabelKey(node.code)}`) }}</span>
|
||||
<section v-if="batchLifecycleNodes.length" class="mb-4 border-b border-default pb-4" data-testid="shipping-workflow-lifecycle-progress">
|
||||
<div class="grid grid-cols-2 gap-2 sm:grid-cols-5">
|
||||
<button v-for="node in batchLifecycleNodes" :key="node.code" type="button" class="rounded-lg border px-2 py-2 text-left text-xs transition-colors" :class="[node.status === 'passed' ? 'border-emerald-200 bg-emerald-50 text-emerald-800' : node.status === 'blocked' ? 'border-amber-300 bg-amber-50 text-amber-800' : node.status === 'running' ? 'border-brand-300 bg-brand-50 text-brand-800' : 'border-default bg-surface-muted text-secondary', lifecycleFilter === node.code ? 'ring-2 ring-brand-400 ring-offset-1' : 'hover:brightness-95']" :data-testid="`shipping-workflow-stage-filter-${node.code}`" @click="selectLifecycleFilter(node.code)">
|
||||
<span class="block font-semibold">{{ t(`chat.shippingNoticeUi.stage.${batchLifecycleLabelKey(node.code)}`) }}</span>
|
||||
<span class="mt-0.5 block text-[11px] opacity-80">{{ stageTotalText(node) }}</span>
|
||||
</button>
|
||||
</div>
|
||||
<div v-if="lifecycleFilter !== 'all'" class="mt-2 flex items-center justify-between gap-2 text-xs text-secondary">
|
||||
<span>{{ t('chat.shippingProcessing.batchWorkbench.filteringByStage', { stage: t(`chat.shippingNoticeUi.stage.${batchFourStageLabelKey(lifecycleFilter)}`) }) }}</span>
|
||||
<span>{{ t('chat.shippingProcessing.batchWorkbench.filteringByStage', { stage: t(`chat.shippingNoticeUi.stage.${batchLifecycleLabelKey(lifecycleFilter)}`) }) }}</span>
|
||||
<button type="button" class="text-brand-700 hover:underline" data-testid="shipping-workflow-clear-stage-filter" @click="lifecycleFilter = 'all'">{{ t('chat.shippingProcessing.batchWorkbench.clearStageFilter') }}</button>
|
||||
</div>
|
||||
<p v-if="Number(displayProcessing?.unclassified_summary?.count || 0) > 0" class="mt-2 text-xs text-amber-700" data-testid="shipping-workflow-unclassified-summary">
|
||||
@@ -1048,7 +975,7 @@ watch(
|
||||
<span class="sr-only">{{ t('chat.shippingProcessing.batchWorkbench.search.label') }}</span>
|
||||
<input v-model="fileSearchQuery" type="search" class="w-full rounded-md border border-default bg-surface px-2.5 py-1.5 text-xs" :placeholder="t('chat.shippingProcessing.batchWorkbench.search.placeholder')" data-testid="shipping-workflow-file-search">
|
||||
</label>
|
||||
<div v-if="lifecycleFilter === 'upload_complete' && downloadableTaskNos.length" class="flex flex-wrap items-center gap-2" data-testid="shipping-workflow-download-toolbar">
|
||||
<div v-if="lifecycleFilter === 'freight_upload' && downloadableTaskNos.length" class="flex flex-wrap items-center gap-2" data-testid="shipping-workflow-download-toolbar">
|
||||
<label class="inline-flex items-center gap-1 text-xs text-secondary"><input type="checkbox" :checked="allDownloadableSelected" data-testid="shipping-workflow-download-select-all" @change="toggleAllDownloadSelections"><span>{{ t('chat.shippingProcessing.batchWorkbench.artifacts.selectAll') }}</span></label>
|
||||
<span class="text-xs text-secondary">{{ t('chat.shippingProcessing.batchWorkbench.artifacts.selected', { count: selectedDownloadTaskNos.length }) }}</span>
|
||||
<button type="button" class="rounded-md border border-brand-300 px-2.5 py-1 text-xs font-medium text-brand-700 disabled:opacity-50" :disabled="!selectedDownloadTaskNos.length" data-testid="shipping-workflow-download-selected" @click="downloadSelectedBatchArtifacts">{{ t('chat.shippingProcessing.batchWorkbench.artifacts.downloadSelected') }}</button>
|
||||
|
||||
@@ -37,21 +37,15 @@ describe('useChat user attachment snapshots', () => {
|
||||
});
|
||||
});
|
||||
|
||||
const buildBatchUiStateEvent = (
|
||||
const buildTaskUiStateEvent = (
|
||||
taskNo: string,
|
||||
batchNo: string,
|
||||
actionId: string,
|
||||
checkpoint = 'ready_export',
|
||||
) => ({
|
||||
event: 'shipping_ui_state',
|
||||
batch_no: batchNo,
|
||||
batch_ui_state: {
|
||||
batch_no: batchNo,
|
||||
current_focus_task_no: taskNo,
|
||||
tasks: [],
|
||||
focus_task_ui_state: {
|
||||
task_no: taskNo,
|
||||
ui_state: {
|
||||
task_no: taskNo,
|
||||
batch_no: batchNo,
|
||||
checkpoint,
|
||||
match_status: 'matched',
|
||||
review_status: null,
|
||||
@@ -73,7 +67,6 @@ const buildBatchUiStateEvent = (
|
||||
},
|
||||
],
|
||||
updated_at: '2026-07-01T10:00:00+08:00',
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
@@ -81,38 +74,38 @@ describe('useChat shipping_ui_state SSE', () => {
|
||||
it('hydrates ui_state for notifications and never attaches chat fulfillment actions', () => {
|
||||
const message: ChatMessage = {
|
||||
role: 'assistant',
|
||||
content: '当前正在处理批次任务',
|
||||
content: '当前正在处理任务',
|
||||
type: 'shipping-match-result',
|
||||
payload: { action_buttons: [{ id: 'legacy' }] },
|
||||
};
|
||||
|
||||
const batchEvent = buildBatchUiStateEvent('SN-UNIT-001', 'SB-UNIT-001', 'generate_excel');
|
||||
const taskEvent = buildTaskUiStateEvent('SN-UNIT-001', 'generate_excel');
|
||||
|
||||
applyShippingUiStateToMessage(message, batchEvent);
|
||||
applyShippingUiStateToMessage(message, taskEvent);
|
||||
|
||||
expect(message.shipping_ui_state?.task_no).toBe('SN-UNIT-001');
|
||||
expect(message.shipping_actions).toBeUndefined();
|
||||
expect((message.payload as { action_buttons?: unknown[] }).action_buttons).toBeUndefined();
|
||||
expect((message.payload as { shipping_batch_ui_state?: { batch_no?: string } }).shipping_batch_ui_state?.batch_no).toBe('SB-UNIT-001');
|
||||
expect((message.payload as { shipping_ui_state?: { task_no?: string } }).shipping_ui_state?.task_no).toBe('SN-UNIT-001');
|
||||
});
|
||||
|
||||
it('updates ui_state when batch focus task changes without remounting action buttons', () => {
|
||||
it('updates ui_state when task changes without remounting action buttons', () => {
|
||||
const message: ChatMessage = {
|
||||
role: 'assistant',
|
||||
content: '请继续处理当前批次',
|
||||
content: '请继续处理当前任务',
|
||||
payload: { action_buttons: [] },
|
||||
};
|
||||
|
||||
applyShippingUiStateToMessage(message, buildBatchUiStateEvent('SN-FOCUS-A', 'SB-FOCUS-001', 'generate_excel'));
|
||||
applyShippingUiStateToMessage(message, buildTaskUiStateEvent('SN-FOCUS-A', 'generate_excel'));
|
||||
|
||||
expect(message.shipping_ui_state?.task_no).toBe('SN-FOCUS-A');
|
||||
expect(message.shipping_actions).toBeUndefined();
|
||||
|
||||
applyShippingUiStateToMessage(message, buildBatchUiStateEvent('SN-FOCUS-B', 'SB-FOCUS-001', 'retry_upload'));
|
||||
applyShippingUiStateToMessage(message, buildTaskUiStateEvent('SN-FOCUS-B', 'retry_upload'));
|
||||
|
||||
expect(message.shipping_ui_state?.task_no).toBe('SN-FOCUS-B');
|
||||
expect(message.shipping_actions).toBeUndefined();
|
||||
expect((message.payload as { shipping_batch_ui_state?: { current_focus_task_no?: string } }).shipping_batch_ui_state?.current_focus_task_no)
|
||||
expect((message.payload as { shipping_ui_state?: { task_no?: string } }).shipping_ui_state?.task_no)
|
||||
.toBe('SN-FOCUS-B');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -15,7 +15,7 @@ import type {
|
||||
RetrieverResource,
|
||||
ShippingOrderExtractionState,
|
||||
} from '../types/chat.types';
|
||||
import type { ShippingBatchUiState, ShippingTaskUiState } from '../types/shipping.api.types';
|
||||
import type { ShippingTaskUiState } from '../types/shipping.api.types';
|
||||
import type { ChatMessageSendResult } from '../types/chat-turn.types';
|
||||
import { createStartChatTurn } from './useChatTurn';
|
||||
|
||||
@@ -112,29 +112,19 @@ const addAttributionParts = (msg: ChatMessage, value: unknown) => {
|
||||
/**
|
||||
* 解析发货通知 SSE 事件中的统一 UI State 载荷。
|
||||
*
|
||||
* 核心逻辑:优先读取单票 `ui_state`,批次事件则下钻 `batch_ui_state.focus_task_ui_state`;
|
||||
* 同时保留批次态原文,供会话上传摘要与后续同步逻辑继续消费。
|
||||
* 核心逻辑:只读取正式任务 `ui_state`;已删除的 shipping_batches 不再参与事件恢复。
|
||||
* @param data - SSE 事件 JSON
|
||||
* @returns 提炼后的单票 UI State 与原始批次 UI State
|
||||
* @returns 提炼后的单票 UI State
|
||||
*/
|
||||
export const resolveShippingUiStatePayload = (data: Record<string, unknown>): {
|
||||
uiState?: ShippingTaskUiState;
|
||||
batchUiState?: ShippingBatchUiState;
|
||||
} => {
|
||||
const rawUiState = data.ui_state;
|
||||
const uiState = rawUiState && typeof rawUiState === 'object'
|
||||
? rawUiState as ShippingTaskUiState
|
||||
: undefined;
|
||||
const rawBatchUiState = data.batch_ui_state;
|
||||
const batchUiState = rawBatchUiState && typeof rawBatchUiState === 'object'
|
||||
? rawBatchUiState as ShippingBatchUiState
|
||||
: undefined;
|
||||
const focusTaskUiState = batchUiState?.focus_task_ui_state && typeof batchUiState.focus_task_ui_state === 'object'
|
||||
? batchUiState.focus_task_ui_state
|
||||
: undefined;
|
||||
return {
|
||||
uiState: uiState || focusTaskUiState,
|
||||
batchUiState,
|
||||
uiState,
|
||||
};
|
||||
};
|
||||
|
||||
@@ -145,7 +135,7 @@ export const resolveShippingUiStatePayload = (data: Record<string, unknown>): {
|
||||
* 不再把 action_buttons 挂到聊天消息(履约写操作改由任务处理工作台承接)。
|
||||
*/
|
||||
export const applyShippingUiStateToMessage = (msg: ChatMessage, data: Record<string, unknown>) => {
|
||||
const { uiState, batchUiState } = resolveShippingUiStatePayload(data);
|
||||
const { uiState } = resolveShippingUiStatePayload(data);
|
||||
if (!uiState) return;
|
||||
|
||||
msg.shipping_ui_state = uiState;
|
||||
@@ -156,7 +146,6 @@ export const applyShippingUiStateToMessage = (msg: ChatMessage, data: Record<str
|
||||
msg.payload = {
|
||||
...(msg.payload && typeof msg.payload === 'object' ? msg.payload as Record<string, unknown> : {}),
|
||||
shipping_ui_state: uiState,
|
||||
...(batchUiState ? { shipping_batch_ui_state: batchUiState } : {}),
|
||||
};
|
||||
};
|
||||
|
||||
@@ -602,7 +591,7 @@ export function useChat() {
|
||||
| { type: 'image' | 'document' | 'audio' | 'video' | 'custom'; transfer_method: 'local_file'; upload_file_id: string }
|
||||
| { type: 'image' | 'document' | 'audio' | 'video' | 'custom'; transfer_method: 'remote_url'; url: string }
|
||||
>,
|
||||
context?: { task_id?: string; batch_no?: string; shipping_temporary_inventory_asset_no?: string; shipping_temporary_inventory_session_no?: string; display_query?: string },
|
||||
context?: { task_id?: string; shipping_temporary_inventory_asset_no?: string; shipping_temporary_inventory_session_no?: string; display_query?: string },
|
||||
hooks?: SendMessageLifecycleHooks,
|
||||
): Promise<ChatMessageSendResult> => {
|
||||
const displayQuery = String(
|
||||
@@ -669,7 +658,6 @@ export function useChat() {
|
||||
kb_type: kbType,
|
||||
files: files && files.length > 0 ? files : undefined,
|
||||
task_id: context?.task_id || undefined,
|
||||
batch_no: context?.batch_no || undefined,
|
||||
shipping_temporary_inventory_asset_no: context?.shipping_temporary_inventory_asset_no || undefined,
|
||||
shipping_temporary_inventory_session_no: context?.shipping_temporary_inventory_session_no || undefined,
|
||||
display_query: context && Object.prototype.hasOwnProperty.call(context, 'display_query')
|
||||
|
||||
@@ -35,7 +35,6 @@ import { useChatStore } from '../stores/chat.store';
|
||||
import { useTrainingWorkspace } from './useTrainingWorkspace';
|
||||
import { matchesTrainingAgent } from '../training/trainingWorkspace.utils';
|
||||
import { hasActiveRunningChatRun } from '../shipping/shippingActionBusy';
|
||||
import { clearPendingNoticeBatchRetry } from '../shipping/useChatShippingUploadHandler';
|
||||
import {
|
||||
createChatPageConversationApi,
|
||||
createChatPageLocalMessageApi,
|
||||
@@ -195,7 +194,7 @@ export function useChatPage() {
|
||||
}, { immediate: true });
|
||||
|
||||
const dialogs = useChatPageDialogs(messages);
|
||||
const { openDeleteConfirmDialog, openRetryFailedConfirm, showShippingToast } = dialogs;
|
||||
const { openDeleteConfirmDialog } = dialogs;
|
||||
|
||||
let loadConversation: (id: string, options?: { force?: boolean }) => Promise<void>;
|
||||
let startNewChat: () => void;
|
||||
@@ -330,35 +329,6 @@ export function useChatPage() {
|
||||
|| procurement.allowsSendWithAttachmentsOnly.value,
|
||||
);
|
||||
|
||||
/**
|
||||
* 打开批次失败重试确认弹窗(会话摘要场景的兜底入口)。
|
||||
*/
|
||||
const openRetryFailedConfirmDialog = () => {
|
||||
openRetryFailedConfirm(() => confirmRetryFailedTasks());
|
||||
};
|
||||
|
||||
/**
|
||||
* 确认后执行批次失败任务重试,并以非阻塞 toast 反馈结果。
|
||||
* 核心逻辑:调用 useChatShipping.retryCurrentShippingBatchPendingTasks,成功后刷新已内置;仅补 toast。
|
||||
*/
|
||||
const retryingShippingPendingTasks = ref(false);
|
||||
const confirmRetryFailedTasks = async () => {
|
||||
if (retryingShippingPendingTasks.value) return;
|
||||
retryingShippingPendingTasks.value = true;
|
||||
try {
|
||||
const result = await shipping.retryCurrentShippingBatchPendingTasks();
|
||||
if (!result) return;
|
||||
showShippingToast(
|
||||
t('chat.shippingNoticeUi.retryFailedStarted', {
|
||||
started: result.started,
|
||||
skipped: result.skipped,
|
||||
}),
|
||||
);
|
||||
} finally {
|
||||
retryingShippingPendingTasks.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
const conversationApi = createChatPageConversationApi({
|
||||
deps,
|
||||
route,
|
||||
@@ -370,13 +340,11 @@ export function useChatPage() {
|
||||
isThinking,
|
||||
loadConversationState,
|
||||
createNewChatView,
|
||||
clearPendingNoticeBatchRetry,
|
||||
onConversationIdChanging: shipping.onConversationIdChanging,
|
||||
onConversationLoadedEmpty: shipping.onConversationLoadedEmpty,
|
||||
onConversationLoadFailed: shipping.onConversationLoadFailed,
|
||||
isShippingNoticeAgent: shipping.isShippingNoticeAgent,
|
||||
shippingTaskIdFromQuery: shipping.shippingTaskIdFromQuery,
|
||||
shippingBatchNoFromQuery: shipping.shippingBatchNoFromQuery,
|
||||
clearHistory,
|
||||
clearAttachments: attachmentApi.clearAttachments,
|
||||
input,
|
||||
@@ -498,7 +466,6 @@ export function useChatPage() {
|
||||
currentAgentId,
|
||||
presetQuestion,
|
||||
shippingTaskIdFromQuery: shipping.shippingTaskIdFromQuery,
|
||||
shippingBatchNoFromQuery: shipping.shippingBatchNoFromQuery,
|
||||
isShippingNoticeAgent: shipping.isShippingNoticeAgent,
|
||||
resetChatStateForAgentChange,
|
||||
cancelVoiceInput: voice.cancelVoiceInput,
|
||||
@@ -639,11 +606,6 @@ export function useChatPage() {
|
||||
deleteConfirmMessage: dialogs.deleteConfirmMessage,
|
||||
closeDeleteConfirmDialog: dialogs.closeDeleteConfirmDialog,
|
||||
handleDeleteConfirm: dialogs.handleDeleteConfirm,
|
||||
showRetryFailedConfirmDialog: dialogs.showRetryFailedConfirmDialog,
|
||||
closeRetryFailedConfirm: dialogs.closeRetryFailedConfirm,
|
||||
handleRetryFailedConfirm: dialogs.handleRetryFailedConfirm,
|
||||
openRetryFailedConfirm: openRetryFailedConfirmDialog,
|
||||
retryingShippingPendingTasks,
|
||||
shippingToastMessage: dialogs.shippingToastMessage,
|
||||
clearShippingToast: dialogs.clearShippingToast,
|
||||
showChatRating,
|
||||
@@ -655,10 +617,6 @@ export function useChatPage() {
|
||||
clearProcurementOriginalContract: procurement.clearOriginalContract,
|
||||
showShippingProgressWorkspace: shipping.showShippingProgressWorkspace,
|
||||
clearShippingFocus: shipping.clearShippingFocus,
|
||||
shippingBatchSummary: shipping.shippingBatchSummary,
|
||||
shippingConversationWorkspace: shipping.shippingConversationWorkspace,
|
||||
activeShippingBatchNo: shipping.activeShippingBatchNo,
|
||||
shippingBatchTasks: shipping.shippingBatchTasks,
|
||||
activeShippingTaskDetail: shipping.activeShippingTaskDetail,
|
||||
getActiveOrderExtractionRunNo: shipping.getActiveOrderExtractionRunNo,
|
||||
workflowRefreshTrigger: shipping.workflowRefreshTrigger,
|
||||
@@ -667,8 +625,6 @@ export function useChatPage() {
|
||||
setFocusedConversationTaskNo: shipping.setFocusedConversationTaskNo,
|
||||
shippingInventorySelectionActive: shipping.shippingInventorySelectionActive,
|
||||
shippingInventorySelectionTaskId: shipping.shippingInventorySelectionTaskId,
|
||||
switchShippingBatch: shipping.switchShippingBatch,
|
||||
retryCurrentShippingBatchPendingTasks: shipping.retryCurrentShippingBatchPendingTasks,
|
||||
queryShippingShortageDetails: shipping.queryShippingShortageDetails,
|
||||
selectShippingInventoryUploadTask: shipping.selectShippingInventoryUploadTask,
|
||||
cancelShippingInventoryTaskSelection: shipping.cancelShippingInventoryTaskSelection,
|
||||
|
||||
@@ -13,7 +13,6 @@ export interface UseChatRouteSyncOptions {
|
||||
currentAgentId: ComputedRef<number>;
|
||||
presetQuestion: ComputedRef<string>;
|
||||
shippingTaskIdFromQuery: ComputedRef<string | null>;
|
||||
shippingBatchNoFromQuery?: ComputedRef<string | null>;
|
||||
isShippingNoticeAgent: ComputedRef<boolean>;
|
||||
resetChatStateForAgentChange: () => void;
|
||||
cancelVoiceInput: () => void;
|
||||
@@ -39,7 +38,6 @@ export function useChatRouteSync(options: UseChatRouteSyncOptions) {
|
||||
currentAgentId,
|
||||
presetQuestion,
|
||||
shippingTaskIdFromQuery,
|
||||
shippingBatchNoFromQuery,
|
||||
resetChatStateForAgentChange,
|
||||
cancelVoiceInput,
|
||||
syncCurrentUserProfile,
|
||||
@@ -103,7 +101,7 @@ export function useChatRouteSync(options: UseChatRouteSyncOptions) {
|
||||
loadConversation(convId, { force: true }),
|
||||
]);
|
||||
if (syncToken !== routeSyncToken) return;
|
||||
} else if (shippingTaskIdFromQuery.value || shippingBatchNoFromQuery?.value) {
|
||||
} else if (shippingTaskIdFromQuery.value) {
|
||||
await historyPromise;
|
||||
if (syncToken !== routeSyncToken) return;
|
||||
await resumeShippingTaskFromQuery();
|
||||
@@ -129,17 +127,16 @@ export function useChatRouteSync(options: UseChatRouteSyncOptions) {
|
||||
});
|
||||
|
||||
watch(
|
||||
() => [route.params.agentId, route.query.conversation_id, route.query.preset, route.query.task_id, route.query.batch_no],
|
||||
() => [route.params.agentId, route.query.conversation_id, route.query.preset, route.query.task_id],
|
||||
async (
|
||||
[nextAgentId, nextConversationId, nextPreset, nextTaskId, nextBatchNo],
|
||||
[prevAgentId, prevConversationId, prevPreset, prevTaskId, prevBatchNo],
|
||||
[nextAgentId, nextConversationId, nextPreset, nextTaskId],
|
||||
[prevAgentId, prevConversationId, prevPreset, prevTaskId],
|
||||
) => {
|
||||
if (
|
||||
nextAgentId === prevAgentId
|
||||
&& nextConversationId === prevConversationId
|
||||
&& nextPreset === prevPreset
|
||||
&& nextTaskId === prevTaskId
|
||||
&& nextBatchNo === prevBatchNo
|
||||
) {
|
||||
return;
|
||||
}
|
||||
@@ -148,7 +145,6 @@ export function useChatRouteSync(options: UseChatRouteSyncOptions) {
|
||||
nextAgentId === prevAgentId
|
||||
&& nextPreset === prevPreset
|
||||
&& nextTaskId === prevTaskId
|
||||
&& nextBatchNo === prevBatchNo
|
||||
&& nextConversationId !== prevConversationId
|
||||
) {
|
||||
if (typeof nextConversationId === 'string' && nextConversationId) {
|
||||
|
||||
@@ -1,150 +1,36 @@
|
||||
/**
|
||||
* features/chat/composables/useChatShipping.spec.ts
|
||||
* 用途:验证发货批次切换后的默认焦点解析,避免右侧工作台沿用旧批次的 focused task。
|
||||
* 用途:验证聊天恢复只使用单票任务锚点。
|
||||
* 依赖:vitest、useChatShipping 纯函数导出。
|
||||
* 逻辑:覆盖 current focus、process summary 回退、首票回退与无任务时清空焦点原因四种路径。
|
||||
* 逻辑:历史回放只接受 task_no / shipping_ui_state,不恢复已下线批次快照。
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
resolveLatestShippingMessageRecoveryPayload,
|
||||
resolveLatestShippingBatchSnapshot,
|
||||
resolveShippingBatchFocusState,
|
||||
selectShippingConversationBatch,
|
||||
} from './useChatShipping';
|
||||
|
||||
describe('useChatShipping batch focus sync', () => {
|
||||
it('prefers batch current focus task and keeps default reason', () => {
|
||||
expect(resolveShippingBatchFocusState(
|
||||
{
|
||||
current_focus_task_no: 'SN-BATCH-B2',
|
||||
process_summary: { current_task_no: 'SN-BATCH-B1' },
|
||||
},
|
||||
[{ task_no: 'SN-BATCH-B0' }],
|
||||
'当前聚焦任务',
|
||||
)).toEqual({
|
||||
taskNo: 'SN-BATCH-B2',
|
||||
focusReason: '当前聚焦任务',
|
||||
});
|
||||
});
|
||||
|
||||
it('falls back to process summary and first task when current focus is absent', () => {
|
||||
expect(resolveShippingBatchFocusState(
|
||||
{
|
||||
current_focus_task_no: '',
|
||||
process_summary: { current_task_no: 'SN-BATCH-C1' },
|
||||
},
|
||||
[{ task_no: 'SN-BATCH-C0' }],
|
||||
'当前聚焦任务',
|
||||
)).toEqual({
|
||||
taskNo: 'SN-BATCH-C1',
|
||||
focusReason: '当前聚焦任务',
|
||||
});
|
||||
|
||||
expect(resolveShippingBatchFocusState(
|
||||
{
|
||||
current_focus_task_no: '',
|
||||
process_summary: { current_task_no: '' },
|
||||
},
|
||||
[{ task_no: 'SN-BATCH-D0' }],
|
||||
'当前聚焦任务',
|
||||
)).toEqual({
|
||||
taskNo: 'SN-BATCH-D0',
|
||||
focusReason: '当前聚焦任务',
|
||||
});
|
||||
});
|
||||
|
||||
it('clears focus state when the new batch has no resolvable task', () => {
|
||||
expect(resolveShippingBatchFocusState(
|
||||
{
|
||||
current_focus_task_no: '',
|
||||
process_summary: { current_task_no: '' },
|
||||
},
|
||||
[],
|
||||
'当前聚焦任务',
|
||||
)).toEqual({
|
||||
taskNo: '',
|
||||
focusReason: '',
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('useChatShipping conversation workspace selection', () => {
|
||||
const batches = [
|
||||
{ batch_no: 'SB-OLD', focus_task: { task_no: 'SN-OLD' } },
|
||||
{ batch_no: 'SB-NEW', focus_task: { task_no: 'SN-NEW' } },
|
||||
];
|
||||
|
||||
it('keeps the active batch during a normal refresh', () => {
|
||||
expect(selectShippingConversationBatch(batches, 'SB-OLD', '', false)?.batch_no).toBe('SB-OLD');
|
||||
});
|
||||
|
||||
it('selects the latest batch after an order extraction turn', () => {
|
||||
expect(selectShippingConversationBatch(batches, 'SB-OLD', '', true)?.batch_no).toBe('SB-NEW');
|
||||
});
|
||||
});
|
||||
|
||||
describe('useChatShipping persisted batch snapshot', () => {
|
||||
it('restores the latest valid batch snapshot from assistant message payloads', () => {
|
||||
const snapshot = resolveLatestShippingBatchSnapshot([
|
||||
{
|
||||
role: 'assistant',
|
||||
content: '旧结果',
|
||||
payload: { shipping_batch_ui_state: { batch_no: 'SB-OLD', tasks: [] } },
|
||||
},
|
||||
{
|
||||
role: 'assistant',
|
||||
content: '无效结果',
|
||||
payload: { shipping_batch_ui_state: { batch_no: 'SB-INVALID' } },
|
||||
},
|
||||
{
|
||||
role: 'assistant',
|
||||
content: '已打开已有任务',
|
||||
payload: {
|
||||
shipping_batch_ui_state: {
|
||||
batch_no: 'SB-EXISTING',
|
||||
current_focus_task_no: 'SN-EXISTING',
|
||||
tasks: [{ task_no: 'SN-EXISTING', source_type: 'email', review_status: 'parse_review' }],
|
||||
},
|
||||
},
|
||||
},
|
||||
]);
|
||||
|
||||
expect(snapshot?.batch_no).toBe('SB-EXISTING');
|
||||
expect(snapshot?.current_focus_task_no).toBe('SN-EXISTING');
|
||||
});
|
||||
|
||||
it('ignores malformed snapshots', () => {
|
||||
expect(resolveLatestShippingBatchSnapshot([
|
||||
{ role: 'assistant', content: '', payload: { shipping_batch_ui_state: { batch_no: 'SB-NO-TASKS' } } },
|
||||
{ role: 'user', content: '继续' },
|
||||
])).toBeNull();
|
||||
});
|
||||
});
|
||||
import { resolveLatestShippingMessageRecoveryPayload } from './useChatShipping';
|
||||
|
||||
describe('useChatShipping message recovery payload', () => {
|
||||
it('falls back to task anchor when batch snapshot is absent', () => {
|
||||
it('recovers a task anchor and read-only UI state', () => {
|
||||
const payload = resolveLatestShippingMessageRecoveryPayload([
|
||||
{
|
||||
role: 'assistant',
|
||||
content: '已打开已有任务',
|
||||
payload: {
|
||||
task_no: 'SN-OPEN-EXISTING',
|
||||
batch_no: 'SB-OPEN-EXISTING',
|
||||
shipping_ui_state: {
|
||||
task_no: 'SN-OPEN-EXISTING',
|
||||
batch_no: 'SB-OPEN-EXISTING',
|
||||
inventory_lines_json: [{ reservation_id: 'R-1' }],
|
||||
steps: [],
|
||||
summary: {},
|
||||
action_buttons: [],
|
||||
},
|
||||
},
|
||||
},
|
||||
]);
|
||||
|
||||
expect(payload?.task_no).toBe('SN-OPEN-EXISTING');
|
||||
expect(payload?.batch_no).toBe('SB-OPEN-EXISTING');
|
||||
expect(payload?.shipping_ui_state?.task_no).toBe('SN-OPEN-EXISTING');
|
||||
expect(payload?.shipping_batch_ui_state).toBeUndefined();
|
||||
});
|
||||
|
||||
it('ignores a legacy batch-only payload', () => {
|
||||
expect(resolveLatestShippingMessageRecoveryPayload([
|
||||
{ role: 'assistant', content: '', payload: { shipping_batch_ui_state: { tasks: [] } } },
|
||||
])).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -3,9 +3,8 @@
|
||||
* 用途:发货通知聊天编排入口,组合 shipping/* 子模块并对 ChatView 暴露统一交互能力。
|
||||
* 依赖: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 供调用方兼容,不再发起批次网络请求。
|
||||
* 以及 focusedConversationTaskNo(提交追加优先级 / 侧栏焦点)。会话恢复唯一使用 task_no;
|
||||
* 批次进度由 shipping-processing projection 承接,不维护已下线 shipping_batches 的本地快照。
|
||||
*/
|
||||
|
||||
import {
|
||||
@@ -31,7 +30,6 @@ import {
|
||||
createShippingSendHandlers,
|
||||
createShippingUploadHandlers,
|
||||
useShippingOrderExtractionRuns,
|
||||
onNoticeBatchConversationChanging,
|
||||
findLatestShippingTaskId,
|
||||
getShippingMatchResultPayload,
|
||||
getShippingParseReviewPayload,
|
||||
@@ -43,13 +41,9 @@ import {
|
||||
getWorkspaceShippingTask,
|
||||
listWorkspaceShippingCustomerOptions,
|
||||
confirmWorkspaceShippingCustomer,
|
||||
type ShippingConversationWorkspace,
|
||||
type ShippingTaskDetail,
|
||||
type ShippingTaskSummary,
|
||||
} from '@/features/chat/api/shipping.api';
|
||||
import type {
|
||||
ShippingBatchSummary,
|
||||
ShippingBatchUiState,
|
||||
ShippingCustomerOption,
|
||||
} from '../types/shipping.api.types';
|
||||
import { buildShippingQueryShortageTurn } from '../shipping/shippingTurnActions';
|
||||
@@ -91,7 +85,7 @@ export interface UseChatShippingOptions {
|
||||
agentId: number,
|
||||
kb: string,
|
||||
files: ChatUploadFileSpec[],
|
||||
context?: { task_id?: string; batch_no?: string; shipping_temporary_inventory_asset_no?: string; shipping_temporary_inventory_session_no?: string; display_query?: string },
|
||||
context?: { task_id?: string; shipping_temporary_inventory_asset_no?: string; shipping_temporary_inventory_session_no?: string; display_query?: string },
|
||||
hooks?: SendMessageLifecycleHooks,
|
||||
) => Promise<ChatMessageSendResult>;
|
||||
startChatTurn: (options: import('../types/chat-turn.types').StartChatTurnOptions) => Promise<boolean>;
|
||||
@@ -100,78 +94,9 @@ export interface UseChatShippingOptions {
|
||||
createNewChatView: () => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析批次切换后的默认焦点状态。
|
||||
* 核心逻辑:优先取状态机记录的 current focus,其次回退到 process summary 当前任务,再回退到任务列表首票;只有拿到 task_no 才回填默认聚焦原因。
|
||||
* @param batchSummary - 当前批次摘要
|
||||
* @param batchTasks - 当前批次任务列表
|
||||
* @param defaultReason - 批次切换后写入输入栏提示的默认焦点原因
|
||||
* @returns 供步骤条、按钮与右侧工作台共用的 focus 状态;取不到 task 时返回空焦点
|
||||
*/
|
||||
export const resolveShippingBatchFocusState = (
|
||||
batchSummary: {
|
||||
current_focus_task_no?: string | null;
|
||||
process_summary?: { current_task_no?: string | null } | null;
|
||||
} | null | undefined,
|
||||
batchTasks: Array<{ task_no?: string | null }> | null | undefined,
|
||||
defaultReason: string,
|
||||
) => {
|
||||
const taskNo = String(
|
||||
batchSummary?.current_focus_task_no
|
||||
|| batchSummary?.process_summary?.current_task_no
|
||||
|| batchTasks?.[0]?.task_no
|
||||
|| '',
|
||||
).trim();
|
||||
return {
|
||||
taskNo,
|
||||
focusReason: taskNo ? defaultReason : '',
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* 从会话工作台选择本轮应展示的批次。
|
||||
* 核心逻辑:订单抽取完成后选服务端按创建时间升序返回的最后一个批次;普通续办优先保留当前批次。
|
||||
*/
|
||||
export const selectShippingConversationBatch = <T extends { batch_no: string; focus_task?: unknown }>(
|
||||
batches: T[],
|
||||
currentBatchNo: string,
|
||||
queryBatchNo: string,
|
||||
preferLatest = false,
|
||||
): T | undefined => (
|
||||
(preferLatest ? batches[batches.length - 1] : undefined)
|
||||
|| batches.find((item) => item.batch_no === currentBatchNo)
|
||||
|| (queryBatchNo ? batches.find((item) => item.batch_no === queryBatchNo) : undefined)
|
||||
|| batches.find((item) => Boolean(item.focus_task))
|
||||
|| batches[0]
|
||||
);
|
||||
|
||||
/**
|
||||
* 从消息列表解析最近一次权威批次快照。
|
||||
* 核心逻辑:只接受包含批次号和任务数组的 `shipping_batch_ui_state`,供实时终态与历史会话共用。
|
||||
* @param sourceMessages - 当前会话消息
|
||||
* @returns 最近的合法批次快照;不存在时返回 null
|
||||
*/
|
||||
export const resolveLatestShippingBatchSnapshot = (
|
||||
sourceMessages: ChatMessage[],
|
||||
): ShippingBatchUiState | null => {
|
||||
for (let index = sourceMessages.length - 1; index >= 0; index -= 1) {
|
||||
const message = sourceMessages[index];
|
||||
const payload = message?.payload && typeof message.payload === 'object'
|
||||
? message.payload as Record<string, unknown>
|
||||
: null;
|
||||
const rawSnapshot = payload?.shipping_batch_ui_state;
|
||||
if (!rawSnapshot || typeof rawSnapshot !== 'object') continue;
|
||||
const snapshot = rawSnapshot as ShippingBatchUiState;
|
||||
if (String(snapshot.batch_no || '').trim() && Array.isArray(snapshot.tasks)) {
|
||||
return snapshot;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
/**
|
||||
* 从单条助手消息中提取工作台恢复锚点。
|
||||
* 核心逻辑:优先识别合法 `shipping_batch_ui_state`,其次回退到 `task_no / batch_no / shipping_ui_state`;
|
||||
* 核心逻辑:只接受 `task_no / shipping_ui_state`;
|
||||
* 供实时终态、历史回放与刷新恢复共用。
|
||||
*/
|
||||
export const resolveShippingMessageRecoveryPayload = (
|
||||
@@ -181,34 +106,18 @@ export const resolveShippingMessageRecoveryPayload = (
|
||||
? message.payload as ShippingMessageRecoveryPayload
|
||||
: null;
|
||||
if (!payload) return null;
|
||||
const batchSnapshot = payload.shipping_batch_ui_state;
|
||||
const hasBatchSnapshot = Boolean(
|
||||
batchSnapshot
|
||||
&& String(batchSnapshot.batch_no || '').trim()
|
||||
&& Array.isArray(batchSnapshot.tasks),
|
||||
);
|
||||
const taskNo = String(
|
||||
payload.task_no
|
||||
|| payload.shipping_ui_state?.task_no
|
||||
|| batchSnapshot?.current_focus_task_no
|
||||
|| batchSnapshot?.focus_task?.task_no
|
||||
|| batchSnapshot?.tasks?.[0]?.task_no
|
||||
|| '',
|
||||
).trim();
|
||||
const batchNo = String(
|
||||
payload.batch_no
|
||||
|| payload.shipping_ui_state?.batch_no
|
||||
|| batchSnapshot?.batch_no
|
||||
|| '',
|
||||
).trim();
|
||||
const hasTaskUiState = Boolean(payload.shipping_ui_state && typeof payload.shipping_ui_state === 'object');
|
||||
if (!hasBatchSnapshot && !taskNo && !batchNo && !hasTaskUiState) {
|
||||
if (!taskNo && !hasTaskUiState) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
...payload,
|
||||
...(taskNo ? { task_no: taskNo } : {}),
|
||||
...(batchNo ? { batch_no: batchNo } : {}),
|
||||
};
|
||||
};
|
||||
|
||||
@@ -288,160 +197,34 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
return sanitizeShippingConversationText(stripReasoningPrelude(text), isShippingNoticeAgent.value);
|
||||
};
|
||||
|
||||
// ── 任务编号状态(会话摘要同步,无抽屉/焦点条) ──────────────
|
||||
// ── 任务编号状态(单票恢复锚点) ─────────────────────────────
|
||||
const shippingTaskIdFromQuery = computed(() => {
|
||||
const value = route.query.task_id;
|
||||
return typeof value === 'string' ? value.trim() : '';
|
||||
});
|
||||
const shippingBatchNoFromQuery = computed(() => {
|
||||
const value = route.query.batch_no;
|
||||
return typeof value === 'string' ? value.trim() : '';
|
||||
});
|
||||
const resolvedShippingTaskId = ref('');
|
||||
const resolvedShippingBatchNo = ref('');
|
||||
const activeShippingBatchNo = ref('');
|
||||
const shippingConversationWorkspace = ref<ShippingConversationWorkspace | null>(null);
|
||||
const shippingBatchSummary = ref<ShippingBatchSummary | null>(null);
|
||||
const shippingBatchTasks = ref<ShippingTaskSummary[]>([]);
|
||||
const activeShippingTaskDetail = ref<ShippingTaskDetail | null>(null);
|
||||
const autoResumedShippingTasks = ref<Record<string, boolean>>({});
|
||||
const lastConversationSyncKey = ref('');
|
||||
let shippingStatusPollTimer: ReturnType<typeof setInterval> | null = null;
|
||||
|
||||
const applyShippingBatchDetail = (
|
||||
detail: ShippingBatchUiState,
|
||||
fallbackBatchNo: string,
|
||||
) => {
|
||||
const normalizedBatchNo = detail.batch_no || fallbackBatchNo;
|
||||
resolvedShippingBatchNo.value = normalizedBatchNo;
|
||||
if (!activeShippingBatchNo.value || activeShippingBatchNo.value === fallbackBatchNo) {
|
||||
activeShippingBatchNo.value = normalizedBatchNo;
|
||||
}
|
||||
shippingBatchTasks.value = Array.isArray(detail.tasks) ? detail.tasks : [];
|
||||
shippingBatchSummary.value = {
|
||||
id: detail.id,
|
||||
batch_no: detail.batch_no,
|
||||
conversation_id: detail.conversation_id,
|
||||
current_focus_task_no: detail.focus_task?.task_no || detail.current_focus_task_no || null,
|
||||
file_count: detail.file_count,
|
||||
process_summary: detail.process_summary || null,
|
||||
created_at: detail.created_at,
|
||||
updated_at: detail.updated_at,
|
||||
};
|
||||
const preferredTaskNo = String(
|
||||
detail.focus_task?.task_no
|
||||
|| detail.process_summary?.current_task_no
|
||||
|| detail.current_focus_task_no
|
||||
|| '',
|
||||
).trim();
|
||||
if (preferredTaskNo) {
|
||||
resolvedShippingTaskId.value = preferredTaskNo;
|
||||
}
|
||||
if (detail.focus_task && detail.focus_task_ui_state) {
|
||||
activeShippingTaskDetail.value = {
|
||||
...(activeShippingTaskDetail.value || {}),
|
||||
...detail.focus_task,
|
||||
lines: activeShippingTaskDetail.value?.lines || [],
|
||||
events: activeShippingTaskDetail.value?.events || [],
|
||||
ui_state: detail.focus_task_ui_state,
|
||||
} as ShippingTaskDetail;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 同步批次摘要占位(co8 已下线批次详情 API)。
|
||||
* 按任务锚点恢复聊天工作台。
|
||||
*
|
||||
* 核心逻辑:batchNo 为空时清空摘要;否则仅回填本地 batch_no 与已有 task 焦点,不发起网络请求。
|
||||
* @param batchNo - 目标批次号
|
||||
*/
|
||||
const syncShippingBatchSummary = async (batchNo: string) => {
|
||||
const normalized = String(batchNo || '').trim();
|
||||
if (!normalized) {
|
||||
shippingBatchSummary.value = null;
|
||||
shippingBatchTasks.value = [];
|
||||
return;
|
||||
}
|
||||
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,
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* 同步会话批次工作台(co8 已下线 conversation batches API)。
|
||||
*
|
||||
* 核心逻辑:保留调用签名供抽取 Run / 终态刷新链路兼容;始终清空 workspace 并返回 false,不发起网络。
|
||||
* @param _options - 历史参数,保留兼容
|
||||
* @returns 恒为 false
|
||||
*/
|
||||
const syncShippingConversationWorkspace = async (
|
||||
_options?: { preferLatest?: boolean },
|
||||
): Promise<boolean> => {
|
||||
void _options;
|
||||
shippingConversationWorkspace.value = null;
|
||||
return false;
|
||||
};
|
||||
|
||||
/**
|
||||
* 从本轮 SSE 助手消息恢复权威批次快照。
|
||||
*
|
||||
* 核心逻辑:订单识别可能打开属于旧会话的已有任务,此时按当前会话补拉工作台会返回空批次;
|
||||
* 优先应用 `shipping_ui_state` 事件随消息持久化的 `shipping_batch_ui_state`,再由接口刷新后续状态。
|
||||
* @param message - 当前流式回答完成后的助手消息
|
||||
* @returns 是否找到并应用了合法批次快照
|
||||
*/
|
||||
const applyResolvedShippingBatchSnapshot = (snapshot: ShippingBatchUiState | null): boolean => {
|
||||
if (!snapshot) return false;
|
||||
const batchNo = String(snapshot.batch_no || '').trim();
|
||||
applyShippingBatchDetail(snapshot, batchNo);
|
||||
return true;
|
||||
};
|
||||
|
||||
const applyShippingBatchSnapshot = (message: ChatMessage): boolean => (
|
||||
applyResolvedShippingBatchSnapshot(resolveLatestShippingBatchSnapshot([message]))
|
||||
);
|
||||
|
||||
/**
|
||||
* 按“批次快照 -> 任务/批次锚点 -> 会话工作台”顺序恢复聊天工作台。
|
||||
*
|
||||
* 核心逻辑:`open_existing` 可能只携带 `task_no / shipping_ui_state`;此时先恢复任务锚点并补拉任务详情,
|
||||
* 再尝试按任务所属批次加载批次详情,最后才回退到当前会话工作台。
|
||||
* 核心逻辑:`open_existing` 携带 `task_no / shipping_ui_state`;恢复任务锚点后补拉任务详情。
|
||||
* @param payload - 从消息中解析出的恢复载荷
|
||||
* @returns 是否至少恢复出一层任务或批次上下文
|
||||
* @returns 是否恢复出任务上下文
|
||||
*/
|
||||
const applyResolvedShippingMessageRecovery = async (
|
||||
payload: ShippingMessageRecoveryPayload | null,
|
||||
): Promise<boolean> => {
|
||||
if (!payload) return false;
|
||||
let recovered = false;
|
||||
const snapshot = payload.shipping_batch_ui_state ?? null;
|
||||
if (applyResolvedShippingBatchSnapshot(snapshot)) {
|
||||
recovered = true;
|
||||
}
|
||||
|
||||
const taskNo = String(
|
||||
payload.task_no
|
||||
|| payload.shipping_ui_state?.task_no
|
||||
|| '',
|
||||
).trim().toUpperCase();
|
||||
let batchNo = String(
|
||||
payload.batch_no
|
||||
|| payload.shipping_ui_state?.batch_no
|
||||
|| snapshot?.batch_no
|
||||
|| '',
|
||||
).trim();
|
||||
|
||||
if (batchNo) {
|
||||
resolvedShippingBatchNo.value = batchNo;
|
||||
activeShippingBatchNo.value = batchNo;
|
||||
}
|
||||
if (taskNo) {
|
||||
resolvedShippingTaskId.value = taskNo;
|
||||
}
|
||||
@@ -449,52 +232,23 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
activeShippingTaskDetail.value = {
|
||||
...(activeShippingTaskDetail.value || {}),
|
||||
task_no: taskNo,
|
||||
batch_no: batchNo || payload.shipping_ui_state.batch_no || null,
|
||||
lines: activeShippingTaskDetail.value?.lines || [],
|
||||
events: activeShippingTaskDetail.value?.events || [],
|
||||
ui_state: payload.shipping_ui_state,
|
||||
} as ShippingTaskDetail;
|
||||
recovered = true;
|
||||
}
|
||||
if (!snapshot && batchNo) {
|
||||
await syncShippingBatchSummary(batchNo);
|
||||
recovered = true;
|
||||
}
|
||||
if (taskNo) {
|
||||
await syncActiveShippingTaskDetail(taskNo);
|
||||
const detailBatchNo = String(activeShippingTaskDetail.value?.batch_no || '').trim();
|
||||
if (detailBatchNo) {
|
||||
batchNo = detailBatchNo;
|
||||
resolvedShippingBatchNo.value = detailBatchNo;
|
||||
activeShippingBatchNo.value = detailBatchNo;
|
||||
}
|
||||
if (!snapshot && batchNo && String(shippingBatchSummary.value?.batch_no || '').trim() !== batchNo) {
|
||||
await syncShippingBatchSummary(batchNo);
|
||||
recovered = true;
|
||||
}
|
||||
recovered = recovered || Boolean(activeShippingTaskDetail.value);
|
||||
}
|
||||
return recovered || Boolean(batchNo);
|
||||
return recovered;
|
||||
};
|
||||
|
||||
const applyShippingMessageRecovery = async (message: ChatMessage): Promise<boolean> => (
|
||||
applyResolvedShippingMessageRecovery(resolveShippingMessageRecoveryPayload(message))
|
||||
);
|
||||
|
||||
/**
|
||||
* 切换会话上传摘要中的活动批次(co8 已下线,保留签名兼容)。
|
||||
*
|
||||
* 核心逻辑:批次工作台 API 已移除,调用时仅提示用户改由右侧 processing 工作台操作。
|
||||
* @param batchNo - 目标批次号
|
||||
* @returns 恒为 false
|
||||
*/
|
||||
const switchShippingBatch = async (batchNo: string) => {
|
||||
const normalizedBatchNo = String(batchNo || '').trim();
|
||||
if (!normalizedBatchNo) return false;
|
||||
msg.warning(t('chat.shippingNoticeUi.batchSwitchRemoved'));
|
||||
return false;
|
||||
};
|
||||
|
||||
/**
|
||||
* 清空当前聊天页绑定的发货任务上下文。
|
||||
*
|
||||
@@ -512,11 +266,6 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
shippingInventorySelectionActive.value = false;
|
||||
shippingInventorySelectionTaskId.value = '';
|
||||
resolvedShippingTaskId.value = '';
|
||||
resolvedShippingBatchNo.value = '';
|
||||
activeShippingBatchNo.value = '';
|
||||
shippingConversationWorkspace.value = null;
|
||||
shippingBatchSummary.value = null;
|
||||
shippingBatchTasks.value = [];
|
||||
activeShippingTaskDetail.value = null;
|
||||
lastConversationSyncKey.value = '';
|
||||
};
|
||||
@@ -527,16 +276,8 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
|| shippingTaskIdFromQuery.value
|
||||
|| '';
|
||||
|
||||
const getActiveShippingBatchNo = () =>
|
||||
activeShippingBatchNo.value
|
||||
|| resolvedShippingBatchNo.value
|
||||
|| shippingBatchNoFromQuery.value
|
||||
|| String(shippingBatchSummary.value?.batch_no || '').trim()
|
||||
|| '';
|
||||
|
||||
const getCurrentShippingChatContext = () => ({
|
||||
task_id: getActiveBatchTaskId() || getActiveShippingTaskId(),
|
||||
batch_no: getActiveShippingBatchNo(),
|
||||
task_id: getActiveShippingTaskId(),
|
||||
});
|
||||
|
||||
const getCurrentShippingChatContextWithDisplay = (displayQuery: string) => ({
|
||||
@@ -544,23 +285,10 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
display_query: displayQuery,
|
||||
});
|
||||
|
||||
const getActiveBatchTaskId = () => String(
|
||||
shippingBatchSummary.value?.current_focus_task_no
|
||||
|| shippingBatchSummary.value?.process_summary?.current_task_no
|
||||
|| shippingBatchTasks.value[0]?.task_no
|
||||
|| resolvedShippingTaskId.value
|
||||
|| '',
|
||||
).trim();
|
||||
|
||||
const hasRunningShippingBatchTasks = () =>
|
||||
shippingBatchTasks.value.some(
|
||||
(task) => String(task.ui_state?.stage?.code || '').trim() !== 'upload_complete',
|
||||
);
|
||||
|
||||
/**
|
||||
* 同步当前焦点任务详情,并在仅恢复 `task_no` 的场景下补齐 `batch_no` 上下文。
|
||||
* 同步当前焦点任务详情。
|
||||
*
|
||||
* 核心逻辑:先拉取任务详情,再把详情里的批次号回填到聊天状态,确保会话恢复后仍能继续按批次模式加载 2 票/多票摘要。
|
||||
* 核心逻辑:仅拉取任务详情;批次进度由独立 processing projection 提供。
|
||||
* @param taskId - 可选任务编号;未传时回退到当前激活任务
|
||||
*/
|
||||
const syncActiveShippingTaskDetail = async (taskId?: string) => {
|
||||
@@ -571,16 +299,7 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
}
|
||||
try {
|
||||
const detail = await getWorkspaceShippingTask(normalized);
|
||||
const detailBatchNo = String(detail.batch_no || '').trim();
|
||||
const activeBatchNo = String(activeShippingBatchNo.value || '').trim();
|
||||
if (activeBatchNo && detailBatchNo && detailBatchNo !== activeBatchNo) {
|
||||
return;
|
||||
}
|
||||
activeShippingTaskDetail.value = detail;
|
||||
if (detailBatchNo && resolvedShippingBatchNo.value !== detailBatchNo) {
|
||||
resolvedShippingBatchNo.value = detailBatchNo;
|
||||
activeShippingBatchNo.value = activeShippingBatchNo.value || detailBatchNo;
|
||||
}
|
||||
} catch {
|
||||
activeShippingTaskDetail.value = null;
|
||||
}
|
||||
@@ -637,7 +356,7 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
isThinking,
|
||||
resolvedShippingTaskId,
|
||||
shippingTaskIdFromQuery,
|
||||
getActiveBatchTaskId,
|
||||
getActiveShippingTaskId,
|
||||
});
|
||||
|
||||
/**
|
||||
@@ -649,10 +368,6 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
const finalizeShippingAssistantMessage = async () => {
|
||||
if (!isShippingNoticeAgent.value) return;
|
||||
await shippingIntakes.refreshStatuses();
|
||||
if (!(await syncShippingConversationWorkspace())) {
|
||||
await new Promise((resolve) => setTimeout(resolve, 300));
|
||||
await syncShippingConversationWorkspace();
|
||||
}
|
||||
shippingIntakes.clearConsumedAttachments();
|
||||
await refreshShippingActions();
|
||||
};
|
||||
@@ -666,15 +381,10 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
const resolveShippingTaskForShortageQuery = async (taskNo?: string) => {
|
||||
const normalizedTaskNo = String(
|
||||
taskNo
|
||||
|| getActiveBatchTaskId()
|
||||
|| getActiveShippingTaskId()
|
||||
|| '',
|
||||
).trim().toUpperCase();
|
||||
if (!normalizedTaskNo) return null;
|
||||
const summaryTask = shippingBatchTasks.value.find(
|
||||
(item) => String(item.task_no || '').trim().toUpperCase() === normalizedTaskNo,
|
||||
);
|
||||
if (summaryTask && hasShortageLines(summaryTask)) return summaryTask;
|
||||
const detail = activeShippingTaskDetail.value;
|
||||
if (String(detail?.task_no || '').trim().toUpperCase() === normalizedTaskNo && hasShortageLines(detail)) {
|
||||
return detail;
|
||||
@@ -682,7 +392,7 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
try {
|
||||
return await getWorkspaceShippingTask(normalizedTaskNo);
|
||||
} catch {
|
||||
return summaryTask || null;
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
@@ -772,7 +482,6 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
refreshNoticeIntakeStatuses: shippingIntakes.refreshStatuses,
|
||||
getOrderExtractionReview: shippingIntakes.getOrderExtractionReview,
|
||||
clearConsumedNoticeAttachments: shippingIntakes.clearConsumedAttachments,
|
||||
syncShippingConversationWorkspace,
|
||||
refreshShippingActions,
|
||||
loadHistory,
|
||||
onConversationResolved: async (resolvedConversationId) => {
|
||||
@@ -962,6 +671,7 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
const {
|
||||
handleShippingAutoUploadFile,
|
||||
handleShippingAutoUploadNoticeBatch,
|
||||
openShippingInventoryPicker,
|
||||
openShippingNoticePicker,
|
||||
selectShippingInventoryUploadTask,
|
||||
cancelShippingInventoryTaskSelection,
|
||||
@@ -981,9 +691,6 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
pendingShippingNoticeTaskId,
|
||||
pendingShippingInventoryFile,
|
||||
resolvedShippingTaskId,
|
||||
resolvedShippingBatchNo,
|
||||
shippingBatchSummary,
|
||||
shippingBatchTasks,
|
||||
shippingInventorySelectionActive,
|
||||
shippingInventorySelectionTaskId,
|
||||
getActiveShippingTaskId,
|
||||
@@ -1013,6 +720,7 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
getActiveShippingTaskId,
|
||||
messages,
|
||||
sendShippingMenuMessage,
|
||||
openShippingInventoryPicker,
|
||||
openShippingNoticePicker,
|
||||
openShippingCustomerDialog,
|
||||
executeShippingDecision,
|
||||
@@ -1033,7 +741,6 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
attachments,
|
||||
shippingAutoFlowRequested,
|
||||
resolvedShippingTaskId,
|
||||
getActiveShippingBatchNo,
|
||||
currentAgentId,
|
||||
selectedKb,
|
||||
attachmentPolicy,
|
||||
@@ -1060,8 +767,6 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
getParsedIntakeNos: shippingIntakes.getParsedIntakeNos,
|
||||
startOrderExtractionRun: shippingOrderExtractionRuns.startRun,
|
||||
applyShippingMessageRecovery,
|
||||
applyShippingBatchSnapshot,
|
||||
syncShippingConversationWorkspace,
|
||||
refreshShippingActions,
|
||||
shippingSuggestedPrompt,
|
||||
isShippingShortageQueryIntent,
|
||||
@@ -1072,19 +777,11 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
|
||||
// ── 路由 / 会话生命周期 ───────────────────────────────────
|
||||
/**
|
||||
* 根据路由中的 `task_id/batch_no` 恢复发货任务上下文。
|
||||
* 核心逻辑:优先同步显式传入的批次摘要;若仍缺少会话,则直接基于 `task_id` 发起一次继续任务请求,
|
||||
* 禁止再按历史标题模糊猜测旧会话,避免多批次/多票场景跳进错误会话。
|
||||
* 根据路由中的 `task_id` 恢复发货任务上下文。
|
||||
* 核心逻辑:直接基于明确 task_id 发起一次继续任务请求,禁止按历史标题模糊猜测会话。
|
||||
* @returns Promise<void>
|
||||
*/
|
||||
const resumeShippingTaskFromQuery = async () => {
|
||||
const batchNo = shippingBatchNoFromQuery.value;
|
||||
if (batchNo && isShippingNoticeAgent.value) {
|
||||
await syncShippingBatchSummary(batchNo);
|
||||
if (!shippingTaskIdFromQuery.value && resolvedShippingTaskId.value) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
const taskId = shippingTaskIdFromQuery.value;
|
||||
if (!taskId || !isShippingNoticeAgent.value) return;
|
||||
if (route.query.conversation_id) return;
|
||||
@@ -1103,7 +800,6 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
};
|
||||
|
||||
const onConversationIdChanging = (nextId: string, prevId: string | null | undefined) => {
|
||||
onNoticeBatchConversationChanging(nextId, prevId);
|
||||
shippingIntakes.stopPolling();
|
||||
if (nextId && nextId !== prevId) {
|
||||
focusedConversationTaskNo.value = null;
|
||||
@@ -1114,28 +810,9 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
}
|
||||
if (prevId !== nextId) {
|
||||
resolvedShippingTaskId.value = '';
|
||||
if (!shippingBatchNoFromQuery.value) {
|
||||
resolvedShippingBatchNo.value = '';
|
||||
shippingBatchSummary.value = null;
|
||||
shippingBatchTasks.value = [];
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 重试当前聚焦批次中可恢复的失败/排队任务(co8 已下线,保留签名兼容)。
|
||||
*
|
||||
* 核心逻辑:批次重试 API 已移除,调用时提示用户改由 processing 工作台或任务动作重试。
|
||||
* @returns 恒为 null
|
||||
*/
|
||||
const retryCurrentShippingBatchPendingTasks = async (): Promise<{
|
||||
started: number;
|
||||
skipped: number;
|
||||
} | null> => {
|
||||
msg.warning(t('chat.shippingNoticeUi.batchRetryRemoved'));
|
||||
return null;
|
||||
};
|
||||
|
||||
const handleShippingLocalFilesSelected = (event: Event): boolean => {
|
||||
if (!isShippingNoticeAgent.value) return false;
|
||||
const inputEl = event.target as HTMLInputElement | null;
|
||||
@@ -1167,7 +844,6 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
const onConversationLoadedEmpty = async () => {
|
||||
if (!isShippingNoticeAgent.value || !shippingTaskIdFromQuery.value || isShippingActionBusy.value) return;
|
||||
const nextQuery: Record<string, string> = { task_id: shippingTaskIdFromQuery.value };
|
||||
if (shippingBatchNoFromQuery.value) nextQuery.batch_no = shippingBatchNoFromQuery.value;
|
||||
await router.replace({ path: route.path, query: nextQuery });
|
||||
};
|
||||
|
||||
@@ -1175,7 +851,6 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
if (!isShippingNoticeAgent.value || !shippingTaskIdFromQuery.value || isShippingActionBusy.value) return;
|
||||
createNewChatView();
|
||||
const nextQuery: Record<string, string> = { task_id: shippingTaskIdFromQuery.value };
|
||||
if (shippingBatchNoFromQuery.value) nextQuery.batch_no = shippingBatchNoFromQuery.value;
|
||||
void router.replace({ path: route.path, query: nextQuery });
|
||||
const displayText = t('chat.shippingNoticeUi.retrySingleTaskMessage', { taskId: shippingTaskIdFromQuery.value });
|
||||
await sendMessage(
|
||||
@@ -1200,18 +875,18 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
shippingStatusPollTimer = null;
|
||||
}
|
||||
if (!isShippingNoticeAgent.value) return;
|
||||
const taskId = getActiveBatchTaskId() || getActiveShippingTaskId();
|
||||
const taskId = getActiveShippingTaskId();
|
||||
if (!taskId) return;
|
||||
|
||||
shippingStatusPollTimer = setInterval(() => {
|
||||
if (!isShippingNoticeAgent.value) return;
|
||||
const nextTaskId = getActiveBatchTaskId() || getActiveShippingTaskId();
|
||||
const nextTaskId = getActiveShippingTaskId();
|
||||
if (!nextTaskId) return;
|
||||
void (async () => {
|
||||
await syncActiveShippingTaskDetail(nextTaskId);
|
||||
await syncConversationMessagesIfNeeded(nextTaskId);
|
||||
await refreshShippingActions();
|
||||
if (!hasRunningShippingBatchTasks() && !isShippingActionBusy.value && shippingStatusPollTimer) {
|
||||
if (!isShippingActionBusy.value && shippingStatusPollTimer) {
|
||||
clearInterval(shippingStatusPollTimer);
|
||||
shippingStatusPollTimer = null;
|
||||
}
|
||||
@@ -1232,15 +907,11 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
});
|
||||
const shippingRecoveryWatchKey = computed(() => {
|
||||
const recovery = resolveLatestShippingMessageRecoveryPayload(messages.value);
|
||||
const snapshot = recovery?.shipping_batch_ui_state;
|
||||
const uiState = recovery?.shipping_ui_state;
|
||||
return [
|
||||
String(conversationId.value || ''),
|
||||
String(recovery?.batch_no || snapshot?.batch_no || uiState?.batch_no || ''),
|
||||
String(recovery?.task_no || snapshot?.current_focus_task_no || uiState?.task_no || ''),
|
||||
String(snapshot?.updated_at || ''),
|
||||
String(recovery?.task_no || uiState?.task_no || ''),
|
||||
String(uiState?.updated_at || ''),
|
||||
String(snapshot?.tasks.length || 0),
|
||||
].join('|');
|
||||
});
|
||||
watch([shippingRecoveryWatchKey, isShippingNoticeAgent], () => {
|
||||
@@ -1249,7 +920,7 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
}, { immediate: true });
|
||||
watch([shippingActionsWatchKey, isThinking, isShippingNoticeAgent, () => currentAgent.value?.name], () => {
|
||||
void refreshShippingActions().then(async () => {
|
||||
const taskId = getActiveBatchTaskId() || getActiveShippingTaskId();
|
||||
const taskId = getActiveShippingTaskId();
|
||||
await Promise.all([
|
||||
syncShippingParseReviewCard(taskId),
|
||||
syncActiveShippingTaskDetail(taskId),
|
||||
@@ -1257,19 +928,8 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
await syncConversationMessagesIfNeeded(taskId);
|
||||
});
|
||||
});
|
||||
watch([activeShippingBatchNo, shippingBatchNoFromQuery, resolvedShippingBatchNo], ([activeBatchNo, queryBatchNo, batchNo]) => {
|
||||
const nextBatchNo = String(activeBatchNo || queryBatchNo || batchNo || '').trim();
|
||||
if (!nextBatchNo) {
|
||||
shippingBatchSummary.value = null;
|
||||
return;
|
||||
}
|
||||
void syncShippingBatchSummary(nextBatchNo);
|
||||
}, { immediate: true });
|
||||
watch([conversationId, isShippingNoticeAgent], () => {
|
||||
void syncShippingConversationWorkspace();
|
||||
}, { immediate: true });
|
||||
watch(
|
||||
[isShippingNoticeAgent, conversationId, resolvedShippingBatchNo, shippingBatchNoFromQuery, resolvedShippingTaskId, shippingTaskIdFromQuery, isThinking],
|
||||
[isShippingNoticeAgent, conversationId, resolvedShippingTaskId, shippingTaskIdFromQuery, isThinking],
|
||||
() => {
|
||||
restartShippingStatusPolling();
|
||||
},
|
||||
@@ -1294,18 +954,9 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
shippingInventorySelectionTaskId,
|
||||
allowsSendWithAttachmentsOnly,
|
||||
shippingTaskIdFromQuery,
|
||||
shippingBatchNoFromQuery,
|
||||
resolvedShippingBatchNo,
|
||||
activeShippingBatchNo,
|
||||
shippingConversationWorkspace,
|
||||
shippingBatchSummary,
|
||||
shippingBatchTasks,
|
||||
isShippingActionBusy,
|
||||
activeShippingTaskDetail,
|
||||
getCurrentShippingChatContext,
|
||||
getActiveShippingBatchNo,
|
||||
switchShippingBatch,
|
||||
retryCurrentShippingBatchPendingTasks,
|
||||
queryShippingShortageDetails,
|
||||
resetShippingConversationState,
|
||||
resumeShippingTaskFromQuery,
|
||||
|
||||
@@ -65,15 +65,16 @@ describe('shipping order review workbench viewport layout contract', () => {
|
||||
expect(share1440).toBeGreaterThanOrEqual(0.62);
|
||||
});
|
||||
|
||||
it('keeps four lifecycle columns while reserving 16rem only for the desktop sidebar', () => {
|
||||
it('keeps five lifecycle columns while reserving 16rem only for the desktop sidebar', () => {
|
||||
const lifecycleNavigation = readFileSync(lifecycleNavigationPath, 'utf8');
|
||||
const reviewWorkbench = readFileSync(reviewWorkbenchPath, 'utf8');
|
||||
|
||||
// 关键断言:接收解析为第四阶段;必须断言真实导航组件,不能只验证 spec 内常量。
|
||||
expect(lifecycleNavigation).toContain('class="grid gap-2 sm:grid-cols-4"');
|
||||
// 关键断言:导航真实渲染五个业务阶段,不能只验证 spec 内常量。
|
||||
expect(lifecycleNavigation).toContain('class="grid gap-2 sm:grid-cols-5"');
|
||||
// sidebar/sidebar_search 是唯一允许预留 16rem 的模式;tabs/hidden/narrow 均落入 contents。
|
||||
expect(reviewWorkbench).toMatch(/reviewDocumentNavigationMode\.value === 'sidebar'\s*\|\|\s*reviewDocumentNavigationMode\.value === 'sidebar_search'/);
|
||||
expect(reviewWorkbench).toMatch(/:class="reviewDocumentNavigationUsesSidebar\s*\? 'grid gap-2 lg:grid-cols-\[16rem_minmax\(0,1fr\)\] lg:items-start lg:gap-3'\s*:\s*'contents'"/);
|
||||
expect(reviewWorkbench).toContain('reviewDocumentNavigationCollapsed');
|
||||
expect(reviewWorkbench).toContain('lg:grid-cols-[16rem_minmax(0,1fr)]');
|
||||
expect(reviewWorkbench).not.toMatch(/reviewDocumentNavigationMode\.value === '(?:tabs|hidden|narrow)'\s*\?\s*'[^']*16rem/);
|
||||
});
|
||||
});
|
||||
@@ -8,7 +8,6 @@ import { computed, ref } from 'vue';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { createChatPageConversationApi } from './useChatPageConversation';
|
||||
import {
|
||||
clearPendingNoticeBatchRetry,
|
||||
createShippingUploadHandlers,
|
||||
resetShippingNoticeBatchSubmitStateForTests,
|
||||
type ShippingUploadHandlerContext,
|
||||
@@ -49,13 +48,11 @@ const createConversationContext = () => {
|
||||
messages.value = loaded;
|
||||
},
|
||||
createNewChatView,
|
||||
clearPendingNoticeBatchRetry,
|
||||
onConversationIdChanging: vi.fn(),
|
||||
onConversationLoadedEmpty: vi.fn(async () => undefined),
|
||||
onConversationLoadFailed: vi.fn(async () => undefined),
|
||||
isShippingNoticeAgent: computed(() => true),
|
||||
shippingTaskIdFromQuery: computed(() => ''),
|
||||
shippingBatchNoFromQuery: computed(() => ''),
|
||||
clearHistory: vi.fn(),
|
||||
clearAttachments: vi.fn(),
|
||||
input: ref(''),
|
||||
@@ -86,9 +83,6 @@ const createUploadContext = (
|
||||
pendingShippingNoticeTaskId: ref(''),
|
||||
pendingShippingInventoryFile: ref(null),
|
||||
resolvedShippingTaskId: ref(''),
|
||||
resolvedShippingBatchNo: ref(''),
|
||||
shippingBatchSummary: ref(null),
|
||||
shippingBatchTasks: ref([]),
|
||||
shippingInventorySelectionActive: ref(false),
|
||||
shippingInventorySelectionTaskId: ref(''),
|
||||
getActiveShippingTaskId: () => '',
|
||||
|
||||
@@ -17,13 +17,11 @@ export interface ChatPageConversationContext {
|
||||
isThinking: Ref<boolean>;
|
||||
loadConversationState: (id: string, loaded: ChatMessage[]) => void;
|
||||
createNewChatView: () => void;
|
||||
clearPendingNoticeBatchRetry: () => void;
|
||||
onConversationIdChanging: (nextId: string, prevId: string | null | undefined) => void;
|
||||
onConversationLoadedEmpty: () => Promise<void>;
|
||||
onConversationLoadFailed: () => Promise<void>;
|
||||
isShippingNoticeAgent: ComputedRef<boolean>;
|
||||
shippingTaskIdFromQuery: ComputedRef<string>;
|
||||
shippingBatchNoFromQuery?: ComputedRef<string>;
|
||||
clearHistory: () => void;
|
||||
clearAttachments: () => void;
|
||||
input: Ref<string>;
|
||||
@@ -98,7 +96,7 @@ export function createChatPageConversationApi(ctx: ChatPageConversationContext)
|
||||
await ctx.onConversationLoadFailed();
|
||||
if (
|
||||
ctx.isShippingNoticeAgent.value
|
||||
&& (ctx.shippingTaskIdFromQuery.value || ctx.shippingBatchNoFromQuery?.value)
|
||||
&& ctx.shippingTaskIdFromQuery.value
|
||||
&& !ctx.isThinking.value
|
||||
) {
|
||||
return;
|
||||
@@ -108,7 +106,6 @@ export function createChatPageConversationApi(ctx: ChatPageConversationContext)
|
||||
};
|
||||
|
||||
const startNewChat = () => {
|
||||
ctx.clearPendingNoticeBatchRetry();
|
||||
ctx.createNewChatView();
|
||||
ctx.clearAttachments();
|
||||
ctx.input.value = '';
|
||||
@@ -122,7 +119,6 @@ export function createChatPageConversationApi(ctx: ChatPageConversationContext)
|
||||
};
|
||||
|
||||
const resetChatStateForAgentChange = () => {
|
||||
ctx.clearPendingNoticeBatchRetry();
|
||||
ctx.createNewChatView();
|
||||
ctx.clearHistory();
|
||||
ctx.clearAttachments();
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
/**
|
||||
* features/chat/page/useChatPageDialogs.ts
|
||||
* 用途:对话页删除确认、发货「重试所有失败」确认、反馈弹窗与轻量 toast 状态。
|
||||
* 用途:对话页删除确认、反馈弹窗与轻量 toast 状态。
|
||||
* 依赖:vue computed/ref、chat.types。
|
||||
* 逻辑:由 useChatPage 组装;ChatViewOverlays 绑定 DeleteConfirmDialog 与 toast 条。
|
||||
*/
|
||||
@@ -43,37 +43,6 @@ export function useChatPageDialogs(messages: Ref<ChatMessage[]>) {
|
||||
closeDeleteConfirmDialog();
|
||||
};
|
||||
|
||||
const showRetryFailedConfirmDialog = ref(false);
|
||||
let pendingRetryFailedAction: (() => Promise<void> | void) | null = null;
|
||||
|
||||
/**
|
||||
* 打开「重试所有失败」确认弹窗。
|
||||
* 核心逻辑:仅登记确认后要执行的动作,实际请求由调用方注入。
|
||||
* @param onConfirm - 用户点「确认重试」后执行的回调
|
||||
*/
|
||||
const openRetryFailedConfirm = (onConfirm: () => Promise<void> | void) => {
|
||||
pendingRetryFailedAction = onConfirm;
|
||||
showRetryFailedConfirmDialog.value = true;
|
||||
};
|
||||
|
||||
/** 关闭重试确认弹窗并清空待执行动作。 */
|
||||
const closeRetryFailedConfirm = () => {
|
||||
showRetryFailedConfirmDialog.value = false;
|
||||
pendingRetryFailedAction = null;
|
||||
};
|
||||
|
||||
/**
|
||||
* 用户确认后执行重试动作;弹窗由 DeleteConfirmDialog 自行关闭。
|
||||
* 核心逻辑:取出并清空 pending,再 await 执行,避免重复确认。
|
||||
*/
|
||||
const handleRetryFailedConfirm = async () => {
|
||||
const action = pendingRetryFailedAction;
|
||||
pendingRetryFailedAction = null;
|
||||
showRetryFailedConfirmDialog.value = false;
|
||||
if (!action) return;
|
||||
await action();
|
||||
};
|
||||
|
||||
const shippingToastMessage = ref('');
|
||||
let shippingToastTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
|
||||
@@ -85,7 +54,7 @@ export function useChatPageDialogs(messages: Ref<ChatMessage[]>) {
|
||||
};
|
||||
|
||||
/**
|
||||
* 展示非阻塞顶部 toast(用于发货批量重试等轻量成功反馈)。
|
||||
* 展示非阻塞顶部 toast。
|
||||
* @param message - toast 正文;空字符串视为关闭
|
||||
*/
|
||||
const showShippingToast = (message: string) => {
|
||||
@@ -143,10 +112,6 @@ export function useChatPageDialogs(messages: Ref<ChatMessage[]>) {
|
||||
openDeleteConfirmDialog,
|
||||
closeDeleteConfirmDialog,
|
||||
handleDeleteConfirm,
|
||||
showRetryFailedConfirmDialog,
|
||||
openRetryFailedConfirm,
|
||||
closeRetryFailedConfirm,
|
||||
handleRetryFailedConfirm,
|
||||
shippingToastMessage,
|
||||
showShippingToast,
|
||||
clearShippingToast,
|
||||
|
||||
@@ -38,6 +38,7 @@ function createContext(overrides: Partial<ChatPageSendContext> = {}): ChatPageSe
|
||||
refreshHistoryAfterSend: vi.fn(async () => undefined),
|
||||
refreshConversationAfterSend: vi.fn(async () => undefined),
|
||||
tryHandleShippingAttachmentAutoFlow: vi.fn(async () => false),
|
||||
tryHandleProcurementContractSend: vi.fn(async () => false),
|
||||
tryHandleLeaveSend: vi.fn(() => false),
|
||||
tryHandleShippingSend: vi.fn(async () => false),
|
||||
refreshToolRunProgressAfterSend: vi.fn(async () => undefined),
|
||||
|
||||
@@ -55,7 +55,7 @@ export interface ChatPageSendContext {
|
||||
agentId: number,
|
||||
kb: string,
|
||||
files: ChatUploadFileSpec[],
|
||||
context?: { task_id?: string; batch_no?: string; shipping_temporary_inventory_asset_no?: string; shipping_temporary_inventory_session_no?: string; display_query?: string },
|
||||
context?: { task_id?: string; shipping_temporary_inventory_asset_no?: string; shipping_temporary_inventory_session_no?: string; display_query?: string },
|
||||
hooks?: SendMessageLifecycleHooks,
|
||||
) => Promise<ChatMessageSendResult>;
|
||||
refreshHistoryAfterSend: () => Promise<void>;
|
||||
@@ -81,7 +81,7 @@ export interface ChatPageSendContext {
|
||||
msg: { warning: (text: string) => void; info: (text: string) => void };
|
||||
t: (key: string, values?: Record<string, unknown>) => string;
|
||||
copiedIndex: Ref<number | null>;
|
||||
getChatContext?: () => { task_id?: string; batch_no?: string; shipping_temporary_inventory_asset_no?: string; shipping_temporary_inventory_session_no?: string; display_query?: string };
|
||||
getChatContext?: () => { task_id?: string; shipping_temporary_inventory_asset_no?: string; shipping_temporary_inventory_session_no?: string; display_query?: string };
|
||||
onAssistantMessageFinished?: (message: ChatMessage, runMessages: ChatMessage[]) => void | Promise<void>;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
/**
|
||||
* features/chat/shipping-review/showReviewResumeOutcome.spec.ts
|
||||
* 用途:验证复核保存后的后端入队结果会被明确展示,避免用户误以为校验后没有推进。
|
||||
* 依赖:Vitest、showReviewResumeOutcome。
|
||||
* 逻辑:队列状态统一提示已入队;其他结果保持既有自动建单和兜底提示。
|
||||
*/
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { showReviewResumeOutcome } from './showReviewResumeOutcome';
|
||||
|
||||
const translate = (key: string, values?: Record<string, unknown>) => (
|
||||
values?.taskNo ? `${key}:${values.taskNo}` : key
|
||||
);
|
||||
|
||||
describe('showReviewResumeOutcome', () => {
|
||||
it.each(['auto_create_enqueued', 'already_queued', 'already_running'])(
|
||||
'shows the queued progression message for %s',
|
||||
(outcome) => {
|
||||
const success = vi.fn();
|
||||
showReviewResumeOutcome({ outcome }, { success }, translate);
|
||||
|
||||
// 关键断言:用户必须看到后端已接收自动建单,而非泛化的保存成功。
|
||||
expect(success).toHaveBeenCalledWith('chat.shippingOrderReview.resume.autoCreateEnqueued');
|
||||
},
|
||||
);
|
||||
|
||||
it('keeps the explicit auto-created message for synchronous creation', () => {
|
||||
const success = vi.fn();
|
||||
showReviewResumeOutcome({ outcome: 'auto_created', task_no: 'OT-1' }, { success }, translate);
|
||||
expect(success).toHaveBeenCalledWith('chat.shippingOrderReview.resume.autoCreated:OT-1');
|
||||
});
|
||||
|
||||
it.each(['waiting_manual_confirm', 'blocked'])('uses warning for non-success outcome %s', (outcome) => {
|
||||
const success = vi.fn();
|
||||
const warning = vi.fn();
|
||||
showReviewResumeOutcome({ outcome }, { success, warning }, translate, '保存成功');
|
||||
|
||||
// 关键断言:保存完成不等于自动建单完成,阻断状态不得显示绿色成功。
|
||||
expect(success).not.toHaveBeenCalled();
|
||||
expect(warning).toHaveBeenCalledWith(`chat.shippingOrderReview.resume.${outcome === 'blocked' ? 'blocked' : 'waitingManualConfirm'}`);
|
||||
});
|
||||
|
||||
it('uses fallback success only when backend has no resume outcome', () => {
|
||||
const success = vi.fn();
|
||||
const warning = vi.fn();
|
||||
showReviewResumeOutcome(null, { success, warning }, translate, '保存成功');
|
||||
expect(success).toHaveBeenCalledWith('保存成功');
|
||||
expect(warning).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -9,11 +9,14 @@ import type { ShippingOrderReviewResumeOutcome } from '../types/shipping.api.typ
|
||||
|
||||
type ToastApi = {
|
||||
success: (message: string) => void;
|
||||
warning: (message: string) => void;
|
||||
error?: (message: string) => void;
|
||||
};
|
||||
|
||||
/**
|
||||
* 按 resume_outcome 展示成功提示;无 outcome 时使用 fallbackSuccess。
|
||||
* 核心逻辑:auto_created/idempotent_replay → 自动建单;waiting_manual_confirm → 待人工确认。
|
||||
* 核心逻辑:auto_create_enqueued → 已入队等待 Worker;auto_created/idempotent_replay → 自动建单;
|
||||
* waiting_manual_confirm → 已提交但未满足自动建单门禁(兼容历史 outcome 名称)。
|
||||
* @param resume - 后端统一恢复协调结果
|
||||
* @param msg - useMessage 实例
|
||||
* @param t - vue-i18n translate
|
||||
@@ -27,6 +30,10 @@ export function showReviewResumeOutcome(
|
||||
fallbackSuccess?: string,
|
||||
): void {
|
||||
const outcome = String(resume?.outcome || '').trim();
|
||||
if (outcome === 'auto_create_enqueued' || outcome === 'already_queued' || outcome === 'already_running') {
|
||||
msg.success(t('chat.shippingOrderReview.resume.autoCreateEnqueued'));
|
||||
return;
|
||||
}
|
||||
if (outcome === 'auto_created' || outcome === 'idempotent_replay') {
|
||||
msg.success(t('chat.shippingOrderReview.resume.autoCreated', {
|
||||
taskNo: resume?.task_no || '',
|
||||
@@ -34,7 +41,15 @@ export function showReviewResumeOutcome(
|
||||
return;
|
||||
}
|
||||
if (outcome === 'waiting_manual_confirm') {
|
||||
msg.success(t('chat.shippingOrderReview.resume.waitingManualConfirm'));
|
||||
msg.warning(t('chat.shippingOrderReview.resume.waitingManualConfirm'));
|
||||
return;
|
||||
}
|
||||
if (outcome === 'blocked') {
|
||||
msg.warning(t('chat.shippingOrderReview.resume.blocked'));
|
||||
return;
|
||||
}
|
||||
if (outcome === 'auto_create_failed') {
|
||||
(msg.error || msg.warning)(t('chat.shippingOrderReview.resume.autoCreateFailed'));
|
||||
return;
|
||||
}
|
||||
if (fallbackSuccess) {
|
||||
|
||||
@@ -432,10 +432,11 @@ describe('useShippingOrderReview build eligibility writes', () => {
|
||||
resume_outcome: { outcome: 'auto_create_enqueued' },
|
||||
});
|
||||
|
||||
await review.validate();
|
||||
const resume = await review.validate();
|
||||
|
||||
expect(api.validateDraft).toHaveBeenCalledWith('CASE-1', 2);
|
||||
expect(review.activeCase.value?.draft?.draft_version).toBe(3);
|
||||
expect(resume).toEqual({ outcome: 'auto_create_enqueued' });
|
||||
});
|
||||
|
||||
it('refreshes the current Case silently without entering the PDF-switch loading state', async () => {
|
||||
@@ -669,6 +670,181 @@ describe('useShippingOrderReview build eligibility writes', () => {
|
||||
expect(review.activeCase.value?.case_no).toBe('CASE-B');
|
||||
});
|
||||
|
||||
it('aborts the previous Case snapshot request when the user immediately selects another PDF', async () => {
|
||||
let firstSignal: AbortSignal | undefined;
|
||||
let firstEvidenceSignal: AbortSignal | undefined;
|
||||
api.getCase.mockImplementation((caseNo: string, signal?: AbortSignal) => {
|
||||
if (caseNo !== 'CASE-A') return Promise.resolve(buildCase({ case_no: caseNo }));
|
||||
firstSignal = signal;
|
||||
return new Promise((_, reject) => {
|
||||
signal?.addEventListener('abort', () => reject(new DOMException('Aborted', 'AbortError')));
|
||||
});
|
||||
});
|
||||
api.getEvidence.mockImplementation((_caseNo: string, signal?: AbortSignal) => {
|
||||
if (!firstEvidenceSignal) firstEvidenceSignal = signal;
|
||||
return Promise.resolve({ items: [] });
|
||||
});
|
||||
|
||||
const review = useShippingOrderReview();
|
||||
const pendingA = review.selectCase('CASE-A');
|
||||
await review.selectCase('CASE-B');
|
||||
|
||||
// 关键断言:快速跳过 A 时必须释放其仍在途的快照读取,不能只在 UI 丢弃迟到结果。
|
||||
expect(firstSignal?.aborted).toBe(true);
|
||||
expect(firstEvidenceSignal?.aborted).toBe(true);
|
||||
await expect(pendingA).resolves.toBeUndefined();
|
||||
expect(review.activeCase.value?.case_no).toBe('CASE-B');
|
||||
});
|
||||
|
||||
it('keeps the latest Run and Case when an older load response arrives last', async () => {
|
||||
// 关键断言:重识别跳转新版本后,旧 Run 的迟到响应不得覆盖新版工作面。
|
||||
let resolveOldRun: ((value: Record<string, unknown>) => void) | null = null;
|
||||
api.getRun.mockImplementation((runNo: string) => (runNo === 'RUN-OLD'
|
||||
? new Promise<Record<string, unknown>>((resolve) => { resolveOldRun = resolve; })
|
||||
: Promise.resolve({
|
||||
run_no: runNo,
|
||||
summary: {},
|
||||
items: [{ case_no: 'CASE-NEW', document_id: 2, status: 'draft', issue_count: 0 }],
|
||||
})));
|
||||
api.getQueue.mockImplementation((runNo: string) => Promise.resolve({
|
||||
summary: { total: 1, needs_action: 1, processing: 0, completed: 0 },
|
||||
items: [{
|
||||
case_no: runNo === 'RUN-OLD' ? 'CASE-OLD' : 'CASE-NEW',
|
||||
document_id: runNo === 'RUN-OLD' ? 1 : 2,
|
||||
source_run_no: runNo,
|
||||
status: 'draft', issue_count: 0, available_actions: [],
|
||||
}],
|
||||
}));
|
||||
api.getCase.mockImplementation((caseNo: string) => Promise.resolve(buildCase({
|
||||
case_no: caseNo,
|
||||
run_no: caseNo === 'CASE-OLD' ? 'RUN-OLD' : 'RUN-NEW',
|
||||
document: {
|
||||
id: caseNo === 'CASE-OLD' ? 1 : 2,
|
||||
file_name: caseNo === 'CASE-OLD' ? 'old.pdf' : 'new.pdf',
|
||||
},
|
||||
})));
|
||||
api.getEvidence.mockResolvedValue({ items: [] });
|
||||
|
||||
const review = useShippingOrderReview();
|
||||
const olderLoad = review.load('RUN-OLD', 'CASE-OLD');
|
||||
await Promise.resolve();
|
||||
await review.load('RUN-NEW', 'CASE-NEW');
|
||||
|
||||
resolveOldRun?.({
|
||||
run_no: 'RUN-OLD',
|
||||
summary: {},
|
||||
items: [{ case_no: 'CASE-OLD', document_id: 1, status: 'superseded', issue_count: 0 }],
|
||||
});
|
||||
await olderLoad;
|
||||
|
||||
expect(review.reviewRun.value?.run_no).toBe('RUN-NEW');
|
||||
expect(review.activeCase.value?.case_no).toBe('CASE-NEW');
|
||||
});
|
||||
|
||||
it('marks only the first successful Run read as initial loading', async () => {
|
||||
// 关键断言:后续 Run 切换仍可有 Run 读取态,但不能再被页面当作首次整页加载。
|
||||
const review = useShippingOrderReview();
|
||||
await review.load('RUN-1', 'CASE-1');
|
||||
expect(review.initialLoading.value).toBe(false);
|
||||
|
||||
let resolveRun: ((value: Record<string, unknown>) => void) | null = null;
|
||||
api.getRun.mockImplementationOnce(() => new Promise<Record<string, unknown>>((resolve) => {
|
||||
resolveRun = resolve;
|
||||
}));
|
||||
const pending = review.load('RUN-2', 'CASE-2');
|
||||
expect(review.runLoading.value).toBe(true);
|
||||
expect(review.initialLoading.value).toBe(false);
|
||||
|
||||
resolveRun?.({
|
||||
run_no: 'RUN-2', summary: {},
|
||||
items: [{ case_no: 'CASE-2', document_id: 2, status: 'draft', issue_count: 0 }],
|
||||
});
|
||||
await pending;
|
||||
});
|
||||
|
||||
it('shows the cross-Run target Case when its snapshot arrives before slow navigation summaries', async () => {
|
||||
// 关键断言:目标 Case/Evidence 是当前 PDF 的事实源;慢 Run/Queue 仅延后导航校准,
|
||||
// 绝不能继续阻塞用户看到已完成读取的目标文件。
|
||||
const review = useShippingOrderReview();
|
||||
await review.load('RUN-1', 'CASE-1');
|
||||
const previousQueue = review.reviewQueue.value;
|
||||
|
||||
let resolveRun: ((value: Record<string, unknown>) => void) | null = null;
|
||||
let resolveQueue: ((value: Record<string, unknown>) => void) | null = null;
|
||||
let resolveCase: ((value: ShippingOrderReviewCase) => void) | null = null;
|
||||
let resolveEvidence: ((value: { items: unknown[] }) => void) | null = null;
|
||||
api.getRun.mockImplementationOnce(() => new Promise<Record<string, unknown>>((resolve) => { resolveRun = resolve; }));
|
||||
api.getQueue.mockImplementationOnce(() => new Promise<Record<string, unknown>>((resolve) => { resolveQueue = resolve; }));
|
||||
api.getCase.mockImplementationOnce(() => new Promise<ShippingOrderReviewCase>((resolve) => { resolveCase = resolve; }));
|
||||
api.getEvidence.mockImplementationOnce(() => new Promise<{ items: unknown[] }>((resolve) => { resolveEvidence = resolve; }));
|
||||
|
||||
const pending = review.load('RUN-2', 'CASE-2');
|
||||
expect(review.reviewRun.value?.run_no).toBe('RUN-1');
|
||||
expect(review.reviewQueue.value).toBe(previousQueue);
|
||||
expect(review.activeCase.value?.case_no).toBe('CASE-1');
|
||||
|
||||
await vi.waitFor(() => expect(resolveRun).toBeTypeOf('function'));
|
||||
await vi.waitFor(() => expect(resolveQueue).toBeTypeOf('function'));
|
||||
await vi.waitFor(() => expect(resolveCase).toBeTypeOf('function'));
|
||||
expect(review.reviewRun.value?.run_no).toBe('RUN-1');
|
||||
expect(review.activeCase.value?.case_no).toBe('CASE-1');
|
||||
|
||||
resolveCase?.(buildCase({ case_no: 'CASE-2', run_no: 'RUN-2', document: { id: 2, file_name: 'second.pdf' } }));
|
||||
await vi.waitFor(() => expect(resolveEvidence).toBeTypeOf('function'));
|
||||
resolveEvidence?.({ items: [] });
|
||||
await vi.waitFor(() => expect(review.activeCase.value?.case_no).toBe('CASE-2'));
|
||||
expect(review.reviewRun.value?.run_no).toBe('RUN-1');
|
||||
expect(review.reviewQueue.value).toBe(previousQueue);
|
||||
|
||||
resolveRun?.({ run_no: 'RUN-2', summary: {}, items: [{ case_no: 'CASE-2', document_id: 2, status: 'draft', issue_count: 0 }] });
|
||||
resolveQueue?.({ summary: { total: 1, needs_action: 1, processing: 0, completed: 0 }, items: [{ case_no: 'CASE-2', document_id: 2, source_run_no: 'RUN-2', status: 'draft', issue_count: 0, available_actions: [] }] });
|
||||
await pending;
|
||||
expect(review.reviewRun.value?.run_no).toBe('RUN-2');
|
||||
expect(review.reviewQueue.value?.items[0]?.case_no).toBe('CASE-2');
|
||||
expect(review.activeCase.value?.case_no).toBe('CASE-2');
|
||||
});
|
||||
|
||||
it('starts the preferred Case and Evidence reads without waiting for a slow cross-Run summary', async () => {
|
||||
// 关键断言:导航已提供目标 Case 时,Run/Queue 摘要不能把详情读取串行化。
|
||||
const review = useShippingOrderReview();
|
||||
await review.load('RUN-1', 'CASE-1');
|
||||
|
||||
let resolveRun: ((value: Record<string, unknown>) => void) | null = null;
|
||||
let resolveQueue: ((value: Record<string, unknown>) => void) | null = null;
|
||||
api.getCase.mockClear();
|
||||
api.getEvidence.mockClear();
|
||||
api.getRun.mockImplementationOnce(() => new Promise<Record<string, unknown>>((resolve) => { resolveRun = resolve; }));
|
||||
api.getQueue.mockImplementationOnce(() => new Promise<Record<string, unknown>>((resolve) => { resolveQueue = resolve; }));
|
||||
|
||||
const pending = review.load('RUN-2', 'CASE-2');
|
||||
await vi.waitFor(() => expect(api.getCase).toHaveBeenCalledWith('CASE-2'));
|
||||
await vi.waitFor(() => expect(api.getEvidence).toHaveBeenCalledWith('CASE-2'));
|
||||
|
||||
await vi.waitFor(() => expect(review.runLoading.value).toBe(true));
|
||||
expect(review.activeCase.value?.case_no).toBe('CASE-1');
|
||||
resolveRun?.({ run_no: 'RUN-2', summary: {}, items: [{ case_no: 'CASE-2', document_id: 2, status: 'draft', issue_count: 0 }] });
|
||||
resolveQueue?.({ summary: { total: 1, needs_action: 1, processing: 0, completed: 0 }, items: [{ case_no: 'CASE-2', document_id: 2, source_run_no: 'RUN-2', status: 'draft', issue_count: 0, available_actions: [] }] });
|
||||
await pending;
|
||||
});
|
||||
|
||||
it('keeps the stable workbench on a cross-Run load failure', async () => {
|
||||
// 关键断言:目标 Run 读取失败时,用户可继续查看上一份稳定工作面,不能退回整页空白。
|
||||
const review = useShippingOrderReview();
|
||||
await review.load('RUN-1', 'CASE-1');
|
||||
api.getCase.mockResolvedValueOnce(buildCase({ case_no: 'CASE-2', run_no: 'RUN-2' }));
|
||||
api.getEvidence.mockResolvedValueOnce({ items: [] });
|
||||
api.getRun.mockImplementationOnce(() => Promise.reject(new Error('target unavailable')));
|
||||
api.getQueue.mockImplementationOnce(() => Promise.reject(new Error('target unavailable')));
|
||||
|
||||
await review.load('RUN-2', 'CASE-2');
|
||||
|
||||
expect(review.loadFailed.value).toBe(false);
|
||||
expect(review.runSwitchFailed.value).toBe(true);
|
||||
expect(review.reviewRun.value?.run_no).toBe('RUN-1');
|
||||
expect(review.reviewQueue.value?.items[0]?.case_no).toBe('CASE-1');
|
||||
expect(review.activeCase.value?.case_no).toBe('CASE-1');
|
||||
});
|
||||
|
||||
it('blocks confirm when build eligibility cannot build', async () => {
|
||||
|
||||
const review = useShippingOrderReview();
|
||||
@@ -756,6 +932,57 @@ describe('useShippingOrderReview build eligibility writes', () => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it('refreshes the active Case and queue while post-confirm automation is still active', async () => {
|
||||
vi.useFakeTimers();
|
||||
const readyCase = buildCase({
|
||||
status: 'ready',
|
||||
draft: {
|
||||
...buildCase().draft!,
|
||||
build_eligibility: { can_build: true, status: 'ready', line_projections: [] },
|
||||
},
|
||||
});
|
||||
const runningCase = {
|
||||
...readyCase,
|
||||
status: 'confirmed',
|
||||
confirmed_task_no: 'OT-1',
|
||||
automation: { status: 'running', phase: 'post_ot_progress' },
|
||||
};
|
||||
api.getCase
|
||||
.mockResolvedValueOnce(readyCase)
|
||||
.mockResolvedValue(runningCase);
|
||||
api.getRun.mockResolvedValue({
|
||||
run_no: 'RUN-1', summary: {},
|
||||
items: [{ case_no: 'CASE-1', document_id: 1, status: 'confirmed', lifecycle_stage: 'fulfillment_prep', lifecycle_entries: [] }],
|
||||
});
|
||||
api.getQueue.mockResolvedValue({
|
||||
summary: { total: 1, needs_action: 0, processing: 1, completed: 0 },
|
||||
items: [{ case_no: 'CASE-1', document_id: 1, source_run_no: 'RUN-1', status: 'confirmed', lifecycle_stage: 'fulfillment_prep', lifecycle_entries: [] }],
|
||||
});
|
||||
api.getEvidence.mockResolvedValue({ items: [] });
|
||||
api.getProcessingWorkItem.mockResolvedValue({
|
||||
work_item_no: 'OT-1', status: 'processing', stage: 'inventory_preparation',
|
||||
currentGate: { gateCode: 'inventory_preparation', status: 'running' },
|
||||
});
|
||||
api.confirmCase.mockResolvedValue({
|
||||
task_no: 'SN-1', order_task_no: 'OT-1', shipping_notice_no: 'SN-1', idempotent_replay: false,
|
||||
case: runningCase, auto_progress_started: true,
|
||||
});
|
||||
|
||||
const review = useShippingOrderReview();
|
||||
await review.load('RUN-1', 'CASE-1', { conversationId: 'conv-1', itemNo: 'WFI-1' });
|
||||
await review.confirm();
|
||||
await vi.advanceTimersByTimeAsync(2600);
|
||||
|
||||
// 关键断言:活动窗口内同步刷新 Case 与队列,让顶部五阶段读取到后端已推进的通知准备。
|
||||
expect(api.getCase.mock.calls.length).toBeGreaterThanOrEqual(2);
|
||||
expect(api.getQueue.mock.calls.length).toBeGreaterThanOrEqual(2);
|
||||
expect(review.activeCase.value?.confirmed_task_no).toBe('OT-1');
|
||||
expect(review.reviewQueue.value?.items[0]?.lifecycle_stage).toBe('fulfillment_prep');
|
||||
|
||||
review.stopWorkflowProgressPolling();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it('keeps polling after a recoverable RPA failure so a later callback can refresh the workflow', async () => {
|
||||
vi.useFakeTimers();
|
||||
const onWorkflowRefresh = vi.fn();
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
* 用途:订单复核工作台 composable,编排 Run/Case/PDF、草稿写入与建单确认。
|
||||
* 依赖:shipping API review/extraction-run、useShippingProcessingWorkItem、Vue ref/computed、BusinessError。
|
||||
* 逻辑:按 runNo 加载 Review Run/Case;合成 ShippingReviewProgressContext;
|
||||
* OT 绑定 Case.order_task_no / Candidate;切换 Case 时清空 activeCase(纯 skeleton,禁止旧值 DOM);
|
||||
* OT 绑定 Case.order_task_no / Candidate;切换时保留稳定显示壳,目标快照到齐后原子替换;
|
||||
* 409 REVIEW_DRAFT_VERSION_MISMATCH 冲突处理;build_eligibility 驱动 confirm/reroute;
|
||||
* 重识别后刷新正式 Run/Case/Gate 投影;PDF Blob 由 ensurePreviewLoaded 按需加载。
|
||||
*/
|
||||
@@ -47,6 +47,7 @@ import type {
|
||||
ShippingOrderReviewLlmAdjudicationPayload,
|
||||
ShippingOrderReviewLlmSuggestion,
|
||||
ShippingOrderExtractionRun,
|
||||
ShippingOrderExtractionLifecycleProgress,
|
||||
ShippingOrderReviewRun,
|
||||
ShippingOrderReviewQueue,
|
||||
ShippingOrderReviewEmailEvidencePreview,
|
||||
@@ -60,7 +61,6 @@ import { useShippingProcessingWorkItem } from '../shipping/useShippingProcessing
|
||||
export type ReviewStatusMessage =
|
||||
| 'superseded'
|
||||
| 'work_item_closed'
|
||||
| 'reparse_in_progress'
|
||||
| 'restored'
|
||||
| 'draft_version_conflict'
|
||||
| null;
|
||||
@@ -304,6 +304,8 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
|
||||
const caseProjectionVersion = ref<number | null>(null);
|
||||
const caseLoadingContext = ref<ShippingOrderReviewCaseLoadingContext | null>(null);
|
||||
const reviewProgressContext = ref<ShippingReviewProgressContext | null>(null);
|
||||
/** 当前 Run 的用户态五阶段进度;页面 loading 或尚无 Case 时仍可展示。 */
|
||||
const extractionLifecycleProgress = ref<ShippingOrderExtractionLifecycleProgress | null>(null);
|
||||
/** ?? OT ???????????????? */
|
||||
const authoritativeOrderTaskNo = computed(() => {
|
||||
const item = reviewProgressContext.value;
|
||||
@@ -324,11 +326,19 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
|
||||
enabled: computed(() => Boolean(authoritativeOrderTaskNo.value)),
|
||||
// 订单处理工作台:旧 progress_version 不得覆盖较新本地投影。
|
||||
monotonicProgressVersion: true,
|
||||
// 复核页仅由下方 2.5 秒协调轮询驱动,避免此处额外开启 3 秒定时读取。
|
||||
continuousPolling: false,
|
||||
},
|
||||
);
|
||||
const versions = ref<ShippingReviewProgressVersion[]>([]);
|
||||
const statusMessage = ref<ReviewStatusMessage>(null);
|
||||
const loading = ref(false);
|
||||
/** 首次进入工作台的页面级加载态;后续 Run 切换不得重新触发整页 loading。 */
|
||||
const initialLoading = ref(false);
|
||||
/** Run 数据读取态;供跨 Run 切换保持既有工作台壳时使用。 */
|
||||
const runLoading = ref(false);
|
||||
/** 跨 Run 读取失败;有稳定工作台时只显示局部错误,不触发页面失败态。 */
|
||||
const runSwitchFailed = ref(false);
|
||||
let initialLoadCompleted = false;
|
||||
const loadFailed = ref(false);
|
||||
const saving = ref(false);
|
||||
const saveFailed = ref(false);
|
||||
@@ -369,6 +379,8 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
|
||||
let previewInflight: { caseNo: string; promise: Promise<boolean> } | null = null;
|
||||
/** Case 切换请求代次:快速切换时丢弃过期响应,禁止旧 Case 覆盖新 Case。 */
|
||||
let caseLoadGeneration = 0;
|
||||
/** 当前 Case 快照与证据的联合读取;新选择立即取消旧读取,减少无效后端投影。 */
|
||||
let caseSwitchAbortController: AbortController | null = null;
|
||||
/** 当前正在请求或已选定的 Case 编号(与 generation 双校验)。 */
|
||||
const requestedCaseNo = ref<string | null>(null);
|
||||
/** 同 Run 内切换 PDF/Case 的轻量加载态(不触发整页 loading)。 */
|
||||
@@ -425,6 +437,7 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
|
||||
const tick = async () => {
|
||||
try {
|
||||
const run = await getWorkspaceShippingOrderExtractionRun(targetRunNo);
|
||||
extractionLifecycleProgress.value = run.lifecycle_progress || null;
|
||||
const normalizedStatus = String(run.status || '').trim();
|
||||
const synthesized = synthesizeWorkItemFromReviewContext({
|
||||
reviewRun: reviewRun.value,
|
||||
@@ -467,6 +480,26 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 自动推进期间同步当前 Case 与生命周期队列。
|
||||
*
|
||||
* 核心逻辑:仅复用既有只读 API,且只在当前 Case 未切换时写回;不读证据/PDF,
|
||||
* 不触发任何 RPA 或 Gate 写操作。正式 OT 的细粒度状态仍由 processing projection 负责。
|
||||
*/
|
||||
const refreshActiveAutomationLifecycle = async () => {
|
||||
const caseNo = String(activeCase.value?.case_no || '').trim();
|
||||
const runNo = String(reviewRun.value?.run_no || activeCase.value?.run_no || '').trim();
|
||||
if (!caseNo || !runNo) return;
|
||||
const [caseSnapshot, queue] = await Promise.all([
|
||||
getWorkspaceShippingOrderReviewCase(caseNo),
|
||||
getWorkspaceShippingOrderReviewQueue(runNo),
|
||||
]);
|
||||
// Case 切换或重新加载后,旧轮询响应不得覆盖当前工作台。
|
||||
if (String(activeCase.value?.case_no || '').trim() !== caseNo) return;
|
||||
applyCaseSnapshot(caseSnapshot);
|
||||
reviewQueue.value = queue;
|
||||
};
|
||||
|
||||
/**
|
||||
* ?????????????????
|
||||
* ???????? OT ?????? ShippingProcessing????? Extraction Run
|
||||
@@ -484,6 +517,7 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
|
||||
// RPA 超时、可重试失败和人工复核都可能被后续回调推进,页面留存期间持续读取 Projection。
|
||||
const UNIFIED_TERMINAL = new Set(['completed', 'cancelled']);
|
||||
let lastUnifiedStatus = '';
|
||||
let lastLifecycleFingerprint = '';
|
||||
const RUN_TERMINAL = new Set(['completed', 'partially_completed', 'failed', 'cancelled']);
|
||||
const tick = async () => {
|
||||
try {
|
||||
@@ -500,11 +534,25 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
|
||||
}
|
||||
if (UNIFIED_TERMINAL.has(unifiedStatus)) {
|
||||
stopWorkflowProgressPolling();
|
||||
return;
|
||||
}
|
||||
// 顶部五阶段取 Case/Queue 的 lifecycle_entries。仅当 OT 投影的阶段/门禁发生变化
|
||||
// 时刷新一次,避免每 2.5 秒重复读取队列;不等待该读取,保证终态轮询及时停止。
|
||||
const lifecycleFingerprint = [
|
||||
unifiedStatus,
|
||||
String(shippingProcessingProjection.value?.stage || ''),
|
||||
String(shippingProcessingProjection.value?.currentGate?.gateCode || ''),
|
||||
String(shippingProcessingProjection.value?.currentGate?.status || ''),
|
||||
].join('|');
|
||||
if (lifecycleFingerprint !== lastLifecycleFingerprint) {
|
||||
lastLifecycleFingerprint = lifecycleFingerprint;
|
||||
void refreshActiveAutomationLifecycle();
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (targetRunNo) {
|
||||
const run = await getWorkspaceShippingOrderExtractionRun(targetRunNo);
|
||||
extractionLifecycleProgress.value = run.lifecycle_progress || null;
|
||||
const synthesized = synthesizeWorkItemFromReviewContext({
|
||||
reviewRun: reviewRun.value,
|
||||
activeCase: activeCase.value,
|
||||
@@ -529,6 +577,7 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
|
||||
// ???? setup ?????????? composable ?????? Vue warn?
|
||||
if (getCurrentInstance()) {
|
||||
onBeforeUnmount(() => {
|
||||
caseSwitchAbortController?.abort();
|
||||
stopWorkflowProgressPolling();
|
||||
stopReparseCaseRefreshPolling();
|
||||
stopShippingProcessing();
|
||||
@@ -591,14 +640,6 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
|
||||
}
|
||||
// ?????? Case ?????? superseded????????????
|
||||
// ?????????????????????????????
|
||||
if (
|
||||
activeCase.value?.status === 'reparse_pending'
|
||||
|| reviewProgressContext.value?.lifecycle_status === 'extracting'
|
||||
|| reviewProgressContext.value?.lifecycle_status === 'layout_parsing'
|
||||
) {
|
||||
statusMessage.value = 'reparse_in_progress';
|
||||
return;
|
||||
}
|
||||
if (isViewingHistoricalVersion.value || activeCase.value?.status === 'superseded') {
|
||||
statusMessage.value = 'superseded';
|
||||
return;
|
||||
@@ -654,21 +695,34 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
|
||||
/**
|
||||
* ???? WorkItem ???????????????????
|
||||
*/
|
||||
const refreshWorkItemContext = async (conversationId?: string, itemNo?: string) => {
|
||||
const refreshWorkItemContext = async (
|
||||
conversationId?: string,
|
||||
itemNo?: string,
|
||||
options?: { expectedLoadGeneration?: number },
|
||||
) => {
|
||||
const isExpectedLoad = () => (
|
||||
options?.expectedLoadGeneration == null
|
||||
|| options.expectedLoadGeneration === caseLoadGeneration
|
||||
);
|
||||
const conversation = String(conversationId || contextConversationId || '').trim();
|
||||
if (conversation) contextConversationId = conversation;
|
||||
if (itemNo) contextItemNo = itemNo;
|
||||
if (!isExpectedLoad()) return;
|
||||
versionsLoading.value = true;
|
||||
try {
|
||||
reviewProgressContext.value = await resolveWorkItem(conversation, {
|
||||
const context = await resolveWorkItem(conversation, {
|
||||
itemNo: contextItemNo || undefined,
|
||||
caseNo: activeCase.value?.case_no,
|
||||
});
|
||||
if (!isExpectedLoad()) return;
|
||||
reviewProgressContext.value = context;
|
||||
versions.value = [];
|
||||
} catch {
|
||||
if (!isExpectedLoad()) return;
|
||||
reviewProgressContext.value = null;
|
||||
versions.value = [];
|
||||
} finally {
|
||||
if (!isExpectedLoad()) return;
|
||||
versionsLoading.value = false;
|
||||
refreshStatusMessage();
|
||||
}
|
||||
@@ -848,53 +902,139 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
|
||||
preferredCaseNo?: string,
|
||||
options?: { conversationId?: string; itemNo?: string; restoreProgress?: boolean },
|
||||
) => {
|
||||
++caseLoadGeneration;
|
||||
caseSwitchAbortController?.abort();
|
||||
caseSwitchAbortController = null;
|
||||
const generation = ++caseLoadGeneration;
|
||||
++intakeParseRequestGeneration;
|
||||
loading.value = true;
|
||||
requestedCaseNo.value = String(preferredCaseNo || '').trim() || null;
|
||||
const isInitialLoad = !initialLoadCompleted && !reviewRun.value;
|
||||
if (isInitialLoad) initialLoading.value = true;
|
||||
runLoading.value = true;
|
||||
runSwitchFailed.value = false;
|
||||
loadFailed.value = false;
|
||||
draftConflict.value = null;
|
||||
saveFailed.value = false;
|
||||
// [STEP 1] ?????????????????????? WorkflowItem ????? Run ???
|
||||
contextConversationId = String(options?.conversationId || '').trim();
|
||||
contextItemNo = String(options?.itemNo || '').trim();
|
||||
reviewRun.value = null;
|
||||
activeCase.value = null;
|
||||
caseProjectionVersion.value = null;
|
||||
caseLoadingContext.value = null;
|
||||
reviewProgressContext.value = null;
|
||||
versions.value = [];
|
||||
evidence.value = [];
|
||||
llmSuggestions.value = [];
|
||||
intakeParseContext.value = null;
|
||||
intakeParseLoading.value = false;
|
||||
intakeParseLoadFailed.value = false;
|
||||
clearPreview();
|
||||
try {
|
||||
const [run, queue] = await Promise.all([
|
||||
getWorkspaceShippingOrderReviewRun(runNo),
|
||||
getWorkspaceShippingOrderReviewQueue(runNo),
|
||||
]);
|
||||
reviewRun.value = run;
|
||||
reviewQueue.value = queue;
|
||||
// [STREAM] Run 替代不等于其内全部 PDF 替代;当前文件只由队列 Stream 裁决。
|
||||
const caseNo = preferredCaseNo || queue.items[0]?.case_no || run.items[0]?.case_no;
|
||||
const caseSnapshot = caseNo ? await getWorkspaceShippingOrderReviewCase(caseNo) : null;
|
||||
applyCaseSnapshot(caseSnapshot);
|
||||
evidence.value = caseNo ? (await getWorkspaceShippingOrderReviewEvidence(caseNo)).items : [];
|
||||
// [STEP] ??????? PDF??????????????????????
|
||||
clearPreview();
|
||||
await refreshWorkItemContext(contextConversationId, contextItemNo);
|
||||
// refreshWorkItemContext ????? ref???????? ref????? load ???????????
|
||||
} catch {
|
||||
loadFailed.value = true;
|
||||
const hasStableWorkbench = Boolean(reviewRun.value && activeCase.value);
|
||||
const stableSnapshot = hasStableWorkbench
|
||||
? {
|
||||
reviewRun: reviewRun.value,
|
||||
reviewQueue: reviewQueue.value,
|
||||
activeCase: activeCase.value,
|
||||
caseProjectionVersion: caseProjectionVersion.value,
|
||||
caseLoadingContext: caseLoadingContext.value,
|
||||
evidence: evidence.value,
|
||||
llmSuggestions: llmSuggestions.value,
|
||||
extractionLifecycleProgress: extractionLifecycleProgress.value,
|
||||
}
|
||||
: null;
|
||||
if (!hasStableWorkbench) {
|
||||
reviewRun.value = null;
|
||||
activeCase.value = null;
|
||||
caseProjectionVersion.value = null;
|
||||
caseLoadingContext.value = null;
|
||||
reviewProgressContext.value = null;
|
||||
reviewQueue.value = null;
|
||||
extractionLifecycleProgress.value = null;
|
||||
versions.value = [];
|
||||
statusMessage.value = null;
|
||||
evidence.value = [];
|
||||
llmSuggestions.value = [];
|
||||
intakeParseContext.value = null;
|
||||
intakeParseLoading.value = false;
|
||||
intakeParseLoadFailed.value = false;
|
||||
clearPreview();
|
||||
}
|
||||
try {
|
||||
const runRequest = getWorkspaceShippingOrderReviewRun(runNo);
|
||||
const queueRequest = getWorkspaceShippingOrderReviewQueue(runNo);
|
||||
// 路由已明确目标 Case 时,详情读取不应等待较慢的 Run/Queue 摘要;
|
||||
// 四份数据仍在全部成功后原子提交,避免混合工作面。
|
||||
const preferredCaseRequest = preferredCaseNo
|
||||
? Promise.all([
|
||||
getWorkspaceShippingOrderReviewCase(preferredCaseNo),
|
||||
getWorkspaceShippingOrderReviewEvidence(preferredCaseNo),
|
||||
])
|
||||
: null;
|
||||
// 已有稳定工作台且路由明确目标 PDF 时,目标详情是用户切换的关键路径;
|
||||
// Run/Queue 只负责后续更新导航和阶段摘要,不能用其慢投影阻塞当前文件显示。
|
||||
if (hasStableWorkbench && preferredCaseRequest) {
|
||||
const [caseSnapshot, caseEvidence] = await preferredCaseRequest;
|
||||
if (generation !== caseLoadGeneration) return;
|
||||
applyCaseSnapshot(caseSnapshot);
|
||||
evidence.value = caseEvidence?.items || [];
|
||||
clearPreview();
|
||||
|
||||
const [run, queue] = await Promise.all([runRequest, queueRequest]);
|
||||
if (generation !== caseLoadGeneration) return;
|
||||
reviewRun.value = run;
|
||||
reviewQueue.value = queue;
|
||||
extractionLifecycleProgress.value = run.lifecycle_progress || null;
|
||||
await refreshWorkItemContext(contextConversationId, contextItemNo, {
|
||||
expectedLoadGeneration: generation,
|
||||
});
|
||||
initialLoadCompleted = true;
|
||||
return;
|
||||
}
|
||||
|
||||
const [run, queue, preferredSnapshot] = await Promise.all([
|
||||
runRequest,
|
||||
queueRequest,
|
||||
preferredCaseRequest,
|
||||
]);
|
||||
if (generation !== caseLoadGeneration) return;
|
||||
// [STREAM] Run 替代不等于其内全部 PDF 替代;当前文件只由队列 Stream 裁决。
|
||||
const caseNo = preferredCaseNo || queue.items[0]?.case_no || run.items[0]?.case_no;
|
||||
const [caseSnapshot, caseEvidence] = preferredSnapshot
|
||||
? preferredSnapshot
|
||||
: caseNo
|
||||
? await Promise.all([
|
||||
getWorkspaceShippingOrderReviewCase(caseNo),
|
||||
getWorkspaceShippingOrderReviewEvidence(caseNo),
|
||||
])
|
||||
: [null, null];
|
||||
if (generation !== caseLoadGeneration) return;
|
||||
reviewRun.value = run;
|
||||
reviewQueue.value = queue;
|
||||
extractionLifecycleProgress.value = run.lifecycle_progress || null;
|
||||
applyCaseSnapshot(caseSnapshot);
|
||||
evidence.value = caseEvidence?.items || [];
|
||||
// [STEP] ??????? PDF??????????????????????
|
||||
clearPreview();
|
||||
await refreshWorkItemContext(contextConversationId, contextItemNo, {
|
||||
expectedLoadGeneration: generation,
|
||||
});
|
||||
initialLoadCompleted = true;
|
||||
// refreshWorkItemContext ????? ref???????? ref????? load ???????????
|
||||
} catch {
|
||||
if (generation !== caseLoadGeneration) return;
|
||||
loadFailed.value = !hasStableWorkbench;
|
||||
runSwitchFailed.value = hasStableWorkbench;
|
||||
// 目标 Case 已先行显示时,若其所属 Run/Queue 校准失败,必须整体回退到同一份
|
||||
// 稳定快照,不能留下“新文件 + 旧导航”的混合业务工作面。
|
||||
if (stableSnapshot) {
|
||||
reviewRun.value = stableSnapshot.reviewRun;
|
||||
reviewQueue.value = stableSnapshot.reviewQueue;
|
||||
activeCase.value = stableSnapshot.activeCase;
|
||||
caseProjectionVersion.value = stableSnapshot.caseProjectionVersion;
|
||||
caseLoadingContext.value = stableSnapshot.caseLoadingContext;
|
||||
evidence.value = stableSnapshot.evidence;
|
||||
llmSuggestions.value = stableSnapshot.llmSuggestions;
|
||||
extractionLifecycleProgress.value = stableSnapshot.extractionLifecycleProgress;
|
||||
}
|
||||
if (!hasStableWorkbench) {
|
||||
reviewRun.value = null;
|
||||
activeCase.value = null;
|
||||
reviewProgressContext.value = null;
|
||||
extractionLifecycleProgress.value = null;
|
||||
reviewQueue.value = null;
|
||||
versions.value = [];
|
||||
statusMessage.value = null;
|
||||
}
|
||||
} finally {
|
||||
loading.value = false;
|
||||
if (generation !== caseLoadGeneration) return;
|
||||
if (isInitialLoad) initialLoading.value = false;
|
||||
runLoading.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
@@ -932,6 +1072,9 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
|
||||
const selectCase = async (caseNo: string) => {
|
||||
const target = String(caseNo || '').trim();
|
||||
if (!target) return;
|
||||
caseSwitchAbortController?.abort();
|
||||
const controller = new AbortController();
|
||||
caseSwitchAbortController = controller;
|
||||
const generation = ++caseLoadGeneration;
|
||||
++intakeParseRequestGeneration;
|
||||
requestedCaseNo.value = target;
|
||||
@@ -944,8 +1087,8 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
|
||||
intakeParseLoadFailed.value = false;
|
||||
try {
|
||||
const [detail, result] = await Promise.all([
|
||||
getWorkspaceShippingOrderReviewCase(target),
|
||||
getWorkspaceShippingOrderReviewEvidence(target),
|
||||
getWorkspaceShippingOrderReviewCase(target, controller.signal),
|
||||
getWorkspaceShippingOrderReviewEvidence(target, controller.signal),
|
||||
]);
|
||||
// [STEP 2] 代次与目标 Case 双校验;过期响应一律丢弃。
|
||||
if (generation !== caseLoadGeneration) return;
|
||||
@@ -970,6 +1113,7 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
|
||||
// [STEP 3] 失败保留上一份稳定快照,用户仍可继续查看/编辑,不回退成空白工作台。
|
||||
caseSwitchFailed.value = true;
|
||||
} finally {
|
||||
if (caseSwitchAbortController === controller) caseSwitchAbortController = null;
|
||||
if (generation === caseLoadGeneration) {
|
||||
caseSwitchLoading.value = false;
|
||||
}
|
||||
@@ -1195,9 +1339,9 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
|
||||
if (!activeCase.value) return;
|
||||
validationInProgress.value = true;
|
||||
try {
|
||||
await save(async () => (
|
||||
await validateWorkspaceShippingOrderReviewDraft(activeCase.value!.case_no, version())
|
||||
).case);
|
||||
const response = await validateWorkspaceShippingOrderReviewDraft(activeCase.value.case_no, version());
|
||||
await save(async () => response.case);
|
||||
return response.resume_outcome;
|
||||
} finally {
|
||||
validationInProgress.value = false;
|
||||
}
|
||||
@@ -1238,7 +1382,10 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
|
||||
caseProjectionVersion.value = Date.now();
|
||||
caseLoadingContext.value = null;
|
||||
draftConflict.value = null;
|
||||
if (reviewRun.value) reviewRun.value = await getWorkspaceShippingOrderReviewRun(reviewRun.value.run_no);
|
||||
if (reviewRun.value) {
|
||||
reviewRun.value = await getWorkspaceShippingOrderReviewRun(reviewRun.value.run_no);
|
||||
extractionLifecycleProgress.value = reviewRun.value.lifecycle_progress || null;
|
||||
}
|
||||
await refreshWorkItemContext();
|
||||
// [UI-02] ?????? OT???? Notice task_no / ??? workflow_item_id ??????
|
||||
const orderTaskNo = String(
|
||||
@@ -1300,7 +1447,10 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
|
||||
try {
|
||||
const response = await reparseWorkspaceShippingOrderReviewDocument(activeCase.value.case_no, reason, comment);
|
||||
applyCaseSnapshot(await getWorkspaceShippingOrderReviewCase(activeCase.value.case_no));
|
||||
if (reviewRun.value) reviewRun.value = await getWorkspaceShippingOrderReviewRun(reviewRun.value.run_no);
|
||||
if (reviewRun.value) {
|
||||
reviewRun.value = await getWorkspaceShippingOrderReviewRun(reviewRun.value.run_no);
|
||||
extractionLifecycleProgress.value = reviewRun.value.lifecycle_progress || null;
|
||||
}
|
||||
await refreshWorkItemContext();
|
||||
startReparseCaseRefreshPolling(response.run.run_no);
|
||||
return response;
|
||||
@@ -1427,6 +1577,7 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
|
||||
caseProjectionVersion,
|
||||
caseLoadingContext,
|
||||
reviewProgressContext,
|
||||
extractionLifecycleProgress,
|
||||
shippingProcessingProjection,
|
||||
authoritativeOrderTaskNo,
|
||||
shippingProcessingLoading,
|
||||
@@ -1466,7 +1617,9 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
|
||||
clearPreview,
|
||||
showWorkflowProgress,
|
||||
workflowProgressPolling,
|
||||
loading,
|
||||
initialLoading,
|
||||
runLoading,
|
||||
runSwitchFailed,
|
||||
loadFailed,
|
||||
caseSwitchLoading,
|
||||
caseSwitchFailed,
|
||||
|
||||
@@ -49,7 +49,7 @@ export function getPrimaryDocumentName(
|
||||
|
||||
/**
|
||||
* 汇总正式 OT 任务文件数(不含 order_intake)。
|
||||
* 核心逻辑:优先 summary.total_files;缺失时对 needs_action+processing+completed 的 file_count 求和。
|
||||
* 核心逻辑:优先 summary.total_files;缺失时仅对 status_groups 的活动状态求和。
|
||||
* @param projection - 会话 processing 投影
|
||||
*/
|
||||
export function resolveFormalTaskFileCount(
|
||||
@@ -60,10 +60,12 @@ export function resolveFormalTaskFileCount(
|
||||
if (Number.isFinite(fromSummary) && fromSummary >= 0 && projection.summary?.total_files != null) {
|
||||
return fromSummary;
|
||||
}
|
||||
const groups = projection.status_groups;
|
||||
const tasks = [
|
||||
...(projection.needs_action || []),
|
||||
...(projection.processing || []),
|
||||
...(projection.completed || []),
|
||||
...(groups?.failed || []),
|
||||
...(groups?.waiting_human || []),
|
||||
...(groups?.processing || []),
|
||||
...(groups?.completed || []),
|
||||
];
|
||||
return tasks.reduce((sum, task) => {
|
||||
const count = Number(task.file_count);
|
||||
@@ -83,10 +85,13 @@ export function resolveFormalTaskCount(
|
||||
if (Number.isFinite(fromSummary) && fromSummary >= 0 && projection.summary?.total_tasks != null) {
|
||||
return fromSummary;
|
||||
}
|
||||
const groups = projection.status_groups;
|
||||
return (
|
||||
(projection.needs_action?.length || 0)
|
||||
+ (projection.processing?.length || 0)
|
||||
+ (projection.completed?.length || 0)
|
||||
+ (projection.history?.length || 0)
|
||||
(groups?.failed.length || 0)
|
||||
+ (groups?.waiting_human.length || 0)
|
||||
+ (groups?.processing.length || 0)
|
||||
+ (groups?.completed.length || 0)
|
||||
+ (groups?.cancelled.length || 0)
|
||||
+ (groups?.archived.length || 0)
|
||||
);
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -5,7 +5,7 @@
|
||||
* ShippingProcessingProjection、合成 ShippingWorkflowItem)。
|
||||
* 逻辑:Timeline 与 ShippingConversationProcessingCard 复用;文件明细由
|
||||
* mapUserTaskObjectsToFileRows(task.objects) 合成;禁止 Workflow fallback reconcile;
|
||||
* 可由统一 work_items(order_task)合成兼容分组。
|
||||
* 会话卡直接消费后端 status_groups,不从 work_items 二次聚合。
|
||||
* 语义签名与任务稳定化:轮询返回相同业务状态时复用旧对象,避免按钮闪烁。
|
||||
*/
|
||||
|
||||
@@ -16,7 +16,6 @@ import type {
|
||||
ConversationProcessingTaskGroup,
|
||||
ConversationProcessingUserTask,
|
||||
ShippingProcessingBlockingReason,
|
||||
ShippingProcessingFacts,
|
||||
ShippingProcessingLifecycleEntry,
|
||||
ShippingProcessingPrimaryAction,
|
||||
ShippingProcessingProjection,
|
||||
@@ -96,14 +95,21 @@ export function buildTaskSemanticKey(
|
||||
intakeNo: child.intakeNo,
|
||||
status: child.userStatus ?? child.status,
|
||||
stage: child.userStage ?? child.stage,
|
||||
runNo: child.runNo ?? null,
|
||||
caseNo: child.caseNo ?? null,
|
||||
uploadState: child.facts?.uploadState ?? null,
|
||||
filename: child.sourceSummary?.filename ?? null,
|
||||
reason: child.blockingReason?.code ?? child.sourceSummary?.failureReasonCode ?? null,
|
||||
// EML 父卡会缓存其叶子对象。子文件的入口与按钮同样是后端裁决,
|
||||
// 必须进入父卡语义签名;否则父卡引用被复用时会残留已撤销的入口。
|
||||
primaryAction: child.uiState
|
||||
? (child.uiState.primary_action?.code ?? null)
|
||||
: (child.primaryAction?.code ?? null),
|
||||
primaryAction: child.uiState?.primary_action
|
||||
? {
|
||||
code: child.uiState.primary_action.code,
|
||||
executionMode: child.uiState.primary_action.executionMode ?? null,
|
||||
targetSurface: child.uiState.primary_action.targetSurface ?? null,
|
||||
targetLifecycleStage: child.uiState.primary_action.targetLifecycleStage ?? null,
|
||||
}
|
||||
: null,
|
||||
lifecycleEntries: child.uiState?.lifecycleEntries?.map((entry) => ({
|
||||
code: entry.code,
|
||||
state: entry.state,
|
||||
@@ -121,11 +127,7 @@ export function buildTaskSemanticKey(
|
||||
title: task.title,
|
||||
// [AUTHORITY] 新会话批次的可操作动作由 ui_state 单独版本化;把它纳入语义键,
|
||||
// 避免状态未变但后端撤销/切换按钮时前端错误复用旧任务对象。
|
||||
primaryAction: task.uiState
|
||||
? (task.uiState.primary_action?.code ?? null)
|
||||
: ((task as ConversationProcessingUserTask & { primaryAction?: { code?: string } | null }).primaryAction?.code
|
||||
?? task.primary_action
|
||||
?? null),
|
||||
primaryAction: task.uiState?.primary_action?.code ?? null,
|
||||
// 生命周期入口由后端独立裁决;入口被撤销/禁用时必须替换缓存对象,不能保留旧按钮。
|
||||
lifecycleEntries: task.uiState?.lifecycleEntries?.map((entry) => ({
|
||||
code: entry.code,
|
||||
@@ -147,16 +149,11 @@ export function buildTaskSemanticKey(
|
||||
?? null,
|
||||
nextActionCode: (task as ConversationProcessingUserTask & {
|
||||
current_gate?: { blockingReasonCode?: string; nextActionCode?: string };
|
||||
})
|
||||
.current_gate?.nextActionCode
|
||||
?? (task as ConversationProcessingUserTask & { primaryAction?: { code?: string } | null }).primaryAction?.code
|
||||
?? null,
|
||||
}).current_gate?.nextActionCode ?? null,
|
||||
}
|
||||
: null,
|
||||
availableActions: normalizeActionCodes(
|
||||
task.uiState
|
||||
? task.uiState.secondary_actions.filter((action) => action.enabled).map((action) => action.code)
|
||||
: (task.available_actions || []),
|
||||
task.uiState?.secondary_actions.filter((action) => action.enabled).map((action) => action.code) || [],
|
||||
),
|
||||
canAppend: task.can_append ?? null,
|
||||
aggregateChildren,
|
||||
@@ -173,6 +170,7 @@ export function buildProcessingSemanticKey(
|
||||
projection: ConversationProcessingProjection | null | undefined,
|
||||
): string {
|
||||
if (!projection) return '';
|
||||
const groups = projection.status_groups;
|
||||
return JSON.stringify({
|
||||
summary: {
|
||||
total_tasks: projection.summary?.total_tasks || 0,
|
||||
@@ -184,10 +182,14 @@ export function buildProcessingSemanticKey(
|
||||
},
|
||||
focused_task_no: projection.focused_task_no || null,
|
||||
recent_task_no: projection.recent_task_no || null,
|
||||
needs_action: (projection.needs_action || []).map(buildTaskSemanticKey),
|
||||
processing: (projection.processing || []).map(buildTaskSemanticKey),
|
||||
completed: (projection.completed || []).map(buildTaskSemanticKey),
|
||||
history: (projection.history || []).map(buildTaskSemanticKey),
|
||||
status_groups: {
|
||||
failed: (groups?.failed || []).map(buildTaskSemanticKey),
|
||||
waiting_human: (groups?.waiting_human || []).map(buildTaskSemanticKey),
|
||||
processing: (groups?.processing || []).map(buildTaskSemanticKey),
|
||||
completed: (groups?.completed || []).map(buildTaskSemanticKey),
|
||||
cancelled: (groups?.cancelled || []).map(buildTaskSemanticKey),
|
||||
archived: (groups?.archived || []).map(buildTaskSemanticKey),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
@@ -859,74 +861,6 @@ export function groupConversationProcessingTasks(
|
||||
* 核心逻辑:同 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 userGroup = String(item.userGroup || '').trim().toLowerCase();
|
||||
const status = normalizeLifecycleStatus(String(item.userStatus ?? item.status ?? '').trim());
|
||||
const childStatuses = (item.aggregateChildren || []).map((child) => normalizeLifecycleStatus(String(child.userStatus ?? child.status ?? '').trim()));
|
||||
const childHasFailure = childStatuses.some((value) => value === 'failed');
|
||||
const childNeedsHuman = childStatuses.some((value) => value === 'waiting_review' || value === 'manual_upload_pending' || value === 'candidate_ready');
|
||||
const childAllUploaded = childStatuses.length > 0
|
||||
&& childStatuses.every((value, index) => value === 'completed' && item.aggregateChildren?.[index]?.facts?.uploadState === 'succeeded');
|
||||
if (childHasFailure) return 'needs_action';
|
||||
if (childNeedsHuman) return 'needs_action';
|
||||
if (childAllUploaded) return 'completed';
|
||||
// 子项真实状态优先于父级 userGroup,避免 review_required/failed 被旧 processing 覆盖。
|
||||
if (status === 'failed' || status === 'waiting_review' || status === 'manual_upload_pending') return 'needs_action';
|
||||
if (userGroup === 'failed' || userGroup === 'waiting_human') return 'needs_action';
|
||||
if (userGroup === 'completed') return 'completed';
|
||||
if (userGroup === 'cancelled' || userGroup === 'archived') return 'history';
|
||||
if (userGroup === 'processing') return 'processing';
|
||||
const gateAction = String(item.primaryAction?.code ?? item.currentGate?.nextActionCode ?? '').trim().toLowerCase();
|
||||
const hasHumanAction = [gateAction, ...(item.availableActions || [])]
|
||||
.map((value) => String(value || '').trim().toLowerCase())
|
||||
.some((value) => HUMAN_ACTION_CODES.has(value) || value.startsWith('retry_failed_'));
|
||||
if (
|
||||
status === 'waiting_review'
|
||||
|| status === 'blocked'
|
||||
|| status === 'failed'
|
||||
|| status === 'waiting_human'
|
||||
|| status === 'retryable'
|
||||
|| hasHumanAction
|
||||
) {
|
||||
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'
|
||||
? normalizeConversationProcessingProjection(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。
|
||||
* 核心逻辑:新版 embedded.status_groups 是后端已完成“当前文件代表项 → EML 容器”
|
||||
@@ -940,46 +874,15 @@ export function mergeConversationProcessingFocusMetadata(
|
||||
* @returns 会话处理投影;无可用数据时 null
|
||||
*/
|
||||
export function resolveConversationProcessingFromUnified(
|
||||
workItems: ShippingProcessingProjection[] | null | undefined,
|
||||
_workItems: ShippingProcessingProjection[] | null | undefined,
|
||||
embedded: ConversationProcessingProjection | null | undefined,
|
||||
previousProjection?: ConversationProcessingProjection | null,
|
||||
stabilizer?: { hasSeenOrderTaskBefore?(conversationId?: string | null): boolean; markSeen?(conversationId?: string | null): void; reset?(conversationId?: string | null): void; conversationId?: string | null },
|
||||
_previousProjection?: ConversationProcessingProjection | null,
|
||||
_stabilizer?: { hasSeenOrderTaskBefore?(conversationId?: string | null): boolean; markSeen?(conversationId?: string | null): void; reset?(conversationId?: string | null): void; conversationId?: string | null },
|
||||
): ConversationProcessingProjection | null {
|
||||
const items = Array.isArray(workItems) ? workItems : [];
|
||||
// [AUTHORITY] conversation_processing.status_groups 与 four_stage_nodes / ui_state
|
||||
// 同属后端一次裁决。即使顶层 work_items 非空,也不得前端二次聚合或用旧快照覆盖。
|
||||
if (embedded && typeof embedded === 'object' && embedded.status_groups) {
|
||||
return normalizeConversationProcessingProjection(embedded);
|
||||
}
|
||||
// [AUTHORITY] 新版接口已经由后端完成「状态 → EML → 业务文件」聚合。
|
||||
// 会话卡与批次中心必须直接使用该结果;前端从 work_items 重建只保留给旧响应兼容。
|
||||
// [TRANSITION] 只有统一投影里明确存在 order_task,才认为 OT 维度已经成形。
|
||||
// 仅 order_intake 存在时视为过渡阶段:
|
||||
// - 如果此会话/全局在此之前已见到过 order_task(2s 窗口内),
|
||||
// 则延迟回退 embedded,保持 previousProjection 不变,避免闪烁;
|
||||
// - 否则仍走 embedded,但强制 normalize 成 waiting_review。
|
||||
const hasOrderTask = items.some((item) => (
|
||||
item.workItemType === 'order_task'
|
||||
|| (item.workItemType === 'order_intake' && item.sourceType === 'eml')
|
||||
));
|
||||
const convId = stabilizer?.conversationId;
|
||||
if (hasOrderTask) {
|
||||
stabilizer?.markSeen?.(convId);
|
||||
return mergeConversationProcessingFocusMetadata(
|
||||
projectConversationProcessingFromWorkItems(items, previousProjection),
|
||||
embedded,
|
||||
);
|
||||
}
|
||||
const sawOrderTaskRecently = stabilizer?.hasSeenOrderTaskBefore?.(convId) === true;
|
||||
if (sawOrderTaskRecently && previousProjection) {
|
||||
// 刚刚看到过 OT 但这轮响应暂缺 OT:不立即切回 embedded,保持上一轮投影。
|
||||
// 这样 2s 内轮询不会把右侧任务卡从 order_task 派生结果抖回旧 projection。
|
||||
return previousProjection;
|
||||
}
|
||||
if (embedded && typeof embedded === 'object') {
|
||||
return normalizeConversationProcessingProjection(embedded);
|
||||
}
|
||||
return null;
|
||||
// [AUTHORITY] 会话进度只能消费后端一次裁决的状态→EML→PDF树;从 work_items
|
||||
// 二次聚合会让前端重新承担业务状态裁决并重新引入旧四组的重复响应。
|
||||
if (!embedded || typeof embedded !== 'object' || !embedded.status_groups) return null;
|
||||
return normalizeConversationProcessingProjection(embedded);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -993,15 +896,11 @@ export function resolveConversationProcessingFromUnified(
|
||||
export function normalizeConversationProcessingProjection(
|
||||
projection: ConversationProcessingProjection,
|
||||
): ConversationProcessingProjection {
|
||||
const backendAuthoritative = Boolean(projection.status_groups);
|
||||
const normalizeUiState = (
|
||||
rawState: ConversationProcessingUserTask['uiState'] | undefined,
|
||||
): ConversationProcessingUserTask['uiState'] | undefined => {
|
||||
if (!rawState || typeof rawState !== 'object') return undefined;
|
||||
const state = rawState as ConversationProcessingUserTask['uiState'] & {
|
||||
blockingReason?: ShippingProcessingBlockingReason | null;
|
||||
primaryAction?: ShippingProcessingPrimaryAction | null;
|
||||
secondaryActions?: Array<{ code: string; enabled: boolean }>;
|
||||
lifecycle_stage?: ConversationProcessingUserTask['uiState'] extends { lifecycleStage?: infer S } ? S : never;
|
||||
lifecycle_entries?: Array<Record<string, unknown>>;
|
||||
};
|
||||
@@ -1035,11 +934,11 @@ export function normalizeConversationProcessingProjection(
|
||||
: null)
|
||||
),
|
||||
targetLifecycleStage: (
|
||||
['intake_parse', 'order_review', 'fulfillment_prep', 'upload_complete'].includes(
|
||||
['intake_parse', 'order_review', 'fulfillment_prep', 'freight_upload', 'upload_complete'].includes(
|
||||
String(rawAction.targetLifecycleStage),
|
||||
)
|
||||
? rawAction.targetLifecycleStage
|
||||
: (['intake_parse', 'order_review', 'fulfillment_prep', 'upload_complete'].includes(
|
||||
: (['intake_parse', 'order_review', 'fulfillment_prep', 'freight_upload', 'upload_complete'].includes(
|
||||
String(rawAction.target_lifecycle_stage),
|
||||
)
|
||||
? rawAction.target_lifecycle_stage
|
||||
@@ -1057,11 +956,11 @@ export function normalizeConversationProcessingProjection(
|
||||
};
|
||||
return {
|
||||
...state,
|
||||
blocking_reason: normalizeReason(state.blocking_reason ?? state.blockingReason),
|
||||
primary_action: normalizeAction(state.primary_action ?? state.primaryAction),
|
||||
blocking_reason: normalizeReason(state.blocking_reason),
|
||||
primary_action: normalizeAction(state.primary_action),
|
||||
// 次动作与主动作同属后端 ui_state 授权契约。若仅透传原始 snake_case,
|
||||
// 文件行点击会看不到导航目标并错误落入旧兼容分支。
|
||||
secondary_actions: (state.secondary_actions ?? state.secondaryActions ?? [])
|
||||
secondary_actions: (state.secondary_actions || [])
|
||||
.map((action) => {
|
||||
const normalized = normalizeAction(action);
|
||||
return normalized && 'code' in action && 'enabled' in action
|
||||
@@ -1069,23 +968,22 @@ export function normalizeConversationProcessingProjection(
|
||||
: null;
|
||||
})
|
||||
.filter((action): action is ShippingProcessingPrimaryAction & { code: string; enabled: boolean } => Boolean(action)),
|
||||
lifecycleStage: state.lifecycleStage ?? state.lifecycle_stage,
|
||||
lifecycleEntries: Array.isArray(state.lifecycleEntries)
|
||||
? state.lifecycleEntries.filter((entry) => Boolean(entry?.code && entry?.state && entry?.targetSurface))
|
||||
: (Array.isArray(state.lifecycle_entries)
|
||||
? state.lifecycle_entries.map((entry) => {
|
||||
const rawEntry = entry as { code?: unknown; state?: unknown; target_surface?: unknown; targetSurface?: unknown };
|
||||
return {
|
||||
code: String(rawEntry.code || '') as ShippingProcessingLifecycleEntry['code'],
|
||||
state: String(rawEntry.state || '') as ShippingProcessingLifecycleEntry['state'],
|
||||
targetSurface: String(rawEntry.targetSurface ?? rawEntry.target_surface ?? '') as ShippingProcessingLifecycleEntry['targetSurface'],
|
||||
};
|
||||
}).filter((entry) => Boolean(entry.code && entry.state && entry.targetSurface))
|
||||
: []),
|
||||
lifecycleStage: state.lifecycle_stage,
|
||||
lifecycleEntries: Array.isArray(state.lifecycle_entries)
|
||||
? state.lifecycle_entries.map((entry) => {
|
||||
const rawEntry = entry as { code?: unknown; state?: unknown; target_surface?: unknown };
|
||||
return {
|
||||
code: String(rawEntry.code || '') as ShippingProcessingLifecycleEntry['code'],
|
||||
state: String(rawEntry.state || '') as ShippingProcessingLifecycleEntry['state'],
|
||||
targetSurface: String(rawEntry.target_surface || '') as ShippingProcessingLifecycleEntry['targetSurface'],
|
||||
};
|
||||
}).filter((entry) => Boolean(entry.code && entry.state && entry.targetSurface))
|
||||
: [],
|
||||
};
|
||||
};
|
||||
const normalizeTask = (task: ConversationProcessingUserTask): ConversationProcessingUserTask => {
|
||||
const raw = task as ConversationProcessingUserTask & {
|
||||
user_task_no?: string | null;
|
||||
user_status?: ConversationProcessingUserTask['userStatus'];
|
||||
user_stage?: ConversationProcessingUserTask['userStage'];
|
||||
user_group?: ConversationProcessingUserTask['userGroup'];
|
||||
@@ -1094,406 +992,52 @@ export function normalizeConversationProcessingProjection(
|
||||
aggregate_summary?: ConversationProcessingUserTask['aggregateSummary'];
|
||||
aggregate_children?: unknown[];
|
||||
};
|
||||
const rawPrimaryAction = raw.primaryAction ?? raw.primary_action ?? null;
|
||||
const aggregateChildren = Array.isArray(raw.aggregateChildren)
|
||||
? raw.aggregateChildren
|
||||
: (Array.isArray(raw.aggregate_children)
|
||||
? raw.aggregate_children
|
||||
.map(normalizeShippingProcessingProjection)
|
||||
.filter((item): item is ShippingProcessingProjection => Boolean(item))
|
||||
: []);
|
||||
// 新批次投影的 group/user_group 已由后端裁决;旧 embedded 响应没有 status_groups,
|
||||
// 仅在该兼容分支维持历史规范化,避免旧服务端响应把待人工留在处理中。
|
||||
const rawStatus = task.userStatus ?? task.status_label;
|
||||
const normalizedStatus = normalizeLifecycleStatus(rawStatus);
|
||||
const legacyActions = Array.isArray(task.available_actions) ? task.available_actions : [];
|
||||
const legacyHasHumanAction = legacyActions.some((value) => {
|
||||
const code = String(value || '').trim().toLowerCase();
|
||||
return HUMAN_ACTION_CODES.has(code) || code.startsWith('retry_failed_');
|
||||
});
|
||||
const finalGroup: ConversationProcessingTaskGroup = backendAuthoritative
|
||||
? task.group
|
||||
: classifyConversationProcessingGroup(normalizedStatus || rawStatus, {
|
||||
needsCustomerConfirm: legacyHasHumanAction,
|
||||
});
|
||||
const aggregateChildren = Array.isArray(raw.aggregate_children)
|
||||
? raw.aggregate_children
|
||||
.map(normalizeShippingProcessingProjection)
|
||||
.filter((item): item is ShippingProcessingProjection => Boolean(item))
|
||||
: [];
|
||||
return {
|
||||
...task,
|
||||
status_label: backendAuthoritative
|
||||
? task.status_label
|
||||
: (normalizedStatus || task.status_label),
|
||||
userStatus: raw.userStatus ?? raw.user_status ?? null,
|
||||
userStage: raw.userStage ?? raw.user_stage ?? null,
|
||||
userGroup: raw.userGroup ?? raw.user_group ?? null,
|
||||
blockingReason: raw.blockingReason ?? raw.blocking_reason ?? null,
|
||||
primaryAction: typeof rawPrimaryAction === 'object' ? rawPrimaryAction : null,
|
||||
primary_action: typeof rawPrimaryAction === 'string' ? rawPrimaryAction : task.primary_action,
|
||||
aggregateSummary: raw.aggregateSummary ?? raw.aggregate_summary ?? null,
|
||||
status_label: task.status_label,
|
||||
userStatus: raw.user_status ?? null,
|
||||
userStage: raw.user_stage ?? null,
|
||||
userGroup: raw.user_group ?? null,
|
||||
blockingReason: raw.blocking_reason ?? null,
|
||||
primaryAction: null,
|
||||
primary_action: task.primary_action,
|
||||
aggregateSummary: raw.aggregate_summary ?? null,
|
||||
aggregateChildren,
|
||||
uiState: normalizeUiState(
|
||||
(raw as ConversationProcessingUserTask & { ui_state?: ConversationProcessingUserTask['uiState'] }).uiState
|
||||
?? (raw as ConversationProcessingUserTask & { ui_state?: ConversationProcessingUserTask['uiState'] }).ui_state,
|
||||
(raw as ConversationProcessingUserTask & { ui_state?: ConversationProcessingUserTask['uiState'] }).ui_state,
|
||||
),
|
||||
group: finalGroup,
|
||||
group: task.group,
|
||||
};
|
||||
};
|
||||
const normalizedLegacyTasks = [
|
||||
...(projection.needs_action || []),
|
||||
...(projection.processing || []),
|
||||
...(projection.completed || []),
|
||||
...(projection.history || []),
|
||||
].map(normalizeTask);
|
||||
const normalizedGroups = projection.status_groups
|
||||
? {
|
||||
failed: (projection.status_groups.failed || []).map(normalizeTask),
|
||||
waiting_human: (projection.status_groups.waiting_human || []).map(normalizeTask),
|
||||
processing: (projection.status_groups.processing || []).map(normalizeTask),
|
||||
completed: (projection.status_groups.completed || []).map(normalizeTask),
|
||||
cancelled: (projection.status_groups.cancelled || []).map(normalizeTask),
|
||||
archived: (projection.status_groups.archived || []).map(normalizeTask),
|
||||
}
|
||||
: null;
|
||||
// status_groups 存在时,传统四组只是兼容镜像,可能为空;统计必须保留后端 summary,
|
||||
// 绝不能据空镜像重新裁决成 0。
|
||||
const normalizedAll = normalizedGroups
|
||||
? [
|
||||
...normalizedGroups.failed,
|
||||
...normalizedGroups.waiting_human,
|
||||
...normalizedGroups.processing,
|
||||
...normalizedGroups.completed,
|
||||
...normalizedGroups.cancelled,
|
||||
...normalizedGroups.archived,
|
||||
]
|
||||
: normalizedLegacyTasks;
|
||||
const needs_action = normalizedGroups
|
||||
? [...normalizedGroups.failed, ...normalizedGroups.waiting_human]
|
||||
: normalizedAll.filter((task) => task.group === 'needs_action');
|
||||
const processing = normalizedGroups?.processing || normalizedAll.filter((task) => task.group === 'processing');
|
||||
const completed = normalizedGroups?.completed || normalizedAll.filter((task) => task.group === 'completed');
|
||||
const history = normalizedGroups
|
||||
? [...normalizedGroups.cancelled, ...normalizedGroups.archived]
|
||||
: normalizedAll.filter((task) => task.group === 'history');
|
||||
const normalizedGroups = {
|
||||
failed: (projection.status_groups?.failed || []).map(normalizeTask),
|
||||
waiting_human: (projection.status_groups?.waiting_human || []).map(normalizeTask),
|
||||
processing: (projection.status_groups?.processing || []).map(normalizeTask),
|
||||
completed: (projection.status_groups?.completed || []).map(normalizeTask),
|
||||
cancelled: (projection.status_groups?.cancelled || []).map(normalizeTask),
|
||||
archived: (projection.status_groups?.archived || []).map(normalizeTask),
|
||||
};
|
||||
const {
|
||||
needs_action: _legacyNeedsAction,
|
||||
processing: _legacyProcessing,
|
||||
completed: _legacyCompleted,
|
||||
history: _legacyHistory,
|
||||
...authoritativeProjection
|
||||
} = projection;
|
||||
return {
|
||||
...projection,
|
||||
// [AUTHORITY] 新批次 status_groups + summary 同属一次后端裁决。summary 可能覆盖完整批次,
|
||||
// 而当前组只返回可见 EML;前端不得用局部行数覆盖后端文件/任务统计。
|
||||
summary: backendAuthoritative
|
||||
? projection.summary
|
||||
: {
|
||||
...(projection.summary || {}),
|
||||
total_tasks: normalizedAll.length,
|
||||
total_files: normalizedAll.reduce((sum, task) => sum + Number(task.file_count || 0), 0),
|
||||
needs_action: needs_action.length,
|
||||
processing: processing.length,
|
||||
completed: completed.length,
|
||||
history: history.length,
|
||||
},
|
||||
needs_action,
|
||||
processing,
|
||||
completed,
|
||||
history,
|
||||
status_groups: normalizedGroups || projection.status_groups,
|
||||
four_stage_nodes: projection.four_stage_nodes || [],
|
||||
...authoritativeProjection,
|
||||
// [AUTHORITY] summary 与 status_groups 同属后端一次裁决。前端不得从局部 EML
|
||||
// 行重算任务/文件统计,也不得重新生成旧四组镜像。
|
||||
summary: projection.summary,
|
||||
status_groups: normalizedGroups,
|
||||
lifecycle_nodes: projection.lifecycle_nodes || [],
|
||||
unclassified_summary: projection.unclassified_summary || { count: 0 },
|
||||
ui_state: projection.ui_state || undefined,
|
||||
output_artifacts: projection.output_artifacts || [],
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 从统一 work_items 合成 ConversationProcessingProjection(order_task 与 EML order_intake)。
|
||||
*
|
||||
* 核心逻辑:order_task 与 EML order_intake 均进入状态区;非 EML intake 不入组;
|
||||
* available_actions 使用标准化(去重、排序)动作码;按 previousProjection 复用旧对象引用。
|
||||
*
|
||||
* @param workItems - 统一投影 work_items
|
||||
* @param previousProjection - 上一版投影(语义稳定化复用旧对象)
|
||||
* @returns 兼容投影;无可展示任务时返回 null
|
||||
*/
|
||||
export function projectConversationProcessingFromWorkItems(
|
||||
workItems: ShippingProcessingProjection[] | null | undefined,
|
||||
previousProjection?: ConversationProcessingProjection | null,
|
||||
): ConversationProcessingProjection | null {
|
||||
const items = Array.isArray(workItems) ? workItems : [];
|
||||
const orderTasks = items.filter((row) => (
|
||||
row.workItemType === 'order_task'
|
||||
|| (row.workItemType === 'order_intake' && row.sourceType === 'eml')
|
||||
));
|
||||
if (!orderTasks.length) return null;
|
||||
|
||||
const rawTaskEntries: Array<{ task: ConversationProcessingUserTask; item: ShippingProcessingProjection }> = [];
|
||||
|
||||
for (const item of orderTasks) {
|
||||
const taskNo = String(item.workItemNo || item.rootOrderTaskNo || '').trim();
|
||||
if (!taskNo) continue;
|
||||
const group = mapShippingProcessingStatusToTaskGroup(item);
|
||||
// EML 父项的 sourceSummary.filename 是邮件名,只能用于分组标题;
|
||||
// 文件行与数量必须来自其真实附件叶子。
|
||||
const leafFiles = flattenBusinessFileProjections([item]);
|
||||
const leafKeys = businessFileKeys([item]);
|
||||
const leafNames = [...new Set(leafFiles
|
||||
.map((child) => String(child.sourceSummary?.filename || '').trim())
|
||||
.filter(Boolean))];
|
||||
const leafObjects = leafFiles.map((child, index) => {
|
||||
const summary = child.sourceSummary || {};
|
||||
const documentId = Number(summary.documentId || 0) || undefined;
|
||||
const leafFilename = String(summary.filename || '').trim();
|
||||
return {
|
||||
kind: 'document' as const,
|
||||
object_key: documentId ? `DOC-${documentId}` : `${taskNo}-leaf-${index}`,
|
||||
label: leafFilename || String(child.workItemNo || taskNo),
|
||||
filename: leafFilename || undefined,
|
||||
document_id: documentId,
|
||||
status_label: String(child.userStatus ?? child.status ?? ''),
|
||||
run_no: child.runNo || undefined,
|
||||
current_run_no: child.runNo || undefined,
|
||||
case_no: child.caseNo || undefined,
|
||||
task_no: child.rootOrderTaskNo || undefined,
|
||||
workflow_item_no: child.workItemNo || undefined,
|
||||
};
|
||||
});
|
||||
const isEmlContainer = item.sourceType === 'eml' && Array.isArray(item.aggregateChildren)
|
||||
&& item.aggregateChildren.length > 0;
|
||||
const sourceDocCount = Number(item.sourceSummary?.documentCount || 0);
|
||||
// 只有已展开的 EML 聚合以叶子集合覆盖后端摘要;普通/旧单项投影仍保留
|
||||
// sourceSummary.documentCount,避免稀疏投影把一个多文件任务错误压成 1 个文件。
|
||||
const docCount = isEmlContainer
|
||||
? leafKeys.length
|
||||
: (sourceDocCount || leafKeys.length);
|
||||
const filename = isEmlContainer
|
||||
? String(item.sourceSummary?.filename || '').trim()
|
||||
: (leafNames[0] || String(item.sourceSummary?.filename || '').trim());
|
||||
const normalizedActions = normalizeActionCodes(item.availableActions || []);
|
||||
const gateNextAction = String(item.primaryAction?.code ?? item.currentGate?.nextActionCode ?? '').trim().toLowerCase() || null;
|
||||
const effectiveStatus = normalizeLifecycleStatus(String(item.userStatus ?? item.status ?? '').trim()) || null;
|
||||
const userBlocking: ConversationProcessingUserTask['blockingReason'] = (item.blockingReason && typeof item.blockingReason === 'object')
|
||||
? {
|
||||
code: item.blockingReason.code,
|
||||
i18nKey: (item.blockingReason as { i18nKey?: string | null }).i18nKey
|
||||
?? (item.blockingReason as { i18n_key?: string | null }).i18n_key
|
||||
?? undefined,
|
||||
details: (item.blockingReason as { details?: Record<string, unknown> }).details,
|
||||
} satisfies ShippingProcessingBlockingReason
|
||||
: null;
|
||||
const userPrimaryAction: ConversationProcessingUserTask['primaryAction'] = item.primaryAction
|
||||
? {
|
||||
code: item.primaryAction.code,
|
||||
i18nKey: (item.primaryAction as { i18nKey?: string | null }).i18nKey
|
||||
?? (item.primaryAction as { i18n_key?: string | null }).i18n_key
|
||||
?? undefined,
|
||||
parameters: (item.primaryAction as { parameters?: Record<string, unknown> }).parameters,
|
||||
} satisfies ShippingProcessingPrimaryAction
|
||||
: null;
|
||||
const userFacts: ConversationProcessingUserTask['facts'] = item.facts
|
||||
? {
|
||||
inventorySourceStatus: (item.facts as { inventorySourceStatus?: string | null }).inventorySourceStatus ?? undefined,
|
||||
candidateSourceCodes: (item.facts as { candidateSourceCodes?: string[] }).candidateSourceCodes ?? [],
|
||||
preparedSourceCodes: (item.facts as { preparedSourceCodes?: string[] }).preparedSourceCodes ?? [],
|
||||
pendingSourceCodes: (item.facts as { pendingSourceCodes?: string[] }).pendingSourceCodes ?? [],
|
||||
lineResolutions: (item.facts as { lineResolutions?: Record<string, unknown>[] }).lineResolutions ?? undefined,
|
||||
exportState: (item.facts as { exportState?: string }).exportState ?? undefined,
|
||||
uploadState: (item.facts as { uploadState?: string }).uploadState ?? undefined,
|
||||
switchState: (item.facts as { switchState?: string }).switchState ?? undefined,
|
||||
forcedMatchSourceCode: (item.facts as { forcedMatchSourceCode?: string | null }).forcedMatchSourceCode ?? undefined,
|
||||
} satisfies ShippingProcessingFacts
|
||||
: undefined;
|
||||
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: leafNames.length ? leafNames : (isEmlContainer ? [] : (filename ? [filename] : [])),
|
||||
group,
|
||||
status_label: effectiveStatus,
|
||||
file_count: docCount > 0 ? docCount : (isEmlContainer ? 0 : (filename ? 1 : 0)),
|
||||
run_no: String(item.runNo || '').trim() || null,
|
||||
objects: leafObjects,
|
||||
can_append: false,
|
||||
last_activity_at: item.lastActivityAt || null,
|
||||
available_actions: normalizedActions,
|
||||
primary_action: gateNextAction || normalizedActions[0] || null,
|
||||
userStatus: item.userStatus ?? null,
|
||||
userStage: item.userStage ?? null,
|
||||
blockingReason: userBlocking,
|
||||
primaryAction: userPrimaryAction,
|
||||
facts: userFacts,
|
||||
userGroup: item.userGroup ?? null,
|
||||
userCurrentGateCode: item.userCurrentGateCode ?? null,
|
||||
legacyStatus: item.legacyStatus ?? null,
|
||||
legacyStage: item.legacyStage ?? null,
|
||||
aggregateSummary: item.aggregateSummary ?? null,
|
||||
aggregateChildren: item.aggregateChildren ?? [],
|
||||
};
|
||||
rawTaskEntries.push({ task, item });
|
||||
}
|
||||
|
||||
const rawTasks: ConversationProcessingUserTask[] = [];
|
||||
const emlGroups = new Map<string, Array<{ task: ConversationProcessingUserTask; item: ShippingProcessingProjection }>>();
|
||||
for (const entry of rawTaskEntries) {
|
||||
if (entry.item.sourceType !== 'eml' || !entry.item.intakeNo) {
|
||||
rawTasks.push(entry.task);
|
||||
continue;
|
||||
}
|
||||
const key = String(entry.item.intakeNo).trim();
|
||||
const group = emlGroups.get(key) || [];
|
||||
group.push(entry);
|
||||
emlGroups.set(key, group);
|
||||
}
|
||||
for (const [intakeNo, entries] of emlGroups) {
|
||||
if (entries.length === 1) {
|
||||
rawTasks.push({
|
||||
...entries[0]!.task,
|
||||
aggregateChildren: entries[0]!.task.aggregateChildren?.length
|
||||
? entries[0]!.task.aggregateChildren
|
||||
: entries[0]!.item.aggregateChildren || [],
|
||||
});
|
||||
continue;
|
||||
}
|
||||
const completed = entries.filter(({ item }) => String(item.userStatus ?? item.status).toLowerCase() === 'completed').length;
|
||||
const failed = entries.filter(({ item }) => ['failed', 'retryable'].includes(String(item.userStatus ?? item.status).toLowerCase())).length;
|
||||
const needsAction = entries.filter(({ task }) => task.group === 'needs_action').length;
|
||||
const processing = entries.filter(({ task }) => task.group === 'processing').length;
|
||||
const stages = [...new Set(entries.flatMap(({ item }) => [item.userStage, item.stage].filter(Boolean).map(String)))];
|
||||
const reasonCodes = [...new Set(entries.flatMap(({ item }) => [
|
||||
item.blockingReason?.code,
|
||||
item.sourceSummary?.failureReasonCode,
|
||||
].filter(Boolean).map(String)))];
|
||||
const entryGroups = entries.map(({ task, item }) => {
|
||||
const children = item.aggregateChildren || [];
|
||||
const childStatuses = children.map((child) => normalizeLifecycleStatus(String(child.userStatus ?? child.status ?? '').trim()));
|
||||
if (childStatuses.some((value) => value === 'failed')) return 'failed';
|
||||
if (childStatuses.some((value) => value === 'waiting_review' || value === 'manual_upload_pending' || value === 'candidate_ready')) return 'waiting_human';
|
||||
if (childStatuses.length > 0 && childStatuses.every((value, index) => value === 'completed' && children[index]?.facts?.uploadState === 'succeeded')) return 'completed';
|
||||
const explicit = String(item.userGroup || '').trim().toLowerCase();
|
||||
if (explicit) return explicit;
|
||||
const status = String(item.userStatus ?? item.status ?? '').trim().toLowerCase();
|
||||
if (status === 'failed' || status === 'retryable') return 'failed';
|
||||
if (task.group === 'needs_action') return 'waiting_human';
|
||||
if (task.group === 'completed' && status === 'completed') return 'completed';
|
||||
if (task.group === 'history') return status === 'cancelled' ? 'cancelled' : 'archived';
|
||||
return 'processing';
|
||||
});
|
||||
const aggregateUserGroup = entryGroups.includes('failed')
|
||||
? 'failed'
|
||||
: entryGroups.includes('waiting_human')
|
||||
? 'waiting_human'
|
||||
: entryGroups.includes('processing')
|
||||
? 'processing'
|
||||
: entryGroups.includes('completed') && entryGroups.every((value) => value === 'completed')
|
||||
? 'completed'
|
||||
: entryGroups.includes('cancelled')
|
||||
? 'cancelled'
|
||||
: entryGroups.includes('archived')
|
||||
? 'archived'
|
||||
: 'processing';
|
||||
const group = aggregateUserGroup === 'failed' || aggregateUserGroup === 'waiting_human'
|
||||
? 'needs_action'
|
||||
: aggregateUserGroup === 'completed'
|
||||
? 'completed'
|
||||
: aggregateUserGroup === 'cancelled' || aggregateUserGroup === 'archived'
|
||||
? 'history'
|
||||
: 'processing';
|
||||
const representative = entries[0]!.task;
|
||||
const aggregateChildren = entries.flatMap(({ item }) => item.aggregateChildren || [item]);
|
||||
const documentNames = [...new Set(flattenBusinessFileProjections(aggregateChildren)
|
||||
.map((child) => String(child.sourceSummary?.filename || '').trim())
|
||||
.filter(Boolean))];
|
||||
const fileCount = businessFileKeys(aggregateChildren).length;
|
||||
rawTasks.push({
|
||||
...representative,
|
||||
title: representative.title || `EML ${intakeNo}`,
|
||||
display_kind: fileCount > 1 ? 'multi_document_task' : representative.display_kind,
|
||||
document_names: documentNames,
|
||||
file_count: fileCount,
|
||||
group,
|
||||
available_actions: [...new Set(entries.flatMap(({ task }) => task.available_actions || []))].sort(),
|
||||
aggregateSummary: {
|
||||
intakeNo,
|
||||
total: entries.length,
|
||||
completed,
|
||||
processing,
|
||||
needsAction,
|
||||
failed,
|
||||
stages,
|
||||
reasonCodes,
|
||||
},
|
||||
aggregateChildren,
|
||||
userGroup: aggregateUserGroup as ConversationProcessingUserTask['userGroup'],
|
||||
});
|
||||
}
|
||||
|
||||
if (!rawTasks.length) return null;
|
||||
|
||||
const needs_action_raw: ConversationProcessingUserTask[] = [];
|
||||
const processing_raw: ConversationProcessingUserTask[] = [];
|
||||
const completed_raw: ConversationProcessingUserTask[] = [];
|
||||
const history_raw: ConversationProcessingUserTask[] = [];
|
||||
for (const task of rawTasks) {
|
||||
if (task.group === 'needs_action') needs_action_raw.push(task);
|
||||
else if (task.group === 'processing') processing_raw.push(task);
|
||||
else if (task.group === 'completed') completed_raw.push(task);
|
||||
else history_raw.push(task);
|
||||
}
|
||||
const active = [...needs_action_raw, ...processing_raw, ...completed_raw];
|
||||
if (!active.length && !history_raw.length) return null;
|
||||
|
||||
// 统计口径与卡片完全一致:递归叶子业务文件,排除 EML 容器。
|
||||
const totalFiles = businessFileKeys(orderTasks).length || active.reduce(
|
||||
(sum, task) => sum + Number(task.file_count || 0),
|
||||
0,
|
||||
);
|
||||
|
||||
const stabilizedAll = stabilizeTaskObjects(
|
||||
previousProjection
|
||||
? [
|
||||
...(previousProjection.needs_action || []),
|
||||
...(previousProjection.processing || []),
|
||||
...(previousProjection.completed || []),
|
||||
...(previousProjection.history || []),
|
||||
]
|
||||
: [],
|
||||
rawTasks,
|
||||
);
|
||||
const needs_action = stabilizeTaskObjects(
|
||||
previousProjection?.needs_action || [],
|
||||
stabilizedAll.filter((t) => t.group === 'needs_action'),
|
||||
);
|
||||
const processing = stabilizeTaskObjects(
|
||||
previousProjection?.processing || [],
|
||||
stabilizedAll.filter((t) => t.group === 'processing'),
|
||||
);
|
||||
const completed = stabilizeTaskObjects(
|
||||
previousProjection?.completed || [],
|
||||
stabilizedAll.filter((t) => t.group === 'completed'),
|
||||
);
|
||||
const history = stabilizeTaskObjects(
|
||||
previousProjection?.history || [],
|
||||
stabilizedAll.filter((t) => t.group === 'history'),
|
||||
);
|
||||
|
||||
const status_groups = {
|
||||
failed: stabilizedAll.filter((task) => task.userGroup === 'failed'),
|
||||
waiting_human: stabilizedAll.filter((task) => task.userGroup === 'waiting_human'),
|
||||
processing: stabilizedAll.filter((task) => task.userGroup === 'processing'),
|
||||
completed: stabilizedAll.filter((task) => task.userGroup === 'completed'),
|
||||
cancelled: stabilizedAll.filter((task) => task.userGroup === 'cancelled'),
|
||||
archived: stabilizedAll.filter((task) => task.userGroup === 'archived'),
|
||||
};
|
||||
|
||||
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,
|
||||
status_groups,
|
||||
};
|
||||
}
|
||||
@@ -82,7 +82,7 @@ describe('normalizeShippingProcessingProjection', () => {
|
||||
expect(normalized!.sourceSummary.filename).toBe('a.pdf');
|
||||
expect(normalized!.sourceSummary.documentId).toBe(17);
|
||||
expect(normalized!.sourceSummary.assetStatus).toBe('ready');
|
||||
expect(normalized!.availableActions).toEqual(['open_review']);
|
||||
expect(normalized!.availableActions).toEqual(['resolve_field_conflicts', 'view_details']);
|
||||
expect(normalized!.uiState).toMatchObject({
|
||||
status: 'waiting_human',
|
||||
stage: 'order_review',
|
||||
@@ -108,6 +108,35 @@ describe('normalizeShippingProcessingProjection', () => {
|
||||
expect(normalized?.stageNodes?.[1]?.absoluteIndex).toBe(2);
|
||||
});
|
||||
|
||||
it('保留后端五阶段生命周期入口,包括 freight_upload', () => {
|
||||
const normalized = normalizeShippingProcessingProjection({
|
||||
work_item_no: 'OT-LIFECYCLE-5',
|
||||
work_item_type: 'order_task',
|
||||
status: 'waiting_review',
|
||||
stage: 'freight_uploading',
|
||||
ui_state: {
|
||||
status: 'waiting_human',
|
||||
stage: 'freight_uploading',
|
||||
lifecycle_stage: 'freight_upload',
|
||||
lifecycle_entries: [
|
||||
{ code: 'intake_parse', state: 'available', target_surface: 'order_lifecycle_workbench' },
|
||||
{ code: 'order_review', state: 'available', target_surface: 'order_lifecycle_workbench' },
|
||||
{ code: 'fulfillment_prep', state: 'available', target_surface: 'order_lifecycle_workbench' },
|
||||
{ code: 'freight_upload', state: 'current', target_surface: 'order_lifecycle_workbench' },
|
||||
{ code: 'upload_complete', state: 'unavailable', target_surface: 'order_lifecycle_workbench' },
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
expect(normalized?.uiState?.lifecycleEntries).toEqual([
|
||||
{ code: 'intake_parse', state: 'available', targetSurface: 'order_lifecycle_workbench', disabledReasonKey: null },
|
||||
{ code: 'order_review', state: 'available', targetSurface: 'order_lifecycle_workbench', disabledReasonKey: null },
|
||||
{ code: 'fulfillment_prep', state: 'available', targetSurface: 'order_lifecycle_workbench', disabledReasonKey: null },
|
||||
{ code: 'freight_upload', state: 'current', targetSurface: 'order_lifecycle_workbench', disabledReasonKey: null },
|
||||
{ code: 'upload_complete', state: 'unavailable', targetSurface: 'order_lifecycle_workbench', disabledReasonKey: null },
|
||||
]);
|
||||
});
|
||||
|
||||
it('normalizes structured inventory candidate facts', () => {
|
||||
const projection = normalizeShippingProcessingProjection({
|
||||
work_item_no: 'SN-001',
|
||||
|
||||
@@ -25,25 +25,23 @@ import type {
|
||||
} from '../types/shipping.api.types';
|
||||
|
||||
/** 后端可裁决并透传到订单生命周期工作台的阶段;前端不根据本地状态补造入口。 */
|
||||
const lifecycleStages = ['intake_parse', 'order_review', 'fulfillment_prep', 'upload_complete'] as const;
|
||||
const lifecycleStages = ['intake_parse', 'order_review', 'fulfillment_prep', 'freight_upload', 'upload_complete'] as const;
|
||||
|
||||
/**
|
||||
* 读取原始对象上的字符串字段(兼容 snake / camel)。
|
||||
*/
|
||||
function readString(raw: Record<string, unknown>, snake: string, camel: string): string {
|
||||
const value = raw[snake] ?? raw[camel];
|
||||
/** 读取后端正式 snake_case DTO 的字符串字段。 */
|
||||
function readString(raw: Record<string, unknown>, snake: string, _removedLegacyCamel?: string): string {
|
||||
const value = raw[snake];
|
||||
return value == null ? '' : String(value);
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取可空字符串。
|
||||
* 读取后端正式 snake_case DTO 的可空字符串。
|
||||
*/
|
||||
function readNullableString(
|
||||
raw: Record<string, unknown>,
|
||||
snake: string,
|
||||
camel: string,
|
||||
_removedLegacyCamel?: string,
|
||||
): string | null {
|
||||
const value = raw[snake] ?? raw[camel];
|
||||
const value = raw[snake];
|
||||
if (value == null || value === '') return null;
|
||||
return String(value);
|
||||
}
|
||||
@@ -118,7 +116,7 @@ function normalizeBlockingReason(raw: unknown): ShippingProcessingBlockingReason
|
||||
if (!code) return null;
|
||||
return {
|
||||
code,
|
||||
i18nKey: item.i18n_key != null ? String(item.i18n_key) : (item.i18nKey != null ? String(item.i18nKey) : null),
|
||||
i18nKey: item.i18n_key != null ? String(item.i18n_key) : null,
|
||||
details:
|
||||
typeof item.details === 'object' && item.details != null
|
||||
? (item.details as Record<string, unknown>)
|
||||
@@ -136,23 +134,23 @@ function normalizePrimaryAction(raw: unknown): ShippingProcessingPrimaryAction |
|
||||
if (!code) return null;
|
||||
return {
|
||||
code,
|
||||
i18nKey: item.i18n_key != null ? String(item.i18n_key) : (item.i18nKey != null ? String(item.i18nKey) : null),
|
||||
i18nKey: item.i18n_key != null ? String(item.i18n_key) : null,
|
||||
parameters:
|
||||
typeof item.parameters === 'object' && item.parameters != null
|
||||
? (item.parameters as Record<string, unknown>)
|
||||
: {},
|
||||
executionMode: item.execution_mode === 'navigate' || item.executionMode === 'navigate'
|
||||
executionMode: item.execution_mode === 'navigate'
|
||||
? 'navigate'
|
||||
: item.execution_mode === 'execute' || item.executionMode === 'execute'
|
||||
: item.execution_mode === 'execute'
|
||||
? 'execute'
|
||||
: undefined,
|
||||
targetSurface: item.target_surface === 'order_lifecycle_workbench' || item.targetSurface === 'order_lifecycle_workbench'
|
||||
targetSurface: item.target_surface === 'order_lifecycle_workbench'
|
||||
? 'order_lifecycle_workbench'
|
||||
: null,
|
||||
targetLifecycleStage: lifecycleStages.includes(
|
||||
String(item.target_lifecycle_stage ?? item.targetLifecycleStage ?? '') as typeof lifecycleStages[number],
|
||||
String(item.target_lifecycle_stage ?? '') as typeof lifecycleStages[number],
|
||||
)
|
||||
? String(item.target_lifecycle_stage ?? item.targetLifecycleStage) as ShippingProcessingPrimaryAction['targetLifecycleStage']
|
||||
? String(item.target_lifecycle_stage) as ShippingProcessingPrimaryAction['targetLifecycleStage']
|
||||
: null,
|
||||
};
|
||||
}
|
||||
@@ -165,10 +163,10 @@ function normalizeLifecycleEntries(raw: unknown): NonNullable<ConversationProces
|
||||
.map((item) => ({
|
||||
code: String(item.code ?? '') as NonNullable<ConversationProcessingUiState['lifecycleEntries']>[number]['code'],
|
||||
state: String(item.state ?? '') as NonNullable<ConversationProcessingUiState['lifecycleEntries']>[number]['state'],
|
||||
targetSurface: String(item.target_surface ?? item.targetSurface ?? '') as NonNullable<ConversationProcessingUiState['lifecycleEntries']>[number]['targetSurface'],
|
||||
targetSurface: String(item.target_surface ?? '') as NonNullable<ConversationProcessingUiState['lifecycleEntries']>[number]['targetSurface'],
|
||||
disabledReasonKey: item.disabled_reason_key != null
|
||||
? String(item.disabled_reason_key)
|
||||
: item.disabledReasonKey != null ? String(item.disabledReasonKey) : null,
|
||||
: null,
|
||||
}))
|
||||
.filter((item) => lifecycleStages.includes(item.code as typeof lifecycleStages[number])
|
||||
&& ['available', 'current', 'unavailable'].includes(item.state)
|
||||
@@ -373,9 +371,13 @@ export function normalizeShippingProcessingProjection(
|
||||
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)
|
||||
// ui_state 是处理进度唯一的用户态/动作合同。旧顶层动作字段已下线,
|
||||
// 客户端只能由该合同派生本地展示索引,不能读取或补造历史 available_actions。
|
||||
const uiState = normalizeProcessingUiState(item.ui_state);
|
||||
const availableActions = uiState
|
||||
? [uiState.primary_action, ...uiState.secondary_actions]
|
||||
.map((action) => String(action?.code || '').trim())
|
||||
.filter(Boolean)
|
||||
: [];
|
||||
const stageNodesRaw = item.stage_nodes ?? item.stageNodes;
|
||||
const stageNodes = Array.isArray(stageNodesRaw)
|
||||
@@ -428,14 +430,12 @@ export function normalizeShippingProcessingProjection(
|
||||
userStage: readNullableString(item, 'user_stage', 'userStage') as ShippingProcessingProjection['userStage'],
|
||||
userCurrentGateCode: readNullableString(item, 'user_current_gate_code', 'userCurrentGateCode'),
|
||||
blockingReason: normalizeBlockingReason(item.blocking_reason ?? item.blockingReason),
|
||||
primaryAction: normalizePrimaryAction(item.primary_action ?? item.primaryAction),
|
||||
uiState: normalizeProcessingUiState(item.ui_state ?? item.uiState),
|
||||
primaryAction: uiState?.primary_action ?? null,
|
||||
uiState,
|
||||
facts: normalizeFacts(item.facts),
|
||||
userGroup: readNullableString(item, 'user_group', 'userGroup') as ShippingProcessingProjection['userGroup'],
|
||||
aggregateSummary: normalizeAggregateSummary(item.aggregate_summary ?? item.aggregateSummary),
|
||||
aggregateChildren: aggregateChildren?.length ? aggregateChildren : undefined,
|
||||
legacyStatus: readNullableString(item, 'legacy_status', 'legacyStatus'),
|
||||
legacyStage: readNullableString(item, 'legacy_stage', 'legacyStage'),
|
||||
hasFormalOt:
|
||||
(item.has_formal_ot as boolean | undefined) == null ? false : Boolean(item.has_formal_ot),
|
||||
inventoryPreparation: normalizeInventoryPreparation(
|
||||
@@ -453,11 +453,11 @@ function normalizeProcessGateSummary(raw: unknown): ShippingProcessGateUserSumma
|
||||
: null;
|
||||
}
|
||||
|
||||
/** 规范化单项后端 UI 裁决;缺失时返回 undefined 以保留旧响应兼容。 */
|
||||
/** 规范化单项后端 UI 裁决;缺失时不展示动作,禁止从旧顶层字段回退。 */
|
||||
function normalizeProcessingUiState(raw: unknown): ShippingProcessingProjection['uiState'] {
|
||||
if (!raw || typeof raw !== 'object') return undefined;
|
||||
const state = raw as Record<string, unknown>;
|
||||
const secondaryRaw = state.secondary_actions ?? state.secondaryActions;
|
||||
const secondaryRaw = state.secondary_actions;
|
||||
const secondaryActions = Array.isArray(secondaryRaw)
|
||||
? secondaryRaw
|
||||
.filter((item): item is Record<string, unknown> => Boolean(item && typeof item === 'object'))
|
||||
@@ -470,10 +470,10 @@ function normalizeProcessingUiState(raw: unknown): ShippingProcessingProjection[
|
||||
return {
|
||||
status: (readString(state, 'status', 'status') || 'running') as NonNullable<ShippingProcessingProjection['userStatus']>,
|
||||
stage: readString(state, 'stage', 'stage'),
|
||||
lifecycleStage: readString(state, 'lifecycle_stage', 'lifecycleStage') as ConversationProcessingUiState['lifecycleStage'],
|
||||
lifecycleEntries: normalizeLifecycleEntries(state.lifecycle_entries ?? state.lifecycleEntries),
|
||||
blocking_reason: normalizeBlockingReason(state.blocking_reason ?? state.blockingReason),
|
||||
primary_action: normalizePrimaryAction(state.primary_action ?? state.primaryAction),
|
||||
lifecycleStage: readString(state, 'lifecycle_stage') as ConversationProcessingUiState['lifecycleStage'],
|
||||
lifecycleEntries: normalizeLifecycleEntries(state.lifecycle_entries),
|
||||
blocking_reason: normalizeBlockingReason(state.blocking_reason),
|
||||
primary_action: normalizePrimaryAction(state.primary_action),
|
||||
secondary_actions: secondaryActions,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -21,7 +21,7 @@ export interface ShippingConversationContext {
|
||||
agentId: number,
|
||||
kb: string,
|
||||
files: ChatUploadFileSpec[],
|
||||
context?: { task_id?: string; batch_no?: string; display_query?: string },
|
||||
context?: { task_id?: string; display_query?: string },
|
||||
) => Promise<ChatMessageSendResult>;
|
||||
}
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
*/
|
||||
import {
|
||||
downloadWorkspaceShippingExportArchive as requestShippingExportArchive,
|
||||
workspaceShippingNoticeExportUrl,
|
||||
workspaceShippingExportUrl,
|
||||
workspaceShippingInventoryFileUrl,
|
||||
workspaceShippingLineInventoryFileUrl,
|
||||
@@ -16,6 +17,14 @@ export async function downloadWorkspaceShippingExcelFile(taskId: string): Promis
|
||||
await downloadWorkspaceShippingFile(workspaceShippingExportUrl(taskId), `${taskId}.xlsx`);
|
||||
}
|
||||
|
||||
/**
|
||||
* 按发货通知单号下载其唯一正式 Excel。
|
||||
* 新货代操作只能传 business_no;task_no 下载函数仅保留给尚未迁移的非货代工作流。
|
||||
*/
|
||||
export async function downloadWorkspaceShippingNoticeExcelFile(businessNo: string): Promise<void> {
|
||||
await downloadWorkspaceShippingFile(workspaceShippingNoticeExportUrl(businessNo), `${businessNo}.xlsx`);
|
||||
}
|
||||
|
||||
/**
|
||||
* 下载当前任务活动关联的库存快照。
|
||||
* 核心逻辑:浏览器只发起受控 URL;后端复核任务归属、active link 与物理文件,不按库存源猜测文件。
|
||||
@@ -60,8 +69,29 @@ async function downloadWorkspaceShippingFile(url: string, fallbackName: string):
|
||||
URL.revokeObjectURL(objectUrl);
|
||||
}
|
||||
|
||||
/** 批次 ZIP 下载只转发后端归档响应;选择和授权均不在前端重算。 */
|
||||
/** 多任务 ZIP 下载只转发后端归档响应;选择和授权均不在前端重算。 */
|
||||
export const downloadWorkspaceShippingExportArchive = (payload: {
|
||||
batch_no?: string;
|
||||
task_nos?: string[];
|
||||
}) => requestShippingExportArchive(payload);
|
||||
|
||||
/** 按多个 business_no 下载各自唯一 Excel 的 ZIP。 */
|
||||
export async function downloadWorkspaceShippingNoticeExportArchive(businessNos: string[]): Promise<void> {
|
||||
const response = await fetch('/api/workspace/shipping-notices/batch/export', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
|
||||
body: JSON.stringify({ business_nos: businessNos }),
|
||||
});
|
||||
if (!response.ok) {
|
||||
const body = await response.json().catch(() => ({}));
|
||||
throw new Error((body as { error?: string; message?: string }).error || response.statusText);
|
||||
}
|
||||
const blob = await response.blob();
|
||||
const objectUrl = URL.createObjectURL(blob);
|
||||
const anchor = document.createElement('a');
|
||||
anchor.href = objectUrl;
|
||||
anchor.download = 'shipping_notices.zip';
|
||||
document.body.appendChild(anchor);
|
||||
anchor.click();
|
||||
document.body.removeChild(anchor);
|
||||
URL.revokeObjectURL(objectUrl);
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
/**
|
||||
* features/chat/shipping/shippingStepper.spec.ts
|
||||
* 用途:验证发货通知四阶段 Stepper 只消费后端 UI State 投影。
|
||||
* 用途:验证发货通知五阶段 Stepper 只消费后端 UI State 投影。
|
||||
* 依赖:shippingStepper 纯函数、vitest。
|
||||
* 逻辑:后端 UI State 缺失时,前端仍需把关键人工介入态渲染为 blocked。
|
||||
*/
|
||||
@@ -12,19 +12,20 @@ import {
|
||||
} from './shippingStepper';
|
||||
|
||||
describe('shippingStepper', () => {
|
||||
it('renders exactly four stages from backend ui_state', () => {
|
||||
it('renders exactly five stages from backend ui_state', () => {
|
||||
const steps = resolveShippingWorkflowSteps({
|
||||
ui_state: {
|
||||
steps: [
|
||||
{ id: 'shipping-stage-1', code: 'intake_parse', label: '接收解析', status: 'completed' },
|
||||
{ id: 'shipping-stage-2', code: 'order_review', label: '订单复核', status: 'completed' },
|
||||
{ id: 'shipping-stage-3', code: 'fulfillment_prep', label: '通知准备', status: 'blocked' },
|
||||
{ id: 'shipping-stage-4', code: 'upload_complete', label: '通知完成', status: 'pending' },
|
||||
{ id: 'shipping-stage-4', code: 'freight_upload', label: '货代上传', status: 'pending' },
|
||||
{ id: 'shipping-stage-5', code: 'upload_complete', label: '通知完成', status: 'pending' },
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
expect(steps).toHaveLength(4);
|
||||
expect(steps).toHaveLength(5);
|
||||
expect(steps[2]?.status).toBe('blocked');
|
||||
});
|
||||
|
||||
@@ -33,17 +34,18 @@ describe('shippingStepper', () => {
|
||||
expect(normalizeShippingWorkflowSteps(null)).toEqual([]);
|
||||
});
|
||||
|
||||
it('maps technical processing stages into the four business stages', () => {
|
||||
it('maps technical processing stages into the five business stages', () => {
|
||||
const base = normalizeShippingWorkflowSteps([
|
||||
{ code: 'intake_parse', status: 'pending' },
|
||||
{ code: 'order_review', status: 'pending' },
|
||||
{ code: 'fulfillment_prep', status: 'pending' },
|
||||
{ code: 'freight_upload', status: 'pending' },
|
||||
{ code: 'upload_complete', status: 'pending' },
|
||||
]);
|
||||
const steps = applyShippingProcessingStageToSteps(base, {
|
||||
stage: 'inventory_matching',
|
||||
status: 'running',
|
||||
});
|
||||
expect(steps.map((step) => step.status)).toEqual(['completed', 'completed', 'current', 'pending']);
|
||||
expect(steps.map((step) => step.status)).toEqual(['completed', 'completed', 'current', 'pending', 'pending']);
|
||||
});
|
||||
});
|
||||
@@ -1,8 +1,8 @@
|
||||
/**
|
||||
* features/chat/shipping/shippingStepper.ts
|
||||
* 用途:基于后端 ui_state 投影渲染四阶段业务 Stepper。
|
||||
* 用途:基于后端 ui_state 投影渲染五阶段业务 Stepper。
|
||||
* 依赖:ShippingProcessingProjection(可选叠加)、shippingProcessingFulfillment;ShippingWorkflowStepper.vue 消费输出。
|
||||
* 逻辑:只消费后端 ui_state.steps 四阶段投影;缺失投影时 fail-closed。
|
||||
* 逻辑:只消费后端 ui_state.steps 五阶段投影;缺失投影时 fail-closed。
|
||||
*/
|
||||
import {
|
||||
FULFILLMENT_PROGRESS_NODES,
|
||||
@@ -32,6 +32,7 @@ export const SHIPPING_WORKFLOW_STEP_LABELS = [
|
||||
'chat.shippingNoticeUi.stage.intakeParse',
|
||||
'chat.shippingNoticeUi.stage.orderReview',
|
||||
'chat.shippingNoticeUi.stage.fulfillmentPrep',
|
||||
'chat.shippingNoticeUi.stage.freightUpload',
|
||||
'chat.shippingNoticeUi.stage.uploadComplete',
|
||||
] as const;
|
||||
|
||||
@@ -90,7 +91,7 @@ const PROCESSING_STAGE_INDEX_MAP: Record<string, number> = {
|
||||
inventory_matching: 2,
|
||||
excel_generating: 2,
|
||||
freight_uploading: 3,
|
||||
completed: 3,
|
||||
completed: 4,
|
||||
};
|
||||
|
||||
/**
|
||||
|
||||
@@ -34,12 +34,10 @@ export function resolveShippingChatTurn(
|
||||
/**
|
||||
* 构造货代领域 refs,键名与 agent_runtime_context.refs 对齐。
|
||||
*/
|
||||
export function buildShippingTurnRefs(taskNo: string, batchNo?: string): Record<string, string> {
|
||||
export function buildShippingTurnRefs(taskNo: string): Record<string, string> {
|
||||
const refs: Record<string, string> = {};
|
||||
const task = String(taskNo || '').trim().toUpperCase();
|
||||
const batch = String(batchNo || '').trim();
|
||||
if (task) refs.task_no = task;
|
||||
if (batch) refs.batch_no = batch;
|
||||
return refs;
|
||||
}
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
* features/chat/shipping/shippingUploadPrompt.ts
|
||||
* 用途:通知上传后提示语构建、文件格式识别与临时库存声明判断。
|
||||
* 依赖:无;useChatShippingUploadHandler 在上传成功后调用。
|
||||
* 逻辑:按 checkpoint 生成不同 follow-up 提示;通知建批后触发 Dify 完整动态订单抽取。
|
||||
* 逻辑:按提交结果生成 follow-up 提示;通知进入 Intake 后触发完整动态订单抽取。
|
||||
*/
|
||||
import i18n from '@/i18n';
|
||||
|
||||
@@ -10,17 +10,12 @@ import i18n from '@/i18n';
|
||||
* 根据上传 API 响应 checkpoint 生成发给 Agent 的 follow-up 提示语。
|
||||
*/
|
||||
/**
|
||||
* 根据通知建批 API 响应生成发给 Dify 的 follow-up 提示语(触发完整订单抽取链)。
|
||||
* 根据通知提交 API 响应生成发给 Dify 的 follow-up 提示语(触发完整订单抽取链)。
|
||||
*/
|
||||
export function buildShippingNoticeUploadPrompt(
|
||||
result: Record<string, unknown> | null | undefined,
|
||||
options?: { fileCount?: number; fileName?: string },
|
||||
): string {
|
||||
const batchNo = String(
|
||||
(result?.batch_no as string | undefined)
|
||||
|| ((result?.data as { batch?: { batch_no?: string } } | undefined)?.batch?.batch_no)
|
||||
|| '',
|
||||
).trim();
|
||||
const taskId = String(
|
||||
((result?.data as { focus_task?: { task_no?: string } } | undefined)?.focus_task?.task_no)
|
||||
|| (result?.task_id as string | undefined)
|
||||
@@ -39,9 +34,6 @@ export function buildShippingNoticeUploadPrompt(
|
||||
? String(i18n.global.t('chat.shippingNoticePrompt.notice.fileLabelMulti', { fileCount }))
|
||||
: String(i18n.global.t('chat.shippingNoticePrompt.notice.fileLabelDefault')));
|
||||
const parts = [String(i18n.global.t('chat.shippingNoticePrompt.notice.uploadedPrefix', { fileLabel }))];
|
||||
if (batchNo) {
|
||||
parts.push(String(i18n.global.t('chat.shippingNoticePrompt.notice.batchLabel', { batchNo })));
|
||||
}
|
||||
if (taskId) {
|
||||
parts.push(String(i18n.global.t('chat.shippingNoticePrompt.notice.taskLabel', { taskId })));
|
||||
}
|
||||
|
||||
@@ -22,7 +22,6 @@ const createContext = (
|
||||
isThinking: ref(false),
|
||||
currentAgentId: computed(() => 42),
|
||||
getActiveShippingTaskId: () => 'SN-ACTIVE-001',
|
||||
getActiveShippingBatchNo: () => 'BATCH-001',
|
||||
messages: ref([]),
|
||||
sendShippingMenuMessage: vi.fn(async () => undefined),
|
||||
openShippingInventoryPicker: vi.fn((_taskId?: string) => true),
|
||||
|
||||
@@ -14,6 +14,7 @@ export interface ShippingMenuHandlerContext {
|
||||
getActiveShippingTaskId: () => string;
|
||||
messages: Ref<ChatMessage[]>;
|
||||
sendShippingMenuMessage: (message: string) => Promise<void>;
|
||||
openShippingInventoryPicker: (taskId?: string) => boolean;
|
||||
openShippingNoticePicker: (taskId?: string) => boolean;
|
||||
openShippingCustomerDialog: (taskId: string) => Promise<void>;
|
||||
executeShippingDecision: (
|
||||
@@ -76,6 +77,10 @@ export function createShippingMenuHandlers(ctx: ShippingMenuHandlerContext) {
|
||||
ctx.openShippingNoticePicker(resolveTaskId());
|
||||
return;
|
||||
}
|
||||
if (action.id === 'upload_inventory_file') {
|
||||
ctx.openShippingInventoryPicker(resolveTaskId());
|
||||
return;
|
||||
}
|
||||
if (action.id && [
|
||||
'freeze_order', 'match_inventory', 'rematch',
|
||||
'generate_excel', 'retry_upload', 'mark_manual_uploaded', 'reparse_inventory',
|
||||
|
||||
@@ -21,18 +21,18 @@ describe('useChatShippingRefresh', () => {
|
||||
getWorkspaceShippingTaskUiState.mockReset();
|
||||
});
|
||||
|
||||
it('prefers current batch focus task over other explicit anchors', () => {
|
||||
it('prefers active task over message, resolved and query anchors', () => {
|
||||
expect(resolvePreferredShippingTaskId({
|
||||
batchTaskId: 'sn-batch-001',
|
||||
activeTaskId: 'sn-active-001',
|
||||
messageTaskId: 'sn-message-001',
|
||||
resolvedTaskId: 'sn-resolved-001',
|
||||
queryTaskId: 'sn-query-001',
|
||||
})).toBe('SN-BATCH-001');
|
||||
})).toBe('SN-ACTIVE-001');
|
||||
});
|
||||
|
||||
it('returns empty string when no explicit task anchor is available', () => {
|
||||
expect(resolvePreferredShippingTaskId({
|
||||
batchTaskId: '',
|
||||
activeTaskId: '',
|
||||
messageTaskId: '',
|
||||
resolvedTaskId: '',
|
||||
queryTaskId: '',
|
||||
@@ -42,7 +42,6 @@ describe('useChatShippingRefresh', () => {
|
||||
it('syncs ui_state for notifications without attaching chat action buttons', async () => {
|
||||
getWorkspaceShippingTaskUiState.mockResolvedValue({
|
||||
task_no: 'SN-FOCUS-B',
|
||||
batch_no: 'SB-FOCUS-001',
|
||||
checkpoint: 'ready_export',
|
||||
match_status: 'matched',
|
||||
review_status: null,
|
||||
@@ -70,7 +69,7 @@ describe('useChatShippingRefresh', () => {
|
||||
const messages = ref([
|
||||
{
|
||||
role: 'assistant' as const,
|
||||
content: '请继续处理当前批次',
|
||||
content: '请继续处理当前任务',
|
||||
shipping_actions: [
|
||||
{
|
||||
id: 'old-action',
|
||||
@@ -89,7 +88,7 @@ describe('useChatShippingRefresh', () => {
|
||||
isThinking: ref(false),
|
||||
resolvedShippingTaskId,
|
||||
shippingTaskIdFromQuery: computed(() => ''),
|
||||
getActiveBatchTaskId: () => 'SN-FOCUS-B',
|
||||
getActiveShippingTaskId: () => 'SN-FOCUS-B',
|
||||
});
|
||||
|
||||
await refreshShippingActions();
|
||||
@@ -103,7 +102,6 @@ describe('useChatShippingRefresh', () => {
|
||||
it('clears legacy shipping_actions even when api returns action_buttons', async () => {
|
||||
getWorkspaceShippingTaskUiState.mockResolvedValue({
|
||||
task_no: 'SN-SOURCE-001',
|
||||
batch_no: 'SB-SOURCE-001',
|
||||
checkpoint: 'ready_export',
|
||||
match_status: 'matched',
|
||||
review_status: null,
|
||||
@@ -158,7 +156,7 @@ describe('useChatShippingRefresh', () => {
|
||||
isThinking: ref(false),
|
||||
resolvedShippingTaskId: ref('SN-SOURCE-001'),
|
||||
shippingTaskIdFromQuery: computed(() => ''),
|
||||
getActiveBatchTaskId: () => 'SN-SOURCE-001',
|
||||
getActiveShippingTaskId: () => 'SN-SOURCE-001',
|
||||
});
|
||||
|
||||
await refreshShippingActions();
|
||||
@@ -181,7 +179,7 @@ describe('useChatShippingRefresh', () => {
|
||||
isThinking: ref(false),
|
||||
resolvedShippingTaskId: ref(''),
|
||||
shippingTaskIdFromQuery: computed(() => ''),
|
||||
getActiveBatchTaskId: () => '',
|
||||
getActiveShippingTaskId: () => '',
|
||||
});
|
||||
|
||||
await refreshShippingActions();
|
||||
|
||||
@@ -19,25 +19,27 @@ export interface ShippingRefreshContext {
|
||||
isThinking: Ref<boolean>;
|
||||
resolvedShippingTaskId: Ref<string>;
|
||||
shippingTaskIdFromQuery: ComputedRef<string>;
|
||||
getActiveBatchTaskId: () => string;
|
||||
getActiveShippingTaskId: () => string;
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析当前聊天页最可靠的发货任务编号。
|
||||
*
|
||||
* 核心逻辑:优先使用批次当前焦点任务,其次才回退到消息内嵌任务号、已解析状态和路由参数;
|
||||
* 核心逻辑:优先使用消息内嵌任务号,再回退到已解析状态和路由参数;
|
||||
* 禁止再按 conversation 标题“猜”一票,避免多票会话把状态挂错任务。
|
||||
* @param params - 当前聊天页中可用的任务定位线索
|
||||
* @returns 可信的任务编号;无法明确定位时返回空字符串
|
||||
*/
|
||||
export function resolvePreferredShippingTaskId(params: {
|
||||
activeTaskId?: string | null;
|
||||
batchTaskId?: string | null;
|
||||
messageTaskId?: string | null;
|
||||
resolvedTaskId?: string | null;
|
||||
queryTaskId?: string | null;
|
||||
}) {
|
||||
return String(
|
||||
params.batchTaskId
|
||||
params.activeTaskId
|
||||
|| params.batchTaskId
|
||||
|| params.messageTaskId
|
||||
|| params.resolvedTaskId
|
||||
|| params.queryTaskId
|
||||
@@ -71,7 +73,7 @@ export function createShippingActionsRefresher(ctx: ShippingRefreshContext) {
|
||||
const msgs = ctx.messages.value;
|
||||
if (!msgs.length) return;
|
||||
const taskId = resolvePreferredShippingTaskId({
|
||||
batchTaskId: ctx.getActiveBatchTaskId(),
|
||||
activeTaskId: ctx.getActiveShippingTaskId(),
|
||||
messageTaskId: findLatestShippingTaskId(msgs),
|
||||
resolvedTaskId: ctx.resolvedShippingTaskId.value,
|
||||
queryTaskId: ctx.shippingTaskIdFromQuery.value,
|
||||
|
||||
@@ -19,7 +19,6 @@ const createContext = (
|
||||
attachments: ref([]),
|
||||
shippingAutoFlowRequested: ref(true),
|
||||
resolvedShippingTaskId: ref(''),
|
||||
getActiveShippingBatchNo: () => '',
|
||||
currentAgentId: computed(() => 1),
|
||||
selectedKb: ref(''),
|
||||
attachmentPolicy: computed(() => ({ anyEnabled: true })),
|
||||
@@ -47,7 +46,6 @@ const createContext = (
|
||||
getParsedIntakeNos: () => [],
|
||||
startOrderExtractionRun: vi.fn(async () => true),
|
||||
applyShippingMessageRecovery: vi.fn(async () => false),
|
||||
applyShippingBatchSnapshot: vi.fn(() => false),
|
||||
syncShippingConversationWorkspace: vi.fn(async () => true),
|
||||
refreshShippingActions: vi.fn(async () => undefined),
|
||||
shippingSuggestedPrompt: computed(() => ''),
|
||||
@@ -254,7 +252,6 @@ describe('useChatShippingSendHandler', () => {
|
||||
|
||||
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);
|
||||
|
||||
|
||||
@@ -33,7 +33,6 @@ export interface ShippingSendHandlerContext {
|
||||
attachments: Ref<PendingAttachment[]>;
|
||||
shippingAutoFlowRequested: Ref<boolean>;
|
||||
resolvedShippingTaskId: Ref<string>;
|
||||
getActiveShippingBatchNo: () => string;
|
||||
currentAgentId: ComputedRef<number>;
|
||||
selectedKb: Ref<string>;
|
||||
attachmentPolicy: ComputedRef<{ anyEnabled: boolean }>;
|
||||
@@ -45,7 +44,7 @@ export interface ShippingSendHandlerContext {
|
||||
agentId: number,
|
||||
kb: string,
|
||||
files: ChatUploadFileSpec[],
|
||||
context?: { task_id?: string; batch_no?: string; shipping_temporary_inventory_asset_no?: string; shipping_temporary_inventory_session_no?: string; display_query?: string },
|
||||
context?: { task_id?: string; shipping_temporary_inventory_asset_no?: string; shipping_temporary_inventory_session_no?: string; display_query?: string },
|
||||
hooks?: SendMessageLifecycleHooks,
|
||||
) => Promise<ChatMessageSendResult>;
|
||||
buildFileSpecsForSend: () => Promise<ChatUploadFileSpec[]>;
|
||||
@@ -72,8 +71,6 @@ export interface ShippingSendHandlerContext {
|
||||
uploadBatchId?: string,
|
||||
) => Promise<boolean>;
|
||||
applyShippingMessageRecovery?: (message: ChatMessage) => Promise<boolean>;
|
||||
applyShippingBatchSnapshot?: (message: ChatMessage) => boolean;
|
||||
syncShippingConversationWorkspace: (options?: { preferLatest?: boolean }) => Promise<boolean>;
|
||||
refreshShippingActions: () => Promise<void>;
|
||||
shippingSuggestedPrompt: ComputedRef<string>;
|
||||
isShippingShortageQueryIntent: (text: string) => boolean;
|
||||
|
||||
@@ -7,9 +7,7 @@
|
||||
import { computed, ref } from 'vue';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import {
|
||||
clearPendingNoticeBatchRetry,
|
||||
createShippingUploadHandlers,
|
||||
onNoticeBatchConversationChanging,
|
||||
resetShippingNoticeBatchSubmitStateForTests,
|
||||
type ShippingUploadHandlerContext,
|
||||
} from './useChatShippingUploadHandler';
|
||||
@@ -47,9 +45,6 @@ const createContext = (
|
||||
pendingShippingNoticeTaskId: ref(''),
|
||||
pendingShippingInventoryFile: ref(null),
|
||||
resolvedShippingTaskId: ref(''),
|
||||
resolvedShippingBatchNo: ref(''),
|
||||
shippingBatchSummary: ref(null),
|
||||
shippingBatchTasks: ref([]),
|
||||
shippingInventorySelectionActive: ref(false),
|
||||
shippingInventorySelectionTaskId: ref(''),
|
||||
getActiveShippingTaskId: () => 'SN-ACTIVE-001',
|
||||
@@ -222,12 +217,6 @@ describe('useChatShippingUploadHandler', () => {
|
||||
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', () => {
|
||||
const noticeClick = vi.fn();
|
||||
const warning = vi.fn();
|
||||
|
||||
@@ -6,7 +6,6 @@
|
||||
* 单票覆盖仍经 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 { buildShippingReplaceNoticeTurn, buildShippingTurnRefs } from './shippingTurnActions';
|
||||
@@ -18,25 +17,6 @@ import type { ComputedRef, Ref } from 'vue';
|
||||
|
||||
let noticeBatchSubmitting = false;
|
||||
|
||||
/**
|
||||
* 显式清理待重试建批幂等状态(co8 后建批已下线,保留空实现供会话切换调用方兼容)。
|
||||
*/
|
||||
export function clearPendingNoticeBatchRetry(): void {
|
||||
/* no-op: shipping_batches 已 DROP */
|
||||
}
|
||||
|
||||
/**
|
||||
* 用户主动切换会话时的钩子(co8 后无幂等键可清)。
|
||||
* @param _nextId - 新会话 ID
|
||||
* @param _prevId - 旧会话 ID
|
||||
*/
|
||||
export function onNoticeBatchConversationChanging(
|
||||
_nextId: string,
|
||||
_prevId?: string | null,
|
||||
): void {
|
||||
/* no-op */
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询发货通知建批是否正在提交中(供发送拦截器消费重复点击)。
|
||||
*/
|
||||
@@ -47,7 +27,6 @@ export function isShippingNoticeBatchSubmitting(): boolean {
|
||||
/** 单测重置模块级建批提交状态。 */
|
||||
export function resetShippingNoticeBatchSubmitStateForTests(): void {
|
||||
noticeBatchSubmitting = false;
|
||||
clearPendingNoticeBatchRetry();
|
||||
}
|
||||
|
||||
export interface ShippingUploadHandlerContext {
|
||||
@@ -62,9 +41,6 @@ export interface ShippingUploadHandlerContext {
|
||||
pendingShippingNoticeTaskId: Ref<string>;
|
||||
pendingShippingInventoryFile: Ref<File | null>;
|
||||
resolvedShippingTaskId: Ref<string>;
|
||||
resolvedShippingBatchNo: Ref<string>;
|
||||
shippingBatchSummary: Ref<unknown | null>;
|
||||
shippingBatchTasks: Ref<ShippingTaskSummary[]>;
|
||||
shippingInventorySelectionActive: Ref<boolean>;
|
||||
shippingInventorySelectionTaskId: Ref<string>;
|
||||
getActiveShippingTaskId: () => string;
|
||||
@@ -160,11 +136,9 @@ export function createShippingUploadHandlers(ctx: ShippingUploadHandlerContext)
|
||||
|
||||
const syncBatchContextFromTurnMessage = (assistantMsg: ChatMessage) => {
|
||||
const payload = assistantMsg.payload && typeof assistantMsg.payload === 'object'
|
||||
? assistantMsg.payload as { batch_no?: string; task_no?: string; orchestrator_started?: boolean }
|
||||
? assistantMsg.payload as { task_no?: string; orchestrator_started?: boolean }
|
||||
: {};
|
||||
const batchNo = String(payload.batch_no || assistantMsg.shipping_ui_state?.batch_no || '').trim();
|
||||
const taskId = String(payload.task_no || assistantMsg.shipping_ui_state?.task_no || '').trim();
|
||||
if (batchNo) ctx.resolvedShippingBatchNo.value = batchNo;
|
||||
if (taskId) ctx.resolvedShippingTaskId.value = taskId;
|
||||
};
|
||||
|
||||
|
||||
@@ -201,6 +201,42 @@ describe('useShippingNoticeWorkflow', () => {
|
||||
ctl.stop();
|
||||
});
|
||||
|
||||
it('uses summary PDF leaves as the minimal live work items for the batch center', async () => {
|
||||
api.getShippingProcessing.mockResolvedValue({
|
||||
conversation_id: 'conv-1',
|
||||
work_items: [{
|
||||
workItemType: 'order_task', workItemNo: 'DOCUMENT:1', rootOrderTaskNo: 'OT-1',
|
||||
sourceType: 'direct_pdf', status: 'processing', stage: 'document_parsing',
|
||||
sourceSummary: { documentId: 1, filename: 'po.pdf', documentCount: 1 },
|
||||
}],
|
||||
conversation_processing: buildProcessing(),
|
||||
});
|
||||
const ctl = useShippingNoticeWorkflow({ conversationId: ref('conv-1') });
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
await Promise.resolve();
|
||||
|
||||
expect(ctl.processingWorkItems.value[0]?.sourceSummary.filename).toBe('po.pdf');
|
||||
ctl.stop();
|
||||
});
|
||||
|
||||
it('applies a current conversation response that completes after 10 seconds', async () => {
|
||||
const pending = deferred<ReturnType<typeof buildUnifiedProcessing>>();
|
||||
api.getShippingProcessing.mockImplementation(() => pending.promise);
|
||||
|
||||
const ctl = useShippingNoticeWorkflow({ conversationId: ref('conv-1') });
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
// API 层拥有共享请求的 30 秒超时;10 秒后当前会话不能先把消费者标为取消。
|
||||
await vi.advanceTimersByTimeAsync(10_001);
|
||||
pending.resolve(buildUnifiedProcessing('conv-1'));
|
||||
await Promise.resolve();
|
||||
await nextTick();
|
||||
|
||||
expect(ctl.processing.value?.conversation_id).toBe('conv-1');
|
||||
expect(ctl.initialLoading.value).toBe(false);
|
||||
expect(ctl.error.value).toBeNull();
|
||||
ctl.stop();
|
||||
});
|
||||
|
||||
it('records recoverable error without throwing', async () => {
|
||||
const conversationId = ref('conv-1');
|
||||
const ctl = useShippingNoticeWorkflow({ conversationId });
|
||||
@@ -243,7 +279,7 @@ describe('useShippingNoticeWorkflow', () => {
|
||||
ctl.stop();
|
||||
});
|
||||
|
||||
it('uses unified work_items as the sole processing read source', async () => {
|
||||
it('does not rebuild conversation processing from work_items without status_groups', async () => {
|
||||
api.getShippingProcessing.mockResolvedValue({
|
||||
conversation_id: 'conv-1',
|
||||
work_items: [buildOrderTaskWorkItem('OT-UNIFIED', {
|
||||
@@ -265,12 +301,12 @@ describe('useShippingNoticeWorkflow', () => {
|
||||
await Promise.resolve();
|
||||
|
||||
expect(api.getShippingProcessing).toHaveBeenCalled();
|
||||
expect(ctl.processingWorkItems.value).toHaveLength(1);
|
||||
expect(ctl.processing.value?.needs_action[0]?.user_task_no).toBe('OT-UNIFIED');
|
||||
expect(ctl.processingWorkItems.value).toHaveLength(0);
|
||||
expect(ctl.processing.value).toBeNull();
|
||||
ctl.stop();
|
||||
});
|
||||
|
||||
it('preserves previous order_task work_items when stabilizer keeps previous projection', async () => {
|
||||
it('does not retain a legacy work_items-derived projection across sparse responses', async () => {
|
||||
api.getShippingProcessing
|
||||
.mockResolvedValueOnce({
|
||||
conversation_id: 'conv-1',
|
||||
@@ -310,21 +346,17 @@ describe('useShippingNoticeWorkflow', () => {
|
||||
await nextTick();
|
||||
await Promise.resolve();
|
||||
|
||||
expect(ctl.processing.value?.processing[0]?.user_task_no).toBe('OT-STABLE');
|
||||
expect(ctl.processingWorkItems.value[0]?.workItemType).toBe('order_task');
|
||||
expect(ctl.processing.value).toBeNull();
|
||||
|
||||
await vi.advanceTimersByTimeAsync(2000);
|
||||
await nextTick();
|
||||
await Promise.resolve();
|
||||
|
||||
expect(ctl.processing.value?.processing[0]?.user_task_no).toBe('OT-STABLE');
|
||||
expect(ctl.processingWorkItems.value).toHaveLength(1);
|
||||
expect(ctl.processingWorkItems.value[0]?.workItemType).toBe('order_task');
|
||||
expect(ctl.processingWorkItems.value[0]?.workItemNo).toBe('OT-STABLE');
|
||||
expect(ctl.processing.value).toBeNull();
|
||||
ctl.stop();
|
||||
});
|
||||
|
||||
it('aggregates sibling EML OT work_items into one highest-attention Intake card', async () => {
|
||||
it('does not aggregate sibling work_items in the browser when status_groups is absent', async () => {
|
||||
api.getShippingProcessing.mockResolvedValue({
|
||||
conversation_id: 'conv-1',
|
||||
work_items: [
|
||||
@@ -409,15 +441,8 @@ describe('useShippingNoticeWorkflow', () => {
|
||||
await nextTick();
|
||||
await Promise.resolve();
|
||||
|
||||
expect(ctl.processing.value?.needs_action.map((t) => t.user_task_no)).toEqual(['OT-ROOT']);
|
||||
expect(ctl.processing.value?.processing).toEqual([]);
|
||||
expect(ctl.processing.value?.needs_action[0]?.aggregateSummary).toMatchObject({
|
||||
intakeNo: 'SNI-1',
|
||||
total: 2,
|
||||
processing: 1,
|
||||
});
|
||||
expect(ctl.processing.value?.focused_task_no).toBe('OT-ROOT');
|
||||
expect(ctl.processing.value?.recent_task_no).toBe('OT-SIBLING');
|
||||
expect(ctl.processing.value).toBeNull();
|
||||
expect(ctl.processingWorkItems.value).toEqual([]);
|
||||
ctl.stop();
|
||||
});
|
||||
|
||||
@@ -436,7 +461,7 @@ describe('useShippingNoticeWorkflow', () => {
|
||||
await Promise.resolve();
|
||||
|
||||
expect(api.getShippingProcessing).toHaveBeenCalledTimes(2);
|
||||
expect(ctl.processing.value?.needs_action[0]?.user_task_no).toBe('OT-conv-1');
|
||||
expect(ctl.processing.value?.status_groups?.waiting_human[0]?.user_task_no).toBe('OT-conv-1');
|
||||
expect(ctl.error.value).toBeNull();
|
||||
ctl.stop();
|
||||
});
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
* 依赖:shipping.api getWorkspaceShippingProcessing / focus·viewed、Vue 响应式、BusinessError。
|
||||
* 逻辑:由 ChatViewContent / ShippingWorkflowTimeline 消费;仅读 shipping-processing;
|
||||
* focus/viewed 写路径优先应用响应中的 work_items;
|
||||
* 前台 2s / 后台 8s;请求 10s AbortController 超时;失败指数退避至 8s;
|
||||
* 前台 2s / 后台 8s;共享请求的超时由 API 层统一管理;会话切换/卸载才取消当前消费者;失败指数退避至 8s;
|
||||
* 分层轮询:仅系统处理中 2s 轮询;外部 Run 轮询不会在待人工处理时反复唤醒本读接口;
|
||||
* 区分 initialLoading / manualRefreshing / polling 三种 loading 态;
|
||||
* 语义签名比较:业务状态未变化时不替换投影对象,防止按钮闪烁与 DOM 重建。
|
||||
@@ -40,7 +40,6 @@ const FIRST_ACTIVE_POLL_MS = 2000;
|
||||
const MID_ACTIVE_POLL_MS = 5000;
|
||||
const LONG_ACTIVE_POLL_MS = 10000;
|
||||
const BACKGROUND_POLL_MS = 30000;
|
||||
const REQUEST_TIMEOUT_MS = 10000;
|
||||
const MAX_BACKOFF_MS = 30000;
|
||||
const SNAPSHOT_CACHE_LIMIT = 20;
|
||||
|
||||
@@ -137,7 +136,7 @@ export function shouldContinueProcessingPolling(
|
||||
processing?: ConversationProcessingProjection | null,
|
||||
): boolean {
|
||||
const processingCount = Number(
|
||||
processing?.summary?.processing || processing?.processing?.length || 0,
|
||||
processing?.summary?.processing ?? processing?.status_groups?.processing.length ?? 0,
|
||||
);
|
||||
return processingCount > 0;
|
||||
}
|
||||
@@ -200,10 +199,22 @@ export function useShippingNoticeWorkflow(
|
||||
return JSON.stringify(items.map((item) => ({
|
||||
no: item.workItemNo,
|
||||
type: item.workItemType,
|
||||
status: item.uiState?.status ?? item.userStatus ?? item.status,
|
||||
stage: item.uiState?.stage ?? item.userStage ?? item.stage,
|
||||
gate: item.uiState?.blocking_reason?.code ?? item.blockingReason?.code ?? null,
|
||||
action: item.uiState?.primary_action?.code ?? item.primaryAction?.code ?? null,
|
||||
status: item.uiState?.status ?? null,
|
||||
stage: item.uiState?.stage ?? null,
|
||||
runNo: item.runNo ?? null,
|
||||
caseNo: item.caseNo ?? null,
|
||||
gate: item.uiState?.blocking_reason?.code ?? null,
|
||||
action: (() => {
|
||||
const action = item.uiState?.primary_action ?? null;
|
||||
return action
|
||||
? {
|
||||
code: action.code,
|
||||
executionMode: action.executionMode ?? null,
|
||||
targetSurface: action.targetSurface ?? null,
|
||||
targetLifecycleStage: action.targetLifecycleStage ?? null,
|
||||
}
|
||||
: null;
|
||||
})(),
|
||||
lifecycleEntries: item.uiState?.lifecycleEntries?.map((entry) => ({
|
||||
code: entry.code,
|
||||
state: entry.state,
|
||||
@@ -215,6 +226,16 @@ export function useShippingNoticeWorkflow(
|
||||
no: child.workItemNo,
|
||||
status: child.uiState?.status ?? child.userStatus ?? child.status,
|
||||
stage: child.uiState?.stage ?? child.userStage ?? child.stage,
|
||||
runNo: child.runNo ?? null,
|
||||
caseNo: child.caseNo ?? null,
|
||||
primaryAction: child.uiState?.primary_action
|
||||
? {
|
||||
code: child.uiState.primary_action.code,
|
||||
executionMode: child.uiState.primary_action.executionMode ?? null,
|
||||
targetSurface: child.uiState.primary_action.targetSurface ?? null,
|
||||
targetLifecycleStage: child.uiState.primary_action.targetLifecycleStage ?? null,
|
||||
}
|
||||
: null,
|
||||
lifecycleEntries: child.uiState?.lifecycleEntries?.map((entry) => ({
|
||||
code: entry.code,
|
||||
state: entry.state,
|
||||
@@ -292,20 +313,22 @@ export function useShippingNoticeWorkflow(
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建带超时的 AbortController。
|
||||
* 创建当前会话代际的 AbortController。
|
||||
*
|
||||
* 共享 API 请求自行持有 30 秒超时,不能在此再设更短的消费者超时:
|
||||
* 否则底层请求虽仍可成功返回,当前代际会因 signal 已 aborted 而丢弃响应,
|
||||
* 导致首屏永久停留在权威投影骨架。这里仅用于会话切换或组件卸载的真实取消。
|
||||
*/
|
||||
function createRequestController(): AbortController {
|
||||
requestController?.abort();
|
||||
const controller = new AbortController();
|
||||
requestController = controller;
|
||||
const timeout = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
|
||||
controller.signal.addEventListener('abort', () => clearTimeout(timeout), { once: true });
|
||||
return controller;
|
||||
}
|
||||
|
||||
/**
|
||||
* 仅拉取统一 shipping-processing 投影。
|
||||
* 核心逻辑:后端 status_groups 存在时直接使用;仅旧响应缺状态组才由 work_items 合成;
|
||||
* 核心逻辑:只消费后端 status_groups;
|
||||
* 同会话在途请求合并;跨会话请求中止,且只有最新一代可回写页面数据;
|
||||
* 语义签名相同则不替换 projection 对象,避免 DOM 重建与按钮闪烁。
|
||||
*
|
||||
@@ -450,7 +473,7 @@ export function useShippingNoticeWorkflow(
|
||||
|
||||
/**
|
||||
* 将 focus/viewed/submit 写路径响应应用到本地 processing 与 work_items。
|
||||
* 核心逻辑:有 work_items 时用统一合成;否则仅回写 processing 兼容块;
|
||||
* 核心逻辑:只回写后端返回的 status_groups;work_items 仅提供最小附件叶子。
|
||||
* 每次回写后更新语义签名,避免下一轮轮询误判为「无变化」。
|
||||
*/
|
||||
function applyMutationProcessingResponse(response: {
|
||||
@@ -458,12 +481,12 @@ export function useShippingNoticeWorkflow(
|
||||
work_items?: unknown[];
|
||||
}): void {
|
||||
const workItems = Array.isArray(response.work_items) ? response.work_items : [];
|
||||
if (workItems.length > 0) {
|
||||
const nextProjection = resolveConversationProcessingFromUnified(
|
||||
workItems as typeof processingWorkItems.value,
|
||||
response.processing ?? null,
|
||||
processing.value,
|
||||
);
|
||||
const nextProjection = resolveConversationProcessingFromUnified(
|
||||
workItems as typeof processingWorkItems.value,
|
||||
response.processing ?? null,
|
||||
processing.value,
|
||||
);
|
||||
if (nextProjection) {
|
||||
processingWorkItems.value = resolveStableWorkItems(
|
||||
workItems as typeof processingWorkItems.value,
|
||||
processing.value,
|
||||
@@ -476,13 +499,6 @@ export function useShippingNoticeWorkflow(
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (response.processing) {
|
||||
const nextKey = buildProcessingSemanticKey(response.processing);
|
||||
if (nextKey !== lastSemanticKey) {
|
||||
processing.value = response.processing;
|
||||
lastSemanticKey = nextKey;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -136,7 +136,7 @@ describe('useShippingOrderExtractionRuns lifecycle', () => {
|
||||
harness.runs.stopPolling();
|
||||
});
|
||||
|
||||
it('merges sibling Runs from one upload batch into one chat status card', async () => {
|
||||
it('keeps the submitted Run card independent from sibling Runs in the same upload batch', async () => {
|
||||
const first = Object.assign(run({
|
||||
run_no: 'SNER-BATCH-1',
|
||||
conversation_id: 'conv-batch',
|
||||
@@ -191,7 +191,6 @@ describe('useShippingOrderExtractionRuns lifecycle', () => {
|
||||
operation_id: 'op-batch',
|
||||
});
|
||||
api.getRun.mockResolvedValue(first);
|
||||
api.listRuns.mockResolvedValue({ items: [first, second] });
|
||||
const harness = createHarness();
|
||||
|
||||
await harness.runs.startRun('', ['SNI-BATCH-1', 'SNI-BATCH-2'], [], 'upload-batch-1');
|
||||
@@ -199,14 +198,14 @@ describe('useShippingOrderExtractionRuns lifecycle', () => {
|
||||
const cards = harness.messages.value.filter((message) => message.shipping_order_extraction_state);
|
||||
expect(cards).toHaveLength(1);
|
||||
expect(cards[0]?.shipping_order_extraction_state?.summary).toMatchObject({
|
||||
totalDocuments: 2,
|
||||
totalDocuments: 1,
|
||||
pendingDocuments: 1,
|
||||
processingDocuments: 1,
|
||||
processingDocuments: 0,
|
||||
});
|
||||
expect(cards[0]?.shipping_order_extraction_state?.documents?.map((item) => item.fileName)).toEqual([
|
||||
'notice-a.pdf',
|
||||
'notice-b.pdf',
|
||||
]);
|
||||
expect(api.listRuns).not.toHaveBeenCalled();
|
||||
harness.runs.stopPolling();
|
||||
});
|
||||
|
||||
@@ -290,25 +289,27 @@ describe('useShippingOrderExtractionRuns lifecycle', () => {
|
||||
api.getRun.mockReturnValueOnce(pending.promise);
|
||||
const harness = createHarness();
|
||||
harness.conversationId.value = 'conv-old';
|
||||
await harness.runs.restoreForConversation('conv-old');
|
||||
await vi.advanceTimersByTimeAsync(1000);
|
||||
const oldRestore = harness.runs.restoreForConversation('conv-old');
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
expect(api.getRun).toHaveBeenCalledWith('SNER-OLD', expect.any(AbortSignal));
|
||||
|
||||
harness.conversationId.value = 'conv-new';
|
||||
await expect(harness.runs.restoreForConversation('conv-new')).resolves.toBeUndefined();
|
||||
pending.resolve(run({ run_no: 'SNER-OLD', conversation_id: 'conv-old', status: 'completed' }));
|
||||
await Promise.resolve();
|
||||
await oldRestore;
|
||||
expect(harness.runs.getActiveRunNo()).toBe('');
|
||||
expect(harness.messages.value).toHaveLength(1);
|
||||
expect(harness.messages.value[0]?.shipping_order_extraction_state?.status).toBe('processing');
|
||||
expect(harness.messages.value).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('notifies session work items refresh after restoring a terminal run', async () => {
|
||||
api.listRuns.mockResolvedValue({
|
||||
items: [run({ run_no: 'SNER-DONE', status: 'completed', phase: 'completed' })],
|
||||
});
|
||||
const summary = run({ run_no: 'SNER-DONE', status: 'completed', phase: 'completed' });
|
||||
const detail = run({ run_no: 'SNER-DONE', status: 'completed', phase: 'completed' });
|
||||
api.listRuns.mockResolvedValue({ items: [summary] });
|
||||
api.getRun.mockResolvedValue(detail);
|
||||
const harness = createHarness();
|
||||
harness.conversationId.value = 'conv-1';
|
||||
await harness.runs.restoreForConversation('conv-1');
|
||||
expect(api.getRun).toHaveBeenCalledWith('SNER-DONE', expect.any(AbortSignal));
|
||||
expect(harness.options.onWorkflowRefresh).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
@@ -348,7 +349,7 @@ describe('useShippingOrderExtractionRuns lifecycle', () => {
|
||||
const queued = run({ run_no: 'SNER-RETRY', status: 'queued', phase: 'manual_retry_queued', error: null });
|
||||
api.listRuns.mockResolvedValue({ items: [failed] });
|
||||
api.retryRun.mockResolvedValue({ run: queued, reused: false });
|
||||
api.getRun.mockResolvedValue(queued);
|
||||
api.getRun.mockResolvedValueOnce(failed).mockResolvedValue(queued);
|
||||
const harness = createHarness();
|
||||
harness.conversationId.value = 'conv-1';
|
||||
await harness.runs.restoreForConversation('conv-1');
|
||||
@@ -381,7 +382,7 @@ describe('useShippingOrderExtractionRuns lifecycle', () => {
|
||||
});
|
||||
api.listRuns.mockResolvedValue({ items: [source] });
|
||||
api.reparseRun.mockResolvedValue({ run: replacement, reused: false });
|
||||
api.getRun.mockResolvedValue(replacement);
|
||||
api.getRun.mockResolvedValueOnce(source).mockResolvedValueOnce(source).mockResolvedValue(replacement);
|
||||
const harness = createHarness();
|
||||
harness.conversationId.value = 'conv-1';
|
||||
await harness.runs.restoreForConversation('conv-1');
|
||||
@@ -393,6 +394,21 @@ describe('useShippingOrderExtractionRuns lifecycle', () => {
|
||||
expect(harness.messages.value).toHaveLength(2);
|
||||
harness.runs.stopPolling();
|
||||
});
|
||||
|
||||
it('uses a lightweight Run list only to locate the latest Run before loading one detail', async () => {
|
||||
const latest = run({ run_no: 'SNER-LATEST', conversation_id: 'conv-1', status: 'processing' });
|
||||
const older = run({ run_no: 'SNER-OLDER', conversation_id: 'conv-1', status: 'completed' });
|
||||
api.listRuns.mockResolvedValue({ items: [latest, older] });
|
||||
api.getRun.mockResolvedValue(latest);
|
||||
const harness = createHarness();
|
||||
harness.conversationId.value = 'conv-1';
|
||||
|
||||
await harness.runs.restoreForConversation('conv-1');
|
||||
|
||||
expect(api.getRun).toHaveBeenCalledTimes(1);
|
||||
expect(api.getRun).toHaveBeenCalledWith('SNER-LATEST', expect.any(AbortSignal));
|
||||
harness.runs.stopPolling();
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -644,6 +660,7 @@ describe('mapOrderExtractionRunToMessageState', () => {
|
||||
it('acknowledges a terminal Run only after it is restored into the active conversation', async () => {
|
||||
const terminal = run({ run_no: 'SNER-SEEN', status: 'completed' });
|
||||
api.listRuns.mockResolvedValue({ items: [terminal] });
|
||||
api.getRun.mockResolvedValue(terminal);
|
||||
api.markSeen.mockResolvedValue({ seen: true });
|
||||
const harness = createHarness();
|
||||
harness.conversationId.value = 'conv-1';
|
||||
|
||||
@@ -36,7 +36,6 @@ interface UseShippingOrderExtractionRunsOptions {
|
||||
refreshNoticeIntakeStatuses: () => Promise<void>;
|
||||
getOrderExtractionReview: (intakeNos: string[]) => ShippingOrderExtractionReviewAttachment[];
|
||||
clearConsumedNoticeAttachments: () => void;
|
||||
syncShippingConversationWorkspace: (options?: { preferLatest?: boolean }) => Promise<boolean>;
|
||||
refreshShippingActions: () => Promise<void>;
|
||||
loadHistory: () => Promise<void>;
|
||||
onConversationResolved: (conversationId: string) => Promise<void> | void;
|
||||
@@ -54,69 +53,6 @@ const ACTIVE_RUN_STATUSES = new Set(['queued', 'processing']);
|
||||
const FOREGROUND_POLL_MS = 2000;
|
||||
const BACKGROUND_POLL_MS = 8000;
|
||||
|
||||
/**
|
||||
* 将同一上传批次的独立 Run 合成单张聊天状态卡。
|
||||
*
|
||||
* 核心逻辑:Run 仍按 Intake 独立执行、审计和复核;仅把同会话同 upload_batch_id
|
||||
* 的用户态摘要相加,保证一次文件选择在聊天区只出现一个卡片。
|
||||
*/
|
||||
function mergeUploadBatchRuns(primary: ShippingOrderExtractionRun, runs: ShippingOrderExtractionRun[]): ShippingOrderExtractionRun {
|
||||
const batchId = String(primary.upload_batch_id || '').trim();
|
||||
if (!batchId) return primary;
|
||||
const members = runs.filter((item) => (
|
||||
item.conversation_id === primary.conversation_id
|
||||
&& String(item.upload_batch_id || '').trim() === batchId
|
||||
));
|
||||
if (members.length <= 1) return primary;
|
||||
const activeMembers = members.filter((item) => ACTIVE_RUN_STATUSES.has(item.status));
|
||||
const status = activeMembers.some((item) => item.status === 'processing')
|
||||
? 'processing'
|
||||
: activeMembers.length > 0
|
||||
? 'queued'
|
||||
: members.some((item) => item.status === 'failed')
|
||||
? 'failed'
|
||||
: members.some((item) => item.status === 'review_required')
|
||||
? 'review_required'
|
||||
: members.some((item) => item.status === 'partially_completed')
|
||||
? 'partially_completed'
|
||||
: 'completed';
|
||||
const failedParseMembers = members.filter((item) => (
|
||||
item.documents || []
|
||||
).some((document) => document.reason_code === 'intake_parse_failed' || String(document.user_visible_stage || '') === 'parse_failed'));
|
||||
const effectiveStatus = failedParseMembers.length > 0 && activeMembers.length === 0 ? 'failed' : status;
|
||||
const summaryKeys = [
|
||||
'total_documents', 'pending_documents', 'processing_documents', 'completed_documents',
|
||||
'review_required_documents', 'failed_documents', 'cancelled_documents', 'candidate_count',
|
||||
'opened_existing_documents',
|
||||
] as const;
|
||||
const summary = summaryKeys.reduce((result, key) => {
|
||||
result[key] = members.reduce((total, item) => total + Number(item.summary?.[key] || 0), 0);
|
||||
return result;
|
||||
}, {} as ShippingOrderExtractionRun['summary']);
|
||||
const documentIds = new Set<number>();
|
||||
const documents = members.flatMap((item) => item.documents || []).filter((item) => {
|
||||
const id = Number(item.document_id || 0);
|
||||
if (id && documentIds.has(id)) return false;
|
||||
if (id) documentIds.add(id);
|
||||
return true;
|
||||
});
|
||||
const mostRecent = [...members].sort((left, right) => String(right.last_activity_at || '').localeCompare(String(left.last_activity_at || '')))[0] || primary;
|
||||
return {
|
||||
...primary,
|
||||
status: effectiveStatus,
|
||||
phase: effectiveStatus,
|
||||
intake_nos: [...new Set(members.flatMap((item) => item.intake_nos || []))],
|
||||
summary,
|
||||
documents,
|
||||
current_activity: mostRecent.current_activity || primary.current_activity,
|
||||
available_actions: [...new Set(members.flatMap((item) => item.available_actions || []))],
|
||||
handling_items: members.flatMap((item) => item.handling_items || []),
|
||||
health_tips: members.flatMap((item) => item.health_tips || []),
|
||||
progress_version: Math.max(...members.map((item) => Number(item.progress_version || 0))),
|
||||
last_activity_at: mostRecent.last_activity_at || primary.last_activity_at,
|
||||
};
|
||||
}
|
||||
|
||||
/** 按页面可见性选择轮询间隔;后台放慢,失败退避另算。 */
|
||||
function resolvePollIntervalMs(failureCount = 0): number {
|
||||
if (failureCount > 0) {
|
||||
@@ -296,21 +232,8 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
|
||||
return composerContextId;
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取同批次兄弟 Run 后生成聊天展示快照。
|
||||
*
|
||||
* 仅在服务端已返回 upload_batch_id 时查询;旧 Run 或重识别 Run 保持原有单卡逻辑。
|
||||
*/
|
||||
const loadDisplayRun = async (run: ShippingOrderExtractionRun): Promise<ShippingOrderExtractionRun> => {
|
||||
if (!String(run.upload_batch_id || '').trim()) return run;
|
||||
try {
|
||||
const response = await listWorkspaceShippingOrderExtractionRuns(run.conversation_id, 100);
|
||||
return mergeUploadBatchRuns(run, response.items || []);
|
||||
} catch {
|
||||
// 聚合读失败时宁可显示本 Run 的真实状态,也不阻断轮询或误改业务状态。
|
||||
return run;
|
||||
}
|
||||
};
|
||||
/** Run 卡只消费该 Run 的完整权威详情;批次聚合由独立处理投影负责。 */
|
||||
const loadDisplayRun = async (run: ShippingOrderExtractionRun): Promise<ShippingOrderExtractionRun> => run;
|
||||
|
||||
/** 停止当前 Run 短轮询;切会话和组件卸载时再清空 activeRunNo。 */
|
||||
const stopPolling = () => {
|
||||
@@ -452,14 +375,6 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
|
||||
reviewAttachments = options.getOrderExtractionReview(run.intake_nos);
|
||||
}
|
||||
options.clearConsumedNoticeAttachments();
|
||||
try {
|
||||
if (!(await options.syncShippingConversationWorkspace({ preferLatest: true }))) {
|
||||
await new Promise((resolve) => setTimeout(resolve, 300));
|
||||
await options.syncShippingConversationWorkspace({ preferLatest: true });
|
||||
}
|
||||
} catch {
|
||||
// Run 状态卡已持久化;工作台可由页面下一次刷新继续恢复。
|
||||
}
|
||||
await Promise.allSettled([options.loadHistory()]);
|
||||
options.onWorkflowRefresh?.();
|
||||
return reviewAttachments;
|
||||
@@ -768,8 +683,9 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
|
||||
if (options.conversationId.value !== conversationId) return;
|
||||
const latest = items[0];
|
||||
if (!latest) return;
|
||||
activeRunNo = latest.run_no;
|
||||
const displayRun = mergeUploadBatchRuns(latest, items);
|
||||
const displayRun = await getWorkspaceShippingOrderExtractionRun(latest.run_no, request.signal);
|
||||
if (options.conversationId.value !== conversationId) return;
|
||||
activeRunNo = displayRun.run_no;
|
||||
const reviewAttachments = ACTIVE_RUN_STATUSES.has(displayRun.status)
|
||||
? undefined
|
||||
: await refreshTerminalFacts(displayRun);
|
||||
|
||||
@@ -33,7 +33,7 @@ export type ShippingProcessingWorkItemTypeArg = 'order_intake' | 'order_task';
|
||||
*
|
||||
* @param workItemType - order_intake | order_task
|
||||
* @param workItemNo - Intake 编号或 OT 编号(MaybeRef)
|
||||
* @param options.enabled - 是否启用;options.pollMs - 轮询间隔;
|
||||
* @param options.enabled - 是否启用;options.pollMs - 轮询间隔;options.continuousPolling - 是否由本 composable 持续轮询;
|
||||
* options.monotonicProgressVersion - 仅工作台:旧 progress_version 不覆盖本地
|
||||
* @returns projection / loading / error / refresh / stop
|
||||
*/
|
||||
@@ -43,6 +43,8 @@ export function useShippingProcessingWorkItem(
|
||||
options: {
|
||||
enabled?: MaybeRefOrGetter<boolean>;
|
||||
pollMs?: number;
|
||||
/** false 时仅由调用方显式 refresh;用于已有页面级协调轮询的工作台。 */
|
||||
continuousPolling?: boolean;
|
||||
/** 仅订单处理工作台开启;任务中心保持默认 false。 */
|
||||
monotonicProgressVersion?: boolean;
|
||||
} = {},
|
||||
@@ -61,6 +63,7 @@ export function useShippingProcessingWorkItem(
|
||||
let stopped = false;
|
||||
let refreshInFlight: { no: string; promise: Promise<void> } | null = null;
|
||||
const pollMs = options.pollMs ?? DEFAULT_POLL_MS;
|
||||
const continuousPolling = options.continuousPolling !== false;
|
||||
const monotonic = Boolean(options.monotonicProgressVersion);
|
||||
|
||||
/**
|
||||
@@ -112,7 +115,7 @@ export function useShippingProcessingWorkItem(
|
||||
error.value = null;
|
||||
clearTimer();
|
||||
const next = projection.value;
|
||||
if (next && !TERMINAL_STATUSES.has(next.status) && !stopped) {
|
||||
if (continuousPolling && next && !TERMINAL_STATUSES.has(next.status) && !stopped) {
|
||||
timer = window.setTimeout(() => {
|
||||
void refresh();
|
||||
}, pollMs);
|
||||
@@ -128,7 +131,7 @@ export function useShippingProcessingWorkItem(
|
||||
}
|
||||
error.value = err instanceof BusinessError ? err.message : 'network_recoverable';
|
||||
clearTimer();
|
||||
if (!stopped) {
|
||||
if (continuousPolling && !stopped) {
|
||||
timer = window.setTimeout(() => {
|
||||
void refresh();
|
||||
}, pollMs);
|
||||
|
||||
@@ -9,7 +9,7 @@ export type ChatTurnInputType = 'text' | 'action' | 'form_submit' | 'upload_foll
|
||||
|
||||
/**
|
||||
* 会话级业务锚点。
|
||||
* 货代双工作台阶段 2 优先键:conversation_id / run_no / candidate_no / task_no / batch_no;
|
||||
* 货代对话优先键:conversation_id / run_no / candidate_no / task_no;
|
||||
* 其他 Agent 可使用各自键名。禁止用本结构承载业务状态机推导结果。
|
||||
*/
|
||||
export type ChatTurnRefs = Record<string, string>;
|
||||
@@ -20,7 +20,6 @@ export const SHIPPING_CHAT_TURN_REF_KEYS = [
|
||||
'run_no',
|
||||
'candidate_no',
|
||||
'task_no',
|
||||
'batch_no',
|
||||
] as const;
|
||||
|
||||
export interface StartChatTurnOptions {
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
* composerContextId;与 shipping.api.types 提交 DTO 对齐。
|
||||
*/
|
||||
import type { LeaveAgentOption } from './leave.types';
|
||||
import type { ShippingBatchUiState, ShippingTaskUiState } from './shipping.api.types';
|
||||
import type { ShippingTaskUiState } from './shipping.api.types';
|
||||
import type { ShippingNoticeCandidate } from './shipping.types';
|
||||
|
||||
export type { LeaveAgentOption };
|
||||
@@ -207,9 +207,7 @@ export interface ShippingOrderExtractionReviewAttachment {
|
||||
/** 历史消息中用于恢复发货工作台焦点的最小持久化载荷。 */
|
||||
export interface ShippingMessageRecoveryPayload {
|
||||
task_no?: string;
|
||||
batch_no?: string;
|
||||
shipping_ui_state?: ShippingTaskUiState;
|
||||
shipping_batch_ui_state?: ShippingBatchUiState;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
|
||||
@@ -90,7 +90,28 @@ export type ShippingProcessingActionIntent =
|
||||
| 'open_inventory_match_review'
|
||||
| 'open_shortage_review'
|
||||
| 'upload_inventory_file'
|
||||
| 'retry'
|
||||
| 'reload_inventory_result'
|
||||
| 'retry_inventory_preparation'
|
||||
| 'retry_inventory_matching'
|
||||
| 'retry_parse'
|
||||
| 'retry_failed_documents'
|
||||
| 'retry_failed_attachments'
|
||||
| 'retry_freight_upload_rpa'
|
||||
| 'retry_order_extraction'
|
||||
| 'retry_layout_parsing'
|
||||
| 'rematerialize_document'
|
||||
| 'reroute_document_profile'
|
||||
| 'revalidate_reservation'
|
||||
| 'retry_customer_resolution'
|
||||
| 'retry_duplicate_detection'
|
||||
| 'retry_with_latest_rules'
|
||||
| 'recheck_freeze_readiness'
|
||||
| 'retry_task_creation'
|
||||
| 'retry_inventory_field_mapping'
|
||||
| 'recheck_inventory_sufficiency'
|
||||
| 'recheck_excel_readiness'
|
||||
| 'retry_stp_auto_create'
|
||||
| 'reparse'
|
||||
| 'reparse_batch'
|
||||
| 'refresh'
|
||||
| 'regenerate_excel'
|
||||
@@ -163,7 +184,7 @@ export interface ShippingProcessingPrimaryAction {
|
||||
}
|
||||
|
||||
/** 订单生命周期工作台的后端目标阶段。 */
|
||||
export type LifecycleWorkbenchStage = 'intake_parse' | 'order_review' | 'fulfillment_prep' | 'upload_complete';
|
||||
export type LifecycleWorkbenchStage = 'intake_parse' | 'order_review' | 'fulfillment_prep' | 'freight_upload' | 'upload_complete';
|
||||
|
||||
/** 文件级生命周期入口;状态、目标均由后端裁决。 */
|
||||
export interface ShippingProcessingLifecycleEntry {
|
||||
@@ -354,10 +375,7 @@ export interface ShippingProcessingProjection {
|
||||
blockingReason?: ShippingProcessingBlockingReason | null;
|
||||
/** 唯一主入口按钮建议:{code, i18nKey, parameters};前端只渲染不新建动作码。 */
|
||||
primaryAction?: ShippingProcessingPrimaryAction | null;
|
||||
/**
|
||||
* 单项后端展示裁决;存在时状态、阶段、原因和动作必须只消费此对象。
|
||||
* primaryAction / availableActions 仅保留给尚未升级该契约的旧服务端响应。
|
||||
*/
|
||||
/** 单项后端展示裁决;状态、阶段、原因和动作必须只消费此对象。 */
|
||||
uiState?: ConversationProcessingUiState;
|
||||
/** 文件关联的正式 Gate 用户摘要;仅用于执行后端已裁决的 primary_action。 */
|
||||
processGate?: ShippingProcessGateUserSummary | null;
|
||||
@@ -369,10 +387,6 @@ export interface ShippingProcessingProjection {
|
||||
aggregateSummary?: ConversationProcessingUserTask['aggregateSummary'];
|
||||
/** EML Intake 聚合卡的真实子附件工作项;仅展示,不作为写操作目标。 */
|
||||
aggregateChildren?: ShippingProcessingProjection[];
|
||||
/** 旧 status 备份(T8 apply_user_projection_fields.legacy_status);调试用。 */
|
||||
legacyStatus?: string | null;
|
||||
/** 旧 stage 备份(T8 apply_user_projection_fields.legacy_stage);调试用。 */
|
||||
legacyStage?: string | null;
|
||||
/** 正式 OT 是否已挂接真实 ShippingNotice;T1 判定:order_task + shipping_notice_id 非空 + shipping_notice_no 非空。 */
|
||||
hasFormalOt?: boolean;
|
||||
/**
|
||||
@@ -606,8 +620,6 @@ export interface ConversationProcessingUserTask {
|
||||
facts?: ShippingProcessingFacts;
|
||||
/** EML Intake 的用户可见全局分组;前端只消费,不从附件状态自行推导。 */
|
||||
userGroup?: ShippingProcessingProjection['userGroup'];
|
||||
legacyStatus?: string | null;
|
||||
legacyStage?: string | null;
|
||||
/** 同一 EML Intake 聚合后的子任务状态,仅供展示,不作为写操作事实。 */
|
||||
aggregateSummary?: {
|
||||
intakeNo: string;
|
||||
@@ -664,11 +676,17 @@ export interface ConversationProcessingProjection {
|
||||
summary: ConversationProcessingSummary;
|
||||
focused_task_no?: string | null;
|
||||
recent_task_no?: string | null;
|
||||
needs_action: ConversationProcessingUserTask[];
|
||||
processing: ConversationProcessingUserTask[];
|
||||
/** 成功完成待查看;与 needs_action 异常态分离 */
|
||||
/**
|
||||
* @deprecated 仅用于编译期迁移旧夹具;生产响应和生产读取均不得使用。
|
||||
* 新调用必须只消费 status_groups。
|
||||
*/
|
||||
needs_action?: ConversationProcessingUserTask[];
|
||||
/** @deprecated 仅用于编译期迁移旧夹具;生产响应和生产读取均不得使用。 */
|
||||
processing?: ConversationProcessingUserTask[];
|
||||
/** @deprecated 仅用于编译期迁移旧夹具;生产响应和生产读取均不得使用。 */
|
||||
completed?: ConversationProcessingUserTask[];
|
||||
history: ConversationProcessingUserTask[];
|
||||
/** @deprecated 仅用于编译期迁移旧夹具;生产响应和生产读取均不得使用。 */
|
||||
history?: ConversationProcessingUserTask[];
|
||||
/** 按 EML Intake 唯一归组后的六类用户状态;同一 EML 只允许出现一次。 */
|
||||
status_groups?: {
|
||||
failed: ConversationProcessingUserTask[];
|
||||
@@ -678,12 +696,11 @@ export interface ConversationProcessingProjection {
|
||||
cancelled: ConversationProcessingUserTask[];
|
||||
archived: ConversationProcessingUserTask[];
|
||||
};
|
||||
/** 会话批次主进度;后端已将技术阶段折叠为四个业务节点。 */
|
||||
four_stage_nodes?: Array<{
|
||||
code: 'intake_parse' | 'order_review' | 'fulfillment_prep' | 'upload_complete';
|
||||
/** 会话批次主进度;后端已将技术阶段折叠为五个业务节点。 */
|
||||
lifecycle_nodes?: Array<{
|
||||
code: LifecycleWorkbenchStage;
|
||||
label_key: string;
|
||||
status: 'passed' | 'running' | 'blocked' | 'pending';
|
||||
/** 批次阶段摘要由后端按完整叶子工作项裁决,禁止页面从筛选结果反算。 */
|
||||
summary?: {
|
||||
total: number;
|
||||
completed: number;
|
||||
@@ -693,7 +710,7 @@ export interface ConversationProcessingProjection {
|
||||
blocking_reason?: ShippingProcessingBlockingReason | null;
|
||||
};
|
||||
}>;
|
||||
/** 后端无法归类到四阶段的业务文件数量;页面只提示,不擅自归类。 */
|
||||
/** 后端无法归类到五阶段的业务文件数量;页面只提示,不擅自归类。 */
|
||||
unclassified_summary?: { count: number };
|
||||
/** 批次级用户态:状态、问题与可操作动作必须来自同一次后端裁决。 */
|
||||
ui_state?: ConversationProcessingUiState;
|
||||
@@ -711,8 +728,8 @@ export interface ConversationProcessingProjection {
|
||||
export interface ConversationProcessingUiState {
|
||||
status: ShippingUserProcessingStatus;
|
||||
stage: string;
|
||||
/** 后端从技术节点裁决的四阶段业务编码,批次中心与工作台共同消费。 */
|
||||
lifecycleStage?: 'intake_parse' | 'order_review' | 'fulfillment_prep' | 'upload_complete';
|
||||
/** 后端从技术节点裁决的五阶段业务编码,批次中心与工作台共同消费。 */
|
||||
lifecycleStage?: LifecycleWorkbenchStage;
|
||||
lifecycleEntries?: ShippingProcessingLifecycleEntry[];
|
||||
blocking_reason: ShippingProcessingBlockingReason | null;
|
||||
primary_action: ShippingProcessingPrimaryAction | null;
|
||||
@@ -808,10 +825,22 @@ export interface ShippingInventorySnapshot {
|
||||
export interface ShippingTaskSummary {
|
||||
id: number;
|
||||
task_no: string;
|
||||
shipping_case_id?: number | null;
|
||||
case_no?: string | null;
|
||||
business_no?: string | null;
|
||||
batch_no?: string | null;
|
||||
/** 通知单列表只读行摘要;库存数据由后端当前匹配事实投影,前端不得自行计算。 */
|
||||
notice_line_summary?: Array<{
|
||||
line_no?: string | number | null;
|
||||
part_number?: string | null;
|
||||
customer_part_number?: string | null;
|
||||
reservation_id?: string | null;
|
||||
shipment_qty?: string | null;
|
||||
available_qty?: string | null;
|
||||
shortage_qty?: string | null;
|
||||
inventory_status?: string | null;
|
||||
}>;
|
||||
artifact_summary?: {
|
||||
export_file_name?: string | null;
|
||||
export_file_path?: string | null;
|
||||
} | null;
|
||||
source_type: string;
|
||||
source_file_name?: string | null;
|
||||
source_file_type?: string | null;
|
||||
@@ -1038,6 +1067,7 @@ export type ShippingProcessGateActionCode =
|
||||
| 'retry_with_latest_rules'
|
||||
| 'recheck_freeze_readiness'
|
||||
| 'retry_task_creation'
|
||||
| 'reload_inventory_result'
|
||||
| 'retry_inventory_preparation'
|
||||
| 'poll_inventory_preparation'
|
||||
| 'upload_inventory_file'
|
||||
@@ -1414,7 +1444,6 @@ export type ShippingActionKind = 'forward' | 'recovery' | 'view' | 'terminate';
|
||||
|
||||
export interface ShippingTaskUiState {
|
||||
task_no: string;
|
||||
batch_no?: string | null;
|
||||
stage?: {
|
||||
code: ShippingBusinessStage | string;
|
||||
label: string;
|
||||
@@ -1445,7 +1474,7 @@ export interface ShippingTaskUiState {
|
||||
primary?: ShippingUnifiedAction | null;
|
||||
secondary?: ShippingUnifiedAction[];
|
||||
};
|
||||
/** 四阶段工作台只读事实;由后端 ui_state 投影,不参与状态或权限裁决。 */
|
||||
/** 五阶段工作台只读事实;由后端 ui_state 投影,不参与状态或权限裁决。 */
|
||||
stage_context?: {
|
||||
preparation?: {
|
||||
status?: 'processing' | 'blocked' | 'ready' | string;
|
||||
@@ -1483,6 +1512,14 @@ export interface ShippingTaskUiState {
|
||||
} | null;
|
||||
upload?: {
|
||||
outcome?: 'not_started' | 'running' | 'awaiting_manual' | 'succeeded' | 'failed' | 'unknown' | string;
|
||||
/** 仅 upload_complete 工作面读取的、后端验证过的成功上传事实。 */
|
||||
succeeded_attempt?: {
|
||||
id?: number | null;
|
||||
status?: string | null;
|
||||
mode?: string | null;
|
||||
freight_ref_no?: string | null;
|
||||
finished_at?: string | null;
|
||||
} | null;
|
||||
latest_attempt?: {
|
||||
id?: number | null;
|
||||
status?: string | null;
|
||||
@@ -1567,66 +1604,35 @@ export interface ShippingUnifiedAction {
|
||||
|
||||
/**
|
||||
* `shipping_ui_state` SSE 与历史回放共用的恢复契约。
|
||||
* 核心逻辑:任务锚点 `task_no` 是 open_existing 场景恢复聊天工作台的最小必需字段;
|
||||
* 若后端能解析到所属批次或完整批次快照,应继续补齐 `batch_no`、`batch_ui_state` 与 `ui_state`。
|
||||
* 核心逻辑:任务锚点 `task_no` 是恢复聊天工作台的最小必需字段,`ui_state` 是其只读事实快照。
|
||||
*/
|
||||
export interface ShippingUiStateEventPayload {
|
||||
event?: 'shipping_ui_state';
|
||||
conversation_id?: string;
|
||||
task_no?: string | null;
|
||||
batch_no?: string | null;
|
||||
ui_state?: ShippingTaskUiState;
|
||||
batch_ui_state?: ShippingBatchUiState;
|
||||
source?: string;
|
||||
}
|
||||
|
||||
export interface ShippingBatchSummary {
|
||||
id: number;
|
||||
batch_no: string;
|
||||
conversation_id?: string | null;
|
||||
current_focus_task_no?: string | null;
|
||||
file_count?: number | null;
|
||||
process_summary?: Record<string, unknown> & {
|
||||
total?: number;
|
||||
completed?: number;
|
||||
failed?: number;
|
||||
running?: number;
|
||||
pending?: number;
|
||||
needs_human?: number;
|
||||
current_index?: number;
|
||||
current_task_no?: string | null;
|
||||
} | null;
|
||||
created_at?: string | null;
|
||||
updated_at?: string | null;
|
||||
/** 订单工作台货代上传区的 Notice 聚合行;一行对应一个 business_no 与唯一 Excel。 */
|
||||
export interface ShippingFreightNoticeGroup {
|
||||
business_no: string;
|
||||
po_number: string | null;
|
||||
upload_status?: string | null;
|
||||
export_file_name?: string | null;
|
||||
available_actions?: string[];
|
||||
lines: Array<{
|
||||
line_no?: string | number | null;
|
||||
part_number?: string | null;
|
||||
reservation_id?: string | null;
|
||||
shipment_qty?: string | number | null;
|
||||
}>;
|
||||
}
|
||||
|
||||
export interface ShippingBatchUiState extends ShippingBatchSummary {
|
||||
/** 批次仅作为会话上传集合摘要,非履约写操作面 */
|
||||
role?: 'upload_session_summary' | string;
|
||||
focus_task?: ShippingTaskSummary | null;
|
||||
focus_task_ui_state?: ShippingTaskUiState | null;
|
||||
tasks: ShippingTaskSummary[];
|
||||
}
|
||||
|
||||
export interface ShippingConversationWorkspaceSummary {
|
||||
batch_count: number;
|
||||
total: number;
|
||||
completed: number;
|
||||
running: number;
|
||||
failed: number;
|
||||
needs_human: number;
|
||||
pending: number;
|
||||
}
|
||||
|
||||
export interface ShippingConversationBatch extends ShippingBatchSummary {
|
||||
tasks: ShippingTaskSummary[];
|
||||
focus_task?: ShippingTaskSummary | null;
|
||||
}
|
||||
|
||||
export interface ShippingConversationWorkspace {
|
||||
conversation_id: string;
|
||||
summary: ShippingConversationWorkspaceSummary;
|
||||
batches: ShippingConversationBatch[];
|
||||
export interface ShippingFreightNoticeGroupsResponse {
|
||||
po_number: string | null;
|
||||
items: ShippingFreightNoticeGroup[];
|
||||
reason?: 'po_missing' | 'no_business_notice' | string | null;
|
||||
}
|
||||
|
||||
export interface ShippingInventoryUploadResponse {
|
||||
@@ -1663,16 +1669,10 @@ export interface ShippingNoticeUploadResponse {
|
||||
status: string;
|
||||
message?: string;
|
||||
task_id?: string;
|
||||
batch_no?: string;
|
||||
checkpoint?: string;
|
||||
idempotent_replay?: boolean;
|
||||
file_summary?: ShippingNoticeFileSummary;
|
||||
data?: Record<string, unknown> & {
|
||||
batch?: ShippingBatchSummary;
|
||||
focus_task?: ShippingTaskSummary | null;
|
||||
tasks?: Array<Record<string, unknown>>;
|
||||
orchestrator_started?: boolean;
|
||||
};
|
||||
data?: Record<string, unknown> & { orchestrator_started?: boolean };
|
||||
human_options?: string[];
|
||||
}
|
||||
|
||||
@@ -1847,6 +1847,36 @@ export interface ShippingOrderExtractionRunSummary {
|
||||
opened_existing_documents?: number;
|
||||
}
|
||||
|
||||
/** 复核工作台直接消费的 Run 级五阶段进度;字段由后端 Projection 裁决。 */
|
||||
export interface ShippingOrderExtractionLifecycleProgress {
|
||||
lifecycle_stage: 'intake_parse' | 'order_review' | 'fulfillment_prep' | 'freight_upload' | 'upload_complete' | string;
|
||||
lifecycle_status: 'running' | 'waiting' | 'failed' | 'cancelled' | 'completed' | string;
|
||||
current_step_code?: string | null;
|
||||
current_step_i18n_key?: string | null;
|
||||
completed_step_codes: string[];
|
||||
last_activity_at?: string | null;
|
||||
health_status: 'normal' | 'attention' | 'failed' | string;
|
||||
blocking_reason_i18n_key?: string | null;
|
||||
primary_action?: string | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 会话恢复和任务中心列表的固定成本摘要;完整文档、Case、Gate 投影必须按 Run 编号单独读取。
|
||||
*/
|
||||
export interface ShippingOrderExtractionRunListItem {
|
||||
run_no: string;
|
||||
user_task_no?: string | null;
|
||||
agent_id: number;
|
||||
conversation_id: string;
|
||||
status: ShippingOrderExtractionRunStatus;
|
||||
phase: string;
|
||||
summary: ShippingOrderExtractionRunSummary;
|
||||
progress_version?: number | null;
|
||||
last_activity_at?: string | null;
|
||||
created_at?: string | null;
|
||||
updated_at?: string | null;
|
||||
}
|
||||
|
||||
export interface ShippingOrderExtractionCurrentActivity {
|
||||
unit_id: number;
|
||||
file_name?: string | null;
|
||||
@@ -1883,6 +1913,7 @@ export interface ShippingOrderExtractionDocumentResult {
|
||||
queue_position?: number | null;
|
||||
elapsed_seconds?: number | null;
|
||||
health_tips?: ShippingOrderExtractionHealthTip[];
|
||||
lifecycle_progress?: ShippingOrderExtractionLifecycleProgress | null;
|
||||
cancellation?: ShippingOrderExtractionCancellation | null;
|
||||
activity_version?: number | null;
|
||||
selection_batch?: number | null;
|
||||
@@ -1994,11 +2025,12 @@ export interface ShippingOrderExtractionRun {
|
||||
primary_notice?: string | null;
|
||||
user_visible_stage?: ShippingOrderExtractionUserVisibleStage | null;
|
||||
health_tips?: ShippingOrderExtractionHealthTip[];
|
||||
/** Run 解析中或尚无 Case 时的后端用户态进度。 */
|
||||
lifecycle_progress?: ShippingOrderExtractionLifecycleProgress | null;
|
||||
cancellation?: ShippingOrderExtractionCancellation | null;
|
||||
progress_version?: number | null;
|
||||
last_activity_at?: string | null;
|
||||
result?: {
|
||||
batch_no?: string | null;
|
||||
created_count?: number;
|
||||
opened_existing_count?: number;
|
||||
pending_count?: number;
|
||||
@@ -2255,6 +2287,8 @@ export interface ShippingOrderReviewCaseSummary {
|
||||
draft_version?: number | null;
|
||||
issue_count: number;
|
||||
available_actions: string[];
|
||||
/** 仅 parse_failed 时由后端下发,供当前阶段卡调用原 Intake retry API。 */
|
||||
intake_no?: string | null;
|
||||
source_run_no?: string | null;
|
||||
}
|
||||
|
||||
@@ -2263,6 +2297,8 @@ export interface ShippingOrderReviewRun {
|
||||
superseded_by_run_no?: string | null;
|
||||
summary: Record<string, number>;
|
||||
items: ShippingOrderReviewCaseSummary[];
|
||||
/** Run 解析中或尚无 Case 时的后端用户态进度。 */
|
||||
lifecycle_progress?: ShippingOrderExtractionLifecycleProgress | null;
|
||||
}
|
||||
|
||||
export interface ShippingOrderReviewQueue {
|
||||
@@ -2435,7 +2471,8 @@ export interface ShippingOrderReviewBuildEligibilityIssue {
|
||||
}
|
||||
|
||||
export interface ShippingOrderReviewBuildEligibility {
|
||||
can_build: boolean;
|
||||
/** 未执行校验时为 null;只有 validated/needs_review 才返回布尔结论。 */
|
||||
can_build: boolean | null;
|
||||
can_auto_create?: boolean;
|
||||
status: string;
|
||||
gates?: Record<string, boolean>;
|
||||
@@ -2497,12 +2534,8 @@ export interface ShippingOrderReviewFieldConflictOption {
|
||||
evidence_role?: 'primary_pdf' | 'auxiliary' | 'context' | string | null;
|
||||
/** PDF_PRIORITY_EVIDENCE_RANKS 档位名。 */
|
||||
evidence_rank?: string | null;
|
||||
/** Vendor Comments 三来源专属:字段来源种类(header_region / table_column / vendor_comments)。 */
|
||||
vc_source_kind?: string | null;
|
||||
/** Vendor Comments 三来源专属:来源种类的本地化展示标签。 */
|
||||
vc_source_kind_label?: string | null;
|
||||
/** Vendor Comments 三来源专属:vc:<doc>:p<N>:region:<rid> 证据引用,可跳转证据查看器定位对应区域。 */
|
||||
evidence_ref?: string | null;
|
||||
/** 结构化文档证据或兼容字符串,可跳转证据查看器定位对应区域。 */
|
||||
evidence_ref?: Record<string, unknown> | string | null;
|
||||
}
|
||||
|
||||
/** 建单前 Candidate 字段冲突投影(复核工作台集中裁决区)。 */
|
||||
@@ -2517,18 +2550,8 @@ export interface ShippingOrderReviewFieldConflict {
|
||||
reason: string;
|
||||
options: ShippingOrderReviewFieldConflictOption[];
|
||||
observation_ids?: string[];
|
||||
/** Vendor Comments 三来源专属:true 表示该冲突来自 VC 三来源合并,conflict_key 以 vc: 开头。 */
|
||||
vc_kind?: boolean | null;
|
||||
/** Vendor Comments 三来源专属:细因码(vc_source_conflict_unresolved / vc_source_format_invalid / vc_source_region_unbound)。 */
|
||||
vc_reason?: string | null;
|
||||
/** Vendor Comments 三来源专属:冲突组稳定键(scope:field_code:line_no),裁决时写回 merged_candidates 使用。 */
|
||||
vc_conflict_group_key?: string | null;
|
||||
/** Vendor Comments 三来源专属:只读诊断,展示 resolution / decision_status / format_valid。 */
|
||||
vc_detail?: {
|
||||
resolution?: string | null;
|
||||
decision_status?: string | null;
|
||||
format_valid?: boolean | null;
|
||||
} | null;
|
||||
/** 后端给出的下一步恢复动作;例如 reparse_current_pdf。 */
|
||||
recovery_action?: string | null;
|
||||
}
|
||||
|
||||
export interface ShippingOrderReviewCase {
|
||||
@@ -2632,6 +2655,8 @@ export interface ShippingOrderReviewCase {
|
||||
build_eligibility?: ShippingOrderReviewBuildEligibility;
|
||||
} | null;
|
||||
available_actions: string[];
|
||||
/** 仅 parse_failed 时由后端下发,供当前阶段卡调用原 Intake retry API。 */
|
||||
intake_no?: string | null;
|
||||
/** 正式任务 Schema 放行可写字段 field_id;confirmed + edit_formal_task 时由后端投影。 */
|
||||
formal_editable_field_ids?: string[];
|
||||
/** 关联 Notice 的 order_data_version;formal patch 乐观锁。 */
|
||||
@@ -2936,6 +2961,14 @@ export interface ShippingOrderReviewProfileMatchCandidate {
|
||||
hard_match?: boolean | null;
|
||||
reason_codes?: string[];
|
||||
missing_required_anchor_ids?: string[];
|
||||
/** 管理员技术详情:共同 matcher 已确认的受限平移,不含正文或完整坐标。 */
|
||||
coordinate_transform?: {
|
||||
status: 'applied' | 'unavailable' | 'rejected' | string;
|
||||
translate_x?: number | null;
|
||||
translate_y?: number | null;
|
||||
anchor_ids?: string[];
|
||||
reason_codes?: string[];
|
||||
} | null;
|
||||
}
|
||||
|
||||
/** 建单前文档模板匹配只读投影。 */
|
||||
@@ -3044,6 +3077,7 @@ export interface ShippingOrderReviewLineFulfillmentDecision {
|
||||
part_number?: string | null;
|
||||
task_id?: number | null;
|
||||
wave_no?: number | null;
|
||||
notice_no?: string | null;
|
||||
created_at?: string | null;
|
||||
}
|
||||
|
||||
|
||||
Loaded 100 of 402 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user