feat(shipping-notice): 增强订单抽取与审计功能,支持取消与保留策略
- 在环境配置中新增进度细化、订单提取取消与审计导出相关的开关 - 实现订单抽取运行的取消功能,允许管理员在运行中进行操作 - 引入审计事件的保留策略,支持三年保留期的自动清理 - 更新相关模型与服务,确保新功能的完整性与可追溯性 - 增强文档与代码注释,反映新的业务逻辑与审计要求
This commit is contained in:
1 parent
c85997884b
commit
95cdfe66b0
158 files changed
+19005
-1201
No files matched your search
@@ -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,
|
||||
|
||||
Reference in new issue
Block a user