feat(shipping-notice): 实现滚动履约功能,优化发货通知流程与代码清理
清理废弃的ShippingCase相关代码与依赖,统一使用ShippingNotice直接关联客户数据。调整库存网关依赖规则,支持仅对库存满足或已人工放行的订单行生成发货Excel,实现滚动履约逻辑。
This commit is contained in:
1 parent
7cfd5d167e
commit
1e5aedb9ed
235 files changed
+11394
-9613
No files matched your search
@@ -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(),
|
||||
},
|
||||
);
|
||||
|
||||
|
||||
+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) {
|
||||
|
||||
+475
-215
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);
|
||||
});
|
||||
});
|
||||
+29
-3
@@ -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);优先于空态提示。 */
|
||||
@@ -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;
|
||||
@@ -364,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>
|
||||
@@ -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); }
|
||||
|
||||
+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 = [
|
||||
|
||||
+124
@@ -6,6 +6,7 @@
|
||||
*/
|
||||
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { reactive } from 'vue';
|
||||
import {
|
||||
mergeOrderProfileHeaderLabels,
|
||||
restoreOrderProfileRegionPageNo,
|
||||
@@ -13,10 +14,13 @@ import {
|
||||
shouldShowStandardOrderProfilePreview,
|
||||
toOrderProfileAnchorId,
|
||||
buildOrderProfileRecognitionResults,
|
||||
buildOrderProfileCanvasLineFieldValues,
|
||||
selectCurrentDatasetsValidationEvidence,
|
||||
normalizeOrderProfileRelativeRegion,
|
||||
restoreReservationIdRegion,
|
||||
groupUniqueOrderProfileLineFields,
|
||||
restoreFormalBindingFieldCodes,
|
||||
reconcileAutomarkOrderFieldRegions,
|
||||
buildAutomarkSuggestedRegions,
|
||||
normalizeAutomarkFieldCandidates,
|
||||
preferredAutomarkTableSource,
|
||||
@@ -29,6 +33,23 @@ import {
|
||||
} 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,
|
||||
@@ -409,6 +430,73 @@ 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',
|
||||
@@ -431,6 +519,42 @@ describe('order profile form rules', () => {
|
||||
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',
|
||||
|
||||
+202
-10
@@ -139,6 +139,61 @@ export const restoreFormalBindingFieldCodes = (
|
||||
});
|
||||
};
|
||||
|
||||
/** 自动候选与既有共同订单字段框被视为同一视觉证据的最小 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 - 可能来自拖拽、自动建议或历史模板的页面区域。
|
||||
@@ -156,6 +211,26 @@ 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;
|
||||
@@ -212,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()) {
|
||||
@@ -243,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 || {
|
||||
@@ -361,9 +453,11 @@ export const preferredAutomarkTableSource = (
|
||||
*/
|
||||
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> : {};
|
||||
@@ -373,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 只有技术控件名和几何;它必须作为
|
||||
@@ -387,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 的表格不受上一张表多物理行状态影响。
|
||||
@@ -463,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 - 当前页画布区域;未标注字段不会伪装成可定位项。
|
||||
@@ -476,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
|
||||
@@ -513,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;
|
||||
@@ -526,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] };
|
||||
};
|
||||
|
||||
/**
|
||||
|
||||
@@ -94,6 +94,12 @@ export interface OrderProfileVisualDefinition {
|
||||
/** 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 {
|
||||
@@ -233,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。 */
|
||||
@@ -928,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;
|
||||
@@ -1171,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;
|
||||
}
|
||||
@@ -23,6 +23,7 @@ import type {
|
||||
ShippingNoticeIntakeResponse,
|
||||
ShippingTaskCreateResponse,
|
||||
ShippingTaskDetail,
|
||||
ShippingFreightNoticeGroupsResponse,
|
||||
ShippingTaskBatchDispositionResponse,
|
||||
ShippingTaskPage,
|
||||
ShippingCustomerOption,
|
||||
@@ -121,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 单源)。
|
||||
*/
|
||||
@@ -141,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`;
|
||||
@@ -871,7 +882,7 @@ export const decideWorkspaceShippingOrderReviewLineFulfillment = (
|
||||
);
|
||||
|
||||
/**
|
||||
* 为选中完整明细行创建履约波次 Task。
|
||||
* 为选中完整明细行创建独立发货通知和 Excel。
|
||||
*/
|
||||
export const waveWorkspaceShippingOrderReviewLineFulfillment = (
|
||||
caseNo: string,
|
||||
@@ -887,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`,
|
||||
{
|
||||
@@ -1282,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';
|
||||
|
||||
|
||||
+14
@@ -19,9 +19,11 @@ const i18n = createI18n({
|
||||
shippingNotice: {
|
||||
processGate: {
|
||||
actionCodes: {
|
||||
reload_inventory_result: '重新读取库存结果',
|
||||
retry_inventory_preparation: '重新获取库存',
|
||||
},
|
||||
inventoryActions: {
|
||||
reloadInventoryResult: '重新读取库存结果',
|
||||
retryInventoryMatching: '重新库存匹配',
|
||||
retryInventoryPreparation: '重新获取库存',
|
||||
},
|
||||
@@ -80,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: {
|
||||
|
||||
+12
-1
@@ -352,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"
|
||||
|
||||
+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>
|
||||
+10
-1
@@ -22,6 +22,7 @@ const i18n = createI18n({
|
||||
lifecycle: {
|
||||
navigation: '订单生命周期阶段',
|
||||
current: '当前可处理',
|
||||
processing: '处理中',
|
||||
completed: '已完成,可查看',
|
||||
blocked: '前置未完成',
|
||||
},
|
||||
@@ -41,7 +42,7 @@ const stages: ReviewLifecycleStageItem[] = [
|
||||
/** 挂载导航,复用真实 i18n 以覆盖状态文案渲染。 */
|
||||
function mountNavigation() {
|
||||
return mount(ReviewLifecycleStageNavigation, {
|
||||
props: { stages, activeCode: 'fulfillment_prep' },
|
||||
props: { stages, activeCode: 'fulfillment_prep', processingCode: 'fulfillment_prep' },
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
}
|
||||
@@ -102,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"]');
|
||||
|
||||
+13
-2
@@ -5,7 +5,7 @@
|
||||
逻辑:用户可打开当前或已完成阶段查看;后续阶段由父级传入 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' | 'freight_upload' | 'upload_complete';
|
||||
export type ReviewLifecycleStageState = 'current' | 'completed' | 'blocked';
|
||||
@@ -23,6 +23,8 @@ const props = defineProps<{
|
||||
activeCode: ReviewLifecycleStageCode | null;
|
||||
/** 仅消费当前对象后端下发的恢复动作,禁止按阶段或状态由前端猜测。 */
|
||||
availableActions?: string[];
|
||||
/** 当前阶段正在执行自动推进时的技术阶段码;只影响展示,不授权动作。 */
|
||||
processingCode?: ReviewLifecycleStageCode | null;
|
||||
/** retry_parse 请求中的互斥状态,避免用户重复提交。 */
|
||||
retrying?: boolean;
|
||||
}>();
|
||||
@@ -67,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" />
|
||||
@@ -88,7 +97,9 @@ 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')) }}
|
||||
|
||||
@@ -18,6 +18,7 @@ const i18n = createI18n({
|
||||
title: '文档模板匹配', subtitle: '摘要', selected: '命中模板', noSelected: '未选定模板',
|
||||
expandCandidates: '查看候选模板({count})', collapseCandidates: '收起候选模板',
|
||||
routeType: '路由类型', executionMode: '执行模式',
|
||||
extractionBlocked: '模板已命中,但字段提取仍被安全门禁阻断', extractionBlockedReason: '阻断原因:{reasons}',
|
||||
coordinateModel: {
|
||||
anchorFrame: '锚点坐标框架', status: '变换状态', translateX: '横向平移',
|
||||
translateY: '纵向平移', reasonCodes: '原因码',
|
||||
@@ -102,6 +103,27 @@ describe('ReviewProfileMatchPanel', () => {
|
||||
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();
|
||||
|
||||
|
||||
@@ -43,6 +43,10 @@ const selectedCoordinateTransform = computed(() => {
|
||||
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}`,
|
||||
@@ -108,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"
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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"
|
||||
|
||||
+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');
|
||||
});
|
||||
|
||||
@@ -73,7 +73,8 @@ describe('shipping order review workbench viewport layout contract', () => {
|
||||
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/);
|
||||
});
|
||||
});
|
||||
@@ -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),
|
||||
|
||||
@@ -741,6 +741,110 @@ describe('useShippingOrderReview build eligibility writes', () => {
|
||||
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();
|
||||
@@ -828,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);
|
||||
@@ -427,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,
|
||||
@@ -469,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
|
||||
@@ -486,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 {
|
||||
@@ -502,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,
|
||||
@@ -594,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;
|
||||
@@ -869,59 +907,134 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
|
||||
const generation = ++caseLoadGeneration;
|
||||
++intakeParseRequestGeneration;
|
||||
requestedCaseNo.value = String(preferredCaseNo || '').trim() || null;
|
||||
loading.value = true;
|
||||
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();
|
||||
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;
|
||||
extractionLifecycleProgress.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),
|
||||
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;
|
||||
// [STREAM] Run 替代不等于其内全部 PDF 替代;当前文件只由队列 Stream 裁决。
|
||||
const caseNo = preferredCaseNo || queue.items[0]?.case_no || run.items[0]?.case_no;
|
||||
const caseSnapshot = caseNo ? await getWorkspaceShippingOrderReviewCase(caseNo) : null;
|
||||
if (generation !== caseLoadGeneration) return;
|
||||
extractionLifecycleProgress.value = run.lifecycle_progress || null;
|
||||
applyCaseSnapshot(caseSnapshot);
|
||||
const caseEvidence = caseNo ? await getWorkspaceShippingOrderReviewEvidence(caseNo) : null;
|
||||
if (generation !== caseLoadGeneration) return;
|
||||
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 = true;
|
||||
reviewRun.value = null;
|
||||
activeCase.value = null;
|
||||
reviewProgressContext.value = null;
|
||||
reviewQueue.value = null;
|
||||
versions.value = [];
|
||||
statusMessage.value = null;
|
||||
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 {
|
||||
if (generation !== caseLoadGeneration) return;
|
||||
loading.value = false;
|
||||
if (isInitialLoad) initialLoading.value = false;
|
||||
runLoading.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1269,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(
|
||||
@@ -1331,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;
|
||||
@@ -1458,6 +1577,7 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
|
||||
caseProjectionVersion,
|
||||
caseLoadingContext,
|
||||
reviewProgressContext,
|
||||
extractionLifecycleProgress,
|
||||
shippingProcessingProjection,
|
||||
authoritativeOrderTaskNo,
|
||||
shippingProcessingLoading,
|
||||
@@ -1497,7 +1617,9 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
|
||||
clearPreview,
|
||||
showWorkflowProgress,
|
||||
workflowProgressPolling,
|
||||
loading,
|
||||
initialLoading,
|
||||
runLoading,
|
||||
runSwitchFailed,
|
||||
loadFailed,
|
||||
caseSwitchLoading,
|
||||
caseSwitchFailed,
|
||||
|
||||
@@ -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 与物理文件,不按库存源猜测文件。
|
||||
@@ -64,3 +73,25 @@ async function downloadWorkspaceShippingFile(url: string, fallbackName: string):
|
||||
export const downloadWorkspaceShippingExportArchive = (payload: {
|
||||
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);
|
||||
}
|
||||
@@ -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);
|
||||
|
||||
@@ -90,6 +90,7 @@ export type ShippingProcessingActionIntent =
|
||||
| 'open_inventory_match_review'
|
||||
| 'open_shortage_review'
|
||||
| 'upload_inventory_file'
|
||||
| 'reload_inventory_result'
|
||||
| 'retry_inventory_preparation'
|
||||
| 'retry_inventory_matching'
|
||||
| 'retry_parse'
|
||||
@@ -824,9 +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;
|
||||
/** 通知单列表只读行摘要;库存数据由后端当前匹配事实投影,前端不得自行计算。 */
|
||||
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;
|
||||
@@ -1053,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'
|
||||
@@ -1599,6 +1614,27 @@ export interface ShippingUiStateEventPayload {
|
||||
source?: string;
|
||||
}
|
||||
|
||||
/** 订单工作台货代上传区的 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 ShippingFreightNoticeGroupsResponse {
|
||||
po_number: string | null;
|
||||
items: ShippingFreightNoticeGroup[];
|
||||
reason?: 'po_missing' | 'no_business_notice' | string | null;
|
||||
}
|
||||
|
||||
export interface ShippingInventoryUploadResponse {
|
||||
status: string;
|
||||
message?: string;
|
||||
@@ -1811,6 +1847,19 @@ 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 编号单独读取。
|
||||
*/
|
||||
@@ -1864,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;
|
||||
@@ -1975,6 +2025,8 @@ 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;
|
||||
@@ -2245,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 {
|
||||
@@ -2480,10 +2534,6 @@ 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;
|
||||
/** 结构化文档证据或兼容字符串,可跳转证据查看器定位对应区域。 */
|
||||
evidence_ref?: Record<string, unknown> | string | null;
|
||||
}
|
||||
@@ -2502,18 +2552,6 @@ export interface ShippingOrderReviewFieldConflict {
|
||||
observation_ids?: string[];
|
||||
/** 后端给出的下一步恢复动作;例如 reparse_current_pdf。 */
|
||||
recovery_action?: string | null;
|
||||
/** 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;
|
||||
}
|
||||
|
||||
export interface ShippingOrderReviewCase {
|
||||
@@ -3039,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;
|
||||
}
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
* 逻辑:标准模式无对话上下文、无常驻 PDF 列;底栏无「确认并创建任务」;
|
||||
* 正式 OT / STP 对象级重试走 /retry 或 STP retry;敏感面板审计失败不打开。
|
||||
*/
|
||||
import { describe, expect, it, vi, beforeEach } from 'vitest';
|
||||
import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest';
|
||||
import { computed, nextTick, ref } from 'vue';
|
||||
import { flushPromises, mount } from '@vue/test-utils';
|
||||
import { createI18n } from 'vue-i18n';
|
||||
@@ -16,21 +16,34 @@ import { CHAT_PAGE_KEY } from '@/features/chat/composables/chat.context';
|
||||
import {
|
||||
auditWorkspaceShippingOrderReviewEligibilityDetails,
|
||||
auditWorkspaceShippingOrderReviewVersionHistory,
|
||||
getWorkspaceShippingFreightNoticeGroups,
|
||||
getWorkspaceShippingTask,
|
||||
decideWorkspaceShippingOrderReviewLineFulfillment,
|
||||
waveWorkspaceShippingOrderReviewLineFulfillment,
|
||||
retryWorkspaceShippingOrderStpAutoCreate,
|
||||
retryShippingNoticeIntake,
|
||||
} from '@/features/chat/api/shipping.api';
|
||||
|
||||
const { batchConfirmFreightMock, batchRpaFreightMock, downloadFreightArchiveMock } = vi.hoisted(() => ({
|
||||
batchConfirmFreightMock: vi.fn().mockResolvedValue({ results: [] }),
|
||||
batchRpaFreightMock: vi.fn().mockResolvedValue({ results: [] }),
|
||||
downloadFreightArchiveMock: vi.fn().mockResolvedValue(undefined),
|
||||
}));
|
||||
|
||||
const { downloadWorkspaceShippingLineInventoryFileMock } = vi.hoisted(() => ({
|
||||
downloadWorkspaceShippingLineInventoryFileMock: vi.fn().mockResolvedValue(undefined),
|
||||
}));
|
||||
const { downloadWorkspaceShippingExcelFileMock } = vi.hoisted(() => ({
|
||||
downloadWorkspaceShippingExcelFileMock: vi.fn().mockResolvedValue(undefined),
|
||||
}));
|
||||
const { downloadWorkspaceShippingNoticeExcelFileMock } = vi.hoisted(() => ({
|
||||
downloadWorkspaceShippingNoticeExcelFileMock: vi.fn().mockResolvedValue(undefined),
|
||||
}));
|
||||
|
||||
vi.mock('@/features/chat/shipping/shippingDownload', () => ({
|
||||
downloadWorkspaceShippingLineInventoryFile: downloadWorkspaceShippingLineInventoryFileMock,
|
||||
downloadWorkspaceShippingNoticeExcelFile: downloadWorkspaceShippingNoticeExcelFileMock,
|
||||
downloadWorkspaceShippingNoticeExportArchive: downloadFreightArchiveMock,
|
||||
}));
|
||||
vi.mock('@/features/workspace/api/shipping-tasks.api', () => ({
|
||||
downloadWorkspaceShippingExcelFile: downloadWorkspaceShippingExcelFileMock,
|
||||
@@ -44,10 +57,16 @@ const ensureIntakeParseContextLoaded = vi.fn().mockResolvedValue(true);
|
||||
const confirmMock = vi.fn();
|
||||
const reloadLatestDraftMock = vi.fn().mockResolvedValue(undefined);
|
||||
const refreshShippingProcessingMock = vi.fn().mockResolvedValue(undefined);
|
||||
const startWorkflowProgressPollingMock = vi.fn();
|
||||
const patchLineMock = vi.fn().mockResolvedValue(undefined);
|
||||
const { submitProcessGatePrimaryActionMock } = vi.hoisted(() => ({
|
||||
submitProcessGatePrimaryActionMock: vi.fn().mockResolvedValue({ outcome: 'submitted' }),
|
||||
}));
|
||||
|
||||
/**
|
||||
* 本文件每个用例均挂载完整工作台;统一卸载,避免跨用例残留 watch/router 响应式副作用。
|
||||
*/
|
||||
const mountedWrappers: Array<{ unmount: () => void }> = [];
|
||||
const { postFormalGateActionMock } = vi.hoisted(() => ({
|
||||
postFormalGateActionMock: vi.fn().mockResolvedValue({}),
|
||||
}));
|
||||
@@ -105,12 +124,20 @@ const reviewQueue = ref({
|
||||
});
|
||||
const workItem = ref<Record<string, any> | null>(null);
|
||||
const reviewProgressContext = ref<Record<string, any> | null>(null);
|
||||
/** Run 解析中的用户态进度;与真实 composable 返回契约保持一致。 */
|
||||
const extractionLifecycleProgress = ref<Record<string, any> | null>(null);
|
||||
/** 旧重解析横幅状态;回归用例确认它不再驱动独立黄色进度提示。 */
|
||||
const statusMessage = ref<string | null>(null);
|
||||
const runLoading = ref(false);
|
||||
const runSwitchFailed = ref(false);
|
||||
/** 与 activeCase 同源共享,供断言 Progress 优先阶段源。 */
|
||||
const shippingProcessingProjection = ref<Record<string, any> | null>(null);
|
||||
/** 正式任务投影的请求中状态;用于覆盖 Case 先到、Projection 后到的过渡窗口。 */
|
||||
const shippingProcessingLoading = ref(false);
|
||||
const intakeParseContext = ref<Record<string, any> | null>(null);
|
||||
const requestedCaseNo = ref<string | null>(null);
|
||||
const reviewEditable = ref(true);
|
||||
const reviewFormalEditable = ref(false);
|
||||
|
||||
/** 每个用例必须从独立的 Case 图快照开始,避免嵌套 schema/draft 被浅拷贝污染。 */
|
||||
function createActiveCaseFixture() {
|
||||
@@ -170,6 +197,7 @@ vi.mock('@/features/chat/api/shipping.api', async (importOriginal) => {
|
||||
auditWorkspaceShippingOrderReviewVersionHistory: vi.fn().mockResolvedValue({ audited: true, case_no: 'CASE-1' }),
|
||||
auditWorkspaceShippingOrderReviewEligibilityDetails: vi.fn().mockResolvedValue({ audited: true, case_no: 'CASE-1' }),
|
||||
decideWorkspaceShippingOrderReviewLineFulfillment: vi.fn().mockResolvedValue({ status: 'ok' }),
|
||||
waveWorkspaceShippingOrderReviewLineFulfillment: vi.fn().mockResolvedValue({ status: 'ok' }),
|
||||
retryWorkspaceShippingOrderStpAutoCreate: vi.fn().mockResolvedValue({
|
||||
status: 'queued',
|
||||
job_id: 901,
|
||||
@@ -180,6 +208,9 @@ vi.mock('@/features/chat/api/shipping.api', async (importOriginal) => {
|
||||
task_no: 'SN-MOCK',
|
||||
status: 'created',
|
||||
}),
|
||||
getWorkspaceShippingFreightNoticeGroups: vi.fn().mockResolvedValue({ items: [] }),
|
||||
batchConfirmWorkspaceShippingNoticesUploaded: (...args: unknown[]) => batchConfirmFreightMock(...args),
|
||||
batchStartWorkspaceShippingNoticeRpaUpload: (...args: unknown[]) => batchRpaFreightMock(...args),
|
||||
};
|
||||
});
|
||||
|
||||
@@ -209,6 +240,7 @@ function createReviewComposableMock() {
|
||||
caseProjectionVersion: ref(1),
|
||||
caseLoadingContext: ref(null),
|
||||
reviewProgressContext,
|
||||
extractionLifecycleProgress,
|
||||
workItem,
|
||||
authoritativeOrderTaskNo: computed(() => {
|
||||
const no = String(reviewProgressContext.value?.user_task_no || '').trim();
|
||||
@@ -216,7 +248,7 @@ function createReviewComposableMock() {
|
||||
return no;
|
||||
}),
|
||||
versions: ref([]),
|
||||
statusMessage: ref(null),
|
||||
statusMessage,
|
||||
draftConflict: ref(null),
|
||||
draftConflictDiffLines: ref([]),
|
||||
buildEligibility: ref({ can_build: true, issues: [], lines: [] }),
|
||||
@@ -224,7 +256,9 @@ function createReviewComposableMock() {
|
||||
routingRecoveryLines: ref([]),
|
||||
isViewingHistoricalVersion: computed(() => false),
|
||||
isReadOnly: computed(() => false),
|
||||
loading: ref(false),
|
||||
initialLoading: ref(false),
|
||||
runLoading,
|
||||
runSwitchFailed,
|
||||
loadFailed: ref(false),
|
||||
caseSwitchLoading: ref(false),
|
||||
caseSwitchFailed: ref(false),
|
||||
@@ -281,13 +315,14 @@ function createReviewComposableMock() {
|
||||
clearEvidenceDrawerFocus: vi.fn(),
|
||||
requestSuggestion: vi.fn(),
|
||||
decideSuggestion: vi.fn(),
|
||||
editable: computed(() => true),
|
||||
formalEditable: computed(() => false),
|
||||
editable: computed(() => reviewEditable.value),
|
||||
formalEditable: computed(() => reviewFormalEditable.value),
|
||||
canEditFormalFields: computed(() => false),
|
||||
isFieldEditable: () => true,
|
||||
isWorkItemClosed: computed(() => false),
|
||||
showWorkflowProgress: computed(() => false),
|
||||
workflowProgressPolling: computed(() => false),
|
||||
startWorkflowProgressPolling: startWorkflowProgressPollingMock,
|
||||
shippingProcessingProjection,
|
||||
shippingProcessingLoading,
|
||||
shippingProcessingError: ref(null),
|
||||
@@ -604,6 +639,7 @@ async function mountView(query: Record<string, string> = {}) {
|
||||
lifecycle: {
|
||||
navigation: '订单生命周期阶段',
|
||||
current: '当前可处理',
|
||||
processing: '处理中',
|
||||
prerequisite: '请先完成当前阶段',
|
||||
stages: {
|
||||
intake_parse: '接收解析',
|
||||
@@ -642,6 +678,10 @@ async function mountView(query: Record<string, string> = {}) {
|
||||
stageLabel: {
|
||||
waiting_system_start: '等待系统启动',
|
||||
},
|
||||
progress: {
|
||||
step: { profile_matching: '正在匹配订单模板' },
|
||||
lifecycleReason: { processing_slow: '当前步骤耗时较长,系统仍在继续。' },
|
||||
},
|
||||
},
|
||||
shippingSessionWorkItem: {
|
||||
versionLabel: 'V{version}',
|
||||
@@ -676,6 +716,7 @@ async function mountView(query: Record<string, string> = {}) {
|
||||
[CHAT_PAGE_KEY as symbol]: {
|
||||
conversationId: 'conv-1',
|
||||
messages: [],
|
||||
bumpWorkflowRefresh: vi.fn(),
|
||||
},
|
||||
},
|
||||
stubs: {
|
||||
@@ -693,6 +734,7 @@ async function mountView(query: Record<string, string> = {}) {
|
||||
},
|
||||
},
|
||||
});
|
||||
mountedWrappers.push(wrapper);
|
||||
await flushPromises();
|
||||
return wrapper;
|
||||
}
|
||||
@@ -700,21 +742,79 @@ async function mountView(query: Record<string, string> = {}) {
|
||||
/** 将共享 Case fixture 恢复为可编辑草稿,避免跨用例污染确认恢复态。 */
|
||||
function resetActiveCaseFixture() {
|
||||
activeCase.value = createActiveCaseFixture();
|
||||
reviewRun.value = {
|
||||
run_no: 'RUN-1',
|
||||
items: [{
|
||||
case_no: 'CASE-1', document_id: 1, file_name: 'po.pdf', status: 'draft',
|
||||
issue_count: 0, available_actions: ['validate', 'confirm'],
|
||||
}],
|
||||
};
|
||||
requestedCaseNo.value = null;
|
||||
shippingProcessingProjection.value = null;
|
||||
shippingProcessingLoading.value = false;
|
||||
intakeParseContext.value = null;
|
||||
extractionLifecycleProgress.value = null;
|
||||
statusMessage.value = null;
|
||||
runLoading.value = false;
|
||||
runSwitchFailed.value = false;
|
||||
}
|
||||
|
||||
describe('ShippingOrderReviewView layout phase 1', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.useRealTimers();
|
||||
ensureIntakeParseContextLoaded.mockResolvedValue(true);
|
||||
resetActiveCaseFixture();
|
||||
reviewEditable.value = true;
|
||||
reviewFormalEditable.value = false;
|
||||
workItem.value = null;
|
||||
reviewProgressContext.value = null;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
while (mountedWrappers.length) {
|
||||
mountedWrappers.pop()?.unmount();
|
||||
}
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it('puts customer PO line first and excludes internal line number and inventory source from the main table', async () => {
|
||||
activeCase.value = {
|
||||
...activeCase.value,
|
||||
schema: {
|
||||
...activeCase.value.schema,
|
||||
fields: [
|
||||
...activeCase.value.schema.fields,
|
||||
{ field_id: 'fld-line-no', field_code: 'line_no', display_name: '内部项次', scope: 'line', value_type: 'string', required: true, options: [] },
|
||||
{ field_id: 'fld-customer-po-line', field_code: 'customer_po_line_no', display_name: '客户 PO 项次', scope: 'line', value_type: 'string', required: true, options: [] },
|
||||
{ field_id: 'fld-part-number', field_code: 'part_number', display_name: '料号', scope: 'line', value_type: 'string', required: true, options: [] },
|
||||
],
|
||||
},
|
||||
draft: {
|
||||
...activeCase.value.draft,
|
||||
lines: [{
|
||||
line_key: 'LINE-1',
|
||||
values: {
|
||||
'fld-line-no': { value: '10' },
|
||||
'fld-customer-po-line': { value: '00010' },
|
||||
'fld-part-number': { value: 'PN-ONE' },
|
||||
'fld-inventory-source-hint': { value: 'DBS' },
|
||||
},
|
||||
machine_fields: [],
|
||||
}],
|
||||
},
|
||||
};
|
||||
|
||||
const wrapper = await mountView();
|
||||
const headers = wrapper.find('[data-testid="review-lines-scroll"]').findAll('th').map((item) => item.text());
|
||||
|
||||
// 关键断言:业务主键首列,内部项次和库存源线索不挤占默认主表宽度。
|
||||
expect(headers.slice(0, 3)).toEqual(['#', '客户 PO 项次 *', '料号 *']);
|
||||
expect(headers).not.toContain('内部项次 *');
|
||||
expect(headers).not.toContain('库存源');
|
||||
expect(wrapper.find('[data-testid="review-line-inventory-source"]').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it('keeps the requested replacement Case when the loaded Run updates the URL', async () => {
|
||||
// 关键断言:新版 Run 先到而旧 URL Case 仍在时,不能拼出 RUN-NEW + CASE-OLD。
|
||||
const wrapper = await mountView({ case_no: 'CASE-OLD' });
|
||||
@@ -729,6 +829,50 @@ describe('ShippingOrderReviewView layout phase 1', () => {
|
||||
expect((wrapper.vm as any).$route.query.case_no).toBe('CASE-NEW');
|
||||
});
|
||||
|
||||
it('shows the five-stage Run progress and current parsing step before a Case is available', async () => {
|
||||
activeCase.value = null as any;
|
||||
reviewRun.value = { run_no: 'RUN-PARSING', items: [] };
|
||||
extractionLifecycleProgress.value = {
|
||||
lifecycle_stage: 'intake_parse', lifecycle_status: 'running',
|
||||
current_step_i18n_key: 'chat.shippingProcessing.progress.step.profile_matching',
|
||||
completed_step_codes: ['layout_parsing_completed'], health_status: 'normal',
|
||||
};
|
||||
const wrapper = await mountView();
|
||||
expect(wrapper.get('[data-testid="review-run-lifecycle-progress"]').exists()).toBe(true);
|
||||
expect(wrapper.get('[data-testid="review-run-lifecycle-current-step"]').text()).toContain('正在匹配订单模板');
|
||||
expect(wrapper.find('[data-testid="review-lifecycle-stage-intake_parse"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="review-lifecycle-stage-upload_complete"]').exists()).toBe(true);
|
||||
});
|
||||
|
||||
it('keeps the compact Run progress visible with a stable stalled reason', async () => {
|
||||
activeCase.value = null as any;
|
||||
reviewRun.value = { run_no: 'RUN-STALLED', items: [] };
|
||||
extractionLifecycleProgress.value = {
|
||||
lifecycle_stage: 'intake_parse', lifecycle_status: 'running',
|
||||
current_step_i18n_key: 'chat.shippingProcessing.progress.step.profile_matching',
|
||||
blocking_reason_i18n_key: 'chat.shippingProcessing.progress.lifecycleReason.processing_slow',
|
||||
completed_step_codes: [], health_status: 'attention',
|
||||
};
|
||||
const wrapper = await mountView();
|
||||
expect(wrapper.get('[data-testid="review-run-lifecycle-current-step"]').text()).toContain('当前步骤耗时较长');
|
||||
});
|
||||
|
||||
it('uses the lifecycle progress below navigation instead of a legacy yellow reparse banner', async () => {
|
||||
extractionLifecycleProgress.value = {
|
||||
lifecycle_stage: 'intake_parse', lifecycle_status: 'running',
|
||||
current_step_i18n_key: 'chat.shippingProcessing.progress.step.profile_matching',
|
||||
completed_step_codes: ['layout_parsing_completed'], health_status: 'normal',
|
||||
};
|
||||
statusMessage.value = 'reparse_in_progress';
|
||||
|
||||
const wrapper = await mountView();
|
||||
|
||||
// 关键断言:重解析不再拥有第二条黄色横幅;唯一进度紧跟五阶段导航。
|
||||
expect(wrapper.find('[data-testid="review-status-banner"]').exists()).toBe(false);
|
||||
expect(wrapper.findAll('[data-testid="review-run-lifecycle-progress"]')).toHaveLength(1);
|
||||
expect(wrapper.get('[data-testid="review-run-lifecycle-progress"]').text()).toContain('正在匹配订单模板');
|
||||
});
|
||||
|
||||
it('loads a cross-Run file once through the route watcher', async () => {
|
||||
const originalQueue = reviewQueue.value;
|
||||
try {
|
||||
@@ -759,6 +903,47 @@ describe('ShippingOrderReviewView layout phase 1', () => {
|
||||
}
|
||||
});
|
||||
|
||||
it('keeps old workbench content in place and shows only a non-layout-shifting loading indicator while a cross-Run target is loading', async () => {
|
||||
// 关键断言:跨 Run 不能插入大块 skeleton 把旧内容推离视口;仅允许无布局占位的轻提示。
|
||||
runLoading.value = true;
|
||||
const wrapper = await mountView();
|
||||
|
||||
const shell = wrapper.get('[data-testid="review-case-workbench-shell"]');
|
||||
expect(wrapper.find('[data-testid="review-workbench-scroll"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="review-case-switch-loading"]').exists()).toBe(false);
|
||||
expect(wrapper.get('[data-testid="review-case-switch-indicator"]').exists()).toBe(true);
|
||||
expect(shell.attributes('aria-busy')).toBe('true');
|
||||
expect(shell.classes()).toContain('pointer-events-none');
|
||||
expect((wrapper.vm as any).workbenchActionsExecutable).toBe(false);
|
||||
});
|
||||
|
||||
it('does not read freight Notice groups while the selected file is outside freight upload', async () => {
|
||||
// 关键断言:货代 Notice 聚合只服务货代上传面,不能加入普通文件切换关键路径。
|
||||
activeCase.value = {
|
||||
...activeCase.value,
|
||||
status: 'confirmed', confirmed_task_no: 'SN-NOTICE-PREP', confirmed_task_id: 91, has_formal_ot: true,
|
||||
};
|
||||
const taskApi = await import('@/features/chat/api/shipping.api');
|
||||
vi.mocked(taskApi.getWorkspaceShippingTask).mockResolvedValue({
|
||||
task_no: 'SN-NOTICE-PREP', status: 'processing', lines: [], events: [],
|
||||
ui_state: { lifecycle_stage: 'fulfillment_prep', lifecycle_entries: [], actions: { primary: null, secondary: [] } },
|
||||
} as any);
|
||||
|
||||
await mountView({ lifecycle_stage: 'fulfillment_prep' });
|
||||
await flushPromises();
|
||||
|
||||
expect(taskApi.getWorkspaceShippingFreightNoticeGroups).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('keeps the workbench shell visible with a local retry state when cross-Run loading fails', async () => {
|
||||
// 关键断言:跨 Run 失败不能进入页面级 unavailable 分支,旧文件仍可见且可重试。
|
||||
runSwitchFailed.value = true;
|
||||
const wrapper = await mountView();
|
||||
expect(wrapper.find('[data-testid="review-workbench-scroll"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="shipping-order-review-load-failed"]').exists()).toBe(false);
|
||||
expect(wrapper.get('[data-testid="review-run-switch-failed"]').exists()).toBe(true);
|
||||
});
|
||||
|
||||
it('uses the current-task card as the only Gate action entry for every formal-OT Gate', async () => {
|
||||
activeCase.value = {
|
||||
...activeCase.value,
|
||||
@@ -806,7 +991,7 @@ describe('ShippingOrderReviewView layout phase 1', () => {
|
||||
expect(wrapper.find('[data-testid="mock-process-gate"]').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it('submits a server-authorized Gate action from the current-task card without an action-code alias', async () => {
|
||||
it('does not expose Excel regeneration from the current-task card', async () => {
|
||||
activeCase.value = {
|
||||
...activeCase.value,
|
||||
status: 'confirmed', has_formal_ot: true, task_missing: false,
|
||||
@@ -858,19 +1043,10 @@ describe('ShippingOrderReviewView layout phase 1', () => {
|
||||
|
||||
const wrapper = await mountView();
|
||||
await flushPromises();
|
||||
await wrapper.get('[data-testid="review-current-task-primary-action"]').trigger('click');
|
||||
await flushPromises();
|
||||
|
||||
// 关键断言:旧 Projection 的 regenerate_excel 不可执行;正式任务的原始动作码
|
||||
// 只委托统一 Gate 执行器,由其按后端版本与授权再次校验。
|
||||
expect(submitProcessGatePrimaryActionMock).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
execution_no: 'EXEC-EXCEL-1',
|
||||
current_blocking_gate: expect.objectContaining({ gate_code: 'artifact_generation' }),
|
||||
}),
|
||||
{ actionCode: 'regenerate_excel_artifact' },
|
||||
);
|
||||
// 关键断言:Excel Artifact 属于发货通知单对象,右侧任务摘要不得提供写入口。
|
||||
expect(wrapper.find('[data-testid="review-current-task-primary-action"]').exists()).toBe(false);
|
||||
expect(postFormalGateActionMock).not.toHaveBeenCalled();
|
||||
expect(submitProcessGatePrimaryActionMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('does not submit an action merely because its code has a Gate-like prefix', async () => {
|
||||
@@ -1461,6 +1637,86 @@ describe('ShippingOrderReviewView layout phase 1', () => {
|
||||
expect(orderFooter.text()).toContain('提交订单');
|
||||
});
|
||||
|
||||
it('switches the workbench to the backend current stage and marks it processing', async () => {
|
||||
const originalQueue = reviewQueue.value;
|
||||
try {
|
||||
reviewQueue.value = {
|
||||
...reviewQueue.value,
|
||||
items: [{
|
||||
...reviewQueue.value.items[0],
|
||||
lifecycle_stage: 'order_review',
|
||||
lifecycle_entries: [
|
||||
{ code: 'intake_parse', state: 'available', targetSurface: 'order_lifecycle_workbench' },
|
||||
{ code: 'order_review', state: 'current', targetSurface: 'order_lifecycle_workbench' },
|
||||
{ code: 'fulfillment_prep', state: 'unavailable', targetSurface: 'order_lifecycle_workbench' },
|
||||
{ code: 'freight_upload', state: 'unavailable', targetSurface: 'order_lifecycle_workbench' },
|
||||
{ code: 'upload_complete', state: 'unavailable', targetSurface: 'order_lifecycle_workbench' },
|
||||
],
|
||||
}],
|
||||
};
|
||||
const wrapper = await mountView({ lifecycle_stage: 'order_review' });
|
||||
shippingProcessingProjection.value = {
|
||||
stage: 'inventory_preparation', status: 'processing',
|
||||
uiState: {
|
||||
status: 'running', lifecycleStage: 'fulfillment_prep', lifecycleEntries: [],
|
||||
primary_action: null, secondary_actions: [],
|
||||
},
|
||||
};
|
||||
reviewQueue.value = {
|
||||
...reviewQueue.value,
|
||||
items: [{
|
||||
...reviewQueue.value.items[0],
|
||||
lifecycle_stage: 'fulfillment_prep',
|
||||
lifecycle_entries: [
|
||||
{ code: 'intake_parse', state: 'available', targetSurface: 'order_lifecycle_workbench' },
|
||||
{ code: 'order_review', state: 'available', targetSurface: 'order_lifecycle_workbench' },
|
||||
{ code: 'fulfillment_prep', state: 'current', targetSurface: 'order_lifecycle_workbench' },
|
||||
{ code: 'freight_upload', state: 'unavailable', targetSurface: 'order_lifecycle_workbench' },
|
||||
{ code: 'upload_complete', state: 'unavailable', targetSurface: 'order_lifecycle_workbench' },
|
||||
],
|
||||
}],
|
||||
};
|
||||
await flushPromises();
|
||||
|
||||
// 关键断言:后端已推进时,仍停在旧当前阶段的页面必须自动进入新工作面并标注处理中。
|
||||
expect((wrapper.vm as any).$router.currentRoute.value.query.lifecycle_stage).toBe('fulfillment_prep');
|
||||
expect(wrapper.get('[data-testid="review-lifecycle-stage-fulfillment_prep"]').attributes('data-processing')).toBe('1');
|
||||
} finally {
|
||||
reviewQueue.value = originalQueue;
|
||||
shippingProcessingProjection.value = null;
|
||||
}
|
||||
});
|
||||
|
||||
it('keeps a manually selected completed stage after the backend has already advanced', async () => {
|
||||
const originalQueue = reviewQueue.value;
|
||||
try {
|
||||
reviewQueue.value = {
|
||||
...reviewQueue.value,
|
||||
items: [{
|
||||
...reviewQueue.value.items[0],
|
||||
lifecycle_stage: 'fulfillment_prep',
|
||||
lifecycle_entries: [
|
||||
{ code: 'intake_parse', state: 'available', targetSurface: 'order_lifecycle_workbench' },
|
||||
{ code: 'order_review', state: 'available', targetSurface: 'order_lifecycle_workbench' },
|
||||
{ code: 'fulfillment_prep', state: 'current', targetSurface: 'order_lifecycle_workbench' },
|
||||
{ code: 'freight_upload', state: 'unavailable', targetSurface: 'order_lifecycle_workbench' },
|
||||
{ code: 'upload_complete', state: 'unavailable', targetSurface: 'order_lifecycle_workbench' },
|
||||
],
|
||||
}],
|
||||
};
|
||||
const wrapper = await mountView({ lifecycle_stage: 'fulfillment_prep' });
|
||||
|
||||
await wrapper.get('[data-testid="review-lifecycle-stage-order_review"]').findAll('button')[1].trigger('click');
|
||||
await flushPromises();
|
||||
|
||||
// 后端并未再次推进时,主动回看订单复核必须保持该工作面,不能被 watcher 改回通知准备。
|
||||
expect((wrapper.vm as { $route: { query: Record<string, string> } }).$route.query.lifecycle_stage)
|
||||
.toBe('order_review');
|
||||
} finally {
|
||||
reviewQueue.value = originalQueue;
|
||||
}
|
||||
});
|
||||
|
||||
it('does not request intake context when its lifecycle entry is missing or unavailable', async () => {
|
||||
shippingProcessingProjection.value = {
|
||||
uiState: {
|
||||
@@ -1643,7 +1899,7 @@ describe('ShippingOrderReviewView layout phase 1', () => {
|
||||
expect(messageMocks.warning).not.toHaveBeenCalledWith('处理结果尚未生成');
|
||||
});
|
||||
|
||||
it('uses case line fulfillment as a read-only fallback when formal preparation rows are temporarily empty', async () => {
|
||||
it('normalizes Decimal quantity display in the case fallback while formal preparation rows are temporarily empty', async () => {
|
||||
const taskApi = await import('@/features/chat/api/shipping.api');
|
||||
// 正式任务详情延迟/失败不能阻塞已由 Case 投影下发的只读库存匹配事实。
|
||||
vi.mocked(taskApi.getWorkspaceShippingTask).mockRejectedValue(new Error('detail unavailable'));
|
||||
@@ -1656,7 +1912,7 @@ describe('ShippingOrderReviewView layout phase 1', () => {
|
||||
line_fulfillment: {
|
||||
lines: [{
|
||||
line_key: 'line-1', reservation_id: 'RSV-FALLBACK', part_number: 'PN-FALLBACK',
|
||||
required_qty: '8', available_qty: '5', shortage_qty: '3', inventory_source_code: 'DBS_DUB',
|
||||
required_qty: '8.0', available_qty: '5.0', shortage_qty: '3.0', inventory_source_code: 'DBS_DUB',
|
||||
}],
|
||||
},
|
||||
};
|
||||
@@ -1674,7 +1930,9 @@ describe('ShippingOrderReviewView layout phase 1', () => {
|
||||
|
||||
expect(wrapper.get('[data-testid="review-lifecycle-fulfillment-prep"]').text()).toContain('RSV-FALLBACK');
|
||||
expect(wrapper.get('[data-testid="review-lifecycle-fulfillment-prep"]').text()).toContain('PN-FALLBACK');
|
||||
expect(wrapper.get('[data-testid="review-lifecycle-fulfillment-prep"]').text()).toContain('3');
|
||||
const preparationText = wrapper.get('[data-testid="review-lifecycle-fulfillment-prep"]').text();
|
||||
expect(preparationText).toContain('3');
|
||||
expect(preparationText).not.toContain('3.0');
|
||||
expect(wrapper.find('[data-testid="review-fulfillment-prep-workspace"]').exists()).toBe(true);
|
||||
expect(messageMocks.warning).not.toHaveBeenCalledWith('处理结果尚未生成');
|
||||
// 通知准备工作区必须属于五阶段导航的下方主区,不能仍停留在导航之前的状态摘要区。
|
||||
@@ -1712,6 +1970,14 @@ describe('ShippingOrderReviewView layout phase 1', () => {
|
||||
vi.mocked(taskApi.getWorkspaceShippingTask).mockResolvedValue({
|
||||
task_no: 'SN-FROZEN', status: 'processing', lines: [], events: [],
|
||||
ui_state: {
|
||||
process_gate: {
|
||||
execution_no: 'EXEC-FROZEN-LINE',
|
||||
current_blocking_gate: { gate_code: 'inventory_preparation', status: 'blocked_retryable' },
|
||||
},
|
||||
actions: {
|
||||
primary: { code: 'retry_inventory_preparation', enabled: true, dispatch: 'mutation' },
|
||||
secondary: [],
|
||||
},
|
||||
lifecycle_stage: 'fulfillment_prep', lifecycle_entries: [{ code: 'fulfillment_prep', state: 'current' }],
|
||||
stage_context: {
|
||||
preparation: {
|
||||
@@ -1735,6 +2001,12 @@ describe('ShippingOrderReviewView layout phase 1', () => {
|
||||
|
||||
// 关键断言:订单基线列和库存事实合为唯一行级工作表,库存源不得退化为任务级 CRANE。
|
||||
const workspace = wrapper.get('[data-testid="review-fulfillment-prep-workspace"]');
|
||||
// 关键交互断言:明细在窄视口保持横向可读,行级操作列固定在右侧。
|
||||
expect(workspace.classes()).toContain('review-fulfillment-prep-workspace');
|
||||
expect(workspace.classes()).toContain('overflow-x-auto');
|
||||
expect(workspace.get('table').classes()).toContain('review-fulfillment-prep-table');
|
||||
expect(workspace.get('thead th:last-child').classes()).toContain('review-fulfillment-sticky-action-head');
|
||||
expect(workspace.get('tbody tr:first-child td:last-child').classes()).toContain('review-fulfillment-sticky-action-cell');
|
||||
expect(workspace.text()).toContain('RSV-FROZEN');
|
||||
expect(workspace.text()).toContain('PN-FROZEN');
|
||||
expect(workspace.text()).toContain('DBS');
|
||||
@@ -1756,6 +2028,8 @@ describe('ShippingOrderReviewView layout phase 1', () => {
|
||||
payload: { line_key: 'line-frozen' },
|
||||
}),
|
||||
);
|
||||
// Gate 恢复受理后立即启动五阶段轮询,不依赖浏览器手动刷新。
|
||||
expect(startWorkflowProgressPollingMock).toHaveBeenCalledTimes(1);
|
||||
await wrapper.get('[data-testid="review-fulfillment-line-release-line-frozen"]').trigger('click');
|
||||
expect(wrapper.get('[data-testid="review-release-inventory-dialog"]').text()).toContain('ODM ID');
|
||||
expect(wrapper.get('[data-testid="review-release-inventory-dialog"]').text()).toContain('ODM-001');
|
||||
@@ -1768,6 +2042,62 @@ describe('ShippingOrderReviewView layout phase 1', () => {
|
||||
reason: '客户确认分批发货',
|
||||
release_field_values: { '102': 'A-01' },
|
||||
}));
|
||||
// 放行写成功后立即释放弹窗;后续读取不得阻塞用户确认按钮。
|
||||
expect(wrapper.find('[data-testid="review-release-inventory-dialog"]').exists()).toBe(false);
|
||||
expect(startWorkflowProgressPollingMock).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('keeps the manual notice-generation entry in the main workspace for an editable formal task', async () => {
|
||||
const taskApi = await import('@/features/chat/api/shipping.api');
|
||||
reviewEditable.value = false;
|
||||
reviewFormalEditable.value = true;
|
||||
activeCase.value = {
|
||||
...activeCase.value,
|
||||
status: 'confirmed', confirmed_task_id: 904, confirmed_task_no: 'SN-READY', has_formal_ot: true,
|
||||
line_fulfillment: {
|
||||
lines: [{
|
||||
line_key: 'line-ready', line_status: 'pending_decision', can_fulfill_complete_line: true,
|
||||
inventory_source: { code: 'DBS', label: 'DBS', status: 'resolved' },
|
||||
}],
|
||||
},
|
||||
};
|
||||
shippingProcessingProjection.value = {
|
||||
uiState: {
|
||||
lifecycleStage: 'fulfillment_prep',
|
||||
lifecycleEntries: [{ code: 'fulfillment_prep', state: 'current', targetSurface: 'order_lifecycle_workbench' }],
|
||||
primary_action: null,
|
||||
secondary_actions: [],
|
||||
},
|
||||
};
|
||||
vi.mocked(taskApi.getWorkspaceShippingTask).mockResolvedValue({
|
||||
task_no: 'SN-READY', status: 'processing', lines: [], events: [],
|
||||
ui_state: {
|
||||
lifecycle_stage: 'fulfillment_prep', lifecycle_entries: [{ code: 'fulfillment_prep', state: 'current' }],
|
||||
stage_context: {
|
||||
preparation: {
|
||||
status: 'ready', has_match_result: true,
|
||||
lines: [{
|
||||
line_key: 'line-ready', reservation_id: 'RSV-READY', part_number: 'PN-READY',
|
||||
required_qty: '20', available_qty: '65', shortage_qty: '0', source_code: 'DBS', status: 'matched',
|
||||
}],
|
||||
},
|
||||
},
|
||||
},
|
||||
} as any);
|
||||
|
||||
const wrapper = await mountView({ lifecycle_stage: 'fulfillment_prep' });
|
||||
await flushPromises();
|
||||
|
||||
const workspace = wrapper.get('[data-testid="review-fulfillment-prep-workspace"]');
|
||||
expect(workspace.get('[data-testid="review-fulfillment-prep-confirm-wave"]').exists()).toBe(true);
|
||||
expect(wrapper.findComponent({ name: 'ReviewFulfillmentDecisionPanel' }).exists()).toBe(false);
|
||||
|
||||
await workspace.get('[data-testid="review-fulfillment-line-select-line-ready"]').setValue(true);
|
||||
await workspace.get('[data-testid="review-fulfillment-prep-confirm-wave"]').trigger('click');
|
||||
expect(vi.mocked(waveWorkspaceShippingOrderReviewLineFulfillment)).toHaveBeenCalledWith('CASE-1', expect.objectContaining({
|
||||
line_keys: ['line-ready'],
|
||||
expected_draft_version: 1,
|
||||
}));
|
||||
});
|
||||
|
||||
it('keeps intake parse on the standard workbench and removes the inventory return row', async () => {
|
||||
@@ -1953,9 +2283,9 @@ describe('ShippingOrderReviewView layout phase 1', () => {
|
||||
} finally {
|
||||
reviewQueue.value = originalQueue;
|
||||
}
|
||||
});
|
||||
}, 15000);
|
||||
|
||||
it('opens the page-level evidence dialog from freight upload when the current-task action is manual upload', async () => {
|
||||
it('keeps manual-upload confirmation out of the current-task card', async () => {
|
||||
activeCase.value = {
|
||||
...activeCase.value,
|
||||
status: 'confirmed', confirmed_task_no: 'SN-UPLOAD-DIALOG', confirmed_task_id: 19, has_formal_ot: true,
|
||||
@@ -1967,7 +2297,7 @@ describe('ShippingOrderReviewView layout phase 1', () => {
|
||||
actions: {
|
||||
primary: {
|
||||
code: 'mark_manual_uploaded', kind: 'forward', enabled: true,
|
||||
dispatch: 'dialog', ui_handler: 'manual_upload_evidence',
|
||||
dispatch: 'dialog', ui_handler: 'manual_upload_confirmation',
|
||||
target_surface: 'freight_upload', target_anchor: 'manual_upload',
|
||||
requires_confirmation: false,
|
||||
},
|
||||
@@ -1975,17 +2305,24 @@ describe('ShippingOrderReviewView layout phase 1', () => {
|
||||
},
|
||||
summary: {}, steps: [],
|
||||
},
|
||||
} as any);
|
||||
|
||||
vi.mocked(taskApi.getWorkspaceShippingFreightNoticeGroups).mockResolvedValue({
|
||||
po_number: 'PO-DOWNLOAD',
|
||||
items: [{ business_no: 'WYC26082401', po_number: 'PO-DOWNLOAD', lines: [
|
||||
{ line_no: '10', part_number: 'PN-ONE', reservation_id: 'RSV-1', shipment_qty: '4' },
|
||||
{ line_no: '20', part_number: 'PN-TWO', reservation_id: 'RSV-2', shipment_qty: '7' },
|
||||
] }],
|
||||
} as any);
|
||||
|
||||
const wrapper = await mountView({ lifecycle_stage: 'freight_upload' });
|
||||
await flushPromises();
|
||||
await wrapper.get('[data-testid="review-current-task-primary-action"]').trigger('click');
|
||||
await flushPromises();
|
||||
|
||||
expect(wrapper.find('[data-testid="manual-upload-evidence-dialog"]').exists()).toBe(true);
|
||||
// 人工确认由主区选中发货通知单后的批量入口处理,右侧不再打开单任务弹窗。
|
||||
expect(wrapper.find('[data-testid="review-current-task-primary-action"]').exists()).toBe(false);
|
||||
expect(wrapper.find('[data-testid="manual-upload-evidence-dialog"]').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it('renders the authorized Excel download in every freight-upload order line instead of the task rail', async () => {
|
||||
it('renders one Notice card and one business_no Excel download for freight upload', async () => {
|
||||
activeCase.value = {
|
||||
...activeCase.value,
|
||||
status: 'confirmed', confirmed_task_no: 'SN-DOWNLOAD-DISPATCH', confirmed_task_id: 20, has_formal_ot: true,
|
||||
@@ -2019,7 +2356,7 @@ describe('ShippingOrderReviewView layout phase 1', () => {
|
||||
actions: {
|
||||
primary: {
|
||||
code: 'mark_manual_uploaded', kind: 'forward', enabled: true,
|
||||
dispatch: 'dialog', ui_handler: 'manual_upload_evidence',
|
||||
dispatch: 'dialog', ui_handler: 'manual_upload_confirmation',
|
||||
requires_confirmation: false,
|
||||
},
|
||||
secondary: [{
|
||||
@@ -2034,6 +2371,13 @@ describe('ShippingOrderReviewView layout phase 1', () => {
|
||||
process_gate: { execution_no: 'EXEC-DOWNLOAD-DISPATCH' }, summary: {}, steps: [],
|
||||
},
|
||||
} as any);
|
||||
vi.mocked(taskApi.getWorkspaceShippingFreightNoticeGroups).mockResolvedValue({
|
||||
po_number: 'PO-DOWNLOAD',
|
||||
items: [{ business_no: 'WYC26082401', po_number: 'PO-DOWNLOAD', lines: [
|
||||
{ line_no: '10', part_number: 'PN-ONE', reservation_id: 'RSV-1', shipment_qty: '4' },
|
||||
{ line_no: '20', part_number: 'PN-TWO', reservation_id: 'RSV-2', shipment_qty: '7' },
|
||||
] }],
|
||||
} as any);
|
||||
|
||||
const wrapper = await mountView({ lifecycle_stage: 'freight_upload' });
|
||||
await flushPromises();
|
||||
@@ -2042,13 +2386,13 @@ describe('ShippingOrderReviewView layout phase 1', () => {
|
||||
expect(rows).toHaveLength(2);
|
||||
expect(rows[0].text()).toContain('PN-ONE');
|
||||
expect(rows[1].text()).toContain('PN-TWO');
|
||||
expect(wrapper.find('[data-testid="review-current-task-recovery-download_excel"]').exists()).toBe(false);
|
||||
expect(wrapper.findAll('[data-testid="review-freight-upload-download"]').length).toBeGreaterThanOrEqual(1);
|
||||
|
||||
await wrapper.get('[data-testid="review-freight-upload-download-LINE-1"]').trigger('click');
|
||||
await wrapper.get('[data-testid="review-freight-upload-download"]').trigger('click');
|
||||
await flushPromises();
|
||||
|
||||
// 下载是 Artifact 只读操作;订单行不按 PO 聚合,且不得伪装成 Gate mutation。
|
||||
expect(downloadWorkspaceShippingExcelFileMock).toHaveBeenCalledWith('SN-DOWNLOAD-DISPATCH');
|
||||
expect(downloadWorkspaceShippingNoticeExcelFileMock).toHaveBeenCalledWith('WYC26082401');
|
||||
expect(messageMocks.success).not.toHaveBeenCalled();
|
||||
expect(submitProcessGatePrimaryActionMock).not.toHaveBeenCalled();
|
||||
});
|
||||
@@ -2275,14 +2619,14 @@ describe('ShippingOrderReviewView layout phase 1', () => {
|
||||
actions: {
|
||||
primary: {
|
||||
code: 'mark_manual_uploaded', kind: 'forward', enabled: true,
|
||||
dispatch: 'dialog', ui_handler: 'manual_upload_evidence',
|
||||
dispatch: 'dialog', ui_handler: 'manual_upload_confirmation',
|
||||
},
|
||||
secondary: [],
|
||||
},
|
||||
stage_context: {
|
||||
upload: {
|
||||
latest_attempt: { status: 'failed', mode: 'rpa', freight_ref_no: 'LATEST-FAILED' },
|
||||
succeeded_attempt: { status: 'succeeded', mode: 'manual', freight_ref_no: 'VERIFIED-REF' },
|
||||
succeeded_attempt: { status: 'succeeded', mode: 'manual', freight_ref_no: 'LEGACY-REF-MUST-NOT-BE-SHOWN' },
|
||||
},
|
||||
},
|
||||
summary: {}, steps: [],
|
||||
@@ -2293,21 +2637,93 @@ describe('ShippingOrderReviewView layout phase 1', () => {
|
||||
await flushPromises();
|
||||
|
||||
const evidence = wrapper.get('[data-testid="review-lifecycle-upload-complete"]');
|
||||
expect(evidence.text()).toContain('VERIFIED-REF');
|
||||
expect(evidence.text()).toContain('succeeded');
|
||||
expect(evidence.text()).not.toContain('LATEST-FAILED');
|
||||
// 人工确认不再展示或依赖货代回执号,即使历史投影仍带有 freight_ref_no。
|
||||
expect(evidence.text()).not.toContain('LEGACY-REF-MUST-NOT-BE-SHOWN');
|
||||
expect(evidence.text()).not.toContain('failed');
|
||||
expect(wrapper.find('[data-testid="review-current-task-primary-action"]').exists()).toBe(false);
|
||||
expect(wrapper.find('[data-testid="review-current-processing-retry"]').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it('renders empty optional schema fields as editable line columns', async () => {
|
||||
it('aggregates freight upload by business_no and keeps one Excel action per notice', async () => {
|
||||
activeCase.value = {
|
||||
...activeCase.value,
|
||||
status: 'confirmed', confirmed_task_no: 'SN-PO-WAVE-1', confirmed_task_id: 22, has_formal_ot: true,
|
||||
};
|
||||
const taskApi = await import('@/features/chat/api/shipping.api');
|
||||
vi.mocked(taskApi.getWorkspaceShippingTask).mockResolvedValue({
|
||||
task_no: 'SN-PO-WAVE-1', business_no: 'WYC26082401', status: 'processing', upload_status: 'pending',
|
||||
lines: [], events: [],
|
||||
ui_state: { lifecycle_stage: 'freight_upload', lifecycle_entries: [], actions: { primary: null, secondary: [] }, stage_context: { upload: {} } },
|
||||
} as any);
|
||||
vi.mocked(taskApi.getWorkspaceShippingFreightNoticeGroups).mockResolvedValue({
|
||||
po_number: 'PO-100',
|
||||
items: [
|
||||
{ business_no: 'WYC26082401', po_number: 'PO-100', upload_status: 'pending', export_file_name: 'WYC26082401.xlsx', lines: [
|
||||
{ line_no: '00010', part_number: 'PART-A', reservation_id: 'RSV-A', qty: '2' },
|
||||
{ line_no: '00020', part_number: 'PART-B', reservation_id: 'RSV-B', qty: '1' },
|
||||
] },
|
||||
{ business_no: 'WYC26082402', po_number: 'PO-100', upload_status: 'pending', export_file_name: 'WYC26082402.xlsx', lines: [
|
||||
{ line_no: '00030', part_number: 'PART-C', reservation_id: 'RSV-C', qty: '4' },
|
||||
] },
|
||||
],
|
||||
} as any);
|
||||
|
||||
const wrapper = await mountView({ lifecycle_stage: 'freight_upload' });
|
||||
await flushPromises();
|
||||
|
||||
const groups = wrapper.findAll('[data-testid="review-freight-upload-notice"]');
|
||||
expect(groups).toHaveLength(2);
|
||||
expect(wrapper.text()).toContain('WYC26082401');
|
||||
expect(wrapper.text()).toContain('WYC26082402');
|
||||
expect(wrapper.text()).toContain('PART-A');
|
||||
expect(wrapper.text()).toContain('PART-C');
|
||||
expect(wrapper.findAll('[data-testid="review-freight-upload-download"]')).toHaveLength(2);
|
||||
expect(wrapper.findAll('[data-testid="review-freight-upload-line"]')).toHaveLength(3);
|
||||
expect(wrapper.findAll('[data-testid="review-freight-upload-download-SN-PO-WAVE-1"]')).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('sends selected business_nos for freight batch actions', async () => {
|
||||
activeCase.value = { ...activeCase.value, status: 'confirmed', confirmed_task_no: 'SN-PO-BATCH', confirmed_task_id: 23, has_formal_ot: true };
|
||||
const taskApi = await import('@/features/chat/api/shipping.api');
|
||||
vi.mocked(taskApi.getWorkspaceShippingTask).mockResolvedValue({
|
||||
task_no: 'SN-PO-BATCH', status: 'processing', lines: [], events: [],
|
||||
ui_state: { lifecycle_stage: 'freight_upload', lifecycle_entries: [], actions: { primary: null, secondary: [] }, stage_context: { upload: {} } },
|
||||
} as any);
|
||||
vi.mocked(taskApi.getWorkspaceShippingFreightNoticeGroups).mockResolvedValue({
|
||||
po_number: 'PO-BATCH', items: [
|
||||
{ business_no: 'WYC26082411', po_number: 'PO-BATCH', lines: [] },
|
||||
{ business_no: 'WYC26082412', po_number: 'PO-BATCH', lines: [] },
|
||||
],
|
||||
} as any);
|
||||
|
||||
const wrapper = await mountView({ lifecycle_stage: 'freight_upload' });
|
||||
await flushPromises();
|
||||
await wrapper.get('[aria-label="WYC26082411"]').setValue(true);
|
||||
await wrapper.get('[aria-label="WYC26082412"]').setValue(true);
|
||||
const buttons = wrapper.get('[data-testid="review-freight-upload-batch-toolbar"]').findAll('button');
|
||||
await buttons[0].trigger('click');
|
||||
await flushPromises();
|
||||
expect(downloadFreightArchiveMock).toHaveBeenCalledWith(['WYC26082411', 'WYC26082412']);
|
||||
await wrapper.get('[aria-label="WYC26082411"]').setValue(true);
|
||||
await wrapper.get('[aria-label="WYC26082412"]').setValue(true);
|
||||
await buttons[1].trigger('click');
|
||||
await flushPromises();
|
||||
expect(batchRpaFreightMock).toHaveBeenCalledWith(['WYC26082411', 'WYC26082412']);
|
||||
await wrapper.get('[aria-label="WYC26082411"]').setValue(true);
|
||||
await wrapper.get('[aria-label="WYC26082412"]').setValue(true);
|
||||
await buttons[2].trigger('click');
|
||||
await flushPromises();
|
||||
expect(batchConfirmFreightMock).toHaveBeenCalledWith(['WYC26082411', 'WYC26082412']);
|
||||
});
|
||||
|
||||
it('does not place internal inventory hint fields in the primary line table', async () => {
|
||||
const wrapper = await mountView();
|
||||
const inputs = wrapper.findAll('[data-testid="review-line-field-input"]');
|
||||
// 关键断言:库存源线索即使非必填且尚无机器值,也必须作为 Schema 列显示并可编辑。
|
||||
expect(wrapper.text()).toContain('库存源线索');
|
||||
expect(inputs).toHaveLength(1);
|
||||
expect(inputs[0].attributes('disabled')).toBeUndefined();
|
||||
// 关键断言:主表只保留业务核对字段,库存源线索由行级履约详情承载。
|
||||
expect(wrapper.text()).not.toContain('库存源线索');
|
||||
expect(inputs).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('ignores a stale line change after the current draft has accepted the value', async () => {
|
||||
@@ -2559,10 +2975,11 @@ describe('ShippingOrderReviewView audit and progress recovery', () => {
|
||||
},
|
||||
} as any);
|
||||
|
||||
const wrapper = await mountView();
|
||||
// 正式 OT 动作只有进入履约工作面后才读取 ShippingTask.ui_state;测试必须提供真实阶段上下文。
|
||||
const wrapper = await mountView({ lifecycle_stage: 'fulfillment_prep' });
|
||||
await flushPromises();
|
||||
|
||||
expect(wrapper.get('[data-testid="review-current-task-primary-action"]').attributes('disabled')).toBeDefined();
|
||||
expect(wrapper.get('[data-testid="review-current-processing-retry"]').attributes('disabled')).toBeDefined();
|
||||
}, 15000);
|
||||
|
||||
it('keeps top / wide / narrow stage labels identical via Progress projection (waiting_system_start)', async () => {
|
||||
@@ -2641,6 +3058,8 @@ describe('ShippingOrderReviewView audit and progress recovery', () => {
|
||||
const wrapper = await mountView();
|
||||
await flushPromises();
|
||||
// 关键断言:failed 态主卡/底栏露出 STP 重试(非确认后 auto_progress)。
|
||||
expect(wrapper.get('[data-testid="review-current-task-stage"]').text()).toContain('创建正式订单');
|
||||
expect(wrapper.get('[data-testid="review-current-task-status"]').text()).toContain('自动处理失败');
|
||||
const railBtn = wrapper.find('[data-testid="review-current-processing-retry"]');
|
||||
const footerBtn = wrapper.find('[data-testid="review-retry-stp-auto-create"]');
|
||||
expect(railBtn.exists() || footerBtn.exists()).toBe(true);
|
||||
@@ -2649,6 +3068,28 @@ describe('ShippingOrderReviewView audit and progress recovery', () => {
|
||||
expect(retryWorkspaceShippingOrderStpAutoCreate).toHaveBeenCalledWith('CASE-1');
|
||||
}, 15000);
|
||||
|
||||
it('hides the duplicate submit-order guidance while STP auto-create is running', async () => {
|
||||
activeCase.value = {
|
||||
...activeCase.value,
|
||||
status: 'ready',
|
||||
available_actions: ['validate'],
|
||||
automation: {
|
||||
status: 'running',
|
||||
retryable: false,
|
||||
can_auto_create: true,
|
||||
can_build: true,
|
||||
phase: 'pre_ot_stp',
|
||||
},
|
||||
};
|
||||
const wrapper = await mountView();
|
||||
await flushPromises();
|
||||
|
||||
// 关键断言:系统接管建单后,底栏只能保留运行态,不得同时出现提交按钮及其旧说明。
|
||||
expect(wrapper.find('[data-testid="review-footer-automating-hint"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="review-submit-order-hint"]').exists()).toBe(false);
|
||||
expect(wrapper.find('[data-testid="review-footer-actions"]').text()).not.toContain('提交订单');
|
||||
}, 15000);
|
||||
|
||||
it('shows STP retry for manual_fallback without confirm-create (UI-02)', async () => {
|
||||
activeCase.value = {
|
||||
...activeCase.value,
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -59,7 +59,7 @@ onMounted(() => { void Promise.all([admin.loadCustomers(), admin.loadShadowRepor
|
||||
<th class="px-5 py-4 text-left">{{ t('admin.shippingCustomers.headers.shortCode') }}</th>
|
||||
<th class="px-5 py-4 text-left">{{ t('admin.shippingCustomers.headers.status') }}</th>
|
||||
<th class="px-5 py-4 text-left">{{ t('admin.shippingCustomers.headers.identityEvidences') }}</th>
|
||||
<th class="px-5 py-4 text-left">{{ t('admin.shippingCustomers.headers.cases') }}</th>
|
||||
<th class="px-5 py-4 text-left">{{ t('admin.shippingCustomers.headers.notices') }}</th>
|
||||
<th class="px-5 py-4 text-right">{{ t('admin.shippingCustomers.headers.actions') }}</th>
|
||||
</tr></thead>
|
||||
<tbody>
|
||||
@@ -69,7 +69,7 @@ onMounted(() => { void Promise.all([admin.loadCustomers(), admin.loadShadowRepor
|
||||
<td class="px-5 py-4 font-mono text-sm">{{ customer.short_code }}</td>
|
||||
<td class="px-5 py-4"><span class="text-sm" :class="customer.status === 'active' ? 'text-emerald-600' : 'text-muted'">{{ t(`admin.shippingCustomers.status.${customer.status}`) }}</span></td>
|
||||
<td class="px-5 py-4 text-sm">{{ customer.identity_evidence_count || 0 }}</td>
|
||||
<td class="px-5 py-4 text-sm">{{ customer.case_count }}</td>
|
||||
<td class="px-5 py-4 text-sm">{{ customer.notice_count }}</td>
|
||||
<td class="px-5 py-4"><div class="flex justify-end gap-1">
|
||||
<button type="button" class="p-2 text-indigo-600 hover:bg-indigo-50 rounded-lg" :title="t('admin.shippingCustomers.identifiers.title')" @click="admin.openIdentifiers(customer)"><Fingerprint class="w-4 h-4" /></button>
|
||||
<button type="button" class="p-2 text-slate-600 hover:bg-slate-100 rounded-lg" :title="t('admin.shippingCustomers.lifecycle.open')" @click="admin.openLifecycleTimeline(customer)"><History class="w-4 h-4" /></button>
|
||||
|
||||
@@ -29,7 +29,7 @@ export interface ShippingCustomerRow {
|
||||
status: ShippingCustomerStatus;
|
||||
merged_into_customer_id?: number | null;
|
||||
remark?: string | null;
|
||||
case_count: number;
|
||||
notice_count: number;
|
||||
identifier_count: number;
|
||||
identity_evidence_count?: number;
|
||||
identifiers?: ShippingCustomerIdentifier[];
|
||||
@@ -105,7 +105,7 @@ export interface ShippingCustomerLifecycleImpact {
|
||||
customer: Pick<ShippingCustomerRow, 'id' | 'standard_name' | 'short_code' | 'status'>;
|
||||
can_delete: boolean;
|
||||
blockers: {
|
||||
business_cases: number;
|
||||
shipping_notices: number;
|
||||
business_sequences: number;
|
||||
external_references: number;
|
||||
order_customer_matches: number;
|
||||
|
||||
+1
-1
@@ -238,7 +238,7 @@ describe('ProcessGateRecoveryCard', () => {
|
||||
label_key: 'workspace.shippingNotice.processGate.actionCodes.mark_manual_uploaded',
|
||||
kind: 'current_gate',
|
||||
dispatch: 'dialog',
|
||||
ui_handler: 'manual_upload_evidence',
|
||||
ui_handler: 'manual_upload_confirmation',
|
||||
},
|
||||
task_no: 'SN-TEST-001',
|
||||
} as ShippingProcessGateUserSummary),
|
||||
|
||||
@@ -133,7 +133,7 @@ async function runPrimaryAction() {
|
||||
emit('confirmCustomer', result.taskNo);
|
||||
return;
|
||||
}
|
||||
if (result.outcome === 'dialog' && result.uiHandler === 'manual_upload_evidence') {
|
||||
if (result.outcome === 'dialog' && result.uiHandler === 'manual_upload_confirmation') {
|
||||
emit('manualUpload');
|
||||
return;
|
||||
}
|
||||
|
||||
+95
@@ -0,0 +1,95 @@
|
||||
/**
|
||||
* features/shipping-process-gates/composables/useShippingProcessGateRecovery.spec.ts
|
||||
* 用途:锁定异步 Gate 动作的即时受理反馈边界,避免用户等待 Worker 终态才看到响应。
|
||||
* 依赖:Vitest、Vue Test Utils、vue-i18n、process-gates.api mock。
|
||||
* 逻辑:后端返回 async_job 后,客户端只提交一次并立即返回;状态终态由既有页面轮询负责。
|
||||
*/
|
||||
import { createApp, defineComponent, h } from 'vue';
|
||||
import { createI18n } from 'vue-i18n';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import workspaceZhCn from '@/locales/zh-CN/workspace.json';
|
||||
import {
|
||||
useShippingProcessGateRecovery,
|
||||
} from './useShippingProcessGateRecovery';
|
||||
|
||||
const getExecutionMock = vi.fn();
|
||||
const postActionMock = vi.fn();
|
||||
|
||||
vi.mock('../api/process-gates.api', () => ({
|
||||
getWorkspaceProcessExecution: (...args: unknown[]) => getExecutionMock(...args),
|
||||
postWorkspaceProcessGateAction: (...args: unknown[]) => postActionMock(...args),
|
||||
}));
|
||||
|
||||
vi.mock('@/shared/composables/useMessage', () => ({
|
||||
useMessage: () => ({
|
||||
success: vi.fn(),
|
||||
warning: vi.fn(),
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock('vue-router', () => ({
|
||||
useRouter: () => ({ push: vi.fn() }),
|
||||
}));
|
||||
|
||||
const i18n = createI18n({
|
||||
legacy: false,
|
||||
locale: 'zh-CN',
|
||||
messages: { 'zh-CN': { workspace: workspaceZhCn } },
|
||||
});
|
||||
|
||||
function summary() {
|
||||
return {
|
||||
execution_no: 'EXEC-1',
|
||||
status: 'blocked',
|
||||
current_blocking_gate: {
|
||||
gate_code: 'inventory_matching',
|
||||
evaluation_version: 3,
|
||||
status: 'blocked',
|
||||
},
|
||||
primary_action: {
|
||||
code: 'retry_inventory_matching',
|
||||
dispatch: 'mutation',
|
||||
},
|
||||
allowed_actions: ['retry_inventory_matching'],
|
||||
} as never;
|
||||
}
|
||||
|
||||
function mountComposable() {
|
||||
let exposed!: ReturnType<typeof useShippingProcessGateRecovery>;
|
||||
const app = createApp(defineComponent({
|
||||
setup() {
|
||||
exposed = useShippingProcessGateRecovery();
|
||||
return () => h('div');
|
||||
},
|
||||
}));
|
||||
app.use(i18n);
|
||||
app.mount(document.createElement('div'));
|
||||
return { exposed, app };
|
||||
}
|
||||
|
||||
describe('useShippingProcessGateRecovery', () => {
|
||||
beforeEach(() => {
|
||||
getExecutionMock.mockReset();
|
||||
postActionMock.mockReset();
|
||||
postActionMock.mockResolvedValue({
|
||||
dispatch: 'async_job',
|
||||
execution_no: 'EXEC-1',
|
||||
gate_code: 'inventory_matching',
|
||||
attempt: { id: 9, status: 'queued' },
|
||||
});
|
||||
});
|
||||
|
||||
it('returns immediately after async Gate submission without version pre-read or terminal polling', async () => {
|
||||
const { exposed, app } = mountComposable();
|
||||
|
||||
const result = await exposed.submitPrimaryAction(summary(), {
|
||||
actionCode: 'retry_inventory_matching',
|
||||
});
|
||||
|
||||
expect(result.outcome).toBe('submitted');
|
||||
expect(postActionMock).toHaveBeenCalledTimes(1);
|
||||
expect(getExecutionMock).not.toHaveBeenCalled();
|
||||
|
||||
app.unmount();
|
||||
});
|
||||
});
|
||||
+3
-68
@@ -11,7 +11,6 @@ import { useRouter } from 'vue-router';
|
||||
import { BusinessError, resolveLocalizedErrorMessage } from '@/shared/api/client';
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
import {
|
||||
getWorkspaceProcessExecution,
|
||||
postWorkspaceProcessGateAction,
|
||||
} from '../api/process-gates.api';
|
||||
import type {
|
||||
@@ -64,47 +63,6 @@ function newIdempotencyKey(): string {
|
||||
return `pg-${Date.now()}-${Math.random().toString(16).slice(2)}`;
|
||||
}
|
||||
|
||||
const ATTEMPT_POLL_INTERVAL_MS = 800;
|
||||
const ATTEMPT_POLL_LIMIT = 25;
|
||||
const ATTEMPT_TERMINAL_STATUSES = new Set(['succeeded', 'failed', 'cancelled', 'superseded']);
|
||||
|
||||
/** 等待异步 Gate Attempt 进入终态,避免 Worker 完成前刷新到旧 Case 投影。 */
|
||||
async function waitForAttemptTerminal(
|
||||
executionNo: string,
|
||||
submittedGateCode: string,
|
||||
attemptId: number,
|
||||
): Promise<void> {
|
||||
for (let index = 0; index < ATTEMPT_POLL_LIMIT; index += 1) {
|
||||
const latest = await getWorkspaceProcessExecution(executionNo);
|
||||
const gateAttempt = latest.current_blocking_gate?.latest_attempt as (
|
||||
{ id?: number; status?: string } | null | undefined
|
||||
);
|
||||
const latestAttemptId = Number(gateAttempt?.id || 0);
|
||||
const latestAttemptStatus = String(gateAttempt?.status || '').trim().toLowerCase();
|
||||
if (
|
||||
(latestAttemptId === attemptId || latestAttemptId === 0)
|
||||
&& ATTEMPT_TERMINAL_STATUSES.has(latestAttemptStatus)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const currentGateCode = String(latest.current_blocking_gate?.gate_code || '').trim();
|
||||
const executionStatus = String(latest.status || '').trim().toLowerCase();
|
||||
if (
|
||||
currentGateCode
|
||||
&& currentGateCode !== submittedGateCode
|
||||
&& !['pending', 'queued', 'running'].includes(executionStatus)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
if (!latest.current_blocking_gate && ['completed', 'cancelled'].includes(
|
||||
executionStatus,
|
||||
)) {
|
||||
return;
|
||||
}
|
||||
await new Promise((resolve) => window.setTimeout(resolve, ATTEMPT_POLL_INTERVAL_MS));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 编排单次门禁恢复:导航类动作直接 router.push;其余 POST 到 Workspace API。
|
||||
* @returns busy 状态与 submitPrimaryAction 方法
|
||||
@@ -193,36 +151,13 @@ export function useShippingProcessGateRecovery() {
|
||||
}
|
||||
busy.value = true;
|
||||
try {
|
||||
// 写入前重新读取服务端 Gate 版本,避免 Case 投影刷新稍慢时提交旧版本。
|
||||
// 动作归属仍由后端最终校验;若当前 Gate 已变化,不复用旧动作。
|
||||
let submitVersion = expectedVersion;
|
||||
try {
|
||||
const latest = await getWorkspaceProcessExecution(summary.execution_no);
|
||||
const latestGate = latest.current_blocking_gate;
|
||||
if (latestGate && String(latestGate.gate_code) === String(gate.gate_code)) {
|
||||
const latestVersion = Number(latestGate.evaluation_version);
|
||||
if (Number.isFinite(latestVersion) && latestVersion >= 1) submitVersion = latestVersion;
|
||||
}
|
||||
} catch {
|
||||
// 读取失败时继续使用页面快照版本,让后端版本锁决定是否允许写入。
|
||||
}
|
||||
const response = await postWorkspaceProcessGateAction(summary.execution_no, String(gate.gate_code), {
|
||||
await postWorkspaceProcessGateAction(summary.execution_no, String(gate.gate_code), {
|
||||
action_code: actionCode,
|
||||
expected_gate_version: submitVersion,
|
||||
expected_gate_version: expectedVersion,
|
||||
idempotency_key: newIdempotencyKey(),
|
||||
payload: options?.payload,
|
||||
});
|
||||
if (response.dispatch === 'async_job' && Number(response.attempt?.id) > 0) {
|
||||
try {
|
||||
await waitForAttemptTerminal(
|
||||
summary.execution_no,
|
||||
String(gate.gate_code),
|
||||
Number(response.attempt.id),
|
||||
);
|
||||
} catch {
|
||||
// 最终仍由父级刷新完整 Case;短暂轮询失败不得把已受理动作误报为执行失败。
|
||||
}
|
||||
}
|
||||
// async_job 只表示服务端已受理;Worker 终态由页面已有 Projection 轮询负责。
|
||||
msg.success(t('workspace.shippingNotice.processGate.actionSubmitted'));
|
||||
return { outcome: 'submitted' };
|
||||
} catch (error: unknown) {
|
||||
|
||||
@@ -34,6 +34,7 @@ const ACTION_CODE_TO_INTENT: Record<string, ShippingProcessingActionIntent> = {
|
||||
adjudicate_duplicate: 'adjudicate_duplicate',
|
||||
open_inventory_match_review: 'open_inventory_match_review',
|
||||
open_shortage_review: 'open_shortage_review',
|
||||
reload_inventory_result: 'reload_inventory_result',
|
||||
retry_inventory_preparation: 'retry_inventory_preparation',
|
||||
retry_inventory_matching: 'retry_inventory_matching',
|
||||
reparse_batch: 'reparse_batch',
|
||||
@@ -85,6 +86,7 @@ const ACTION_CODE_TO_INTENT: Record<string, ShippingProcessingActionIntent> = {
|
||||
const AUTOMATING_STATUSES = new Set(['processing', 'automating', 'queued']);
|
||||
/** 需要在聊天/右侧展示精确恢复动作文案的正式 action_code。 */
|
||||
const RECOVERY_ACTION_CODES = new Set([
|
||||
'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',
|
||||
@@ -129,6 +131,7 @@ const INTERNAL_INVENTORY_ACTION_CODES = new Set([
|
||||
export function inventoryActionLabelKey(code: string | null | undefined): string | null {
|
||||
const normalized = String(code || '').trim().toLowerCase();
|
||||
const keyByCode: Record<string, string> = {
|
||||
reload_inventory_result: 'workspace.shippingNotice.processGate.inventoryActions.reloadInventoryResult',
|
||||
retry_inventory_preparation: 'workspace.shippingNotice.processGate.inventoryActions.retryInventoryPreparation',
|
||||
retry_inventory_matching: 'workspace.shippingNotice.processGate.inventoryActions.retryInventoryMatching',
|
||||
open_inventory_match_review: 'workspace.shippingNotice.processGate.inventoryActions.openInventoryMatchReview',
|
||||
|
||||
@@ -154,6 +154,25 @@ describe('workbenchActionRegistry', () => {
|
||||
expect(resolved?.todoActionCode).toBe('retry_inventory_matching');
|
||||
});
|
||||
|
||||
it('routes reload inventory result through the formal Gate todo action', () => {
|
||||
const result = resolveProcessingActionPresentation(projection({
|
||||
uiState: {
|
||||
status: 'retryable', stage: 'inventory_preparation', blocking_reason: null,
|
||||
primary_action: { code: 'reload_inventory_result', label_key: 'x' }, secondary_actions: [],
|
||||
},
|
||||
currentGate: {
|
||||
gateCode: 'inventory_preparation',
|
||||
status: 'blocked_retryable',
|
||||
nextActionCode: 'reload_inventory_result',
|
||||
},
|
||||
}), { surface: 'review' });
|
||||
|
||||
const resolved = resolveWorkbenchActionItem(result.primary!, { postCreate: true });
|
||||
expect(result.primary?.intent).toBe('reload_inventory_result');
|
||||
expect(resolved?.reviewBehavior).toBe('todo_panel');
|
||||
expect(resolved?.todoActionCode).toBe('reload_inventory_result');
|
||||
});
|
||||
|
||||
it('shows RPA upload retry instead of manual upload entries when Gate 19 is blocked', () => {
|
||||
const result = resolveProcessingActionPresentation(projection({
|
||||
stage: 'freight_uploading',
|
||||
|
||||
@@ -91,6 +91,12 @@ export const WORKBENCH_ACTION_REGISTRY: Record<string, WorkbenchActionRegistryEn
|
||||
isWrite: false,
|
||||
stageFamily: 'pre_create',
|
||||
},
|
||||
edit_reservation: {
|
||||
intent: 'open_order_review',
|
||||
reviewBehavior: 'hidden_on_review',
|
||||
isWrite: false,
|
||||
stageFamily: 'pre_create',
|
||||
},
|
||||
edit_formal_task: {
|
||||
intent: 'edit_formal_task',
|
||||
reviewBehavior: 'hidden_on_review',
|
||||
@@ -156,6 +162,15 @@ export const WORKBENCH_ACTION_REGISTRY: Record<string, WorkbenchActionRegistryEn
|
||||
stageFamily: 'post_create',
|
||||
scrollTestId: 'review-formal-task-todo-panel',
|
||||
},
|
||||
reload_inventory_result: {
|
||||
intent: 'reload_inventory_result',
|
||||
reviewBehavior: 'todo_panel',
|
||||
todoActionCode: 'reload_inventory_result',
|
||||
requiresFormalTask: true,
|
||||
isWrite: true,
|
||||
stageFamily: 'post_create',
|
||||
scrollTestId: 'review-formal-task-todo-panel',
|
||||
},
|
||||
open_shortage_review: {
|
||||
intent: 'open_shortage_review',
|
||||
reviewBehavior: 'focus_inventory_issues',
|
||||
|
||||
@@ -145,6 +145,15 @@ onBeforeUnmount(() => {
|
||||
<component v-if="!collapsed" :is="shippingExpanded ? ChevronDown : ChevronRight" class="h-4 w-4" />
|
||||
</button>
|
||||
<div v-if="!collapsed && shippingExpanded" class="mt-1 space-y-1 pl-5">
|
||||
<RouterLink
|
||||
v-if="isAdmin"
|
||||
:to="WORKSPACE_PATHS.shippingNoticeCustomers"
|
||||
class="ws-nav-btn py-2.5 text-[13px]"
|
||||
:class="{ 'ws-nav-btn--active': isActive(['workspace-shipping-customers']) }"
|
||||
>
|
||||
<ContactRound class="h-4 w-4" />
|
||||
<span>{{ $t('workspace.nav.shippingCustomers') }}</span>
|
||||
</RouterLink>
|
||||
<RouterLink
|
||||
:to="WORKSPACE_PATHS.shippingNoticeMyTasks"
|
||||
class="ws-nav-btn py-2.5 text-[13px]"
|
||||
@@ -159,15 +168,6 @@ onBeforeUnmount(() => {
|
||||
{{ pendingBadge > 99 ? '99+' : pendingBadge }}
|
||||
</span>
|
||||
</RouterLink>
|
||||
<RouterLink
|
||||
v-if="isAdmin"
|
||||
:to="WORKSPACE_PATHS.shippingNoticeCustomers"
|
||||
class="ws-nav-btn py-2.5 text-[13px]"
|
||||
:class="{ 'ws-nav-btn--active': isActive(['workspace-shipping-customers']) }"
|
||||
>
|
||||
<ContactRound class="h-4 w-4" />
|
||||
<span>{{ $t('workspace.nav.shippingCustomers') }}</span>
|
||||
</RouterLink>
|
||||
</div>
|
||||
</div>
|
||||
<RouterLink
|
||||
|
||||
+10
-24
@@ -1,8 +1,8 @@
|
||||
/**
|
||||
* features/workspace/shipping-task-center/ManualUploadEvidenceDialog.spec.ts
|
||||
* 用途:锁定人工上传登记弹窗无障碍与必填校验契约。
|
||||
* 依赖:vitest、@vue/test-utils、vue-i18n、file-assets / shipping-tasks API mock。
|
||||
* 逻辑:打开时具备 dialog 角色;Escape 关闭;缺少回执号不得提交;关闭后恢复先前焦点。
|
||||
* 用途:锁定人工上传确认弹窗无障碍与无凭据提交契约。
|
||||
* 依赖:vitest、@vue/test-utils、vue-i18n、shipping-tasks API mock。
|
||||
* 逻辑:打开时具备 dialog 角色;Escape 关闭;无需截图/PDF或回执即可确认;关闭后恢复先前焦点。
|
||||
*/
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { mount, flushPromises } from '@vue/test-utils';
|
||||
@@ -10,10 +10,6 @@ import { createI18n } from 'vue-i18n';
|
||||
import { nextTick } from 'vue';
|
||||
import ManualUploadEvidenceDialog from './ManualUploadEvidenceDialog.vue';
|
||||
|
||||
vi.mock('@/shared/api/file-assets.api', () => ({
|
||||
uploadFileAsset: vi.fn(async () => ({ asset_no: 'FA-TEST-1' })),
|
||||
}));
|
||||
|
||||
vi.mock('@/features/workspace/api/shipping-tasks.api', () => ({
|
||||
markWorkspaceShippingManualUploaded: vi.fn(async () => ({})),
|
||||
}));
|
||||
@@ -25,11 +21,7 @@ const messages = {
|
||||
actions: { failed: '失败' },
|
||||
manualUpload: {
|
||||
title: '登记人工上传',
|
||||
hint: '请上传凭据并填写回执号',
|
||||
evidenceLabel: '证据文件',
|
||||
freightRefLabel: '货代回执号',
|
||||
evidenceRequired: '请先选择证据文件',
|
||||
freightRefRequired: '请填写货代回执号',
|
||||
hint: '请确认 Excel 已上传至货代平台',
|
||||
cancel: '取消',
|
||||
submit: '确认已上传',
|
||||
submitting: '提交中…',
|
||||
@@ -47,7 +39,7 @@ function mountDialog(open = true) {
|
||||
return mount(ManualUploadEvidenceDialog, {
|
||||
props: {
|
||||
open,
|
||||
taskNo: 'SN-DIALOG-1',
|
||||
businessNo: 'WVC26082301',
|
||||
artifactId: 9,
|
||||
},
|
||||
attachTo: document.body,
|
||||
@@ -97,21 +89,15 @@ describe('ManualUploadEvidenceDialog', () => {
|
||||
wrapper.unmount();
|
||||
});
|
||||
|
||||
it('requires freight receipt before submit when evidence is selected', async () => {
|
||||
it('submits with business_no without file evidence or freight receipt', async () => {
|
||||
const wrapper = mountDialog(true);
|
||||
await nextTick();
|
||||
const fileInput = wrapper.get('input[type="file"]');
|
||||
const file = new File(['evidence'], 'shot.png', { type: 'image/png' });
|
||||
Object.defineProperty(fileInput.element, 'files', {
|
||||
value: [file],
|
||||
configurable: true,
|
||||
});
|
||||
await fileInput.trigger('change');
|
||||
await nextTick();
|
||||
|
||||
const submit = wrapper.findAll('button').find((btn) => btn.text().includes('确认已上传'));
|
||||
expect(submit).toBeTruthy();
|
||||
expect(submit!.attributes('disabled')).toBeDefined();
|
||||
expect(submit!.attributes('disabled')).toBeUndefined();
|
||||
await submit!.trigger('click');
|
||||
await flushPromises();
|
||||
expect(wrapper.emitted('success')).toHaveLength(1);
|
||||
wrapper.unmount();
|
||||
});
|
||||
});
|
||||
+8
-55
@@ -1,19 +1,18 @@
|
||||
/**
|
||||
* features/workspace/shipping-task-center/ManualUploadEvidenceDialog.vue
|
||||
* 用途:人工上传凭据对话框;截图/PDF 证据与货代回执号均必填。
|
||||
* 依赖:uploadFileAsset、workspace shipping-tasks.api、Vue watch/nextTick。
|
||||
* 逻辑:由 TaskTodoPanel 在 mark_manual_uploaded 动作时打开;禁止触发 RPA 上传;
|
||||
* 用途:人工确认货代已上传当前发货通知 Excel 的对话框。
|
||||
* 依赖:workspace shipping-tasks.api、Vue watch/nextTick。
|
||||
* 逻辑:由 TaskTodoPanel 在 mark_manual_uploaded 动作时打开;不采集截图/PDF或回执号;
|
||||
* 对齐复核弹层无障碍:role=dialog、aria-modal、焦点陷阱、Escape、关闭后焦点恢复。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import { nextTick, onBeforeUnmount, ref, watch } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { uploadFileAsset } from '@/shared/api/file-assets.api';
|
||||
import { markWorkspaceShippingManualUploaded } from '@/features/workspace/api/shipping-tasks.api';
|
||||
|
||||
const props = defineProps<{
|
||||
open: boolean;
|
||||
taskNo: string;
|
||||
businessNo: string;
|
||||
artifactId?: number | null;
|
||||
disabled?: boolean;
|
||||
}>();
|
||||
@@ -26,8 +25,6 @@ const emit = defineEmits<{
|
||||
const { t } = useI18n();
|
||||
const busy = ref(false);
|
||||
const error = ref('');
|
||||
const evidenceFile = ref<File | null>(null);
|
||||
const freightRefNo = ref('');
|
||||
const panelRef = ref<HTMLElement | null>(null);
|
||||
let previouslyFocused: HTMLElement | null = null;
|
||||
|
||||
@@ -54,8 +51,6 @@ function focusableNodes(): HTMLElement[] {
|
||||
*/
|
||||
function close() {
|
||||
if (busy.value) return;
|
||||
evidenceFile.value = null;
|
||||
freightRefNo.value = '';
|
||||
error.value = '';
|
||||
emit('update:open', false);
|
||||
}
|
||||
@@ -126,36 +121,15 @@ onBeforeUnmount(() => {
|
||||
});
|
||||
|
||||
/**
|
||||
* 选择证据文件(截图或 PDF)。
|
||||
*/
|
||||
function onFileChange(event: Event) {
|
||||
const input = event.target as HTMLInputElement;
|
||||
evidenceFile.value = input.files?.[0] || null;
|
||||
error.value = '';
|
||||
}
|
||||
|
||||
/**
|
||||
* 上传证据资产并登记人工上传完成。
|
||||
* 核心逻辑:证据文件与回执号均必填,与后端 record_manual_upload 契约一致。
|
||||
* 登记人工上传完成。
|
||||
* 核心逻辑:仅提交 business_no 与可选 Artifact,服务端负责唯一 Excel 和状态门禁。
|
||||
*/
|
||||
async function submit() {
|
||||
if (props.disabled || busy.value) return;
|
||||
if (!evidenceFile.value) {
|
||||
error.value = t('workspace.shippingNotice.manualUpload.evidenceRequired');
|
||||
return;
|
||||
}
|
||||
const receipt = freightRefNo.value.trim();
|
||||
if (!receipt) {
|
||||
error.value = t('workspace.shippingNotice.manualUpload.freightRefRequired');
|
||||
return;
|
||||
}
|
||||
busy.value = true;
|
||||
error.value = '';
|
||||
try {
|
||||
const asset = await uploadFileAsset(evidenceFile.value);
|
||||
await markWorkspaceShippingManualUploaded(props.taskNo, {
|
||||
evidence_asset_no: asset.asset_no,
|
||||
freight_ref_no: receipt,
|
||||
await markWorkspaceShippingManualUploaded(props.businessNo, {
|
||||
...(props.artifactId ? { artifact_id: props.artifactId } : {}),
|
||||
});
|
||||
emit('success');
|
||||
@@ -193,27 +167,6 @@ async function submit() {
|
||||
{{ $t('workspace.shippingNotice.manualUpload.hint') }}
|
||||
</p>
|
||||
|
||||
<label class="mt-4 block text-xs font-medium text-muted">
|
||||
{{ $t('workspace.shippingNotice.manualUpload.evidenceLabel') }}
|
||||
<input
|
||||
type="file"
|
||||
accept="image/*,application/pdf"
|
||||
class="mt-1 block w-full text-sm"
|
||||
:disabled="busy || disabled"
|
||||
@change="onFileChange"
|
||||
>
|
||||
</label>
|
||||
|
||||
<label class="mt-3 block text-xs font-medium text-muted">
|
||||
{{ $t('workspace.shippingNotice.manualUpload.freightRefLabel') }}
|
||||
<input
|
||||
v-model="freightRefNo"
|
||||
type="text"
|
||||
class="mt-1 w-full rounded-xl border border-default bg-surface px-3 py-2 text-sm"
|
||||
:disabled="busy || disabled"
|
||||
>
|
||||
</label>
|
||||
|
||||
<p v-if="error" class="mt-3 text-sm text-rose-600" role="alert">{{ error }}</p>
|
||||
|
||||
<div class="mt-5 flex justify-end gap-2">
|
||||
@@ -228,7 +181,7 @@ async function submit() {
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-xl bg-brand-600 px-3 py-1.5 text-sm font-medium text-white hover:bg-brand-700 disabled:opacity-50"
|
||||
:disabled="busy || disabled || !evidenceFile || !freightRefNo.trim()"
|
||||
:disabled="busy || disabled"
|
||||
@click="submit"
|
||||
>
|
||||
{{ busy ? $t('workspace.shippingNotice.manualUpload.submitting') : $t('workspace.shippingNotice.manualUpload.submit') }}
|
||||
|
||||
+204
@@ -0,0 +1,204 @@
|
||||
/**
|
||||
* features/workspace/shipping-task-center/ShippingTaskCenterPage.notice-batch.spec.ts
|
||||
* 用途:验收任务中心只按发货通知单 business_no 展示与执行货代批量操作。
|
||||
* 依赖:ShippingTaskCenterPage、货代 API、我的待办 API、Vue Test Utils。
|
||||
* 逻辑:正式 Notice 可选择并传 business_nos;Review/Intake 不能进入选择集;列表行只显示服务端投影的通知明细。
|
||||
*/
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import { flushPromises, mount } from '@vue/test-utils';
|
||||
import { createI18n } from 'vue-i18n';
|
||||
import { createMemoryHistory, createRouter } from 'vue-router';
|
||||
import ShippingTaskCenterPage from './ShippingTaskCenterPage.vue';
|
||||
|
||||
const batchConfirm = vi.fn(async () => ({ results: [{ status: 'confirmed' }] }));
|
||||
const batchRpa = vi.fn(async () => ({ results: [{ status: 'accepted' }] }));
|
||||
const downloadArchive = vi.fn(async () => undefined);
|
||||
const listTodos = vi.fn(async () => ({ items: [], page: 1, page_size: 20, total: 0 }));
|
||||
|
||||
vi.mock('@/features/chat/api/shipping.api', () => ({
|
||||
SHIPPING_NOTICE_AGENT_CODE: 'shipping_notice',
|
||||
listShippingChatAgents: vi.fn(async () => []),
|
||||
getWorkspaceShippingTask: vi.fn(),
|
||||
retryWorkspaceShippingOrderStpAutoCreate: vi.fn(),
|
||||
batchConfirmWorkspaceShippingNoticesUploaded: (...args: unknown[]) => batchConfirm(...args),
|
||||
batchStartWorkspaceShippingNoticeRpaUpload: (...args: unknown[]) => batchRpa(...args),
|
||||
}));
|
||||
|
||||
vi.mock('@/features/workspace/api/shipping-tasks.api', () => ({
|
||||
listWorkspaceShippingMyTodos: (...args: unknown[]) => listTodos(...args),
|
||||
countWorkspaceShippingMyTodos: vi.fn(async () => ({ pending: 0, processing: 0, done: 0, total_pending_badge: 0 })),
|
||||
}));
|
||||
|
||||
vi.mock('@/features/workspace/composables/useShippingTodoBadge', () => ({
|
||||
useShippingTodoBadge: () => ({ refreshShippingTodoBadge: vi.fn(async () => undefined) }),
|
||||
}));
|
||||
|
||||
vi.mock('@/features/chat/shipping/shippingDownload', () => ({
|
||||
downloadWorkspaceShippingNoticeExportArchive: (...args: unknown[]) => downloadArchive(...args),
|
||||
}));
|
||||
|
||||
const i18n = createI18n({
|
||||
legacy: false,
|
||||
locale: 'zh-CN',
|
||||
messages: {
|
||||
'zh-CN': {
|
||||
workspace: {
|
||||
shippingNotice: {
|
||||
title: '批次进度中心',
|
||||
refresh: '刷新',
|
||||
loading: '加载中',
|
||||
selectCase: '请选择任务',
|
||||
myTodos: {
|
||||
title: '批次进度中心',
|
||||
subtitle: '按文件查看进度',
|
||||
lifecycleStages: {
|
||||
filterLabel: '阶段',
|
||||
intake_parse: '接收解析',
|
||||
order_review: '订单复核',
|
||||
fulfillment_prep: '通知准备',
|
||||
freight_upload: '货代上传',
|
||||
upload_complete: '通知完成',
|
||||
},
|
||||
buckets: { pending: '待处理', processing: '处理中', done: '已完成' },
|
||||
filters: {
|
||||
todoCategory: '待办类型', all: '全部', review: '待复核', exception: '异常',
|
||||
manualUpload: '人工上传', intakeParse: '接收解析', customer: '客户',
|
||||
customerPlaceholder: '客户名称或简称', taskNo: '任务编号', taskNoPlaceholder: 'SN 编号',
|
||||
apply: '应用筛选', reset: '重置',
|
||||
},
|
||||
empty: '当前桶内暂无待办',
|
||||
openProcessingHint: '请处理',
|
||||
openProcessingUnavailable: '暂不可用',
|
||||
openReview: '订单复核',
|
||||
openLifecycleWorkbench: '进入工作台',
|
||||
openConversation: '打开对话',
|
||||
intakeParseBadge: '材料解析',
|
||||
progressSummary: '当前阶段:{stage}',
|
||||
progressBlocker: '当前阻断:{reason}',
|
||||
viewStage: '查看阶段',
|
||||
},
|
||||
openChat: '打开对话',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const routes = [{
|
||||
path: '/',
|
||||
name: 'workspace-shipping-my-tasks',
|
||||
component: ShippingTaskCenterPage,
|
||||
}];
|
||||
|
||||
function notice(businessNo: string, poNumber: string, partNumber: string) {
|
||||
return {
|
||||
id: Number(businessNo.slice(-2)), task_no: `SN-${businessNo}`, business_no: businessNo,
|
||||
item_kind: 'task', todo_ref: `SN-${businessNo}`, source_type: 'post_ot_fulfillment_wave',
|
||||
po_number: poNumber, customer_name: 'Customer', upload_status: 'pending',
|
||||
notice_line_summary: [{ line_no: '10', part_number: partNumber, shipment_qty: '4', available_qty: '9' }],
|
||||
artifact_summary: { export_file_name: `${businessNo}.xlsx` },
|
||||
};
|
||||
}
|
||||
|
||||
async function mountPage() {
|
||||
const router = createRouter({ history: createMemoryHistory(), routes });
|
||||
await router.push('/');
|
||||
await router.isReady();
|
||||
return mount(ShippingTaskCenterPage, {
|
||||
global: {
|
||||
plugins: [i18n, router],
|
||||
stubs: {
|
||||
RouterLink: true,
|
||||
ShippingRunProgressTable: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
describe('ShippingTaskCenterPage notice batch operations', () => {
|
||||
afterEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it('only makes formal Notices selectable and displays each Notice projection', async () => {
|
||||
listTodos.mockResolvedValueOnce({
|
||||
items: [
|
||||
notice('WYC26082301', 'PO-100', 'PART-A'),
|
||||
notice('WYC26082302', 'PO-100', 'PART-B'),
|
||||
{ id: 30, task_no: 'OT-30', item_kind: 'review_case', todo_ref: 'SNRC-30', review_case_no: 'SNRC-30', source_type: 'review' },
|
||||
{ id: 31, task_no: '', item_kind: 'order_intake', todo_ref: 'SNI-31', intake_no: 'SNI-31', source_type: 'intake' },
|
||||
], page: 1, page_size: 20, total: 4,
|
||||
});
|
||||
const wrapper = await mountPage();
|
||||
await flushPromises();
|
||||
|
||||
expect(wrapper.get('[aria-label="WYC26082301"]').exists()).toBe(true);
|
||||
expect(wrapper.get('[aria-label="WYC26082302"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[aria-label="SNRC-30"]').exists()).toBe(false);
|
||||
expect(wrapper.text()).toContain('PO-100');
|
||||
expect(wrapper.text()).toContain('PART-A');
|
||||
expect(wrapper.text()).toContain('PART-B');
|
||||
expect(wrapper.text()).toContain('WYC26082301.xlsx');
|
||||
wrapper.unmount();
|
||||
});
|
||||
|
||||
it('sends selected business_nos to download, manual confirmation and RPA independently', async () => {
|
||||
listTodos.mockResolvedValue({
|
||||
items: [notice('WYC26082301', 'PO-100', 'PART-A'), notice('WYC26082302', 'PO-100', 'PART-B')],
|
||||
page: 1, page_size: 20, total: 2,
|
||||
});
|
||||
const wrapper = await mountPage();
|
||||
await flushPromises();
|
||||
await wrapper.get('[aria-label="WYC26082301"]').setValue(true);
|
||||
await wrapper.get('[aria-label="WYC26082302"]').setValue(true);
|
||||
|
||||
const toolbar = wrapper.get('[data-testid="shipping-notice-batch-toolbar"]');
|
||||
const buttons = toolbar.findAll('button');
|
||||
await buttons[0].trigger('click');
|
||||
expect(downloadArchive).toHaveBeenCalledWith(['WYC26082301', 'WYC26082302']);
|
||||
|
||||
await buttons[1].trigger('click');
|
||||
await flushPromises();
|
||||
expect(batchConfirm).toHaveBeenCalledWith(['WYC26082301', 'WYC26082302']);
|
||||
|
||||
await buttons[2].trigger('click');
|
||||
await flushPromises();
|
||||
expect(batchRpa).toHaveBeenCalledWith(['WYC26082301', 'WYC26082302']);
|
||||
wrapper.unmount();
|
||||
});
|
||||
|
||||
it('keeps all five lifecycle stage filters on one wide-screen row', async () => {
|
||||
const wrapper = await mountPage();
|
||||
await flushPromises();
|
||||
|
||||
const track = wrapper.get('[data-testid="my-todos-lifecycle-stage-filter"]');
|
||||
expect(track.classes()).toContain('xl:grid-cols-5');
|
||||
expect(track.findAll('button')).toHaveLength(5);
|
||||
expect(track.text()).toContain('货代上传');
|
||||
expect(track.text()).not.toContain('workspace.shippingNotice.myTodos.lifecycleStages.freight_upload');
|
||||
wrapper.unmount();
|
||||
});
|
||||
|
||||
it('counts a pending review item from its backend stage even without an enterable lifecycle entry', async () => {
|
||||
listTodos.mockResolvedValueOnce({
|
||||
items: [{
|
||||
item_kind: 'review_case',
|
||||
task_no: '',
|
||||
review_run_no: 'RUN-1',
|
||||
review_case_no: 'CASE-1',
|
||||
ui_state: {
|
||||
stage: { code: 'order_review', label: '订单复核', index: 2, total: 5 },
|
||||
lifecycle_entries: [],
|
||||
},
|
||||
}],
|
||||
page: 1,
|
||||
page_size: 20,
|
||||
total: 1,
|
||||
});
|
||||
const wrapper = await mountPage();
|
||||
await flushPromises();
|
||||
|
||||
expect(wrapper.get('[data-testid="my-todos-stage-filter-order_review"]').text()).toContain('1');
|
||||
wrapper.unmount();
|
||||
});
|
||||
});
|
||||
@@ -11,12 +11,14 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue';
|
||||
import { useRoute, useRouter } from 'vue-router';
|
||||
import { ExternalLink, RefreshCw } from 'lucide-vue-next';
|
||||
import { CheckSquare, Download, ExternalLink, RefreshCw, Upload } from 'lucide-vue-next';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import {
|
||||
getWorkspaceShippingTask,
|
||||
listShippingChatAgents,
|
||||
retryWorkspaceShippingOrderStpAutoCreate,
|
||||
batchConfirmWorkspaceShippingNoticesUploaded,
|
||||
batchStartWorkspaceShippingNoticeRpaUpload,
|
||||
SHIPPING_NOTICE_AGENT_CODE,
|
||||
type ShippingTaskDetail,
|
||||
type ShippingTaskSummary,
|
||||
@@ -38,6 +40,7 @@ import {
|
||||
isShippingTodoListItemInProgress,
|
||||
} from './shippingTaskCenterPolling';
|
||||
import ShippingRunProgressTable from './ShippingRunProgressTable.vue';
|
||||
import { downloadWorkspaceShippingNoticeExportArchive } from '@/features/chat/shipping/shippingDownload';
|
||||
|
||||
const { t, te } = useI18n();
|
||||
const msg = useMessage();
|
||||
@@ -98,6 +101,9 @@ const appliedFilters = ref({
|
||||
const loading = ref(false);
|
||||
const detailLoading = ref(false);
|
||||
const tasks = ref<ShippingTaskSummary[]>([]);
|
||||
/** 货代批量选择只容纳有 business_no 的正式发货通知,Review/Intake 永不进入集合。 */
|
||||
const selectedBusinessNos = ref<string[]>([]);
|
||||
const batchActionBusy = ref<'download' | 'confirm' | 'rpa' | null>(null);
|
||||
const selectedRef = ref<string | null>(null);
|
||||
/** 仅直链摘要,供入口卡展示;禁止内嵌履约工作台。 */
|
||||
const detail = ref<ShippingTaskDetail | null>(null);
|
||||
@@ -176,7 +182,13 @@ function lifecycleEntriesOf(item: ShippingTaskSummary | ShippingTaskDetail) {
|
||||
/** 当前阶段只取后端标为 current 的入口,不能以技术 stage 或阶段顺序回填。 */
|
||||
function lifecycleStageCodeOf(item: ShippingTaskSummary | ShippingTaskDetail): LifecycleStageCode | null {
|
||||
const current = lifecycleEntriesOf(item).find((entry) => entry.state === 'current');
|
||||
return current ? current.code as LifecycleStageCode : null;
|
||||
if (current) return current.code as LifecycleStageCode;
|
||||
// [AUTHORITY] 待人工处理的 Review Case 可能没有可进入工作台的 lifecycle entry,
|
||||
// 但后端仍会下发 ui_state.stage 作为当前业务阶段;统计与筛选必须保留该阶段。
|
||||
const stage = String(item.ui_state?.stage?.code || '').trim();
|
||||
return LIFECYCLE_STAGES.includes(stage as LifecycleStageCode)
|
||||
? stage as LifecycleStageCode
|
||||
: null;
|
||||
}
|
||||
|
||||
/** 可进入工作台的业务阶段仅由后端 entry.state 授权。 */
|
||||
@@ -192,6 +204,35 @@ function lifecycleEntryIsEnterable(entry: ReturnType<typeof lifecycleEntryFor>):
|
||||
return entry?.state === 'current' || entry?.state === 'available';
|
||||
}
|
||||
|
||||
/** 接收解析入口只消费后端独立授权,不从阶段名称推导可写权限。 */
|
||||
function canOpenIntakeParse(item: ShippingTaskSummary | ShippingTaskDetail | null): boolean {
|
||||
if (!item) return false;
|
||||
const runNo = String(item.review_run_no || '').trim();
|
||||
const agentId = Number(item.owner_agent_id || chatAgentId.value || 0);
|
||||
return Boolean(
|
||||
runNo
|
||||
&& agentId
|
||||
&& item.ui_state?.intake_parse_authorized === true,
|
||||
);
|
||||
}
|
||||
|
||||
/** 打开对话中的接收解析工作面,复用批次进度中心的同一深链契约。 */
|
||||
function openIntakeParse(item: ShippingTaskSummary | ShippingTaskDetail) {
|
||||
if (!canOpenIntakeParse(item)) return;
|
||||
const runNo = String(item.review_run_no || '').trim();
|
||||
const agentId = Number(item.owner_agent_id || chatAgentId.value || 0);
|
||||
const query: Record<string, string> = {
|
||||
mode: 'order-review',
|
||||
run_no: runNo,
|
||||
lifecycle_stage: 'intake_parse',
|
||||
};
|
||||
const cid = String(item.conversation_id || '').trim();
|
||||
if (cid) query.conversation_id = cid;
|
||||
const caseNo = String(item.review_case_no || '').trim();
|
||||
if (caseNo) query.case_no = caseNo;
|
||||
void router.push({ path: `/chat/${agentId}`, query });
|
||||
}
|
||||
|
||||
function defaultLifecycleTarget(item: ShippingTaskSummary | ShippingTaskDetail): Exclude<LifecycleStageCode, 'intake_parse'> | null {
|
||||
const current = lifecycleEntriesOf(item).find(
|
||||
(entry) => entry.code !== 'intake_parse' && entry.state === 'current',
|
||||
@@ -215,6 +256,12 @@ const filteredTasks = computed(() => (
|
||||
? tasks.value
|
||||
: tasks.value.filter((item) => lifecycleStageCodeOf(item) === lifecycleStageFilter.value)
|
||||
));
|
||||
const noticeRows = computed(() => filteredTasks.value.filter((item) => Boolean(String(item.business_no || '').trim())));
|
||||
const selectedBusinessNoSet = computed(() => new Set(selectedBusinessNos.value));
|
||||
const selectedNoticeCount = computed(() => selectedBusinessNos.value.length);
|
||||
const allVisibleNoticesSelected = computed(() => (
|
||||
noticeRows.value.length > 0 && noticeRows.value.every((item) => selectedBusinessNoSet.value.has(String(item.business_no)))
|
||||
));
|
||||
const lifecycleStageTargetOptions = computed(() => {
|
||||
if (!entryItem.value) return [];
|
||||
return lifecycleEntriesOf(entryItem.value)
|
||||
@@ -248,7 +295,53 @@ function todoDisplayNo(item: ShippingTaskSummary): string {
|
||||
if (item.item_kind === 'order_intake' || item.intake_no) {
|
||||
return String(item.intake_no || item.todo_ref || '—');
|
||||
}
|
||||
return String(item.task_no || item.todo_ref || '—');
|
||||
return String(item.business_no || item.task_no || item.todo_ref || '—');
|
||||
}
|
||||
|
||||
/** 切换一张正式发货通知的批量选择,始终按 business_no 去重。 */
|
||||
function toggleNoticeSelection(item: ShippingTaskSummary): void {
|
||||
const businessNo = String(item.business_no || '').trim();
|
||||
if (!businessNo) return;
|
||||
selectedBusinessNos.value = selectedBusinessNoSet.value.has(businessNo)
|
||||
? selectedBusinessNos.value.filter((value) => value !== businessNo)
|
||||
: [...selectedBusinessNos.value, businessNo];
|
||||
}
|
||||
|
||||
/** 对当前筛选页的正式通知全选/取消;Review 与 Intake 保持不可选。 */
|
||||
function toggleAllVisibleNotices(): void {
|
||||
const visible = noticeRows.value.map((item) => String(item.business_no || '').trim()).filter(Boolean);
|
||||
selectedBusinessNos.value = allVisibleNoticesSelected.value
|
||||
? selectedBusinessNos.value.filter((value) => !visible.includes(value))
|
||||
: Array.from(new Set([...selectedBusinessNos.value, ...visible]));
|
||||
}
|
||||
|
||||
/** 批量请求后只提示汇总,逐单状态由服务端结果决定,避免前端自行推断。 */
|
||||
function summarizeBatchResults(results: Array<Record<string, unknown>>, action: string): void {
|
||||
const accepted = results.filter((item) => ['accepted', 'confirmed'].includes(String(item.status || ''))).length;
|
||||
const blocked = results.length - accepted;
|
||||
if (blocked) msg.warning(t('workspace.shippingNotice.batch.partialResult', { action, accepted, blocked }));
|
||||
else msg.success(t('workspace.shippingNotice.batch.success', { action, count: accepted }));
|
||||
}
|
||||
|
||||
async function runNoticeBatchAction(action: 'download' | 'confirm' | 'rpa'): Promise<void> {
|
||||
if (!selectedBusinessNos.value.length || batchActionBusy.value) return;
|
||||
batchActionBusy.value = action;
|
||||
try {
|
||||
if (action === 'download') {
|
||||
await downloadWorkspaceShippingNoticeExportArchive(selectedBusinessNos.value);
|
||||
msg.success(t('workspace.shippingNotice.batch.downloadStarted'));
|
||||
return;
|
||||
}
|
||||
const result = action === 'confirm'
|
||||
? await batchConfirmWorkspaceShippingNoticesUploaded(selectedBusinessNos.value)
|
||||
: await batchStartWorkspaceShippingNoticeRpaUpload(selectedBusinessNos.value);
|
||||
summarizeBatchResults(result.results || [], t(`workspace.shippingNotice.batch.${action}`));
|
||||
await refreshAll();
|
||||
} catch (error) {
|
||||
msg.error(error instanceof Error ? error.message : t('workspace.shippingNotice.actions.failed'));
|
||||
} finally {
|
||||
batchActionBusy.value = null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -372,6 +465,8 @@ async function loadTodos(resetPage = false) {
|
||||
task_no: appliedFilters.value.task_no || undefined,
|
||||
});
|
||||
tasks.value = result.items || [];
|
||||
const visibleBusinessNos = new Set(tasks.value.map((item) => String(item.business_no || '').trim()).filter(Boolean));
|
||||
selectedBusinessNos.value = selectedBusinessNos.value.filter((value) => visibleBusinessNos.has(value));
|
||||
totalTasks.value = Number(result.total || 0);
|
||||
if (preferredTaskNo.value && !selectedRef.value) {
|
||||
const hit = tasks.value.find(
|
||||
@@ -670,6 +765,17 @@ onBeforeUnmount(() => {
|
||||
</p>
|
||||
<div class="flex flex-wrap gap-2">
|
||||
<button
|
||||
v-if="canOpenIntakeParse(detail)"
|
||||
type="button"
|
||||
class="inline-flex items-center gap-1.5 rounded-xl bg-brand-600 px-4 py-2 text-sm font-medium text-white hover:bg-brand-700 disabled:opacity-50"
|
||||
data-testid="my-todos-open-intake-parse"
|
||||
@click="openIntakeParse(detail)"
|
||||
>
|
||||
<ExternalLink class="h-3.5 w-3.5" />
|
||||
{{ $t('workspace.shippingNotice.myTodos.openIntakeParse') }}
|
||||
</button>
|
||||
<button
|
||||
v-else
|
||||
type="button"
|
||||
class="inline-flex items-center gap-1.5 rounded-xl bg-brand-600 px-4 py-2 text-sm font-medium text-white hover:bg-brand-700 disabled:opacity-50"
|
||||
:disabled="!canOpenOrderProcessing(detail)"
|
||||
@@ -690,7 +796,7 @@ onBeforeUnmount(() => {
|
||||
</button>
|
||||
</div>
|
||||
<p
|
||||
v-if="!canOpenOrderProcessing(detail)"
|
||||
v-if="!canOpenOrderProcessing(detail) && !canOpenIntakeParse(detail)"
|
||||
class="text-xs text-amber-700 dark:text-amber-300"
|
||||
data-testid="my-todos-open-processing-unavailable"
|
||||
>
|
||||
@@ -717,7 +823,7 @@ onBeforeUnmount(() => {
|
||||
</div>
|
||||
|
||||
<div
|
||||
class="grid gap-2 sm:grid-cols-2 xl:grid-cols-4"
|
||||
class="grid gap-2 sm:grid-cols-2 xl:grid-cols-5"
|
||||
data-testid="my-todos-lifecycle-stage-filter"
|
||||
>
|
||||
<button
|
||||
@@ -792,6 +898,51 @@ onBeforeUnmount(() => {
|
||||
|
||||
<div class="grid gap-5 lg:grid-cols-[minmax(18rem,0.85fr)_minmax(0,2.15fr)]">
|
||||
<div class="space-y-2">
|
||||
<div
|
||||
v-if="noticeRows.length"
|
||||
class="flex flex-wrap items-center gap-2 rounded-2xl border border-default bg-surface px-3 py-2"
|
||||
data-testid="shipping-notice-batch-toolbar"
|
||||
>
|
||||
<label class="inline-flex items-center gap-2 text-xs text-secondary">
|
||||
<input
|
||||
type="checkbox"
|
||||
:checked="allVisibleNoticesSelected"
|
||||
:aria-label="$t('workspace.shippingNotice.batch.selectAll')"
|
||||
@change="toggleAllVisibleNotices"
|
||||
>
|
||||
{{ $t('workspace.shippingNotice.batch.selectAll') }}
|
||||
</label>
|
||||
<span class="text-xs text-muted">
|
||||
{{ $t('workspace.shippingNotice.batch.selected', { count: selectedNoticeCount }) }}
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
class="inline-flex items-center gap-1 rounded-lg border border-default px-2 py-1 text-xs disabled:opacity-50"
|
||||
:disabled="!selectedNoticeCount || Boolean(batchActionBusy)"
|
||||
@click="runNoticeBatchAction('download')"
|
||||
>
|
||||
<Download class="h-3.5 w-3.5" />
|
||||
{{ $t('workspace.shippingNotice.batch.download') }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="inline-flex items-center gap-1 rounded-lg border border-default px-2 py-1 text-xs disabled:opacity-50"
|
||||
:disabled="!selectedNoticeCount || Boolean(batchActionBusy)"
|
||||
@click="runNoticeBatchAction('confirm')"
|
||||
>
|
||||
<CheckSquare class="h-3.5 w-3.5" />
|
||||
{{ $t('workspace.shippingNotice.batch.confirm') }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="inline-flex items-center gap-1 rounded-lg border border-default px-2 py-1 text-xs disabled:opacity-50"
|
||||
:disabled="!selectedNoticeCount || Boolean(batchActionBusy)"
|
||||
@click="runNoticeBatchAction('rpa')"
|
||||
>
|
||||
<Upload class="h-3.5 w-3.5" />
|
||||
{{ $t('workspace.shippingNotice.batch.rpa') }}
|
||||
</button>
|
||||
</div>
|
||||
<div v-if="loading" class="rounded-2xl border border-dashed border-default py-10 text-center text-sm text-muted">
|
||||
{{ $t('workspace.shippingNotice.loading') }}
|
||||
</div>
|
||||
@@ -807,7 +958,17 @@ onBeforeUnmount(() => {
|
||||
@click="selectTodo(item)"
|
||||
>
|
||||
<div class="flex items-center justify-between gap-2">
|
||||
<span class="font-mono text-sm font-semibold text-primary">{{ todoDisplayNo(item) }}</span>
|
||||
<span class="inline-flex min-w-0 items-center gap-2">
|
||||
<input
|
||||
v-if="item.business_no"
|
||||
type="checkbox"
|
||||
:checked="selectedBusinessNoSet.has(String(item.business_no))"
|
||||
:aria-label="String(item.business_no)"
|
||||
@click.stop
|
||||
@change="toggleNoticeSelection(item)"
|
||||
>
|
||||
<span class="font-mono text-sm font-semibold text-primary">{{ todoDisplayNo(item) }}</span>
|
||||
</span>
|
||||
<span
|
||||
v-if="item.todo_category === 'review' || item.item_kind === 'review_case'"
|
||||
class="rounded-full bg-amber-50 px-2 py-0.5 text-[10px] text-amber-700"
|
||||
@@ -833,6 +994,20 @@ onBeforeUnmount(() => {
|
||||
<div class="mt-1 truncate text-xs text-muted">
|
||||
{{ item.customer_name || item.source_file_name || item.review_run_no || '—' }}
|
||||
</div>
|
||||
<template v-if="item.business_no">
|
||||
<div class="mt-2 flex flex-wrap gap-x-3 gap-y-1 text-[11px] text-muted">
|
||||
<span>PO: {{ item.po_number || '—' }}</span>
|
||||
<span>{{ $t('workspace.shippingNotice.batch.lines') }}: {{ item.notice_line_summary?.length || 0 }}</span>
|
||||
<span>{{ $t('workspace.shippingNotice.batch.parts') }}: {{ item.notice_line_summary?.map((line) => line.part_number).filter(Boolean).join(' / ') || '—' }}</span>
|
||||
</div>
|
||||
<div class="mt-1 text-[11px] text-muted">
|
||||
{{ $t('workspace.shippingNotice.batch.quantities') }}:
|
||||
{{ item.notice_line_summary?.map((line) => `${line.shipment_qty || '—'} / ${line.available_qty || '—'}`).join(' · ') || '—' }}
|
||||
</div>
|
||||
<div class="mt-1 text-[11px] text-muted">
|
||||
Excel: {{ item.artifact_summary?.export_file_name || '—' }} · {{ $t('workspace.shippingNotice.batch.uploadStatus') }}: {{ item.upload_status || '—' }}
|
||||
</div>
|
||||
</template>
|
||||
</button>
|
||||
<div v-if="totalPages > 1" class="flex items-center justify-between gap-2 pt-2 text-xs text-muted">
|
||||
<button
|
||||
@@ -888,6 +1063,17 @@ onBeforeUnmount(() => {
|
||||
</option>
|
||||
</select>
|
||||
<button
|
||||
v-if="canOpenIntakeParse(selectedItem)"
|
||||
type="button"
|
||||
class="inline-flex items-center gap-1.5 rounded-xl bg-brand-600 px-4 py-2 text-sm font-medium text-white hover:bg-brand-700 disabled:opacity-50"
|
||||
data-testid="my-todos-open-intake-parse"
|
||||
@click="openIntakeParse(selectedItem)"
|
||||
>
|
||||
<ExternalLink class="h-3.5 w-3.5" />
|
||||
{{ $t('workspace.shippingNotice.myTodos.openIntakeParse') }}
|
||||
</button>
|
||||
<button
|
||||
v-else
|
||||
type="button"
|
||||
class="inline-flex items-center gap-1.5 rounded-xl bg-brand-600 px-4 py-2 text-sm font-medium text-white hover:bg-brand-700 disabled:opacity-50"
|
||||
:disabled="!canOpenOrderProcessing(selectedItem, lifecycleStageTarget)"
|
||||
@@ -987,6 +1173,17 @@ onBeforeUnmount(() => {
|
||||
</option>
|
||||
</select>
|
||||
<button
|
||||
v-if="canOpenIntakeParse(entryItem)"
|
||||
type="button"
|
||||
class="inline-flex items-center gap-1.5 rounded-xl bg-brand-600 px-4 py-2 text-sm font-medium text-white hover:bg-brand-700 disabled:opacity-50"
|
||||
data-testid="my-todos-open-intake-parse"
|
||||
@click="openIntakeParse(entryItem)"
|
||||
>
|
||||
<ExternalLink class="h-3.5 w-3.5" />
|
||||
{{ $t('workspace.shippingNotice.myTodos.openIntakeParse') }}
|
||||
</button>
|
||||
<button
|
||||
v-else
|
||||
type="button"
|
||||
class="inline-flex items-center gap-1.5 rounded-xl bg-brand-600 px-4 py-2 text-sm font-medium text-white hover:bg-brand-700 disabled:opacity-50"
|
||||
:disabled="!canOpenOrderProcessing(entryItem, lifecycleStageTarget)"
|
||||
@@ -1007,7 +1204,7 @@ onBeforeUnmount(() => {
|
||||
</button>
|
||||
</div>
|
||||
<p
|
||||
v-if="!canOpenOrderProcessing(entryItem)"
|
||||
v-if="!canOpenOrderProcessing(entryItem) && !canOpenIntakeParse(entryItem)"
|
||||
class="text-xs text-amber-700 dark:text-amber-300"
|
||||
data-testid="my-todos-open-processing-unavailable"
|
||||
>
|
||||
|
||||
@@ -22,7 +22,7 @@ import { formatLocalDateTime } from '@/shared/utils/dateTime';
|
||||
import TaskTodoPanel from './TaskTodoPanel.vue';
|
||||
import StpProgressFactsPanel from './StpProgressFactsPanel.vue';
|
||||
import TaskProgressTimeline from './TaskProgressTimeline.vue';
|
||||
import { downloadWorkspaceShippingExcelFile } from '@/features/workspace/api/shipping-tasks.api';
|
||||
import { downloadWorkspaceShippingNoticeExcelFile } from '@/features/chat/shipping/shippingDownload';
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
|
||||
const props = defineProps<{
|
||||
@@ -149,7 +149,9 @@ watch(
|
||||
*/
|
||||
async function downloadExcel() {
|
||||
try {
|
||||
await downloadWorkspaceShippingExcelFile(props.detail.task_no);
|
||||
const businessNo = String(props.detail.business_no || '').trim();
|
||||
if (!businessNo) throw new Error(t('workspace.shippingNotice.actions.failed'));
|
||||
await downloadWorkspaceShippingNoticeExcelFile(businessNo);
|
||||
emit('refreshed');
|
||||
} catch (e: unknown) {
|
||||
msg.warning(e instanceof Error ? e.message : t('workspace.shippingNotice.actions.failed'));
|
||||
@@ -214,8 +216,6 @@ async function downloadExcel() {
|
||||
<dd>{{ detail.ship_to || '—' }}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt class="text-muted">{{ $t('workspace.shippingNotice.fields.freightRef') }}</dt>
|
||||
<dd>{{ detail.freight_ref_no || '—' }}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
</section>
|
||||
|
||||
@@ -20,7 +20,7 @@ import {
|
||||
confirmWorkspaceShippingCustomer,
|
||||
listWorkspaceShippingCustomerOptions,
|
||||
} from '@/features/chat/api/shipping.api';
|
||||
import { downloadWorkspaceShippingExcelFile } from '@/features/workspace/api/shipping-tasks.api';
|
||||
import { downloadWorkspaceShippingNoticeExcelFile } from '@/features/chat/shipping/shippingDownload';
|
||||
import { refreshShippingTodoBadge } from '@/features/workspace/composables/useShippingTodoBadge';
|
||||
import ManualUploadEvidenceDialog from './ManualUploadEvidenceDialog.vue';
|
||||
import ProcessGateRecoveryCard from '@/features/shipping-process-gates/components/ProcessGateRecoveryCard.vue';
|
||||
@@ -289,7 +289,7 @@ async function runUnifiedAction(action: ShippingUnifiedAction) {
|
||||
if (!resolvedActionsExecutable.value || !action.enabled || busyId.value) return;
|
||||
const dispatch = String(action.dispatch || 'mutation').trim();
|
||||
const uiHandler = String(action.ui_handler || '').trim();
|
||||
if (dispatch === 'dialog' && uiHandler === 'manual_upload_evidence') {
|
||||
if (dispatch === 'dialog' && uiHandler === 'manual_upload_confirmation') {
|
||||
if (!(await assertFulfillmentOwnership())) return;
|
||||
manualUploadOpen.value = true;
|
||||
return;
|
||||
@@ -297,7 +297,9 @@ async function runUnifiedAction(action: ShippingUnifiedAction) {
|
||||
if (dispatch === 'view' && uiHandler === 'excel_download') {
|
||||
busyId.value = action.code;
|
||||
try {
|
||||
await downloadWorkspaceShippingExcelFile(props.detail.task_no);
|
||||
const businessNo = String(props.detail.business_no || '').trim();
|
||||
if (!businessNo) throw new Error(t('workspace.shippingNotice.actions.failed'));
|
||||
await downloadWorkspaceShippingNoticeExcelFile(businessNo);
|
||||
await afterSuccess();
|
||||
} catch (e: unknown) {
|
||||
msg.warning(e instanceof Error ? e.message : t('workspace.shippingNotice.actions.failed'));
|
||||
@@ -389,9 +391,9 @@ async function runUnifiedAction(action: ShippingUnifiedAction) {
|
||||
</div>
|
||||
<ManualUploadEvidenceDialog
|
||||
v-model:open="manualUploadOpen"
|
||||
:task-no="detail.task_no"
|
||||
:business-no="detail.business_no || ''"
|
||||
:artifact-id="currentExportArtifactId"
|
||||
:disabled="!resolvedActionsExecutable"
|
||||
:disabled="!resolvedActionsExecutable || !detail.business_no"
|
||||
@success="afterSuccess"
|
||||
/>
|
||||
<ShippingCustomerConfirmDialog
|
||||
|
||||
+18
-49
@@ -1,60 +1,29 @@
|
||||
/**
|
||||
* features/workspace/shipping-task-center/shippingTaskCenterPolling.spec.ts
|
||||
* 用途:验收任务中心 Intake / Review / OT 轮询边界(UI-01 / UI-02)。
|
||||
* 依赖:isShippingTodoListItemInProgress、ShippingTaskSummary。
|
||||
* 逻辑:parsing Intake 轮询;parse_failed 停止;Intake→OT 后按投影状态决定。
|
||||
* 用途:锁定任务中心自动轮询的边界,避免人工待处理任务被误判为持续处理中。
|
||||
* 依赖:isShippingTodoListItemInProgress。
|
||||
* 逻辑:只有后端明确的进行中状态继续轮询;复核草稿、失败和完成任务停止轮询。
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import type { ShippingTaskSummary } from '@/features/chat/api/shipping.api';
|
||||
import { isShippingTodoListItemInProgress } from './shippingTaskCenterPolling';
|
||||
|
||||
function intakeItem(status: string): ShippingTaskSummary {
|
||||
return {
|
||||
item_kind: 'order_intake',
|
||||
todo_ref: 'SNI-1',
|
||||
intake_no: 'SNI-1',
|
||||
intake_parse_status: status,
|
||||
todo_category: 'intake_parse',
|
||||
} as ShippingTaskSummary;
|
||||
}
|
||||
|
||||
describe('isShippingTodoListItemInProgress', () => {
|
||||
it('polls created/queued/parsing intake items', () => {
|
||||
// 关键断言:解析中 Intake 必须持续轮询,避免任务中心卡在旧状态。
|
||||
expect(isShippingTodoListItemInProgress(intakeItem('created'))).toBe(true);
|
||||
expect(isShippingTodoListItemInProgress(intakeItem('queued'))).toBe(true);
|
||||
expect(isShippingTodoListItemInProgress(intakeItem('parsing'))).toBe(true);
|
||||
it('does not poll a review case that is waiting for human editing', () => {
|
||||
expect(isShippingTodoListItemInProgress({
|
||||
item_kind: 'review_case',
|
||||
status: 'waiting_human',
|
||||
task_no: '',
|
||||
review_run_no: 'RUN-1',
|
||||
} as never)).toBe(false);
|
||||
});
|
||||
|
||||
it('stops polling parse_failed intake items', () => {
|
||||
expect(isShippingTodoListItemInProgress(intakeItem('parse_failed'))).toBe(false);
|
||||
});
|
||||
|
||||
it('keeps polling open review cases', () => {
|
||||
expect(
|
||||
isShippingTodoListItemInProgress({
|
||||
item_kind: 'review_case',
|
||||
review_case_no: 'SNRC-1',
|
||||
review_run_no: 'SNER-1',
|
||||
} as ShippingTaskSummary),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it('after intake becomes OT, uses shipping_processing_status', () => {
|
||||
// Intake 消失后由 OT 卡承接:waiting_review 继续轮询,completed 停止。
|
||||
expect(
|
||||
isShippingTodoListItemInProgress({
|
||||
item_kind: 'task',
|
||||
task_no: 'OT-1',
|
||||
shipping_processing_status: 'waiting_review',
|
||||
} as ShippingTaskSummary),
|
||||
).toBe(true);
|
||||
expect(
|
||||
isShippingTodoListItemInProgress({
|
||||
item_kind: 'task',
|
||||
task_no: 'OT-1',
|
||||
shipping_processing_status: 'completed',
|
||||
} as ShippingTaskSummary),
|
||||
).toBe(false);
|
||||
it('continues polling a review case with an explicit processing status', () => {
|
||||
expect(isShippingTodoListItemInProgress({
|
||||
item_kind: 'review_case',
|
||||
status: 'processing',
|
||||
shipping_processing_status: 'processing',
|
||||
task_no: '',
|
||||
review_run_no: 'RUN-1',
|
||||
} as never)).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -43,7 +43,12 @@ export const INTAKE_POLLING_PARSE_STATUSES = new Set([
|
||||
*/
|
||||
export function isShippingTodoListItemInProgress(item: ShippingTaskSummary): boolean {
|
||||
if (item.item_kind === 'review_case' || (item.review_run_no && !item.task_no)) {
|
||||
return true;
|
||||
const unified = String(item.shipping_processing_status || '').trim().toLowerCase();
|
||||
if (unified) {
|
||||
if (TERMINAL_PROCESSING_STATUSES.has(unified)) return false;
|
||||
return IN_PROGRESS_PROCESSING_STATUSES.has(unified);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
if (item.item_kind === 'order_intake') {
|
||||
const intakeStatus = String(
|
||||
|
||||
Reference in new issue
Block a user