feat(shipping-notice): 增强订单抽取与审计功能,支持取消与保留策略
- 在环境配置中新增进度细化、订单提取取消与审计导出相关的开关 - 实现订单抽取运行的取消功能,允许管理员在运行中进行操作 - 引入审计事件的保留策略,支持三年保留期的自动清理 - 更新相关模型与服务,确保新功能的完整性与可追溯性 - 增强文档与代码注释,反映新的业务逻辑与审计要求
This commit is contained in:
1 parent
c85997884b
commit
95cdfe66b0
158 files changed
+19005
-1201
No files matched your search
@@ -82,9 +82,21 @@ export type ShippingOrderExtractionDiagnosticAutoFreezePolicy = {
|
||||
|
||||
export type ShippingOrderExtractionDiagnosticRun = {
|
||||
run_no: string; status: string; phase: string; conversation_id: string;
|
||||
attempt_count: number; current_event_code?: string | null; created_at?: string | null; started_at?: string | null;
|
||||
candidate_materialized_at?: string | null; finished_at?: string | null; error_code?: string | null; durations_ms: Record<string, number | null>;
|
||||
user_id?: number | null;
|
||||
attempt_count: number; progress_version?: number | null;
|
||||
current_event_code?: string | null; created_at?: string | null; started_at?: string | null;
|
||||
candidate_materialized_at?: string | null; finished_at?: string | null; last_activity_at?: string | null;
|
||||
error_code?: string | null; durations_ms: Record<string, number | null>;
|
||||
result_counts: Record<string, number>;
|
||||
cancellation?: {
|
||||
requested: boolean;
|
||||
completed: boolean;
|
||||
in_flight: boolean;
|
||||
requested_at?: string | null;
|
||||
completed_at?: string | null;
|
||||
actor_type?: string | null;
|
||||
reason_code?: string | null;
|
||||
} | null;
|
||||
auto_freeze_policy: ShippingOrderExtractionDiagnosticAutoFreezePolicy;
|
||||
};
|
||||
export type ShippingOrderExtractionDiagnosticDetail = {
|
||||
@@ -93,13 +105,50 @@ export type ShippingOrderExtractionDiagnosticDetail = {
|
||||
units: Array<{ unit_id: number; position: number; unit_type: string; document_type: string; status: string; attempt_count: number; duration_ms?: number | null; error_code?: string | null; route_decisions: Array<{ attempt_no: number; execution_mode: 'deterministic' | 'review_required' | 'skipped'; match_status: string; selected_profile_code?: string | null; selected_profile_version?: number | null; auto_create_approved?: boolean | null; candidate_count: number; table_count: number; approved_table_count: number; candidates: Array<{ profile_code: string; version: number; score: number; hard_match: boolean; reason_codes: string[]; missing_required_anchor_ids?: string[] }>; fallback_reason_codes: string[] }> }>;
|
||||
progress_events: Array<{ sequence_no: number; visibility: 'workspace' | 'admin'; event_code: string; status?: string | null; unit_id?: number | null; document_id?: number | null; reason_code?: string | null; summary?: Record<string, unknown> | null; occurred_at?: string | null }>;
|
||||
};
|
||||
export const listShippingOrderExtractionDiagnosticRuns = (page = 1, pageSize = 25, status = '') => {
|
||||
export type ShippingOrderExtractionHealth = {
|
||||
generated_at: string;
|
||||
health_status: 'healthy' | 'degraded' | string;
|
||||
window_hours: number;
|
||||
thresholds: Record<string, number>;
|
||||
counts: Record<string, number>;
|
||||
status_counts: Record<string, number>;
|
||||
phase_counts: Record<string, number>;
|
||||
error_code_counts: Record<string, number>;
|
||||
failure_rate: number;
|
||||
latency: Record<string, { count: number; avg_ms?: number | null; p50_ms?: number | null; p95_ms?: number | null; max_ms?: number | null }>;
|
||||
stale_run_nos: string[];
|
||||
};
|
||||
export const listShippingOrderExtractionDiagnosticRuns = (
|
||||
page = 1,
|
||||
pageSize = 25,
|
||||
status = '',
|
||||
options?: { staleOnly?: boolean; cancellationInFlight?: boolean },
|
||||
) => {
|
||||
const params = new URLSearchParams({ page: String(page), page_size: String(pageSize) });
|
||||
if (status) params.set('status', status);
|
||||
if (options?.staleOnly) params.set('stale_only', 'true');
|
||||
if (options?.cancellationInFlight) params.set('cancellation_in_flight', 'true');
|
||||
return requestJson<{ items: ShippingOrderExtractionDiagnosticRun[]; total: number; page: number; page_size: number }>(`/api/admin/shipping-notice/order-extraction-runs?${params}`, auth());
|
||||
};
|
||||
export const getShippingOrderExtractionDiagnosticRun = (runNo: string) =>
|
||||
requestJson<ShippingOrderExtractionDiagnosticDetail>(`/api/admin/shipping-notice/order-extraction-runs/${encodeURIComponent(runNo)}`, auth());
|
||||
/** 管理员取消任意活跃订单抽取 Run;代取消必须提供 reason。 */
|
||||
export const cancelShippingOrderExtractionRun = (
|
||||
runNo: string,
|
||||
payload: { reason?: string | null; reason_code?: string | null } = {},
|
||||
) => requestJson<{ run: ShippingOrderExtractionDiagnosticRun }>(
|
||||
`/api/admin/shipping-notice/order-extraction-runs/${encodeURIComponent(runNo)}/cancel`,
|
||||
{ method: 'POST', body: JSON.stringify(payload), ...jsonAuth() },
|
||||
);
|
||||
|
||||
/** 管理员健康聚合:积压、失败率、P50/P95 时延与卡住 Run 编号。 */
|
||||
export const getShippingOrderExtractionHealth = (windowHours = 24) => {
|
||||
const params = new URLSearchParams({ window_hours: String(windowHours) });
|
||||
return requestJson<ShippingOrderExtractionHealth>(
|
||||
`/api/admin/shipping-notice/order-extraction-runs/health?${params}`,
|
||||
auth(),
|
||||
);
|
||||
};
|
||||
|
||||
/** 下载管理员可访问的库存快照,并保留服务端指定的原始文件名。 */
|
||||
export const downloadShippingInventorySnapshot = async (snapshotId: number, fallbackName: string): Promise<void> => {
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
/**
|
||||
* features/admin/api/shipping-audit.api.ts
|
||||
* 用途:货代统一审计查询/详情/导出 HTTP 客户端。
|
||||
* 依赖:shared/api/client、getAuthHeaders。
|
||||
* 逻辑:由 ShippingAuditCenterPage 调用;导出走 blob 下载并保留服务端文件名。
|
||||
*/
|
||||
import { requestJson } from '@/shared/api/client';
|
||||
import { getAuthHeaders } from '@/shared/utils/auth';
|
||||
|
||||
export type ShippingAuditEventSummary = {
|
||||
id: number;
|
||||
event_type: string;
|
||||
aggregate_type: string;
|
||||
aggregate_id: string;
|
||||
run_no?: string | null;
|
||||
task_no?: string | null;
|
||||
document_id?: string | null;
|
||||
conversation_id?: string | null;
|
||||
session_item_id?: string | null;
|
||||
review_case_no?: string | null;
|
||||
owner_user_id?: string | null;
|
||||
actor_type: string;
|
||||
actor_id?: string | null;
|
||||
request_id?: string | null;
|
||||
operation_id?: string | null;
|
||||
result?: string | null;
|
||||
action?: string | null;
|
||||
reason_code?: string | null;
|
||||
error_code?: string | null;
|
||||
has_snapshots: boolean;
|
||||
created_at?: string | null;
|
||||
};
|
||||
|
||||
export type ShippingAuditDiffRow = {
|
||||
key: string;
|
||||
change: 'added' | 'removed' | 'changed' | string;
|
||||
before: unknown;
|
||||
after: unknown;
|
||||
};
|
||||
|
||||
export type ShippingAuditEventDetail = ShippingAuditEventSummary & {
|
||||
before_snapshot?: Record<string, unknown> | null;
|
||||
after_snapshot?: Record<string, unknown> | null;
|
||||
diff?: ShippingAuditDiffRow[];
|
||||
metadata?: Record<string, unknown>;
|
||||
evidence_refs?: Array<Record<string, unknown>>;
|
||||
artifact_refs?: Array<Record<string, unknown>>;
|
||||
};
|
||||
|
||||
export type ShippingAuditFilters = {
|
||||
event_type?: string;
|
||||
actor_type?: string;
|
||||
/** 操作者用户 ID;与后端 audit_query_service.actor_id 对齐 */
|
||||
actor_id?: string;
|
||||
run_no?: string;
|
||||
task_no?: string;
|
||||
document_id?: string;
|
||||
operation_id?: string;
|
||||
request_id?: string;
|
||||
/** 会话 ID;与后端 conversation_id 筛选对齐 */
|
||||
conversation_id?: string;
|
||||
/** 会话 PDF 工作项编号 */
|
||||
session_item_id?: string;
|
||||
/** 人工复核 Case 编号 */
|
||||
review_case_no?: string;
|
||||
/** 工作项属主用户 ID */
|
||||
owner_user_id?: string;
|
||||
result?: string;
|
||||
created_from?: string;
|
||||
created_to?: string;
|
||||
q?: string;
|
||||
};
|
||||
|
||||
const auth = () => ({ headers: getAuthHeaders() });
|
||||
|
||||
/**
|
||||
* 分页查询审计事件列表(无快照全文)。
|
||||
*/
|
||||
export function listShippingAuditEvents(page = 1, pageSize = 25, filters: ShippingAuditFilters = {}) {
|
||||
const params = new URLSearchParams({ page: String(page), page_size: String(pageSize) });
|
||||
Object.entries(filters).forEach(([key, value]) => {
|
||||
if (value) params.set(key, String(value));
|
||||
});
|
||||
return requestJson<{ items: ShippingAuditEventSummary[]; total: number; page: number; page_size: number }>(
|
||||
`/api/admin/shipping-notice/audit-events?${params}`,
|
||||
auth(),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取单条审计详情(含白名单快照与 diff)。
|
||||
*/
|
||||
export function getShippingAuditEvent(eventId: number) {
|
||||
return requestJson<ShippingAuditEventDetail>(
|
||||
`/api/admin/shipping-notice/audit-events/${encodeURIComponent(String(eventId))}`,
|
||||
auth(),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 受控导出审计 CSV/JSON,并触发浏览器下载。
|
||||
*/
|
||||
export async function exportShippingAuditEvents(
|
||||
filters: ShippingAuditFilters = {},
|
||||
format: 'csv' | 'json' = 'csv',
|
||||
): Promise<void> {
|
||||
const response = await fetch('/api/admin/shipping-notice/audit-events/export', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
...getAuthHeaders(),
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({ ...filters, format, limit: 2000 }),
|
||||
});
|
||||
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
||||
const blob = await response.blob();
|
||||
const disposition = response.headers.get('Content-Disposition') || '';
|
||||
const filename = disposition.match(/filename="?([^";]+)"?/i)?.[1]
|
||||
|| `shipping-audit.${format}`;
|
||||
const objectUrl = URL.createObjectURL(blob);
|
||||
const anchor = document.createElement('a');
|
||||
anchor.href = objectUrl;
|
||||
anchor.download = filename;
|
||||
anchor.click();
|
||||
URL.revokeObjectURL(objectUrl);
|
||||
}
|
||||
@@ -391,6 +391,15 @@ export const getOrderProfilePageTextCandidates = (profileId: number, documentId:
|
||||
auth(),
|
||||
);
|
||||
|
||||
/** 读取当前受控样本中框选区域的坐标文本;仅用于画布生成文档匹配锚点。 */
|
||||
export const readOrderProfilePreviewPageRegionText = (
|
||||
profileId: number, documentId: number, pageNo: number, region: { x0: number; y0: number; x1: number; y1: number },
|
||||
) => requestJson<{ document_id: number; page_no: number; text: string; source: string | null; status: 'needs_review' }>(
|
||||
`/api/admin/shipping-notice/order-document-profiles/${profileId}/preview-pages/${pageNo}/region-text`, {
|
||||
method: 'POST', body: JSON.stringify({ document_id: documentId, region }), ...jsonAuth(),
|
||||
},
|
||||
);
|
||||
|
||||
/** 使用当前 Profile 绑定样本执行局部坐标重建候选。 */
|
||||
export const previewOrderProfileRegion = (
|
||||
profileId: number, documentId: number, tableId: string, definition: ShippingOrderDocumentProfile['definition'],
|
||||
@@ -426,8 +435,8 @@ export const removeOrderProfileTestSample = (suiteId: number, sampleId: number)
|
||||
);
|
||||
|
||||
/** 列出未参与当前模板标注/训练且可用于盲测的受控订单样本。 */
|
||||
export const listOrderProfileBlindTestAvailableSamples = (suiteId: number) => requestJson<{ samples: OrderProfileBlindTestAvailableSample[] }>(
|
||||
`/api/admin/shipping-notice/order-document-profile-test-suites/${suiteId}/available-samples`, auth(),
|
||||
export const listOrderProfileBlindTestAvailableSamples = (suiteId: number, signal?: AbortSignal) => requestJson<{ samples: OrderProfileBlindTestAvailableSample[] }>(
|
||||
`/api/admin/shipping-notice/order-document-profile-test-suites/${suiteId}/available-samples`, { ...auth(), signal },
|
||||
);
|
||||
/** 自动运行独立样本,候选仅供管理员勾选复核,尚未写入真值。 */
|
||||
export const previewOrderProfileBlindTestCandidate = (suiteId: number, payload: { document_id: number; table_id: string }) => requestJson<OrderProfileBlindTestCandidate>(
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
/**
|
||||
* features/admin/api/shipping-review-supervision.api.ts
|
||||
* 用途:管理员跨用户会话 PDF 工作项监管 HTTP 客户端。
|
||||
* 依赖:shared/api/client、chat 域 ShippingSessionWorkItem 类型。
|
||||
* 逻辑:由 ShippingReviewSupervisionPage 调用;终止/撤销须理由与 confirm_token。
|
||||
*/
|
||||
import { requestJson } from '@/shared/api/client';
|
||||
import { getAuthHeaders } from '@/shared/utils/auth';
|
||||
import type { ShippingSessionWorkItem } from '@/features/chat/types/shipping.api.types';
|
||||
|
||||
export type ShippingReviewSupervisionFilters = {
|
||||
lifecycle_status?: string;
|
||||
owner_user_id?: string;
|
||||
conversation_id?: string;
|
||||
q?: string;
|
||||
};
|
||||
|
||||
export type ShippingReviewSupervisionPage = {
|
||||
items: ShippingSessionWorkItem[];
|
||||
total: number;
|
||||
page: number;
|
||||
page_size: number;
|
||||
};
|
||||
|
||||
export const SUPERVISION_CONFIRM_TERMINATE = 'CONFIRM_TERMINATE';
|
||||
export const SUPERVISION_CONFIRM_REVOKE = 'CONFIRM_REVOKE';
|
||||
|
||||
const auth = () => ({ headers: getAuthHeaders() });
|
||||
|
||||
/**
|
||||
* 分页查询跨用户会话 PDF 工作项;服务端已做管理员鉴权。
|
||||
*/
|
||||
export function listShippingReviewSupervisionItems(
|
||||
page = 1,
|
||||
pageSize = 20,
|
||||
filters: ShippingReviewSupervisionFilters = {},
|
||||
) {
|
||||
const params = new URLSearchParams({
|
||||
page: String(page),
|
||||
page_size: String(pageSize),
|
||||
});
|
||||
if (filters.lifecycle_status) params.set('lifecycle_status', filters.lifecycle_status);
|
||||
if (filters.owner_user_id) params.set('owner_user_id', filters.owner_user_id);
|
||||
if (filters.conversation_id) params.set('conversation_id', filters.conversation_id);
|
||||
if (filters.q) params.set('q', filters.q);
|
||||
return requestJson<ShippingReviewSupervisionPage>(
|
||||
`/api/admin/shipping-notice/session-work-items?${params}`,
|
||||
auth(),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 管理员终止工作项;必须填写 reason 且 confirm_token 为 CONFIRM_TERMINATE。
|
||||
*/
|
||||
export function terminateShippingReviewSupervisionItem(
|
||||
itemNo: string,
|
||||
payload: { reason: string; confirm_token: typeof SUPERVISION_CONFIRM_TERMINATE },
|
||||
) {
|
||||
return requestJson<{ item: ShippingSessionWorkItem }>(
|
||||
`/api/admin/shipping-notice/session-work-items/${encodeURIComponent(itemNo)}/terminate`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: {
|
||||
...getAuthHeaders(),
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify(payload),
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 管理员 24 小时内撤销确认;必须填写 reason 且 confirm_token 为 CONFIRM_REVOKE。
|
||||
*/
|
||||
export function revokeShippingReviewSupervisionConfirmation(
|
||||
itemNo: string,
|
||||
payload: { reason: string; confirm_token: typeof SUPERVISION_CONFIRM_REVOKE },
|
||||
) {
|
||||
return requestJson<Record<string, unknown>>(
|
||||
`/api/admin/shipping-notice/session-work-items/${encodeURIComponent(itemNo)}/revoke-confirmation`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: {
|
||||
...getAuthHeaders(),
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify(payload),
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
/**
|
||||
* features/admin/api/shipping-review-supervision.spec.ts
|
||||
* 用途:复核监管台 API 契约——confirm_token 与理由必填边界。
|
||||
* 依赖:shipping-review-supervision.api 常量。
|
||||
* 逻辑:断言终止/撤销 token 稳定,便于前后端与 i18n 对齐。
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
SUPERVISION_CONFIRM_REVOKE,
|
||||
SUPERVISION_CONFIRM_TERMINATE,
|
||||
} from './shipping-review-supervision.api';
|
||||
|
||||
describe('shipping review supervision api contract', () => {
|
||||
it('requires stable terminate confirm token', () => {
|
||||
expect(SUPERVISION_CONFIRM_TERMINATE).toBe('CONFIRM_TERMINATE');
|
||||
});
|
||||
|
||||
it('requires stable revoke confirm token', () => {
|
||||
expect(SUPERVISION_CONFIRM_REVOKE).toBe('CONFIRM_REVOKE');
|
||||
});
|
||||
|
||||
it('rejects empty reason before submit in UI contract', () => {
|
||||
const reason = ' ';
|
||||
// 关键断言:监管台须在客户端拦截空理由,与服务端校验一致。
|
||||
expect(reason.trim().length).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -21,6 +21,8 @@ export interface ShippingConfigSubModuleMeta {
|
||||
| 'AdminShippingOrderSchema'
|
||||
| 'AdminShippingIdentityRules'
|
||||
| 'AdminShippingOrderExtractionRuns'
|
||||
| 'AdminShippingAudit'
|
||||
| 'AdminShippingReviewSupervision'
|
||||
| 'AdminShippingOrderDocumentProfiles';
|
||||
path:
|
||||
| 'shipping-notice'
|
||||
@@ -28,6 +30,8 @@ export interface ShippingConfigSubModuleMeta {
|
||||
| 'shipping-order-schema'
|
||||
| 'shipping-identity-rules'
|
||||
| 'shipping-order-extraction-runs'
|
||||
| 'shipping-audit'
|
||||
| 'shipping-review-supervision'
|
||||
| 'shipping-order-document-profiles';
|
||||
labelKey: string;
|
||||
groupKey: 'admin.nav.shippingOrderRecognition' | 'admin.nav.shippingInventoryManagement' | 'admin.nav.shippingRunAudit';
|
||||
@@ -69,6 +73,8 @@ export const SHIPPING_CONFIG_SUB_MODULE_METAS: ShippingConfigSubModuleMeta[] = [
|
||||
{ id: 'warehouse_mappings', routeName: 'AdminShippingInventory', path: 'shipping-notice', labelKey: 'admin.shippingInventory.externalMappings', groupKey: 'admin.nav.shippingInventoryManagement', query: { section: 'mappings' } },
|
||||
{ id: 'routing_rules', routeName: 'AdminShippingInventory', path: 'shipping-notice', labelKey: 'admin.shippingInventory.rules', groupKey: 'admin.nav.shippingInventoryManagement', query: { section: 'rules' } },
|
||||
{ id: 'shipping_templates', routeName: 'AdminShippingInventory', path: 'shipping-notice', labelKey: 'admin.shippingInventory.excelTemplates', groupKey: 'admin.nav.shippingInventoryManagement', query: { section: 'templates' } },
|
||||
{ id: 'shipping_audit', routeName: 'AdminShippingAudit', path: 'shipping-audit', labelKey: 'admin.nav.shippingAudit', groupKey: 'admin.nav.shippingRunAudit' },
|
||||
{ id: 'shipping_review_supervision', routeName: 'AdminShippingReviewSupervision', path: 'shipping-review-supervision', labelKey: 'admin.nav.shippingReviewSupervision', groupKey: 'admin.nav.shippingRunAudit' },
|
||||
{ id: 'inventory_snapshots', routeName: 'AdminShippingInventory', path: 'shipping-notice', labelKey: 'admin.shippingInventory.snapshots', groupKey: 'admin.nav.shippingRunAudit', query: { section: 'snapshots' } },
|
||||
{ id: 'export_records', routeName: 'AdminShippingInventory', path: 'shipping-notice', labelKey: 'admin.shippingInventory.exports', groupKey: 'admin.nav.shippingRunAudit', query: { section: 'exports' } },
|
||||
];
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
/**
|
||||
* features/admin/e2e/shipping-audit.spec.ts
|
||||
* 用途:阶段 4 管理员审计中心契约冒烟——Diff/导出权限、会话工作项筛选与脱敏边界。
|
||||
* 依赖:Vitest、shipping-audit.api 类型约定。
|
||||
* 逻辑:断言列表不含快照字段;详情 Diff 仅白名单键;筛选 DTO 含 session 工作项字段。
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import type {
|
||||
ShippingAuditDiffRow,
|
||||
ShippingAuditEventDetail,
|
||||
ShippingAuditEventSummary,
|
||||
ShippingAuditFilters,
|
||||
} from '@/features/admin/api/shipping-audit.api';
|
||||
|
||||
describe('shipping audit center e2e contract', () => {
|
||||
it('list summary must not carry snapshot bodies', () => {
|
||||
const summary: ShippingAuditEventSummary = {
|
||||
id: 1,
|
||||
event_type: 'candidate_promoted',
|
||||
aggregate_type: 'shipping_task',
|
||||
aggregate_id: 'ST-1',
|
||||
actor_type: 'user',
|
||||
has_snapshots: true,
|
||||
run_no: 'SNER-1',
|
||||
task_no: 'ST-1',
|
||||
operation_id: 'op-1',
|
||||
};
|
||||
// 关键断言:列表 DTO 无 before/after 快照字段,避免误渲染正文。
|
||||
expect('before_snapshot' in summary).toBe(false);
|
||||
expect('after_snapshot' in summary).toBe(false);
|
||||
expect(summary.has_snapshots).toBe(true);
|
||||
});
|
||||
|
||||
it('detail diff only exposes whitelist change rows', () => {
|
||||
const detail: ShippingAuditEventDetail = {
|
||||
id: 2,
|
||||
event_type: 'order_extraction_run_status_changed',
|
||||
aggregate_type: 'order_extraction_run',
|
||||
aggregate_id: 'SNER-2',
|
||||
actor_type: 'system',
|
||||
has_snapshots: true,
|
||||
before_snapshot: { status: 'queued' },
|
||||
after_snapshot: { status: 'processing' },
|
||||
diff: [
|
||||
{ key: 'status', change: 'changed', before: 'queued', after: 'processing' },
|
||||
] satisfies ShippingAuditDiffRow[],
|
||||
};
|
||||
expect(detail.diff?.[0]?.key).toBe('status');
|
||||
expect(JSON.stringify(detail)).not.toContain('email_body');
|
||||
expect(JSON.stringify(detail)).not.toContain('https://');
|
||||
});
|
||||
|
||||
it('export disabled error code is stable for i18n', () => {
|
||||
const code = 'SHIPPING_NOTICE.AUDIT_EXPORT_FEATURE_DISABLED';
|
||||
expect(code.startsWith('SHIPPING_NOTICE.')).toBe(true);
|
||||
});
|
||||
|
||||
it('audit filters carry session work item query keys', () => {
|
||||
const filters: ShippingAuditFilters = {
|
||||
conversation_id: 'conv-1',
|
||||
session_item_id: 'SPWI-1',
|
||||
review_case_no: 'SRC-1',
|
||||
owner_user_id: '42',
|
||||
};
|
||||
// 关键断言:前端筛选 DTO 与 admin API _audit_filters_from_request 键对齐。
|
||||
expect(Object.keys(filters).sort()).toEqual([
|
||||
'conversation_id',
|
||||
'owner_user_id',
|
||||
'review_case_no',
|
||||
'session_item_id',
|
||||
]);
|
||||
});
|
||||
|
||||
it('detail exposes session work item context without snapshots in summary', () => {
|
||||
const detail: ShippingAuditEventDetail = {
|
||||
id: 3,
|
||||
event_type: 'session_work_item_confirmed',
|
||||
aggregate_type: 'shipping_session_pdf_work_item',
|
||||
aggregate_id: 'SPWI-3',
|
||||
actor_type: 'user',
|
||||
has_snapshots: true,
|
||||
conversation_id: 'conv-3',
|
||||
session_item_id: 'SPWI-3',
|
||||
review_case_no: 'SRC-3',
|
||||
owner_user_id: '99',
|
||||
diff: [],
|
||||
};
|
||||
expect(detail.session_item_id).toBe('SPWI-3');
|
||||
expect(detail.owner_user_id).toBe('99');
|
||||
expect('before_snapshot' in (detail as ShippingAuditEventSummary)).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,316 @@
|
||||
<!--
|
||||
features/admin/modules/shipping-audit/ShippingAuditCenterPage.vue
|
||||
用途:管理员货代统一审计中心——筛选、详情 Diff、受控导出。
|
||||
依赖:shipping-audit.api、Vue I18n、Vue Router。
|
||||
逻辑:列表展示会话/工作项/Case 关联字段;不含快照全文;打开详情才拉取白名单前后差异;导出写服务端访问审计。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { onMounted, ref } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import {
|
||||
exportShippingAuditEvents,
|
||||
getShippingAuditEvent,
|
||||
listShippingAuditEvents,
|
||||
type ShippingAuditEventDetail,
|
||||
type ShippingAuditEventSummary,
|
||||
type ShippingAuditFilters,
|
||||
} from '@/features/admin/api/shipping-audit.api';
|
||||
|
||||
const { t } = useI18n();
|
||||
const loading = ref(false);
|
||||
const detailLoading = ref(false);
|
||||
const exporting = ref(false);
|
||||
const error = ref('');
|
||||
const page = ref(1);
|
||||
const pageSize = 25;
|
||||
const total = ref(0);
|
||||
const rows = ref<ShippingAuditEventSummary[]>([]);
|
||||
const detail = ref<ShippingAuditEventDetail | null>(null);
|
||||
const filters = ref<ShippingAuditFilters>({
|
||||
event_type: '',
|
||||
actor_type: '',
|
||||
actor_id: '',
|
||||
run_no: '',
|
||||
task_no: '',
|
||||
document_id: '',
|
||||
conversation_id: '',
|
||||
session_item_id: '',
|
||||
review_case_no: '',
|
||||
owner_user_id: '',
|
||||
operation_id: '',
|
||||
request_id: '',
|
||||
result: '',
|
||||
created_from: '',
|
||||
created_to: '',
|
||||
q: '',
|
||||
});
|
||||
|
||||
/**
|
||||
* 将 datetime-local 值规范为 ISO 字符串供 API 查询。
|
||||
*/
|
||||
function normalizeDateTimeFilter(value?: string): string {
|
||||
const raw = String(value || '').trim();
|
||||
if (!raw) return '';
|
||||
const date = new Date(raw);
|
||||
if (Number.isNaN(date.getTime())) return raw;
|
||||
return date.toISOString();
|
||||
}
|
||||
|
||||
const formatTime = (value?: string | null) => (value ? new Date(value).toLocaleString() : '—');
|
||||
|
||||
/**
|
||||
* 加载审计列表;服务端已做管理员鉴权与访问留痕。
|
||||
*/
|
||||
async function load() {
|
||||
loading.value = true;
|
||||
error.value = '';
|
||||
try {
|
||||
const payload: ShippingAuditFilters = {
|
||||
...filters.value,
|
||||
created_from: normalizeDateTimeFilter(filters.value.created_from),
|
||||
created_to: normalizeDateTimeFilter(filters.value.created_to),
|
||||
};
|
||||
const response = await listShippingAuditEvents(page.value, pageSize, payload);
|
||||
rows.value = response.items;
|
||||
total.value = response.total;
|
||||
} catch {
|
||||
error.value = t('admin.shippingAudit.loadFailed');
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 应用筛选并回到第一页。
|
||||
*/
|
||||
async function applyFilters() {
|
||||
page.value = 1;
|
||||
await load();
|
||||
}
|
||||
|
||||
/**
|
||||
* 打开详情抽屉并加载白名单 Diff。
|
||||
*/
|
||||
async function openDetail(eventId: number) {
|
||||
detailLoading.value = true;
|
||||
error.value = '';
|
||||
try {
|
||||
detail.value = await getShippingAuditEvent(eventId);
|
||||
} catch {
|
||||
error.value = t('admin.shippingAudit.detailFailed');
|
||||
} finally {
|
||||
detailLoading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 导出当前筛选条件下的 CSV。
|
||||
*/
|
||||
async function exportCsv() {
|
||||
exporting.value = true;
|
||||
error.value = '';
|
||||
try {
|
||||
const payload: ShippingAuditFilters = {
|
||||
...filters.value,
|
||||
created_from: normalizeDateTimeFilter(filters.value.created_from),
|
||||
created_to: normalizeDateTimeFilter(filters.value.created_to),
|
||||
};
|
||||
await exportShippingAuditEvents(payload, 'csv');
|
||||
} catch {
|
||||
error.value = t('admin.shippingAudit.exportFailed');
|
||||
} finally {
|
||||
exporting.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
void load();
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="space-y-5 p-5 md:p-7" data-testid="shipping-audit-center">
|
||||
<header class="flex flex-wrap items-start justify-between gap-4">
|
||||
<div>
|
||||
<h1 class="section-title">{{ t('admin.shippingAudit.title') }}</h1>
|
||||
<p class="section-desc mt-1 max-w-3xl">{{ t('admin.shippingAudit.subtitle') }}</p>
|
||||
</div>
|
||||
<div class="flex gap-2">
|
||||
<button type="button" class="btn-secondary btn-sm" :disabled="exporting" @click="exportCsv">
|
||||
{{ exporting ? t('admin.shippingAudit.exporting') : t('admin.shippingAudit.export') }}
|
||||
</button>
|
||||
<button type="button" class="btn-secondary btn-sm" :disabled="loading" @click="load">
|
||||
{{ t('admin.shippingAudit.refresh') }}
|
||||
</button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div class="grid gap-3 rounded-xl border border-default bg-surface p-3 md:grid-cols-3 lg:grid-cols-4">
|
||||
<label class="space-y-1 text-xs text-secondary">
|
||||
<span>{{ t('admin.shippingAudit.filters.eventType') }}</span>
|
||||
<input v-model="filters.event_type" class="input-field text-sm" @keyup.enter="applyFilters">
|
||||
</label>
|
||||
<label class="space-y-1 text-xs text-secondary">
|
||||
<span>{{ t('admin.shippingAudit.filters.actorType') }}</span>
|
||||
<select v-model="filters.actor_type" class="select-field text-sm" @change="applyFilters">
|
||||
<option value="">{{ t('admin.shippingAudit.filters.all') }}</option>
|
||||
<option value="user">user</option>
|
||||
<option value="admin">admin</option>
|
||||
<option value="system">system</option>
|
||||
<option value="rpa">rpa</option>
|
||||
</select>
|
||||
</label>
|
||||
<label class="space-y-1 text-xs text-secondary">
|
||||
<span>{{ t('admin.shippingAudit.filters.actorId') }}</span>
|
||||
<input v-model="filters.actor_id" class="input-field text-sm" @keyup.enter="applyFilters">
|
||||
</label>
|
||||
<label class="space-y-1 text-xs text-secondary">
|
||||
<span>{{ t('admin.shippingAudit.filters.runNo') }}</span>
|
||||
<input v-model="filters.run_no" class="input-field text-sm" @keyup.enter="applyFilters">
|
||||
</label>
|
||||
<label class="space-y-1 text-xs text-secondary">
|
||||
<span>{{ t('admin.shippingAudit.filters.taskNo') }}</span>
|
||||
<input v-model="filters.task_no" class="input-field text-sm" @keyup.enter="applyFilters">
|
||||
</label>
|
||||
<label class="space-y-1 text-xs text-secondary">
|
||||
<span>{{ t('admin.shippingAudit.filters.documentId') }}</span>
|
||||
<input v-model="filters.document_id" class="input-field text-sm" @keyup.enter="applyFilters">
|
||||
</label>
|
||||
<label class="space-y-1 text-xs text-secondary">
|
||||
<span>{{ t('admin.shippingAudit.filters.conversationId') }}</span>
|
||||
<input v-model="filters.conversation_id" class="input-field text-sm" @keyup.enter="applyFilters">
|
||||
</label>
|
||||
<label class="space-y-1 text-xs text-secondary">
|
||||
<span>{{ t('admin.shippingAudit.filters.sessionItemId') }}</span>
|
||||
<input v-model="filters.session_item_id" class="input-field text-sm" @keyup.enter="applyFilters">
|
||||
</label>
|
||||
<label class="space-y-1 text-xs text-secondary">
|
||||
<span>{{ t('admin.shippingAudit.filters.reviewCaseNo') }}</span>
|
||||
<input v-model="filters.review_case_no" class="input-field text-sm" @keyup.enter="applyFilters">
|
||||
</label>
|
||||
<label class="space-y-1 text-xs text-secondary">
|
||||
<span>{{ t('admin.shippingAudit.filters.ownerUserId') }}</span>
|
||||
<input v-model="filters.owner_user_id" class="input-field text-sm" @keyup.enter="applyFilters">
|
||||
</label>
|
||||
<label class="space-y-1 text-xs text-secondary">
|
||||
<span>{{ t('admin.shippingAudit.filters.operationId') }}</span>
|
||||
<input v-model="filters.operation_id" class="input-field text-sm" @keyup.enter="applyFilters">
|
||||
</label>
|
||||
<label class="space-y-1 text-xs text-secondary">
|
||||
<span>{{ t('admin.shippingAudit.filters.requestId') }}</span>
|
||||
<input v-model="filters.request_id" class="input-field text-sm" @keyup.enter="applyFilters">
|
||||
</label>
|
||||
<label class="space-y-1 text-xs text-secondary">
|
||||
<span>{{ t('admin.shippingAudit.filters.result') }}</span>
|
||||
<input v-model="filters.result" class="input-field text-sm" @keyup.enter="applyFilters">
|
||||
</label>
|
||||
<label class="space-y-1 text-xs text-secondary">
|
||||
<span>{{ t('admin.shippingAudit.filters.createdFrom') }}</span>
|
||||
<input v-model="filters.created_from" type="datetime-local" class="input-field text-sm" @change="applyFilters">
|
||||
</label>
|
||||
<label class="space-y-1 text-xs text-secondary">
|
||||
<span>{{ t('admin.shippingAudit.filters.createdTo') }}</span>
|
||||
<input v-model="filters.created_to" type="datetime-local" class="input-field text-sm" @change="applyFilters">
|
||||
</label>
|
||||
<label class="space-y-1 text-xs text-secondary md:col-span-2 lg:col-span-1">
|
||||
<span>{{ t('admin.shippingAudit.filters.q') }}</span>
|
||||
<div class="flex gap-2">
|
||||
<input v-model="filters.q" class="input-field text-sm flex-1" @keyup.enter="applyFilters">
|
||||
<button type="button" class="btn-secondary btn-sm" @click="applyFilters">{{ t('admin.shippingAudit.apply') }}</button>
|
||||
</div>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<p v-if="error" class="rounded-lg border border-rose-200 bg-rose-50 p-3 text-sm text-rose-700">{{ error }}</p>
|
||||
|
||||
<div class="overflow-x-auto rounded-xl border border-default bg-surface">
|
||||
<table class="min-w-[1280px] w-full text-left text-sm">
|
||||
<thead class="border-b border-default bg-surface-soft text-xs text-muted">
|
||||
<tr>
|
||||
<th class="px-3 py-2">{{ t('admin.shippingAudit.columns.time') }}</th>
|
||||
<th class="px-3 py-2">{{ t('admin.shippingAudit.columns.event') }}</th>
|
||||
<th class="px-3 py-2">{{ t('admin.shippingAudit.columns.actor') }}</th>
|
||||
<th class="px-3 py-2">{{ t('admin.shippingAudit.columns.conversation') }}</th>
|
||||
<th class="px-3 py-2">{{ t('admin.shippingAudit.columns.sessionItem') }}</th>
|
||||
<th class="px-3 py-2">{{ t('admin.shippingAudit.columns.reviewCase') }}</th>
|
||||
<th class="px-3 py-2">{{ t('admin.shippingAudit.columns.run') }}</th>
|
||||
<th class="px-3 py-2">{{ t('admin.shippingAudit.columns.task') }}</th>
|
||||
<th class="px-3 py-2">{{ t('admin.shippingAudit.columns.result') }}</th>
|
||||
<th class="px-3 py-2"></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-if="loading">
|
||||
<td colspan="10" class="px-3 py-8 text-center text-muted">{{ t('admin.shippingAudit.loading') }}</td>
|
||||
</tr>
|
||||
<tr v-else-if="!rows.length">
|
||||
<td colspan="10" class="px-3 py-8 text-center text-muted">{{ t('admin.shippingAudit.empty') }}</td>
|
||||
</tr>
|
||||
<tr v-for="row in rows" :key="row.id" class="border-b border-default last:border-0">
|
||||
<td class="px-3 py-2 text-xs">{{ formatTime(row.created_at) }}</td>
|
||||
<td class="px-3 py-2">
|
||||
<div class="font-medium">{{ row.event_type }}</div>
|
||||
<div class="text-[11px] text-muted">{{ row.action || '—' }}</div>
|
||||
</td>
|
||||
<td class="px-3 py-2 text-xs">{{ row.actor_type }}<span v-if="row.actor_id"> / {{ row.actor_id }}</span></td>
|
||||
<td class="px-3 py-2 font-mono text-xs">{{ row.conversation_id || '—' }}</td>
|
||||
<td class="px-3 py-2 font-mono text-xs">{{ row.session_item_id || '—' }}</td>
|
||||
<td class="px-3 py-2 font-mono text-xs">{{ row.review_case_no || '—' }}</td>
|
||||
<td class="px-3 py-2 font-mono text-xs">{{ row.run_no || '—' }}</td>
|
||||
<td class="px-3 py-2 font-mono text-xs">{{ row.task_no || '—' }}</td>
|
||||
<td class="px-3 py-2">{{ row.result || '—' }}</td>
|
||||
<td class="px-3 py-2">
|
||||
<button type="button" class="text-brand-600 hover:underline" @click="openDetail(row.id)">
|
||||
{{ t('admin.shippingAudit.diff') }}
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<div class="flex items-center justify-end gap-3 text-sm">
|
||||
<span class="text-xs text-muted">{{ t('admin.shippingAudit.total', { count: total }) }}</span>
|
||||
<button type="button" class="rounded border border-default px-3 py-1.5 disabled:opacity-50" :disabled="page <= 1 || loading" @click="page -= 1; load()">{{ t('admin.shippingAudit.previous') }}</button>
|
||||
<span>{{ page }}</span>
|
||||
<button type="button" class="rounded border border-default px-3 py-1.5 disabled:opacity-50" :disabled="page * pageSize >= total || loading" @click="page += 1; load()">{{ t('admin.shippingAudit.next') }}</button>
|
||||
</div>
|
||||
|
||||
<div v-if="detail || detailLoading" class="fixed inset-0 z-50 flex justify-end bg-overlay" @click.self="detail = null">
|
||||
<aside class="h-full w-full max-w-xl overflow-y-auto bg-surface p-6 shadow-2xl">
|
||||
<div class="flex items-center justify-between">
|
||||
<h2 class="text-lg font-bold">{{ t('admin.shippingAudit.detailTitle') }}</h2>
|
||||
<button type="button" class="text-secondary" @click="detail = null">{{ t('admin.close') }}</button>
|
||||
</div>
|
||||
<p v-if="detailLoading" class="mt-6 text-muted">{{ t('admin.shippingAudit.loading') }}</p>
|
||||
<template v-else-if="detail">
|
||||
<dl class="mt-5 grid grid-cols-2 gap-3 text-sm">
|
||||
<dt>{{ t('admin.shippingAudit.columns.event') }}</dt><dd>{{ detail.event_type }}</dd>
|
||||
<dt>{{ t('admin.shippingAudit.columns.actor') }}</dt><dd>{{ detail.actor_type }} / {{ detail.actor_id || '—' }}</dd>
|
||||
<dt>{{ t('admin.shippingAudit.columns.run') }}</dt><dd class="font-mono text-xs">{{ detail.run_no || '—' }}</dd>
|
||||
<dt>{{ t('admin.shippingAudit.columns.task') }}</dt><dd class="font-mono text-xs">{{ detail.task_no || '—' }}</dd>
|
||||
<dt>{{ t('admin.shippingAudit.filters.conversationId') }}</dt><dd class="font-mono text-xs">{{ detail.conversation_id || '—' }}</dd>
|
||||
<dt>{{ t('admin.shippingAudit.filters.sessionItemId') }}</dt><dd class="font-mono text-xs">{{ detail.session_item_id || '—' }}</dd>
|
||||
<dt>{{ t('admin.shippingAudit.filters.reviewCaseNo') }}</dt><dd class="font-mono text-xs">{{ detail.review_case_no || '—' }}</dd>
|
||||
<dt>{{ t('admin.shippingAudit.filters.ownerUserId') }}</dt><dd class="font-mono text-xs">{{ detail.owner_user_id || '—' }}</dd>
|
||||
<dt>operation_id</dt><dd class="font-mono text-xs">{{ detail.operation_id || '—' }}</dd>
|
||||
<dt>request_id</dt><dd class="font-mono text-xs">{{ detail.request_id || '—' }}</dd>
|
||||
</dl>
|
||||
<h3 class="mt-6 font-semibold">{{ t('admin.shippingAudit.diff') }}</h3>
|
||||
<div v-if="detail.diff?.length" class="mt-2 space-y-2">
|
||||
<div
|
||||
v-for="row in detail.diff"
|
||||
:key="row.key"
|
||||
class="rounded-lg border border-default p-3 text-xs"
|
||||
>
|
||||
<div class="font-medium">{{ row.key }} · {{ row.change }}</div>
|
||||
<div class="mt-1 text-muted">{{ t('admin.shippingAudit.before') }}: {{ row.before == null ? '—' : JSON.stringify(row.before) }}</div>
|
||||
<div class="text-muted">{{ t('admin.shippingAudit.after') }}: {{ row.after == null ? '—' : JSON.stringify(row.after) }}</div>
|
||||
</div>
|
||||
</div>
|
||||
<p v-else class="mt-2 text-sm text-muted">{{ t('admin.shippingAudit.noDiff') }}</p>
|
||||
</template>
|
||||
</aside>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
+107
-7
@@ -5,7 +5,7 @@
|
||||
逻辑:验证页进入本页;管理员选择未参与建模的样本、复核候选后写入真值,再执行并批准,最后回到发布检查。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref } from 'vue';
|
||||
import { computed, onBeforeUnmount, onMounted, ref } from 'vue';
|
||||
import { useRoute, useRouter } from 'vue-router';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { BusinessError } from '@/shared/api/client';
|
||||
@@ -15,11 +15,15 @@ import {
|
||||
confirmOrderProfileBlindTestReviews,
|
||||
createOrderProfileTestSuite,
|
||||
executeOrderProfileTestSuite,
|
||||
createOrderProfileSample,
|
||||
getOrderProfileSampleStatus,
|
||||
listOrderProfileBlindTestAvailableSamples,
|
||||
listOrderProfileBoundSamples,
|
||||
listOrderProfileSamples,
|
||||
previewOrderProfileBlindTestCandidate,
|
||||
removeOrderProfileTestSample,
|
||||
} from '@/features/admin/api/shipping-order-document-profile.api';
|
||||
import { uploadFileAsset } from '@/shared/api/file-assets.api';
|
||||
import type {
|
||||
OrderProfileBlindTestAvailableSample,
|
||||
OrderProfileBlindTestCandidate,
|
||||
@@ -43,9 +47,22 @@ const working = ref(false);
|
||||
const hasTrainingSample = ref(false);
|
||||
const availableSamplesLoaded = ref(false);
|
||||
const availableSamplesLoading = ref(false);
|
||||
const uploadingSample = ref(false);
|
||||
const pendingUpload = ref<{ intakeNo: string; filename: string; state: 'parsing' | 'failed' } | null>(null);
|
||||
let uploadPollingTimer: number | null = null;
|
||||
let availableSamplesController: AbortController | null = null;
|
||||
let availableSamplesTimeout: number | null = null;
|
||||
|
||||
/** 当前选择仅以 API 列表中的 document/table 组合为准,避免浏览器提交伪造样本。 */
|
||||
const selectedSample = computed(() => availableSamples.value.find((item) => `${item.document_id}:${item.table_id}` === selectedSampleKey.value) || null);
|
||||
/** 用安全表格摘要区分同页多表;内部 table_id 仅作为请求身份,绝不展示给管理员。 */
|
||||
function sampleLabel(sample: OrderProfileBlindTestAvailableSample): string {
|
||||
const header = sample.header_preview.join(' / ');
|
||||
return t('admin.shippingOrderProfiles.blindTest.sampleOption', {
|
||||
filename: sample.filename, page: sample.page_no, table: sample.table_index,
|
||||
rows: sample.row_count, columns: sample.column_count, header,
|
||||
});
|
||||
}
|
||||
/** 盲测执行成功且尚未批准时才允许批准;批准后证据在服务端保持不可变。 */
|
||||
const canApprove = computed(() => hasTrainingSample.value && suite.value?.status === 'draft' && suite.value.latest_run?.status === 'passed');
|
||||
/** 将服务端安全失败码转为管理员可定位的摘要;不回显订单正文或人工真值。 */
|
||||
@@ -100,17 +117,93 @@ async function loadSuite(): Promise<void> {
|
||||
}
|
||||
}
|
||||
|
||||
/** 仅在管理员需要挑选盲测样本时加载候选摘要,避免页面首屏等待历史样本逐份证据校验。 */
|
||||
async function loadAvailableSamples(): Promise<void> {
|
||||
if (!suite.value || suite.value.status !== 'draft' || availableSamplesLoaded.value || availableSamplesLoading.value) return;
|
||||
/** 按需读取独立样本摘要;上传解析完成时可强制刷新并定位刚上传的文档。 */
|
||||
async function loadAvailableSamples(force = false): Promise<void> {
|
||||
if (!suite.value || suite.value.status !== 'draft' || (!force && availableSamplesLoaded.value) || availableSamplesLoading.value) return;
|
||||
availableSamplesController?.abort();
|
||||
if (availableSamplesTimeout) window.clearTimeout(availableSamplesTimeout);
|
||||
const controller = new AbortController();
|
||||
availableSamplesController = controller;
|
||||
availableSamplesLoading.value = true;
|
||||
let timedOut = false;
|
||||
availableSamplesTimeout = window.setTimeout(() => {
|
||||
timedOut = true;
|
||||
controller.abort();
|
||||
}, 15_000);
|
||||
try {
|
||||
availableSamples.value = (await listOrderProfileBlindTestAvailableSamples(suite.value.id)).samples;
|
||||
availableSamples.value = (await listOrderProfileBlindTestAvailableSamples(suite.value.id, controller.signal)).samples;
|
||||
availableSamplesLoaded.value = true;
|
||||
} catch (error) {
|
||||
if (timedOut) {
|
||||
message.error(t('admin.shippingOrderProfiles.blindTest.loadIndependentSamplesTimedOut'));
|
||||
} else if (!controller.signal.aborted) {
|
||||
report(error);
|
||||
}
|
||||
} finally {
|
||||
if (availableSamplesController === controller) {
|
||||
availableSamplesController = null;
|
||||
availableSamplesLoading.value = false;
|
||||
}
|
||||
if (availableSamplesTimeout) window.clearTimeout(availableSamplesTimeout);
|
||||
availableSamplesTimeout = null;
|
||||
}
|
||||
}
|
||||
|
||||
/** 停止上传样本的后台轮询,避免离开盲测页后继续向已卸载页面写入状态。 */
|
||||
function stopUploadPolling(): void {
|
||||
if (uploadPollingTimer) window.clearTimeout(uploadPollingTimer);
|
||||
uploadPollingTimer = null;
|
||||
}
|
||||
|
||||
/** 上传完成后精确选中同一 Intake 的首个可盲测表格,仍必须经过管理员预览和复核。 */
|
||||
async function pollUploadedSample(intakeNo: string): Promise<void> {
|
||||
try {
|
||||
const result = await getOrderProfileSampleStatus(intakeNo);
|
||||
if (result.parse_status === 'parsed' && result.document_count > 0) {
|
||||
const uploaded = (await listOrderProfileSamples()).find((item) => item.intake_no === intakeNo);
|
||||
await loadAvailableSamples(true);
|
||||
const selected = uploaded && availableSamples.value.find((item) => item.document_id === uploaded.document_id);
|
||||
if (selected) {
|
||||
selectedSampleKey.value = `${selected.document_id}:${selected.table_id}`;
|
||||
pendingUpload.value = null;
|
||||
message.success(t('admin.shippingOrderProfiles.wizard.sampleReady'));
|
||||
} else {
|
||||
pendingUpload.value = { intakeNo, filename: pendingUpload.value?.filename || '', state: 'failed' };
|
||||
message.error(t('admin.shippingOrderProfiles.blindTest.noIndependentSamples'));
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (['failed', 'error'].includes(result.parse_status)) {
|
||||
pendingUpload.value = { intakeNo, filename: pendingUpload.value?.filename || '', state: 'failed' };
|
||||
return;
|
||||
}
|
||||
uploadPollingTimer = window.setTimeout(() => void pollUploadedSample(intakeNo), 1500);
|
||||
} catch {
|
||||
uploadPollingTimer = window.setTimeout(() => void pollUploadedSample(intakeNo), 2000);
|
||||
}
|
||||
}
|
||||
|
||||
/** 上传 PDF/EML 到隔离模板样本池;上传后不会自动写入盲测真值。 */
|
||||
async function uploadIndependentSample(event: Event): Promise<void> {
|
||||
const input = event.target as HTMLInputElement;
|
||||
const file = input.files?.[0];
|
||||
input.value = '';
|
||||
if (!file || uploadingSample.value) return;
|
||||
if (!/\.(pdf|eml)$/i.test(file.name)) {
|
||||
message.error(t('admin.shippingOrderProfiles.sampleFileTypeInvalid'));
|
||||
return;
|
||||
}
|
||||
stopUploadPolling();
|
||||
uploadingSample.value = true;
|
||||
try {
|
||||
const asset = await uploadFileAsset(file);
|
||||
const intake = await createOrderProfileSample(asset.asset_no);
|
||||
pendingUpload.value = { intakeNo: intake.intake_no, filename: file.name, state: 'parsing' };
|
||||
void pollUploadedSample(intake.intake_no);
|
||||
} catch (error) {
|
||||
report(error);
|
||||
} finally {
|
||||
availableSamplesLoading.value = false;
|
||||
uploadingSample.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -239,6 +332,11 @@ function goToPublishCheck(): void {
|
||||
}
|
||||
|
||||
onMounted(loadSuite);
|
||||
onBeforeUnmount(() => {
|
||||
stopUploadPolling();
|
||||
availableSamplesController?.abort();
|
||||
if (availableSamplesTimeout) window.clearTimeout(availableSamplesTimeout);
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -261,7 +359,8 @@ onMounted(loadSuite);
|
||||
<h2>{{ t('admin.shippingOrderProfiles.blindTest.selectIndependentSample') }}</h2>
|
||||
<p v-if="!availableSamplesLoaded">{{ t('admin.shippingOrderProfiles.blindTest.loadIndependentSamplesHint') }}</p>
|
||||
<p v-else-if="!availableSamples.length">{{ t('admin.shippingOrderProfiles.blindTest.noIndependentSamples') }}</p>
|
||||
<div class="sample-picker"><button v-if="!availableSamplesLoaded" type="button" class="btn-secondary" :disabled="availableSamplesLoading" @click="loadAvailableSamples">{{ availableSamplesLoading ? t('admin.shippingOrderProfiles.blindTest.loadingIndependentSamples') : t('admin.shippingOrderProfiles.blindTest.loadIndependentSamples') }}</button><template v-else-if="availableSamples.length"><select v-model="selectedSampleKey" class="select-field"><option value="">{{ t('admin.shippingOrderProfiles.blindTest.selectSamplePlaceholder') }}</option><option v-for="sample in availableSamples" :key="`${sample.document_id}:${sample.table_id}`" :value="`${sample.document_id}:${sample.table_id}`">{{ sample.filename }} · P{{ sample.page_no }}</option></select><button type="button" class="btn-primary" :disabled="!selectedSample || working" @click="previewSample">{{ t('admin.shippingOrderProfiles.blindTest.addCurrentSample') }}</button></template></div>
|
||||
<div class="sample-picker"><label class="btn-secondary upload-sample"><input type="file" accept=".pdf,.eml,application/pdf,message/rfc822" :disabled="uploadingSample" @change="uploadIndependentSample"><span>{{ uploadingSample ? t('admin.shippingOrderProfiles.wizard.uploading') : t('admin.shippingOrderProfiles.wizard.uploadNewSample') }}</span></label><button v-if="!availableSamplesLoaded" type="button" class="btn-secondary" :disabled="availableSamplesLoading" @click="() => void loadAvailableSamples()">{{ availableSamplesLoading ? t('admin.shippingOrderProfiles.blindTest.loadingIndependentSamples') : t('admin.shippingOrderProfiles.blindTest.loadIndependentSamples') }}</button><template v-else-if="availableSamples.length"><select v-model="selectedSampleKey" class="select-field"><option value="">{{ t('admin.shippingOrderProfiles.blindTest.selectSamplePlaceholder') }}</option><option v-for="sample in availableSamples" :key="`${sample.document_id}:${sample.table_id}`" :value="`${sample.document_id}:${sample.table_id}`">{{ sampleLabel(sample) }}</option></select><button type="button" class="btn-primary" :disabled="!selectedSample || working" @click="previewSample">{{ t('admin.shippingOrderProfiles.blindTest.addCurrentSample') }}</button></template></div>
|
||||
<p v-if="pendingUpload" class="upload-status" :class="{ failed: pendingUpload.state === 'failed' }">{{ pendingUpload.filename }} · {{ pendingUpload.state === 'parsing' ? t('admin.shippingOrderProfiles.wizard.sampleParsing') : t('admin.shippingOrderProfiles.wizard.sampleParseFailed') }}</p>
|
||||
</section>
|
||||
|
||||
<section v-if="candidate" class="card candidate-card">
|
||||
@@ -296,6 +395,7 @@ header { align-items: flex-start; margin-bottom: 24px; } h1, h2, h3, p { margin:
|
||||
.card { display: grid; gap: 14px; margin-top: 14px; border: 1px solid var(--border-default); border-radius: 12px; background: var(--bg-surface); padding: 18px; }
|
||||
.status { color: var(--status-warning-fg); font-weight: 700; } .status.approved { color: var(--status-success-fg); } .status.superseded { color: var(--status-error-fg); }
|
||||
.sample-picker .select-field { min-width: 260px; } .candidate-card .input-field { padding: 8px; border-radius: 6px; } textarea.input-field { min-height: 72px; font-family: ui-monospace, monospace; }
|
||||
.upload-sample { position: relative; cursor: pointer; }.upload-sample input { position: absolute; width: 1px; height: 1px; opacity: 0; }.upload-status { margin: 10px 0 0; color: var(--status-info-fg); font-size: .85rem; }.upload-status.failed { color: var(--status-error-fg); }
|
||||
.candidate-card { grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); } .candidate-card > h2, .candidate-card > p, .candidate-card > button { grid-column: 1 / -1; }
|
||||
.review-item { display: grid; gap: 8px; border: 1px solid var(--border-default); border-radius: 8px; padding: 12px; } code { overflow-wrap: anywhere; white-space: pre-wrap; color: var(--text-primary); font-size: 12px; } label { display: flex; gap: 6px; align-items: center; }
|
||||
ul { display: grid; gap: 8px; margin: 0; padding: 0; list-style: none; } li { border-top: 1px solid var(--border-default); padding-top: 8px; }
|
||||
|
||||
+205
-12
@@ -32,6 +32,7 @@ import {
|
||||
previewOrderProfileOrderFieldValues,
|
||||
releaseOrderDocumentProfileEditLease,
|
||||
renewOrderDocumentProfileEditLease,
|
||||
readOrderProfilePreviewPageRegionText,
|
||||
suggestOrderProfileHeader,
|
||||
suggestOrderProfileOrderFields,
|
||||
saveOrderDocumentProfileDraft,
|
||||
@@ -41,6 +42,7 @@ import type {
|
||||
CoordinateReconstructionPreview,
|
||||
OrderFieldValuePreview,
|
||||
OrderProfileCanvasRegion,
|
||||
OrderProfileDocumentMatchAnchor,
|
||||
OrderProfileFieldRegion,
|
||||
OrderProfileRelativeRegion,
|
||||
OrderProfileBoundSample,
|
||||
@@ -120,6 +122,9 @@ let resolveRouteLeave: ((allowed: boolean) => void) | null = null;
|
||||
const suggestingRegions = ref(false);
|
||||
const suggestionProgress = ref("");
|
||||
const creationKind = ref<OrderProfileCanvasRegion["kind"] | null>(null);
|
||||
const pendingDocumentAnchorLabel = ref<OrderProfileCanvasRegion | null>(null);
|
||||
const pendingOrderFieldAnchor = ref<OrderProfileCanvasRegion | null>(null);
|
||||
const documentAnchorNotice = ref('');
|
||||
const history = ref<OrderProfileCanvasRegion[][]>([]);
|
||||
const future = ref<OrderProfileCanvasRegion[][]>([]);
|
||||
const editLeaseToken = ref<string | null>(null);
|
||||
@@ -146,6 +151,14 @@ const form = reactive({
|
||||
changeNote: "",
|
||||
});
|
||||
const regions = ref<OrderProfileCanvasRegion[]>([]);
|
||||
/** 文档匹配锚点独立于字段坐标;必须以固定标签和固定值关系区分模板。 */
|
||||
const documentMatch = reactive({
|
||||
requiredAnchors: [] as OrderProfileDocumentMatchAnchor[],
|
||||
optionalAnchors: [] as OrderProfileDocumentMatchAnchor[],
|
||||
minimumScore: 0.9,
|
||||
minimumMargin: 0.15,
|
||||
});
|
||||
const documentMatchDirty = ref(false);
|
||||
const lineFields = computed<ShippingOrderFieldConfig[]>(
|
||||
() =>
|
||||
schemas.value
|
||||
@@ -180,7 +193,9 @@ const selectedRegion = computed(
|
||||
/** 当前样本值只能来自本次按画布坐标回读的结果,禁止回退到旧的自动建议缓存。 */
|
||||
const selectedRegionSampleValue = computed(() => {
|
||||
const region = selectedRegion.value;
|
||||
if (region?.kind !== 'order_field' || !region.fieldCode) return null;
|
||||
if (!region || !['order_field', 'header_field'].includes(region.kind)) return null;
|
||||
if (region.suggestedValue) return region.suggestedValue;
|
||||
if (!region.fieldCode) return null;
|
||||
return orderFieldValuePreviews.value.find((item) => item.field_code === region.fieldCode)?.value || null;
|
||||
});
|
||||
/** 右侧选区值与画布标签共享同一个读取状态,禁止以旧建议值回退。 */
|
||||
@@ -199,6 +214,7 @@ const selectedRegionKindLabel = computed(() => {
|
||||
const translationKeys: Record<NonNullable<OrderProfileCanvasRegion['kind']>, string> = {
|
||||
order_anchor: 'orderAnchor', order_field: 'orderField', header_field: 'header',
|
||||
header: 'header', line: 'line', field: 'field', exclusion: 'exclusion',
|
||||
document_anchor_label: 'documentMatchAnchorLabel', document_anchor_value: 'documentMatchAnchorValue',
|
||||
};
|
||||
const translationKey = translationKeys[kind];
|
||||
return t(`admin.shippingOrderProfiles.workbench.${translationKey}`);
|
||||
@@ -260,7 +276,7 @@ const selectedFieldHeaderSuggestion = computed(() => {
|
||||
)
|
||||
: null;
|
||||
});
|
||||
const dirty = computed(() => history.value.length > 0);
|
||||
const dirty = computed(() => history.value.length > 0 || documentMatchDirty.value);
|
||||
/** 当前标注样本可同时作为训练证据;盲测样本仍由独立工作台维护。 */
|
||||
const currentSampleIsTraining = computed(() => boundSamples.value.some(
|
||||
(item) => item.sample_role === 'training' && item.document_id === form.documentId && item.table_id === form.tableId,
|
||||
@@ -362,6 +378,7 @@ const redo = () => {
|
||||
const addRegion = (
|
||||
kind: OrderProfileCanvasRegion["kind"],
|
||||
drawnRegion?: OrderProfileRelativeRegion,
|
||||
selectedText?: string | null,
|
||||
) => {
|
||||
checkpoint();
|
||||
const effectiveKind = kind === "header" ? "header_field" : kind;
|
||||
@@ -432,7 +449,7 @@ const addRegion = (
|
||||
const item: OrderProfileCanvasRegion = {
|
||||
id: `${effectiveKind}_${pageNo.value}_${sequence}`,
|
||||
kind: effectiveKind,
|
||||
label: t(`admin.shippingOrderProfiles.workbench.regionLabels.${effectiveKind}`, {
|
||||
label: selectedText || t(`admin.shippingOrderProfiles.workbench.regionLabels.${effectiveKind}`, {
|
||||
count: sequence,
|
||||
}),
|
||||
region,
|
||||
@@ -444,6 +461,7 @@ const addRegion = (
|
||||
? `order_field_${pageNo.value}_${sequence}`
|
||||
: null,
|
||||
fieldCode: null,
|
||||
suggestedValue: selectedText || null,
|
||||
pageNo: pageNo.value,
|
||||
};
|
||||
if (effectiveKind === "order_field" && selectedOrderAnchor) {
|
||||
@@ -456,14 +474,124 @@ const addRegion = (
|
||||
};
|
||||
/** 进入画布绘制模式;下一次拖拽创建对应区域,避免先生成默认框再反复移动。 */
|
||||
const startDrawing = (kind: OrderProfileCanvasRegion["kind"]) => {
|
||||
if (kind === 'document_anchor_label') pendingDocumentAnchorLabel.value = null;
|
||||
if (kind === 'order_anchor') pendingOrderFieldAnchor.value = null;
|
||||
creationKind.value = creationKind.value === kind ? null : kind;
|
||||
};
|
||||
/** 应用画布拖出的区域并退出绘制模式;字段自动归属当前或首个物理行。 */
|
||||
const createDrawnRegion = (region: OrderProfileRelativeRegion) => {
|
||||
/** 读取画布框内的冻结文字;空框只保留在本地,绝不触发一个必填项不完整的自动保存。 */
|
||||
const readDocumentAnchorText = async (region: OrderProfileRelativeRegion): Promise<string | null> => {
|
||||
if (!active.value || !form.documentId) return null;
|
||||
try {
|
||||
const result = await readOrderProfilePreviewPageRegionText(active.value.id, form.documentId, pageNo.value, region);
|
||||
return result.text.trim() || null;
|
||||
} catch (error) {
|
||||
fail(error);
|
||||
return null;
|
||||
}
|
||||
};
|
||||
/** 应用画布拖出的区域并退出绘制模式;匹配锚点从框内坐标文本建立,字段自动归属当前或首个物理行。 */
|
||||
const createDrawnRegion = async (region: OrderProfileRelativeRegion) => {
|
||||
const kind = creationKind.value;
|
||||
creationKind.value = null;
|
||||
if (kind === 'document_anchor_label') {
|
||||
const label = await readDocumentAnchorText(region);
|
||||
if (!label) {
|
||||
documentAnchorNotice.value = t('admin.shippingOrderProfiles.workbench.documentMatchAnchorTextMissing');
|
||||
creationKind.value = 'document_anchor_label';
|
||||
return;
|
||||
}
|
||||
// The first box is only a pending local gesture. Do not autosave a half-built
|
||||
// anchor because the v2 contract correctly requires both label and fixed value.
|
||||
history.value.push(snapshot());
|
||||
future.value = [];
|
||||
const id = `document_anchor_${pageNo.value}_${documentMatch.requiredAnchors.length + 1}`;
|
||||
const labelRegion: OrderProfileCanvasRegion = {
|
||||
id: `${id}_label`, kind, label, region, parentId: id, pageNo: pageNo.value,
|
||||
};
|
||||
regions.value.push(labelRegion);
|
||||
documentAnchorNotice.value = '';
|
||||
pendingDocumentAnchorLabel.value = labelRegion;
|
||||
selectedId.value = labelRegion.id;
|
||||
creationKind.value = 'document_anchor_value';
|
||||
return;
|
||||
}
|
||||
if (kind === 'document_anchor_value' && pendingDocumentAnchorLabel.value) {
|
||||
const value = await readDocumentAnchorText(region);
|
||||
if (!value) {
|
||||
documentAnchorNotice.value = t('admin.shippingOrderProfiles.workbench.documentMatchAnchorTextMissing');
|
||||
creationKind.value = 'document_anchor_value';
|
||||
return;
|
||||
}
|
||||
const labelRegion = pendingDocumentAnchorLabel.value;
|
||||
const anchorId = labelRegion.parentId!;
|
||||
const valueRegion: OrderProfileCanvasRegion = {
|
||||
id: `${anchorId}_value`, kind, label: value, region, parentId: anchorId, pageNo: pageNo.value,
|
||||
};
|
||||
regions.value.push(valueRegion);
|
||||
documentAnchorNotice.value = '';
|
||||
documentMatch.requiredAnchors.push({
|
||||
anchor_id: anchorId,
|
||||
label: labelRegion.label, value, value_position: region.y0 >= labelRegion.region.y1 ? 'below' : 'right',
|
||||
page_no: pageNo.value,
|
||||
label_region: labelRegion.region,
|
||||
value_region: valueRegion.region,
|
||||
minimum_evidence_level: 'coordinate',
|
||||
});
|
||||
pendingDocumentAnchorLabel.value = null;
|
||||
documentMatchDirty.value = true;
|
||||
selectedId.value = valueRegion.id;
|
||||
markLocalChange();
|
||||
schedulePreview();
|
||||
scheduleAutosave();
|
||||
return;
|
||||
}
|
||||
if (kind === 'order_anchor') {
|
||||
const label = await readDocumentAnchorText(region);
|
||||
if (!label) {
|
||||
documentAnchorNotice.value = t('admin.shippingOrderProfiles.workbench.documentMatchAnchorTextMissing');
|
||||
creationKind.value = 'order_anchor';
|
||||
return;
|
||||
}
|
||||
history.value.push(snapshot());
|
||||
future.value = [];
|
||||
const sequence = pageRegions.value.filter((item) => item.kind === 'order_anchor').length + 1;
|
||||
const orderFieldId = `order_field_${pageNo.value}_${sequence}`;
|
||||
const anchor: OrderProfileCanvasRegion = {
|
||||
id: `${orderFieldId}_anchor`, kind, label, region, orderFieldId, pageNo: pageNo.value,
|
||||
};
|
||||
regions.value.push(anchor);
|
||||
pendingOrderFieldAnchor.value = anchor;
|
||||
selectedId.value = anchor.id;
|
||||
documentAnchorNotice.value = t('admin.shippingOrderProfiles.workbench.orderFieldAnchorNext');
|
||||
creationKind.value = 'order_field';
|
||||
return;
|
||||
}
|
||||
if (kind === 'order_field' && pendingOrderFieldAnchor.value) {
|
||||
const value = await readDocumentAnchorText(region);
|
||||
if (!value) {
|
||||
documentAnchorNotice.value = t('admin.shippingOrderProfiles.workbench.documentMatchAnchorTextMissing');
|
||||
creationKind.value = 'order_field';
|
||||
return;
|
||||
}
|
||||
const anchor = pendingOrderFieldAnchor.value;
|
||||
const valueRegion: OrderProfileCanvasRegion = {
|
||||
id: anchor.orderFieldId!, kind, label: value, region, parentId: anchor.id,
|
||||
orderFieldId: anchor.orderFieldId, valueMode: 'single_line', suggestedValue: value, pageNo: pageNo.value,
|
||||
};
|
||||
regions.value.push(valueRegion);
|
||||
pendingOrderFieldAnchor.value = null;
|
||||
documentAnchorNotice.value = '';
|
||||
selectedId.value = valueRegion.id;
|
||||
markLocalChange();
|
||||
schedulePreview();
|
||||
scheduleAutosave();
|
||||
return;
|
||||
}
|
||||
if (kind) {
|
||||
addRegion(kind, region);
|
||||
const selectedText = kind === 'header_field'
|
||||
? await readDocumentAnchorText(region)
|
||||
: null;
|
||||
addRegion(kind, region, selectedText);
|
||||
schedulePreview();
|
||||
}
|
||||
};
|
||||
@@ -501,12 +629,20 @@ const removeSelected = () => {
|
||||
checkpoint();
|
||||
const removedId = selectedRegion.value.id;
|
||||
const removesSharedAnchor = selectedRegion.value.kind === "order_anchor";
|
||||
const documentAnchorId = ['document_anchor_label', 'document_anchor_value'].includes(selectedRegion.value.kind)
|
||||
? selectedRegion.value.parentId
|
||||
: null;
|
||||
// Removing a shared label removes dependent value boxes; removing one value box
|
||||
// preserves the label and any sibling customer/address field.
|
||||
regions.value = regions.value.filter(
|
||||
(item) => item.id !== removedId && item.parentId !== removedId &&
|
||||
(!removesSharedAnchor || item.parentId !== removedId),
|
||||
(!removesSharedAnchor || item.parentId !== removedId) && item.parentId !== documentAnchorId,
|
||||
);
|
||||
if (documentAnchorId) {
|
||||
documentMatch.requiredAnchors = documentMatch.requiredAnchors.filter((item) => item.anchor_id !== documentAnchorId);
|
||||
documentMatch.optionalAnchors = documentMatch.optionalAnchors.filter((item) => item.anchor_id !== documentAnchorId);
|
||||
documentMatchDirty.value = true;
|
||||
}
|
||||
selectedId.value = null;
|
||||
schedulePreview();
|
||||
};
|
||||
@@ -535,6 +671,15 @@ const updateRegion = (id: string, region: OrderProfileRelativeRegion) => {
|
||||
const normalized = normalizedCanvasRegion(region);
|
||||
if (!normalized) return;
|
||||
item.region = normalized;
|
||||
if (item.parentId && ['document_anchor_label', 'document_anchor_value'].includes(item.kind)) {
|
||||
const anchor = documentMatch.requiredAnchors.find((entry) => entry.anchor_id === item.parentId)
|
||||
|| documentMatch.optionalAnchors.find((entry) => entry.anchor_id === item.parentId);
|
||||
if (anchor) {
|
||||
if (item.kind === 'document_anchor_label') anchor.label_region = normalized;
|
||||
else anchor.value_region = normalized;
|
||||
documentMatchDirty.value = true;
|
||||
}
|
||||
}
|
||||
schedulePreview();
|
||||
scheduleOrderFieldSuggestionValues();
|
||||
};
|
||||
@@ -670,10 +815,10 @@ const definition = () => {
|
||||
document_match: {
|
||||
document_type: "purchase_order" as const,
|
||||
page_pattern: "one_or_more" as const,
|
||||
required_anchors: [],
|
||||
optional_anchors: [],
|
||||
minimum_score: 0.9,
|
||||
minimum_margin: 0.15,
|
||||
required_anchors: documentMatch.requiredAnchors.map((item) => ({ ...item })),
|
||||
optional_anchors: documentMatch.optionalAnchors.map((item) => ({ ...item })),
|
||||
minimum_score: documentMatch.minimumScore,
|
||||
minimum_margin: documentMatch.minimumMargin,
|
||||
},
|
||||
table_regions: tableRegions,
|
||||
order_field_layouts: regions.value
|
||||
@@ -807,6 +952,7 @@ const save = async (automatic = false) => {
|
||||
if (localChangeVersion === savingChangeVersion) {
|
||||
history.value = [];
|
||||
future.value = [];
|
||||
documentMatchDirty.value = false;
|
||||
}
|
||||
saveState.value = 'saved';
|
||||
autosaveFailures = 0;
|
||||
@@ -1248,6 +1394,16 @@ const mergeEquivalentOrderAnchors = (items: OrderProfileCanvasRegion[]) => {
|
||||
/** 从 v2 定义恢复区域,供草稿重开后继续在画布上编辑。 */
|
||||
const restoreRegions = (profile: ShippingOrderDocumentProfile) => {
|
||||
const restored: OrderProfileCanvasRegion[] = [
|
||||
...(profile.definition.document_match.required_anchors || []).flatMap<OrderProfileCanvasRegion>((anchor) => {
|
||||
if (!anchor.label_region || !anchor.value_region || !anchor.page_no) return [];
|
||||
return [{
|
||||
id: `${anchor.anchor_id}_label`, kind: 'document_anchor_label', label: anchor.label,
|
||||
region: anchor.label_region, parentId: anchor.anchor_id, pageNo: anchor.page_no,
|
||||
}, {
|
||||
id: `${anchor.anchor_id}_value`, kind: 'document_anchor_value', label: anchor.value,
|
||||
region: anchor.value_region, parentId: anchor.anchor_id, pageNo: anchor.page_no,
|
||||
}];
|
||||
}),
|
||||
...(profile.definition.draft_unbound_order_field_layouts || []).flatMap<OrderProfileCanvasRegion>((item) => {
|
||||
const pageNo = item.page_scope === "exact_page" ? item.page_no || 1 : 1;
|
||||
if (!item.anchor?.region || (!item.value_region && !item.absolute_value_region)) {
|
||||
@@ -1436,6 +1592,11 @@ const edit = async (profile: ShippingOrderDocumentProfile) => {
|
||||
form.displayName = profile.display_name;
|
||||
form.schemaId = profile.schema_version_id;
|
||||
form.changeNote = profile.change_note || "";
|
||||
documentMatch.requiredAnchors = (profile.definition.document_match.required_anchors || []).map((item) => ({ ...item }));
|
||||
documentMatch.optionalAnchors = (profile.definition.document_match.optional_anchors || []).map((item) => ({ ...item }));
|
||||
documentMatch.minimumScore = profile.definition.document_match.minimum_score;
|
||||
documentMatch.minimumMargin = profile.definition.document_match.minimum_margin;
|
||||
documentMatchDirty.value = false;
|
||||
regions.value = restoreRegions(profile);
|
||||
history.value = [];
|
||||
future.value = [];
|
||||
@@ -1604,7 +1765,13 @@ const handleShortcut = (event: KeyboardEvent) => {
|
||||
documentCanvas.value?.resetZoom();
|
||||
return;
|
||||
}
|
||||
if (event.key.toLowerCase() === "g") {
|
||||
event.preventDefault();
|
||||
void suggestRegions();
|
||||
return;
|
||||
}
|
||||
const kindByKey: Record<string, OrderProfileCanvasRegion["kind"]> = {
|
||||
m: "document_anchor_label",
|
||||
h: "header_field",
|
||||
l: "line",
|
||||
f: "field",
|
||||
@@ -1768,13 +1935,27 @@ onBeforeUnmount(() => {
|
||||
<header>
|
||||
<span>{{ t("admin.shippingOrderProfiles.workbench.currentConfiguration") }}</span>
|
||||
</header>
|
||||
<section class="document-match-editor">
|
||||
<div class="document-match-editor__heading">
|
||||
<div>
|
||||
<strong>{{ t('admin.shippingOrderProfiles.workbench.documentMatchAnchorTool') }}</strong>
|
||||
<p>{{ t('admin.shippingOrderProfiles.workbench.documentMatchAnchorHint') }}</p>
|
||||
</div>
|
||||
</div>
|
||||
<p v-if="!documentMatch.requiredAnchors.length" class="document-match-editor__warning">{{ t('admin.shippingOrderProfiles.workbench.documentMatchAnchorEmpty') }}</p>
|
||||
<p v-if="documentAnchorNotice" class="document-match-editor__warning">{{ documentAnchorNotice }}</p>
|
||||
<article v-for="(anchor, index) in documentMatch.requiredAnchors" :key="`required-${index}`" class="document-match-editor__row">
|
||||
<b>{{ t('common.required') }}</b>
|
||||
<span>{{ anchor.label }}</span><span>{{ anchor.value }}</span>
|
||||
</article>
|
||||
</section>
|
||||
<section v-if="selectedRegion" class="editor">
|
||||
<div class="selected-region-meta">
|
||||
<span>{{ t('admin.shippingOrderProfiles.workbench.selectedRegion') }}</span>
|
||||
<strong>{{ selectedRegionKindLabel }}</strong>
|
||||
<small>{{ selectedRegionGeometry }}</small>
|
||||
</div>
|
||||
<section v-if="selectedRegion.kind === 'order_field'" class="sample-value-card">
|
||||
<section v-if="['order_field', 'header_field'].includes(selectedRegion.kind)" class="sample-value-card">
|
||||
<span>{{ t('admin.shippingOrderProfiles.workbench.currentSampleValue') }}</span>
|
||||
<strong :class="{ empty: !selectedRegionSampleValue }">
|
||||
{{ selectedRegionSampleDisplay }}
|
||||
@@ -2187,6 +2368,18 @@ onBeforeUnmount(() => {
|
||||
margin: 0 0.8rem;
|
||||
padding: 0.8rem 0;
|
||||
}
|
||||
.document-match-editor {
|
||||
border-bottom: 1px solid #cbd5e1;
|
||||
padding: 0.85rem;
|
||||
background: #f8fafc;
|
||||
}
|
||||
.document-match-editor__heading { display: flex; gap: 0.5rem; align-items: start; }
|
||||
.document-match-editor__heading strong { font-size: 0.84rem; }
|
||||
.document-match-editor__heading p { margin: 0.3rem 0 0; font-size: 0.72rem; color: #64748b; }
|
||||
.document-match-editor__warning { margin: 0.6rem 0; color: #b45309; font-size: 0.75rem; }
|
||||
.document-match-editor__row { display: grid; grid-template-columns: auto minmax(0, 1fr) minmax(0, 1.4fr); gap: 0.35rem; align-items: center; margin-top: 0.45rem; }
|
||||
.document-match-editor__row b { font-size: 0.7rem; color: #0f766e; }
|
||||
.document-match-editor__row span { overflow: hidden; color: #475569; font-size: .72rem; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.selected-region-meta { display: grid; gap: .2rem; margin-bottom: .8rem; border-bottom: 1px solid #dbe4ef; padding-bottom: .75rem; }
|
||||
.selected-region-meta span { color: #64748b; font-size: .7rem; font-weight: 700; }
|
||||
.selected-region-meta strong { color: #0f172a; font-size: .82rem; }
|
||||
|
||||
+36
-2
@@ -2,7 +2,7 @@
|
||||
features/admin/modules/shipping-order-document-profiles/OrderProfileLibraryPage.vue
|
||||
用途:按 profile_code 聚合展示订单文档模板族,是创建和继续编辑的唯一首页。
|
||||
依赖:Profile family API、Vue Router、Vue I18n。
|
||||
逻辑:列表只选择下一步路由;草稿进入编辑页,已发布版本创建新草稿,历史版本进入只读版本中心。
|
||||
逻辑:列表只选择下一步路由;草稿可继续编辑或删除,已发布版本创建新草稿,历史版本进入只读版本中心。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref } from 'vue';
|
||||
@@ -10,7 +10,8 @@ import { useRouter } from 'vue-router';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { BusinessError } from '@/shared/api/client';
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
import { cloneOrderDocumentProfile, listOrderDocumentProfileFamilies } from '@/features/admin/api/shipping-order-document-profile.api';
|
||||
import DeleteConfirmDialog from '@/shared/components/DeleteConfirmDialog.vue';
|
||||
import { cloneOrderDocumentProfile, deleteOrderDocumentProfile, listOrderDocumentProfileFamilies } from '@/features/admin/api/shipping-order-document-profile.api';
|
||||
import type { OrderProfileVersionFamilySummary } from '@/features/admin/types/shipping-order-document-profile.types';
|
||||
|
||||
const { t } = useI18n();
|
||||
@@ -19,6 +20,13 @@ const message = useMessage();
|
||||
const loading = ref(false);
|
||||
const query = ref('');
|
||||
const families = ref<OrderProfileVersionFamilySummary[]>([]);
|
||||
const deletingDraft = ref<OrderProfileVersionFamilySummary | null>(null);
|
||||
const deleteConfirmOpen = computed({
|
||||
get: () => deletingDraft.value !== null,
|
||||
set: (visible: boolean) => {
|
||||
if (!visible) deletingDraft.value = null;
|
||||
},
|
||||
});
|
||||
|
||||
const filteredFamilies = computed(() => {
|
||||
const keyword = query.value.trim().toLowerCase();
|
||||
@@ -55,6 +63,26 @@ async function createNewVersion(item: OrderProfileVersionFamilySummary): Promise
|
||||
}
|
||||
}
|
||||
|
||||
/** 打开系统内确认框,避免浏览器原生弹窗中断管理员的模板管理流程。 */
|
||||
function requestDeleteDraft(item: OrderProfileVersionFamilySummary): void {
|
||||
if (item.draft_profile_id) deletingDraft.value = item;
|
||||
}
|
||||
|
||||
/** 删除已确认的草稿;服务端仍拒绝删除已发布或退役的历史版本。 */
|
||||
async function confirmDeleteDraft(): Promise<void> {
|
||||
const item = deletingDraft.value;
|
||||
if (!item?.draft_profile_id) return;
|
||||
try {
|
||||
await deleteOrderDocumentProfile(item.draft_profile_id);
|
||||
message.success(t('admin.shippingOrderProfiles.deleted'));
|
||||
await loadFamilies();
|
||||
} catch (error) {
|
||||
message.error(error instanceof BusinessError ? error.message : t('admin.shippingOrderProfiles.library.loadFailed'));
|
||||
} finally {
|
||||
deletingDraft.value = null;
|
||||
}
|
||||
}
|
||||
|
||||
/** 进入不可变历史详情,不允许在此页面把版本伪装成新草稿。 */
|
||||
function viewVersion(item: OrderProfileVersionFamilySummary): void {
|
||||
router.push({ name: 'AdminShippingOrderDocumentProfileVersionDetail', params: { profileCode: item.profile_code, version: item.default_version } });
|
||||
@@ -103,6 +131,7 @@ onMounted(loadFamilies);
|
||||
</td>
|
||||
<td class="profile-library__actions">
|
||||
<button v-if="item.draft_profile_id" class="btn-ghost btn-sm" type="button" @click="continueEditing(item)">{{ t('admin.shippingOrderProfiles.versionCenter.continueEditing') }}</button>
|
||||
<button v-if="item.draft_profile_id" class="btn-danger btn-sm" type="button" @click="requestDeleteDraft(item)">{{ t('admin.delete') }}</button>
|
||||
<button v-else-if="item.published_profile_id" class="btn-secondary btn-sm" type="button" @click="createNewVersion(item)">{{ t('admin.shippingOrderProfiles.newVersion') }}</button>
|
||||
<button class="btn-ghost btn-sm" type="button" @click="viewVersion(item)">{{ t('admin.shippingOrderProfiles.versionCenter.viewVersion') }}</button>
|
||||
</td>
|
||||
@@ -111,6 +140,11 @@ onMounted(loadFamilies);
|
||||
</table>
|
||||
</div>
|
||||
</section>
|
||||
<DeleteConfirmDialog
|
||||
v-model="deleteConfirmOpen"
|
||||
:message="t('admin.shippingOrderProfiles.deleteConfirm')"
|
||||
@confirm="confirmDeleteDraft"
|
||||
/>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
|
||||
+18
-21
@@ -7,7 +7,7 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onBeforeUnmount, ref, watch } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { ArrowLeft, ArrowRight, BoxSelect, Copy, Eraser, Minus, Plus, Redo2, RotateCcw, Save, ScanLine, Sparkles, TableProperties, Trash2 } from 'lucide-vue-next';
|
||||
import { Anchor, ArrowLeft, ArrowRight, Columns3, Copy, Eraser, Minus, Plus, Redo2, RotateCcw, Rows3, Save, TableProperties, Tag, TextCursorInput, Trash2, WandSparkles } from 'lucide-vue-next';
|
||||
import { getAuthHeaders } from '@/shared/utils/auth';
|
||||
import type { OrderProfileCanvasRegion, OrderProfilePreviewPageGrant } from '@/features/admin/types/shipping-order-document-profile.types';
|
||||
|
||||
@@ -59,7 +59,6 @@ const loading = ref(false);
|
||||
const canvas = ref<HTMLElement | null>(null);
|
||||
const viewport = ref<HTMLElement | null>(null);
|
||||
const zoom = ref(1);
|
||||
const toolsOpen = ref(true);
|
||||
const zoomPercent = computed(() => Math.round(zoom.value * 100));
|
||||
const pageInput = ref(props.pageNo);
|
||||
type ResizeHandle = 'n' | 'ne' | 'e' | 'se' | 's' | 'sw' | 'w' | 'nw';
|
||||
@@ -238,18 +237,16 @@ onBeforeUnmount(() => { endMove(); endPan(); endCreation(); URL.revokeObjectURL(
|
||||
<div v-if="loading" class="canvas-state">{{ t('admin.shippingOrderProfiles.workbench.loadingPage') }}</div>
|
||||
<div v-else-if="!imageUrl" class="canvas-state">{{ t('admin.shippingOrderProfiles.workbench.selectBoundPdf') }}</div>
|
||||
<div v-else class="canvas-work-area" :class="{ readonly: readonlyMode }">
|
||||
<aside v-if="!readonlyMode" class="annotation-tools" :class="{ collapsed: !toolsOpen }">
|
||||
<button type="button" class="tools-toggle" :aria-expanded="toolsOpen" :aria-label="toolsOpen ? t('admin.shippingOrderProfiles.workbench.hideAnnotationTools') : t('admin.shippingOrderProfiles.workbench.showAnnotationTools')" @click="toolsOpen = !toolsOpen"><BoxSelect /><span v-if="toolsOpen">{{ t('admin.shippingOrderProfiles.workbench.annotationTools') }}</span></button>
|
||||
<template v-if="toolsOpen">
|
||||
<button type="button" :title="t('admin.shippingOrderProfiles.workbench.drawOrderAnchor')" :class="{ active: creationKind === 'order_anchor' }" @click="emit('draw', 'order_anchor')"><BoxSelect /><span>{{ t('admin.shippingOrderProfiles.workbench.orderAnchorTool') }}</span></button>
|
||||
<button type="button" :title="t('admin.shippingOrderProfiles.workbench.drawOrderField')" :class="{ active: creationKind === 'order_field' }" @click="emit('draw', 'order_field')"><BoxSelect /><span>{{ t('admin.shippingOrderProfiles.workbench.orderField') }}</span></button>
|
||||
<button type="button" :title="t('admin.shippingOrderProfiles.workbench.drawHeader')" :class="{ active: creationKind === 'header_field' }" @click="emit('draw', 'header_field')"><TableProperties /><span>{{ t('admin.shippingOrderProfiles.workbench.headerTool') }}</span></button>
|
||||
<button type="button" :title="t('admin.shippingOrderProfiles.workbench.drawLine')" :class="{ active: creationKind === 'line' }" @click="emit('draw', 'line')"><ScanLine /><span>{{ t('admin.shippingOrderProfiles.workbench.lineTool') }}</span></button>
|
||||
<button type="button" :title="t('admin.shippingOrderProfiles.workbench.drawField')" :class="{ active: creationKind === 'field' }" @click="emit('draw', 'field')"><BoxSelect /><span>{{ t('admin.shippingOrderProfiles.workbench.fieldTool') }}</span></button>
|
||||
<button type="button" :title="t('admin.shippingOrderProfiles.workbench.drawExclusion')" :class="{ active: creationKind === 'exclusion' }" @click="emit('draw', 'exclusion')"><Eraser /><span>{{ t('admin.shippingOrderProfiles.workbench.exclusionTool') }}</span></button>
|
||||
<button type="button" class="suggest" :disabled="autoSuggestDisabled || suggesting" @click="emit('suggest')"><Sparkles /><span>{{ suggesting ? t('admin.shippingOrderProfiles.workbench.autoSuggestRunning') : t('admin.shippingOrderProfiles.workbench.autoSuggest') }}</span></button>
|
||||
<p v-if="suggestionProgress" class="suggestion-progress" :class="{ failed: !suggesting }">{{ suggestionProgress }}</p>
|
||||
</template>
|
||||
<aside v-if="!readonlyMode" class="annotation-tools">
|
||||
<button type="button" :aria-label="t('admin.shippingOrderProfiles.workbench.drawDocumentMatchAnchorShortcut')" :title="t('admin.shippingOrderProfiles.workbench.drawDocumentMatchAnchorShortcut')" :class="{ active: creationKind === 'document_anchor_label' || creationKind === 'document_anchor_value' }" @click="emit('draw', 'document_anchor_label')"><Anchor /></button>
|
||||
<button type="button" :aria-label="t('admin.shippingOrderProfiles.workbench.drawOrderAnchorShortcut')" :title="t('admin.shippingOrderProfiles.workbench.drawOrderAnchorShortcut')" :class="{ active: creationKind === 'order_anchor' }" @click="emit('draw', 'order_anchor')"><Tag /></button>
|
||||
<button type="button" :aria-label="t('admin.shippingOrderProfiles.workbench.drawOrderFieldShortcut')" :title="t('admin.shippingOrderProfiles.workbench.drawOrderFieldShortcut')" :class="{ active: creationKind === 'order_field' }" @click="emit('draw', 'order_field')"><TextCursorInput /></button>
|
||||
<button type="button" :aria-label="t('admin.shippingOrderProfiles.workbench.drawHeaderShortcut')" :title="t('admin.shippingOrderProfiles.workbench.drawHeaderShortcut')" :class="{ active: creationKind === 'header_field' }" @click="emit('draw', 'header_field')"><TableProperties /></button>
|
||||
<button type="button" :aria-label="t('admin.shippingOrderProfiles.workbench.drawLineShortcut')" :title="t('admin.shippingOrderProfiles.workbench.drawLineShortcut')" :class="{ active: creationKind === 'line' }" @click="emit('draw', 'line')"><Rows3 /></button>
|
||||
<button type="button" :aria-label="t('admin.shippingOrderProfiles.workbench.drawFieldShortcut')" :title="t('admin.shippingOrderProfiles.workbench.drawFieldShortcut')" :class="{ active: creationKind === 'field' }" @click="emit('draw', 'field')"><Columns3 /></button>
|
||||
<button type="button" :aria-label="t('admin.shippingOrderProfiles.workbench.drawExclusionShortcut')" :title="t('admin.shippingOrderProfiles.workbench.drawExclusionShortcut')" :class="{ active: creationKind === 'exclusion' }" @click="emit('draw', 'exclusion')"><Eraser /></button>
|
||||
<button type="button" class="suggest" :aria-label="t('admin.shippingOrderProfiles.workbench.autoSuggestShortcut')" :title="t('admin.shippingOrderProfiles.workbench.autoSuggestShortcut')" :disabled="autoSuggestDisabled || suggesting" @click="emit('suggest')"><WandSparkles /></button>
|
||||
<p v-if="suggestionProgress" class="suggestion-progress" :class="{ failed: !suggesting }">{{ suggestionProgress }}</p>
|
||||
</aside>
|
||||
<div ref="viewport" class="canvas-viewport" :class="{ panning: !creationKind || readonlyMode }" @wheel.prevent="handleWheel">
|
||||
<div ref="canvas" class="canvas-stage" :class="{ drawing: creationKind && !readonlyMode }" :style="{ '--canvas-zoom': zoom }" @pointerdown="beginCreation">
|
||||
@@ -312,13 +309,10 @@ onBeforeUnmount(() => { endMove(); endPan(); endCreation(); URL.revokeObjectURL(
|
||||
.canvas-stage img { display: block; width: 100%; user-select: none; }
|
||||
.canvas-stage.drawing { cursor: crosshair; }
|
||||
.creation-region { position: absolute; z-index: 5; box-sizing: border-box; border: 2px dashed #34d399; background: rgb(16 185 129 / .18); pointer-events: none; }
|
||||
.annotation-tools { display: grid; align-content: start; gap: .3rem; flex: 0 0 7rem; padding: .35rem; border: 1px solid rgb(71 85 105 / .9); border-radius: .5rem; background: rgb(15 23 42 / .94); box-shadow: 0 8px 24px rgb(15 23 42 / .3); }
|
||||
.annotation-tools.collapsed { flex-basis: 2.45rem; padding: .3rem; }
|
||||
.annotation-tools button { display: flex; min-height: 2rem; align-items: center; gap: .4rem; border: 1px solid transparent; border-radius: .35rem; background: #1e293b; padding: .35rem .45rem; color: #e2e8f0; font-size: .7rem; text-align: left; white-space: nowrap; }
|
||||
.annotation-tools { display: grid; align-content: start; gap: .3rem; flex: 0 0 2.65rem; padding: .3rem; border: 1px solid rgb(71 85 105 / .9); border-radius: .5rem; background: rgb(15 23 42 / .94); box-shadow: 0 8px 24px rgb(15 23 42 / .3); }
|
||||
.annotation-tools button { display: grid; min-height: 2rem; place-items: center; border: 1px solid transparent; border-radius: .35rem; background: #1e293b; padding: .35rem; color: #e2e8f0; }
|
||||
.annotation-tools button:hover, .annotation-tools button.active { border-color: #38bdf8; background: #0c4a6e; color: #f0f9ff; }
|
||||
.annotation-tools .tools-toggle { justify-content: center; }
|
||||
.annotation-tools.collapsed .tools-toggle { padding-inline: 0; }
|
||||
.annotation-tools .suggest { border-color: #0ea5e9; background: #0284c7; font-weight: 700; }
|
||||
.annotation-tools .suggest { border-color: #0ea5e9; background: #0284c7; }
|
||||
.annotation-tools button:disabled { cursor: not-allowed; opacity: .45; }
|
||||
.suggestion-progress { margin: .1rem; color: #bae6fd; font-size: .66rem; line-height: 1.35; }
|
||||
.suggestion-progress.failed { color: #fca5a5; }
|
||||
@@ -340,6 +334,10 @@ onBeforeUnmount(() => { endMove(); endPan(); endCreation(); URL.revokeObjectURL(
|
||||
.region-order_field .region-label, .region-order_field .resize-handle { background: #15803d; }
|
||||
.region-order_anchor { z-index: 2; border: 1.5px solid #a855f7; background: rgb(168 85 247 / .08); }
|
||||
.region-order_anchor .region-label, .region-order_anchor .resize-handle { background: #7e22ce; }
|
||||
.region-document_anchor_label { z-index: 2; border: 1.5px solid #0ea5e9; background: rgb(14 165 233 / .1); }
|
||||
.region-document_anchor_label .region-label, .region-document_anchor_label .resize-handle { background: #0369a1; }
|
||||
.region-document_anchor_value { z-index: 2; border: 1.5px solid #f97316; background: rgb(249 115 22 / .1); }
|
||||
.region-document_anchor_value .region-label, .region-document_anchor_value .resize-handle { background: #c2410c; }
|
||||
.region-line { z-index: 0; border-color: #a78bfa; background: rgb(167 139 250 / .1); pointer-events: none; }
|
||||
.region-line .region-label, .region-line .line-hit-edge, .region-line.selected .resize-handle { pointer-events: auto; }
|
||||
.region-line .region-label, .region-line .resize-handle { background: #6d28d9; }
|
||||
@@ -370,5 +368,4 @@ onBeforeUnmount(() => { endMove(); endPan(); endCreation(); URL.revokeObjectURL(
|
||||
.annotation-tools { flex-basis: 2.45rem; }
|
||||
.annotation-tools button span, .suggestion-progress { display: none; }
|
||||
}
|
||||
.tools-toggle span { display: none; }
|
||||
</style>
|
||||
+260
-20
@@ -1,30 +1,40 @@
|
||||
<!--
|
||||
features/admin/modules/shipping-order-extraction-runs/ShippingOrderExtractionRunsPage.vue
|
||||
用途:为所有管理员提供订单识别异步 Run 的只读诊断视图。
|
||||
依赖:admin.api 的脱敏诊断 DTO、Vue Composition API、Vue I18n。
|
||||
逻辑:列表按状态筛选并按需加载单条详情;页面不提供重试、取消或任何业务数据修改入口。
|
||||
用途:管理员订单识别运行诊断——健康聚合、积压/取消中筛选、只读详情与活跃 Run 取消。
|
||||
依赖:admin.api 脱敏诊断/健康/取消 DTO、Vue Composition API、Vue I18n。
|
||||
逻辑:健康面板 + 列表筛选;详情仍只读;取消走 admin cancel API 且强制填写原因。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { onMounted, ref, watch } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { useRoute, useRouter } from 'vue-router';
|
||||
import {
|
||||
cancelShippingOrderExtractionRun,
|
||||
getShippingOrderExtractionDiagnosticRun,
|
||||
getShippingOrderExtractionHealth,
|
||||
listShippingOrderExtractionDiagnosticRuns,
|
||||
type ShippingOrderExtractionDiagnosticDetail,
|
||||
type ShippingOrderExtractionDiagnosticRun,
|
||||
type ShippingOrderExtractionHealth,
|
||||
} from '@/features/admin/api/admin.api';
|
||||
|
||||
const { t } = useI18n();
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
const loading = ref(false);
|
||||
const healthLoading = ref(false);
|
||||
const detailLoading = ref(false);
|
||||
const cancellingRunNo = ref('');
|
||||
const pendingCancelRunNo = ref('');
|
||||
const cancelReason = ref('');
|
||||
const page = ref(1);
|
||||
const pageSize = 25;
|
||||
const total = ref(0);
|
||||
const status = ref('');
|
||||
const staleOnly = ref(false);
|
||||
const cancellationInFlight = ref(false);
|
||||
const rows = ref<ShippingOrderExtractionDiagnosticRun[]>([]);
|
||||
const health = ref<ShippingOrderExtractionHealth | null>(null);
|
||||
const detail = ref<ShippingOrderExtractionDiagnosticDetail | null>(null);
|
||||
const error = ref('');
|
||||
|
||||
@@ -33,12 +43,72 @@ const formatDuration = (value?: number | null) => value == null ? '-' : `${(valu
|
||||
const translateAutoFreezeReason = (code: string) =>
|
||||
t(`admin.shippingOrderExtractionRuns.autoFreezeReasonCodes.${code}`, code);
|
||||
|
||||
/**
|
||||
* 判断管理员是否可对 Run 发起取消(活跃且未完成取消)。
|
||||
*/
|
||||
const canCancelRun = (row: ShippingOrderExtractionDiagnosticRun) => (
|
||||
['queued', 'processing'].includes(row.status)
|
||||
&& !row.cancellation?.completed
|
||||
&& !row.cancellation?.in_flight
|
||||
);
|
||||
|
||||
/** 展开/收起列表行取消表单。 */
|
||||
const beginCancelRun = (runNo: string) => {
|
||||
if (pendingCancelRunNo.value === runNo) {
|
||||
pendingCancelRunNo.value = '';
|
||||
cancelReason.value = '';
|
||||
return;
|
||||
}
|
||||
pendingCancelRunNo.value = runNo;
|
||||
cancelReason.value = '';
|
||||
};
|
||||
|
||||
/**
|
||||
* 管理员取消 Run;后端强制要求 reason。
|
||||
*/
|
||||
const submitCancelRun = async (runNo: string) => {
|
||||
const reason = String(cancelReason.value || '').trim();
|
||||
if (!reason || cancellingRunNo.value) return;
|
||||
cancellingRunNo.value = runNo;
|
||||
error.value = '';
|
||||
try {
|
||||
await cancelShippingOrderExtractionRun(runNo, { reason, reason_code: 'admin_cancelled' });
|
||||
pendingCancelRunNo.value = '';
|
||||
cancelReason.value = '';
|
||||
await refreshAll();
|
||||
} catch {
|
||||
error.value = t('admin.shippingOrderExtractionRuns.cancelFailed');
|
||||
} finally {
|
||||
cancellingRunNo.value = '';
|
||||
}
|
||||
};
|
||||
|
||||
/** 加载健康聚合;失败不阻断列表。 */
|
||||
const loadHealth = async () => {
|
||||
healthLoading.value = true;
|
||||
try {
|
||||
health.value = await getShippingOrderExtractionHealth(24);
|
||||
} catch {
|
||||
health.value = null;
|
||||
} finally {
|
||||
healthLoading.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
/** 加载安全摘要;服务端已完成管理员鉴权、审计及敏感字段剔除。 */
|
||||
const load = async () => {
|
||||
loading.value = true;
|
||||
error.value = '';
|
||||
try {
|
||||
const response = await listShippingOrderExtractionDiagnosticRuns(page.value, pageSize, status.value);
|
||||
const response = await listShippingOrderExtractionDiagnosticRuns(
|
||||
page.value,
|
||||
pageSize,
|
||||
status.value,
|
||||
{
|
||||
staleOnly: staleOnly.value,
|
||||
cancellationInFlight: cancellationInFlight.value,
|
||||
},
|
||||
);
|
||||
rows.value = response.items;
|
||||
total.value = response.total;
|
||||
} catch {
|
||||
@@ -48,6 +118,10 @@ const load = async () => {
|
||||
}
|
||||
};
|
||||
|
||||
const refreshAll = async () => {
|
||||
await Promise.all([loadHealth(), load()]);
|
||||
};
|
||||
|
||||
/** 按需打开一条 Run 的脱敏执行尝试和节点生命周期,不预取详情以减少诊断审计噪声。 */
|
||||
const openDetail = async (runNo: string) => {
|
||||
detailLoading.value = true;
|
||||
@@ -73,13 +147,13 @@ const closeDetail = () => {
|
||||
}
|
||||
};
|
||||
|
||||
const applyStatus = async () => {
|
||||
const applyFilters = async () => {
|
||||
page.value = 1;
|
||||
await load();
|
||||
};
|
||||
|
||||
onMounted(() => {
|
||||
void load();
|
||||
void refreshAll();
|
||||
const runNo = String(route.query.runNo || '').trim();
|
||||
if (runNo) void openDetail(runNo);
|
||||
});
|
||||
@@ -104,43 +178,173 @@ watch(
|
||||
<h1 class="section-title">{{ t('admin.shippingOrderExtractionRuns.title') }}</h1>
|
||||
<p class="section-desc mt-1 max-w-3xl">{{ t('admin.shippingOrderExtractionRuns.subtitle') }}</p>
|
||||
</div>
|
||||
<button type="button" class="btn-secondary btn-sm" :disabled="loading" @click="load">
|
||||
<button type="button" class="btn-secondary btn-sm" :disabled="loading || healthLoading" @click="refreshAll">
|
||||
{{ t('admin.shippingOrderExtractionRuns.refresh') }}
|
||||
</button>
|
||||
</header>
|
||||
|
||||
<div
|
||||
class="grid gap-3 rounded-xl border border-default bg-surface p-4 md:grid-cols-4"
|
||||
data-testid="shipping-order-extraction-health"
|
||||
>
|
||||
<div v-if="healthLoading" class="md:col-span-4 text-sm text-muted">{{ t('admin.shippingOrderExtractionRuns.loading') }}</div>
|
||||
<template v-else-if="health">
|
||||
<div>
|
||||
<div class="text-xs text-muted">{{ t('admin.shippingOrderExtractionRuns.healthStatus') }}</div>
|
||||
<div class="mt-1 text-lg font-semibold" :class="health.health_status === 'healthy' ? 'text-emerald-700' : 'text-amber-700'">
|
||||
{{ t(`admin.shippingOrderExtractionRuns.healthStatuses.${health.health_status}`, health.health_status) }}
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<div class="text-xs text-muted">{{ t('admin.shippingOrderExtractionRuns.activeCount') }}</div>
|
||||
<div class="mt-1 text-lg font-semibold">{{ health.counts.active || 0 }}</div>
|
||||
</div>
|
||||
<div>
|
||||
<div class="text-xs text-muted">{{ t('admin.shippingOrderExtractionRuns.staleCount') }}</div>
|
||||
<div class="mt-1 text-lg font-semibold">{{ health.counts.stale || 0 }}</div>
|
||||
</div>
|
||||
<div>
|
||||
<div class="text-xs text-muted">{{ t('admin.shippingOrderExtractionRuns.failureRate') }}</div>
|
||||
<div class="mt-1 text-lg font-semibold">{{ Math.round((health.failure_rate || 0) * 100) }}%</div>
|
||||
</div>
|
||||
<div class="md:col-span-4 text-xs text-secondary">
|
||||
{{ t('admin.shippingOrderExtractionRuns.latencySummary', {
|
||||
p50: formatDuration(health.latency?.total?.p50_ms),
|
||||
p95: formatDuration(health.latency?.total?.p95_ms),
|
||||
max: formatDuration(health.latency?.total?.max_ms),
|
||||
}) }}
|
||||
<span v-if="health.stale_run_nos?.length" class="ml-2">
|
||||
{{ t('admin.shippingOrderExtractionRuns.staleRuns', { runs: health.stale_run_nos.slice(0, 5).join(', ') }) }}
|
||||
</span>
|
||||
</div>
|
||||
</template>
|
||||
<div v-else class="md:col-span-4 text-sm text-muted">{{ t('admin.shippingOrderExtractionRuns.healthUnavailable') }}</div>
|
||||
</div>
|
||||
|
||||
<div class="flex flex-wrap items-center gap-3 rounded-xl border border-default bg-surface p-3">
|
||||
<label class="flex items-center gap-2 text-sm text-secondary">
|
||||
{{ t('admin.shippingOrderExtractionRuns.status') }}
|
||||
<select v-model="status" class="select-field py-1.5" @change="applyStatus">
|
||||
<select v-model="status" class="select-field py-1.5" @change="applyFilters">
|
||||
<option value="">{{ t('admin.shippingOrderExtractionRuns.allStatuses') }}</option>
|
||||
<option v-for="value in ['queued', 'processing', 'completed', 'partially_completed', 'review_required', 'failed', 'cancelled']" :key="value" :value="value">
|
||||
{{ t(`admin.shippingOrderExtractionRuns.statuses.${value}`) }}
|
||||
</option>
|
||||
</select>
|
||||
</label>
|
||||
<label class="flex items-center gap-2 text-sm text-secondary">
|
||||
<input v-model="staleOnly" type="checkbox" class="rounded border-default" @change="applyFilters">
|
||||
{{ t('admin.shippingOrderExtractionRuns.staleOnly') }}
|
||||
</label>
|
||||
<label class="flex items-center gap-2 text-sm text-secondary">
|
||||
<input v-model="cancellationInFlight" type="checkbox" class="rounded border-default" @change="applyFilters">
|
||||
{{ t('admin.shippingOrderExtractionRuns.cancellationInFlight') }}
|
||||
</label>
|
||||
<span class="text-xs text-muted">{{ t('admin.shippingOrderExtractionRuns.total', { count: total }) }}</span>
|
||||
</div>
|
||||
|
||||
<p v-if="error" class="rounded-lg border border-rose-200 bg-rose-50 p-3 text-sm text-rose-700">{{ error }}</p>
|
||||
<div class="overflow-x-auto rounded-xl border border-default bg-surface">
|
||||
<table class="min-w-[940px] w-full text-left text-sm">
|
||||
<table class="min-w-[1040px] w-full text-left text-sm">
|
||||
<thead class="border-b border-default bg-surface-soft text-xs text-muted"><tr>
|
||||
<th class="px-4 py-3">{{ t('admin.shippingOrderExtractionRuns.runNo') }}</th><th class="px-4 py-3">{{ t('admin.shippingOrderExtractionRuns.status') }}</th><th class="px-4 py-3">{{ t('admin.shippingOrderExtractionRuns.stage') }}</th><th class="px-4 py-3">{{ t('admin.shippingOrderExtractionRuns.attempts') }}</th><th class="px-4 py-3">{{ t('admin.shippingOrderExtractionRuns.createdAt') }}</th><th class="px-4 py-3">{{ t('admin.shippingOrderExtractionRuns.totalDuration') }}</th><th class="px-4 py-3"></th>
|
||||
<th class="px-4 py-3">{{ t('admin.shippingOrderExtractionRuns.runNo') }}</th>
|
||||
<th class="px-4 py-3">{{ t('admin.shippingOrderExtractionRuns.status') }}</th>
|
||||
<th class="px-4 py-3">{{ t('admin.shippingOrderExtractionRuns.stage') }}</th>
|
||||
<th class="px-4 py-3">{{ t('admin.shippingOrderExtractionRuns.cancellation') }}</th>
|
||||
<th class="px-4 py-3">{{ t('admin.shippingOrderExtractionRuns.attempts') }}</th>
|
||||
<th class="px-4 py-3">{{ t('admin.shippingOrderExtractionRuns.createdAt') }}</th>
|
||||
<th class="px-4 py-3">{{ t('admin.shippingOrderExtractionRuns.totalDuration') }}</th>
|
||||
<th class="px-4 py-3">{{ t('admin.shippingOrderExtractionRuns.actions') }}</th>
|
||||
</tr></thead>
|
||||
<tbody><tr v-if="loading"><td colspan="7" class="px-4 py-8 text-center text-muted">{{ t('admin.shippingOrderExtractionRuns.loading') }}</td></tr>
|
||||
<tr v-else-if="!rows.length"><td colspan="7" class="px-4 py-8 text-center text-muted">{{ t('admin.shippingOrderExtractionRuns.empty') }}</td></tr>
|
||||
<tr v-for="row in rows" :key="row.run_no" class="border-b border-default last:border-0"><td class="px-4 py-3 font-mono text-xs">{{ row.run_no }}</td><td class="px-4 py-3">{{ t(`admin.shippingOrderExtractionRuns.statuses.${row.status}`) }}</td><td class="px-4 py-3">{{ row.current_event_code || '-' }}</td><td class="px-4 py-3">{{ row.attempt_count }}</td><td class="px-4 py-3">{{ formatTime(row.created_at) }}</td><td class="px-4 py-3">{{ formatDuration(row.durations_ms.total) }}</td><td class="px-4 py-3"><button type="button" class="text-brand-600 hover:underline" @click="openDetail(row.run_no)">{{ t('admin.shippingOrderExtractionRuns.viewDetail') }}</button></td></tr>
|
||||
<tbody>
|
||||
<tr v-if="loading"><td colspan="9" class="px-4 py-8 text-center text-muted">{{ t('admin.shippingOrderExtractionRuns.loading') }}</td></tr>
|
||||
<tr v-else-if="!rows.length"><td colspan="9" class="px-4 py-8 text-center text-muted">{{ t('admin.shippingOrderExtractionRuns.empty') }}</td></tr>
|
||||
<tr v-for="row in rows" :key="row.run_no" class="border-b border-default last:border-0">
|
||||
<td class="px-4 py-3 font-mono text-xs">{{ row.run_no }}</td>
|
||||
<td class="px-4 py-3">{{ t(`admin.shippingOrderExtractionRuns.statuses.${row.status}`) }}</td>
|
||||
<td class="px-4 py-3">{{ row.current_event_code || '-' }}</td>
|
||||
<td class="px-4 py-3">
|
||||
<span v-if="row.cancellation?.in_flight" class="rounded-full bg-amber-100 px-2 py-0.5 text-xs text-amber-800">
|
||||
{{ t('admin.shippingOrderExtractionRuns.cancellationStates.in_flight') }}
|
||||
</span>
|
||||
<span v-else-if="row.cancellation?.completed" class="text-xs text-muted">
|
||||
{{ t('admin.shippingOrderExtractionRuns.cancellationStates.completed') }}
|
||||
</span>
|
||||
<span v-else class="text-xs text-muted">—</span>
|
||||
</td>
|
||||
<td class="px-4 py-3">{{ row.attempt_count }}</td>
|
||||
<td class="px-4 py-3">{{ formatTime(row.created_at) }}</td>
|
||||
<td class="px-4 py-3">{{ formatDuration(row.durations_ms.total ?? row.durations_ms.elapsed_active) }}</td>
|
||||
<td class="px-4 py-3">
|
||||
<div class="flex flex-col gap-2">
|
||||
<button type="button" class="text-left text-brand-600 hover:underline" @click="openDetail(row.run_no)">{{ t('admin.shippingOrderExtractionRuns.viewDetail') }}</button>
|
||||
<template v-if="canCancelRun(row)">
|
||||
<div
|
||||
v-if="pendingCancelRunNo === row.run_no"
|
||||
class="min-w-[220px] space-y-1.5 rounded-md border border-rose-200 bg-rose-50/60 p-2 dark:border-rose-900/40 dark:bg-rose-950/20"
|
||||
>
|
||||
<label class="block text-[11px] text-secondary">{{ t('chat.shippingOrderExtractionCancel.reasonRequired') }}</label>
|
||||
<textarea v-model="cancelReason" rows="2" class="input-field w-full py-1 text-xs" />
|
||||
<div class="flex flex-wrap gap-2">
|
||||
<button
|
||||
type="button"
|
||||
class="text-xs font-medium text-rose-700 hover:underline"
|
||||
:disabled="cancellingRunNo === row.run_no || !cancelReason.trim()"
|
||||
@click="submitCancelRun(row.run_no)"
|
||||
>
|
||||
{{ cancellingRunNo === row.run_no
|
||||
? t('chat.shippingOrderExtractionCancel.submitting')
|
||||
: t('admin.shippingOrderExtractionRuns.cancelRun') }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="text-xs text-muted hover:underline"
|
||||
:disabled="cancellingRunNo === row.run_no"
|
||||
@click="pendingCancelRunNo = ''; cancelReason = ''"
|
||||
>
|
||||
{{ t('admin.cancel') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
v-else
|
||||
type="button"
|
||||
class="text-left text-xs font-medium text-rose-700 hover:underline"
|
||||
:disabled="Boolean(cancellingRunNo)"
|
||||
@click="beginCancelRun(row.run_no)"
|
||||
>
|
||||
{{ t('admin.shippingOrderExtractionRuns.cancelRun') }}
|
||||
</button>
|
||||
</template>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<div class="flex items-center justify-end gap-3 text-sm"><button type="button" class="rounded border border-default px-3 py-1.5 disabled:opacity-50" :disabled="page <= 1 || loading" @click="page -= 1; load()">{{ t('admin.shippingOrderExtractionRuns.previous') }}</button><span>{{ page }}</span><button type="button" class="rounded border border-default px-3 py-1.5 disabled:opacity-50" :disabled="page * pageSize >= total || loading" @click="page += 1; load()">{{ t('admin.shippingOrderExtractionRuns.next') }}</button></div>
|
||||
<div class="flex items-center justify-end gap-3 text-sm">
|
||||
<button type="button" class="rounded border border-default px-3 py-1.5 disabled:opacity-50" :disabled="page <= 1 || loading" @click="page -= 1; load()">{{ t('admin.shippingOrderExtractionRuns.previous') }}</button>
|
||||
<span>{{ page }}</span>
|
||||
<button type="button" class="rounded border border-default px-3 py-1.5 disabled:opacity-50" :disabled="page * pageSize >= total || loading" @click="page += 1; load()">{{ t('admin.shippingOrderExtractionRuns.next') }}</button>
|
||||
</div>
|
||||
|
||||
<div v-if="detail || detailLoading" class="fixed inset-0 z-50 flex justify-end bg-overlay" @click.self="closeDetail">
|
||||
<aside class="h-full w-full max-w-2xl overflow-y-auto bg-surface p-6 shadow-2xl">
|
||||
<div class="flex items-center justify-between"><h2 class="text-lg font-bold">{{ t('admin.shippingOrderExtractionRuns.detailTitle') }}</h2><button type="button" class="text-secondary" @click="closeDetail">{{ t('admin.close') }}</button></div>
|
||||
<p v-if="detailLoading" class="mt-6 text-muted">{{ t('admin.shippingOrderExtractionRuns.loading') }}</p>
|
||||
<template v-else-if="detail"><dl class="mt-5 grid grid-cols-2 gap-3 text-sm"><dt>{{ t('admin.shippingOrderExtractionRuns.runNo') }}</dt><dd class="font-mono text-xs">{{ detail.run.run_no }}</dd><dt>{{ t('admin.shippingOrderExtractionRuns.currentEvent') }}</dt><dd class="font-mono text-xs">{{ detail.run.current_event_code || '-' }}</dd><dt>{{ t('admin.shippingOrderExtractionRuns.candidateMaterializedAt') }}</dt><dd>{{ formatTime(detail.run.candidate_materialized_at) }}</dd><dt>{{ t('admin.shippingOrderExtractionRuns.errorCode') }}</dt><dd>{{ detail.run.error_code || '-' }}</dd><dt>{{ t('admin.shippingOrderExtractionRuns.totalDuration') }}</dt><dd>{{ formatDuration(detail.run.durations_ms.total) }}</dd></dl>
|
||||
<template v-else-if="detail">
|
||||
<dl class="mt-5 grid grid-cols-2 gap-3 text-sm">
|
||||
<dt>{{ t('admin.shippingOrderExtractionRuns.runNo') }}</dt><dd class="font-mono text-xs">{{ detail.run.run_no }}</dd>
|
||||
<dt>{{ t('admin.shippingOrderExtractionRuns.currentEvent') }}</dt><dd class="font-mono text-xs">{{ detail.run.current_event_code || '-' }}</dd>
|
||||
<dt>{{ t('admin.shippingOrderExtractionRuns.cancellation') }}</dt>
|
||||
<dd>
|
||||
<template v-if="detail.run.cancellation?.in_flight">{{ t('admin.shippingOrderExtractionRuns.cancellationStates.in_flight') }}</template>
|
||||
<template v-else-if="detail.run.cancellation?.completed">{{ t('admin.shippingOrderExtractionRuns.cancellationStates.completed') }}</template>
|
||||
<template v-else>—</template>
|
||||
</dd>
|
||||
<dt>{{ t('admin.shippingOrderExtractionRuns.candidateMaterializedAt') }}</dt><dd>{{ formatTime(detail.run.candidate_materialized_at) }}</dd>
|
||||
<dt>{{ t('admin.shippingOrderExtractionRuns.errorCode') }}</dt><dd>{{ detail.run.error_code || '-' }}</dd>
|
||||
<dt>{{ t('admin.shippingOrderExtractionRuns.totalDuration') }}</dt><dd>{{ formatDuration(detail.run.durations_ms.total) }}</dd>
|
||||
</dl>
|
||||
<section class="mt-6 rounded-lg border border-default p-4 text-sm">
|
||||
<div class="font-semibold">{{ t('admin.shippingOrderExtractionRuns.autoFreezePolicy') }}</div>
|
||||
<dl class="mt-3 grid grid-cols-2 gap-x-3 gap-y-2">
|
||||
@@ -173,11 +377,47 @@ watch(
|
||||
<div v-else class="mt-2 text-xs text-muted">{{ t('admin.shippingOrderExtractionRuns.autoFreezeNoBlockingReasons') }}</div>
|
||||
</div>
|
||||
</section>
|
||||
<h3 class="mt-7 font-semibold">{{ t('admin.shippingOrderExtractionRuns.jobAttempts') }}</h3><div class="mt-2 space-y-2"><div v-for="job in detail.job_attempts" :key="job.job_id" class="rounded-lg border border-default p-3 text-sm"><b>#{{ job.job_id }}</b> · {{ job.status }} · {{ t('admin.shippingOrderExtractionRuns.attempts') }} {{ job.attempts }}/{{ job.max_attempts }} · {{ formatDuration(job.duration_ms) }}</div><p v-if="!detail.job_attempts.length" class="text-sm text-muted">{{ t('admin.shippingOrderExtractionRuns.empty') }}</p></div>
|
||||
<h3 class="mt-7 font-semibold">{{ t('admin.shippingOrderExtractionRuns.units') }}</h3><div class="mt-2 space-y-2"><div v-for="unit in detail.units" :key="unit.unit_id" class="rounded-lg border border-default p-3 text-sm"><b>#{{ unit.position + 1 }} {{ unit.unit_type }}</b> · {{ unit.status }} · {{ t('admin.shippingOrderExtractionRuns.attempts') }} {{ unit.attempt_count }} · {{ formatDuration(unit.duration_ms) }}<span v-if="unit.error_code" class="ml-2 font-mono text-xs text-danger">{{ unit.error_code }}</span>
|
||||
<section v-for="route in unit.route_decisions" :key="`${unit.unit_id}:${route.attempt_no}`" class="mt-3 rounded border border-default bg-surface-soft p-3 text-xs"><h4 class="font-semibold text-primary">{{ t('admin.shippingOrderExtractionRuns.routeDecision') }} #{{ route.attempt_no }}</h4><dl class="mt-2 grid grid-cols-2 gap-x-3 gap-y-1"><dt>{{ t('admin.shippingOrderExtractionRuns.executionMode') }}</dt><dd>{{ t(`admin.shippingOrderExtractionRuns.executionModes.${route.execution_mode}`) }}</dd><dt>{{ t('admin.shippingOrderExtractionRuns.matchStatus') }}</dt><dd>{{ t(`admin.shippingOrderExtractionRuns.matchStatuses.${route.match_status}`) }}</dd><dt>{{ t('admin.shippingOrderExtractionRuns.selectedProfile') }}</dt><dd>{{ route.selected_profile_code ? `${route.selected_profile_code} V${route.selected_profile_version}` : '-' }}</dd><dt>{{ t('admin.shippingOrderExtractionRuns.autoCreateApproved') }}</dt><dd>{{ route.auto_create_approved == null ? '-' : t(route.auto_create_approved ? 'admin.shippingOrderExtractionRuns.yes' : 'admin.shippingOrderExtractionRuns.no') }}</dd><dt>{{ t('admin.shippingOrderExtractionRuns.fallbackReasons') }}</dt><dd>{{ route.fallback_reason_codes.length ? route.fallback_reason_codes.map(code => t(`admin.shippingOrderExtractionRuns.reasonCodes.${code}`)).join(';') : '-' }}</dd></dl><div v-if="route.candidates.length" class="mt-3"><p class="font-medium">{{ t('admin.shippingOrderExtractionRuns.candidates') }}</p><div v-for="candidate in route.candidates" :key="`${candidate.profile_code}:${candidate.version}`" class="mt-1 flex flex-wrap gap-x-2 text-muted"><span>{{ candidate.profile_code }} V{{ candidate.version }}</span><span>{{ candidate.score.toFixed(2) }}</span><span>{{ candidate.hard_match ? t('admin.shippingOrderExtractionRuns.hardMatch') : t('admin.shippingOrderExtractionRuns.hardMismatch') }}</span><span v-if="candidate.missing_required_anchor_ids?.length">{{ t('admin.shippingOrderExtractionRuns.missingAnchors', { ids: candidate.missing_required_anchor_ids.join(', ') }) }}</span></div></div></section>
|
||||
</div><p v-if="!detail.units.length" class="text-sm text-muted">{{ t('admin.shippingOrderExtractionRuns.empty') }}</p></div>
|
||||
<h3 class="mt-7 font-semibold">{{ t('admin.shippingOrderExtractionRuns.lifecycle') }}</h3><div class="mt-2 space-y-2"><div v-for="event in detail.progress_events" :key="`${event.sequence_no}:${event.event_code}`" class="rounded-lg border border-default p-3 text-sm"><b>{{ event.event_code }}</b><span class="ml-2 text-secondary">{{ event.status || '-' }}</span><span class="ml-2 font-mono text-xs text-muted">{{ t(`admin.shippingOrderExtractionRuns.visibilities.${event.visibility}`) }}</span><span v-if="event.reason_code" class="ml-2 font-mono text-xs text-muted">{{ event.reason_code }}</span><time class="ml-2 text-xs text-muted">{{ formatTime(event.occurred_at) }}</time></div><p v-if="!detail.progress_events.length" class="text-sm text-muted">{{ t('admin.shippingOrderExtractionRuns.empty') }}</p></div>
|
||||
<h3 class="mt-7 font-semibold">{{ t('admin.shippingOrderExtractionRuns.jobAttempts') }}</h3>
|
||||
<div class="mt-2 space-y-2">
|
||||
<div v-for="job in detail.job_attempts" :key="job.job_id" class="rounded-lg border border-default p-3 text-sm">
|
||||
<b>#{{ job.job_id }}</b> · {{ job.status }} · {{ t('admin.shippingOrderExtractionRuns.attempts') }} {{ job.attempts }}/{{ job.max_attempts }} · {{ formatDuration(job.duration_ms) }}
|
||||
</div>
|
||||
<p v-if="!detail.job_attempts.length" class="text-sm text-muted">{{ t('admin.shippingOrderExtractionRuns.empty') }}</p>
|
||||
</div>
|
||||
<h3 class="mt-7 font-semibold">{{ t('admin.shippingOrderExtractionRuns.units') }}</h3>
|
||||
<div class="mt-2 space-y-2">
|
||||
<div v-for="unit in detail.units" :key="unit.unit_id" class="rounded-lg border border-default p-3 text-sm">
|
||||
<b>#{{ unit.position + 1 }} {{ unit.unit_type }}</b> · {{ unit.status }} · {{ t('admin.shippingOrderExtractionRuns.attempts') }} {{ unit.attempt_count }} · {{ formatDuration(unit.duration_ms) }}
|
||||
<span v-if="unit.error_code" class="ml-2 font-mono text-xs text-danger">{{ unit.error_code }}</span>
|
||||
<section v-for="routeItem in unit.route_decisions" :key="`${unit.unit_id}:${routeItem.attempt_no}`" class="mt-3 rounded border border-default bg-surface-soft p-3 text-xs">
|
||||
<h4 class="font-semibold text-primary">{{ t('admin.shippingOrderExtractionRuns.routeDecision') }} #{{ routeItem.attempt_no }}</h4>
|
||||
<dl class="mt-2 grid grid-cols-2 gap-x-3 gap-y-1">
|
||||
<dt>{{ t('admin.shippingOrderExtractionRuns.executionMode') }}</dt>
|
||||
<dd>{{ t(`admin.shippingOrderExtractionRuns.executionModes.${routeItem.execution_mode}`) }}</dd>
|
||||
<dt>{{ t('admin.shippingOrderExtractionRuns.matchStatus') }}</dt>
|
||||
<dd>{{ t(`admin.shippingOrderExtractionRuns.matchStatuses.${routeItem.match_status}`) }}</dd>
|
||||
<dt>{{ t('admin.shippingOrderExtractionRuns.selectedProfile') }}</dt>
|
||||
<dd>{{ routeItem.selected_profile_code ? `${routeItem.selected_profile_code} V${routeItem.selected_profile_version}` : '-' }}</dd>
|
||||
<dt>{{ t('admin.shippingOrderExtractionRuns.autoCreateApproved') }}</dt>
|
||||
<dd>{{ routeItem.auto_create_approved == null ? '-' : t(routeItem.auto_create_approved ? 'admin.shippingOrderExtractionRuns.yes' : 'admin.shippingOrderExtractionRuns.no') }}</dd>
|
||||
<dt>{{ t('admin.shippingOrderExtractionRuns.fallbackReasons') }}</dt>
|
||||
<dd>{{ routeItem.fallback_reason_codes.length ? routeItem.fallback_reason_codes.map(code => t(`admin.shippingOrderExtractionRuns.reasonCodes.${code}`)).join(';') : '-' }}</dd>
|
||||
</dl>
|
||||
</section>
|
||||
</div>
|
||||
<p v-if="!detail.units.length" class="text-sm text-muted">{{ t('admin.shippingOrderExtractionRuns.empty') }}</p>
|
||||
</div>
|
||||
<h3 class="mt-7 font-semibold">{{ t('admin.shippingOrderExtractionRuns.lifecycle') }}</h3>
|
||||
<div class="mt-2 space-y-2">
|
||||
<div v-for="event in detail.progress_events" :key="`${event.sequence_no}:${event.event_code}`" class="rounded-lg border border-default p-3 text-sm">
|
||||
<b>{{ event.event_code }}</b>
|
||||
<span class="ml-2 text-secondary">{{ event.status || '-' }}</span>
|
||||
<span class="ml-2 font-mono text-xs text-muted">{{ t(`admin.shippingOrderExtractionRuns.visibilities.${event.visibility}`) }}</span>
|
||||
<span v-if="event.reason_code" class="ml-2 font-mono text-xs text-muted">{{ event.reason_code }}</span>
|
||||
<time class="ml-2 text-xs text-muted">{{ formatTime(event.occurred_at) }}</time>
|
||||
</div>
|
||||
<p v-if="!detail.progress_events.length" class="text-sm text-muted">{{ t('admin.shippingOrderExtractionRuns.empty') }}</p>
|
||||
</div>
|
||||
</template>
|
||||
</aside>
|
||||
</div>
|
||||
|
||||
+339
@@ -0,0 +1,339 @@
|
||||
<!--
|
||||
features/admin/modules/shipping-review-supervision/ShippingReviewSupervisionPage.vue
|
||||
用途:管理员跨用户会话 PDF 工作项监管台——筛选、终止、撤销确认。
|
||||
依赖:shipping-review-supervision.api、Vue I18n、useMessage。
|
||||
逻辑:终止/撤销须填写理由与 confirm_token;成功后刷新列表。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { onMounted, ref } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { BusinessError } from '@/shared/api/client';
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
import type { ShippingSessionWorkItem } from '@/features/chat/types/shipping.api.types';
|
||||
import {
|
||||
SUPERVISION_CONFIRM_REVOKE,
|
||||
SUPERVISION_CONFIRM_TERMINATE,
|
||||
listShippingReviewSupervisionItems,
|
||||
revokeShippingReviewSupervisionConfirmation,
|
||||
terminateShippingReviewSupervisionItem,
|
||||
type ShippingReviewSupervisionFilters,
|
||||
} from '@/features/admin/api/shipping-review-supervision.api';
|
||||
|
||||
type SupervisionAction = 'terminate' | 'revoke';
|
||||
|
||||
const { t, te } = useI18n();
|
||||
const msg = useMessage();
|
||||
const loading = ref(false);
|
||||
const submitting = ref(false);
|
||||
const error = ref('');
|
||||
const page = ref(1);
|
||||
const pageSize = 20;
|
||||
const total = ref(0);
|
||||
const rows = ref<ShippingSessionWorkItem[]>([]);
|
||||
const filters = ref<ShippingReviewSupervisionFilters>({
|
||||
lifecycle_status: '',
|
||||
owner_user_id: '',
|
||||
conversation_id: '',
|
||||
q: '',
|
||||
});
|
||||
const actionDialogOpen = ref(false);
|
||||
const actionKind = ref<SupervisionAction>('terminate');
|
||||
const actionTarget = ref<ShippingSessionWorkItem | null>(null);
|
||||
const actionReason = ref('');
|
||||
const actionConfirmChecked = ref(false);
|
||||
const reasonMissing = ref(false);
|
||||
const confirmMissing = ref(false);
|
||||
|
||||
const formatTime = (value?: string | null) => (value ? new Date(value).toLocaleString() : '—');
|
||||
|
||||
/**
|
||||
* 解析生命周期状态文案。
|
||||
*/
|
||||
function lifecycleLabel(status: string): string {
|
||||
const key = `chat.shippingSessionWorkItem.status.${status}`;
|
||||
return te(key) ? t(key) : status;
|
||||
}
|
||||
|
||||
/**
|
||||
* 加载监管列表。
|
||||
*/
|
||||
async function load() {
|
||||
loading.value = true;
|
||||
error.value = '';
|
||||
try {
|
||||
const response = await listShippingReviewSupervisionItems(page.value, pageSize, filters.value);
|
||||
rows.value = response.items;
|
||||
total.value = response.total;
|
||||
} catch {
|
||||
error.value = t('admin.shippingReviewSupervision.loadFailed');
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function applyFilters() {
|
||||
page.value = 1;
|
||||
await load();
|
||||
}
|
||||
|
||||
/**
|
||||
* 打开终止或撤销确认弹窗。
|
||||
*/
|
||||
function openAction(kind: SupervisionAction, item: ShippingSessionWorkItem) {
|
||||
actionKind.value = kind;
|
||||
actionTarget.value = item;
|
||||
actionReason.value = '';
|
||||
actionConfirmChecked.value = false;
|
||||
reasonMissing.value = false;
|
||||
confirmMissing.value = false;
|
||||
actionDialogOpen.value = true;
|
||||
}
|
||||
|
||||
function closeActionDialog() {
|
||||
actionDialogOpen.value = false;
|
||||
actionTarget.value = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 提交监管写操作;校验理由与 confirm_token。
|
||||
*/
|
||||
async function submitAction() {
|
||||
const item = actionTarget.value;
|
||||
if (!item?.item_no) return;
|
||||
const reason = actionReason.value.trim();
|
||||
if (!reason) {
|
||||
reasonMissing.value = true;
|
||||
return;
|
||||
}
|
||||
if (!actionConfirmChecked.value) {
|
||||
confirmMissing.value = true;
|
||||
return;
|
||||
}
|
||||
submitting.value = true;
|
||||
error.value = '';
|
||||
try {
|
||||
if (actionKind.value === 'terminate') {
|
||||
await terminateShippingReviewSupervisionItem(item.item_no, {
|
||||
reason,
|
||||
confirm_token: SUPERVISION_CONFIRM_TERMINATE,
|
||||
});
|
||||
msg.success(t('admin.shippingReviewSupervision.terminateSuccess'));
|
||||
} else {
|
||||
await revokeShippingReviewSupervisionConfirmation(item.item_no, {
|
||||
reason,
|
||||
confirm_token: SUPERVISION_CONFIRM_REVOKE,
|
||||
});
|
||||
msg.success(t('admin.shippingReviewSupervision.revokeSuccess'));
|
||||
}
|
||||
closeActionDialog();
|
||||
await load();
|
||||
} catch (err) {
|
||||
const message = err instanceof BusinessError ? err.message : t('admin.shippingReviewSupervision.actionFailed');
|
||||
msg.error(message);
|
||||
} finally {
|
||||
submitting.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
const canTerminate = (item: ShippingSessionWorkItem) =>
|
||||
item.lifecycle_status !== 'closed' && (item.available_actions || []).includes('admin_terminate');
|
||||
|
||||
const canRevoke = (item: ShippingSessionWorkItem) =>
|
||||
item.lifecycle_status === 'closed'
|
||||
&& item.closed_reason === 'confirmed'
|
||||
&& (item.available_actions || []).includes('admin_revoke_confirmation');
|
||||
|
||||
onMounted(() => {
|
||||
void load();
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="space-y-5 p-5 md:p-7" data-testid="shipping-review-supervision-page">
|
||||
<header class="flex flex-wrap items-start justify-between gap-4">
|
||||
<div>
|
||||
<h1 class="section-title">{{ t('admin.shippingReviewSupervision.title') }}</h1>
|
||||
<p class="section-desc mt-1 max-w-3xl">{{ t('admin.shippingReviewSupervision.subtitle') }}</p>
|
||||
</div>
|
||||
<button type="button" class="btn-secondary btn-sm" :disabled="loading" @click="load">
|
||||
{{ t('admin.shippingReviewSupervision.refresh') }}
|
||||
</button>
|
||||
</header>
|
||||
|
||||
<div class="grid gap-3 rounded-xl border border-default bg-surface p-3 md:grid-cols-2 lg:grid-cols-4">
|
||||
<label class="space-y-1 text-xs text-secondary">
|
||||
<span>{{ t('admin.shippingReviewSupervision.filters.lifecycleStatus') }}</span>
|
||||
<select v-model="filters.lifecycle_status" class="input-field text-sm">
|
||||
<option value="">{{ t('admin.shippingReviewSupervision.filters.all') }}</option>
|
||||
<option value="pending_review">{{ lifecycleLabel('pending_review') }}</option>
|
||||
<option value="extracting">{{ lifecycleLabel('extracting') }}</option>
|
||||
<option value="reparse_failed">{{ lifecycleLabel('reparse_failed') }}</option>
|
||||
<option value="closed">{{ lifecycleLabel('closed') }}</option>
|
||||
</select>
|
||||
</label>
|
||||
<label class="space-y-1 text-xs text-secondary">
|
||||
<span>{{ t('admin.shippingReviewSupervision.filters.ownerUserId') }}</span>
|
||||
<input v-model="filters.owner_user_id" class="input-field text-sm" @keyup.enter="applyFilters">
|
||||
</label>
|
||||
<label class="space-y-1 text-xs text-secondary">
|
||||
<span>{{ t('admin.shippingReviewSupervision.filters.conversationId') }}</span>
|
||||
<input v-model="filters.conversation_id" class="input-field text-sm" @keyup.enter="applyFilters">
|
||||
</label>
|
||||
<label class="space-y-1 text-xs text-secondary">
|
||||
<span>{{ t('admin.shippingReviewSupervision.filters.q') }}</span>
|
||||
<input v-model="filters.q" class="input-field text-sm" @keyup.enter="applyFilters">
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div class="flex gap-2">
|
||||
<button type="button" class="btn-primary btn-sm" :disabled="loading" @click="applyFilters">
|
||||
{{ t('admin.shippingReviewSupervision.apply') }}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<p v-if="error" class="text-sm text-rose-600 dark:text-rose-400">{{ error }}</p>
|
||||
|
||||
<div class="overflow-x-auto rounded-xl border border-default bg-surface">
|
||||
<table class="min-w-full text-left text-sm">
|
||||
<thead class="border-b border-default bg-muted/40 text-xs text-secondary">
|
||||
<tr>
|
||||
<th class="px-3 py-2 font-medium">{{ t('admin.shippingReviewSupervision.columns.itemNo') }}</th>
|
||||
<th class="px-3 py-2 font-medium">{{ t('admin.shippingReviewSupervision.columns.owner') }}</th>
|
||||
<th class="px-3 py-2 font-medium">{{ t('admin.shippingReviewSupervision.columns.conversation') }}</th>
|
||||
<th class="px-3 py-2 font-medium">{{ t('admin.shippingReviewSupervision.columns.document') }}</th>
|
||||
<th class="px-3 py-2 font-medium">{{ t('admin.shippingReviewSupervision.columns.status') }}</th>
|
||||
<th class="px-3 py-2 font-medium">{{ t('admin.shippingReviewSupervision.columns.updated') }}</th>
|
||||
<th class="px-3 py-2 font-medium">{{ t('admin.shippingReviewSupervision.columns.actions') }}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-if="loading">
|
||||
<td colspan="7" class="px-3 py-6 text-center text-secondary">{{ t('admin.shippingReviewSupervision.loading') }}</td>
|
||||
</tr>
|
||||
<tr v-else-if="!rows.length">
|
||||
<td colspan="7" class="px-3 py-6 text-center text-secondary">{{ t('admin.shippingReviewSupervision.empty') }}</td>
|
||||
</tr>
|
||||
<tr v-for="item in rows" :key="item.item_no" class="border-b border-default last:border-0">
|
||||
<td class="px-3 py-2 font-mono text-xs">{{ item.item_no }}</td>
|
||||
<td class="px-3 py-2">{{ item.owner_user_id }}</td>
|
||||
<td class="max-w-40 truncate px-3 py-2 font-mono text-xs" :title="item.conversation_id">{{ item.conversation_id }}</td>
|
||||
<td class="max-w-48 truncate px-3 py-2" :title="item.current_document_filename || ''">
|
||||
{{ item.current_document_filename || '—' }}
|
||||
</td>
|
||||
<td class="px-3 py-2">
|
||||
<span class="rounded-full bg-muted px-2 py-0.5 text-xs">{{ lifecycleLabel(String(item.lifecycle_status)) }}</span>
|
||||
</td>
|
||||
<td class="px-3 py-2 text-xs text-secondary">{{ formatTime(item.updated_at) }}</td>
|
||||
<td class="px-3 py-2">
|
||||
<div class="flex flex-wrap gap-1">
|
||||
<button
|
||||
v-if="canTerminate(item)"
|
||||
type="button"
|
||||
class="btn-danger btn-xs"
|
||||
data-testid="supervision-terminate-btn"
|
||||
@click="openAction('terminate', item)"
|
||||
>
|
||||
{{ t('admin.shippingReviewSupervision.terminate') }}
|
||||
</button>
|
||||
<button
|
||||
v-if="canRevoke(item)"
|
||||
type="button"
|
||||
class="btn-secondary btn-xs"
|
||||
data-testid="supervision-revoke-btn"
|
||||
@click="openAction('revoke', item)"
|
||||
>
|
||||
{{ t('admin.shippingReviewSupervision.revoke') }}
|
||||
</button>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<footer class="flex items-center justify-between text-sm text-secondary">
|
||||
<span>{{ t('admin.shippingReviewSupervision.total', { count: total }) }}</span>
|
||||
<div class="flex gap-2">
|
||||
<button type="button" class="btn-secondary btn-sm" :disabled="loading || page <= 1" @click="page -= 1; load()">
|
||||
{{ t('admin.shippingReviewSupervision.previous') }}
|
||||
</button>
|
||||
<button type="button" class="btn-secondary btn-sm" :disabled="loading || page * pageSize >= total" @click="page += 1; load()">
|
||||
{{ t('admin.shippingReviewSupervision.next') }}
|
||||
</button>
|
||||
</div>
|
||||
</footer>
|
||||
|
||||
<Teleport to="body">
|
||||
<div
|
||||
v-if="actionDialogOpen && actionTarget"
|
||||
class="dialog-overlay z-50 flex items-center justify-center p-4"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
data-testid="supervision-action-dialog"
|
||||
@click.self="closeActionDialog"
|
||||
>
|
||||
<div class="dialog-panel w-full max-w-md space-y-4 p-5">
|
||||
<header>
|
||||
<h2 class="text-base font-semibold text-primary">
|
||||
{{ actionKind === 'terminate'
|
||||
? t('admin.shippingReviewSupervision.terminateTitle')
|
||||
: t('admin.shippingReviewSupervision.revokeTitle') }}
|
||||
</h2>
|
||||
<p class="mt-2 text-sm text-secondary">
|
||||
{{ actionKind === 'terminate'
|
||||
? t('admin.shippingReviewSupervision.terminateImpact', { itemNo: actionTarget.item_no })
|
||||
: t('admin.shippingReviewSupervision.revokeImpact', { itemNo: actionTarget.item_no }) }}
|
||||
</p>
|
||||
</header>
|
||||
|
||||
<label class="block space-y-1 text-sm">
|
||||
<span class="text-secondary">{{ t('admin.shippingReviewSupervision.reasonLabel') }}</span>
|
||||
<textarea
|
||||
v-model="actionReason"
|
||||
rows="3"
|
||||
class="input-field w-full resize-y text-sm"
|
||||
data-testid="supervision-reason-input"
|
||||
@input="reasonMissing = false"
|
||||
/>
|
||||
<p v-if="reasonMissing" class="text-xs text-rose-600 dark:text-rose-400">
|
||||
{{ t('admin.shippingReviewSupervision.reasonRequired') }}
|
||||
</p>
|
||||
</label>
|
||||
|
||||
<label class="flex items-start gap-2 text-sm">
|
||||
<input
|
||||
v-model="actionConfirmChecked"
|
||||
type="checkbox"
|
||||
class="mt-0.5"
|
||||
data-testid="supervision-confirm-checkbox"
|
||||
@change="confirmMissing = false"
|
||||
>
|
||||
<span class="text-secondary">
|
||||
{{ actionKind === 'terminate'
|
||||
? t('admin.shippingReviewSupervision.confirmTerminate')
|
||||
: t('admin.shippingReviewSupervision.confirmRevoke') }}
|
||||
</span>
|
||||
</label>
|
||||
<p v-if="confirmMissing" class="text-xs text-rose-600 dark:text-rose-400">
|
||||
{{ t('admin.shippingReviewSupervision.confirmRequired') }}
|
||||
</p>
|
||||
|
||||
<footer class="flex justify-end gap-2">
|
||||
<button type="button" class="btn-secondary btn-sm" :disabled="submitting" @click="closeActionDialog">
|
||||
{{ t('common.deleteDialog.cancel') }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
:class="actionKind === 'terminate' ? 'btn-danger btn-sm' : 'btn-primary btn-sm'"
|
||||
:disabled="submitting"
|
||||
data-testid="supervision-action-submit"
|
||||
@click="submitAction"
|
||||
>
|
||||
{{ submitting ? t('admin.shippingReviewSupervision.submitting') : t('admin.shippingReviewSupervision.submit') }}
|
||||
</button>
|
||||
</footer>
|
||||
</div>
|
||||
</div>
|
||||
</Teleport>
|
||||
</section>
|
||||
</template>
|
||||
@@ -16,6 +16,8 @@ const shippingRoutes = adminRoutes[0].children?.filter((route) =>
|
||||
|| route.name === 'AdminShippingOrderSchema'
|
||||
|| route.name === 'AdminShippingIdentityRules'
|
||||
|| route.name === 'AdminShippingOrderExtractionRuns'
|
||||
|| route.name === 'AdminShippingAudit'
|
||||
|| route.name === 'AdminShippingReviewSupervision'
|
||||
|| route.name === 'AdminShippingOrderDocumentProfiles',
|
||||
) ?? [];
|
||||
|
||||
@@ -44,10 +46,12 @@ describe('shipping configuration navigation contract', () => {
|
||||
{ id: 'warehouse_mappings', routeName: 'AdminShippingInventory', path: 'shipping-notice', labelKey: 'admin.shippingInventory.externalMappings', groupKey: 'admin.nav.shippingInventoryManagement', query: { section: 'mappings' } },
|
||||
{ id: 'routing_rules', routeName: 'AdminShippingInventory', path: 'shipping-notice', labelKey: 'admin.shippingInventory.rules', groupKey: 'admin.nav.shippingInventoryManagement', query: { section: 'rules' } },
|
||||
{ id: 'shipping_templates', routeName: 'AdminShippingInventory', path: 'shipping-notice', labelKey: 'admin.shippingInventory.excelTemplates', groupKey: 'admin.nav.shippingInventoryManagement', query: { section: 'templates' } },
|
||||
{ id: 'shipping_audit', routeName: 'AdminShippingAudit', path: 'shipping-audit', labelKey: 'admin.nav.shippingAudit', groupKey: 'admin.nav.shippingRunAudit' },
|
||||
{ id: 'shipping_review_supervision', routeName: 'AdminShippingReviewSupervision', path: 'shipping-review-supervision', labelKey: 'admin.nav.shippingReviewSupervision', groupKey: 'admin.nav.shippingRunAudit' },
|
||||
{ id: 'inventory_snapshots', routeName: 'AdminShippingInventory', path: 'shipping-notice', labelKey: 'admin.shippingInventory.snapshots', groupKey: 'admin.nav.shippingRunAudit', query: { section: 'snapshots' } },
|
||||
{ id: 'export_records', routeName: 'AdminShippingInventory', path: 'shipping-notice', labelKey: 'admin.shippingInventory.exports', groupKey: 'admin.nav.shippingRunAudit', query: { section: 'exports' } },
|
||||
]);
|
||||
expect(shippingRoutes).toHaveLength(6);
|
||||
expect(shippingRoutes).toHaveLength(8);
|
||||
});
|
||||
|
||||
it('keeps exactly three ordered accordion groups', () => {
|
||||
@@ -68,6 +72,8 @@ describe('shipping configuration navigation contract', () => {
|
||||
expect.objectContaining({ requiresAdmin: true, adminModule: 'shipping_inventory', adminSubModule: 'order_schema' }),
|
||||
expect.objectContaining({ requiresAdmin: true, adminModule: 'shipping_inventory', adminSubModule: 'identity_rules' }),
|
||||
expect.objectContaining({ requiresAdmin: true, adminModule: 'shipping_inventory', adminSubModule: 'order_extraction_runs' }),
|
||||
expect.objectContaining({ requiresAdmin: true, adminModule: 'shipping_inventory', adminSubModule: 'shipping_audit' }),
|
||||
expect.objectContaining({ requiresAdmin: true, adminModule: 'shipping_inventory', adminSubModule: 'shipping_review_supervision' }),
|
||||
expect.objectContaining({ requiresAdmin: true, adminModule: 'shipping_inventory', adminSubModule: 'order_document_profiles' }),
|
||||
]);
|
||||
});
|
||||
|
||||
@@ -27,6 +27,8 @@ export type ShippingConfigSubModuleId =
|
||||
| 'order_document_profiles'
|
||||
| 'identity_rules'
|
||||
| 'order_extraction_runs'
|
||||
| 'shipping_audit'
|
||||
| 'shipping_review_supervision'
|
||||
| 'inventory_fields'
|
||||
| 'connections'
|
||||
| 'inventory_sites'
|
||||
|
||||
@@ -26,6 +26,7 @@ export type OrderProfileGovernanceErrorCode =
|
||||
|
||||
export interface OrderProfileRelativeRegion { x0: number; y0: number; x1: number; y1: number; }
|
||||
export interface OrderProfileAnchorRelativeRegion { x0: number; y0: number; x1: number; y1: number; }
|
||||
export interface OrderProfileDocumentMatchAnchor { anchor_id: string; label: string; value: string; value_position: 'right' | 'below'; page_no?: number | null; label_region?: OrderProfileRelativeRegion | null; value_region?: OrderProfileRelativeRegion | null; minimum_evidence_level: OrderProfileEvidenceLevel; }
|
||||
export interface OrderProfileAnchorRule { anchor_id: string; text: string; aliases?: string[]; match_mode: 'exact' | 'contains'; region?: OrderProfileRelativeRegion | null; minimum_evidence_level: OrderProfileEvidenceLevel; }
|
||||
export interface OrderProfileFieldRegion { field_id: string; field_code: string; region: OrderProfileRelativeRegion; extractor_key: OrderProfileExtractorKey; allowed_sources: OrderProfileAllowedSource[]; minimum_evidence_level: OrderProfileEvidenceLevel; target_fields?: Array<{ field_id: string; field_code: string }>; }
|
||||
export interface OrderProfileOrderFieldLayout { layout_id: string; field_id: string; field_code: string; page_scope: 'first_page' | 'all_pages' | 'exact_page'; page_no?: number | null; anchor?: OrderProfileAnchorRule | null; value_region?: OrderProfileAnchorRelativeRegion | null; absolute_value_region?: OrderProfileRelativeRegion | null; fallback_value_region?: OrderProfileRelativeRegion | null; value_mode: 'single_line' | 'multi_line' | 'right_of_anchor' | 'below_anchor'; stop_anchors: OrderProfileAnchorRule[]; normalizer_key?: string | null; required: boolean; minimum_evidence_level: OrderProfileEvidenceLevel; }
|
||||
@@ -33,7 +34,7 @@ export interface OrderProfileDraftUnboundOrderFieldLayout { layout_id: string; l
|
||||
export interface OrderProfileHeaderLayout { layout_id: string; region: OrderProfileRelativeRegion; field_regions: OrderProfileFieldRegion[]; }
|
||||
export interface OrderProfileLineLayout { layout_id: string; row_offset: number; role: 'main' | 'continuation'; region: OrderProfileRelativeRegion; field_regions: OrderProfileFieldRegion[]; new_line_anchor?: OrderProfileAnchorRule | null; continuation_conditions: OrderProfileAnchorRule[]; required_fields: string[]; allowed_empty_fields: string[]; }
|
||||
export interface OrderProfileTableRegion { region_id: string; page_scope: 'first_page' | 'all_pages' | 'continuation_pages' | 'exact_page'; page_no?: number | null; region: OrderProfileRelativeRegion; header_layouts: OrderProfileHeaderLayout[]; line_layouts: OrderProfileLineLayout[]; continuation_rule: { allow_cross_page: boolean; required_anchor_ids: string[] }; termination_rules: Array<{ rule_id: string; anchor: OrderProfileAnchorRule }>; exclusion_regions: OrderProfileRelativeRegion[]; draft_unbound_field_regions?: Array<{ region_id: string; parent_layout_id: string; label: string; region: OrderProfileRelativeRegion }>; }
|
||||
export interface OrderProfileDocumentMatch { document_type: 'purchase_order'; page_pattern: 'one_or_more'; required_anchors: OrderProfileAnchorRule[]; optional_anchors: OrderProfileAnchorRule[]; minimum_score: number; minimum_margin: number; }
|
||||
export interface OrderProfileDocumentMatch { document_type: 'purchase_order'; page_pattern: 'one_or_more'; required_anchors: OrderProfileDocumentMatchAnchor[]; optional_anchors: OrderProfileDocumentMatchAnchor[]; minimum_score: number; minimum_margin: number; }
|
||||
|
||||
/** 阶段 3 重构前仅用于让旧工作台编译;不能作为 v2 API 请求或持久化定义。 */
|
||||
export interface OrderProfileColumnRule { column_index: number; extractor_key: 'direct' | 'temp_internal_parts'; target_field_codes: string[]; target_fields?: Array<{ field_id: string; field_code: string }>; }
|
||||
@@ -390,7 +391,16 @@ export interface OrderProfileBlindTestInput {
|
||||
expected_order_fields?: Record<string, unknown>;
|
||||
}
|
||||
/** 盲测工作台的独立候选样本;已排除当前模板的标注和训练证据。 */
|
||||
export interface OrderProfileBlindTestAvailableSample { document_id: number; table_id: string; page_no: number; filename: string; }
|
||||
export interface OrderProfileBlindTestAvailableSample {
|
||||
document_id: number;
|
||||
table_id: string;
|
||||
page_no: number;
|
||||
filename: string;
|
||||
table_index: number;
|
||||
row_count: number;
|
||||
column_count: number;
|
||||
header_preview: string[];
|
||||
}
|
||||
export interface OrderProfileBlindTestCandidate {
|
||||
document_id: number; table_id: string; rows: Array<Record<string, unknown>>;
|
||||
order_fields: Array<{ field_code: string; value: unknown; status: 'confirmed' | 'needs_review' | 'unavailable'; page_no: number | null; issues: string[] }>;
|
||||
@@ -399,7 +409,7 @@ export interface OrderProfileBlindTestCandidate {
|
||||
/** 工作台的本地几何状态;保存前转为 v2 相对区域定义。 */
|
||||
export interface OrderProfileCanvasRegion {
|
||||
id: string;
|
||||
kind: 'header' | 'header_field' | 'line' | 'field' | 'order_anchor' | 'order_field' | 'exclusion';
|
||||
kind: 'header' | 'header_field' | 'line' | 'field' | 'order_anchor' | 'order_field' | 'exclusion' | 'document_anchor_label' | 'document_anchor_value';
|
||||
label: string;
|
||||
region: OrderProfileRelativeRegion;
|
||||
fieldCode?: string | null;
|
||||
|
||||
@@ -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>
|
||||
@@ -0,0 +1,325 @@
|
||||
/**
|
||||
* features/workspace/shipping-task-center/ShippingRunProgressTable.vue
|
||||
* 用途:任务中心「我的识别」续办表——展示用户自有抽取 Run 的阶段、耗时、取消态与续办动作。
|
||||
* 依赖:shipping.api 分页列表/取消/重试、vue-i18n、vue-router、orderExtractionProgressDisplay。
|
||||
* 逻辑:事实来自后端投影;打开会话/复核深链到 Chat;取消/重试复用工作台 API。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import { onMounted, ref, watch } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { useRouter } from 'vue-router';
|
||||
import {
|
||||
cancelWorkspaceShippingOrderExtractionRun,
|
||||
listShippingChatAgents,
|
||||
listWorkspaceShippingOrderExtractionRunsPage,
|
||||
retryWorkspaceShippingOrderExtractionRun,
|
||||
SHIPPING_NOTICE_AGENT_CODE,
|
||||
} from '@/features/chat/api/shipping.api';
|
||||
import type { ShippingOrderExtractionRun } from '@/features/chat/types/shipping.api.types';
|
||||
import { formatOrderExtractionElapsed } from '@/features/chat/shipping/orderExtractionProgressDisplay';
|
||||
|
||||
const { t, te } = useI18n();
|
||||
const router = useRouter();
|
||||
|
||||
const loading = ref(false);
|
||||
const actingRunNo = ref('');
|
||||
const pendingCancelRunNo = ref('');
|
||||
const cancelReason = ref('');
|
||||
const status = ref('');
|
||||
const page = ref(1);
|
||||
const pageSize = 20;
|
||||
const total = ref(0);
|
||||
const rows = ref<ShippingOrderExtractionRun[]>([]);
|
||||
const chatAgentId = ref<number | null>(null);
|
||||
const error = ref('');
|
||||
|
||||
/**
|
||||
* 解析货代 Chat Agent,供会话深链。
|
||||
*/
|
||||
async function resolveChatAgent() {
|
||||
try {
|
||||
const agents = await listShippingChatAgents();
|
||||
const found = agents.find((a) => String(a.agent_code || '').trim() === SHIPPING_NOTICE_AGENT_CODE);
|
||||
if (found) chatAgentId.value = found.id;
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 分页加载当前用户识别 Run。
|
||||
*/
|
||||
async function load() {
|
||||
loading.value = true;
|
||||
error.value = '';
|
||||
try {
|
||||
const response = await listWorkspaceShippingOrderExtractionRunsPage({
|
||||
status: status.value || undefined,
|
||||
page: page.value,
|
||||
page_size: pageSize,
|
||||
});
|
||||
rows.value = response.items || [];
|
||||
total.value = Number(response.total || 0);
|
||||
} catch {
|
||||
error.value = t('workspace.shippingNotice.myRuns.loadFailed');
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 用户可见阶段文案;无投影时回退状态文案。
|
||||
*/
|
||||
function stageLabel(run: ShippingOrderExtractionRun): string {
|
||||
const stage = String(run.current_activity?.user_visible_stage || '').trim();
|
||||
if (stage) {
|
||||
const key = `chat.shippingOrderExtractionUserStage.${stage}`;
|
||||
if (te(key)) return t(key);
|
||||
}
|
||||
const statusKey = `chat.shippingOrderExtractionCardTitle.${run.status}`;
|
||||
return te(statusKey) ? t(statusKey) : run.status;
|
||||
}
|
||||
|
||||
/**
|
||||
* 打开所属会话;活动 Run 进入聊天进度面。
|
||||
*/
|
||||
async function openInChat(run: ShippingOrderExtractionRun) {
|
||||
const agentId = Number(run.agent_id || chatAgentId.value || 0);
|
||||
if (!agentId) return;
|
||||
const query: Record<string, string> = {};
|
||||
const cid = String(run.conversation_id || '').trim();
|
||||
if (cid) query.conversation_id = cid;
|
||||
if (['review_required', 'partially_completed'].includes(run.status)) {
|
||||
query.mode = 'order-review';
|
||||
query.run_no = run.run_no;
|
||||
}
|
||||
await router.push({ path: `/chat/${agentId}`, query });
|
||||
}
|
||||
|
||||
/** 请求取消整批;排队立即取消,执行中进入正在取消。 */
|
||||
async function submitCancelRun(run: ShippingOrderExtractionRun, reason?: string | null) {
|
||||
if (actingRunNo.value) return;
|
||||
actingRunNo.value = run.run_no;
|
||||
try {
|
||||
await cancelWorkspaceShippingOrderExtractionRun(run.run_no, {
|
||||
reason: String(reason || '').trim() || null,
|
||||
});
|
||||
pendingCancelRunNo.value = '';
|
||||
cancelReason.value = '';
|
||||
await load();
|
||||
} catch {
|
||||
error.value = t('chat.shippingOrderExtractionCancel.failed');
|
||||
} finally {
|
||||
actingRunNo.value = '';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 展开/收起单行取消表单。
|
||||
*/
|
||||
function beginCancelRun(run: ShippingOrderExtractionRun) {
|
||||
if (pendingCancelRunNo.value === run.run_no) {
|
||||
pendingCancelRunNo.value = '';
|
||||
cancelReason.value = '';
|
||||
return;
|
||||
}
|
||||
pendingCancelRunNo.value = run.run_no;
|
||||
cancelReason.value = '';
|
||||
}
|
||||
|
||||
/**
|
||||
* 重试失败附件。
|
||||
*/
|
||||
async function retryRun(run: ShippingOrderExtractionRun) {
|
||||
if (actingRunNo.value) return;
|
||||
actingRunNo.value = run.run_no;
|
||||
try {
|
||||
await retryWorkspaceShippingOrderExtractionRun(run.run_no);
|
||||
await load();
|
||||
} catch {
|
||||
error.value = t('chat.shippingOrderExtractionRetryFailed');
|
||||
} finally {
|
||||
actingRunNo.value = '';
|
||||
}
|
||||
}
|
||||
|
||||
watch(status, () => {
|
||||
page.value = 1;
|
||||
void load();
|
||||
});
|
||||
|
||||
onMounted(async () => {
|
||||
await resolveChatAgent();
|
||||
await load();
|
||||
});
|
||||
|
||||
defineExpose({ reload: load });
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="space-y-3" data-testid="shipping-run-progress-table">
|
||||
<div class="flex flex-wrap items-center justify-between gap-3">
|
||||
<div>
|
||||
<h3 class="text-base font-semibold text-primary">{{ t('workspace.shippingNotice.myRuns.title') }}</h3>
|
||||
<p class="text-xs text-muted">{{ t('workspace.shippingNotice.myRuns.subtitle') }}</p>
|
||||
</div>
|
||||
<label class="flex items-center gap-2 text-sm text-secondary">
|
||||
{{ t('workspace.shippingNotice.myRuns.status') }}
|
||||
<select v-model="status" class="input-field py-1.5 text-sm">
|
||||
<option value="">{{ t('workspace.shippingNotice.myRuns.allStatuses') }}</option>
|
||||
<option
|
||||
v-for="value in ['queued', 'processing', 'completed', 'partially_completed', 'review_required', 'failed', 'cancelled']"
|
||||
:key="value"
|
||||
:value="value"
|
||||
>
|
||||
{{ t(`chat.shippingOrderExtractionCardTitle.${value}`) }}
|
||||
</option>
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<p v-if="error" class="rounded-lg border border-rose-200 bg-rose-50 p-3 text-sm text-rose-700">{{ error }}</p>
|
||||
|
||||
<div class="overflow-x-auto rounded-xl border border-default bg-surface">
|
||||
<table class="min-w-[860px] w-full text-left text-sm">
|
||||
<thead class="border-b border-default bg-surface-soft text-xs text-muted">
|
||||
<tr>
|
||||
<th class="px-3 py-2">{{ t('workspace.shippingNotice.myRuns.runNo') }}</th>
|
||||
<th class="px-3 py-2">{{ t('workspace.shippingNotice.myRuns.status') }}</th>
|
||||
<th class="px-3 py-2">{{ t('workspace.shippingNotice.myRuns.stage') }}</th>
|
||||
<th class="px-3 py-2">{{ t('workspace.shippingNotice.myRuns.summary') }}</th>
|
||||
<th class="px-3 py-2">{{ t('workspace.shippingNotice.myRuns.elapsed') }}</th>
|
||||
<th class="px-3 py-2">{{ t('workspace.shippingNotice.myRuns.actions') }}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-if="loading">
|
||||
<td colspan="6" class="px-3 py-8 text-center text-muted">{{ t('workspace.shippingNotice.myRuns.loading') }}</td>
|
||||
</tr>
|
||||
<tr v-else-if="!rows.length">
|
||||
<td colspan="6" class="px-3 py-8 text-center text-muted">{{ t('workspace.shippingNotice.myRuns.empty') }}</td>
|
||||
</tr>
|
||||
<tr
|
||||
v-for="run in rows"
|
||||
:key="run.run_no"
|
||||
class="border-b border-default last:border-0"
|
||||
>
|
||||
<td class="px-3 py-2 font-mono text-xs">{{ run.run_no }}</td>
|
||||
<td class="px-3 py-2">
|
||||
{{ t(`chat.shippingOrderExtractionCardTitle.${run.status}`) }}
|
||||
<span
|
||||
v-if="run.cancellation?.requested && !run.cancellation?.completed_at"
|
||||
class="ml-1 rounded-full bg-amber-100 px-1.5 py-0.5 text-[10px] text-amber-800"
|
||||
>
|
||||
{{ t('chat.shippingOrderExtractionUserStage.cancellation_requested') }}
|
||||
</span>
|
||||
</td>
|
||||
<td class="px-3 py-2">
|
||||
<div>{{ stageLabel(run) }}</div>
|
||||
<div v-if="run.current_activity?.file_name" class="text-[11px] text-muted">
|
||||
{{ run.current_activity.file_name }}
|
||||
</div>
|
||||
</td>
|
||||
<td class="px-3 py-2 text-xs text-secondary">
|
||||
{{ t('workspace.shippingNotice.myRuns.summaryCounts', {
|
||||
total: run.summary?.total_documents || 0,
|
||||
done: run.summary?.completed_documents || 0,
|
||||
review: run.summary?.review_required_documents || 0,
|
||||
failed: run.summary?.failed_documents || 0,
|
||||
cancelled: run.summary?.cancelled_documents || 0,
|
||||
}) }}
|
||||
</td>
|
||||
<td class="px-3 py-2 text-xs">
|
||||
{{ formatOrderExtractionElapsed(run.current_activity?.elapsed_seconds) || '—' }}
|
||||
</td>
|
||||
<td class="px-3 py-2">
|
||||
<div class="flex flex-wrap gap-2">
|
||||
<button
|
||||
type="button"
|
||||
class="text-xs font-medium text-brand-700 hover:underline"
|
||||
@click="openInChat(run)"
|
||||
>
|
||||
{{ t('workspace.shippingNotice.myRuns.openChat') }}
|
||||
</button>
|
||||
<template v-if="(run.available_actions || []).includes('cancel_run')">
|
||||
<div
|
||||
v-if="pendingCancelRunNo === run.run_no"
|
||||
class="w-full min-w-[220px] space-y-1.5 rounded-md border border-rose-200 bg-rose-50/60 p-2 dark:border-rose-900/40 dark:bg-rose-950/20"
|
||||
>
|
||||
<label class="block text-[11px] text-secondary">
|
||||
{{ t('chat.shippingOrderExtractionCancel.reasonOptional') }}
|
||||
</label>
|
||||
<textarea
|
||||
v-model="cancelReason"
|
||||
rows="2"
|
||||
class="input-field w-full py-1 text-xs"
|
||||
/>
|
||||
<div class="flex flex-wrap gap-2">
|
||||
<button
|
||||
type="button"
|
||||
class="text-xs font-medium text-rose-700 hover:underline"
|
||||
:disabled="actingRunNo === run.run_no"
|
||||
@click="submitCancelRun(run, cancelReason)"
|
||||
>
|
||||
{{ actingRunNo === run.run_no
|
||||
? t('chat.shippingOrderExtractionCancel.submitting')
|
||||
: t('chat.shippingOrderExtractionAction.cancel_run') }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="text-xs text-muted hover:underline"
|
||||
:disabled="actingRunNo === run.run_no"
|
||||
@click="pendingCancelRunNo = ''; cancelReason = ''"
|
||||
>
|
||||
{{ t('chat.shippingOrderExtractionCancel.dismiss') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
v-else
|
||||
type="button"
|
||||
class="text-xs font-medium text-rose-700 hover:underline"
|
||||
:disabled="actingRunNo === run.run_no"
|
||||
@click="beginCancelRun(run)"
|
||||
>
|
||||
{{ t('chat.shippingOrderExtractionAction.cancel_run') }}
|
||||
</button>
|
||||
</template>
|
||||
<button
|
||||
v-if="(run.available_actions || []).includes('retry_failed_attachments') || (run.summary?.failed_documents || 0) > 0"
|
||||
type="button"
|
||||
class="text-xs font-medium text-secondary hover:underline"
|
||||
:disabled="actingRunNo === run.run_no"
|
||||
@click="retryRun(run)"
|
||||
>
|
||||
{{ t('chat.shippingOrderExtractionAction.retry_failed_attachments') }}
|
||||
</button>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<div class="flex items-center justify-end gap-3 text-sm">
|
||||
<span class="text-xs text-muted">{{ t('workspace.shippingNotice.myRuns.total', { count: total }) }}</span>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded border border-default px-3 py-1.5 disabled:opacity-50"
|
||||
:disabled="page <= 1 || loading"
|
||||
@click="page -= 1; load()"
|
||||
>
|
||||
{{ t('workspace.shippingNotice.myRuns.previous') }}
|
||||
</button>
|
||||
<span>{{ page }}</span>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded border border-default px-3 py-1.5 disabled:opacity-50"
|
||||
:disabled="page * pageSize >= total || loading"
|
||||
@click="page += 1; load()"
|
||||
>
|
||||
{{ t('workspace.shippingNotice.myRuns.next') }}
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
@@ -1,8 +1,8 @@
|
||||
/**
|
||||
* features/workspace/shipping-task-center/ShippingTaskCenterPage.vue
|
||||
* 用途:发货「我的待办」壳——Pending|Processing|Done + 右侧任务工作台或复核深链。
|
||||
* 依赖:shipping-tasks.api(my-todos)、shipping.api 详情、ShippingTaskWorkbench、useShippingTodoBadge。
|
||||
* 逻辑:review_case 项用 review_run_no 打开人工复核;task 项打开任务处理工作台。
|
||||
* 用途:发货「我的待办」壳——Pending|Processing|Done + 识别 Run 续办表 + 右侧任务工作台或复核深链。
|
||||
* 依赖:shipping-tasks.api(my-todos)、shipping.api 详情、ShippingTaskWorkbench、ShippingRunProgressTable、useShippingTodoBadge。
|
||||
* 逻辑:review_case 项用 review_run_no 打开人工复核;task 项打开任务处理工作台;识别页承接取消/重试/回会话。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref, watch } from 'vue';
|
||||
@@ -22,11 +22,14 @@ import {
|
||||
} from '@/features/workspace/api/shipping-tasks.api';
|
||||
import { useShippingTodoBadge } from '../composables/useShippingTodoBadge';
|
||||
import ShippingTaskWorkbench from './ShippingTaskWorkbench.vue';
|
||||
import ShippingRunProgressTable from './ShippingRunProgressTable.vue';
|
||||
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
const { refreshShippingTodoBadge } = useShippingTodoBadge();
|
||||
|
||||
/** todos=建单后待办;runs=建单前识别续办 */
|
||||
const surface = ref<'todos' | 'runs'>('todos');
|
||||
const bucket = ref<'pending' | 'processing' | 'done'>('pending');
|
||||
const filterTodoCategory = ref<'all' | 'review' | 'exception' | 'manual_upload'>('all');
|
||||
const filterCustomer = ref('');
|
||||
@@ -58,6 +61,7 @@ const preferredTaskNo = computed(() =>
|
||||
String(route.params.taskNo || route.query.task_no || '').trim().toUpperCase(),
|
||||
);
|
||||
const preferredReviewRun = computed(() => String(route.query.run_no || '').trim());
|
||||
const isDirectTaskRoute = computed(() => Boolean(String(route.params.taskNo || '').trim()));
|
||||
|
||||
const selectedItem = computed(() =>
|
||||
tasks.value.find((item) => todoItemKey(item) === selectedRef.value) || null,
|
||||
@@ -193,6 +197,10 @@ async function loadDetail(taskNo: string) {
|
||||
*/
|
||||
async function refreshAll() {
|
||||
await Promise.all([loadTodos(), loadCounts()]);
|
||||
if (isDirectTaskRoute.value && preferredTaskNo.value) {
|
||||
await loadDetail(preferredTaskNo.value);
|
||||
return;
|
||||
}
|
||||
const item = selectedItem.value;
|
||||
if (item?.task_no && item.item_kind !== 'review_case') {
|
||||
await loadDetail(item.task_no);
|
||||
@@ -281,6 +289,11 @@ watch(selectedItem, (item) => {
|
||||
onMounted(async () => {
|
||||
await Promise.all([resolveChatAgent(), loadCounts(), loadTodos()]);
|
||||
if (preferredTaskNo.value) {
|
||||
if (isDirectTaskRoute.value) {
|
||||
selectedRef.value = preferredTaskNo.value;
|
||||
await loadDetail(preferredTaskNo.value);
|
||||
return;
|
||||
}
|
||||
const hit = tasks.value.find((item) => String(item.task_no || '').toUpperCase() === preferredTaskNo.value);
|
||||
if (!hit) {
|
||||
selectedRef.value = preferredTaskNo.value;
|
||||
@@ -307,6 +320,52 @@ onMounted(async () => {
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="flex flex-wrap gap-2">
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-xl px-3 py-1.5 text-sm font-medium"
|
||||
:class="surface === 'todos' ? 'bg-brand-600 text-white' : 'border border-default text-secondary hover:bg-surface-soft'"
|
||||
@click="surface = 'todos'"
|
||||
>
|
||||
{{ $t('workspace.shippingNotice.myTodos.title') }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-xl px-3 py-1.5 text-sm font-medium"
|
||||
:class="surface === 'runs' ? 'bg-brand-600 text-white' : 'border border-default text-secondary hover:bg-surface-soft'"
|
||||
@click="surface = 'runs'"
|
||||
>
|
||||
{{ $t('workspace.shippingNotice.myRuns.title') }}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div v-if="isDirectTaskRoute" class="rounded-2xl border border-default bg-surface p-4">
|
||||
<div v-if="detailLoading" class="py-16 text-center text-sm text-muted">
|
||||
{{ $t('workspace.shippingNotice.loading') }}
|
||||
</div>
|
||||
<div v-else-if="!detail" class="py-16 text-center text-sm text-muted">
|
||||
{{ $t('workspace.shippingNotice.selectCase') }}
|
||||
</div>
|
||||
<div v-else class="space-y-3">
|
||||
<div class="flex flex-wrap items-center justify-between gap-2">
|
||||
<div class="font-mono text-lg font-bold text-primary">{{ detail.task_no }}</div>
|
||||
<button
|
||||
v-if="chatAgentId"
|
||||
type="button"
|
||||
class="inline-flex items-center gap-1 rounded-xl border border-default px-3 py-1.5 text-xs font-medium text-secondary hover:bg-surface-soft"
|
||||
@click="openInChat"
|
||||
>
|
||||
<ExternalLink class="h-3.5 w-3.5" />
|
||||
{{ $t('workspace.shippingNotice.openChat') }}
|
||||
</button>
|
||||
</div>
|
||||
<ShippingTaskWorkbench :detail="detail" :can-handle="canHandle" @refreshed="refreshAll" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<ShippingRunProgressTable v-else-if="surface === 'runs'" />
|
||||
|
||||
<template v-else>
|
||||
<div class="flex flex-wrap gap-2">
|
||||
<button
|
||||
v-for="key in (['pending', 'processing', 'done'] as const)"
|
||||
@@ -480,5 +539,6 @@ onMounted(async () => {
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
</template>
|
||||
Reference in new issue
Block a user