feat(shipping-notice): 增强订单抽取与审计功能,支持取消与保留策略
- 在环境配置中新增进度细化、订单提取取消与审计导出相关的开关 - 实现订单抽取运行的取消功能,允许管理员在运行中进行操作 - 引入审计事件的保留策略,支持三年保留期的自动清理 - 更新相关模型与服务,确保新功能的完整性与可追溯性 - 增强文档与代码注释,反映新的业务逻辑与审计要求
This commit is contained in:
1 parent
c85997884b
commit
95cdfe66b0
158 files changed
+19005
-1201
No files matched your search
@@ -1,6 +1,6 @@
|
||||
/**
|
||||
* features/chat/api/shipping.api.ts
|
||||
* 用途:封装发货通知相关 HTTP API,包括任务/批次查询、人工决策与 Excel 导出。
|
||||
* 用途:封装发货通知相关 HTTP API,包括任务/批次查询、人工决策、订单抽取取消/时间线与 Excel 导出。
|
||||
* 依赖:统一 requestJson / BusinessError、shipping.api.types 类型定义。
|
||||
* 逻辑:上游由 useChatShipping、shipping-task-center 与 shipping/* handler 调用;
|
||||
* 「我的待办」列表/徽标见 features/workspace/api/shipping-tasks.api.ts。
|
||||
@@ -25,6 +25,7 @@ import type {
|
||||
ShippingTaskPage,
|
||||
ShippingTaskSummary,
|
||||
ShippingCustomerOption,
|
||||
ShippingOrderExtractionDocumentResult,
|
||||
ShippingOrderExtractionRun,
|
||||
ShippingOrderExtractionProgressEvent,
|
||||
ShippingOrderExtractionRunCreateResponse,
|
||||
@@ -33,6 +34,9 @@ import type {
|
||||
ShippingOrderReviewEvidence,
|
||||
ShippingOrderReviewReparseResponse,
|
||||
ShippingOrderReviewRun,
|
||||
ShippingSessionWorkItem,
|
||||
ShippingSessionWorkItemSummary,
|
||||
ShippingSessionWorkItemVersion,
|
||||
ShippingTaskUiState,
|
||||
} from '../types/shipping.api.types';
|
||||
|
||||
@@ -191,6 +195,34 @@ export const retryWorkspaceShippingOrderExtractionRun = (runNo: string) =>
|
||||
jsonPost(),
|
||||
);
|
||||
|
||||
/** 请求取消整批订单抽取;排队项立即取消,执行中项进入正在取消。 */
|
||||
export const cancelWorkspaceShippingOrderExtractionRun = (
|
||||
runNo: string,
|
||||
payload?: { reason?: string | null; reason_code?: string | null; operation_id?: string | null },
|
||||
) => requestJson<{ run: ShippingOrderExtractionRun }>(
|
||||
`/api/workspace/shipping-notice/order-extraction-runs/${encodeURIComponent(runNo)}/cancel`,
|
||||
jsonPost(payload || {}),
|
||||
);
|
||||
|
||||
/** 请求取消单个 PDF Unit。 */
|
||||
export const cancelWorkspaceShippingOrderExtractionDocument = (
|
||||
runNo: string,
|
||||
documentId: number,
|
||||
payload?: { reason?: string | null; reason_code?: string | null; operation_id?: string | null },
|
||||
) => requestJson<{
|
||||
run: ShippingOrderExtractionRun | null;
|
||||
document: ShippingOrderExtractionDocumentResult | null;
|
||||
}>(
|
||||
`/api/workspace/shipping-notice/order-extraction-runs/${encodeURIComponent(runNo)}/documents/${encodeURIComponent(String(documentId))}/cancel`,
|
||||
jsonPost(payload || {}),
|
||||
);
|
||||
|
||||
/** 获取用户可见 Run 时间线(含取消与重试事件)。 */
|
||||
export const listWorkspaceShippingOrderExtractionTimeline = (runNo: string) =>
|
||||
requestJson<{ items: ShippingOrderExtractionProgressEvent[] }>(
|
||||
`/api/workspace/shipping-notice/order-extraction-runs/${encodeURIComponent(runNo)}/timeline`,
|
||||
);
|
||||
|
||||
/** 使用当前发布的 Schema、绑定和布局快照创建原始文件的新版订单识别 Run。 */
|
||||
export const reparseWorkspaceShippingOrderExtractionRun = (
|
||||
runNo: string,
|
||||
@@ -340,19 +372,72 @@ export const markWorkspaceShippingOrderExtractionRunSeen = (runNo: string) =>
|
||||
jsonPost(),
|
||||
);
|
||||
|
||||
/** 拉取会话级 PDF 工作项工作台;右侧「本次处理」唯一列表事实源。 */
|
||||
export const listWorkspaceShippingSessionWorkItems = (
|
||||
conversationId: string,
|
||||
options?: { open_only?: boolean; signal?: AbortSignal },
|
||||
) => {
|
||||
const params = new URLSearchParams({ conversation_id: conversationId });
|
||||
if (options?.open_only) params.set('open_only', 'true');
|
||||
return requestJson<ShippingSessionWorkItemSummary>(
|
||||
`/api/workspace/shipping-notice/session-work-items?${params.toString()}`,
|
||||
{ signal: options?.signal },
|
||||
);
|
||||
};
|
||||
|
||||
/** 读取单条工作项的版本历史时间线。 */
|
||||
export const listWorkspaceShippingSessionWorkItemVersions = (itemNo: string) =>
|
||||
requestJson<{ item_no: string; versions: ShippingSessionWorkItemVersion[] }>(
|
||||
`/api/workspace/shipping-notice/session-work-items/${encodeURIComponent(itemNo)}/versions`,
|
||||
);
|
||||
|
||||
/** 关闭(取消)会话 PDF 工作项;需携带 reason 与可选乐观锁版本。 */
|
||||
export const closeWorkspaceShippingSessionWorkItem = (
|
||||
itemNo: string,
|
||||
payload: { reason: string; expected_lock_version?: number | null },
|
||||
) => requestJson<{ item: ShippingSessionWorkItem }>(
|
||||
`/api/workspace/shipping-notice/session-work-items/${encodeURIComponent(itemNo)}/close`,
|
||||
jsonPost(payload),
|
||||
);
|
||||
|
||||
/** 按会话恢复订单抽取 Run,刷新页面后不依赖聊天 SSE 历史。 */
|
||||
export const listWorkspaceShippingOrderExtractionRuns = (
|
||||
conversationId: string,
|
||||
conversationId?: string | null,
|
||||
limit = 50,
|
||||
signal?: AbortSignal,
|
||||
) => {
|
||||
const params = new URLSearchParams({ conversation_id: conversationId, limit: String(limit) });
|
||||
const params = new URLSearchParams({ limit: String(limit) });
|
||||
if (conversationId) params.set('conversation_id', conversationId);
|
||||
return requestJson<{ items: ShippingOrderExtractionRun[] }>(
|
||||
`/api/workspace/shipping-notice/order-extraction-runs?${params.toString()}`,
|
||||
{ signal },
|
||||
);
|
||||
};
|
||||
|
||||
/** 任务中心续办:分页列出当前用户订单抽取 Run(可按状态过滤)。 */
|
||||
export const listWorkspaceShippingOrderExtractionRunsPage = (params?: {
|
||||
status?: string;
|
||||
page?: number;
|
||||
page_size?: number;
|
||||
conversation_id?: string;
|
||||
signal?: AbortSignal;
|
||||
}) => {
|
||||
const sp = new URLSearchParams();
|
||||
if (params?.status) sp.set('status', params.status);
|
||||
if (params?.page) sp.set('page', String(params.page));
|
||||
if (params?.page_size) sp.set('page_size', String(params.page_size));
|
||||
if (params?.conversation_id) sp.set('conversation_id', params.conversation_id);
|
||||
return requestJson<{
|
||||
items: ShippingOrderExtractionRun[];
|
||||
total: number;
|
||||
page: number;
|
||||
page_size: number;
|
||||
}>(
|
||||
`/api/workspace/shipping-notice/order-extraction-runs?${sp.toString()}`,
|
||||
{ signal: params?.signal },
|
||||
);
|
||||
};
|
||||
|
||||
/** 批量归档任务,适用于外部上传中或已上传而禁止平台单方作废的任务。 */
|
||||
export const archiveWorkspaceShippingTasks = (taskNos: string[]) =>
|
||||
requestJson<ShippingTaskBatchDispositionResponse>(
|
||||
|
||||
@@ -6,7 +6,8 @@
|
||||
|
||||
* 依赖:ChatSidebar、ChatMessageList、ChatInputBar、ShippingSessionSummaryPanel、chat.context。
|
||||
|
||||
* 逻辑:本文件只做页面结构编排;货代 Chat 仅上传/进度通知,履约写操作不在本页;右侧摘要只读展示后端 ui_state/summary。
|
||||
* 逻辑:本文件只做页面结构编排;货代 Chat 仅上传/进度通知,履约写操作不在本页;
|
||||
* 右侧「本次处理」由 conversationId 驱动 session-work-items,extractionRunNo 仅作进度装饰。
|
||||
|
||||
*/
|
||||
|
||||
@@ -139,19 +140,13 @@ const activeExtractionRunNo = computed(() => {
|
||||
|
||||
|
||||
const showShippingSessionSummary = computed(() => (
|
||||
|
||||
page.isShippingNoticeAgent
|
||||
|
||||
&& Boolean(
|
||||
|
||||
page.shippingBatchSummary
|
||||
|
||||
page.conversationId
|
||||
|| page.shippingBatchSummary
|
||||
|| page.shippingConversationWorkspace?.batches?.length
|
||||
|
||||
|| activeExtractionRunNo.value
|
||||
|
||||
)
|
||||
|
||||
));
|
||||
|
||||
const embeddedIframeSrc = computed(() => {
|
||||
@@ -664,6 +659,8 @@ watch(() => page.currentAgentId, () => {
|
||||
|
||||
v-if="showShippingSessionSummary"
|
||||
|
||||
:conversation-id="page.conversationId"
|
||||
|
||||
:conversation-workspace="page.shippingConversationWorkspace"
|
||||
|
||||
:active-batch-no="page.activeShippingBatchNo"
|
||||
@@ -676,6 +673,8 @@ watch(() => page.currentAgentId, () => {
|
||||
|
||||
:extraction-run-no="activeExtractionRunNo"
|
||||
|
||||
:refresh-trigger="page.sessionWorkItemsRefreshTrigger"
|
||||
|
||||
/>
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,174 @@
|
||||
/**
|
||||
* features/chat/components/ShippingSessionSummaryPanel.spec.ts
|
||||
* 用途:验证右侧「本次处理」以 session-work-items 为列表事实源。
|
||||
* 依赖:Vitest、Vue Test Utils、vue-i18n、vue-router、shipping.api mock。
|
||||
* 逻辑:断言两次重识别后仍展示 2 条 open 项;已关闭分组默认折叠。
|
||||
*/
|
||||
import { mount, flushPromises } from '@vue/test-utils';
|
||||
import { describe, expect, it, vi, beforeEach } from 'vitest';
|
||||
import { createI18n } from 'vue-i18n';
|
||||
import { createRouter, createMemoryHistory } from 'vue-router';
|
||||
import chatZhCn from '@/locales/zh-CN/chat.json';
|
||||
import ShippingSessionSummaryPanel from './ShippingSessionSummaryPanel.vue';
|
||||
import type { ShippingSessionWorkItemSummary } from '../types/shipping.api.types';
|
||||
|
||||
vi.mock('@/features/chat/api/shipping.api', () => ({
|
||||
listWorkspaceShippingSessionWorkItems: vi.fn(),
|
||||
listWorkspaceShippingSessionWorkItemVersions: vi.fn(),
|
||||
getWorkspaceShippingOrderExtractionRun: vi.fn(),
|
||||
closeWorkspaceShippingSessionWorkItem: vi.fn(),
|
||||
markWorkspaceShippingOrderReviewNonOrder: vi.fn(),
|
||||
reparseWorkspaceShippingOrderReviewDocument: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('@/shared/composables/useMessage', () => ({
|
||||
useMessage: () => ({
|
||||
success: vi.fn(),
|
||||
error: vi.fn(),
|
||||
warning: vi.fn(),
|
||||
info: vi.fn(),
|
||||
}),
|
||||
}));
|
||||
|
||||
import {
|
||||
getWorkspaceShippingOrderExtractionRun,
|
||||
listWorkspaceShippingSessionWorkItems,
|
||||
} from '@/features/chat/api/shipping.api';
|
||||
|
||||
const i18n = createI18n({
|
||||
legacy: false,
|
||||
locale: 'zh-CN',
|
||||
messages: { 'zh-CN': { chat: chatZhCn } },
|
||||
});
|
||||
|
||||
const router = createRouter({
|
||||
history: createMemoryHistory(),
|
||||
routes: [{ path: '/chat/:agentId', name: 'Chat', component: { template: '<div />' } }],
|
||||
});
|
||||
|
||||
const buildWorkbench = (patch: Partial<ShippingSessionWorkItemSummary> = {}): ShippingSessionWorkItemSummary => ({
|
||||
conversation_id: 'conv-1',
|
||||
open_count: 2,
|
||||
closed_count: 1,
|
||||
pending_review_count: 2,
|
||||
extracting_count: 0,
|
||||
open_items: [
|
||||
{
|
||||
item_no: 'SWI-001',
|
||||
conversation_id: 'conv-1',
|
||||
owner_user_id: 1,
|
||||
root_document_id: 10,
|
||||
current_document_id: 10,
|
||||
current_document_filename: 'PO-A.pdf',
|
||||
current_run_no: 'SNER-1',
|
||||
current_case_no: 'SNRC-1',
|
||||
current_version_no: 1,
|
||||
lifecycle_status: 'pending_review',
|
||||
lock_version: 1,
|
||||
available_actions: [
|
||||
'enter_manual_review',
|
||||
'view_version_history',
|
||||
'request_reparse',
|
||||
'mark_non_order',
|
||||
'cancel',
|
||||
'replace_file',
|
||||
],
|
||||
},
|
||||
{
|
||||
item_no: 'SWI-002',
|
||||
conversation_id: 'conv-1',
|
||||
owner_user_id: 1,
|
||||
root_document_id: 11,
|
||||
current_document_id: 11,
|
||||
current_document_filename: 'PO-B.pdf',
|
||||
current_run_no: 'SNER-2',
|
||||
current_case_no: 'SNRC-2',
|
||||
current_version_no: 2,
|
||||
lifecycle_status: 'pending_review',
|
||||
lock_version: 2,
|
||||
version_replaced: true,
|
||||
available_actions: [
|
||||
'enter_manual_review',
|
||||
'view_version_history',
|
||||
'request_reparse',
|
||||
'mark_non_order',
|
||||
'cancel',
|
||||
'replace_file',
|
||||
],
|
||||
},
|
||||
],
|
||||
closed_items: [
|
||||
{
|
||||
item_no: 'SWI-003',
|
||||
conversation_id: 'conv-1',
|
||||
owner_user_id: 1,
|
||||
root_document_id: 12,
|
||||
current_document_id: 12,
|
||||
current_document_filename: 'PO-C.pdf',
|
||||
current_version_no: 1,
|
||||
lifecycle_status: 'closed',
|
||||
closed_reason: 'confirmed',
|
||||
lock_version: 1,
|
||||
available_actions: ['view_version_history'],
|
||||
},
|
||||
],
|
||||
closed_collapsed: true,
|
||||
max_open_items: 50,
|
||||
truncated: false,
|
||||
...patch,
|
||||
});
|
||||
|
||||
describe('ShippingSessionSummaryPanel', () => {
|
||||
beforeEach(() => {
|
||||
vi.mocked(listWorkspaceShippingSessionWorkItems).mockReset();
|
||||
vi.mocked(getWorkspaceShippingOrderExtractionRun).mockReset();
|
||||
vi.mocked(getWorkspaceShippingOrderExtractionRun).mockResolvedValue(null as never);
|
||||
});
|
||||
|
||||
it('shows two open work items after two reparses mock', async () => {
|
||||
vi.mocked(listWorkspaceShippingSessionWorkItems).mockResolvedValue(buildWorkbench());
|
||||
const wrapper = mount(ShippingSessionSummaryPanel, {
|
||||
props: {
|
||||
conversationId: 'conv-1',
|
||||
conversationWorkspace: null,
|
||||
activeBatchNo: '',
|
||||
batchSummary: null,
|
||||
batchTasks: [],
|
||||
activeTaskDetail: null,
|
||||
},
|
||||
global: { plugins: [i18n, router] },
|
||||
});
|
||||
await flushPromises();
|
||||
const rows = wrapper.findAll('[data-testid^="shipping-session-work-item-"]');
|
||||
expect(rows.length).toBe(2);
|
||||
expect(wrapper.text()).toContain('PO-A.pdf');
|
||||
expect(wrapper.text()).toContain('PO-B.pdf');
|
||||
expect(wrapper.text()).toContain('V2');
|
||||
expect(wrapper.text()).toContain('已生成新版本');
|
||||
expect(wrapper.findAll('[data-testid="shipping-session-action-cancel"]').length).toBe(2);
|
||||
expect(wrapper.findAll('[data-testid="shipping-session-action-non-order"]').length).toBe(2);
|
||||
expect(wrapper.findAll('[data-testid="shipping-session-action-reparse"]').length).toBe(2);
|
||||
expect(wrapper.findAll('[data-testid="shipping-session-action-replace"]').length).toBe(2);
|
||||
});
|
||||
|
||||
it('keeps closed section collapsed by default', async () => {
|
||||
vi.mocked(listWorkspaceShippingSessionWorkItems).mockResolvedValue(buildWorkbench());
|
||||
const wrapper = mount(ShippingSessionSummaryPanel, {
|
||||
props: {
|
||||
conversationId: 'conv-1',
|
||||
conversationWorkspace: null,
|
||||
activeBatchNo: '',
|
||||
batchSummary: null,
|
||||
batchTasks: [],
|
||||
activeTaskDetail: null,
|
||||
},
|
||||
global: { plugins: [i18n, router] },
|
||||
});
|
||||
await flushPromises();
|
||||
expect(wrapper.find('[data-testid="shipping-session-closed-section"]').exists()).toBe(true);
|
||||
expect(wrapper.text()).toContain('已完成 1 项');
|
||||
expect(wrapper.text()).not.toContain('PO-C.pdf');
|
||||
await wrapper.find('[data-testid="shipping-session-closed-section"] button').trigger('click');
|
||||
expect(wrapper.text()).toContain('PO-C.pdf');
|
||||
});
|
||||
});
|
||||
@@ -1,329 +1,284 @@
|
||||
/**
|
||||
* features/chat/components/ShippingSessionSummaryPanel.vue
|
||||
* 用途:聊天页右侧「本次处理」唯一状态面——每 PDF 实时状态、异常原因与复核/已有任务深链。
|
||||
* 依赖:vue-i18n、vue-router、lucide、shipping.api(含 extraction documents)。
|
||||
* 逻辑:合并批次 Task 行与抽取 Run 文档行;open_existing 分流为「重复处理中 + 查看已有任务」。
|
||||
* 用途:聊天页右侧「本次处理」面板——以会话级 PDF 工作项 API 为唯一列表事实源。
|
||||
* 依赖:vue-i18n、vue-router、shipping.api session-work-items / 复核处置、useMessage。
|
||||
* 逻辑:conversationId 驱动 listWorkspaceShippingSessionWorkItems 轮询;extractionRunNo 仅作 Run 级处理事项装饰;
|
||||
* 按 available_actions 渲染人工复核/版本历史/取消/非订单/重识别/替换文件入口。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import { computed, onBeforeUnmount, ref, watch } from 'vue';
|
||||
import { useRoute, useRouter } from 'vue-router';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { ChevronDown, ChevronRight, ExternalLink } from 'lucide-vue-next';
|
||||
import { BusinessError } from '@/shared/api/client';
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
import {
|
||||
getWorkspaceShippingOrderReviewRun,
|
||||
listWorkspaceShippingOrderExtractionDocuments,
|
||||
closeWorkspaceShippingSessionWorkItem,
|
||||
getWorkspaceShippingOrderExtractionRun,
|
||||
listWorkspaceShippingSessionWorkItemVersions,
|
||||
listWorkspaceShippingSessionWorkItems,
|
||||
markWorkspaceShippingOrderReviewNonOrder,
|
||||
reparseWorkspaceShippingOrderReviewDocument,
|
||||
type ShippingBatchSummary,
|
||||
type ShippingConversationWorkspace,
|
||||
type ShippingTaskDetail,
|
||||
type ShippingTaskSummary,
|
||||
type ShippingTaskUiState,
|
||||
} from '@/features/chat/api/shipping.api';
|
||||
import type { ShippingOrderExtractionDocumentResult } from '@/features/chat/types/shipping.api.types';
|
||||
import type {
|
||||
ShippingOrderExtractionRun,
|
||||
ShippingSessionWorkItem,
|
||||
ShippingSessionWorkItemSummary,
|
||||
ShippingSessionWorkItemVersion,
|
||||
} from '@/features/chat/types/shipping.api.types';
|
||||
import {
|
||||
listDisplayableHandlingAffectedRefs,
|
||||
type ShippingHandlingAffectedRef,
|
||||
type ShippingHandlingRefTarget,
|
||||
} from '@/features/chat/shipping/orderExtractionHandlingRefs';
|
||||
|
||||
const props = defineProps<{
|
||||
/** 当前聊天会话 ID;工作项列表的唯一驱动键。 */
|
||||
conversationId?: string | null;
|
||||
conversationWorkspace: ShippingConversationWorkspace | null;
|
||||
activeBatchNo: string;
|
||||
batchSummary: ShippingBatchSummary | null;
|
||||
batchTasks: ShippingTaskSummary[];
|
||||
activeTaskDetail: ShippingTaskDetail | null;
|
||||
/** 当前会话活跃抽取 Run;有值时右侧轮询每 PDF 状态 */
|
||||
/** 可选:当前活跃抽取 Run,仅用于 Run 级 handling_items 装饰,不驱动 PDF 列表。 */
|
||||
extractionRunNo?: string | null;
|
||||
/** 父级递增以触发立即刷新(终态/重识别/会话恢复后)。 */
|
||||
refreshTrigger?: number;
|
||||
}>();
|
||||
|
||||
const { t, te } = useI18n();
|
||||
const { t, te, locale } = useI18n();
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
const msg = useMessage();
|
||||
const collapsed = ref(false);
|
||||
const extractionDocs = ref<ShippingOrderExtractionDocumentResult[]>([]);
|
||||
const docsLoading = ref(false);
|
||||
let docsTimer: ReturnType<typeof setInterval> | null = null;
|
||||
const openOnlyFilter = ref(false);
|
||||
const closedExpanded = ref(false);
|
||||
const workbench = ref<ShippingSessionWorkItemSummary | null>(null);
|
||||
const workItemsLoading = ref(false);
|
||||
const actionBusyItemNo = ref<string | null>(null);
|
||||
const extractionRun = ref<ShippingOrderExtractionRun | null>(null);
|
||||
const versionHistoryItemNo = ref<string | null>(null);
|
||||
const versionHistoryItems = ref<ShippingSessionWorkItemVersion[]>([]);
|
||||
const versionHistoryLoading = ref(false);
|
||||
let workItemsTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
let workItemsPollGeneration = 0;
|
||||
let workItemsRequestController: AbortController | null = null;
|
||||
|
||||
const workspaceBatches = computed(() => props.conversationWorkspace?.batches || []);
|
||||
const activeBatchNo = computed(() =>
|
||||
String(props.activeBatchNo || props.batchSummary?.batch_no || workspaceBatches.value[0]?.batch_no || '').trim(),
|
||||
);
|
||||
const FOREGROUND_POLL_MS = 2000;
|
||||
const BACKGROUND_POLL_MS = 8000;
|
||||
|
||||
/**
|
||||
* 判断文档是否为「打开已有任务」分流。
|
||||
* 按页面可见性选择工作项轮询间隔。
|
||||
*/
|
||||
function isOpenExistingDoc(doc: ShippingOrderExtractionDocumentResult): boolean {
|
||||
const taskNo = String(doc.existing_task_no || '').trim();
|
||||
return Boolean(
|
||||
taskNo
|
||||
&& (
|
||||
doc.duplicate_resolution === 'open_existing'
|
||||
|| doc.available_actions.includes('open_existing')
|
||||
),
|
||||
);
|
||||
function resolveWorkItemsPollMs(): number {
|
||||
if (typeof document !== 'undefined' && document.visibilityState === 'hidden') {
|
||||
return BACKGROUND_POLL_MS;
|
||||
}
|
||||
return FOREGROUND_POLL_MS;
|
||||
}
|
||||
|
||||
const processSummary = computed(() => {
|
||||
const summary = props.batchSummary?.process_summary || props.conversationWorkspace?.summary || null;
|
||||
const fromDocs = extractionDocs.value;
|
||||
const total = Number(
|
||||
(summary as { total?: number } | null)?.total
|
||||
|| props.batchSummary?.file_count
|
||||
|| props.batchTasks.length
|
||||
|| fromDocs.length
|
||||
|| 0,
|
||||
const normalizedConversationId = computed(() => String(props.conversationId || '').trim());
|
||||
|
||||
const handlingItems = computed(() => (
|
||||
Array.isArray(extractionRun.value?.handling_items)
|
||||
? extractionRun.value!.handling_items!.filter((item) => String(item.category || '').trim())
|
||||
: []
|
||||
));
|
||||
|
||||
const openItems = computed((): ShippingSessionWorkItem[] => workbench.value?.open_items || []);
|
||||
const closedItems = computed((): ShippingSessionWorkItem[] => workbench.value?.closed_items || []);
|
||||
|
||||
const displayOpenItems = computed(() => {
|
||||
if (!openOnlyFilter.value) return openItems.value;
|
||||
return openItems.value.filter((item) =>
|
||||
item.lifecycle_status === 'pending_review' || item.lifecycle_status === 'reparse_failed',
|
||||
);
|
||||
const reviewFromDocs = fromDocs.filter((d) =>
|
||||
!isOpenExistingDoc(d)
|
||||
&& (
|
||||
d.status === 'review_required'
|
||||
|| d.available_actions.some((a) => a === 'review_candidate' || a === 'manual_review')
|
||||
),
|
||||
).length;
|
||||
const openExistingFromDocs = fromDocs.filter((d) => isOpenExistingDoc(d)).length;
|
||||
return {
|
||||
total,
|
||||
completed: Number((summary as { completed?: number } | null)?.completed || 0),
|
||||
running: Number((summary as { running?: number } | null)?.running || 0),
|
||||
failed: Number((summary as { failed?: number } | null)?.failed
|
||||
|| fromDocs.filter((d) => d.status === 'failed').length
|
||||
|| 0),
|
||||
needsHuman: Number(
|
||||
(summary as { needs_human?: number } | null)?.needs_human
|
||||
|| props.conversationWorkspace?.summary?.needs_human
|
||||
|| reviewFromDocs
|
||||
|| 0,
|
||||
),
|
||||
openExisting: openExistingFromDocs,
|
||||
pending: Number((summary as { pending?: number } | null)?.pending || 0),
|
||||
};
|
||||
});
|
||||
|
||||
type SummaryRow = {
|
||||
key: string;
|
||||
fileName: string;
|
||||
taskNo: string;
|
||||
runNo: string;
|
||||
caseNo: string;
|
||||
index: number;
|
||||
total: number;
|
||||
stage: string;
|
||||
message: string;
|
||||
entrySurface: string;
|
||||
/** exception=需人工异常;duplicate=已识别重复关联;none=无标签 */
|
||||
badge: 'exception' | 'duplicate' | 'none';
|
||||
kind: 'task' | 'document';
|
||||
};
|
||||
const processSummary = computed(() => ({
|
||||
total: Number(workbench.value?.open_count || 0) + Number(workbench.value?.closed_count || 0),
|
||||
completed: Number(workbench.value?.closed_count || 0),
|
||||
running: Number(workbench.value?.extracting_count || 0),
|
||||
needsHuman: Number(workbench.value?.pending_review_count || 0),
|
||||
failed: openItems.value.filter((item) => item.lifecycle_status === 'reparse_failed').length,
|
||||
pending: 0,
|
||||
openExisting: 0,
|
||||
pendingConfirmation: 0,
|
||||
cancelled: 0,
|
||||
}));
|
||||
|
||||
/**
|
||||
* 将 Task ui_state 映射为右侧行。
|
||||
* 解析 Run 级处理事项标题。
|
||||
*/
|
||||
function mapTaskRow(task: ShippingTaskSummary, index: number, total: number): SummaryRow {
|
||||
const uiState: ShippingTaskUiState | null | undefined =
|
||||
(props.activeTaskDetail?.task_no === task.task_no ? props.activeTaskDetail.ui_state : null)
|
||||
|| task.ui_state;
|
||||
const summary = uiState?.summary;
|
||||
const kind = String(uiState?.checkpoint_kind || summary?.checkpoint_kind || '');
|
||||
const stage = String(summary?.stage || summary?.title || task.process_status || '').trim();
|
||||
let normalizedStage = stage;
|
||||
if (kind === 'wait_manual_upload') normalizedStage = t('chat.shippingSessionSummary.waitingUpload');
|
||||
else if (kind === 'auto_continue') normalizedStage = t('chat.shippingSessionSummary.autoProcessing');
|
||||
else if (kind === 'must_human') normalizedStage = stage || t('chat.shippingSessionSummary.needsReview');
|
||||
return {
|
||||
key: `task:${task.task_no || index}`,
|
||||
fileName: String(task.source_file_name || '').trim(),
|
||||
taskNo: String(task.task_no || '').trim(),
|
||||
runNo: '',
|
||||
caseNo: '',
|
||||
index: Number(task.batch_index || index + 1),
|
||||
total: Number(task.batch_total || total || 1),
|
||||
stage: normalizedStage,
|
||||
message: String(summary?.message || summary?.current_todo || summary?.pause_reason || '').trim(),
|
||||
entrySurface: String(summary?.entry_surface || 'none').trim(),
|
||||
badge: (
|
||||
summary?.pause_reason
|
||||
|| task.pending_human_reason
|
||||
|| task.error_message
|
||||
|| kind === 'must_human'
|
||||
|| ['rejected', 'upload_failed'].includes(String(task.process_status || ''))
|
||||
) ? 'exception' : 'none',
|
||||
kind: 'task',
|
||||
};
|
||||
function handlingTitle(category: string): string {
|
||||
const key = `chat.shippingOrderExtractionHandling.category.${category}`;
|
||||
return te(key) ? t(key) : category;
|
||||
}
|
||||
|
||||
/**
|
||||
* 将 reason_code / review_details 拼成用户可读原因。
|
||||
* 解析原因码文案。
|
||||
*/
|
||||
function formatDocumentReason(doc: ShippingOrderExtractionDocumentResult): string {
|
||||
const reasonKey = `chat.shippingOrderExtractionReason.${doc.reason_code || ''}`;
|
||||
const reasonText = doc.reason_code && te(reasonKey)
|
||||
? t(reasonKey)
|
||||
: String(doc.reason_code || doc.activity_event_code || '').trim();
|
||||
const detailParts: string[] = [];
|
||||
for (const detail of (doc.review_details || []).slice(0, 2)) {
|
||||
const fieldCode = String(detail.field_code || '').trim();
|
||||
const fieldKey = `chat.shippingOrderExtractionReviewField.${fieldCode || 'unknown'}`;
|
||||
const fieldLabel = te(fieldKey) ? t(fieldKey) : (fieldCode || t('chat.shippingOrderExtractionReviewField.unknown'));
|
||||
const detailReasonKey = `chat.shippingOrderExtractionReason.${detail.reason_code || ''}`;
|
||||
const detailReason = detail.reason_code && te(detailReasonKey)
|
||||
? t(detailReasonKey)
|
||||
: String(detail.reason_code || '').trim();
|
||||
detailParts.push(
|
||||
t('chat.shippingOrderExtractionReviewDetail', {
|
||||
line: detail.line_number,
|
||||
field: fieldLabel,
|
||||
}) + (detailReason ? `(${detailReason})` : ''),
|
||||
);
|
||||
}
|
||||
if (reasonText && detailParts.length) return `${reasonText};${detailParts.join(';')}`;
|
||||
if (detailParts.length) return detailParts.join(';');
|
||||
return reasonText;
|
||||
function handlingReasonLabel(code: string): string {
|
||||
const key = `chat.shippingOrderExtractionReason.${code}`;
|
||||
if (te(key)) return t(key);
|
||||
const freezeKey = `chat.shippingOrderExtractionHandling.reason.${code}`;
|
||||
return te(freezeKey) ? t(freezeKey) : code;
|
||||
}
|
||||
|
||||
/**
|
||||
* 将抽取文档映射为建单前右侧行;open_existing 走任务深链。
|
||||
* 解析工作项生命周期状态文案。
|
||||
*/
|
||||
function mapDocumentRow(
|
||||
doc: ShippingOrderExtractionDocumentResult,
|
||||
index: number,
|
||||
total: number,
|
||||
runNo: string,
|
||||
caseNo = '',
|
||||
): SummaryRow {
|
||||
const existingTaskNo = String(doc.existing_task_no || '').trim();
|
||||
const openExisting = isOpenExistingDoc(doc);
|
||||
const needsReview = !openExisting && (
|
||||
doc.status === 'review_required'
|
||||
|| doc.available_actions.some((a) => a === 'review_candidate' || a === 'manual_review')
|
||||
|| Boolean(caseNo)
|
||||
);
|
||||
const failed = doc.status === 'failed';
|
||||
const reasonText = formatDocumentReason(doc);
|
||||
let stage = t('chat.shippingSessionSummary.autoProcessing');
|
||||
let entrySurface = 'none';
|
||||
let message = reasonText;
|
||||
let taskNo = '';
|
||||
if (openExisting && existingTaskNo) {
|
||||
stage = t('chat.shippingSessionSummary.duplicateProcessing');
|
||||
entrySurface = 'task_workbench';
|
||||
taskNo = existingTaskNo;
|
||||
message = reasonText
|
||||
? `${t('chat.shippingSessionSummary.existingTaskNo', { taskNo: existingTaskNo })} · ${reasonText}`
|
||||
: t('chat.shippingSessionSummary.existingTaskNo', { taskNo: existingTaskNo });
|
||||
} else if (needsReview) {
|
||||
stage = t('chat.shippingSessionSummary.needsReview');
|
||||
entrySurface = 'review_workbench';
|
||||
} else if (failed) {
|
||||
stage = t('chat.shippingOrderExtractionDocumentStatus.failed');
|
||||
}
|
||||
return {
|
||||
key: `doc:${doc.unit_id || doc.document_id || index}`,
|
||||
fileName: String(doc.file_name || '').trim(),
|
||||
taskNo,
|
||||
runNo,
|
||||
caseNo,
|
||||
index: index + 1,
|
||||
total,
|
||||
stage,
|
||||
message,
|
||||
entrySurface,
|
||||
badge: openExisting ? 'duplicate' : (needsReview || failed ? 'exception' : 'none'),
|
||||
kind: 'document',
|
||||
};
|
||||
function lifecycleStatusLabel(status: string): string {
|
||||
const key = `chat.shippingSessionWorkItem.status.${status}`;
|
||||
return te(key) ? t(key) : status;
|
||||
}
|
||||
|
||||
const caseNoByDocumentId = ref<Record<number, string>>({});
|
||||
|
||||
const taskRows = computed((): SummaryRow[] => {
|
||||
const runNo = String(props.extractionRunNo || '').trim();
|
||||
// [STEP 1] 建单前:有抽取 Run 时优先展示每 PDF 文档行(含复核/已有任务深链)。
|
||||
if (runNo && extractionDocs.value.length) {
|
||||
return extractionDocs.value.map((doc, index) =>
|
||||
mapDocumentRow(
|
||||
doc,
|
||||
index,
|
||||
extractionDocs.value.length,
|
||||
runNo,
|
||||
caseNoByDocumentId.value[Number(doc.document_id)] || '',
|
||||
));
|
||||
}
|
||||
// [STEP 2] 建单后:展示 Task 行。
|
||||
const tasks = props.batchTasks.length
|
||||
? props.batchTasks
|
||||
: (workspaceBatches.value.find((b) => b.batch_no === activeBatchNo.value)?.tasks || []);
|
||||
if (tasks.length) {
|
||||
return tasks.map((task, index) => mapTaskRow(task, index, processSummary.value.total || tasks.length));
|
||||
}
|
||||
return [];
|
||||
});
|
||||
/**
|
||||
* 解析工作项关闭原因文案。
|
||||
*/
|
||||
function closedReasonLabel(reason?: string | null): string {
|
||||
const normalized = String(reason || '').trim();
|
||||
if (!normalized) return '';
|
||||
const key = `chat.shippingSessionWorkItem.closedReason.${normalized}`;
|
||||
return te(key) ? t(key) : normalized;
|
||||
}
|
||||
|
||||
/**
|
||||
* 拉取当前 Run 文档与复核 Case,保证右侧可深链 case_no/run_no/existing_task_no。
|
||||
* 格式化 updated_at 为「更新于 HH:mm」。
|
||||
*/
|
||||
async function refreshExtractionDocs() {
|
||||
const runNo = String(props.extractionRunNo || '').trim();
|
||||
if (!runNo || docsLoading.value) return;
|
||||
docsLoading.value = true;
|
||||
function formatUpdatedLabel(value?: string | null): string {
|
||||
const date = new Date(String(value || ''));
|
||||
if (Number.isNaN(date.getTime())) return '';
|
||||
const time = new Intl.DateTimeFormat(String(locale.value || 'zh-CN'), {
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
hour12: false,
|
||||
}).format(date);
|
||||
return t('chat.shippingOrderExtractionDocumentTiming.updated', { time });
|
||||
}
|
||||
|
||||
/**
|
||||
* 拉取会话工作台与可选 Run 装饰数据。
|
||||
*/
|
||||
async function refreshWorkItems() {
|
||||
const conversationId = normalizedConversationId.value;
|
||||
if (!conversationId || workItemsLoading.value) return;
|
||||
workItemsLoading.value = true;
|
||||
workItemsRequestController?.abort();
|
||||
const controller = new AbortController();
|
||||
workItemsRequestController = controller;
|
||||
try {
|
||||
const [docsResponse, reviewResponse] = await Promise.all([
|
||||
listWorkspaceShippingOrderExtractionDocuments(runNo),
|
||||
getWorkspaceShippingOrderReviewRun(runNo).catch(() => null),
|
||||
const [summaryResponse, runResponse] = await Promise.all([
|
||||
listWorkspaceShippingSessionWorkItems(conversationId, {
|
||||
open_only: openOnlyFilter.value,
|
||||
signal: controller.signal,
|
||||
}),
|
||||
(() => {
|
||||
const runNo = String(props.extractionRunNo || '').trim();
|
||||
return runNo ? getWorkspaceShippingOrderExtractionRun(runNo).catch(() => null) : Promise.resolve(null);
|
||||
})(),
|
||||
]);
|
||||
extractionDocs.value = docsResponse.items || [];
|
||||
const mapping: Record<number, string> = {};
|
||||
for (const item of reviewResponse?.items || []) {
|
||||
const docId = Number(item.document_id);
|
||||
const caseNo = String(item.case_no || '').trim();
|
||||
if (docId && caseNo) mapping[docId] = caseNo;
|
||||
if (controller.signal.aborted) return;
|
||||
workbench.value = summaryResponse;
|
||||
extractionRun.value = runResponse;
|
||||
if (!closedExpanded.value) {
|
||||
closedExpanded.value = false;
|
||||
}
|
||||
caseNoByDocumentId.value = mapping;
|
||||
} catch {
|
||||
/* 右侧失败不打断聊天 */
|
||||
} finally {
|
||||
docsLoading.value = false;
|
||||
if (workItemsRequestController === controller) {
|
||||
workItemsRequestController = null;
|
||||
}
|
||||
workItemsLoading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
function stopDocsPolling() {
|
||||
if (docsTimer) clearInterval(docsTimer);
|
||||
docsTimer = null;
|
||||
function stopWorkItemsPolling() {
|
||||
if (workItemsTimer) clearTimeout(workItemsTimer);
|
||||
workItemsTimer = null;
|
||||
workItemsRequestController?.abort();
|
||||
workItemsRequestController = null;
|
||||
workItemsPollGeneration += 1;
|
||||
}
|
||||
|
||||
function restartDocsPolling() {
|
||||
stopDocsPolling();
|
||||
const runNo = String(props.extractionRunNo || '').trim();
|
||||
if (!runNo) {
|
||||
extractionDocs.value = [];
|
||||
return;
|
||||
}
|
||||
void refreshExtractionDocs();
|
||||
docsTimer = setInterval(() => void refreshExtractionDocs(), 2000);
|
||||
}
|
||||
|
||||
watch(() => props.extractionRunNo, () => restartDocsPolling(), { immediate: true });
|
||||
onBeforeUnmount(stopDocsPolling);
|
||||
|
||||
/**
|
||||
* 打开任务处理工作台。
|
||||
* 可见性感知的工作项轮询;前台 2s,后台 8s。
|
||||
*/
|
||||
async function openTaskWorkbench(taskNo: string) {
|
||||
const normalized = String(taskNo || '').trim();
|
||||
if (!normalized) return;
|
||||
await router.push({
|
||||
path: '/workspace/shipping-notice/my-tasks',
|
||||
query: { task_no: normalized },
|
||||
function scheduleWorkItemsPoll(generation: number, delayMs: number) {
|
||||
if (workItemsTimer) clearTimeout(workItemsTimer);
|
||||
workItemsTimer = setTimeout(async () => {
|
||||
if (generation !== workItemsPollGeneration) return;
|
||||
await refreshWorkItems();
|
||||
if (generation !== workItemsPollGeneration) return;
|
||||
if (!normalizedConversationId.value) return;
|
||||
scheduleWorkItemsPoll(generation, resolveWorkItemsPollMs());
|
||||
}, delayMs);
|
||||
}
|
||||
|
||||
function restartWorkItemsPolling() {
|
||||
stopWorkItemsPolling();
|
||||
const conversationId = normalizedConversationId.value;
|
||||
if (!conversationId) {
|
||||
workbench.value = null;
|
||||
extractionRun.value = null;
|
||||
return;
|
||||
}
|
||||
const generation = workItemsPollGeneration;
|
||||
void refreshWorkItems().then(() => {
|
||||
if (generation !== workItemsPollGeneration) return;
|
||||
scheduleWorkItemsPoll(generation, resolveWorkItemsPollMs());
|
||||
});
|
||||
}
|
||||
|
||||
function onVisibilityChange() {
|
||||
if (typeof document === 'undefined' || document.visibilityState !== 'visible') return;
|
||||
if (!normalizedConversationId.value) return;
|
||||
scheduleWorkItemsPoll(workItemsPollGeneration, 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* 打开人工复核(Chat order-review 模式);携带 case_no 精确定位 PDF。
|
||||
* 打开版本历史面板并拉取时间线。
|
||||
*/
|
||||
async function openReview(runNo: string, caseNo = '') {
|
||||
const normalized = String(runNo || '').trim();
|
||||
if (!normalized) return;
|
||||
async function openVersionHistory(item: ShippingSessionWorkItem) {
|
||||
const itemNo = String(item.item_no || '').trim();
|
||||
if (!itemNo) return;
|
||||
if (versionHistoryItemNo.value === itemNo) {
|
||||
versionHistoryItemNo.value = null;
|
||||
versionHistoryItems.value = [];
|
||||
return;
|
||||
}
|
||||
versionHistoryItemNo.value = itemNo;
|
||||
versionHistoryLoading.value = true;
|
||||
try {
|
||||
const response = await listWorkspaceShippingSessionWorkItemVersions(itemNo);
|
||||
versionHistoryItems.value = response.versions || [];
|
||||
} catch {
|
||||
versionHistoryItems.value = [];
|
||||
} finally {
|
||||
versionHistoryLoading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 打开人工复核(Chat order-review 模式);使用行内 case_no / run_no。
|
||||
*/
|
||||
async function openManualReview(item: ShippingSessionWorkItem) {
|
||||
const runNo = String(item.current_run_no || '').trim();
|
||||
if (!runNo) return;
|
||||
const caseNo = String(item.current_case_no || '').trim();
|
||||
const query: Record<string, string> = {
|
||||
...Object.fromEntries(
|
||||
Object.entries(route.query).filter(([, v]) => typeof v === 'string') as Array<[string, string]>,
|
||||
),
|
||||
mode: 'order-review',
|
||||
run_no: normalized,
|
||||
run_no: runNo,
|
||||
};
|
||||
const caseNormalized = String(caseNo || '').trim();
|
||||
if (caseNormalized) query.case_no = caseNormalized;
|
||||
if (caseNo) query.case = caseNo;
|
||||
await router.push({
|
||||
name: 'Chat',
|
||||
params: { agentId: String(route.params.agentId || '') },
|
||||
@@ -332,19 +287,171 @@ async function openReview(runNo: string, caseNo = '') {
|
||||
}
|
||||
|
||||
/**
|
||||
* 按 entry_surface 分发深链;复核必须有 run_no,禁止空 task 跳转。
|
||||
* 按 Run 级处理事项受影响对象跳转。
|
||||
*/
|
||||
async function openEntrySurface(row: SummaryRow) {
|
||||
if (row.entrySurface === 'review_workbench') {
|
||||
const runNo = row.runNo || String(props.extractionRunNo || '');
|
||||
if (!runNo) return;
|
||||
await openReview(runNo, row.caseNo);
|
||||
async function openAffectedRef(target: ShippingHandlingRefTarget, runNo?: string) {
|
||||
if (target.kind === 'task') {
|
||||
await router.push({
|
||||
name: 'workspace-shipping-tasks',
|
||||
params: { taskNo: target.taskNo },
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (row.entrySurface === 'task_workbench' && row.taskNo) {
|
||||
await openTaskWorkbench(row.taskNo);
|
||||
if (target.kind === 'review') {
|
||||
const normalizedRun = String(runNo || props.extractionRunNo || '').trim();
|
||||
if (!normalizedRun) return;
|
||||
await openManualReview({
|
||||
item_no: '',
|
||||
conversation_id: normalizedConversationId.value,
|
||||
owner_user_id: 0,
|
||||
root_document_id: 0,
|
||||
current_document_id: 0,
|
||||
current_run_no: normalizedRun,
|
||||
current_case_no: target.documentId ? '' : '',
|
||||
current_version_no: 1,
|
||||
lifecycle_status: 'pending_review',
|
||||
lock_version: 1,
|
||||
available_actions: [],
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 按处理事项主动作打开复核入口。
|
||||
*/
|
||||
async function openHandlingAction(
|
||||
action?: string | null,
|
||||
refs?: Array<Record<string, unknown>> | null,
|
||||
) {
|
||||
const runNo = String(props.extractionRunNo || '').trim();
|
||||
if (!runNo) return;
|
||||
const rows = listDisplayableHandlingAffectedRefs(refs as ShippingHandlingAffectedRef[] | undefined);
|
||||
const first = rows[0];
|
||||
if (first) {
|
||||
await openAffectedRef(first.target, runNo);
|
||||
return;
|
||||
}
|
||||
const normalized = String(action || '').trim();
|
||||
if (
|
||||
normalized === 'enter_manual_review'
|
||||
|| normalized === 'review_candidate'
|
||||
|| normalized === 'view_details'
|
||||
|| !normalized
|
||||
) {
|
||||
await router.push({
|
||||
name: 'Chat',
|
||||
params: { agentId: String(route.params.agentId || '') },
|
||||
query: {
|
||||
...Object.fromEntries(
|
||||
Object.entries(route.query).filter(([, v]) => typeof v === 'string') as Array<[string, string]>,
|
||||
),
|
||||
mode: 'order-review',
|
||||
run_no: runNo,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 提示并收集操作原因;取消输入时返回 null。
|
||||
*/
|
||||
function promptActionReason(messageKey: string): string | null {
|
||||
const reason = window.prompt(t(messageKey));
|
||||
if (reason == null) return null;
|
||||
const trimmed = reason.trim();
|
||||
if (!trimmed) {
|
||||
msg.warning(t('chat.shippingSessionWorkItem.reasonRequired'));
|
||||
return null;
|
||||
}
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行工作项写操作后刷新列表;失败用业务错误提示。
|
||||
*/
|
||||
async function runWorkItemAction(item: ShippingSessionWorkItem, action: () => Promise<unknown>) {
|
||||
const itemNo = String(item.item_no || '').trim();
|
||||
if (!itemNo || actionBusyItemNo.value) return;
|
||||
actionBusyItemNo.value = itemNo;
|
||||
try {
|
||||
await action();
|
||||
await refreshWorkItems();
|
||||
} catch (error) {
|
||||
const message = error instanceof BusinessError ? error.message : t('errors.generic');
|
||||
msg.error(message);
|
||||
} finally {
|
||||
actionBusyItemNo.value = null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 取消本次处理(关闭工作项)。
|
||||
*/
|
||||
async function cancelWorkItem(item: ShippingSessionWorkItem) {
|
||||
const reason = promptActionReason('chat.shippingSessionWorkItem.cancelReasonPrompt');
|
||||
if (!reason) return;
|
||||
await runWorkItemAction(item, () => closeWorkspaceShippingSessionWorkItem(String(item.item_no), {
|
||||
reason,
|
||||
expected_lock_version: item.lock_version,
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* 标记非订单并关闭当前 Case/工作项。
|
||||
*/
|
||||
async function markNonOrderFromPanel(item: ShippingSessionWorkItem) {
|
||||
const caseNo = String(item.current_case_no || '').trim();
|
||||
if (!caseNo) {
|
||||
msg.warning(t('chat.shippingSessionWorkItem.caseRequired'));
|
||||
return;
|
||||
}
|
||||
const reason = promptActionReason('chat.shippingSessionWorkItem.nonOrderReasonPrompt');
|
||||
if (!reason) return;
|
||||
await runWorkItemAction(item, () => markWorkspaceShippingOrderReviewNonOrder(caseNo, 'non_order', reason));
|
||||
}
|
||||
|
||||
/**
|
||||
* 单文件重新识别。
|
||||
*/
|
||||
async function reparseFromPanel(item: ShippingSessionWorkItem) {
|
||||
const caseNo = String(item.current_case_no || '').trim();
|
||||
if (!caseNo) {
|
||||
msg.warning(t('chat.shippingSessionWorkItem.caseRequired'));
|
||||
return;
|
||||
}
|
||||
const reason = promptActionReason('chat.shippingSessionWorkItem.reparseReasonPrompt');
|
||||
if (!reason) return;
|
||||
await runWorkItemAction(item, () => reparseWorkspaceShippingOrderReviewDocument(caseNo, 'other', reason));
|
||||
}
|
||||
|
||||
/**
|
||||
* 替换文件:进入人工复核页完成上传替代流程。
|
||||
*/
|
||||
async function replaceFileFromPanel(item: ShippingSessionWorkItem) {
|
||||
await openManualReview(item);
|
||||
}
|
||||
|
||||
function itemHasAction(item: ShippingSessionWorkItem, action: string): boolean {
|
||||
return Array.isArray(item.available_actions) && item.available_actions.includes(action);
|
||||
}
|
||||
|
||||
watch(normalizedConversationId, () => restartWorkItemsPolling(), { immediate: true });
|
||||
watch(openOnlyFilter, () => { void refreshWorkItems(); });
|
||||
watch(() => props.refreshTrigger, () => {
|
||||
if (!normalizedConversationId.value) return;
|
||||
scheduleWorkItemsPoll(workItemsPollGeneration, 0);
|
||||
});
|
||||
watch(() => props.extractionRunNo, () => { void refreshWorkItems(); });
|
||||
|
||||
if (typeof document !== 'undefined') {
|
||||
document.addEventListener('visibilitychange', onVisibilityChange);
|
||||
}
|
||||
onBeforeUnmount(() => {
|
||||
if (typeof document !== 'undefined') {
|
||||
document.removeEventListener('visibilitychange', onVisibilityChange);
|
||||
}
|
||||
stopWorkItemsPolling();
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -362,7 +469,7 @@ async function openEntrySurface(row: SummaryRow) {
|
||||
{{ t('chat.shippingSessionSummary.title') }}
|
||||
</div>
|
||||
<div class="mt-0.5 text-xs text-secondary">
|
||||
{{ t('chat.shippingSessionSummary.pdfCount', { count: processSummary.total || taskRows.length }) }}
|
||||
{{ t('chat.shippingSessionSummary.pdfCount', { count: processSummary.total || displayOpenItems.length }) }}
|
||||
</div>
|
||||
</div>
|
||||
<ChevronDown v-if="!collapsed" class="h-4 w-4 shrink-0 text-muted" />
|
||||
@@ -370,6 +477,56 @@ async function openEntrySurface(row: SummaryRow) {
|
||||
</button>
|
||||
|
||||
<div v-if="!collapsed" class="min-h-0 flex-1 overflow-auto p-3">
|
||||
<label class="mb-3 flex cursor-pointer items-center gap-2 text-[11px] text-secondary">
|
||||
<input
|
||||
v-model="openOnlyFilter"
|
||||
type="checkbox"
|
||||
class="rounded border-default"
|
||||
data-testid="shipping-session-open-only-filter"
|
||||
/>
|
||||
{{ t('chat.shippingSessionWorkItem.openOnlyFilter') }}
|
||||
</label>
|
||||
|
||||
<div
|
||||
v-if="handlingItems.length"
|
||||
class="mb-3 space-y-1.5"
|
||||
data-testid="shipping-session-handling-items"
|
||||
>
|
||||
<div class="text-[11px] font-medium text-secondary">
|
||||
{{ t('chat.shippingOrderExtractionHandling.title') }}
|
||||
</div>
|
||||
<div
|
||||
v-for="item in handlingItems"
|
||||
:key="item.category"
|
||||
class="rounded-md border border-default bg-surface-muted/60 px-2 py-1.5 text-xs"
|
||||
>
|
||||
<div class="flex flex-wrap items-center justify-between gap-2">
|
||||
<div class="min-w-0 font-medium text-primary">
|
||||
{{ handlingTitle(item.category) }}
|
||||
<span class="ml-1 text-secondary">
|
||||
{{ t('chat.shippingOrderExtractionHandling.count', { count: item.count }) }}
|
||||
</span>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
class="shrink-0 rounded-md border border-default px-2 py-0.5 text-[11px] font-medium text-primary hover:bg-surface"
|
||||
@click="openHandlingAction(item.primary_action, item.affected_refs)"
|
||||
>
|
||||
{{ te(`chat.shippingOrderExtractionAction.${item.primary_action || 'view_details'}`)
|
||||
? t(`chat.shippingOrderExtractionAction.${item.primary_action || 'view_details'}`)
|
||||
: t('chat.shippingOrderExtractionAction.view_details') }}
|
||||
</button>
|
||||
</div>
|
||||
<div
|
||||
v-if="(item.reason_codes || []).length"
|
||||
class="mt-1 text-[11px] text-secondary"
|
||||
>
|
||||
{{ t('chat.shippingOrderExtractionHandling.reasonPrefix') }}
|
||||
{{ (item.reason_codes || []).slice(0, 4).map(handlingReasonLabel).join(';') }}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mb-3 flex flex-wrap gap-1.5 text-[11px]">
|
||||
<span class="rounded-md bg-emerald-50 px-2 py-0.5 text-emerald-700 dark:bg-emerald-950/40 dark:text-emerald-200">
|
||||
{{ t('chat.shippingSessionSummary.completed', { count: processSummary.completed }) }}
|
||||
@@ -383,12 +540,6 @@ async function openEntrySurface(row: SummaryRow) {
|
||||
>
|
||||
{{ t('chat.shippingSessionSummary.needsHuman', { count: processSummary.needsHuman }) }}
|
||||
</span>
|
||||
<span
|
||||
v-if="processSummary.openExisting > 0"
|
||||
class="rounded-md bg-violet-50 px-2 py-0.5 text-violet-700 dark:bg-violet-950/40 dark:text-violet-200"
|
||||
>
|
||||
{{ t('chat.shippingSessionSummary.openExistingCount', { count: processSummary.openExisting }) }}
|
||||
</span>
|
||||
<span
|
||||
v-if="processSummary.failed > 0"
|
||||
class="rounded-md bg-rose-50 px-2 py-0.5 text-rose-700 dark:bg-rose-950/40 dark:text-rose-200"
|
||||
@@ -397,76 +548,173 @@ async function openEntrySurface(row: SummaryRow) {
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div v-if="!taskRows.length" class="text-xs text-muted">
|
||||
{{ docsLoading ? t('chat.shippingOrderExtractionDocumentsLoading') : t('chat.shippingSessionSummary.empty') }}
|
||||
<div v-if="!displayOpenItems.length && !closedItems.length" class="text-xs text-muted">
|
||||
{{ workItemsLoading
|
||||
? t('chat.shippingSessionWorkItem.loading')
|
||||
: t('chat.shippingSessionSummary.empty') }}
|
||||
</div>
|
||||
|
||||
<ul v-else class="space-y-2">
|
||||
<ul v-if="displayOpenItems.length" class="space-y-2" data-testid="shipping-session-open-items">
|
||||
<li
|
||||
v-for="row in taskRows"
|
||||
:key="row.key"
|
||||
v-for="item in displayOpenItems"
|
||||
:key="item.item_no"
|
||||
class="rounded-lg border border-default bg-surface-soft/80 px-2.5 py-2"
|
||||
:data-testid="`shipping-session-work-item-${item.item_no}`"
|
||||
>
|
||||
<div class="flex items-start justify-between gap-2">
|
||||
<div class="min-w-0">
|
||||
<div class="truncate text-xs font-semibold text-primary">
|
||||
{{ row.fileName || row.taskNo || t('chat.shippingSessionSummary.unnamedPdf') }}
|
||||
{{ item.current_document_filename || t('chat.shippingSessionSummary.unnamedPdf') }}
|
||||
</div>
|
||||
<div class="mt-0.5 text-[11px] text-muted">
|
||||
{{ t('chat.shippingSessionSummary.progressIndex', {
|
||||
current: row.index,
|
||||
total: row.total || processSummary.total || 1,
|
||||
}) }}
|
||||
<!-- 重复态任务号已在原因行「已有任务 SN-xxx」展示,序号行不再重复 -->
|
||||
<span
|
||||
v-if="row.taskNo && row.badge !== 'duplicate'"
|
||||
class="ml-1 font-mono"
|
||||
>{{ row.taskNo }}</span>
|
||||
{{ t('chat.shippingSessionWorkItem.versionLabel', { version: item.current_version_no }) }}
|
||||
</div>
|
||||
</div>
|
||||
<span
|
||||
v-if="row.badge === 'duplicate'"
|
||||
class="shrink-0 rounded-full bg-violet-100 px-1.5 py-0.5 text-[10px] font-medium text-violet-800 dark:bg-violet-900/50 dark:text-violet-100"
|
||||
class="shrink-0 rounded-full px-1.5 py-0.5 text-[10px] font-medium"
|
||||
:class="{
|
||||
'bg-amber-100 text-amber-800 dark:bg-amber-900/50 dark:text-amber-100':
|
||||
item.lifecycle_status === 'pending_review' || item.lifecycle_status === 'reparse_failed',
|
||||
'bg-sky-100 text-sky-800 dark:bg-sky-900/50 dark:text-sky-100':
|
||||
item.lifecycle_status === 'extracting',
|
||||
}"
|
||||
>
|
||||
{{ t('chat.shippingSessionSummary.duplicateBadge') }}
|
||||
</span>
|
||||
<span
|
||||
v-else-if="row.badge === 'exception'"
|
||||
class="shrink-0 rounded-full bg-amber-100 px-1.5 py-0.5 text-[10px] font-medium text-amber-800 dark:bg-amber-900/50 dark:text-amber-100"
|
||||
>
|
||||
{{ t('chat.shippingSessionSummary.exception') }}
|
||||
{{ lifecycleStatusLabel(String(item.lifecycle_status || '')) }}
|
||||
</span>
|
||||
</div>
|
||||
<div v-if="row.stage" class="mt-1 text-[11px] text-secondary">
|
||||
{{ row.stage }}
|
||||
<div v-if="item.version_replaced" class="mt-1 text-[11px] text-secondary">
|
||||
{{ t('chat.shippingSessionWorkItem.versionReplaced') }}
|
||||
</div>
|
||||
<div v-if="row.message" class="mt-0.5 line-clamp-3 text-[11px] text-muted">
|
||||
{{ row.message }}
|
||||
<div v-if="item.updated_at" class="mt-0.5 text-[11px] text-muted">
|
||||
{{ formatUpdatedLabel(item.updated_at) }}
|
||||
</div>
|
||||
<div class="mt-2 flex flex-wrap gap-2">
|
||||
<button
|
||||
v-if="row.entrySurface === 'review_workbench'"
|
||||
v-if="itemHasAction(item, 'enter_manual_review') && item.current_run_no"
|
||||
type="button"
|
||||
class="inline-flex items-center gap-1 text-[11px] font-medium text-brand-700 hover:underline"
|
||||
@click="openEntrySurface(row)"
|
||||
:disabled="actionBusyItemNo === item.item_no"
|
||||
data-testid="shipping-session-action-review"
|
||||
@click="openManualReview(item)"
|
||||
>
|
||||
<ExternalLink class="h-3 w-3" />
|
||||
{{ t('chat.shippingSessionSummary.openReview') }}
|
||||
{{ t('chat.shippingSessionWorkItem.enterManualReview') }}
|
||||
</button>
|
||||
<button
|
||||
v-else-if="row.entrySurface === 'task_workbench' && row.taskNo"
|
||||
v-if="itemHasAction(item, 'request_reparse') && item.current_case_no"
|
||||
type="button"
|
||||
class="inline-flex items-center gap-1 text-[11px] font-medium text-brand-700 hover:underline disabled:opacity-50"
|
||||
:disabled="actionBusyItemNo === item.item_no"
|
||||
data-testid="shipping-session-action-reparse"
|
||||
@click="reparseFromPanel(item)"
|
||||
>
|
||||
{{ t('chat.shippingSessionWorkItem.requestReparse') }}
|
||||
</button>
|
||||
<button
|
||||
v-if="itemHasAction(item, 'mark_non_order') && item.current_case_no"
|
||||
type="button"
|
||||
class="inline-flex items-center gap-1 text-[11px] font-medium text-brand-700 hover:underline disabled:opacity-50"
|
||||
:disabled="actionBusyItemNo === item.item_no"
|
||||
data-testid="shipping-session-action-non-order"
|
||||
@click="markNonOrderFromPanel(item)"
|
||||
>
|
||||
{{ t('chat.shippingSessionWorkItem.markNonOrder') }}
|
||||
</button>
|
||||
<button
|
||||
v-if="itemHasAction(item, 'replace_file') && item.current_run_no"
|
||||
type="button"
|
||||
class="inline-flex items-center gap-1 text-[11px] font-medium text-brand-700 hover:underline disabled:opacity-50"
|
||||
:disabled="actionBusyItemNo === item.item_no"
|
||||
data-testid="shipping-session-action-replace"
|
||||
@click="replaceFileFromPanel(item)"
|
||||
>
|
||||
{{ t('chat.shippingSessionWorkItem.replaceFile') }}
|
||||
</button>
|
||||
<button
|
||||
v-if="itemHasAction(item, 'cancel')"
|
||||
type="button"
|
||||
class="inline-flex items-center gap-1 text-[11px] font-medium text-rose-700 hover:underline disabled:opacity-50"
|
||||
:disabled="actionBusyItemNo === item.item_no"
|
||||
data-testid="shipping-session-action-cancel"
|
||||
@click="cancelWorkItem(item)"
|
||||
>
|
||||
{{ t('chat.shippingSessionWorkItem.cancelProcessing') }}
|
||||
</button>
|
||||
<button
|
||||
v-if="itemHasAction(item, 'view_version_history')"
|
||||
type="button"
|
||||
class="inline-flex items-center gap-1 text-[11px] font-medium text-brand-700 hover:underline"
|
||||
@click="openTaskWorkbench(row.taskNo)"
|
||||
data-testid="shipping-session-action-versions"
|
||||
@click="openVersionHistory(item)"
|
||||
>
|
||||
<ExternalLink class="h-3 w-3" />
|
||||
{{ row.kind === 'document'
|
||||
? t('chat.shippingSessionSummary.openExistingTask')
|
||||
: t('chat.shippingSessionSummary.openTask') }}
|
||||
{{ t('chat.shippingSessionWorkItem.viewVersionHistory') }}
|
||||
</button>
|
||||
</div>
|
||||
<div
|
||||
v-if="versionHistoryItemNo === item.item_no"
|
||||
class="mt-2 rounded-md border border-default bg-surface-muted/40 p-2"
|
||||
data-testid="shipping-session-version-history"
|
||||
>
|
||||
<div class="text-[11px] font-medium text-secondary">
|
||||
{{ t('chat.shippingSessionWorkItem.versionHistoryTitle') }}
|
||||
</div>
|
||||
<div v-if="versionHistoryLoading" class="mt-1 text-[11px] text-muted">
|
||||
{{ t('chat.shippingSessionWorkItem.loading') }}
|
||||
</div>
|
||||
<ul v-else-if="versionHistoryItems.length" class="mt-1 space-y-1">
|
||||
<li
|
||||
v-for="version in versionHistoryItems"
|
||||
:key="version.case_no"
|
||||
class="text-[11px] text-primary"
|
||||
>
|
||||
{{ version.version_label || version.case_no }}
|
||||
<span v-if="version.is_current" class="ml-1 text-brand-700">
|
||||
({{ t('chat.shippingSessionWorkItem.currentVersion') }})
|
||||
</span>
|
||||
<span v-else-if="version.is_readonly" class="ml-1 text-muted">
|
||||
({{ t('chat.shippingSessionWorkItem.readonlyVersion') }})
|
||||
</span>
|
||||
</li>
|
||||
</ul>
|
||||
<div v-else class="mt-1 text-[11px] text-muted">
|
||||
{{ t('chat.shippingSessionWorkItem.noVersions') }}
|
||||
</div>
|
||||
</div>
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
<div
|
||||
v-if="closedItems.length"
|
||||
class="mt-3"
|
||||
data-testid="shipping-session-closed-section"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
class="flex w-full items-center justify-between gap-2 rounded-md border border-default bg-surface-muted/50 px-2 py-1.5 text-left text-[11px] font-medium text-secondary hover:bg-surface"
|
||||
@click="closedExpanded = !closedExpanded"
|
||||
>
|
||||
<span>{{ t('chat.shippingSessionWorkItem.completedCollapsed', { count: closedItems.length }) }}</span>
|
||||
<ChevronDown v-if="closedExpanded" class="h-3.5 w-3.5 shrink-0" />
|
||||
<ChevronRight v-else class="h-3.5 w-3.5 shrink-0" />
|
||||
</button>
|
||||
<ul v-if="closedExpanded" class="mt-2 space-y-2">
|
||||
<li
|
||||
v-for="item in closedItems"
|
||||
:key="`closed:${item.item_no}`"
|
||||
class="rounded-lg border border-default bg-surface-soft/60 px-2.5 py-2 opacity-80"
|
||||
>
|
||||
<div class="truncate text-xs font-semibold text-primary">
|
||||
{{ item.current_document_filename || t('chat.shippingSessionSummary.unnamedPdf') }}
|
||||
</div>
|
||||
<div class="mt-0.5 text-[11px] text-muted">
|
||||
{{ t('chat.shippingSessionWorkItem.versionLabel', { version: item.current_version_no }) }}
|
||||
<span v-if="item.closed_reason" class="ml-1">
|
||||
· {{ closedReasonLabel(item.closed_reason) }}
|
||||
</span>
|
||||
</div>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</aside>
|
||||
</template>
|
||||
@@ -126,6 +126,8 @@ const showActions = computed(() => (
|
||||
));
|
||||
const shippingOrderExtractionState = computed(() => message.shipping_order_extraction_state);
|
||||
const retryingOrderExtraction = ref(false);
|
||||
const refreshingOrderExtraction = ref(false);
|
||||
const cancellingOrderExtraction = ref(false);
|
||||
const shippingOrderExtractionRunNo = computed(() => {
|
||||
const payload = message.payload && typeof message.payload === 'object'
|
||||
? message.payload as Record<string, unknown>
|
||||
@@ -142,6 +144,26 @@ const retryShippingOrderExtraction = async () => {
|
||||
retryingOrderExtraction.value = false;
|
||||
}
|
||||
};
|
||||
/** 只读刷新 Run 投影,不改变后台业务状态。 */
|
||||
const refreshShippingOrderExtraction = async () => {
|
||||
if (!shippingOrderExtractionRunNo.value || refreshingOrderExtraction.value) return;
|
||||
refreshingOrderExtraction.value = true;
|
||||
try {
|
||||
await shippingHandlers.refreshOrderExtractionRun(shippingOrderExtractionRunNo.value);
|
||||
} finally {
|
||||
refreshingOrderExtraction.value = false;
|
||||
}
|
||||
};
|
||||
/** 请求取消整批;确认后走请求语义,不伪造即时终态。 */
|
||||
const cancelShippingOrderExtraction = async (reason?: string) => {
|
||||
if (!shippingOrderExtractionRunNo.value || cancellingOrderExtraction.value) return;
|
||||
cancellingOrderExtraction.value = true;
|
||||
try {
|
||||
await shippingHandlers.cancelOrderExtractionRun(shippingOrderExtractionRunNo.value, reason || null);
|
||||
} finally {
|
||||
cancellingOrderExtraction.value = false;
|
||||
}
|
||||
};
|
||||
const isLastMessage = computed(() => index === messageCount - 1 || (message.role === 'assistant' && isLatestAssistantMessage));
|
||||
const isCopied = computed(() => copiedIndex === index);
|
||||
const renderedMarkdown = computed(() => (
|
||||
@@ -668,7 +690,12 @@ function handleInlineDownload(file: InlineDownloadFile): void {
|
||||
v-if="shippingOrderExtractionState"
|
||||
:state="shippingOrderExtractionState"
|
||||
:run-no="shippingOrderExtractionRunNo"
|
||||
:retrying="retryingOrderExtraction"
|
||||
:refreshing="refreshingOrderExtraction"
|
||||
:cancelling="cancellingOrderExtraction"
|
||||
@retry="retryShippingOrderExtraction"
|
||||
@refresh="refreshShippingOrderExtraction"
|
||||
@cancel="cancelShippingOrderExtraction"
|
||||
/>
|
||||
<LeaveMessageBlock
|
||||
v-if="isLeaveMessage"
|
||||
|
||||
@@ -16,6 +16,9 @@ export interface ShippingMessageHandlers {
|
||||
addLine: (msg: ChatMessage, line: Partial<ShippingNoticeLine>) => Promise<boolean>;
|
||||
removeLine: (msg: ChatMessage, lineIndex: number) => Promise<boolean>;
|
||||
retryOrderExtractionRun: (runNo: string) => Promise<boolean>;
|
||||
refreshOrderExtractionRun: (runNo: string) => Promise<boolean>;
|
||||
cancelOrderExtractionRun: (runNo: string, reason?: string | null) => Promise<boolean>;
|
||||
cancelOrderExtractionUnit: (runNo: string, documentId: number, reason?: string | null) => Promise<boolean>;
|
||||
reparseOrderExtractionRun: (runNo: string, reason: 'rule_updated' | 'field_mapping_error' | 'document_quality' | 'other') => Promise<boolean>;
|
||||
resolveCandidateDuplicate: (candidateNo: string, action: import('../../types/shipping.types').ShippingDuplicateAction, targetTaskNo: string | undefined, reason: string | undefined, done: (success: boolean) => void) => Promise<void>;
|
||||
promoteCandidate: (candidateNo: string, done: (success: boolean) => void) => Promise<void>;
|
||||
|
||||
@@ -0,0 +1,219 @@
|
||||
<!--
|
||||
features/chat/components/shipping-review/ReviewActionConfirmDialog.vue
|
||||
用途:复核页破坏性/不可逆操作的二次确认弹窗(确认建单、重识别、非订单、质量异常、替代 PDF)。
|
||||
依赖:vue-i18n、dialog-overlay / dialog-panel 设计系统样式。
|
||||
逻辑:ShippingOrderReviewView 以 v-model 控制显隐;质量异常须选原因码,other 时备注必填;
|
||||
非订单/重识别将说明写入 comment,并附带稳定 reasonCode。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, onBeforeUnmount, ref, watch } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
|
||||
export type ReviewConfirmAction = 'confirm' | 'reparse' | 'non_order' | 'replace' | 'quality_issue';
|
||||
|
||||
/** 确认弹窗提交载荷:稳定原因码 + 自由说明,供后端审计复盘。 */
|
||||
export type ReviewConfirmPayload = {
|
||||
reasonCode: string;
|
||||
comment: string;
|
||||
};
|
||||
|
||||
const QUALITY_REASON_CODES = [
|
||||
'blurred',
|
||||
'incomplete_pages',
|
||||
'password_protected',
|
||||
'corrupted',
|
||||
'wrong_orientation',
|
||||
'unsupported_layout',
|
||||
'missing_order_table',
|
||||
'other',
|
||||
] as const;
|
||||
|
||||
interface Props {
|
||||
modelValue: boolean;
|
||||
action: ReviewConfirmAction;
|
||||
confirmLoading?: boolean;
|
||||
}
|
||||
|
||||
const props = withDefaults(defineProps<Props>(), {
|
||||
confirmLoading: false,
|
||||
});
|
||||
|
||||
const emit = defineEmits<{
|
||||
(e: 'update:modelValue', value: boolean): void;
|
||||
(e: 'confirm', payload: ReviewConfirmPayload): void;
|
||||
(e: 'cancel'): void;
|
||||
}>();
|
||||
|
||||
const { t } = useI18n();
|
||||
const reasonCode = ref('other');
|
||||
const comment = ref('');
|
||||
const reasonMissing = ref(false);
|
||||
const commentMissing = ref(false);
|
||||
|
||||
/** 非订单 / 重识别 / 质量异常需要说明或原因选择。 */
|
||||
const needsDispositionInput = computed(
|
||||
() => props.action === 'non_order' || props.action === 'reparse' || props.action === 'quality_issue',
|
||||
);
|
||||
|
||||
const title = computed(() => t(`chat.shippingOrderReview.confirmDialog.${props.action}.title`));
|
||||
const impact = computed(() => t(`chat.shippingOrderReview.confirmDialog.${props.action}.impact`));
|
||||
const confirmText = computed(() => t(`chat.shippingOrderReview.confirmDialog.${props.action}.confirm`));
|
||||
const confirmTone = computed(() => (props.action === 'confirm' ? 'primary' : 'danger'));
|
||||
const confirmButtonClass = computed(() =>
|
||||
confirmTone.value === 'primary' ? 'btn-primary btn-sm' : 'btn-danger btn-sm',
|
||||
);
|
||||
|
||||
/**
|
||||
* 质量异常原因码的展示文案。
|
||||
* @param code - 后端允许的 quality reason 码
|
||||
*/
|
||||
const qualityReasonLabel = (code: string) =>
|
||||
t(`chat.shippingOrderReview.confirmDialog.qualityReasons.${code}`);
|
||||
|
||||
/** 关闭弹窗并同步 v-model。 */
|
||||
const closeDialog = () => {
|
||||
emit('update:modelValue', false);
|
||||
};
|
||||
|
||||
const handleCancel = () => {
|
||||
emit('cancel');
|
||||
closeDialog();
|
||||
};
|
||||
|
||||
/**
|
||||
* 按 action 组装原因码与备注后触发确认。
|
||||
* 核心逻辑:质量异常 `other` 强制备注;非订单/重识别使用稳定 reasonCode + 自由 comment。
|
||||
*/
|
||||
const handleConfirm = () => {
|
||||
reasonMissing.value = false;
|
||||
commentMissing.value = false;
|
||||
const trimmedComment = comment.value.trim();
|
||||
|
||||
if (props.action === 'quality_issue') {
|
||||
if (!reasonCode.value) {
|
||||
reasonMissing.value = true;
|
||||
return;
|
||||
}
|
||||
if (reasonCode.value === 'other' && !trimmedComment) {
|
||||
commentMissing.value = true;
|
||||
return;
|
||||
}
|
||||
emit('confirm', { reasonCode: reasonCode.value, comment: trimmedComment });
|
||||
closeDialog();
|
||||
return;
|
||||
}
|
||||
|
||||
if (props.action === 'non_order' || props.action === 'reparse') {
|
||||
if (!trimmedComment) {
|
||||
commentMissing.value = true;
|
||||
return;
|
||||
}
|
||||
const code = props.action === 'non_order' ? 'non_order' : 'document_quality';
|
||||
emit('confirm', { reasonCode: code, comment: trimmedComment });
|
||||
closeDialog();
|
||||
return;
|
||||
}
|
||||
|
||||
emit('confirm', { reasonCode: '', comment: '' });
|
||||
closeDialog();
|
||||
};
|
||||
|
||||
watch(
|
||||
() => props.modelValue,
|
||||
(open) => {
|
||||
if (!open) {
|
||||
reasonCode.value = 'other';
|
||||
comment.value = '';
|
||||
reasonMissing.value = false;
|
||||
commentMissing.value = false;
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
const onKeydown = (event: KeyboardEvent) => {
|
||||
if (event.key === 'Escape' && props.modelValue) handleCancel();
|
||||
};
|
||||
|
||||
watch(
|
||||
() => props.modelValue,
|
||||
(open) => {
|
||||
if (typeof document === 'undefined') return;
|
||||
if (open) document.addEventListener('keydown', onKeydown);
|
||||
else document.removeEventListener('keydown', onKeydown);
|
||||
},
|
||||
);
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
if (typeof document !== 'undefined') document.removeEventListener('keydown', onKeydown);
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Teleport to="body">
|
||||
<div
|
||||
v-if="modelValue"
|
||||
class="dialog-overlay z-50 flex items-center justify-center p-4"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
:aria-label="title"
|
||||
data-testid="review-action-confirm-dialog"
|
||||
@click.self="handleCancel"
|
||||
>
|
||||
<div class="dialog-panel w-full max-w-md space-y-4 p-5">
|
||||
<header>
|
||||
<h2 class="text-base font-semibold text-primary">{{ title }}</h2>
|
||||
<p class="mt-2 text-sm text-secondary">{{ impact }}</p>
|
||||
</header>
|
||||
|
||||
<template v-if="needsDispositionInput">
|
||||
<label v-if="action === 'quality_issue'" class="block space-y-1 text-sm">
|
||||
<span class="text-secondary">{{ t('chat.shippingOrderReview.confirmDialog.reasonCodeLabel') }}</span>
|
||||
<select
|
||||
v-model="reasonCode"
|
||||
class="select-field w-full text-sm"
|
||||
data-testid="review-action-reason-code"
|
||||
@change="reasonMissing = false"
|
||||
>
|
||||
<option v-for="code in QUALITY_REASON_CODES" :key="code" :value="code">
|
||||
{{ qualityReasonLabel(code) }}
|
||||
</option>
|
||||
</select>
|
||||
<p v-if="reasonMissing" class="text-xs text-rose-600 dark:text-rose-400">
|
||||
{{ t('chat.shippingOrderReview.confirmDialog.reasonCodeRequired') }}
|
||||
</p>
|
||||
</label>
|
||||
|
||||
<label class="block space-y-1 text-sm">
|
||||
<span class="text-secondary">{{ t('chat.shippingOrderReview.confirmDialog.reasonLabel') }}</span>
|
||||
<textarea
|
||||
v-model="comment"
|
||||
rows="3"
|
||||
class="input-field w-full resize-y text-sm"
|
||||
:placeholder="t('chat.shippingOrderReview.confirmDialog.reasonPlaceholder')"
|
||||
data-testid="review-action-reason"
|
||||
@input="commentMissing = false"
|
||||
/>
|
||||
<p v-if="commentMissing" class="text-xs text-rose-600 dark:text-rose-400">
|
||||
{{ t('chat.shippingOrderReview.confirmDialog.reasonRequired') }}
|
||||
</p>
|
||||
</label>
|
||||
</template>
|
||||
|
||||
<footer class="flex justify-end gap-2 pt-1">
|
||||
<button type="button" class="btn-secondary btn-sm" :disabled="confirmLoading" @click="handleCancel">
|
||||
{{ t('common.deleteDialog.cancel') }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
:class="confirmButtonClass"
|
||||
:disabled="confirmLoading"
|
||||
data-testid="review-action-confirm-submit"
|
||||
@click="handleConfirm"
|
||||
>
|
||||
{{ confirmLoading ? t('chat.shippingOrderReview.saving') : confirmText }}
|
||||
</button>
|
||||
</footer>
|
||||
</div>
|
||||
</div>
|
||||
</Teleport>
|
||||
</template>
|
||||
@@ -4,7 +4,7 @@
|
||||
逻辑:预览失败独立显示,不影响同页草稿编辑;缺少可靠 bbox 时只保留页码定位。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { nextTick, ref, watch } from 'vue';
|
||||
import { computed, nextTick, ref, watch } from 'vue';
|
||||
import * as pdfjs from 'pdfjs-dist';
|
||||
import workerUrl from 'pdfjs-dist/build/pdf.worker.min.mjs?url';
|
||||
import type { ShippingOrderReviewEvidence } from '../../types/shipping.api.types';
|
||||
@@ -21,6 +21,8 @@ const props = defineProps<{
|
||||
const canvas = ref<HTMLCanvasElement | null>(null);
|
||||
const loading = ref(false);
|
||||
const failed = ref(false);
|
||||
const scale = ref(1.5);
|
||||
const zoomLabel = computed(() => `${Math.round(scale.value * 100)}%`);
|
||||
|
||||
/** 将当前页渲染到 canvas;高亮以 PDF viewport 为基准,绝不猜测不可靠坐标。 */
|
||||
const render = async () => {
|
||||
@@ -31,7 +33,7 @@ const render = async () => {
|
||||
const document = await pdfjs.getDocument(props.src).promise;
|
||||
const pageNo = Math.min(Math.max(props.evidence?.page_no || 1, 1), document.numPages);
|
||||
const page = await document.getPage(pageNo);
|
||||
const viewport = page.getViewport({ scale: 1.4 });
|
||||
const viewport = page.getViewport({ scale: scale.value });
|
||||
await nextTick();
|
||||
if (!canvas.value) return;
|
||||
canvas.value.width = Math.ceil(viewport.width);
|
||||
@@ -60,14 +62,25 @@ const render = async () => {
|
||||
}
|
||||
};
|
||||
|
||||
watch(() => [props.src, props.evidence?.evidence_id], () => { void render(); }, { immediate: true });
|
||||
const zoomIn = () => { scale.value = Math.min(scale.value + 0.25, 3); };
|
||||
const zoomOut = () => { scale.value = Math.max(scale.value - 0.25, 0.75); };
|
||||
const fitWidth = () => { scale.value = 1.75; };
|
||||
|
||||
watch(() => [props.src, props.evidence?.evidence_id, scale.value], () => { void render(); }, { immediate: true });
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="relative flex min-h-[360px] items-center justify-center overflow-auto bg-slate-100 p-3 dark:bg-slate-950">
|
||||
<div class="relative flex min-h-[180px] flex-1 flex-col overflow-hidden bg-slate-100 xl:min-h-[360px] dark:bg-slate-950">
|
||||
<div class="flex shrink-0 items-center justify-end gap-1 border-b border-slate-200 bg-white/95 px-2 py-1.5 text-xs dark:border-slate-800 dark:bg-slate-900/95">
|
||||
<button type="button" class="rounded border px-2 py-1 hover:bg-slate-50 dark:border-slate-700 dark:hover:bg-slate-800" @click="zoomOut">−</button>
|
||||
<button type="button" class="min-w-12 rounded border px-2 py-1 hover:bg-slate-50 dark:border-slate-700 dark:hover:bg-slate-800" @click="fitWidth">{{ zoomLabel }}</button>
|
||||
<button type="button" class="rounded border px-2 py-1 hover:bg-slate-50 dark:border-slate-700 dark:hover:bg-slate-800" @click="zoomIn">+</button>
|
||||
</div>
|
||||
<div class="relative flex min-h-0 flex-1 items-start justify-center overflow-auto p-4">
|
||||
<!-- Keep the canvas mounted while PDF.js is loading; otherwise nextTick cannot obtain a render target. -->
|
||||
<canvas ref="canvas" :aria-label="title" class="max-w-full bg-white shadow" :class="{ invisible: loading || failed }" />
|
||||
<canvas ref="canvas" :aria-label="title" class="bg-white shadow" :class="{ invisible: loading || failed }" />
|
||||
<span v-if="loading" class="absolute text-sm text-slate-500">{{ loadingText }}</span>
|
||||
<span v-else-if="failed" class="absolute text-sm text-rose-600">{{ unavailableText }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,135 @@
|
||||
<!--
|
||||
features/chat/components/shipping-review/ReviewVersionHistoryPanel.vue
|
||||
用途:复核页工作项版本历史时间线;支持只读跳转至历史 Case。
|
||||
依赖:vue-i18n、ShippingSessionWorkItemVersion 类型。
|
||||
逻辑:ShippingOrderReviewView 传入 versions;emit select 供父级切换 case_no。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import type { ShippingSessionWorkItemVersion } from '@/features/chat/types/shipping.api.types';
|
||||
|
||||
const props = defineProps<{
|
||||
itemNo?: string | null;
|
||||
versions: ShippingSessionWorkItemVersion[];
|
||||
loading?: boolean;
|
||||
activeCaseNo?: string | null;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
(e: 'select', caseNo: string, readonly: boolean): void;
|
||||
}>();
|
||||
|
||||
const { t, te } = useI18n();
|
||||
|
||||
/**
|
||||
* 解析 Case 状态为结果文案。
|
||||
*/
|
||||
function resultLabel(status?: string | null): string {
|
||||
const normalized = String(status || '').trim();
|
||||
if (!normalized) return '—';
|
||||
const key = `chat.shippingOrderReview.caseStatuses.${normalized}`;
|
||||
return te(key) ? t(key) : normalized;
|
||||
}
|
||||
|
||||
/**
|
||||
* 格式化时间戳为本地化短日期时间。
|
||||
*/
|
||||
function formatTime(value?: string | null): string {
|
||||
const date = new Date(String(value || ''));
|
||||
if (Number.isNaN(date.getTime())) return '—';
|
||||
return date.toLocaleString();
|
||||
}
|
||||
|
||||
/**
|
||||
* 跳转至指定版本;历史版本以只读模式打开。
|
||||
*/
|
||||
function selectVersion(version: ShippingSessionWorkItemVersion) {
|
||||
const caseNo = String(version.case_no || '').trim();
|
||||
if (!caseNo) return;
|
||||
emit('select', caseNo, Boolean(version.is_readonly));
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section
|
||||
class="rounded-xl border border-slate-200 bg-white p-4 shadow-sm dark:border-slate-800 dark:bg-slate-900"
|
||||
data-testid="review-version-history-panel"
|
||||
:aria-label="t('chat.shippingOrderReview.versionHistory.title')"
|
||||
>
|
||||
<header class="mb-3 flex items-center justify-between gap-2">
|
||||
<div>
|
||||
<h2 class="text-sm font-semibold">{{ t('chat.shippingOrderReview.versionHistory.title') }}</h2>
|
||||
<p v-if="itemNo" class="mt-0.5 text-xs text-slate-500 dark:text-slate-400">
|
||||
{{ t('chat.shippingOrderReview.versionHistory.itemNo', { itemNo }) }}
|
||||
</p>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div v-if="loading" class="py-4 text-sm text-slate-500">{{ t('chat.shippingSessionWorkItem.loading') }}</div>
|
||||
<p v-else-if="!versions.length" class="py-4 text-sm text-slate-500">
|
||||
{{ t('chat.shippingSessionWorkItem.noVersions') }}
|
||||
</p>
|
||||
|
||||
<ol v-else class="space-y-2">
|
||||
<li
|
||||
v-for="version in versions"
|
||||
:key="version.case_no"
|
||||
class="rounded-lg border p-3 text-sm"
|
||||
:class="activeCaseNo === version.case_no
|
||||
? 'border-sky-500 bg-sky-50 dark:border-sky-700 dark:bg-sky-950/30'
|
||||
: 'border-slate-200 dark:border-slate-700'"
|
||||
:data-testid="`review-version-row-${version.case_no}`"
|
||||
>
|
||||
<div class="flex flex-wrap items-start justify-between gap-2">
|
||||
<div class="min-w-0">
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<span class="font-medium">
|
||||
{{ version.version_label || t('chat.shippingSessionWorkItem.versionLabel', { version: '?' }) }}
|
||||
</span>
|
||||
<span
|
||||
v-if="version.is_current"
|
||||
class="rounded-full bg-emerald-100 px-2 py-0.5 text-[11px] text-emerald-800 dark:bg-emerald-950 dark:text-emerald-100"
|
||||
>
|
||||
{{ t('chat.shippingSessionWorkItem.currentVersion') }}
|
||||
</span>
|
||||
<span
|
||||
v-else-if="version.is_readonly"
|
||||
class="rounded-full bg-slate-100 px-2 py-0.5 text-[11px] text-slate-600 dark:bg-slate-800 dark:text-slate-300"
|
||||
>
|
||||
{{ t('chat.shippingSessionWorkItem.readonlyVersion') }}
|
||||
</span>
|
||||
</div>
|
||||
<p class="mt-1 truncate text-xs text-slate-500 dark:text-slate-400">
|
||||
{{ version.document_filename || version.case_no }}
|
||||
</p>
|
||||
</div>
|
||||
<button
|
||||
v-if="activeCaseNo !== version.case_no"
|
||||
type="button"
|
||||
class="shrink-0 rounded border border-slate-200 px-2 py-1 text-xs hover:bg-slate-50 dark:border-slate-700 dark:hover:bg-slate-800"
|
||||
@click="selectVersion(version)"
|
||||
>
|
||||
{{ version.is_readonly
|
||||
? t('chat.shippingOrderReview.versionHistory.viewReadonly')
|
||||
: t('chat.shippingOrderReview.versionHistory.open') }}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<dl class="mt-2 grid gap-1 text-xs text-slate-600 dark:text-slate-400 sm:grid-cols-2">
|
||||
<div>
|
||||
<dt class="inline">{{ t('chat.shippingOrderReview.versionHistory.result') }}:</dt>
|
||||
<dd class="inline">{{ resultLabel(version.case_status) }}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt class="inline">{{ t('chat.shippingOrderReview.versionHistory.createdAt') }}:</dt>
|
||||
<dd class="inline">{{ formatTime(version.created_at) }}</dd>
|
||||
</div>
|
||||
<div v-if="version.confirmed_at">
|
||||
<dt class="inline">{{ t('chat.shippingOrderReview.versionHistory.confirmedAt') }}:</dt>
|
||||
<dd class="inline">{{ formatTime(version.confirmed_at) }}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
</li>
|
||||
</ol>
|
||||
</section>
|
||||
</template>
|
||||
@@ -3,7 +3,7 @@
|
||||
* features/chat/components/shipping/ShippingOrderDocumentResultItem.vue
|
||||
* 用途:渲染单个 PDF 的订单抽取结果摘要,供详情抽屉按文档逐项展示。
|
||||
* 依赖:订单抽取文档 DTO、vue-i18n。
|
||||
* 逻辑:只显示用户可理解的业务字段;人工复核由上层统一跳转独立工作台。
|
||||
* 逻辑:只显示用户可理解的业务字段;reason_code 优先 i18n,缺失时对 SHIPPING_NOTICE.* 回退通用提示;人工复核由上层统一跳转。
|
||||
*/
|
||||
import { computed } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
@@ -52,11 +52,16 @@ const activityTimeLabel = computed(() => {
|
||||
if (props.document.started_at) return t('chat.shippingOrderExtractionDocumentTiming.started', { time: formatTime(props.document.started_at) });
|
||||
return '';
|
||||
});
|
||||
const reasonLabel = computed(() => (
|
||||
props.document.reason_code
|
||||
? t(`chat.shippingOrderExtractionReason.${props.document.reason_code}`)
|
||||
: ''
|
||||
));
|
||||
const reasonLabel = computed(() => {
|
||||
const code = String(props.document.reason_code || '').trim();
|
||||
if (!code) return '';
|
||||
const key = `chat.shippingOrderExtractionReason.${code}`;
|
||||
if (te(key)) return t(key);
|
||||
if (code.startsWith('SHIPPING_NOTICE.')) {
|
||||
return t('chat.shippingOrderExtractionTechnicalFailureUserHint');
|
||||
}
|
||||
return code;
|
||||
});
|
||||
const emailSupplementLabel = computed(() => {
|
||||
const status = props.document.email_supplement?.status || 'none';
|
||||
const key = `chat.shippingOrderExtractionEmailSupplement.${status}`;
|
||||
|
||||
+139
-14
@@ -1,8 +1,8 @@
|
||||
/**
|
||||
* features/chat/components/shipping/ShippingOrderExtractionCard.spec.ts
|
||||
* 用途:覆盖聊天主区一句过程通知卡(无逐 PDF 列表、无复核按钮、无重复统计)。
|
||||
* 用途:覆盖批次进度卡摘要、阶段、健康提醒与刷新/取消/重试动作。
|
||||
* 依赖:Vitest、Vue Test Utils、vue-i18n、本域组件与 DTO 类型。
|
||||
* 逻辑:断言 processNotice 文案与技术失败重试;复核深链由右侧摘要面板承担。
|
||||
* 逻辑:断言过程通知、摘要计数、取消确认与重试;逐 PDF 深链仍由右侧面板承担。
|
||||
*/
|
||||
import { mount } from '@vue/test-utils';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
@@ -29,15 +29,19 @@ const buildState = (patch: Partial<ShippingOrderExtractionState> = {}): Shipping
|
||||
processingDocuments: 1,
|
||||
completedDocuments: 1,
|
||||
reviewRequiredDocuments: 1,
|
||||
failedDocuments: 1,
|
||||
failedDocuments: 0,
|
||||
cancelledDocuments: 0,
|
||||
candidateCount: 2,
|
||||
},
|
||||
currentActivity: {
|
||||
unitId: 12,
|
||||
fileName: 'PO-450003.pdf',
|
||||
eventCode: 'profile_matching',
|
||||
eventCode: 'extracting',
|
||||
userVisibleStage: 'extracting',
|
||||
elapsedSeconds: 75,
|
||||
},
|
||||
availableActions: [],
|
||||
availableActions: ['refresh_status', 'cancel_run'],
|
||||
healthTips: [{ code: 'processing_slow', thresholdSeconds: 60, idleOrElapsedSeconds: 90 }],
|
||||
terminal: false,
|
||||
refreshFailed: false,
|
||||
errorCode: null,
|
||||
@@ -47,15 +51,16 @@ const buildState = (patch: Partial<ShippingOrderExtractionState> = {}): Shipping
|
||||
});
|
||||
|
||||
describe('ShippingOrderExtractionCard', () => {
|
||||
it('renders one-line process notice without per-PDF list, review CTA, or count stats', () => {
|
||||
it('renders batch summary, current stage, health tip and action buttons', () => {
|
||||
const wrapper = mount(ShippingOrderExtractionCard, {
|
||||
props: { state: buildState(), runNo: 'SNER-1' },
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
expect(wrapper.text()).toContain('正在处理附件');
|
||||
expect(wrapper.text()).toContain('右侧');
|
||||
expect(wrapper.text()).not.toContain('自动推进');
|
||||
expect(wrapper.text()).not.toContain('进入人工复核');
|
||||
expect(wrapper.text()).toContain('PO-450003.pdf');
|
||||
expect(wrapper.text()).toContain('提取订单字段中');
|
||||
expect(wrapper.text()).toContain('处理时间偏长');
|
||||
expect(wrapper.text()).toContain('刷新状态');
|
||||
expect(wrapper.text()).toContain('取消本次识别');
|
||||
expect(wrapper.findAll('[data-testid="shipping-order-document-result"]').length).toBe(0);
|
||||
});
|
||||
|
||||
@@ -75,6 +80,8 @@ describe('ShippingOrderExtractionCard', () => {
|
||||
openedExistingCount: 2,
|
||||
},
|
||||
availableActions: ['view_details'],
|
||||
healthTips: [],
|
||||
currentActivity: null,
|
||||
}),
|
||||
runNo: 'SNER-DUP',
|
||||
},
|
||||
@@ -85,7 +92,123 @@ describe('ShippingOrderExtractionCard', () => {
|
||||
expect(wrapper.text()).not.toContain('需人工处理');
|
||||
});
|
||||
|
||||
it('emits retry for failed attachments only', async () => {
|
||||
it('does not label generated candidates as manual-review exceptions', () => {
|
||||
const wrapper = mount(ShippingOrderExtractionCard, {
|
||||
props: {
|
||||
state: buildState({
|
||||
status: 'review_required',
|
||||
summary: {
|
||||
totalDocuments: 2,
|
||||
pendingDocuments: 0,
|
||||
processingDocuments: 0,
|
||||
completedDocuments: 2,
|
||||
reviewRequiredDocuments: 0,
|
||||
failedDocuments: 0,
|
||||
candidateCount: 2,
|
||||
},
|
||||
availableActions: ['view_details', 'review_candidate'],
|
||||
primaryNotice: 'candidate_confirmation',
|
||||
handlingItems: [{
|
||||
category: 'candidate_confirmation',
|
||||
count: 2,
|
||||
reasonCodes: [],
|
||||
affectedRefs: [],
|
||||
primaryAction: 'review_candidate',
|
||||
}],
|
||||
healthTips: [],
|
||||
currentActivity: null,
|
||||
}),
|
||||
runNo: 'SNER-CANDIDATES',
|
||||
},
|
||||
global: {
|
||||
plugins: [i18n],
|
||||
stubs: { 'router-link': true },
|
||||
},
|
||||
});
|
||||
// 关键断言:成功候选可待人工确认,但绝不能提示为识别异常。
|
||||
expect(wrapper.text()).toContain('订单候选已生成');
|
||||
expect(wrapper.text()).toContain('候选待人工确认');
|
||||
expect(wrapper.text()).not.toContain('部分附件需人工处理');
|
||||
});
|
||||
|
||||
it('renders mixed handling items with reasons instead of a vague needs-action notice', () => {
|
||||
const wrapper = mount(ShippingOrderExtractionCard, {
|
||||
props: {
|
||||
state: buildState({
|
||||
status: 'partially_completed',
|
||||
summary: {
|
||||
totalDocuments: 3,
|
||||
pendingDocuments: 0,
|
||||
processingDocuments: 0,
|
||||
completedDocuments: 1,
|
||||
reviewRequiredDocuments: 1,
|
||||
failedDocuments: 1,
|
||||
candidateCount: 1,
|
||||
},
|
||||
availableActions: ['enter_manual_review', 'retry_failed_attachments', 'view_details'],
|
||||
primaryNotice: 'technical_failure',
|
||||
handlingItems: [
|
||||
{
|
||||
category: 'technical_failure',
|
||||
count: 1,
|
||||
reasonCodes: ['document_unreadable'],
|
||||
affectedRefs: [],
|
||||
primaryAction: 'retry_failed_attachments',
|
||||
},
|
||||
{
|
||||
category: 'candidate_missing_info',
|
||||
count: 1,
|
||||
reasonCodes: ['required_field_missing'],
|
||||
affectedRefs: [],
|
||||
primaryAction: 'review_candidate',
|
||||
},
|
||||
{
|
||||
category: 'auto_freeze_blocked',
|
||||
count: 1,
|
||||
reasonCodes: ['profile_manual_confirmation_required'],
|
||||
affectedRefs: [{ type: 'task', task_no: 'ST-88', candidate_no: 'C-9' }],
|
||||
primaryAction: 'view_details',
|
||||
},
|
||||
],
|
||||
healthTips: [],
|
||||
currentActivity: null,
|
||||
terminal: true,
|
||||
}),
|
||||
runNo: 'SNER-MIXED',
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
expect(wrapper.text()).toContain('部分附件处理失败');
|
||||
expect(wrapper.text()).toContain('订单待补信息');
|
||||
expect(wrapper.text()).toContain('自动冻结受阻');
|
||||
expect(wrapper.text()).toContain('文件损坏、加密或无法读取');
|
||||
expect(wrapper.text()).toContain('影响对象:');
|
||||
expect(wrapper.text()).toContain('ST-88');
|
||||
expect(wrapper.findAll('[data-testid="shipping-order-extraction-handling-item"]').length).toBe(3);
|
||||
});
|
||||
|
||||
it('emits cancel after confirmation', async () => {
|
||||
const wrapper = mount(ShippingOrderExtractionCard, {
|
||||
props: {
|
||||
state: buildState({
|
||||
availableActions: ['cancel_run', 'refresh_status'],
|
||||
}),
|
||||
runNo: 'SNER-1',
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
const cancelBtn = wrapper.findAll('button').find((b) => b.text().includes('取消本次识别'));
|
||||
expect(cancelBtn).toBeTruthy();
|
||||
await cancelBtn!.trigger('click');
|
||||
expect(wrapper.text()).toContain('确认取消本次识别');
|
||||
const textarea = wrapper.find('textarea');
|
||||
await textarea.setValue('不再需要识别');
|
||||
const confirmBtn = wrapper.findAll('button').find((b) => b.text() === '取消本次识别');
|
||||
await confirmBtn!.trigger('click');
|
||||
expect(wrapper.emitted('cancel')?.[0]).toEqual(['不再需要识别']);
|
||||
});
|
||||
|
||||
it('emits retry for failed attachments', async () => {
|
||||
const wrapper = mount(ShippingOrderExtractionCard, {
|
||||
props: {
|
||||
state: buildState({
|
||||
@@ -99,12 +222,14 @@ describe('ShippingOrderExtractionCard', () => {
|
||||
failedDocuments: 1,
|
||||
candidateCount: 0,
|
||||
},
|
||||
healthTips: [],
|
||||
}),
|
||||
runNo: 'SNER-2',
|
||||
runNo: 'SNER-1',
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
await wrapper.get('button').trigger('click');
|
||||
expect(wrapper.emitted('retry')).toBeTruthy();
|
||||
const retryBtn = wrapper.findAll('button').find((b) => b.text().includes('重试失败附件'));
|
||||
await retryBtn!.trigger('click');
|
||||
expect(wrapper.emitted('retry')?.length).toBe(1);
|
||||
});
|
||||
});
|
||||
@@ -1,30 +1,55 @@
|
||||
/**
|
||||
* features/chat/components/shipping/ShippingOrderExtractionCard.vue
|
||||
* 用途:聊天主区一句过程通知——不重复右侧统计,无逐 PDF 列表、无复核按钮。
|
||||
* 依赖:订单抽取 Run 状态卡 DTO、vue-i18n。
|
||||
* 逻辑:右侧 ShippingSessionSummaryPanel 为唯一状态与跳转面;纯 open_existing 时用重复关联文案。
|
||||
* 用途:聊天主区批次进度卡——摘要计数、Run 级处理事项、当前文件阶段、健康提醒与动作。
|
||||
* 依赖:订单抽取 Run 状态卡 DTO、orderExtractionProgressDisplay、vue-router、vue-i18n。
|
||||
* 逻辑:事实一律来自后端 handling_items / primary_notice;右侧 ShippingSessionSummaryPanel 承接逐 PDF 明细。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue';
|
||||
import { computed, ref } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { useRoute, useRouter } from 'vue-router';
|
||||
import { CircleCheck, CircleX, LoaderCircle, TriangleAlert } from 'lucide-vue-next';
|
||||
import type { ShippingOrderExtractionState } from '../../types/chat.types';
|
||||
import type {
|
||||
ShippingOrderExtractionHandlingItemState,
|
||||
ShippingOrderExtractionState,
|
||||
} from '../../types/chat.types';
|
||||
import {
|
||||
formatOrderExtractionElapsed,
|
||||
resolveOrderExtractionUserStageKey,
|
||||
} from '../../shipping/orderExtractionProgressDisplay';
|
||||
import {
|
||||
listDisplayableHandlingAffectedRefs,
|
||||
type ShippingHandlingAffectedRef,
|
||||
type ShippingHandlingRefTarget,
|
||||
} from '../../shipping/orderExtractionHandlingRefs';
|
||||
|
||||
const props = defineProps<{
|
||||
state: ShippingOrderExtractionState;
|
||||
runNo?: string;
|
||||
retrying?: boolean;
|
||||
refreshing?: boolean;
|
||||
cancelling?: boolean;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
retry: [];
|
||||
refresh: [];
|
||||
cancel: [reason?: string];
|
||||
}>();
|
||||
|
||||
const { t, te } = useI18n();
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
const confirmCancelOpen = ref(false);
|
||||
const cancelReason = ref('');
|
||||
|
||||
const handlingItems = computed(() => props.state.handlingItems || []);
|
||||
|
||||
/**
|
||||
* 是否为「仅重复关联已有任务、无需人工复核」终态通知。
|
||||
*/
|
||||
const isDuplicateOnlyNotice = computed(() => {
|
||||
if (handlingItems.value.length > 0) return false;
|
||||
const opened = Math.max(0, Number(props.state.summary.openedExistingCount || 0));
|
||||
if (opened <= 0) return false;
|
||||
const review = Math.max(0, Number(props.state.summary.reviewRequiredDocuments || 0));
|
||||
@@ -32,10 +57,25 @@ const isDuplicateOnlyNotice = computed(() => {
|
||||
return review === 0 && failed === 0;
|
||||
});
|
||||
|
||||
/**
|
||||
* 是否为纯候选确认场景;优先信任后端 primary_notice,避免用摘要计数掩盖混合原因。
|
||||
*/
|
||||
const isCandidateConfirmationNotice = computed(() => (
|
||||
props.state.primaryNotice === 'candidate_confirmation'
|
||||
|| (
|
||||
!props.state.primaryNotice
|
||||
&& handlingItems.value.length === 1
|
||||
&& handlingItems.value[0]?.category === 'candidate_confirmation'
|
||||
)
|
||||
));
|
||||
|
||||
const toneClass = computed(() => {
|
||||
if (isDuplicateOnlyNotice.value) {
|
||||
return 'border-violet-200 bg-violet-50/80 text-violet-950 dark:border-violet-800 dark:bg-violet-950/35 dark:text-violet-100';
|
||||
}
|
||||
if (isCandidateConfirmationNotice.value) {
|
||||
return 'border-teal-200 bg-teal-50/80 text-teal-950 dark:border-teal-800 dark:bg-teal-950/35 dark:text-teal-100';
|
||||
}
|
||||
switch (props.state.status) {
|
||||
case 'completed':
|
||||
return 'border-emerald-200 bg-emerald-50/80 text-emerald-950 dark:border-emerald-800 dark:bg-emerald-950/35 dark:text-emerald-100';
|
||||
@@ -50,13 +90,42 @@ const toneClass = computed(() => {
|
||||
}
|
||||
});
|
||||
|
||||
const stageLabel = computed(() => {
|
||||
const key = resolveOrderExtractionUserStageKey(
|
||||
props.state.currentActivity?.userVisibleStage || props.state.userVisibleStage,
|
||||
props.state.currentActivity?.eventCode || props.state.status,
|
||||
);
|
||||
return te(key) ? t(key) : '';
|
||||
});
|
||||
|
||||
const elapsedLabel = computed(() =>
|
||||
formatOrderExtractionElapsed(props.state.currentActivity?.elapsedSeconds),
|
||||
);
|
||||
|
||||
/**
|
||||
* 一句过程通知;纯重复关联不误报「需人工处理」。
|
||||
* 将处理事项类别映射为一句过程通知文案。
|
||||
* @param category - 后端 primary_notice / handling item category
|
||||
*/
|
||||
function noticeForCategory(category: string): string {
|
||||
const key = `chat.shippingOrderExtractionHandling.primaryNotice.${category}`;
|
||||
return te(key) ? t(key) : t('chat.shippingSessionSummary.processNoticeNeedsAction');
|
||||
}
|
||||
|
||||
/**
|
||||
* 一句过程通知;有 handling_items 时以后端类别为准,不再笼统写「需人工处理」。
|
||||
*/
|
||||
const compactLine = computed(() => {
|
||||
if (props.state.cancellation?.requested && !props.state.cancellation?.completedAt && !props.state.terminal) {
|
||||
return t('chat.shippingOrderExtractionUserStage.cancellation_requested');
|
||||
}
|
||||
if (isDuplicateOnlyNotice.value) {
|
||||
return t('chat.shippingSessionSummary.processNoticeDuplicateLinked');
|
||||
}
|
||||
const notice = String(props.state.primaryNotice || '').trim();
|
||||
if (notice) return noticeForCategory(notice);
|
||||
if (handlingItems.value[0]?.category) {
|
||||
return noticeForCategory(handlingItems.value[0].category);
|
||||
}
|
||||
switch (props.state.status) {
|
||||
case 'completed':
|
||||
return t('chat.shippingSessionSummary.processNoticeCompleted');
|
||||
@@ -66,8 +135,23 @@ const compactLine = computed(() => {
|
||||
case 'failed':
|
||||
case 'cancelled':
|
||||
return t('chat.shippingSessionSummary.processNoticeFailed');
|
||||
default:
|
||||
default: {
|
||||
if (props.state.status === 'queued' || props.state.status === 'processing') {
|
||||
const parts: string[] = [];
|
||||
const fileName = String(props.state.currentActivity?.fileName || '').trim();
|
||||
if (fileName) {
|
||||
parts.push(t('chat.shippingOrderExtractionCurrentFile', {
|
||||
fileName: fileName || t('chat.shippingOrderExtractionUnknownDocument'),
|
||||
}));
|
||||
}
|
||||
const stage = stageLabel.value;
|
||||
if (stage) parts.push(stage);
|
||||
const elapsed = elapsedLabel.value;
|
||||
if (elapsed) parts.push(t('chat.shippingOrderExtractionElapsed', { elapsed }));
|
||||
if (parts.length) return parts.join(' · ');
|
||||
}
|
||||
return t('chat.shippingSessionSummary.processNoticeProcessing');
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
@@ -81,6 +165,133 @@ const showRetry = computed(() => (
|
||||
props.state.availableActions.includes('retry_failed_attachments')
|
||||
|| props.state.summary.failedDocuments > 0
|
||||
));
|
||||
const showRefresh = computed(() => props.state.availableActions.includes('refresh_status'));
|
||||
const showCancel = computed(() => (
|
||||
props.state.availableActions.includes('cancel_run')
|
||||
&& !(props.state.cancellation?.requested && !props.state.cancellation?.completedAt)
|
||||
));
|
||||
const healthTips = computed(() => props.state.healthTips || []);
|
||||
|
||||
/**
|
||||
* 解析处理事项标题。
|
||||
* @param item - 后端 handling item
|
||||
*/
|
||||
function handlingTitle(item: ShippingOrderExtractionHandlingItemState): string {
|
||||
const key = `chat.shippingOrderExtractionHandling.category.${item.category}`;
|
||||
return te(key) ? t(key) : item.category;
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析原因码文案;未知码回退为原文。
|
||||
* @param code - 原因码
|
||||
*/
|
||||
function reasonLabel(code: string): string {
|
||||
const key = `chat.shippingOrderExtractionReason.${code}`;
|
||||
if (te(key)) return t(key);
|
||||
const freezeKey = `chat.shippingOrderExtractionHandling.reason.${code}`;
|
||||
return te(freezeKey) ? t(freezeKey) : code;
|
||||
}
|
||||
|
||||
/**
|
||||
* 打开订单复核工作台(Chat order-review 模式)。
|
||||
* @param options.documentId - 可选,定位到具体 PDF(由右侧 case 映射承接时仍打开 Run 复核)
|
||||
* @param options.candidateNo - 可选,写入 query 供复核页筛选
|
||||
*/
|
||||
async function openOrderReview(options?: { documentId?: number; candidateNo?: string }) {
|
||||
const runNo = String(props.runNo || '').trim();
|
||||
if (!runNo) return;
|
||||
const query: Record<string, string> = {
|
||||
...Object.fromEntries(
|
||||
Object.entries(route.query).filter(([, v]) => typeof v === 'string') as Array<[string, string]>,
|
||||
),
|
||||
mode: 'order-review',
|
||||
run_no: runNo,
|
||||
};
|
||||
const candidateNo = String(options?.candidateNo || '').trim();
|
||||
if (candidateNo) query.candidate = candidateNo;
|
||||
const documentId = Number(options?.documentId || 0);
|
||||
if (documentId > 0) query.document_id = String(documentId);
|
||||
await router.push({
|
||||
name: 'Chat',
|
||||
params: { agentId: String(route.params.agentId || '') },
|
||||
query,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 打开任务工作台,定位自动冻结受阻等任务号。
|
||||
*/
|
||||
async function openTaskWorkbench(taskNo: string) {
|
||||
const normalized = String(taskNo || '').trim();
|
||||
if (!normalized) return;
|
||||
await router.push({
|
||||
name: 'workspace-shipping-tasks',
|
||||
params: { taskNo: normalized },
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 按受影响对象引用跳转到任务或复核入口。
|
||||
*/
|
||||
async function openAffectedRef(target: ShippingHandlingRefTarget) {
|
||||
if (target.kind === 'task') {
|
||||
await openTaskWorkbench(target.taskNo);
|
||||
return;
|
||||
}
|
||||
if (target.kind === 'review') {
|
||||
await openOrderReview({
|
||||
documentId: target.documentId,
|
||||
candidateNo: target.candidateNo,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 列出事项下可展示的受影响对象。
|
||||
*/
|
||||
function affectedRows(item: ShippingOrderExtractionHandlingItemState) {
|
||||
return listDisplayableHandlingAffectedRefs(item.affectedRefs as ShippingHandlingAffectedRef[]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 按处理事项主动作跳转或触发重试;优先跳到首个受影响对象。
|
||||
* @param item - 处理事项
|
||||
*/
|
||||
async function handleHandlingAction(item: ShippingOrderExtractionHandlingItemState) {
|
||||
const action = String(item.primaryAction || '').trim();
|
||||
if (action === 'retry_failed_attachments') {
|
||||
emit('retry');
|
||||
return;
|
||||
}
|
||||
const first = affectedRows(item)[0];
|
||||
if (first && first.target.kind !== 'none') {
|
||||
await openAffectedRef(first.target);
|
||||
return;
|
||||
}
|
||||
if (
|
||||
action === 'enter_manual_review'
|
||||
|| action === 'review_candidate'
|
||||
|| action === 'view_details'
|
||||
) {
|
||||
await openOrderReview();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 确认后发出取消事件;取消是请求语义,由后端检查点生效。
|
||||
*/
|
||||
function confirmCancel() {
|
||||
confirmCancelOpen.value = false;
|
||||
const reason = String(cancelReason.value || '').trim();
|
||||
cancelReason.value = '';
|
||||
emit('cancel', reason || undefined);
|
||||
}
|
||||
|
||||
/** 打开取消确认并清空上次填写的原因。 */
|
||||
function openCancelConfirm() {
|
||||
cancelReason.value = '';
|
||||
confirmCancelOpen.value = true;
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -95,7 +306,7 @@ const showRetry = computed(() => (
|
||||
class="mt-0.5 h-4 w-4 shrink-0 animate-spin"
|
||||
/>
|
||||
<CircleCheck
|
||||
v-else-if="state.status === 'completed' || isDuplicateOnlyNotice"
|
||||
v-else-if="state.status === 'completed' || isDuplicateOnlyNotice || isCandidateConfirmationNotice"
|
||||
class="mt-0.5 h-4 w-4 shrink-0"
|
||||
/>
|
||||
<TriangleAlert
|
||||
@@ -106,23 +317,175 @@ const showRetry = computed(() => (
|
||||
|
||||
<div class="min-w-0 flex-1">
|
||||
<div class="text-sm font-medium">{{ compactLine }}</div>
|
||||
|
||||
<div
|
||||
v-if="state.summary.totalDocuments > 0"
|
||||
class="mt-1.5 flex flex-wrap gap-1.5 text-[11px] opacity-90"
|
||||
data-testid="shipping-order-extraction-summary"
|
||||
>
|
||||
<span>{{ t('chat.shippingOrderExtractionSummary.total', { count: state.summary.totalDocuments }) }}</span>
|
||||
<span v-if="state.summary.processingDocuments > 0">
|
||||
{{ t('chat.shippingOrderExtractionSummary.processing', { count: state.summary.processingDocuments }) }}
|
||||
</span>
|
||||
<span v-if="state.summary.pendingDocuments > 0">
|
||||
{{ t('chat.shippingOrderExtractionSummary.pending', { count: state.summary.pendingDocuments }) }}
|
||||
</span>
|
||||
<span v-if="state.summary.completedDocuments > 0">
|
||||
{{ t('chat.shippingOrderExtractionSummary.completed', { count: state.summary.completedDocuments }) }}
|
||||
</span>
|
||||
<span v-if="state.summary.reviewRequiredDocuments > 0">
|
||||
{{ t('chat.shippingOrderExtractionSummary.reviewRequired', { count: state.summary.reviewRequiredDocuments }) }}
|
||||
</span>
|
||||
<span v-if="state.summary.failedDocuments > 0">
|
||||
{{ t('chat.shippingOrderExtractionSummary.failed', { count: state.summary.failedDocuments }) }}
|
||||
</span>
|
||||
<span v-if="(state.summary.cancelledDocuments || 0) > 0">
|
||||
{{ t('chat.shippingOrderExtractionSummary.cancelled', { count: state.summary.cancelledDocuments }) }}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="handlingItems.length"
|
||||
class="mt-2 space-y-1.5"
|
||||
data-testid="shipping-order-extraction-handling-items"
|
||||
>
|
||||
<div class="text-[11px] font-medium opacity-90">
|
||||
{{ t('chat.shippingOrderExtractionHandling.title') }}
|
||||
</div>
|
||||
<div
|
||||
v-for="item in handlingItems"
|
||||
:key="item.category"
|
||||
class="rounded-md border border-current/15 bg-black/5 px-2 py-1.5 text-xs dark:bg-white/5"
|
||||
data-testid="shipping-order-extraction-handling-item"
|
||||
>
|
||||
<div class="flex flex-wrap items-center justify-between gap-2">
|
||||
<div class="min-w-0 font-medium">
|
||||
{{ handlingTitle(item) }}
|
||||
<span class="ml-1 opacity-80">{{ t('chat.shippingOrderExtractionHandling.count', { count: item.count }) }}</span>
|
||||
</div>
|
||||
<button
|
||||
v-if="item.primaryAction"
|
||||
type="button"
|
||||
class="shrink-0 rounded-md border border-current/20 px-2 py-0.5 text-[11px] font-medium hover:bg-black/5 dark:hover:bg-white/5"
|
||||
@click="handleHandlingAction(item)"
|
||||
>
|
||||
{{ te(`chat.shippingOrderExtractionAction.${item.primaryAction}`)
|
||||
? t(`chat.shippingOrderExtractionAction.${item.primaryAction}`)
|
||||
: t('chat.shippingOrderExtractionAction.view_details') }}
|
||||
</button>
|
||||
</div>
|
||||
<div v-if="item.reasonCodes.length" class="mt-1 opacity-80">
|
||||
{{ t('chat.shippingOrderExtractionHandling.reasonPrefix') }}
|
||||
{{ item.reasonCodes.slice(0, 4).map(reasonLabel).join(';') }}
|
||||
</div>
|
||||
<div
|
||||
v-if="affectedRows(item).length"
|
||||
class="mt-1.5 flex flex-wrap gap-1"
|
||||
data-testid="shipping-order-extraction-affected-refs"
|
||||
>
|
||||
<span class="opacity-80">{{ t('chat.shippingOrderExtractionHandling.affectedPrefix') }}</span>
|
||||
<button
|
||||
v-for="row in affectedRows(item)"
|
||||
:key="row.key"
|
||||
type="button"
|
||||
class="rounded border border-current/20 px-1.5 py-0.5 text-[11px] font-medium underline-offset-2 hover:underline"
|
||||
@click="openAffectedRef(row.target)"
|
||||
>
|
||||
{{ row.label }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="state.currentActivity?.fileName" class="mt-1 text-xs opacity-80">
|
||||
{{ t('chat.shippingOrderExtractionCurrentFile', {
|
||||
fileName: state.currentActivity.fileName || t('chat.shippingOrderExtractionUnknownDocument'),
|
||||
}) }}
|
||||
<span v-if="activityKey"> · {{ t(activityKey) }}</span>
|
||||
<span v-if="stageLabel"> · {{ stageLabel }}</span>
|
||||
<span v-else-if="activityKey"> · {{ t(activityKey) }}</span>
|
||||
<span v-if="elapsedLabel"> · {{ t('chat.shippingOrderExtractionElapsed', { elapsed: elapsedLabel }) }}</span>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-for="tip in healthTips"
|
||||
:key="tip.code"
|
||||
class="mt-1 text-xs font-medium opacity-90"
|
||||
data-testid="shipping-order-extraction-health-tip"
|
||||
>
|
||||
{{ t(`chat.shippingOrderExtractionHealthTip.${tip.code}`) }}
|
||||
</div>
|
||||
|
||||
<div v-if="state.refreshFailed" class="mt-1 text-xs font-medium opacity-90">
|
||||
{{ t('chat.shippingOrderExtractionRefreshFailed') }}
|
||||
</div>
|
||||
<button
|
||||
v-if="showRetry"
|
||||
type="button"
|
||||
class="mt-2 inline-flex items-center rounded-md border border-current/20 px-2.5 py-1 text-xs font-medium hover:bg-black/5 dark:hover:bg-white/5"
|
||||
@click="emit('retry')"
|
||||
>
|
||||
{{ t('chat.shippingOrderExtractionAction.retry_failed_attachments') }}
|
||||
</button>
|
||||
|
||||
<div v-if="confirmCancelOpen" class="mt-2 rounded-md border border-current/20 bg-black/5 p-2 text-xs dark:bg-white/5">
|
||||
<div class="font-medium">{{ t('chat.shippingOrderExtractionCancel.confirmTitle') }}</div>
|
||||
<div class="mt-1 opacity-80">{{ t('chat.shippingOrderExtractionCancel.confirmImpact') }}</div>
|
||||
<label class="mt-2 block opacity-90">
|
||||
{{ t('chat.shippingOrderExtractionCancel.reasonOptional') }}
|
||||
<textarea
|
||||
v-model="cancelReason"
|
||||
rows="2"
|
||||
class="input-field mt-1 w-full py-1 text-xs"
|
||||
:placeholder="t('chat.shippingOrderExtractionCancel.reasonOptional')"
|
||||
/>
|
||||
</label>
|
||||
<div class="mt-2 flex flex-wrap gap-2">
|
||||
<button
|
||||
type="button"
|
||||
class="inline-flex items-center rounded-md border border-current/20 px-2.5 py-1 text-xs font-medium hover:bg-black/5 dark:hover:bg-white/5"
|
||||
:disabled="cancelling"
|
||||
@click="confirmCancel"
|
||||
>
|
||||
{{ cancelling
|
||||
? t('chat.shippingOrderExtractionCancel.submitting')
|
||||
: t('chat.shippingOrderExtractionAction.cancel_run') }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="inline-flex items-center rounded-md px-2.5 py-1 text-xs font-medium opacity-80 hover:underline"
|
||||
:disabled="cancelling"
|
||||
@click="confirmCancelOpen = false; cancelReason = ''"
|
||||
>
|
||||
{{ t('chat.shippingOrderExtractionCancel.dismiss') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-else class="mt-2 flex flex-wrap gap-2">
|
||||
<button
|
||||
v-if="showRefresh"
|
||||
type="button"
|
||||
class="inline-flex items-center rounded-md border border-current/20 px-2.5 py-1 text-xs font-medium hover:bg-black/5 dark:hover:bg-white/5"
|
||||
:disabled="refreshing"
|
||||
@click="emit('refresh')"
|
||||
>
|
||||
{{ refreshing
|
||||
? t('chat.shippingOrderExtractionRefreshing')
|
||||
: t('chat.shippingOrderExtractionAction.refresh_status') }}
|
||||
</button>
|
||||
<button
|
||||
v-if="showCancel"
|
||||
type="button"
|
||||
class="inline-flex items-center rounded-md border border-current/20 px-2.5 py-1 text-xs font-medium hover:bg-black/5 dark:hover:bg-white/5"
|
||||
:disabled="cancelling"
|
||||
@click="openCancelConfirm"
|
||||
>
|
||||
{{ t('chat.shippingOrderExtractionAction.cancel_run') }}
|
||||
</button>
|
||||
<button
|
||||
v-if="showRetry"
|
||||
type="button"
|
||||
class="inline-flex items-center rounded-md border border-current/20 px-2.5 py-1 text-xs font-medium hover:bg-black/5 dark:hover:bg-white/5"
|
||||
:disabled="retrying"
|
||||
@click="emit('retry')"
|
||||
>
|
||||
{{ retrying
|
||||
? t('chat.shippingOrderExtractionRetrying')
|
||||
: t('chat.shippingOrderExtractionAction.retry_failed_attachments') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -625,6 +625,7 @@ export function useChatPage() {
|
||||
shippingBatchTasks: shipping.shippingBatchTasks,
|
||||
activeShippingTaskDetail: shipping.activeShippingTaskDetail,
|
||||
getActiveOrderExtractionRunNo: shipping.getActiveOrderExtractionRunNo,
|
||||
sessionWorkItemsRefreshTrigger: shipping.sessionWorkItemsRefreshTrigger,
|
||||
shippingInventorySelectionActive: shipping.shippingInventorySelectionActive,
|
||||
shippingInventorySelectionTaskId: shipping.shippingInventorySelectionTaskId,
|
||||
switchShippingBatch: shipping.switchShippingBatch,
|
||||
|
||||
@@ -792,6 +792,10 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
msg,
|
||||
t,
|
||||
});
|
||||
const sessionWorkItemsRefreshTrigger = ref(0);
|
||||
const bumpSessionWorkItemsRefresh = () => {
|
||||
sessionWorkItemsRefreshTrigger.value += 1;
|
||||
};
|
||||
const shippingOrderExtractionRuns = useShippingOrderExtractionRuns({
|
||||
messages,
|
||||
conversationId,
|
||||
@@ -813,6 +817,7 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
});
|
||||
},
|
||||
onRetryError: (message) => msg.error(message),
|
||||
onSessionWorkItemsRefresh: bumpSessionWorkItemsRefresh,
|
||||
t,
|
||||
});
|
||||
|
||||
@@ -1384,8 +1389,12 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
removeShippingNoticeAttachment: shippingIntakes.removeNoticeAttachment,
|
||||
retryShippingNoticeAttachment: shippingIntakes.retryNoticeAttachment,
|
||||
retryOrderExtractionRun: shippingOrderExtractionRuns.retryRun,
|
||||
refreshOrderExtractionRun: shippingOrderExtractionRuns.refreshRun,
|
||||
cancelOrderExtractionRun: shippingOrderExtractionRuns.cancelRun,
|
||||
cancelOrderExtractionUnit: shippingOrderExtractionRuns.cancelUnit,
|
||||
reparseOrderExtractionRun: shippingOrderExtractionRuns.reparseRun,
|
||||
getActiveOrderExtractionRunNo: shippingOrderExtractionRuns.getActiveRunNo,
|
||||
sessionWorkItemsRefreshTrigger,
|
||||
shippingNoticeAllReadyForConfirmation: shippingIntakes.allReadyForConfirmation,
|
||||
setShippingCandidateSelected,
|
||||
resolveShippingCandidateDuplicate,
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
/**
|
||||
* features/chat/e2e/shipping-order-extraction-progress.spec.ts
|
||||
* 用途:阶段 5 用户进度卡契约冒烟——取消/刷新仅依赖后端 availableActions,不发明阶段。
|
||||
* 依赖:Vitest、orderExtractionProgressDisplay、ShippingOrderExtractionCard 映射约定。
|
||||
* 逻辑:模拟后端关闭取消开关后的投影;断言前端展示入口只读服务端动作列表。
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
formatOrderExtractionElapsed,
|
||||
resolveOrderExtractionUserStageKey,
|
||||
} from '@/features/chat/shipping/orderExtractionProgressDisplay';
|
||||
|
||||
describe('shipping order extraction progress e2e contract', () => {
|
||||
it('never invents ETA and maps only backend user_visible_stage', () => {
|
||||
// 关键断言:无百分比/ETA;阶段文案 key 完全由后端阶段码驱动。
|
||||
expect(formatOrderExtractionElapsed(null)).toBe('');
|
||||
expect(resolveOrderExtractionUserStageKey('cancellation_requested', 'extracting')).toBe(
|
||||
'chat.shippingOrderExtractionUserStage.cancellation_requested',
|
||||
);
|
||||
});
|
||||
|
||||
it('hides cancel when availableActions omit cancel_run (feature flag rollback)', () => {
|
||||
const availableActions = ['view_details', 'refresh_status'] as const;
|
||||
const showCancel = availableActions.includes('cancel_run');
|
||||
const showRefresh = availableActions.includes('refresh_status');
|
||||
// 关键断言:灰度关闭取消后前端不得本地补按钮。
|
||||
expect(showCancel).toBe(false);
|
||||
expect(showRefresh).toBe(true);
|
||||
});
|
||||
|
||||
it('treats review_required as business review, not technical failure', () => {
|
||||
const stageKey = resolveOrderExtractionUserStageKey('review_required', 'failed');
|
||||
expect(stageKey).toBe('chat.shippingOrderExtractionUserStage.review_required');
|
||||
expect(stageKey.includes('failed')).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -36,6 +36,9 @@ type ShippingHandlerSource = Pick<
|
||||
| 'addShippingParseReviewLine'
|
||||
| 'removeShippingParseReviewLine'
|
||||
| 'retryOrderExtractionRun'
|
||||
| 'refreshOrderExtractionRun'
|
||||
| 'cancelOrderExtractionRun'
|
||||
| 'cancelOrderExtractionUnit'
|
||||
| 'reparseOrderExtractionRun'
|
||||
| 'resolveShippingCandidateDuplicate'
|
||||
| 'promoteShippingCandidate'
|
||||
@@ -74,6 +77,9 @@ export function createShippingMessageHandlers(shipping: ShippingHandlerSource):
|
||||
addLine: shipping.addShippingParseReviewLine,
|
||||
removeLine: shipping.removeShippingParseReviewLine,
|
||||
retryOrderExtractionRun: shipping.retryOrderExtractionRun,
|
||||
refreshOrderExtractionRun: shipping.refreshOrderExtractionRun,
|
||||
cancelOrderExtractionRun: shipping.cancelOrderExtractionRun,
|
||||
cancelOrderExtractionUnit: shipping.cancelOrderExtractionUnit,
|
||||
reparseOrderExtractionRun: shipping.reparseOrderExtractionRun,
|
||||
resolveCandidateDuplicate: shipping.resolveShippingCandidateDuplicate,
|
||||
promoteCandidate: shipping.promoteShippingCandidate,
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
/**
|
||||
* features/chat/shipping-review/useShippingOrderReview.spec.ts
|
||||
* 用途:阶段 3 复核页历史版本只读契约冒烟。
|
||||
* 依赖:isReviewCaseHistorical 纯函数。
|
||||
* 逻辑:断言 superseded / 非当前 case_no 时强制只读。
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { isReviewCaseHistorical } from './useShippingOrderReview';
|
||||
|
||||
describe('useShippingOrderReview historical readonly', () => {
|
||||
it('forces readonly when case status is superseded', () => {
|
||||
expect(isReviewCaseHistorical(
|
||||
{ case_no: 'CASE-OLD', status: 'superseded' },
|
||||
{ current_case_no: 'CASE-NEW' },
|
||||
)).toBe(true);
|
||||
});
|
||||
|
||||
it('forces readonly when viewing non-current work item case', () => {
|
||||
expect(isReviewCaseHistorical(
|
||||
{ case_no: 'CASE-OLD', status: 'draft' },
|
||||
{ current_case_no: 'CASE-NEW', version_replaced: true },
|
||||
)).toBe(true);
|
||||
});
|
||||
|
||||
it('allows edit when viewing current case', () => {
|
||||
expect(isReviewCaseHistorical(
|
||||
{ case_no: 'CASE-1', status: 'draft' },
|
||||
{ current_case_no: 'CASE-1', version_replaced: false },
|
||||
)).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -1,10 +1,10 @@
|
||||
/**
|
||||
* features/chat/shipping-review/useShippingOrderReview.ts
|
||||
* 用途:加载建单前复核 Run 和当前 PDF Case 的只读数据。
|
||||
* 依赖:shipping API、Vue 响应式状态。
|
||||
* 逻辑:路由刷新后以 runNo 重建列表,再按 case_no 加载详情;阶段 2 不写入草稿。
|
||||
* 用途:加载建单前复核 Run、当前 PDF Case 与会话工作项版本上下文。
|
||||
* 依赖:shipping API session-work-items / versions、Vue 响应式状态。
|
||||
* 逻辑:路由刷新后以 runNo 重建列表;阶段 3 写入后刷新工作项;历史版本强制只读。
|
||||
*/
|
||||
import { ref } from 'vue';
|
||||
import { computed, ref } from 'vue';
|
||||
import {
|
||||
addWorkspaceShippingOrderReviewLine,
|
||||
createWorkspaceShippingOrderReviewManualDraft,
|
||||
@@ -18,6 +18,8 @@ import {
|
||||
getWorkspaceShippingOrderReviewPreview,
|
||||
getShippingNoticeIntake,
|
||||
getWorkspaceShippingOrderReviewRun,
|
||||
listWorkspaceShippingSessionWorkItemVersions,
|
||||
listWorkspaceShippingSessionWorkItems,
|
||||
patchWorkspaceShippingOrderReviewHeaderField,
|
||||
patchWorkspaceShippingOrderReviewLineField,
|
||||
markWorkspaceShippingOrderReviewNonOrder,
|
||||
@@ -25,38 +27,176 @@ import {
|
||||
reparseWorkspaceShippingOrderReviewDocument,
|
||||
validateWorkspaceShippingOrderReviewDraft,
|
||||
} from '../api/shipping.api';
|
||||
import type { ShippingOrderReviewCase, ShippingOrderReviewEvidence, ShippingOrderReviewRun } from '../types/shipping.api.types';
|
||||
import type {
|
||||
ShippingOrderReviewCase,
|
||||
ShippingOrderReviewEvidence,
|
||||
ShippingOrderReviewRun,
|
||||
ShippingSessionWorkItem,
|
||||
ShippingSessionWorkItemVersion,
|
||||
} from '../types/shipping.api.types';
|
||||
import { uploadFileAsset } from '@/shared/api/file-assets.api';
|
||||
|
||||
/** 复核页顶部状态横幅类型。 */
|
||||
export type ReviewStatusMessage = 'superseded' | 'reparse_in_progress' | 'restored' | null;
|
||||
|
||||
type ReviewCaseRef = { case_no: string; status: string } | null | undefined;
|
||||
type WorkItemRef = { current_case_no?: string | null; version_replaced?: boolean } | null | undefined;
|
||||
|
||||
/**
|
||||
* 判断当前 Case 是否为历史/被替代版本(强制只读)。
|
||||
*/
|
||||
export function isReviewCaseHistorical(activeCase: ReviewCaseRef, workItem: WorkItemRef): boolean {
|
||||
const caseNo = String(activeCase?.case_no || '');
|
||||
const currentCaseNo = String(workItem?.current_case_no || '');
|
||||
if (activeCase?.status === 'superseded') return true;
|
||||
if (currentCaseNo && caseNo && currentCaseNo !== caseNo) return true;
|
||||
return Boolean(workItem?.version_replaced && currentCaseNo && caseNo !== currentCaseNo);
|
||||
}
|
||||
|
||||
export function useShippingOrderReview() {
|
||||
const reviewRun = ref<ShippingOrderReviewRun | null>(null);
|
||||
const activeCase = ref<ShippingOrderReviewCase | null>(null);
|
||||
const workItem = ref<ShippingSessionWorkItem | null>(null);
|
||||
const versions = ref<ShippingSessionWorkItemVersion[]>([]);
|
||||
const statusMessage = ref<ReviewStatusMessage>(null);
|
||||
const loading = ref(false);
|
||||
const loadFailed = ref(false);
|
||||
const saving = ref(false);
|
||||
const saveFailed = ref(false);
|
||||
const versionsLoading = ref(false);
|
||||
const evidence = ref<ShippingOrderReviewEvidence[]>([]);
|
||||
const previewUrl = ref('');
|
||||
let contextConversationId = '';
|
||||
let contextItemNo = '';
|
||||
|
||||
/**
|
||||
* 是否正在查看非当前版本或已被替代的 Case。
|
||||
*/
|
||||
const isViewingHistoricalVersion = computed(() =>
|
||||
isReviewCaseHistorical(activeCase.value, workItem.value),
|
||||
);
|
||||
|
||||
/**
|
||||
* 编辑权限:历史版本或后端未开放 edit_draft 时强制只读。
|
||||
*/
|
||||
const editable = computed(() => {
|
||||
if (isViewingHistoricalVersion.value) return false;
|
||||
return activeCase.value?.available_actions.includes('edit_draft') || false;
|
||||
});
|
||||
|
||||
/**
|
||||
* 根据工作项与 Case 状态刷新顶部横幅文案键。
|
||||
*/
|
||||
const refreshStatusMessage = () => {
|
||||
if (isViewingHistoricalVersion.value || activeCase.value?.status === 'superseded') {
|
||||
statusMessage.value = 'superseded';
|
||||
return;
|
||||
}
|
||||
if (
|
||||
activeCase.value?.status === 'reparse_pending'
|
||||
|| workItem.value?.lifecycle_status === 'extracting'
|
||||
) {
|
||||
statusMessage.value = 'reparse_in_progress';
|
||||
return;
|
||||
}
|
||||
if (
|
||||
workItem.value?.lifecycle_status === 'pending_review'
|
||||
&& workItem.value?.previous_case_hint
|
||||
) {
|
||||
statusMessage.value = 'restored';
|
||||
return;
|
||||
}
|
||||
statusMessage.value = null;
|
||||
};
|
||||
|
||||
/**
|
||||
* 从会话工作台解析 item_no;优先 query item_no,再按 current_case_no 匹配。
|
||||
*/
|
||||
const resolveWorkItem = async (
|
||||
conversationId: string,
|
||||
options?: { itemNo?: string; caseNo?: string },
|
||||
): Promise<ShippingSessionWorkItem | null> => {
|
||||
const conversation = String(conversationId || '').trim();
|
||||
if (!conversation) return null;
|
||||
const summary = await listWorkspaceShippingSessionWorkItems(conversation);
|
||||
const allItems = [...summary.open_items, ...summary.closed_items];
|
||||
const explicitItemNo = String(options?.itemNo || contextItemNo || '').trim();
|
||||
if (explicitItemNo) {
|
||||
return allItems.find((item) => item.item_no === explicitItemNo) || null;
|
||||
}
|
||||
const caseNo = String(options?.caseNo || activeCase.value?.case_no || '').trim();
|
||||
if (!caseNo) return null;
|
||||
return allItems.find((item) => item.current_case_no === caseNo) || null;
|
||||
};
|
||||
|
||||
/**
|
||||
* 拉取工作项与版本时间线;写入后或路由变化时复用。
|
||||
*/
|
||||
const refreshWorkItemContext = async (conversationId?: string, itemNo?: string) => {
|
||||
const conversation = String(conversationId || contextConversationId || '').trim();
|
||||
if (!conversation) return;
|
||||
contextConversationId = conversation;
|
||||
if (itemNo) contextItemNo = itemNo;
|
||||
try {
|
||||
const item = await resolveWorkItem(conversation, {
|
||||
itemNo: contextItemNo || undefined,
|
||||
caseNo: activeCase.value?.case_no,
|
||||
});
|
||||
workItem.value = item;
|
||||
if (!item?.item_no) {
|
||||
versions.value = [];
|
||||
refreshStatusMessage();
|
||||
return;
|
||||
}
|
||||
contextItemNo = item.item_no;
|
||||
versionsLoading.value = true;
|
||||
const response = await listWorkspaceShippingSessionWorkItemVersions(item.item_no);
|
||||
versions.value = response.versions || [];
|
||||
} catch {
|
||||
workItem.value = null;
|
||||
versions.value = [];
|
||||
} finally {
|
||||
versionsLoading.value = false;
|
||||
refreshStatusMessage();
|
||||
}
|
||||
};
|
||||
|
||||
/** 加载 Run 汇总后优先恢复 URL 指定 Case,否则打开首个 PDF。 */
|
||||
const load = async (runNo: string, preferredCaseNo?: string) => {
|
||||
const load = async (
|
||||
runNo: string,
|
||||
preferredCaseNo?: string,
|
||||
options?: { conversationId?: string; itemNo?: string },
|
||||
) => {
|
||||
loading.value = true;
|
||||
loadFailed.value = false;
|
||||
if (options?.conversationId) contextConversationId = options.conversationId;
|
||||
if (options?.itemNo) contextItemNo = options.itemNo;
|
||||
try {
|
||||
const run = await getWorkspaceShippingOrderReviewRun(runNo);
|
||||
reviewRun.value = run;
|
||||
// 旧 Run 被新版结果替代后不再加载它的只读 Case,避免页面表现为“空订单”。
|
||||
if (run.superseded_by_run_no) {
|
||||
await load(run.superseded_by_run_no, preferredCaseNo, options);
|
||||
return;
|
||||
}
|
||||
const caseNo = preferredCaseNo || run.items[0]?.case_no;
|
||||
activeCase.value = caseNo ? await getWorkspaceShippingOrderReviewCase(caseNo) : null;
|
||||
evidence.value = caseNo ? (await getWorkspaceShippingOrderReviewEvidence(caseNo)).items : [];
|
||||
if (previewUrl.value) URL.revokeObjectURL(previewUrl.value);
|
||||
previewUrl.value = '';
|
||||
if (caseNo) {
|
||||
try { previewUrl.value = URL.createObjectURL(await getWorkspaceShippingOrderReviewPreview(caseNo)); } catch { /* PDF failure must not block the draft. */ }
|
||||
try {
|
||||
previewUrl.value = URL.createObjectURL(await getWorkspaceShippingOrderReviewPreview(caseNo));
|
||||
} catch { /* PDF failure must not block the draft. */ }
|
||||
}
|
||||
await refreshWorkItemContext(contextConversationId, contextItemNo);
|
||||
} catch {
|
||||
loadFailed.value = true;
|
||||
reviewRun.value = null;
|
||||
activeCase.value = null;
|
||||
workItem.value = null;
|
||||
versions.value = [];
|
||||
statusMessage.value = null;
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
@@ -72,7 +212,10 @@ export function useShippingOrderReview() {
|
||||
evidence.value = result.items;
|
||||
if (previewUrl.value) URL.revokeObjectURL(previewUrl.value);
|
||||
previewUrl.value = '';
|
||||
try { previewUrl.value = URL.createObjectURL(await getWorkspaceShippingOrderReviewPreview(caseNo)); } catch { /* Preview remains independently recoverable. */ }
|
||||
try {
|
||||
previewUrl.value = URL.createObjectURL(await getWorkspaceShippingOrderReviewPreview(caseNo));
|
||||
} catch { /* Preview remains independently recoverable. */ }
|
||||
refreshStatusMessage();
|
||||
};
|
||||
|
||||
/** 串行保存当前 Case,成功后使用服务端 DTO 替换本地草稿,避免旧响应回写。 */
|
||||
@@ -89,6 +232,7 @@ export function useShippingOrderReview() {
|
||||
item.issue_count = activeCase.value.draft?.issues.length || 0;
|
||||
}
|
||||
}
|
||||
await refreshWorkItemContext();
|
||||
} catch (error) {
|
||||
saveFailed.value = true;
|
||||
throw error;
|
||||
@@ -125,6 +269,7 @@ export function useShippingOrderReview() {
|
||||
});
|
||||
activeCase.value = response.case;
|
||||
if (reviewRun.value) reviewRun.value = await getWorkspaceShippingOrderReviewRun(reviewRun.value.run_no);
|
||||
await refreshWorkItemContext();
|
||||
return response;
|
||||
} catch (error) {
|
||||
saveFailed.value = true;
|
||||
@@ -134,14 +279,41 @@ export function useShippingOrderReview() {
|
||||
}
|
||||
};
|
||||
const createManualDraft = () => activeCase.value && save(() => createWorkspaceShippingOrderReviewManualDraft(activeCase.value!.case_no));
|
||||
const markNonOrder = (reason: string) => activeCase.value && save(() => markWorkspaceShippingOrderReviewNonOrder(activeCase.value!.case_no, reason));
|
||||
const markQualityIssue = (reason: string) => activeCase.value && save(() => markWorkspaceShippingOrderReviewQualityIssue(activeCase.value!.case_no, reason));
|
||||
const reparseDocument = async (reason: string) => {
|
||||
/**
|
||||
* 标记非订单;附带原因码与备注供统一审计。
|
||||
* @param reason - 处置原因码
|
||||
* @param comment - 自由说明
|
||||
*/
|
||||
const markNonOrder = (reason: string, comment?: string) =>
|
||||
activeCase.value && save(() => markWorkspaceShippingOrderReviewNonOrder(activeCase.value!.case_no, reason, comment));
|
||||
/**
|
||||
* 标记质量异常;`other` 时后端要求非空备注。
|
||||
* @param reason - 质量原因码
|
||||
* @param comment - 业务说明
|
||||
*/
|
||||
const markQualityIssue = (reason: string, comment?: string) =>
|
||||
activeCase.value && save(() => markWorkspaceShippingOrderReviewQualityIssue(activeCase.value!.case_no, reason, comment));
|
||||
/**
|
||||
* 单 PDF 重识别是异步建 Run;复用保存互斥,避免重复点击创建竞争请求或把成功状态覆盖为旧 Case。
|
||||
* @param reason - 重识别原因码
|
||||
* @param comment - 自由说明
|
||||
*/
|
||||
const reparseDocument = async (reason: string, comment?: string) => {
|
||||
if (!activeCase.value) return null;
|
||||
const response = await reparseWorkspaceShippingOrderReviewDocument(activeCase.value.case_no, reason);
|
||||
activeCase.value = await getWorkspaceShippingOrderReviewCase(activeCase.value.case_no);
|
||||
if (reviewRun.value) reviewRun.value = await getWorkspaceShippingOrderReviewRun(reviewRun.value.run_no);
|
||||
return response;
|
||||
saving.value = true;
|
||||
saveFailed.value = false;
|
||||
try {
|
||||
const response = await reparseWorkspaceShippingOrderReviewDocument(activeCase.value.case_no, reason, comment);
|
||||
activeCase.value = await getWorkspaceShippingOrderReviewCase(activeCase.value.case_no);
|
||||
if (reviewRun.value) reviewRun.value = await getWorkspaceShippingOrderReviewRun(reviewRun.value.run_no);
|
||||
await refreshWorkItemContext();
|
||||
return response;
|
||||
} catch (error) {
|
||||
saveFailed.value = true;
|
||||
throw error;
|
||||
} finally {
|
||||
saving.value = false;
|
||||
}
|
||||
};
|
||||
/** 上传替代 PDF 后等待既有 Intake 预解析;只有获得唯一 Document 才创建替代 Run。 */
|
||||
const uploadReplacement = async (file: File) => {
|
||||
@@ -163,8 +335,68 @@ export function useShippingOrderReview() {
|
||||
const response = await createWorkspaceShippingOrderReviewReplacementRun(activeCase.value.case_no, intakeNo);
|
||||
activeCase.value = await getWorkspaceShippingOrderReviewCase(activeCase.value.case_no);
|
||||
if (reviewRun.value) reviewRun.value = await getWorkspaceShippingOrderReviewRun(reviewRun.value.run_no);
|
||||
await refreshWorkItemContext();
|
||||
return response;
|
||||
};
|
||||
|
||||
return { reviewRun, activeCase, evidence, previewUrl, loading, loadFailed, saving, saveFailed, load, selectCase, patchHeader, patchLine, addLine, copyLine, deleteLine, validate, confirm, createManualDraft, markNonOrder, markQualityIssue, reparseDocument, uploadReplacement, startReplacementRun };
|
||||
/**
|
||||
* 跳转至工作项当前版本对应的 Run/Case。
|
||||
* @returns 目标 run_no 与 case_no;无法解析时返回 null。
|
||||
*/
|
||||
const currentVersionTarget = (): { runNo: string; caseNo: string } | null => {
|
||||
const runNo = String(workItem.value?.current_run_no || reviewRun.value?.run_no || '').trim();
|
||||
const caseNo = String(workItem.value?.current_case_no || '').trim();
|
||||
if (!runNo || !caseNo) return null;
|
||||
return { runNo, caseNo };
|
||||
};
|
||||
|
||||
/**
|
||||
* 切换到工作项当前版本,并立即加载其 Run 与 Case。
|
||||
*
|
||||
* 不能只更新路由:历史 Run 会发生替代,且路由 watcher 可能因参数时序保留旧的只读 Case。
|
||||
*/
|
||||
const openCurrentVersion = async (): Promise<{ runNo: string; caseNo: string } | null> => {
|
||||
const target = currentVersionTarget();
|
||||
if (!target) return null;
|
||||
await load(target.runNo, target.caseNo, {
|
||||
conversationId: contextConversationId,
|
||||
itemNo: contextItemNo || undefined,
|
||||
});
|
||||
return target;
|
||||
};
|
||||
|
||||
return {
|
||||
reviewRun,
|
||||
activeCase,
|
||||
workItem,
|
||||
versions,
|
||||
statusMessage,
|
||||
isViewingHistoricalVersion,
|
||||
editable,
|
||||
evidence,
|
||||
previewUrl,
|
||||
loading,
|
||||
loadFailed,
|
||||
saving,
|
||||
saveFailed,
|
||||
versionsLoading,
|
||||
load,
|
||||
selectCase,
|
||||
refreshWorkItemContext,
|
||||
currentVersionTarget,
|
||||
openCurrentVersion,
|
||||
patchHeader,
|
||||
patchLine,
|
||||
addLine,
|
||||
copyLine,
|
||||
deleteLine,
|
||||
validate,
|
||||
confirm,
|
||||
createManualDraft,
|
||||
markNonOrder,
|
||||
markQualityIssue,
|
||||
reparseDocument,
|
||||
uploadReplacement,
|
||||
startReplacementRun,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
/**
|
||||
* features/chat/shipping/orderExtractionHandlingRefs.spec.ts
|
||||
* 用途:验证 handling_items.affected_refs 的展示标签与跳转目标解析。
|
||||
* 依赖:Vitest、本域纯函数工具。
|
||||
* 逻辑:覆盖 task / candidate / attachment 三类受控引用。
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
formatHandlingAffectedRefLabel,
|
||||
listDisplayableHandlingAffectedRefs,
|
||||
resolveHandlingAffectedRefTarget,
|
||||
} from './orderExtractionHandlingRefs';
|
||||
|
||||
describe('orderExtractionHandlingRefs', () => {
|
||||
it('formats and routes task / candidate / attachment refs', () => {
|
||||
expect(formatHandlingAffectedRefLabel({ type: 'task', task_no: 'ST-9' })).toBe('ST-9');
|
||||
expect(formatHandlingAffectedRefLabel({
|
||||
type: 'candidate',
|
||||
candidate_no: 'C-1',
|
||||
po_number: 'PO-2',
|
||||
})).toBe('C-1 · PO-2');
|
||||
expect(formatHandlingAffectedRefLabel({
|
||||
type: 'attachment',
|
||||
file_name: 'skip.pdf',
|
||||
document_id: 8,
|
||||
})).toBe('skip.pdf');
|
||||
|
||||
expect(resolveHandlingAffectedRefTarget({ type: 'task', task_no: 'ST-9' })).toEqual({
|
||||
kind: 'task',
|
||||
taskNo: 'ST-9',
|
||||
});
|
||||
expect(resolveHandlingAffectedRefTarget({
|
||||
type: 'candidate',
|
||||
candidate_no: 'C-1',
|
||||
document_id: 3,
|
||||
})).toEqual({
|
||||
kind: 'review',
|
||||
documentId: 3,
|
||||
candidateNo: 'C-1',
|
||||
});
|
||||
|
||||
const rows = listDisplayableHandlingAffectedRefs([
|
||||
{ type: 'task', task_no: 'ST-9' },
|
||||
{ type: 'candidate', candidate_no: 'C-1' },
|
||||
{ type: 'unknown' },
|
||||
]);
|
||||
expect(rows.map((row) => row.label)).toEqual(['ST-9', 'C-1']);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,89 @@
|
||||
/**
|
||||
* features/chat/shipping/orderExtractionHandlingRefs.ts
|
||||
* 用途:Run 级 handling_items.affected_refs 的展示文案与跳转目标解析。
|
||||
* 依赖:无业务 API;由 ShippingOrderExtractionCard / ShippingSessionSummaryPanel 调用。
|
||||
* 逻辑:只消费后端受控引用(task/candidate/document/attachment),禁止前端发明对象标识。
|
||||
*/
|
||||
|
||||
export type ShippingHandlingAffectedRef = Record<string, unknown>;
|
||||
|
||||
export type ShippingHandlingRefTarget =
|
||||
| { kind: 'task'; taskNo: string }
|
||||
| { kind: 'review'; documentId?: number; candidateNo?: string }
|
||||
| { kind: 'none' };
|
||||
|
||||
/**
|
||||
* 从受影响对象引用生成用户可见短标签。
|
||||
* @param ref - 后端 affected_refs 单项
|
||||
* @returns 可读标签;无法识别时返回空串
|
||||
*/
|
||||
export function formatHandlingAffectedRefLabel(ref: ShippingHandlingAffectedRef): string {
|
||||
const type = String(ref.type || '').trim();
|
||||
const taskNo = String(ref.task_no || '').trim();
|
||||
const candidateNo = String(ref.candidate_no || '').trim();
|
||||
const poNumber = String(ref.po_number || '').trim();
|
||||
const fileName = String(ref.file_name || '').trim();
|
||||
const documentId = Number(ref.document_id || 0);
|
||||
if (type === 'task' && taskNo) return taskNo;
|
||||
if (type === 'candidate') {
|
||||
if (candidateNo && poNumber) return `${candidateNo} · ${poNumber}`;
|
||||
if (candidateNo) return candidateNo;
|
||||
if (poNumber) return poNumber;
|
||||
}
|
||||
if (type === 'attachment' && fileName) return fileName;
|
||||
if (type === 'document') {
|
||||
if (fileName) return fileName;
|
||||
if (documentId > 0) return `#${documentId}`;
|
||||
}
|
||||
if (taskNo) return taskNo;
|
||||
if (candidateNo) return candidateNo;
|
||||
if (fileName) return fileName;
|
||||
return '';
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析受影响对象的跳转目标。
|
||||
* @param ref - 后端 affected_refs 单项
|
||||
*/
|
||||
export function resolveHandlingAffectedRefTarget(ref: ShippingHandlingAffectedRef): ShippingHandlingRefTarget {
|
||||
const type = String(ref.type || '').trim();
|
||||
const taskNo = String(ref.task_no || '').trim();
|
||||
const candidateNo = String(ref.candidate_no || '').trim();
|
||||
const documentId = Number(ref.document_id || 0);
|
||||
if ((type === 'task' || !type) && taskNo) {
|
||||
return { kind: 'task', taskNo };
|
||||
}
|
||||
if (type === 'candidate' || type === 'document' || type === 'attachment' || candidateNo || documentId > 0) {
|
||||
return {
|
||||
kind: 'review',
|
||||
documentId: documentId > 0 ? documentId : undefined,
|
||||
candidateNo: candidateNo || undefined,
|
||||
};
|
||||
}
|
||||
return { kind: 'none' };
|
||||
}
|
||||
|
||||
/**
|
||||
* 过滤并截断可展示的受影响对象列表。
|
||||
* @param refs - 原始 affected_refs
|
||||
* @param limit - 最大展示条数
|
||||
*/
|
||||
export function listDisplayableHandlingAffectedRefs(
|
||||
refs: ShippingHandlingAffectedRef[] | null | undefined,
|
||||
limit = 6,
|
||||
): Array<{ key: string; label: string; target: ShippingHandlingRefTarget; ref: ShippingHandlingAffectedRef }> {
|
||||
const rows: Array<{ key: string; label: string; target: ShippingHandlingRefTarget; ref: ShippingHandlingAffectedRef }> = [];
|
||||
for (const [index, ref] of (refs || []).entries()) {
|
||||
if (!ref || typeof ref !== 'object') continue;
|
||||
const label = formatHandlingAffectedRefLabel(ref);
|
||||
if (!label) continue;
|
||||
rows.push({
|
||||
key: `${String(ref.type || 'ref')}-${label}-${index}`,
|
||||
label,
|
||||
target: resolveHandlingAffectedRefTarget(ref),
|
||||
ref,
|
||||
});
|
||||
if (rows.length >= limit) break;
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
/**
|
||||
* features/chat/shipping/orderExtractionProgressDisplay.spec.ts
|
||||
* 用途:校验进度展示纯函数不发明阶段码,并正确格式化耗时。
|
||||
* 依赖:Vitest、orderExtractionProgressDisplay。
|
||||
* 逻辑:覆盖空值、秒/分/小时格式,以及 stage key 回退路径。
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
formatOrderExtractionElapsed,
|
||||
resolveOrderExtractionUserStageKey,
|
||||
} from './orderExtractionProgressDisplay';
|
||||
|
||||
describe('orderExtractionProgressDisplay', () => {
|
||||
it('formats elapsed seconds without inventing ETA', () => {
|
||||
expect(formatOrderExtractionElapsed(null)).toBe('');
|
||||
expect(formatOrderExtractionElapsed(12)).toBe('12s');
|
||||
expect(formatOrderExtractionElapsed(75)).toBe('1m 15s');
|
||||
expect(formatOrderExtractionElapsed(3600)).toBe('1h');
|
||||
});
|
||||
|
||||
it('prefers user_visible_stage over document status for i18n keys', () => {
|
||||
expect(resolveOrderExtractionUserStageKey('extracting', 'pending')).toBe(
|
||||
'chat.shippingOrderExtractionUserStage.extracting',
|
||||
);
|
||||
expect(resolveOrderExtractionUserStageKey(null, 'routing')).toBe(
|
||||
'chat.shippingOrderExtractionDocumentStatus.routing',
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,37 @@
|
||||
/**
|
||||
* features/chat/shipping/orderExtractionProgressDisplay.ts
|
||||
* 用途:订单抽取进度展示的纯函数(阶段文案 key、耗时格式化),禁止前端发明阶段码。
|
||||
* 依赖:无;由 ShippingOrderExtractionCard / ShippingSessionSummaryPanel 调用。
|
||||
* 逻辑:仅映射后端投影字段到 i18n key 与可读耗时;阈值与阶段判定一律以后端为准。
|
||||
*/
|
||||
|
||||
/** 将秒数格式化为「Xm Ys」风格;空值返回空串。 */
|
||||
export function formatOrderExtractionElapsed(seconds: number | null | undefined): string {
|
||||
if (seconds == null) return '';
|
||||
const value = Number(seconds);
|
||||
if (!Number.isFinite(value) || value < 0) return '';
|
||||
const total = Math.floor(value);
|
||||
if (total < 60) return `${total}s`;
|
||||
const minutes = Math.floor(total / 60);
|
||||
const remain = total % 60;
|
||||
if (minutes < 60) return remain > 0 ? `${minutes}m ${remain}s` : `${minutes}m`;
|
||||
const hours = Math.floor(minutes / 60);
|
||||
const mins = minutes % 60;
|
||||
return mins > 0 ? `${hours}h ${mins}m` : `${hours}h`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析用户可见阶段的 i18n key;无投影时回退到文档 status。
|
||||
* @param userVisibleStage - 后端 user_visible_stage
|
||||
* @param documentStatus - 后端 Unit status 兜底
|
||||
*/
|
||||
export function resolveOrderExtractionUserStageKey(
|
||||
userVisibleStage?: string | null,
|
||||
documentStatus?: string | null,
|
||||
): string {
|
||||
const stage = String(userVisibleStage || '').trim();
|
||||
if (stage) return `chat.shippingOrderExtractionUserStage.${stage}`;
|
||||
const status = String(documentStatus || '').trim();
|
||||
if (status) return `chat.shippingOrderExtractionDocumentStatus.${status}`;
|
||||
return 'chat.shippingOrderExtractionActivity.generic_processing';
|
||||
}
|
||||
@@ -68,7 +68,7 @@ describe('shipping notice order extraction state', () => {
|
||||
expect(resolveShippingOrderExtractionStatus(undefined, 'not_started')).toBe('not_started');
|
||||
});
|
||||
|
||||
it('restores only in-progress and retryable attachments into the input area', () => {
|
||||
it('restores only unsubmitted or pre-parse retryable attachments into the input area', () => {
|
||||
expect(shouldRestoreShippingNoticeIntake('queued')).toBe(true);
|
||||
expect(shouldRestoreShippingNoticeIntake('parsing')).toBe(true);
|
||||
expect(shouldRestoreShippingNoticeIntake('parse_failed')).toBe(true);
|
||||
@@ -77,7 +77,8 @@ describe('shipping notice order extraction state', () => {
|
||||
ready_for_extraction: true,
|
||||
attachment_directory_complete: true,
|
||||
})).toBe(true);
|
||||
expect(shouldRestoreShippingNoticeIntake('parsed', 'failed', 0)).toBe(true);
|
||||
// 抽取失败由 Run 状态卡重试,不能将已发送附件重新放回编辑框。
|
||||
expect(shouldRestoreShippingNoticeIntake('parsed', 'failed', 0)).toBe(false);
|
||||
expect(shouldRestoreShippingNoticeIntake('parsed', 'not_started', 0, {
|
||||
preview_status: 'directory_incomplete',
|
||||
ready_for_extraction: false,
|
||||
|
||||
@@ -41,7 +41,7 @@ const ACTIVE_ORDER_EXTRACTION = new Set(['extracting']);
|
||||
* 判断服务端 Intake 是否应恢复到输入栏。
|
||||
* AI 触发时机:无;页面刷新或重新打开会话时调用。
|
||||
* 上传快览与发送授权已拆分:未发送但已快览成功的附件,刷新后也必须恢复到输入栏;
|
||||
* 已进入订单抽取终态(包括待人工复核)的附件仅保留在消息气泡和结果卡中,
|
||||
* 已进入订单抽取终态(包括失败、待人工复核)的附件仅保留在消息气泡和结果卡中,
|
||||
* 避免把已发送的旧批次误带回当前输入框。
|
||||
* @param parseStatus - 服务端返回的预解析状态。
|
||||
* @param orderExtractionStatus - 服务端返回的订单抽取状态。
|
||||
@@ -61,8 +61,7 @@ export function shouldRestoreShippingNoticeIntake(
|
||||
status === 'parsed'
|
||||
&& (!extractionStatus || extractionStatus === 'not_started')
|
||||
&& !isShippingNoticeAttachmentParseIncomplete(parseSummary)
|
||||
)
|
||||
|| extractionStatus === 'failed';
|
||||
);
|
||||
}
|
||||
|
||||
/** 判断 Intake 是否仍需轮询上传预处理或订单抽取状态。 */
|
||||
|
||||
@@ -17,6 +17,8 @@ const api = vi.hoisted(() => ({
|
||||
markSeen: vi.fn(),
|
||||
retryRun: vi.fn(),
|
||||
reparseRun: vi.fn(),
|
||||
cancelRun: vi.fn(),
|
||||
cancelDocument: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('../api/shipping.api', () => ({
|
||||
@@ -26,6 +28,8 @@ vi.mock('../api/shipping.api', () => ({
|
||||
markWorkspaceShippingOrderExtractionRunSeen: api.markSeen,
|
||||
retryWorkspaceShippingOrderExtractionRun: api.retryRun,
|
||||
reparseWorkspaceShippingOrderExtractionRun: api.reparseRun,
|
||||
cancelWorkspaceShippingOrderExtractionRun: api.cancelRun,
|
||||
cancelWorkspaceShippingOrderExtractionDocument: api.cancelDocument,
|
||||
}));
|
||||
|
||||
const run = (patch: Partial<ShippingOrderExtractionRun>): ShippingOrderExtractionRun => ({
|
||||
@@ -69,6 +73,7 @@ const createHarness = () => {
|
||||
loadHistory: vi.fn(async () => undefined),
|
||||
onConversationResolved: vi.fn(async () => undefined),
|
||||
onRetryError: vi.fn(),
|
||||
onSessionWorkItemsRefresh: vi.fn(),
|
||||
t: (key: string) => key,
|
||||
};
|
||||
return { messages, conversationId, options, runs: useShippingOrderExtractionRuns(options) };
|
||||
@@ -165,6 +170,16 @@ describe('useShippingOrderExtractionRuns lifecycle', () => {
|
||||
expect(harness.messages.value[0]?.shipping_order_extraction_state?.status).toBe('processing');
|
||||
});
|
||||
|
||||
it('notifies session work items refresh after restoring a terminal run', async () => {
|
||||
api.listRuns.mockResolvedValue({
|
||||
items: [run({ run_no: 'SNER-DONE', status: 'completed', phase: 'completed' })],
|
||||
});
|
||||
const harness = createHarness();
|
||||
harness.conversationId.value = 'conv-1';
|
||||
await harness.runs.restoreForConversation('conv-1');
|
||||
expect(harness.options.onSessionWorkItemsRefresh).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('aborts a hanging Run query after ten seconds and keeps polling as a transport failure', async () => {
|
||||
api.createRun.mockResolvedValue({ run: run({ run_no: 'SNER-TIMEOUT', conversation_id: 'conv-timeout' }), reused: false });
|
||||
api.getRun.mockImplementation((_runNo: string, signal: AbortSignal) => new Promise((_resolve, reject) => {
|
||||
@@ -320,6 +335,52 @@ describe('mapOrderExtractionRunToMessageState', () => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it('persists again when only handling_items or primary_notice change', async () => {
|
||||
vi.useFakeTimers();
|
||||
const first = run({
|
||||
run_no: 'SNER-HANDLING',
|
||||
status: 'processing',
|
||||
primary_notice: 'candidate_conflict',
|
||||
handling_items: [{
|
||||
category: 'candidate_conflict',
|
||||
count: 1,
|
||||
reason_codes: ['email_supplement_conflict'],
|
||||
affected_refs: [{ type: 'candidate', candidate_no: 'C-1' }],
|
||||
primary_action: 'review_candidate',
|
||||
}],
|
||||
});
|
||||
const second = run({
|
||||
run_no: 'SNER-HANDLING',
|
||||
status: 'processing',
|
||||
primary_notice: 'auto_freeze_blocked',
|
||||
handling_items: [{
|
||||
category: 'auto_freeze_blocked',
|
||||
count: 1,
|
||||
reason_codes: ['profile_not_auto_freeze_approved'],
|
||||
affected_refs: [{ type: 'task', task_no: 'ST-9', candidate_no: 'C-2' }],
|
||||
primary_action: 'view_details',
|
||||
}],
|
||||
});
|
||||
api.listRuns.mockResolvedValue({ items: [first] });
|
||||
api.getRun.mockResolvedValueOnce(second);
|
||||
const harness = createHarness();
|
||||
harness.conversationId.value = 'conv-1';
|
||||
|
||||
await harness.runs.restoreForConversation('conv-1');
|
||||
expect(harness.options.saveLocalMessageToBackend).toHaveBeenCalledTimes(1);
|
||||
await vi.advanceTimersByTimeAsync(1000);
|
||||
|
||||
// 关键断言:处理说明独立变化也必须重新持久化,历史会话才能恢复最新原因与影响对象。
|
||||
expect(harness.options.saveLocalMessageToBackend).toHaveBeenCalledTimes(2);
|
||||
expect(harness.messages.value[0]?.shipping_order_extraction_state?.primaryNotice).toBe('auto_freeze_blocked');
|
||||
expect(harness.messages.value[0]?.shipping_order_extraction_state?.handlingItems?.[0]?.affectedRefs?.[0]).toMatchObject({
|
||||
type: 'task',
|
||||
task_no: 'ST-9',
|
||||
});
|
||||
harness.runs.stopPolling();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it('merges duplicate local cards for one Run when a terminal update arrives', async () => {
|
||||
vi.useFakeTimers();
|
||||
const active = run({ run_no: 'SNER-DUPLICATE', status: 'processing' });
|
||||
|
||||
@@ -2,10 +2,15 @@
|
||||
* features/chat/shipping/useShippingOrderExtractionRuns.ts
|
||||
* 用途:把货代订单抽取作为独立 Run 启动、轮询并投影到聊天状态消息。
|
||||
* 依赖:shipping.api Run 接口、chat.types、Vue refs。
|
||||
* 逻辑:发送处理器调用 startRun;本模块持久化本地消息并轮询 Run;终态后仍保留 run_no 供右侧「本次处理」面板。
|
||||
* 逻辑:发送处理器调用 startRun;本模块持久化本地消息并轮询 Run;终态后仍保留 run_no 供状态卡展示。
|
||||
* 右侧「本次处理」列表由 session-work-items API 驱动,本模块仅在终态/重识别后触发其刷新。
|
||||
* 轮询前台 2s / 后台 5–10s;取消走请求语义 API,刷新为只读 GET。
|
||||
* 持久化去重签名必须包含 handling_items / primary_notice,避免处理说明变化后历史会话仍读到旧卡。
|
||||
*/
|
||||
import { getCurrentInstance, onBeforeUnmount, type ComputedRef, type Ref } from 'vue';
|
||||
import {
|
||||
cancelWorkspaceShippingOrderExtractionDocument,
|
||||
cancelWorkspaceShippingOrderExtractionRun,
|
||||
createWorkspaceShippingOrderExtractionRun,
|
||||
getWorkspaceShippingOrderExtractionRun,
|
||||
listWorkspaceShippingOrderExtractionRuns,
|
||||
@@ -31,10 +36,25 @@ interface UseShippingOrderExtractionRunsOptions {
|
||||
loadHistory: () => Promise<void>;
|
||||
onConversationResolved: (conversationId: string) => Promise<void> | void;
|
||||
onRetryError: (message: string) => void;
|
||||
/** 终态/重识别/恢复后通知右侧面板立即刷新会话工作项。 */
|
||||
onSessionWorkItemsRefresh?: () => void;
|
||||
t: (key: string, params?: Record<string, unknown>) => string;
|
||||
}
|
||||
|
||||
const ACTIVE_RUN_STATUSES = new Set(['queued', 'processing']);
|
||||
const FOREGROUND_POLL_MS = 2000;
|
||||
const BACKGROUND_POLL_MS = 8000;
|
||||
|
||||
/** 按页面可见性选择轮询间隔;后台放慢,失败退避另算。 */
|
||||
function resolvePollIntervalMs(failureCount = 0): number {
|
||||
if (failureCount > 0) {
|
||||
return Math.min(15000, 2000 * (2 ** Math.min(failureCount, 3)));
|
||||
}
|
||||
if (typeof document !== 'undefined' && document.visibilityState === 'hidden') {
|
||||
return BACKGROUND_POLL_MS;
|
||||
}
|
||||
return FOREGROUND_POLL_MS;
|
||||
}
|
||||
|
||||
/** 把领域 Run 转为聊天组件既有的订单抽取状态卡契约。 */
|
||||
export function mapOrderExtractionRunToMessageState(run: ShippingOrderExtractionRun): ShippingOrderExtractionState {
|
||||
@@ -47,6 +67,7 @@ export function mapOrderExtractionRunToMessageState(run: ShippingOrderExtraction
|
||||
completedDocuments: Number(run.summary?.completed_documents || 0),
|
||||
reviewRequiredDocuments: Number(run.summary?.review_required_documents || 0),
|
||||
failedDocuments: Number(run.summary?.failed_documents || 0),
|
||||
cancelledDocuments: Number(run.summary?.cancelled_documents || 0),
|
||||
candidateCount: Number(run.summary?.candidate_count || 0),
|
||||
openedExistingCount: Number(
|
||||
run.summary?.opened_existing_documents
|
||||
@@ -59,12 +80,17 @@ export function mapOrderExtractionRunToMessageState(run: ShippingOrderExtraction
|
||||
unitId: Number(run.current_activity.unit_id || 0),
|
||||
fileName: run.current_activity.file_name || null,
|
||||
eventCode: String(run.current_activity.event_code || ''),
|
||||
userVisibleStage: run.current_activity.user_visible_stage || null,
|
||||
selectionBatch: run.current_activity.selection_batch != null
|
||||
? Number(run.current_activity.selection_batch || 0) || null
|
||||
: null,
|
||||
reasonCodes: Array.isArray(run.current_activity.reason_codes)
|
||||
? run.current_activity.reason_codes.map((item) => String(item || '').trim()).filter(Boolean)
|
||||
: [],
|
||||
elapsedSeconds: run.current_activity.elapsed_seconds != null
|
||||
? Number(run.current_activity.elapsed_seconds)
|
||||
: null,
|
||||
lastActivityAt: run.current_activity.last_activity_at || null,
|
||||
}
|
||||
: null,
|
||||
selectionPlan: run.selection_plan
|
||||
@@ -108,6 +134,41 @@ export function mapOrderExtractionRunToMessageState(run: ShippingOrderExtraction
|
||||
}
|
||||
: null,
|
||||
availableActions: Array.isArray(run.available_actions) ? [...run.available_actions] : [],
|
||||
handlingItems: Array.isArray(run.handling_items)
|
||||
? run.handling_items.map((item) => ({
|
||||
category: String(item.category || '').trim(),
|
||||
count: Number(item.count || 0),
|
||||
reasonCodes: Array.isArray(item.reason_codes)
|
||||
? item.reason_codes.map((code) => String(code || '').trim()).filter(Boolean)
|
||||
: [],
|
||||
affectedRefs: Array.isArray(item.affected_refs)
|
||||
? item.affected_refs.filter((ref): ref is Record<string, unknown> => Boolean(ref) && typeof ref === 'object')
|
||||
: [],
|
||||
primaryAction: item.primary_action || null,
|
||||
})).filter((item) => item.category)
|
||||
: [],
|
||||
primaryNotice: run.primary_notice || null,
|
||||
userVisibleStage: run.user_visible_stage || null,
|
||||
healthTips: Array.isArray(run.health_tips)
|
||||
? run.health_tips.map((tip) => ({
|
||||
code: tip.code,
|
||||
thresholdSeconds: Number(tip.threshold_seconds || 0),
|
||||
idleOrElapsedSeconds: Number(tip.idle_or_elapsed_seconds || 0),
|
||||
}))
|
||||
: [],
|
||||
cancellation: run.cancellation
|
||||
? {
|
||||
requested: Boolean(run.cancellation.requested),
|
||||
requestedAt: run.cancellation.requested_at || null,
|
||||
completedAt: run.cancellation.completed_at || null,
|
||||
actorType: run.cancellation.actor_type || null,
|
||||
actorId: run.cancellation.actor_id || null,
|
||||
reason: run.cancellation.reason || null,
|
||||
reasonCode: run.cancellation.reason_code || null,
|
||||
}
|
||||
: null,
|
||||
progressVersion: run.progress_version != null ? Number(run.progress_version) : null,
|
||||
lastActivityAt: run.last_activity_at || null,
|
||||
terminal: !ACTIVE_RUN_STATUSES.has(run.status),
|
||||
refreshFailed: false,
|
||||
errorCode: run.error?.code || null,
|
||||
@@ -202,6 +263,11 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
|
||||
summary: run.summary,
|
||||
current_activity: run.current_activity,
|
||||
available_actions: run.available_actions,
|
||||
handling_items: run.handling_items,
|
||||
primary_notice: run.primary_notice,
|
||||
health_tips: run.health_tips,
|
||||
cancellation: run.cancellation,
|
||||
progress_version: run.progress_version,
|
||||
result: run.result,
|
||||
error: run.error,
|
||||
reparse: run.reparse,
|
||||
@@ -259,6 +325,7 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
|
||||
// Run 状态卡已持久化;工作台可由页面下一次刷新继续恢复。
|
||||
}
|
||||
await Promise.allSettled([options.loadHistory()]);
|
||||
options.onSessionWorkItemsRefresh?.();
|
||||
return reviewAttachments;
|
||||
};
|
||||
|
||||
@@ -299,13 +366,12 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
|
||||
await upsertRunMessage(run);
|
||||
await acknowledgeTerminalRunWhenVisible(run);
|
||||
if (generation !== pollGeneration || activeRunNo !== runNo) return;
|
||||
pollTimer = setTimeout(() => void pollRun(run.run_no, generation), 2000);
|
||||
pollTimer = setTimeout(() => void pollRun(run.run_no, generation), resolvePollIntervalMs(0));
|
||||
} catch {
|
||||
if (generation !== pollGeneration || activeRunNo !== runNo) return;
|
||||
pollFailureCount += 1;
|
||||
setRunRefreshFailed(runNo, true);
|
||||
const delayMs = Math.min(15000, 2000 * (2 ** Math.min(pollFailureCount, 3)));
|
||||
pollTimer = setTimeout(() => void pollRun(runNo, generation), delayMs);
|
||||
pollTimer = setTimeout(() => void pollRun(runNo, generation), resolvePollIntervalMs(pollFailureCount));
|
||||
}
|
||||
};
|
||||
|
||||
@@ -317,6 +383,18 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
|
||||
pollTimer = setTimeout(() => void pollRun(runNo, generation), delayMs);
|
||||
};
|
||||
|
||||
/**
|
||||
* 前台恢复时立刻拉一次,避免后台节流后状态滞后。
|
||||
*/
|
||||
const onVisibilityChange = () => {
|
||||
if (typeof document === 'undefined' || document.visibilityState !== 'visible') return;
|
||||
if (!activeRunNo || !pollTimer) return;
|
||||
const runNo = activeRunNo;
|
||||
const generation = pollGeneration;
|
||||
if (pollTimer) clearTimeout(pollTimer);
|
||||
pollTimer = setTimeout(() => void pollRun(runNo, generation), 0);
|
||||
};
|
||||
|
||||
/**
|
||||
* 启动订单抽取后台 Run,并把用户操作和状态卡持久化到本地会话。
|
||||
* @param query - 用户本次备注;允许为空,不发送给 Dify Chatflow。
|
||||
@@ -376,6 +454,7 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
|
||||
await upsertRunMessage(response.run);
|
||||
await acknowledgeTerminalRunWhenVisible(response.run);
|
||||
await Promise.allSettled([options.refreshNoticeIntakeStatuses()]);
|
||||
options.onSessionWorkItemsRefresh?.();
|
||||
if (ACTIVE_RUN_STATUSES.has(response.run.status)) {
|
||||
beginPolling(response.run.run_no, 1000);
|
||||
}
|
||||
@@ -386,6 +465,94 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 只读刷新当前 Run 投影;不改变业务状态,失败仅标记 refreshFailed。
|
||||
* @param runNo - 目标 Run 编号。
|
||||
*/
|
||||
const refreshRun = async (runNo: string): Promise<boolean> => {
|
||||
const normalizedRunNo = String(runNo || '').trim();
|
||||
if (!normalizedRunNo) return false;
|
||||
try {
|
||||
const run = await getWorkspaceShippingOrderExtractionRun(normalizedRunNo);
|
||||
setRunRefreshFailed(run.run_no, false);
|
||||
if (!ACTIVE_RUN_STATUSES.has(run.status)) {
|
||||
const reviewAttachments = await refreshTerminalFacts(run);
|
||||
await upsertRunMessage(run, reviewAttachments);
|
||||
await acknowledgeTerminalRunWhenVisible(run);
|
||||
return true;
|
||||
}
|
||||
await upsertRunMessage(run);
|
||||
if (activeRunNo !== run.run_no || !pollTimer) beginPolling(run.run_no, FOREGROUND_POLL_MS);
|
||||
return true;
|
||||
} catch (error) {
|
||||
setRunRefreshFailed(normalizedRunNo, true);
|
||||
options.onRetryError(error instanceof Error ? error.message : options.t('chat.shippingOrderExtractionRefreshFailed'));
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 请求取消整批;排队 Unit 立即取消,执行中进入 cancellation_requested。
|
||||
* @param runNo - 目标 Run。
|
||||
* @param reason - 可选原因;管理员取消他人时由调用方保证非空。
|
||||
*/
|
||||
const cancelRun = async (runNo: string, reason?: string | null): Promise<boolean> => {
|
||||
const normalizedRunNo = String(runNo || '').trim();
|
||||
if (!normalizedRunNo) return false;
|
||||
try {
|
||||
const response = await cancelWorkspaceShippingOrderExtractionRun(normalizedRunNo, {
|
||||
reason: reason || null,
|
||||
});
|
||||
const run = response.run;
|
||||
await upsertRunMessage(run);
|
||||
await acknowledgeTerminalRunWhenVisible(run);
|
||||
if (ACTIVE_RUN_STATUSES.has(run.status)) {
|
||||
beginPolling(run.run_no, 1000);
|
||||
} else {
|
||||
stopPolling();
|
||||
activeRunNo = run.run_no;
|
||||
const reviewAttachments = await refreshTerminalFacts(run);
|
||||
await upsertRunMessage(run, reviewAttachments);
|
||||
}
|
||||
return true;
|
||||
} catch (error) {
|
||||
options.onRetryError(error instanceof Error ? error.message : options.t('chat.shippingOrderExtractionCancel.failed'));
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 请求取消单个 PDF Unit。
|
||||
* @param runNo - 所属 Run。
|
||||
* @param documentId - 目标文档 ID。
|
||||
* @param reason - 可选原因。
|
||||
*/
|
||||
const cancelUnit = async (
|
||||
runNo: string,
|
||||
documentId: number,
|
||||
reason?: string | null,
|
||||
): Promise<boolean> => {
|
||||
const normalizedRunNo = String(runNo || '').trim();
|
||||
const normalizedDocId = Number(documentId || 0);
|
||||
if (!normalizedRunNo || !normalizedDocId) return false;
|
||||
try {
|
||||
const response = await cancelWorkspaceShippingOrderExtractionDocument(normalizedRunNo, normalizedDocId, {
|
||||
reason: reason || null,
|
||||
});
|
||||
if (response.run) {
|
||||
await upsertRunMessage(response.run);
|
||||
await acknowledgeTerminalRunWhenVisible(response.run);
|
||||
if (ACTIVE_RUN_STATUSES.has(response.run.status)) {
|
||||
beginPolling(response.run.run_no, 1000);
|
||||
}
|
||||
}
|
||||
return true;
|
||||
} catch (error) {
|
||||
options.onRetryError(error instanceof Error ? error.message : options.t('chat.shippingOrderExtractionCancel.failed'));
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
/** 创建新版识别 Run;旧版本保持审计只读,轮询自动转向新的 Run 编号。 */
|
||||
const reparseRun = async (
|
||||
runNo: string,
|
||||
@@ -402,6 +569,7 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
|
||||
await upsertRunMessage(response.run);
|
||||
await acknowledgeTerminalRunWhenVisible(response.run);
|
||||
await Promise.allSettled([options.refreshNoticeIntakeStatuses(), options.refreshShippingActions()]);
|
||||
options.onSessionWorkItemsRefresh?.();
|
||||
if (ACTIVE_RUN_STATUSES.has(response.run.status)) beginPolling(response.run.run_no, 1000);
|
||||
return true;
|
||||
} catch (error) {
|
||||
@@ -432,7 +600,7 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
|
||||
}));
|
||||
};
|
||||
|
||||
/** 刷新或进入既有会话时恢复最新 Run;活动 Run 继续轮询,终态只恢复状态卡并保留 run_no 供右侧面板。 */
|
||||
/** 刷新或进入既有会话时恢复最新 Run 状态卡;活动 Run 继续轮询。右侧面板列表由 session-work-items 独立恢复。 */
|
||||
const restoreForConversation = async (conversationId: string): Promise<void> => {
|
||||
clearActiveRun();
|
||||
try {
|
||||
@@ -449,6 +617,7 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
|
||||
if (options.conversationId.value !== conversationId) return;
|
||||
await upsertRunMessage(latest, reviewAttachments);
|
||||
await acknowledgeTerminalRunWhenVisible(latest);
|
||||
options.onSessionWorkItemsRefresh?.();
|
||||
if (options.conversationId.value !== conversationId) return;
|
||||
if (ACTIVE_RUN_STATUSES.has(latest.status)) {
|
||||
beginPolling(latest.run_no, 1000);
|
||||
@@ -458,10 +627,23 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
|
||||
}
|
||||
};
|
||||
|
||||
if (getCurrentInstance()) onBeforeUnmount(clearActiveRun);
|
||||
if (typeof document !== 'undefined') {
|
||||
document.addEventListener('visibilitychange', onVisibilityChange);
|
||||
}
|
||||
if (getCurrentInstance()) {
|
||||
onBeforeUnmount(() => {
|
||||
if (typeof document !== 'undefined') {
|
||||
document.removeEventListener('visibilitychange', onVisibilityChange);
|
||||
}
|
||||
clearActiveRun();
|
||||
});
|
||||
}
|
||||
return {
|
||||
startRun,
|
||||
retryRun,
|
||||
refreshRun,
|
||||
cancelRun,
|
||||
cancelUnit,
|
||||
reparseRun,
|
||||
restoreForConversation,
|
||||
stopPolling,
|
||||
|
||||
@@ -37,17 +37,41 @@ export interface ShippingOrderExtractionStateSummary {
|
||||
completedDocuments: number;
|
||||
reviewRequiredDocuments: number;
|
||||
failedDocuments: number;
|
||||
/** 已取消 PDF 份数;由后端投影,前端不得自行推算 */
|
||||
cancelledDocuments?: number;
|
||||
candidateCount: number;
|
||||
/** 解析阶段已关联已有任务的份数(open_existing) */
|
||||
openedExistingCount?: number;
|
||||
}
|
||||
|
||||
/** 健康提示;阈值与判定一律以后端投影为准。 */
|
||||
export interface ShippingOrderExtractionHealthTipState {
|
||||
code: 'processing_slow' | 'queue_backlog' | 'processing_attention';
|
||||
thresholdSeconds: number;
|
||||
idleOrElapsedSeconds: number;
|
||||
}
|
||||
|
||||
/** 取消请求元数据投影(请求语义,非即时终态)。 */
|
||||
export interface ShippingOrderExtractionCancellationState {
|
||||
requested: boolean;
|
||||
requestedAt?: string | null;
|
||||
completedAt?: string | null;
|
||||
actorType?: 'user' | 'admin' | 'system' | null;
|
||||
actorId?: string | null;
|
||||
reason?: string | null;
|
||||
reasonCode?: string | null;
|
||||
}
|
||||
|
||||
export interface ShippingOrderExtractionCurrentActivityState {
|
||||
unitId: number;
|
||||
fileName?: string | null;
|
||||
eventCode: string;
|
||||
/** 用户可见业务阶段码;文案走 shippingOrderExtractionUserStage.* */
|
||||
userVisibleStage?: string | null;
|
||||
selectionBatch?: number | null;
|
||||
reasonCodes?: string[];
|
||||
elapsedSeconds?: number | null;
|
||||
lastActivityAt?: string | null;
|
||||
}
|
||||
|
||||
export interface ShippingOrderExtractionSelectionPlanState {
|
||||
@@ -82,6 +106,15 @@ export interface ShippingOrderExtractionUnitSummaryState {
|
||||
technicalFailureReasonCodes?: string[];
|
||||
}
|
||||
|
||||
/** Run 级待处理事项;由后端投影,前端按 category 展示原因与跳转。 */
|
||||
export interface ShippingOrderExtractionHandlingItemState {
|
||||
category: string;
|
||||
count: number;
|
||||
reasonCodes: string[];
|
||||
affectedRefs: Array<Record<string, unknown>>;
|
||||
primaryAction?: string | null;
|
||||
}
|
||||
|
||||
export interface ShippingOrderExtractionState {
|
||||
status: ShippingOrderExtractionStateStatus;
|
||||
summary: ShippingOrderExtractionStateSummary;
|
||||
@@ -89,6 +122,16 @@ export interface ShippingOrderExtractionState {
|
||||
selectionPlan?: ShippingOrderExtractionSelectionPlanState | null;
|
||||
unitSummary?: ShippingOrderExtractionUnitSummaryState | null;
|
||||
availableActions: string[];
|
||||
/** Run 级拆分后的处理事项(待补/冲突/冻结/复核/失败等)。 */
|
||||
handlingItems?: ShippingOrderExtractionHandlingItemState[];
|
||||
/** 优先级最高的处理事项类别,供一句过程通知。 */
|
||||
primaryNotice?: string | null;
|
||||
/** Run 级用户可见阶段;无 currentActivity 时供进度卡兜底。 */
|
||||
userVisibleStage?: string | null;
|
||||
healthTips?: ShippingOrderExtractionHealthTipState[];
|
||||
cancellation?: ShippingOrderExtractionCancellationState | null;
|
||||
progressVersion?: number | null;
|
||||
lastActivityAt?: string | null;
|
||||
terminal: boolean;
|
||||
refreshFailed?: boolean;
|
||||
errorCode?: string | null;
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
* 用途:货代发货 Agent / 工作台 API 请求与响应契约类型。
|
||||
* 依赖:无(纯类型模块)。
|
||||
* 逻辑:shipping.api.ts 与 Chat/工作台组件统一引用本文件 DTO 类型。
|
||||
* 阶段 0 冻结用户可见阶段、健康提示、取消元数据与审计 DTO;写路径与 UI 在后续阶段启用。
|
||||
*/
|
||||
export type InventorySourceStatus =
|
||||
| 'unresolved'
|
||||
@@ -669,6 +670,48 @@ export type ShippingOrderExtractionDocumentStatus =
|
||||
| 'failed'
|
||||
| 'cancelled';
|
||||
|
||||
/** 后端投影的用户可见阶段;前端禁止用本地时钟或猜测重算。 */
|
||||
export type ShippingOrderExtractionUserVisibleStage =
|
||||
| 'pending'
|
||||
| 'document_queued'
|
||||
| 'waiting_layout'
|
||||
| 'layout_parsing_started'
|
||||
| 'routing'
|
||||
| 'matching_profile'
|
||||
| 'extracting'
|
||||
| 'merging_supplement'
|
||||
| 'candidate_ready'
|
||||
| 'review_required'
|
||||
| 'technical_retrying'
|
||||
| 'failed'
|
||||
| 'cancellation_requested'
|
||||
| 'cancelled'
|
||||
| 'completed';
|
||||
|
||||
/** 健康提示码;阈值由后端统一计算。 */
|
||||
export type ShippingOrderExtractionHealthTipCode =
|
||||
| 'processing_slow'
|
||||
| 'queue_backlog'
|
||||
| 'processing_attention';
|
||||
|
||||
export type ShippingOrderExtractionCancelActorType = 'user' | 'admin' | 'system';
|
||||
|
||||
export interface ShippingOrderExtractionHealthTip {
|
||||
code: ShippingOrderExtractionHealthTipCode;
|
||||
threshold_seconds: number;
|
||||
idle_or_elapsed_seconds: number;
|
||||
}
|
||||
|
||||
export interface ShippingOrderExtractionCancellation {
|
||||
requested: boolean;
|
||||
requested_at?: string | null;
|
||||
completed_at?: string | null;
|
||||
actor_type?: ShippingOrderExtractionCancelActorType | null;
|
||||
actor_id?: string | null;
|
||||
reason?: string | null;
|
||||
reason_code?: string | null;
|
||||
}
|
||||
|
||||
export interface ShippingOrderExtractionRunSummary {
|
||||
total_documents: number;
|
||||
pending_documents: number;
|
||||
@@ -676,6 +719,7 @@ export interface ShippingOrderExtractionRunSummary {
|
||||
completed_documents: number;
|
||||
review_required_documents: number;
|
||||
failed_documents: number;
|
||||
cancelled_documents?: number;
|
||||
candidate_count: number;
|
||||
opened_existing_documents?: number;
|
||||
}
|
||||
@@ -684,8 +728,11 @@ export interface ShippingOrderExtractionCurrentActivity {
|
||||
unit_id: number;
|
||||
file_name?: string | null;
|
||||
event_code: string;
|
||||
user_visible_stage?: ShippingOrderExtractionUserVisibleStage | null;
|
||||
selection_batch?: number | null;
|
||||
reason_codes?: string[];
|
||||
elapsed_seconds?: number | null;
|
||||
last_activity_at?: string | null;
|
||||
}
|
||||
|
||||
export interface ShippingOrderExtractionProfileSummary {
|
||||
@@ -707,6 +754,12 @@ export interface ShippingOrderExtractionDocumentResult {
|
||||
document_id: number;
|
||||
file_name?: string | null;
|
||||
status: ShippingOrderExtractionDocumentStatus;
|
||||
user_visible_stage?: ShippingOrderExtractionUserVisibleStage | null;
|
||||
queue_position?: number | null;
|
||||
elapsed_seconds?: number | null;
|
||||
health_tips?: ShippingOrderExtractionHealthTip[];
|
||||
cancellation?: ShippingOrderExtractionCancellation | null;
|
||||
activity_version?: number | null;
|
||||
selection_batch?: number | null;
|
||||
group_key?: string | null;
|
||||
retry_status?: string | null;
|
||||
@@ -787,6 +840,20 @@ export interface ShippingOrderExtractionRun {
|
||||
} | null;
|
||||
current_activity?: ShippingOrderExtractionCurrentActivity | null;
|
||||
available_actions: string[];
|
||||
/** Run 级处理事项;聊天卡与右侧「本次处理」按类别展示。 */
|
||||
handling_items?: Array<{
|
||||
category: string;
|
||||
count: number;
|
||||
reason_codes?: string[];
|
||||
affected_refs?: Array<Record<string, unknown>>;
|
||||
primary_action?: string | null;
|
||||
}>;
|
||||
primary_notice?: string | null;
|
||||
user_visible_stage?: ShippingOrderExtractionUserVisibleStage | null;
|
||||
health_tips?: ShippingOrderExtractionHealthTip[];
|
||||
cancellation?: ShippingOrderExtractionCancellation | null;
|
||||
progress_version?: number | null;
|
||||
last_activity_at?: string | null;
|
||||
result?: {
|
||||
batch_no?: string | null;
|
||||
created_count?: number;
|
||||
@@ -794,6 +861,9 @@ export interface ShippingOrderExtractionRun {
|
||||
pending_count?: number;
|
||||
non_shipping_count?: number;
|
||||
created_with_missing_fields_count?: number;
|
||||
pending_orders?: Array<Record<string, unknown>>;
|
||||
auto_freeze?: Record<string, unknown>;
|
||||
budget_stopped?: boolean;
|
||||
} | null;
|
||||
// 用户态 Run 契约只暴露稳定错误码;错误正文留在服务端管理员诊断边界。
|
||||
error?: { code?: string | null } | null;
|
||||
@@ -813,6 +883,82 @@ export interface ShippingOrderExtractionProgressEvent {
|
||||
occurred_at: string;
|
||||
}
|
||||
|
||||
export interface ShippingOrderExtractionCancelRequest {
|
||||
reason?: string | null;
|
||||
reason_code?: string | null;
|
||||
expected_progress_version?: number | null;
|
||||
}
|
||||
|
||||
export interface ShippingOrderExtractionUnitCancelRequest {
|
||||
reason?: string | null;
|
||||
reason_code?: string | null;
|
||||
expected_activity_version?: number | null;
|
||||
}
|
||||
|
||||
/** 管理员审计查询与详情 DTO;禁止包含正文、密钥或对象存储 URL。 */
|
||||
export type ShippingAuditActorType = 'user' | 'system' | 'rpa' | 'chatflow' | 'admin';
|
||||
export type ShippingAuditResult = 'success' | 'failure' | 'rejected' | 'ignored';
|
||||
|
||||
export interface ShippingAuditEvidenceRef {
|
||||
file_asset_id?: number | null;
|
||||
content_sha256?: string | null;
|
||||
version?: number | null;
|
||||
page_no?: number | null;
|
||||
table_id?: string | null;
|
||||
cell_id?: string | null;
|
||||
}
|
||||
|
||||
export interface ShippingAuditEvent {
|
||||
event_id: number;
|
||||
event_type: string;
|
||||
occurred_at: string;
|
||||
actor_type: ShippingAuditActorType;
|
||||
actor_id?: string | null;
|
||||
actor_role?: string | null;
|
||||
request_id?: string | null;
|
||||
operation_id?: string | null;
|
||||
source?: string | null;
|
||||
result?: ShippingAuditResult | null;
|
||||
error_code?: string | null;
|
||||
aggregate_type: string;
|
||||
aggregate_id: string;
|
||||
conversation_id?: string | null;
|
||||
run_no?: string | null;
|
||||
unit_id?: string | null;
|
||||
document_id?: string | null;
|
||||
review_case_no?: string | null;
|
||||
task_no?: string | null;
|
||||
attempt_no?: number | null;
|
||||
action?: string | null;
|
||||
reason?: string | null;
|
||||
reason_code?: string | null;
|
||||
before_snapshot?: Record<string, unknown> | null;
|
||||
after_snapshot?: Record<string, unknown> | null;
|
||||
evidence_refs?: ShippingAuditEvidenceRef[];
|
||||
artifact_refs?: ShippingAuditEvidenceRef[];
|
||||
context_refs?: Record<string, unknown> | null;
|
||||
}
|
||||
|
||||
export interface ShippingAuditEventQuery {
|
||||
from?: string | null;
|
||||
to?: string | null;
|
||||
actor_id?: string | null;
|
||||
run_no?: string | null;
|
||||
task_no?: string | null;
|
||||
document_id?: string | null;
|
||||
event_type?: string | null;
|
||||
result?: ShippingAuditResult | null;
|
||||
request_id?: string | null;
|
||||
operation_id?: string | null;
|
||||
before_id?: number | null;
|
||||
limit?: number;
|
||||
}
|
||||
|
||||
export interface ShippingAuditEventListResponse {
|
||||
items: ShippingAuditEvent[];
|
||||
next_before_id?: number | null;
|
||||
}
|
||||
|
||||
export interface ShippingOrderExtractionRunCreateResponse {
|
||||
run: ShippingOrderExtractionRun;
|
||||
reused: boolean;
|
||||
@@ -845,6 +991,7 @@ export interface ShippingOrderReviewCaseSummary {
|
||||
|
||||
export interface ShippingOrderReviewRun {
|
||||
run_no: string;
|
||||
superseded_by_run_no?: string | null;
|
||||
summary: Record<string, number>;
|
||||
items: ShippingOrderReviewCaseSummary[];
|
||||
}
|
||||
@@ -981,6 +1128,71 @@ export interface ShippingDuplicateResult {
|
||||
|
||||
export interface ShippingCreateBatchFromIntakesResponse extends ShippingNoticeUploadResponse {}
|
||||
|
||||
/** 会话 PDF 工作项生命周期;禁止前端按最新 Run 推断。 */
|
||||
export type ShippingSessionWorkItemLifecycleStatus =
|
||||
| 'pending_review'
|
||||
| 'extracting'
|
||||
| 'reparse_failed'
|
||||
| 'closed';
|
||||
|
||||
export type ShippingSessionWorkItemClosedReason =
|
||||
| 'confirmed'
|
||||
| 'non_order'
|
||||
| 'user_cancelled'
|
||||
| 'admin_terminated';
|
||||
|
||||
/** 单条会话 PDF 工作项摘要;右侧「本次处理」行模型。 */
|
||||
export interface ShippingSessionWorkItem {
|
||||
item_no: string;
|
||||
conversation_id: string;
|
||||
owner_user_id: number;
|
||||
root_document_id: number;
|
||||
current_document_id: number;
|
||||
current_document_filename?: string | null;
|
||||
current_run_id?: number | null;
|
||||
current_run_no?: string | null;
|
||||
current_case_id?: number | null;
|
||||
current_case_no?: string | null;
|
||||
current_version_no: number;
|
||||
lifecycle_status: ShippingSessionWorkItemLifecycleStatus | string;
|
||||
closed_reason?: ShippingSessionWorkItemClosedReason | string | null;
|
||||
closed_at?: string | null;
|
||||
lock_version: number;
|
||||
version_replaced?: boolean;
|
||||
previous_case_hint?: string | null;
|
||||
available_actions: string[];
|
||||
created_at?: string | null;
|
||||
updated_at?: string | null;
|
||||
}
|
||||
|
||||
/** 工作项版本历史行;只读时间线投影。 */
|
||||
export interface ShippingSessionWorkItemVersion {
|
||||
case_no: string;
|
||||
case_status?: string | null;
|
||||
run_id?: number | null;
|
||||
document_id?: number | null;
|
||||
document_filename?: string | null;
|
||||
is_current?: boolean;
|
||||
is_readonly?: boolean;
|
||||
version_label?: string | null;
|
||||
created_at?: string | null;
|
||||
confirmed_at?: string | null;
|
||||
}
|
||||
|
||||
/** 会话工作台聚合读模型;open_items / closed_items 为唯一列表事实源。 */
|
||||
export interface ShippingSessionWorkItemSummary {
|
||||
conversation_id: string;
|
||||
open_count: number;
|
||||
closed_count: number;
|
||||
pending_review_count: number;
|
||||
extracting_count: number;
|
||||
open_items: ShippingSessionWorkItem[];
|
||||
closed_items: ShippingSessionWorkItem[];
|
||||
closed_collapsed: boolean;
|
||||
max_open_items: number;
|
||||
truncated?: boolean;
|
||||
}
|
||||
|
||||
export interface ShippingDecisionResponse {
|
||||
status: string;
|
||||
message?: string;
|
||||
|
||||
@@ -1,31 +1,99 @@
|
||||
<!--
|
||||
用途:提供按 PDF 独立处理的建单前订单人工复核工作台。
|
||||
依赖:路由参数、复核 composable、冻结 Schema DTO、受控 PDF 预览组件。
|
||||
逻辑:复用聊天壳的历史侧栏;中心维护订单单头和表格化单身,右侧固定 PDF/证据检查器;处置、重识别及确认建单均只消费当前 Case Draft。
|
||||
用途:提供按 PDF 独立处理的建单前订单人工复核工作台(阶段 3:工作项版本中心)。
|
||||
依赖:路由参数、复核 composable、ReviewDocumentPreview、ReviewVersionHistoryPanel、ReviewActionConfirmDialog。
|
||||
逻辑:左侧 PDF 原件预览 + 字段证据定位;中部编辑;右侧版本历史;破坏性操作(含质量异常)二次确认;历史版本强制只读。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, ref, watch } from 'vue';
|
||||
import { useRoute, useRouter } from 'vue-router';
|
||||
import { ArrowLeft, Copy, FileText, MapPin, Plus, RefreshCw, Save, Trash2, TriangleAlert, Undo2 } from 'lucide-vue-next';
|
||||
import { ArrowLeft, Crosshair, ExternalLink, Plus, RefreshCw, Save, TriangleAlert, Undo2, Copy, Trash2 } from 'lucide-vue-next';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { BusinessError } from '@/shared/api/client';
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
import { useIsMobile } from '@/shared/composables/useIsMobile';
|
||||
import DeleteConfirmDialog from '@/shared/components/DeleteConfirmDialog.vue';
|
||||
import { useChatPageContext } from '@/features/chat/composables/chat.context';
|
||||
import { useShippingOrderReview } from '../shipping-review/useShippingOrderReview';
|
||||
import ReviewActionConfirmDialog, {
|
||||
type ReviewConfirmAction,
|
||||
type ReviewConfirmPayload,
|
||||
} from '../components/shipping-review/ReviewActionConfirmDialog.vue';
|
||||
import ReviewDocumentPreview from '../components/shipping-review/ReviewDocumentPreview.vue';
|
||||
import ReviewVersionHistoryPanel from '../components/shipping-review/ReviewVersionHistoryPanel.vue';
|
||||
import { useShippingOrderReview } from '../shipping-review/useShippingOrderReview';
|
||||
import type { ShippingOrderReviewEvidence } from '../types/shipping.api.types';
|
||||
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
const page = useChatPageContext();
|
||||
const { t } = useI18n();
|
||||
const { reviewRun, activeCase, evidence, previewUrl, loading, loadFailed, saving, saveFailed, load, selectCase, patchHeader, patchLine, addLine, copyLine, deleteLine, validate, confirm, createManualDraft, markNonOrder, markQualityIssue, reparseDocument, uploadReplacement } = useShippingOrderReview();
|
||||
const { t, te } = useI18n();
|
||||
const {
|
||||
reviewRun,
|
||||
activeCase,
|
||||
workItem,
|
||||
versions,
|
||||
statusMessage,
|
||||
isViewingHistoricalVersion,
|
||||
loading,
|
||||
loadFailed,
|
||||
saving,
|
||||
saveFailed,
|
||||
versionsLoading,
|
||||
evidence,
|
||||
previewUrl,
|
||||
load,
|
||||
selectCase,
|
||||
refreshWorkItemContext,
|
||||
openCurrentVersion,
|
||||
patchHeader,
|
||||
patchLine,
|
||||
addLine,
|
||||
copyLine,
|
||||
deleteLine,
|
||||
validate,
|
||||
confirm,
|
||||
createManualDraft,
|
||||
markNonOrder,
|
||||
markQualityIssue,
|
||||
reparseDocument,
|
||||
uploadReplacement,
|
||||
editable,
|
||||
} = useShippingOrderReview();
|
||||
const msg = useMessage();
|
||||
const { isMobile } = useIsMobile();
|
||||
/** 新模式从 query 读取 run_no;保留旧路径参数以兼容已收藏的复核链接。 */
|
||||
|
||||
const runNo = computed(() => String(route.query.run_no || route.params.runNo || ''));
|
||||
const agentId = computed(() => String(route.params.agentId || ''));
|
||||
const conversationId = computed(() => String(page.conversationId || route.query.conversation_id || ''));
|
||||
const itemNoFromQuery = computed(() => String(route.query.item_no || ''));
|
||||
|
||||
const focusedEvidenceRef = ref<{ fieldId: string; lineIndex?: number } | null>(null);
|
||||
/**
|
||||
* 当前用于 PDF 证据高亮的条目:明细同时按字段与行号匹配,避免多行同字段定位错位。
|
||||
*/
|
||||
const selectedEvidence = computed((): ShippingOrderReviewEvidence | null => {
|
||||
const items = evidence.value || [];
|
||||
if (!items.length) return null;
|
||||
const fieldId = String(focusedEvidenceRef.value?.fieldId || '').trim();
|
||||
if (fieldId) {
|
||||
const lineIndex = focusedEvidenceRef.value?.lineIndex;
|
||||
const matched = items.find((item) => String(item.field_id || '') === fieldId
|
||||
&& (lineIndex === undefined || Number(item.line_index) === lineIndex));
|
||||
if (matched) return matched;
|
||||
}
|
||||
return items.find((item) => item.bbox) || items[0] || null;
|
||||
});
|
||||
|
||||
/**
|
||||
* 聚焦订单字段以便 PDF 侧定位对应证据。
|
||||
*/
|
||||
const findFieldEvidence = (fieldId: string, lineIndex?: number) => (evidence.value || []).find((item) =>
|
||||
String(item.field_id || '') === String(fieldId || '').trim()
|
||||
&& (lineIndex === undefined || Number(item.line_index) === lineIndex),
|
||||
);
|
||||
const hasFieldEvidence = (fieldId: string, lineIndex?: number) => Boolean(findFieldEvidence(fieldId, lineIndex));
|
||||
/** 聚焦字段证据:有 bbox 时高亮,否则仅切至证据所在页。 */
|
||||
const focusFieldEvidence = (fieldId: string, lineIndex?: number) => {
|
||||
focusedEvidenceRef.value = findFieldEvidence(fieldId, lineIndex)
|
||||
? { fieldId: String(fieldId || '').trim(), lineIndex }
|
||||
: null;
|
||||
};
|
||||
|
||||
const headerSchemaFields = computed(() => (activeCase.value?.schema.fields || []).filter((field) => field.scope === 'header'));
|
||||
const lineSchemaFields = computed(() => (activeCase.value?.schema.fields || []).filter((field) => field.scope === 'line'));
|
||||
@@ -53,18 +121,46 @@ const machineValueByIdFor = (fields: Array<Record<string, unknown>>, fieldId: st
|
||||
const field = fields.find((item) => String(item.field_id || '') === fieldId);
|
||||
return field ? machineValue(field) : '';
|
||||
};
|
||||
const editable = computed(() => activeCase.value?.available_actions.includes('edit_draft') || false);
|
||||
const selectedEvidenceId = ref('');
|
||||
const contextOpen = ref(false);
|
||||
const confirmDialogOpen = ref(false);
|
||||
const confirmSuccess = ref<{ taskNo: string; autoProgress: boolean } | null>(null);
|
||||
const selectedEvidence = computed(() => evidence.value.find((item) => item.evidence_id === selectedEvidenceId.value) || null);
|
||||
// PDF.js uses evidence.page_no to select the page; retain the original Blob URL while switching evidence.
|
||||
const previewSrc = computed(() => previewUrl.value);
|
||||
const selectEvidence = (fieldId: string, lineIndex?: number) => {
|
||||
const item = evidence.value.find((entry) => entry.field_id === fieldId && entry.line_index === lineIndex);
|
||||
selectedEvidenceId.value = item?.evidence_id || '';
|
||||
const caseStatusLabel = (status: string) => {
|
||||
const key = `chat.shippingOrderReview.caseStatuses.${status}`;
|
||||
return te(key) ? t(key) : t('chat.shippingOrderReview.caseStatuses.unknown');
|
||||
};
|
||||
const statusBannerText = computed(() => {
|
||||
if (!statusMessage.value) return '';
|
||||
return t(`chat.shippingOrderReview.statusBanner.${statusMessage.value}`);
|
||||
});
|
||||
const workItemVersionLabel = computed(() => {
|
||||
const versionNo = workItem.value?.current_version_no;
|
||||
if (!versionNo) return '';
|
||||
return t('chat.shippingSessionWorkItem.versionLabel', { version: versionNo });
|
||||
});
|
||||
|
||||
const contextOpen = ref(false);
|
||||
const confirmSuccess = ref<{
|
||||
taskNo: string;
|
||||
autoProgress: boolean;
|
||||
progressStatus: string;
|
||||
progressMessage: string;
|
||||
checkpoint: string;
|
||||
} | null>(null);
|
||||
const pendingAction = ref<ReviewConfirmAction | null>(null);
|
||||
const pendingReplaceFile = ref<File | null>(null);
|
||||
const actionDialogOpen = ref(false);
|
||||
|
||||
/** 将自动推进结果映射为本地化状态;服务端 message 继续作为具体停留原因。 */
|
||||
const autoProgressStatusLabel = (status: string) => {
|
||||
const normalized = String(status || '').trim();
|
||||
const key = `chat.shippingOrderReview.autoProgress.status.${normalized}`;
|
||||
return normalized && te(key) ? t(key) : t('chat.shippingOrderReview.autoProgress.status.unknown');
|
||||
};
|
||||
|
||||
/** 打开已创建订单的任务工作台,由该页持续展示真实流程、待办与事件时间线。 */
|
||||
const openTaskProgress = (taskNo: string) => {
|
||||
const normalized = String(taskNo || '').trim();
|
||||
if (!normalized) return;
|
||||
void router.push({ name: 'workspace-shipping-tasks', params: { taskNo: normalized } });
|
||||
};
|
||||
|
||||
const reportSave = async (action: () => Promise<unknown> | null) => {
|
||||
try { await action(); }
|
||||
catch (error) {
|
||||
@@ -79,98 +175,450 @@ const reportDisposition = async (action: () => Promise<unknown> | null) => {
|
||||
msg.error(message);
|
||||
}
|
||||
};
|
||||
const confirmCase = () => {
|
||||
confirmDialogOpen.value = true;
|
||||
|
||||
/** 打开指定类型的二次确认弹窗。 */
|
||||
const openActionDialog = (action: ReviewConfirmAction) => {
|
||||
pendingAction.value = action;
|
||||
actionDialogOpen.value = true;
|
||||
};
|
||||
const confirmCaseSubmit = async () => {
|
||||
|
||||
/**
|
||||
* 确认弹窗提交:按 action 分发至对应写操作。
|
||||
* 核心逻辑:质量异常/非订单/重识别携带 reasonCode + comment,供后端统一审计复盘。
|
||||
* @param payload - 弹窗确认载荷
|
||||
*/
|
||||
const submitPendingAction = async (payload: ReviewConfirmPayload) => {
|
||||
const action = pendingAction.value;
|
||||
if (!action) return;
|
||||
try {
|
||||
const response = await confirm();
|
||||
if (response?.task_no) {
|
||||
confirmSuccess.value = {
|
||||
taskNo: String(response.task_no),
|
||||
autoProgress: Boolean(response.auto_progress_started || response.auto_progress),
|
||||
};
|
||||
if (action === 'confirm') {
|
||||
const response = await confirm();
|
||||
if (response?.task_no) {
|
||||
confirmSuccess.value = {
|
||||
taskNo: String(response.task_no),
|
||||
autoProgress: Boolean(response.auto_progress_started || response.auto_progress),
|
||||
progressStatus: String(response.auto_progress?.status || ''),
|
||||
progressMessage: String(response.auto_progress?.message || ''),
|
||||
checkpoint: String(response.auto_progress?.checkpoint || ''),
|
||||
};
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (action === 'reparse') {
|
||||
const response = await reparseDocument(payload.reasonCode || 'document_quality', payload.comment);
|
||||
if (response?.run.run_no) {
|
||||
await router.replace({
|
||||
query: {
|
||||
...route.query,
|
||||
run_no: response.run.run_no,
|
||||
case: undefined,
|
||||
case_no: undefined,
|
||||
item_no: workItem.value?.item_no || itemNoFromQuery.value || undefined,
|
||||
},
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (action === 'non_order') {
|
||||
await markNonOrder(payload.reasonCode || 'non_order', payload.comment);
|
||||
return;
|
||||
}
|
||||
if (action === 'quality_issue') {
|
||||
await markQualityIssue(payload.reasonCode || 'other', payload.comment);
|
||||
return;
|
||||
}
|
||||
if (action === 'replace' && pendingReplaceFile.value) {
|
||||
await uploadReplacement(pendingReplaceFile.value);
|
||||
pendingReplaceFile.value = null;
|
||||
}
|
||||
} catch (error) {
|
||||
const message = error instanceof BusinessError ? error.message : t('errors.generic');
|
||||
msg.error(message);
|
||||
} finally {
|
||||
pendingAction.value = null;
|
||||
}
|
||||
};
|
||||
|
||||
const selectReplacement = (event: Event) => {
|
||||
const file = (event.target as HTMLInputElement).files?.[0];
|
||||
if (file) void reportDisposition(() => uploadReplacement(file));
|
||||
if (!file) return;
|
||||
pendingReplaceFile.value = file;
|
||||
pendingAction.value = 'replace';
|
||||
actionDialogOpen.value = true;
|
||||
(event.target as HTMLInputElement).value = '';
|
||||
};
|
||||
|
||||
const select = async (caseNo: string) => {
|
||||
focusedEvidenceRef.value = null;
|
||||
await selectCase(caseNo);
|
||||
// Preserve review mode and the originating conversation while switching PDFs.
|
||||
await router.replace({ query: { ...route.query, case: caseNo } });
|
||||
};
|
||||
/** 在同一 ChatView 内退出复核模式,保留原会话实例及其滚动位置。 */
|
||||
|
||||
/**
|
||||
* 版本历史面板选择:历史版本只读打开,当前版本正常编辑。
|
||||
*/
|
||||
const selectVersionFromHistory = async (caseNo: string) => {
|
||||
await select(caseNo);
|
||||
await refreshWorkItemContext(conversationId.value, workItem.value?.item_no || itemNoFromQuery.value);
|
||||
};
|
||||
|
||||
/**
|
||||
* 跳转至工作项当前版本 Case。
|
||||
*/
|
||||
const jumpToCurrentVersion = async () => {
|
||||
const target = await openCurrentVersion();
|
||||
if (!target) return;
|
||||
await router.replace({
|
||||
query: {
|
||||
...route.query,
|
||||
run_no: target.runNo,
|
||||
case: target.caseNo,
|
||||
case_no: undefined,
|
||||
item_no: workItem.value?.item_no || itemNoFromQuery.value || undefined,
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
/** 退出复核模式回到「本次处理」侧栏视图。 */
|
||||
const back = () => router.replace({
|
||||
name: 'Chat',
|
||||
params: { agentId: agentId.value },
|
||||
query: Object.fromEntries(Object.entries(route.query).filter(([key]) => key !== 'mode' && key !== 'run_no')),
|
||||
query: Object.fromEntries(
|
||||
Object.entries(route.query).filter(([key]) => !['mode', 'run_no', 'case', 'case_no', 'item_no'].includes(key)),
|
||||
),
|
||||
});
|
||||
|
||||
watch(
|
||||
[runNo, () => String(route.query.case || '')],
|
||||
([nextRun, nextCase]) => { if (nextRun) void load(nextRun, nextCase || undefined); },
|
||||
[runNo, () => String(route.query.case || route.query.case_no || ''), conversationId, itemNoFromQuery],
|
||||
([nextRun, nextCase, nextConversationId, nextItemNo]) => {
|
||||
if (nextRun) {
|
||||
void load(nextRun, nextCase || undefined, {
|
||||
conversationId: nextConversationId || undefined,
|
||||
itemNo: nextItemNo || undefined,
|
||||
});
|
||||
}
|
||||
},
|
||||
{ immediate: true },
|
||||
);
|
||||
watch(
|
||||
() => reviewRun.value?.run_no,
|
||||
(resolvedRunNo) => {
|
||||
if (resolvedRunNo && resolvedRunNo !== runNo.value) {
|
||||
void router.replace({
|
||||
query: {
|
||||
...route.query,
|
||||
run_no: resolvedRunNo,
|
||||
case: undefined,
|
||||
case_no: undefined,
|
||||
},
|
||||
});
|
||||
}
|
||||
},
|
||||
);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<main class="flex min-h-0 flex-1 flex-col bg-slate-50 text-slate-900 dark:bg-slate-950 dark:text-slate-100">
|
||||
<header class="flex shrink-0 items-center gap-3 border-b border-slate-200 bg-white px-4 py-3 dark:border-slate-800 dark:bg-slate-900">
|
||||
<button type="button" class="rounded-md p-1 hover:bg-slate-100 dark:hover:bg-slate-800" :aria-label="t('chat.shippingOrderReview.back')" @click="back"><ArrowLeft class="h-5 w-5" /></button>
|
||||
<div class="min-w-0"><h1 class="text-base font-semibold">{{ t('chat.shippingOrderReview.title') }}</h1><p class="truncate text-xs text-slate-500 dark:text-slate-400">{{ t('chat.shippingOrderReview.run', { runNo }) }}</p></div>
|
||||
<button type="button" class="ml-auto rounded border border-slate-200 px-2.5 py-1.5 text-xs hover:bg-slate-50 dark:border-slate-700 dark:hover:bg-slate-800" @click="contextOpen = !contextOpen">{{ contextOpen ? '收起对话上下文' : '对话上下文' }}</button>
|
||||
<span class="shrink-0 rounded-full bg-sky-100 px-2.5 py-1 text-xs text-sky-800 dark:bg-sky-950 dark:text-sky-100">{{ saving ? t('chat.shippingOrderReview.saving') : saveFailed ? t('chat.shippingOrderReview.saveFailed') : t('chat.shippingOrderReview.saved') }}</span>
|
||||
</header>
|
||||
<div
|
||||
v-if="confirmSuccess"
|
||||
class="mx-4 mt-3 rounded-xl border border-emerald-200 bg-emerald-50 px-3 py-2 text-sm text-emerald-800 dark:border-emerald-900 dark:bg-emerald-950 dark:text-emerald-100"
|
||||
>
|
||||
{{ confirmSuccess.autoProgress
|
||||
? t('chat.shippingOrderReview.confirmAutoProgress', { taskNo: confirmSuccess.taskNo })
|
||||
: t('chat.shippingOrderReview.confirmSuccess', { taskNo: confirmSuccess.taskNo }) }}
|
||||
<main
|
||||
class="flex min-h-0 flex-1 flex-col bg-slate-50 text-slate-900 dark:bg-slate-950 dark:text-slate-100"
|
||||
data-testid="shipping-order-review-view"
|
||||
:data-readonly="isViewingHistoricalVersion ? 'true' : 'false'"
|
||||
>
|
||||
<header class="flex shrink-0 items-center gap-3 border-b border-slate-200 bg-white px-4 py-3 dark:border-slate-800 dark:bg-slate-900">
|
||||
<button type="button" class="rounded-md p-1 hover:bg-slate-100 dark:hover:bg-slate-800" :aria-label="t('chat.shippingOrderReview.backToSession')" @click="back">
|
||||
<ArrowLeft class="h-5 w-5" />
|
||||
</button>
|
||||
<div class="min-w-0 flex-1">
|
||||
<h1 class="text-base font-semibold">{{ t('chat.shippingOrderReview.title') }}</h1>
|
||||
<p class="truncate text-xs text-slate-500 dark:text-slate-400">
|
||||
<template v-if="workItem?.item_no">
|
||||
{{ t('chat.shippingOrderReview.workItemHeader', { itemNo: workItem.item_no, version: workItemVersionLabel }) }}
|
||||
</template>
|
||||
<template v-else>{{ t('chat.shippingOrderReview.run', { runNo }) }}</template>
|
||||
</p>
|
||||
</div>
|
||||
<button type="button" class="rounded border border-slate-200 px-2.5 py-1.5 text-xs hover:bg-slate-50 dark:border-slate-700 dark:hover:bg-slate-800" @click="contextOpen = !contextOpen">
|
||||
{{ contextOpen ? t('chat.shippingOrderReview.hideContext') : t('chat.shippingOrderReview.showContext') }}
|
||||
</button>
|
||||
<span class="shrink-0 rounded-full bg-sky-100 px-2.5 py-1 text-xs text-sky-800 dark:bg-sky-950 dark:text-sky-100">
|
||||
{{ saving ? t('chat.shippingOrderReview.saving') : saveFailed ? t('chat.shippingOrderReview.saveFailed') : t('chat.shippingOrderReview.saved') }}
|
||||
</span>
|
||||
</header>
|
||||
|
||||
<div v-if="loading" class="p-8 text-sm text-slate-600 dark:text-slate-300">{{ t('chat.shippingOrderReview.loading') }}</div>
|
||||
<div v-else-if="loadFailed" class="m-4 rounded-lg border border-rose-300 bg-rose-50 p-4 text-sm text-rose-900 dark:border-rose-800 dark:bg-rose-950/30 dark:text-rose-100">{{ t('chat.shippingOrderReview.unavailable') }}</div>
|
||||
<div v-else class="grid min-h-0 flex-1 grid-cols-1 xl:grid-cols-[minmax(0,1fr)_minmax(340px,420px)]">
|
||||
<section class="min-h-0 overflow-y-auto p-4 lg:p-5">
|
||||
<div v-if="activeCase?.draft?.issues?.length" class="mb-4 rounded-lg border border-amber-300 bg-amber-50 p-3 text-xs text-amber-950 dark:border-amber-800 dark:bg-amber-950/30 dark:text-amber-100"><div class="font-semibold">{{ t('chat.shippingOrderReview.issues') }}</div><div v-for="issue in activeCase.draft.issues" :key="`${issue.code}-${issue.severity}`" class="mt-1">{{ issue.code }}</div></div>
|
||||
<section class="rounded-xl border border-slate-200 bg-white p-4 shadow-sm dark:border-slate-800 dark:bg-slate-900">
|
||||
<div class="flex items-center justify-between gap-3"><div><h2 class="text-sm font-semibold">{{ t('chat.shippingOrderReview.orderFields') }}</h2><p class="mt-1 text-xs text-slate-500">{{ t('chat.shippingOrderReview.schemaVersion', { version: activeCase?.schema.schema_version_id || '-' }) }}</p></div></div>
|
||||
<div v-if="primaryHeaderFields.length" class="mt-4 grid gap-3 md:grid-cols-2 2xl:grid-cols-3">
|
||||
<div v-for="field in primaryHeaderFields" :key="field.field_id" class="min-w-0">
|
||||
<label class="flex items-center justify-between gap-2 text-xs font-medium text-slate-600 dark:text-slate-300"><span class="truncate">{{ field.display_name }}<span v-if="field.required"> *</span></span><button type="button" class="shrink-0 text-slate-500 hover:text-sky-600" :aria-label="t('chat.shippingOrderReview.viewEvidence')" @click="selectEvidence(field.field_id)"><MapPin class="h-3.5 w-3.5" /></button></label>
|
||||
<input :value="draftValue(activeCase?.draft?.header_values || {}, field.field_id)" :disabled="!editable || saving" class="mt-1 w-full rounded-md border border-slate-300 bg-white px-2.5 py-2 text-sm dark:border-slate-600 dark:bg-slate-950" @change="reportSave(() => patchHeader(field.field_id, ($event.target as HTMLInputElement).value))">
|
||||
<div class="mt-1 flex items-center justify-between gap-2 text-[11px] text-slate-500"><span>{{ (activeCase?.draft?.header_values as Record<string, unknown>)?.values && Object.prototype.hasOwnProperty.call((activeCase?.draft?.header_values as Record<string, unknown>).values as object, field.field_id) ? t('chat.shippingOrderReview.manualSource') : t('chat.shippingOrderReview.machineSource') }}</span><button v-if="editable" type="button" class="hover:text-sky-600" @click="reportSave(() => patchHeader(field.field_id, null, true))"><Undo2 class="mr-1 inline h-3 w-3" />{{ t('chat.shippingOrderReview.restoreMachine') }}</button></div>
|
||||
<div
|
||||
v-if="statusBannerText"
|
||||
class="mx-4 mt-3 rounded-xl border border-amber-200 bg-amber-50 px-3 py-2 text-sm text-amber-900 dark:border-amber-900 dark:bg-amber-950 dark:text-amber-100"
|
||||
data-testid="review-status-banner"
|
||||
>
|
||||
<div class="flex flex-wrap items-center justify-between gap-2">
|
||||
<span>{{ statusBannerText }}</span>
|
||||
<button
|
||||
v-if="isViewingHistoricalVersion"
|
||||
type="button"
|
||||
class="rounded border border-amber-400 px-2 py-1 text-xs font-medium hover:bg-amber-100 dark:hover:bg-amber-900"
|
||||
data-testid="jump-to-current-version"
|
||||
@click="jumpToCurrentVersion"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.jumpToCurrentVersion') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="confirmSuccess"
|
||||
class="mx-4 mt-3 rounded-xl border border-emerald-200 bg-emerald-50 px-3 py-2 text-sm text-emerald-800 dark:border-emerald-900 dark:bg-emerald-950 dark:text-emerald-100"
|
||||
>
|
||||
<div class="flex flex-wrap items-center justify-between gap-3">
|
||||
<div>
|
||||
<p>{{ confirmSuccess.autoProgress
|
||||
? t('chat.shippingOrderReview.confirmAutoProgress', { taskNo: confirmSuccess.taskNo })
|
||||
: t('chat.shippingOrderReview.confirmSuccess', { taskNo: confirmSuccess.taskNo }) }}</p>
|
||||
<p v-if="confirmSuccess.autoProgress" class="mt-1 text-xs">
|
||||
{{ t('chat.shippingOrderReview.autoProgress.result', { status: autoProgressStatusLabel(confirmSuccess.progressStatus) }) }}
|
||||
</p>
|
||||
<p v-if="confirmSuccess.progressMessage" class="mt-1 text-xs">{{ confirmSuccess.progressMessage }}</p>
|
||||
<p v-if="confirmSuccess.checkpoint" class="mt-1 text-xs text-amber-800 dark:text-amber-200">
|
||||
{{ t('chat.shippingOrderReview.autoProgress.checkpoint', { checkpoint: confirmSuccess.checkpoint }) }}
|
||||
</p>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
class="inline-flex shrink-0 items-center gap-1 rounded border border-emerald-400 px-2.5 py-1.5 text-xs font-medium hover:bg-emerald-100 dark:hover:bg-emerald-900"
|
||||
data-testid="open-confirmed-task-progress"
|
||||
@click="openTaskProgress(confirmSuccess.taskNo)"
|
||||
>
|
||||
<ExternalLink class="h-3.5 w-3.5" />{{ t('chat.shippingOrderReview.autoProgress.viewTask') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="loading" class="p-8 text-sm text-slate-600 dark:text-slate-300">{{ t('chat.shippingOrderReview.loading') }}</div>
|
||||
<div v-else-if="loadFailed" class="m-4 rounded-lg border border-rose-300 bg-rose-50 p-4 text-sm text-rose-900 dark:border-rose-800 dark:bg-rose-950/30 dark:text-rose-100">
|
||||
{{ t('chat.shippingOrderReview.unavailable') }}
|
||||
</div>
|
||||
<div v-else class="min-h-0 flex-1 overflow-y-auto">
|
||||
<section class="p-4 lg:p-5">
|
||||
<div class="grid gap-4 xl:grid-cols-[minmax(480px,1.25fr)_minmax(420px,1fr)]">
|
||||
<aside
|
||||
class="order-2 min-h-[180px] overflow-hidden rounded-xl border border-slate-200 bg-white shadow-sm xl:order-1 xl:h-[calc(100vh-11rem)] xl:min-h-[560px] dark:border-slate-800 dark:bg-slate-900"
|
||||
data-testid="review-document-preview"
|
||||
>
|
||||
<div class="border-b border-slate-200 px-3 py-2 text-xs font-semibold text-slate-600 dark:border-slate-800 dark:text-slate-300">
|
||||
{{ t('chat.shippingOrderReview.previewTitle') }}
|
||||
</div>
|
||||
<ReviewDocumentPreview
|
||||
v-if="previewUrl"
|
||||
:src="previewUrl"
|
||||
:evidence="selectedEvidence"
|
||||
:title="t('chat.shippingOrderReview.previewTitle')"
|
||||
:loading-text="t('chat.shippingOrderReview.previewLoading')"
|
||||
:unavailable-text="t('chat.shippingOrderReview.previewUnavailable')"
|
||||
/>
|
||||
<div v-else class="flex min-h-[140px] items-center justify-center p-4 text-sm text-slate-500 xl:min-h-[360px]">
|
||||
{{ t('chat.shippingOrderReview.previewUnavailable') }}
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
<div class="order-1 min-w-0 space-y-4 xl:order-2">
|
||||
<nav class="rounded-xl border border-slate-200 bg-white p-3 shadow-sm dark:border-slate-800 dark:bg-slate-900" :aria-label="t('chat.shippingOrderReview.documentNavigation')">
|
||||
<div class="mb-2 text-xs font-semibold text-slate-500">{{ t('chat.shippingOrderReview.documents') }}</div>
|
||||
<div class="flex gap-2 overflow-x-auto">
|
||||
<button
|
||||
v-for="item in reviewRun?.items || []"
|
||||
:key="item.case_no"
|
||||
type="button"
|
||||
class="min-w-52 rounded-lg border p-2.5 text-left text-sm"
|
||||
:class="activeCase?.case_no === item.case_no ? 'border-sky-500 bg-sky-50 dark:bg-sky-950/30' : 'border-slate-200 hover:bg-slate-50 dark:border-slate-700 dark:hover:bg-slate-800'"
|
||||
@click="select(item.case_no)"
|
||||
>
|
||||
<div class="truncate font-medium">{{ item.file_name || t('chat.shippingOrderReview.unnamedDocument') }}</div>
|
||||
<div class="mt-1 flex items-center gap-1 text-xs text-slate-500">
|
||||
<TriangleAlert v-if="item.issue_count" class="h-3.5 w-3.5 text-amber-500" />
|
||||
{{ t('chat.shippingOrderReview.caseStatus', { status: caseStatusLabel(item.status), count: item.issue_count }) }}
|
||||
</div>
|
||||
</button>
|
||||
</div>
|
||||
</nav>
|
||||
|
||||
<details class="rounded-xl border border-slate-200 bg-white shadow-sm dark:border-slate-800 dark:bg-slate-900">
|
||||
<summary class="cursor-pointer px-4 py-3 text-sm font-semibold">{{ t('chat.shippingOrderReview.versionHistory.title') }}</summary>
|
||||
<div class="border-t border-slate-200 p-4 dark:border-slate-800">
|
||||
<ReviewVersionHistoryPanel
|
||||
:item-no="workItem?.item_no || itemNoFromQuery"
|
||||
:versions="versions"
|
||||
:loading="versionsLoading"
|
||||
:active-case-no="activeCase?.case_no"
|
||||
@select="selectVersionFromHistory"
|
||||
/>
|
||||
</div>
|
||||
</details>
|
||||
|
||||
<div v-if="contextOpen" class="rounded-xl border border-slate-200 bg-white p-4 shadow-sm dark:border-slate-800 dark:bg-slate-900">
|
||||
<h2 class="text-sm font-semibold">{{ t('chat.shippingOrderReview.contextTitle') }}</h2>
|
||||
<p class="mt-1 text-xs text-slate-500">{{ t('chat.shippingOrderReview.contextDesc') }}</p>
|
||||
<div class="mt-4 space-y-3">
|
||||
<article v-for="(message, index) in page.messages.slice(-6)" :key="`${message.local_id || index}`" class="rounded-lg border border-slate-200 p-3 text-sm dark:border-slate-700">
|
||||
<div class="mb-1 text-xs font-medium text-slate-500">{{ message.role === 'user' ? t('chat.shippingOrderReview.contextUser') : t('chat.shippingOrderReview.contextAi') }}</div>
|
||||
<p class="whitespace-pre-wrap break-words">{{ message.content }}</p>
|
||||
</article>
|
||||
</div>
|
||||
</div>
|
||||
<div v-else class="mt-4 rounded-lg border border-dashed border-slate-300 p-3 text-sm text-slate-500 dark:border-slate-700"><p>{{ t('chat.shippingOrderReview.noMachineOrder') }}</p><div v-if="activeCase?.available_actions.includes('create_draft')" class="mt-3 flex flex-wrap gap-2"><button type="button" class="rounded border px-2 py-1 text-xs" :disabled="saving" @click="reportDisposition(() => createManualDraft())">{{ t('chat.shippingOrderReview.createManualDraft') }}</button><button type="button" class="rounded border px-2 py-1 text-xs" :disabled="saving" @click="reportDisposition(() => markNonOrder('non_order'))">{{ t('chat.shippingOrderReview.markNonOrder') }}</button></div></div>
|
||||
<details v-if="optionalEmptyHeaderFields.length" class="mt-4 rounded-lg border border-slate-200 p-3 text-sm dark:border-slate-700"><summary class="cursor-pointer font-medium">{{ t('chat.shippingOrderReview.moreFields', { count: optionalEmptyHeaderFields.length }) }}</summary><div class="mt-3 grid gap-2 sm:grid-cols-2"><div v-for="field in optionalEmptyHeaderFields" :key="field.field_id" class="text-xs"><div class="text-slate-500">{{ field.display_name }}</div><div>{{ t('chat.shippingOrderReview.emptyValue') }}</div></div></div></details>
|
||||
</section>
|
||||
|
||||
<section class="mt-4 rounded-xl border border-slate-200 bg-white shadow-sm dark:border-slate-800 dark:bg-slate-900">
|
||||
<div class="flex items-center justify-between gap-3 border-b border-slate-200 px-4 py-3 dark:border-slate-800"><div><h3 class="text-sm font-semibold">{{ t('chat.shippingOrderReview.lines') }}</h3><p class="mt-1 text-xs text-slate-500">{{ (activeCase?.draft?.lines || []).length }} {{ t('chat.shippingOrderReview.lines') }}</p></div><button v-if="!isMobile" type="button" :disabled="!editable || saving" class="inline-flex items-center gap-1 rounded border px-2 py-1 text-xs disabled:opacity-50" @click="reportSave(() => addLine())"><Plus class="h-3.5 w-3.5" />{{ t('chat.shippingOrderReview.addLine') }}</button></div>
|
||||
<div v-if="activeCase?.draft?.lines?.length" class="overflow-x-auto"><table class="min-w-full border-collapse text-left text-xs"><thead class="bg-slate-50 text-slate-500 dark:bg-slate-950/40 dark:text-slate-400"><tr><th class="sticky left-0 z-10 min-w-14 border-b border-slate-200 bg-slate-50 px-3 py-2 font-medium dark:border-slate-800 dark:bg-slate-950">#</th><th v-for="field in primaryLineFields" :key="field.field_id" class="min-w-40 border-b border-slate-200 px-3 py-2 font-medium dark:border-slate-800">{{ field.display_name }}<span v-if="field.required"> *</span></th><th v-if="!isMobile" class="sticky right-0 z-10 border-b border-slate-200 bg-slate-50 px-3 py-2 dark:border-slate-800 dark:bg-slate-950"><span class="sr-only">{{ t('chat.shippingOrderReview.line', { index: '' }) }}</span></th></tr></thead><tbody><tr v-for="(line, index) in activeCase?.draft?.lines || []" :key="String(line.line_key || index)" class="border-b border-slate-100 last:border-0 dark:border-slate-800"><td class="sticky left-0 z-10 bg-white px-3 py-2 font-medium dark:bg-slate-900">{{ index + 1 }}</td><td v-for="field in primaryLineFields" :key="field.field_id" class="min-w-40 px-3 py-2 align-top"><div class="flex min-w-0 items-center gap-1"><input :value="draftValue(line, field.field_id)" :disabled="!editable || saving" class="min-w-0 flex-1 rounded border border-slate-300 bg-white px-2 py-1.5 dark:border-slate-600 dark:bg-slate-950" @change="reportSave(() => patchLine(String(line.line_key), field.field_id, ($event.target as HTMLInputElement).value))"><button type="button" class="shrink-0 text-slate-500 hover:text-sky-600" :aria-label="t('chat.shippingOrderReview.viewEvidence')" @click="selectEvidence(field.field_id, index)"><MapPin class="h-3.5 w-3.5" /></button></div></td><td v-if="!isMobile" class="sticky right-0 z-10 whitespace-nowrap bg-white px-2 py-2 dark:bg-slate-900"><button type="button" :disabled="!editable || saving" class="rounded p-1 hover:bg-slate-100 disabled:opacity-50 dark:hover:bg-slate-800" :aria-label="t('chat.shippingOrderReview.copyLine')" @click="reportSave(() => copyLine(String(line.line_key)))"><Copy class="h-3.5 w-3.5" /></button><button type="button" :disabled="!editable || saving" class="rounded p-1 hover:bg-slate-100 disabled:opacity-50 dark:hover:bg-slate-800" :aria-label="t('chat.shippingOrderReview.deleteLine')" @click="reportSave(() => deleteLine(String(line.line_key)))"><Trash2 class="h-3.5 w-3.5" /></button></td></tr></tbody></table></div>
|
||||
<div v-else class="p-4 text-sm text-slate-500">{{ t('chat.shippingOrderReview.noLines') }}</div>
|
||||
<details v-if="optionalEmptyLineFields.length" class="border-t border-slate-200 px-4 py-3 text-xs dark:border-slate-800"><summary class="cursor-pointer text-slate-500">{{ t('chat.shippingOrderReview.moreFields', { count: optionalEmptyLineFields.length }) }}</summary><p class="mt-2 text-slate-500">{{ optionalEmptyLineFields.map((field) => field.display_name).join(' · ') }}</p></details>
|
||||
</section>
|
||||
</section>
|
||||
<div v-if="activeCase?.draft?.issues?.length" class="rounded-lg border border-amber-300 bg-amber-50 p-3 text-xs text-amber-950 dark:border-amber-800 dark:bg-amber-950/30 dark:text-amber-100">
|
||||
<div class="font-semibold">{{ t('chat.shippingOrderReview.issues') }}</div>
|
||||
<div v-for="issue in activeCase.draft.issues" :key="`${issue.code}-${issue.severity}`" class="mt-1">{{ issue.code }}</div>
|
||||
</div>
|
||||
|
||||
<aside class="flex min-h-0 flex-col border-t border-slate-200 bg-white xl:border-l xl:border-t-0 dark:border-slate-800 dark:bg-slate-900">
|
||||
<nav class="shrink-0 border-b border-slate-200 p-3 dark:border-slate-800" :aria-label="t('chat.shippingOrderReview.documentNavigation')"><div class="mb-2 text-xs font-semibold text-slate-500">{{ t('chat.shippingOrderReview.documents') }}</div><div class="flex gap-2 overflow-x-auto xl:flex-col xl:overflow-y-auto"><button v-for="item in reviewRun?.items || []" :key="item.case_no" type="button" class="min-w-52 rounded-lg border p-2.5 text-left text-sm xl:min-w-0" :class="activeCase?.case_no === item.case_no ? 'border-sky-500 bg-sky-50 dark:bg-sky-950/30' : 'border-slate-200 hover:bg-slate-50 dark:border-slate-700 dark:hover:bg-slate-800'" @click="select(item.case_no)"><div class="truncate font-medium">{{ item.file_name || t('chat.shippingOrderReview.unnamedDocument') }}</div><div class="mt-1 flex items-center gap-1 text-xs text-slate-500"><TriangleAlert v-if="item.issue_count" class="h-3.5 w-3.5 text-amber-500" />{{ t('chat.shippingOrderReview.caseStatus', { status: item.status, count: item.issue_count }) }}</div></button></div></nav>
|
||||
<div v-if="contextOpen" class="min-h-0 flex-1 overflow-y-auto p-4"><h2 class="text-sm font-semibold">对话上下文</h2><p class="mt-1 text-xs text-slate-500">当前会话中最近的订单抽取消息与附件。</p><div class="mt-4 space-y-3"><article v-for="(message, index) in page.messages.slice(-6)" :key="`${message.local_id || index}`" class="rounded-lg border border-slate-200 p-3 text-sm dark:border-slate-700"><div class="mb-1 text-xs font-medium text-slate-500">{{ message.role === 'user' ? '用户' : 'AI' }}</div><p class="whitespace-pre-wrap break-words">{{ message.content }}</p><div v-if="message.attachments?.length" class="mt-2 text-xs text-slate-500">{{ message.attachments.map((item) => item.name || '附件').join(' · ') }}</div></article><p v-if="page.messages.length === 0" class="text-sm text-slate-500">暂无可显示的对话上下文。</p></div></div>
|
||||
<div v-else class="flex min-h-0 flex-1 flex-col p-3"><div class="mb-2 flex items-center gap-2 text-sm font-semibold"><FileText class="h-4 w-4" />{{ activeCase?.document.file_name || t('chat.shippingOrderReview.unnamedDocument') }}</div><div class="min-h-[320px] flex-1 overflow-hidden rounded-xl border border-slate-300 bg-slate-50 dark:border-slate-700 dark:bg-slate-950"><ReviewDocumentPreview v-if="previewSrc" :src="previewSrc" :evidence="selectedEvidence" :title="t('chat.shippingOrderReview.previewTitle')" :loading-text="t('chat.shippingOrderReview.previewLoading')" :unavailable-text="t('chat.shippingOrderReview.previewUnavailable')" /></div><div v-if="selectedEvidence" class="mt-3 rounded-lg border border-sky-200 bg-sky-50 p-3 text-xs text-sky-950 dark:border-sky-900 dark:bg-sky-950/30 dark:text-sky-100"><div class="flex items-center gap-1 font-semibold"><MapPin class="h-3.5 w-3.5" />{{ t('chat.shippingOrderReview.evidenceAt', { page: selectedEvidence.page_no || '-' }) }}</div><p v-if="selectedEvidence.quote" class="mt-1 break-words">{{ selectedEvidence.quote }}</p><p v-if="!selectedEvidence.bbox" class="mt-1">{{ t('chat.shippingOrderReview.evidenceNoHighlight') }}</p></div><p v-else class="mt-3 text-xs text-slate-500">{{ t('chat.shippingOrderReview.evidenceSummary') }}</p></div>
|
||||
</aside>
|
||||
</div>
|
||||
<section class="rounded-xl border border-slate-200 bg-white p-4 shadow-sm dark:border-slate-800 dark:bg-slate-900">
|
||||
<div class="flex items-center justify-between gap-3">
|
||||
<div>
|
||||
<h2 class="text-sm font-semibold">{{ t('chat.shippingOrderReview.orderFields') }}</h2>
|
||||
<p class="mt-1 text-xs text-slate-500">{{ t('chat.shippingOrderReview.schemaVersion', { version: activeCase?.schema.schema_version_id || '-' }) }}</p>
|
||||
</div>
|
||||
<span v-if="isViewingHistoricalVersion" class="rounded-full bg-slate-100 px-2 py-0.5 text-xs text-slate-600 dark:bg-slate-800 dark:text-slate-300">
|
||||
{{ t('chat.shippingOrderReview.readOnly') }}
|
||||
</span>
|
||||
</div>
|
||||
<div v-if="primaryHeaderFields.length" class="mt-4 grid gap-3 md:grid-cols-2 2xl:grid-cols-3">
|
||||
<div v-for="field in primaryHeaderFields" :key="field.field_id" class="min-w-0">
|
||||
<div class="flex items-center justify-between gap-2 text-xs font-medium text-slate-600 dark:text-slate-300">
|
||||
<span class="truncate">{{ field.display_name }}<span v-if="field.required"> *</span></span>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded p-1 text-slate-500 hover:bg-sky-50 hover:text-sky-600 disabled:cursor-not-allowed disabled:opacity-35 dark:hover:bg-sky-950"
|
||||
:disabled="!hasFieldEvidence(field.field_id)"
|
||||
:aria-label="t('chat.shippingOrderReview.locateSource', { field: field.display_name })"
|
||||
:title="t('chat.shippingOrderReview.locateSource', { field: field.display_name })"
|
||||
@click="focusFieldEvidence(field.field_id)"
|
||||
><Crosshair class="h-3 w-3" /></button>
|
||||
</div>
|
||||
<input
|
||||
:value="draftValue(activeCase?.draft?.header_values || {}, field.field_id)"
|
||||
:disabled="!editable || saving"
|
||||
class="mt-1 w-full rounded-md border border-slate-300 bg-white px-2.5 py-2 text-sm dark:border-slate-600 dark:bg-slate-950"
|
||||
@focus="focusFieldEvidence(field.field_id)"
|
||||
@change="reportSave(() => patchHeader(field.field_id, ($event.target as HTMLInputElement).value))"
|
||||
>
|
||||
<div class="mt-1 flex items-center justify-between gap-2 text-[11px] text-slate-500">
|
||||
<span>{{ (activeCase?.draft?.header_values as Record<string, unknown>)?.values && Object.prototype.hasOwnProperty.call((activeCase?.draft?.header_values as Record<string, unknown>).values as object, field.field_id) ? t('chat.shippingOrderReview.manualSource') : t('chat.shippingOrderReview.machineSource') }}</span>
|
||||
<button v-if="editable" type="button" class="hover:text-sky-600" @click="reportSave(() => patchHeader(field.field_id, null, true))">
|
||||
<Undo2 class="mr-1 inline h-3 w-3" />{{ t('chat.shippingOrderReview.restoreMachine') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div v-else class="mt-4 rounded-lg border border-dashed border-slate-300 p-3 text-sm text-slate-500 dark:border-slate-700">
|
||||
<p>{{ t('chat.shippingOrderReview.noMachineOrder') }}</p>
|
||||
<div v-if="editable && activeCase?.available_actions.includes('create_draft')" class="mt-3 flex flex-wrap gap-2">
|
||||
<button type="button" class="rounded border px-2 py-1 text-xs" :disabled="saving" @click="reportDisposition(() => createManualDraft())">{{ t('chat.shippingOrderReview.createManualDraft') }}</button>
|
||||
<button type="button" class="rounded border px-2 py-1 text-xs" :disabled="saving" @click="openActionDialog('non_order')">{{ t('chat.shippingOrderReview.markNonOrder') }}</button>
|
||||
</div>
|
||||
</div>
|
||||
<details v-if="optionalEmptyHeaderFields.length" class="mt-4 rounded-lg border border-slate-200 p-3 text-sm dark:border-slate-700">
|
||||
<summary class="cursor-pointer font-medium">{{ t('chat.shippingOrderReview.moreFields', { count: optionalEmptyHeaderFields.length }) }}</summary>
|
||||
</details>
|
||||
</section>
|
||||
|
||||
<footer v-if="activeCase?.draft" class="flex shrink-0 flex-wrap items-center justify-end gap-2 border-t border-slate-200 bg-white p-3 dark:border-slate-800 dark:bg-slate-900"><button v-if="activeCase?.available_actions.includes('mark_non_order')" type="button" :disabled="saving" class="rounded border px-3 py-2 text-sm disabled:opacity-50" @click="reportDisposition(() => markNonOrder('non_order'))">{{ t('chat.shippingOrderReview.markNonOrder') }}</button><button v-if="activeCase?.available_actions.includes('mark_quality_issue')" type="button" :disabled="saving" class="rounded border px-3 py-2 text-sm disabled:opacity-50" @click="reportDisposition(() => markQualityIssue('other'))">{{ t('chat.shippingOrderReview.markQualityIssue') }}</button><button v-if="activeCase?.available_actions.includes('reparse')" type="button" :disabled="saving" class="inline-flex items-center gap-1 rounded border px-3 py-2 text-sm disabled:opacity-50" @click="reportDisposition(() => reparseDocument('document_quality'))"><RefreshCw class="h-4 w-4" />{{ t('chat.shippingOrderReview.reparse') }}</button><label v-if="activeCase?.available_actions.includes('mark_quality_issue')" class="cursor-pointer rounded border px-3 py-2 text-sm"><input class="sr-only" type="file" accept="application/pdf,.pdf" :disabled="saving" @change="selectReplacement">{{ t('chat.shippingOrderReview.uploadReplacement') }}</label><button v-if="activeCase?.available_actions.includes('validate')" type="button" :disabled="saving" class="inline-flex items-center gap-1 rounded bg-sky-600 px-3 py-2 text-sm text-white disabled:opacity-50" @click="reportSave(() => validate())"><Save class="h-4 w-4" />{{ t('chat.shippingOrderReview.saveNow') }}</button><button v-if="activeCase?.available_actions.includes('confirm')" type="button" :disabled="saving" class="rounded bg-emerald-600 px-3 py-2 text-sm text-white disabled:opacity-50" @click="confirmCase">{{ t('chat.shippingOrderReview.confirmCreate') }}</button></footer>
|
||||
<DeleteConfirmDialog v-model="confirmDialogOpen" :title="t('chat.shippingOrderReview.confirmCreate')" :message="t('chat.shippingOrderReview.confirmPrompt')" :confirm-text="t('chat.shippingOrderReview.confirmCreate')" confirm-tone="primary" :confirm-loading="saving" @confirm="confirmCaseSubmit" />
|
||||
</main>
|
||||
<section class="rounded-xl border border-slate-200 bg-white shadow-sm dark:border-slate-800 dark:bg-slate-900">
|
||||
<div class="flex items-center justify-between gap-3 border-b border-slate-200 px-4 py-3 dark:border-slate-800">
|
||||
<div>
|
||||
<h3 class="text-sm font-semibold">{{ t('chat.shippingOrderReview.lines') }}</h3>
|
||||
<p class="mt-1 text-xs text-slate-500">{{ (activeCase?.draft?.lines || []).length }} {{ t('chat.shippingOrderReview.lines') }}</p>
|
||||
</div>
|
||||
<button v-if="editable" type="button" :disabled="saving" class="inline-flex items-center gap-1 rounded border px-2 py-1 text-xs disabled:opacity-50" data-testid="review-add-line" @click="reportSave(() => addLine())">
|
||||
<Plus class="h-3.5 w-3.5" />{{ t('chat.shippingOrderReview.addLine') }}
|
||||
</button>
|
||||
</div>
|
||||
<div v-if="activeCase?.draft?.lines?.length" class="overflow-x-auto">
|
||||
<table class="min-w-full border-collapse text-left text-[11px]">
|
||||
<thead class="bg-slate-50 text-slate-500 dark:bg-slate-950/40 dark:text-slate-400">
|
||||
<tr>
|
||||
<th class="sticky left-0 z-10 min-w-12 border-b border-slate-200 bg-slate-50 px-2 py-1.5 font-medium dark:border-slate-800 dark:bg-slate-950">#</th>
|
||||
<th v-for="field in primaryLineFields" :key="field.field_id" class="min-w-28 border-b border-slate-200 px-2 py-1.5 font-medium dark:border-slate-800">
|
||||
{{ field.display_name }}<span v-if="field.required"> *</span>
|
||||
</th>
|
||||
<th class="sticky right-0 z-10 border-b border-slate-200 bg-slate-50 px-2 py-1.5 dark:border-slate-800 dark:bg-slate-950">
|
||||
<span class="sr-only">{{ t('chat.shippingOrderReview.line', { index: '' }) }}</span>
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-for="(line, index) in activeCase?.draft?.lines || []" :key="String(line.line_key || index)" class="border-b border-slate-100 last:border-0 dark:border-slate-800">
|
||||
<td class="sticky left-0 z-10 bg-white px-2 py-1.5 font-medium dark:bg-slate-900">{{ index + 1 }}</td>
|
||||
<td v-for="field in primaryLineFields" :key="field.field_id" class="min-w-28 px-2 py-1.5 align-middle">
|
||||
<div class="flex min-w-0 items-center gap-1">
|
||||
<input
|
||||
:value="draftValue(line, field.field_id)"
|
||||
:disabled="!editable || saving"
|
||||
class="min-w-0 flex-1 rounded border border-slate-300 bg-white px-1.5 py-1 text-xs dark:border-slate-600 dark:bg-slate-950"
|
||||
@focus="focusFieldEvidence(field.field_id, index)"
|
||||
@change="reportSave(() => patchLine(String(line.line_key), field.field_id, ($event.target as HTMLInputElement).value))"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
class="shrink-0 rounded p-0.5 text-slate-500 hover:bg-sky-50 hover:text-sky-600 disabled:cursor-not-allowed disabled:opacity-35 dark:hover:bg-sky-950"
|
||||
:disabled="!hasFieldEvidence(field.field_id, index)"
|
||||
:aria-label="t('chat.shippingOrderReview.locateSource', { field: field.display_name })"
|
||||
:title="t('chat.shippingOrderReview.locateSource', { field: field.display_name })"
|
||||
@click="focusFieldEvidence(field.field_id, index)"
|
||||
><Crosshair class="h-3 w-3" /></button>
|
||||
</div>
|
||||
</td>
|
||||
<td class="sticky right-0 z-10 whitespace-nowrap bg-white px-1.5 py-1.5 dark:bg-slate-900">
|
||||
<button type="button" :disabled="!editable || saving" class="rounded p-1 hover:bg-slate-100 disabled:opacity-50 dark:hover:bg-slate-800" data-testid="review-copy-line" :aria-label="t('chat.shippingOrderReview.copyLine')" @click="reportSave(() => copyLine(String(line.line_key)))">
|
||||
<Copy class="h-3.5 w-3.5" />
|
||||
</button>
|
||||
<button type="button" :disabled="!editable || saving" class="rounded p-1 hover:bg-slate-100 disabled:opacity-50 dark:hover:bg-slate-800" data-testid="review-delete-line" :aria-label="t('chat.shippingOrderReview.deleteLine')" @click="reportSave(() => deleteLine(String(line.line_key)))">
|
||||
<Trash2 class="h-3.5 w-3.5" />
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<div v-else class="p-4 text-sm text-slate-500">{{ t('chat.shippingOrderReview.noLines') }}</div>
|
||||
<details v-if="optionalEmptyLineFields.length" class="border-t border-slate-200 px-4 py-3 text-xs dark:border-slate-800">
|
||||
<summary class="cursor-pointer text-slate-500">{{ t('chat.shippingOrderReview.moreFields', { count: optionalEmptyLineFields.length }) }}</summary>
|
||||
<p class="mt-2 text-slate-500">{{ optionalEmptyLineFields.map((field) => field.display_name).join(' · ') }}</p>
|
||||
</details>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<footer
|
||||
v-if="activeCase?.draft && !isViewingHistoricalVersion"
|
||||
class="flex shrink-0 flex-wrap items-center justify-end gap-2 border-t border-slate-200 bg-white p-3 dark:border-slate-800 dark:bg-slate-900"
|
||||
>
|
||||
<button v-if="activeCase?.available_actions.includes('mark_non_order')" type="button" :disabled="saving" class="rounded border px-3 py-2 text-sm disabled:opacity-50" @click="openActionDialog('non_order')">
|
||||
{{ t('chat.shippingOrderReview.markNonOrder') }}
|
||||
</button>
|
||||
<button v-if="activeCase?.available_actions.includes('mark_quality_issue')" type="button" :disabled="saving" class="rounded border px-3 py-2 text-sm disabled:opacity-50" @click="openActionDialog('quality_issue')">
|
||||
{{ t('chat.shippingOrderReview.markQualityIssue') }}
|
||||
</button>
|
||||
<button v-if="activeCase?.available_actions.includes('reparse')" type="button" :disabled="saving" class="inline-flex items-center gap-1 rounded border px-3 py-2 text-sm disabled:opacity-50" @click="openActionDialog('reparse')">
|
||||
<RefreshCw class="h-4 w-4" />{{ t('chat.shippingOrderReview.reparse') }}
|
||||
</button>
|
||||
<label v-if="activeCase?.available_actions.includes('mark_quality_issue')" class="cursor-pointer rounded border px-3 py-2 text-sm">
|
||||
<input class="sr-only" type="file" accept="application/pdf,.pdf" :disabled="saving" @change="selectReplacement">
|
||||
{{ t('chat.shippingOrderReview.uploadReplacement') }}
|
||||
</label>
|
||||
<button v-if="activeCase?.available_actions.includes('validate')" type="button" :disabled="saving" class="inline-flex items-center gap-1 rounded bg-sky-600 px-3 py-2 text-sm text-white disabled:opacity-50" @click="reportSave(() => validate())">
|
||||
<Save class="h-4 w-4" />{{ t('chat.shippingOrderReview.saveNow') }}
|
||||
</button>
|
||||
<button v-if="activeCase?.available_actions.includes('confirm')" type="button" :disabled="saving" class="rounded bg-emerald-600 px-3 py-2 text-sm text-white disabled:opacity-50" @click="openActionDialog('confirm')">
|
||||
{{ t('chat.shippingOrderReview.confirmCreate') }}
|
||||
</button>
|
||||
</footer>
|
||||
|
||||
<ReviewActionConfirmDialog
|
||||
v-if="actionDialogOpen && pendingAction"
|
||||
v-model="actionDialogOpen"
|
||||
:action="pendingAction"
|
||||
:confirm-loading="saving"
|
||||
@confirm="submitPendingAction"
|
||||
@cancel="pendingReplaceFile = null"
|
||||
/>
|
||||
</main>
|
||||
</template>
|
||||
Reference in new issue
Block a user