feat(shipping-notice): 增强发货通知与审计功能,支持敏感数据控制与哈希链校验
- 更新发货通知工具 API,剥离不可信的操作人身份字段,确保审计安全 - 引入审计事件的哈希链校验机制,支持数据完整性验证 - 增强订单抽取与审计功能,支持敏感快照的访问控制 - 更新相关模型与服务,确保新功能的完整性与可追溯性 - 完善文档与代码注释,反映新的业务逻辑与审计要求
This commit is contained in:
1 parent
95cdfe66b0
commit
d0fe084999
225 files changed
+25923
-6653
No files matched your search
@@ -1,8 +1,9 @@
|
||||
/**
|
||||
* features/admin/api/shipping-audit.api.ts
|
||||
* 用途:货代统一审计查询/详情/导出 HTTP 客户端。
|
||||
* 用途:货代统一审计查询/详情/关联链/哈希校验/导出 HTTP 客户端。
|
||||
* 依赖:shared/api/client、getAuthHeaders。
|
||||
* 逻辑:由 ShippingAuditCenterPage 调用;导出走 blob 下载并保留服务端文件名。
|
||||
* 逻辑:由 ShippingAuditCenterPage / ShippingAuditEventDetailDrawer 调用;
|
||||
* 导出走 blob 下载;敏感详情由后端按 audit_sensitive_read 裁剪。
|
||||
*/
|
||||
import { requestJson } from '@/shared/api/client';
|
||||
import { getAuthHeaders } from '@/shared/utils/auth';
|
||||
@@ -16,7 +17,8 @@ export type ShippingAuditEventSummary = {
|
||||
task_no?: string | null;
|
||||
document_id?: string | null;
|
||||
conversation_id?: string | null;
|
||||
session_item_id?: string | null;
|
||||
workflow_id?: string | null;
|
||||
workflow_item_id?: string | null;
|
||||
review_case_no?: string | null;
|
||||
owner_user_id?: string | null;
|
||||
actor_type: string;
|
||||
@@ -27,7 +29,11 @@ export type ShippingAuditEventSummary = {
|
||||
action?: string | null;
|
||||
reason_code?: string | null;
|
||||
error_code?: string | null;
|
||||
sensitivity_level?: string | null;
|
||||
previous_event_hash?: string | null;
|
||||
event_hash?: string | null;
|
||||
has_snapshots: boolean;
|
||||
sensitive_redacted?: boolean;
|
||||
created_at?: string | null;
|
||||
};
|
||||
|
||||
@@ -42,6 +48,7 @@ export type ShippingAuditEventDetail = ShippingAuditEventSummary & {
|
||||
before_snapshot?: Record<string, unknown> | null;
|
||||
after_snapshot?: Record<string, unknown> | null;
|
||||
diff?: ShippingAuditDiffRow[];
|
||||
diff_json?: Record<string, unknown> | null;
|
||||
metadata?: Record<string, unknown>;
|
||||
evidence_refs?: Array<Record<string, unknown>>;
|
||||
artifact_refs?: Array<Record<string, unknown>>;
|
||||
@@ -57,13 +64,10 @@ export type ShippingAuditFilters = {
|
||||
document_id?: string;
|
||||
operation_id?: string;
|
||||
request_id?: string;
|
||||
/** 会话 ID;与后端 conversation_id 筛选对齐 */
|
||||
conversation_id?: string;
|
||||
/** 会话 PDF 工作项编号 */
|
||||
session_item_id?: string;
|
||||
/** 人工复核 Case 编号 */
|
||||
workflow_id?: string;
|
||||
workflow_item_id?: string;
|
||||
review_case_no?: string;
|
||||
/** 工作项属主用户 ID */
|
||||
owner_user_id?: string;
|
||||
result?: string;
|
||||
created_from?: string;
|
||||
@@ -71,6 +75,23 @@ export type ShippingAuditFilters = {
|
||||
q?: string;
|
||||
};
|
||||
|
||||
export type ShippingAuditAssociationChain = {
|
||||
items: ShippingAuditEventSummary[];
|
||||
total: number;
|
||||
association_keys: Record<string, string[]>;
|
||||
truncated: boolean;
|
||||
limit: number;
|
||||
};
|
||||
|
||||
export type ShippingAuditHashVerifyResult = {
|
||||
ok: boolean;
|
||||
checked_chains: number;
|
||||
failed_chains: number;
|
||||
failures_sample: Array<Record<string, unknown>>;
|
||||
mode?: string;
|
||||
skipped?: boolean;
|
||||
};
|
||||
|
||||
const auth = () => ({ headers: getAuthHeaders() });
|
||||
|
||||
/**
|
||||
@@ -88,7 +109,7 @@ export function listShippingAuditEvents(page = 1, pageSize = 25, filters: Shippi
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取单条审计详情(含白名单快照与 diff)。
|
||||
* 读取单条审计详情(含白名单快照与 diff;敏感项可能脱敏)。
|
||||
*/
|
||||
export function getShippingAuditEvent(eventId: number) {
|
||||
return requestJson<ShippingAuditEventDetail>(
|
||||
@@ -97,6 +118,40 @@ export function getShippingAuditEvent(eventId: number) {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 按 Workflow / Item / Run / PDF / Case / Task 关联键追溯全链。
|
||||
*/
|
||||
export function listShippingAuditAssociationChain(filters: ShippingAuditFilters = {}, limit = 500) {
|
||||
const params = new URLSearchParams({ limit: String(limit) });
|
||||
Object.entries(filters).forEach(([key, value]) => {
|
||||
if (value) params.set(key, String(value));
|
||||
});
|
||||
return requestJson<ShippingAuditAssociationChain>(
|
||||
`/api/admin/shipping-notice/audit-events/association-chain?${params}`,
|
||||
auth(),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验审计哈希链完整性。
|
||||
*/
|
||||
export function verifyShippingAuditHashChain(body: {
|
||||
aggregate_type?: string;
|
||||
aggregate_id?: string;
|
||||
workflow_id?: string;
|
||||
workflow_item_id?: string;
|
||||
sample_limit?: number;
|
||||
} = {}) {
|
||||
return requestJson<ShippingAuditHashVerifyResult>(
|
||||
'/api/admin/shipping-notice/audit-events/verify-hash-chain',
|
||||
{
|
||||
method: 'POST',
|
||||
headers: { ...getAuthHeaders(), 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(body),
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 受控导出审计 CSV/JSON,并触发浏览器下载。
|
||||
*/
|
||||
|
||||
@@ -8,6 +8,10 @@
|
||||
import { requestJson } from '@/shared/api/client';
|
||||
import { getAuthHeaders } from '@/shared/utils/auth';
|
||||
import type {
|
||||
ShippingOrderDerivationRule,
|
||||
ShippingOrderDerivationSimulateRequest,
|
||||
ShippingOrderDerivationSimulateResult,
|
||||
ShippingOrderDerivationSimulateSampleItem,
|
||||
ShippingOrderField,
|
||||
ShippingOrderFieldConfig,
|
||||
ShippingOrderSchemaAuditEventPage,
|
||||
@@ -154,12 +158,13 @@ export const getShippingOrderExtractionAudit = (extractionId: number) =>
|
||||
auth(),
|
||||
);
|
||||
|
||||
/** 整体保存草稿字段配置、自动建单策略及每个字段的版本纳入状态。 */
|
||||
/** 整体保存草稿字段配置、自动建单策略、派生规则及每个字段的版本纳入状态。 */
|
||||
export const saveShippingOrderSchemaDraft = (
|
||||
versionId: number,
|
||||
payload: {
|
||||
fields: ShippingOrderFieldConfig[];
|
||||
auto_creation_policy?: { enabled: boolean };
|
||||
derivation_rules?: ShippingOrderDerivationRule[];
|
||||
change_note?: string;
|
||||
expected_lock_version: number;
|
||||
},
|
||||
@@ -172,6 +177,34 @@ export const saveShippingOrderSchemaDraft = (
|
||||
},
|
||||
);
|
||||
|
||||
/**
|
||||
* 对 Schema 版本派生规则做样本模拟(不改订单)。
|
||||
* @param versionId - Schema 版本 ID
|
||||
* @param payload - 样本行与可选规则覆盖 / sample_ref
|
||||
*/
|
||||
export const simulateShippingOrderSchemaDerivation = (
|
||||
versionId: number,
|
||||
payload: ShippingOrderDerivationSimulateRequest,
|
||||
) =>
|
||||
requestJson<ShippingOrderDerivationSimulateResult>(
|
||||
`/api/admin/shipping-order-schema/versions/${versionId}/simulate-derivation`,
|
||||
{
|
||||
method: 'POST',
|
||||
body: JSON.stringify(payload),
|
||||
...jsonAuth(),
|
||||
},
|
||||
);
|
||||
|
||||
/**
|
||||
* 列出可供派生规则模拟的历史 Extraction 样本。
|
||||
* @param limit - 返回条数上限
|
||||
*/
|
||||
export const listShippingOrderSchemaDerivationSimulateSamples = (limit = 20) =>
|
||||
requestJson<{ items: ShippingOrderDerivationSimulateSampleItem[] }>(
|
||||
`/api/admin/shipping-order-schema/derivation-simulate-samples?limit=${limit}`,
|
||||
auth(),
|
||||
);
|
||||
|
||||
/** 删除错误草稿;发布版本由服务端拒绝删除。 */
|
||||
export const deleteShippingOrderSchemaDraft = (versionId: number) =>
|
||||
requestJson<void>(`/api/admin/shipping-order-schema/versions/${versionId}`, {
|
||||
|
||||
@@ -1,90 +0,0 @@
|
||||
/**
|
||||
* 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),
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
/**
|
||||
* 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);
|
||||
});
|
||||
});
|
||||
@@ -22,7 +22,6 @@ export interface ShippingConfigSubModuleMeta {
|
||||
| 'AdminShippingIdentityRules'
|
||||
| 'AdminShippingOrderExtractionRuns'
|
||||
| 'AdminShippingAudit'
|
||||
| 'AdminShippingReviewSupervision'
|
||||
| 'AdminShippingOrderDocumentProfiles';
|
||||
path:
|
||||
| 'shipping-notice'
|
||||
@@ -31,7 +30,6 @@ export interface ShippingConfigSubModuleMeta {
|
||||
| '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';
|
||||
@@ -74,7 +72,6 @@ export const SHIPPING_CONFIG_SUB_MODULE_METAS: ShippingConfigSubModuleMeta[] = [
|
||||
{ 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' } },
|
||||
];
|
||||
|
||||
@@ -1,15 +1,17 @@
|
||||
/**
|
||||
* features/admin/e2e/shipping-audit.spec.ts
|
||||
* 用途:阶段 4 管理员审计中心契约冒烟——Diff/导出权限、会话工作项筛选与脱敏边界。
|
||||
* 用途:阶段 4 管理员审计中心契约冒烟——权限脱敏、Diff、关联链与哈希校验 DTO。
|
||||
* 依赖:Vitest、shipping-audit.api 类型约定。
|
||||
* 逻辑:断言列表不含快照字段;详情 Diff 仅白名单键;筛选 DTO 含 session 工作项字段。
|
||||
* 逻辑:断言列表不含快照;筛选含 Workflow/Item/Run/PDF/Case/Task;敏感脱敏字段存在。
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import type {
|
||||
ShippingAuditAssociationChain,
|
||||
ShippingAuditDiffRow,
|
||||
ShippingAuditEventDetail,
|
||||
ShippingAuditEventSummary,
|
||||
ShippingAuditFilters,
|
||||
ShippingAuditHashVerifyResult,
|
||||
} from '@/features/admin/api/shipping-audit.api';
|
||||
|
||||
describe('shipping audit center e2e contract', () => {
|
||||
@@ -23,6 +25,8 @@ describe('shipping audit center e2e contract', () => {
|
||||
has_snapshots: true,
|
||||
run_no: 'SNER-1',
|
||||
task_no: 'ST-1',
|
||||
workflow_id: 'WF-1',
|
||||
workflow_item_id: 'WFI-1',
|
||||
operation_id: 'op-1',
|
||||
};
|
||||
// 关键断言:列表 DTO 无 before/after 快照字段,避免误渲染正文。
|
||||
@@ -39,6 +43,7 @@ describe('shipping audit center e2e contract', () => {
|
||||
aggregate_id: 'SNER-2',
|
||||
actor_type: 'system',
|
||||
has_snapshots: true,
|
||||
sensitive_redacted: false,
|
||||
before_snapshot: { status: 'queued' },
|
||||
after_snapshot: { status: 'processing' },
|
||||
diff: [
|
||||
@@ -50,43 +55,72 @@ describe('shipping audit center e2e contract', () => {
|
||||
expect(JSON.stringify(detail)).not.toContain('https://');
|
||||
});
|
||||
|
||||
it('sensitive detail can be redacted by permission', () => {
|
||||
const detail: ShippingAuditEventDetail = {
|
||||
id: 4,
|
||||
event_type: 'order_review_confirmed',
|
||||
aggregate_type: 'shipping_order_review_case',
|
||||
aggregate_id: 'SRC-4',
|
||||
actor_type: 'user',
|
||||
has_snapshots: true,
|
||||
sensitivity_level: 'sensitive',
|
||||
sensitive_redacted: true,
|
||||
before_snapshot: null,
|
||||
after_snapshot: null,
|
||||
diff: [],
|
||||
};
|
||||
// 关键断言:无 audit_sensitive_read 时敏感正文脱敏。
|
||||
expect(detail.sensitive_redacted).toBe(true);
|
||||
expect(detail.before_snapshot).toBeNull();
|
||||
expect(detail.diff).toEqual([]);
|
||||
});
|
||||
|
||||
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', () => {
|
||||
it('audit filters carry workflow association query keys', () => {
|
||||
const filters: ShippingAuditFilters = {
|
||||
conversation_id: 'conv-1',
|
||||
session_item_id: 'SPWI-1',
|
||||
workflow_id: 'WF-1',
|
||||
workflow_item_id: 'WFI-1',
|
||||
run_no: 'SNER-1',
|
||||
document_id: '42',
|
||||
review_case_no: 'SRC-1',
|
||||
owner_user_id: '42',
|
||||
task_no: 'ST-1',
|
||||
actor_id: '9',
|
||||
result: 'success',
|
||||
};
|
||||
// 关键断言:前端筛选 DTO 与 admin API _audit_filters_from_request 键对齐。
|
||||
expect(Object.keys(filters).sort()).toEqual([
|
||||
'conversation_id',
|
||||
'owner_user_id',
|
||||
'actor_id',
|
||||
'document_id',
|
||||
'result',
|
||||
'review_case_no',
|
||||
'session_item_id',
|
||||
'run_no',
|
||||
'task_no',
|
||||
'workflow_id',
|
||||
'workflow_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: [],
|
||||
it('association chain and hash verify DTOs expose integrity fields', () => {
|
||||
const chain: ShippingAuditAssociationChain = {
|
||||
items: [],
|
||||
total: 0,
|
||||
association_keys: { workflow_id: ['WF-1'], task_no: ['ST-1'] },
|
||||
truncated: false,
|
||||
limit: 500,
|
||||
};
|
||||
expect(detail.session_item_id).toBe('SPWI-3');
|
||||
expect(detail.owner_user_id).toBe('99');
|
||||
expect('before_snapshot' in (detail as ShippingAuditEventSummary)).toBe(false);
|
||||
const verify: ShippingAuditHashVerifyResult = {
|
||||
ok: true,
|
||||
checked_chains: 3,
|
||||
failed_chains: 0,
|
||||
failures_sample: [],
|
||||
mode: 'sample',
|
||||
};
|
||||
expect(chain.association_keys.workflow_id).toEqual(['WF-1']);
|
||||
expect(verify.failed_chains).toBe(0);
|
||||
expect(verify.ok).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -1,8 +1,8 @@
|
||||
<!--
|
||||
features/admin/modules/shipping-audit/ShippingAuditCenterPage.vue
|
||||
用途:管理员货代统一审计中心——筛选、详情 Diff、受控导出。
|
||||
依赖:shipping-audit.api、Vue I18n、Vue Router。
|
||||
逻辑:列表展示会话/工作项/Case 关联字段;不含快照全文;打开详情才拉取白名单前后差异;导出写服务端访问审计。
|
||||
用途:管理员货代统一审计中心——按 Workflow/Item/Run/PDF/Case/Task 筛选、详情 Diff、关联链、哈希校验、受控导出。
|
||||
依赖:shipping-audit.api、ShippingAuditEventDetailDrawer、Vue I18n。
|
||||
逻辑:列表不含快照全文;详情抽屉按权限脱敏;导出/校验写服务端访问审计。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { onMounted, ref } from 'vue';
|
||||
@@ -10,32 +10,40 @@ import { useI18n } from 'vue-i18n';
|
||||
import {
|
||||
exportShippingAuditEvents,
|
||||
getShippingAuditEvent,
|
||||
listShippingAuditAssociationChain,
|
||||
listShippingAuditEvents,
|
||||
verifyShippingAuditHashChain,
|
||||
type ShippingAuditEventDetail,
|
||||
type ShippingAuditEventSummary,
|
||||
type ShippingAuditFilters,
|
||||
type ShippingAuditHashVerifyResult,
|
||||
} from '@/features/admin/api/shipping-audit.api';
|
||||
import ShippingAuditEventDetailDrawer from './ShippingAuditEventDetailDrawer.vue';
|
||||
|
||||
const { t } = useI18n();
|
||||
const loading = ref(false);
|
||||
const detailLoading = ref(false);
|
||||
const exporting = ref(false);
|
||||
const verifying = 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 chainHint = ref('');
|
||||
const verifyResult = ref<ShippingAuditHashVerifyResult | null>(null);
|
||||
const filters = ref<ShippingAuditFilters>({
|
||||
event_type: '',
|
||||
actor_type: '',
|
||||
actor_id: '',
|
||||
workflow_id: '',
|
||||
workflow_item_id: '',
|
||||
run_no: '',
|
||||
task_no: '',
|
||||
document_id: '',
|
||||
conversation_id: '',
|
||||
session_item_id: '',
|
||||
review_case_no: '',
|
||||
task_no: '',
|
||||
conversation_id: '',
|
||||
owner_user_id: '',
|
||||
operation_id: '',
|
||||
request_id: '',
|
||||
@@ -56,6 +64,17 @@ function normalizeDateTimeFilter(value?: string): string {
|
||||
return date.toISOString();
|
||||
}
|
||||
|
||||
/**
|
||||
* 组装当前筛选 payload。
|
||||
*/
|
||||
function buildFilterPayload(): ShippingAuditFilters {
|
||||
return {
|
||||
...filters.value,
|
||||
created_from: normalizeDateTimeFilter(filters.value.created_from),
|
||||
created_to: normalizeDateTimeFilter(filters.value.created_to),
|
||||
};
|
||||
}
|
||||
|
||||
const formatTime = (value?: string | null) => (value ? new Date(value).toLocaleString() : '—');
|
||||
|
||||
/**
|
||||
@@ -65,12 +84,7 @@ 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);
|
||||
const response = await listShippingAuditEvents(page.value, pageSize, buildFilterPayload());
|
||||
rows.value = response.items;
|
||||
total.value = response.total;
|
||||
} catch {
|
||||
@@ -103,6 +117,56 @@ async function openDetail(eventId: number) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 按当前关联种子拉取全链摘要提示。
|
||||
*/
|
||||
async function loadAssociationChain() {
|
||||
error.value = '';
|
||||
chainHint.value = '';
|
||||
try {
|
||||
const payload = buildFilterPayload();
|
||||
const hasSeed = Boolean(
|
||||
payload.workflow_id || payload.workflow_item_id || payload.run_no
|
||||
|| payload.document_id || payload.review_case_no || payload.task_no,
|
||||
);
|
||||
if (!hasSeed) {
|
||||
error.value = t('admin.shippingAudit.chainSeedRequired');
|
||||
return;
|
||||
}
|
||||
const chain = await listShippingAuditAssociationChain(payload, 500);
|
||||
chainHint.value = t('admin.shippingAudit.chainSummary', {
|
||||
total: chain.total,
|
||||
truncated: chain.truncated ? t('admin.shippingAudit.chainTruncated') : '',
|
||||
});
|
||||
rows.value = chain.items.slice().reverse();
|
||||
total.value = chain.total;
|
||||
page.value = 1;
|
||||
} catch {
|
||||
error.value = t('admin.shippingAudit.chainFailed');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 触发哈希链校验。
|
||||
*/
|
||||
async function runHashVerify() {
|
||||
verifying.value = true;
|
||||
error.value = '';
|
||||
verifyResult.value = null;
|
||||
try {
|
||||
const payload = buildFilterPayload();
|
||||
verifyResult.value = await verifyShippingAuditHashChain({
|
||||
workflow_id: payload.workflow_id || undefined,
|
||||
workflow_item_id: payload.workflow_item_id || undefined,
|
||||
sample_limit: 200,
|
||||
});
|
||||
} catch {
|
||||
error.value = t('admin.shippingAudit.verifyFailed');
|
||||
} finally {
|
||||
verifying.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 导出当前筛选条件下的 CSV。
|
||||
*/
|
||||
@@ -110,12 +174,7 @@ 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');
|
||||
await exportShippingAuditEvents(buildFilterPayload(), 'csv');
|
||||
} catch {
|
||||
error.value = t('admin.shippingAudit.exportFailed');
|
||||
} finally {
|
||||
@@ -135,7 +194,13 @@ onMounted(() => {
|
||||
<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">
|
||||
<div class="flex flex-wrap gap-2">
|
||||
<button type="button" class="btn-secondary btn-sm" :disabled="verifying" @click="runHashVerify">
|
||||
{{ verifying ? t('admin.shippingAudit.verifying') : t('admin.shippingAudit.verifyChain') }}
|
||||
</button>
|
||||
<button type="button" class="btn-secondary btn-sm" @click="loadAssociationChain">
|
||||
{{ t('admin.shippingAudit.loadChain') }}
|
||||
</button>
|
||||
<button type="button" class="btn-secondary btn-sm" :disabled="exporting" @click="exportCsv">
|
||||
{{ exporting ? t('admin.shippingAudit.exporting') : t('admin.shippingAudit.export') }}
|
||||
</button>
|
||||
@@ -147,8 +212,28 @@ onMounted(() => {
|
||||
|
||||
<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">
|
||||
<span>{{ t('admin.shippingAudit.filters.workflowId') }}</span>
|
||||
<input v-model="filters.workflow_id" class="input-field text-sm" @keyup.enter="applyFilters">
|
||||
</label>
|
||||
<label class="space-y-1 text-xs text-secondary">
|
||||
<span>{{ t('admin.shippingAudit.filters.workflowItemId') }}</span>
|
||||
<input v-model="filters.workflow_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.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.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.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.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.actorType') }}</span>
|
||||
@@ -165,40 +250,8 @@ onMounted(() => {
|
||||
<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">
|
||||
<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.result') }}</span>
|
||||
@@ -221,17 +274,29 @@ onMounted(() => {
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<p v-if="chainHint" class="rounded-lg border border-default bg-surface-soft px-3 py-2 text-xs text-secondary">{{ chainHint }}</p>
|
||||
<p
|
||||
v-if="verifyResult"
|
||||
class="rounded-lg border border-default bg-surface-soft px-3 py-2 text-xs text-secondary"
|
||||
data-testid="shipping-audit-verify-result"
|
||||
>
|
||||
{{ t('admin.shippingAudit.verifySummary', {
|
||||
ok: verifyResult.ok ? t('admin.shippingAudit.verifyOk') : t('admin.shippingAudit.verifyFailedShort'),
|
||||
checked: verifyResult.checked_chains,
|
||||
failed: verifyResult.failed_chains,
|
||||
}) }}
|
||||
</p>
|
||||
<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">
|
||||
<table class="min-w-[1360px] 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.workflow') }}</th>
|
||||
<th class="px-3 py-2">{{ t('admin.shippingAudit.columns.workflowItem') }}</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>
|
||||
@@ -253,8 +318,8 @@ onMounted(() => {
|
||||
<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.workflow_id || '—' }}</td>
|
||||
<td class="px-3 py-2 font-mono text-xs">{{ row.workflow_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>
|
||||
@@ -276,41 +341,10 @@ onMounted(() => {
|
||||
<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>
|
||||
<ShippingAuditEventDetailDrawer
|
||||
:detail="detail"
|
||||
:loading="detailLoading"
|
||||
@close="detail = null"
|
||||
/>
|
||||
</section>
|
||||
</template>
|
||||
+85
@@ -0,0 +1,85 @@
|
||||
/**
|
||||
* features/admin/modules/shipping-audit/ShippingAuditEventDetailDrawer.spec.ts
|
||||
* 用途:锁定审计详情抽屉脱敏提示与 Diff 渲染契约。
|
||||
* 依赖:Vitest、@vue/test-utils、ShippingAuditEventDetailDrawer。
|
||||
* 逻辑:敏感脱敏文案可见;Diff 行按 key 渲染;无 Diff 显示空态。
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { mount } from '@vue/test-utils';
|
||||
import { createI18n } from 'vue-i18n';
|
||||
import ShippingAuditEventDetailDrawer from './ShippingAuditEventDetailDrawer.vue';
|
||||
import type { ShippingAuditEventDetail } from '@/features/admin/api/shipping-audit.api';
|
||||
|
||||
const messages = {
|
||||
'zh-CN': {
|
||||
admin: {
|
||||
close: '关闭',
|
||||
shippingAudit: {
|
||||
detailTitle: '审计详情',
|
||||
loading: '正在加载...',
|
||||
sensitiveRedacted: '敏感快照已按权限脱敏',
|
||||
diff: '前后差异',
|
||||
before: '变更前',
|
||||
after: '变更后',
|
||||
noDiff: '无可展示的白名单差异',
|
||||
eventHash: '事件哈希',
|
||||
previousEventHash: '前序哈希',
|
||||
columns: { event: '事件', actor: '操作者', run: 'Run', task: 'Task', result: '结果' },
|
||||
filters: {
|
||||
workflowId: 'Workflow',
|
||||
workflowItemId: 'Workflow Item',
|
||||
documentId: 'PDF/文档',
|
||||
reviewCaseNo: 'Case',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* 挂载详情抽屉。
|
||||
*/
|
||||
function mountDrawer(detail: ShippingAuditEventDetail | null, loading = false) {
|
||||
const i18n = createI18n({ legacy: false, locale: 'zh-CN', messages });
|
||||
return mount(ShippingAuditEventDetailDrawer, {
|
||||
props: { detail, loading },
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
}
|
||||
|
||||
describe('ShippingAuditEventDetailDrawer', () => {
|
||||
it('shows sensitive redaction banner when snapshots are trimmed', () => {
|
||||
const detail: ShippingAuditEventDetail = {
|
||||
id: 1,
|
||||
event_type: 'order_review_confirmed',
|
||||
aggregate_type: 'shipping_order_review_case',
|
||||
aggregate_id: 'SRC-1',
|
||||
actor_type: 'user',
|
||||
has_snapshots: true,
|
||||
sensitive_redacted: true,
|
||||
diff: [],
|
||||
};
|
||||
const wrapper = mountDrawer(detail);
|
||||
// 关键断言:无敏感读权限时展示脱敏提示。
|
||||
expect(wrapper.find('[data-testid="shipping-audit-sensitive-redacted"]').exists()).toBe(true);
|
||||
expect(wrapper.text()).toContain('敏感快照已按权限脱敏');
|
||||
});
|
||||
|
||||
it('renders whitelist diff rows', () => {
|
||||
const detail: ShippingAuditEventDetail = {
|
||||
id: 2,
|
||||
event_type: 'status_changed',
|
||||
aggregate_type: 'order_extraction_run',
|
||||
aggregate_id: 'SNER-1',
|
||||
actor_type: 'system',
|
||||
has_snapshots: true,
|
||||
sensitive_redacted: false,
|
||||
diff: [{ key: 'status', change: 'changed', before: 'queued', after: 'processing' }],
|
||||
};
|
||||
const wrapper = mountDrawer(detail);
|
||||
// 关键断言:Diff 仅展示白名单键变化。
|
||||
expect(wrapper.find('[data-testid="shipping-audit-diff-rows"]').text()).toContain('status');
|
||||
expect(wrapper.text()).toContain('queued');
|
||||
expect(wrapper.text()).toContain('processing');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,98 @@
|
||||
<!--
|
||||
features/admin/modules/shipping-audit/ShippingAuditEventDetailDrawer.vue
|
||||
用途:审计事件详情抽屉——元数据、敏感脱敏提示、白名单 Diff、哈希摘要。
|
||||
依赖:shipping-audit.api 类型、Vue I18n。
|
||||
逻辑:由 ShippingAuditCenterPage 传入 detail;关闭时 emit close;不自行拉接口。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import type { ShippingAuditEventDetail } from '@/features/admin/api/shipping-audit.api';
|
||||
|
||||
const props = defineProps<{
|
||||
detail: ShippingAuditEventDetail | null;
|
||||
loading?: boolean;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
close: [];
|
||||
}>();
|
||||
|
||||
const { t } = useI18n();
|
||||
|
||||
const open = computed(() => Boolean(props.detail || props.loading));
|
||||
|
||||
/**
|
||||
* 关闭抽屉。
|
||||
*/
|
||||
function onClose() {
|
||||
emit('close');
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div
|
||||
v-if="open"
|
||||
class="fixed inset-0 z-50 flex justify-end bg-overlay"
|
||||
data-testid="shipping-audit-detail-drawer"
|
||||
@click.self="onClose"
|
||||
>
|
||||
<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="onClose">{{ t('admin.close') }}</button>
|
||||
</div>
|
||||
<p v-if="loading" class="mt-6 text-muted">{{ t('admin.shippingAudit.loading') }}</p>
|
||||
<template v-else-if="detail">
|
||||
<p
|
||||
v-if="detail.sensitive_redacted"
|
||||
class="mt-4 rounded-lg border border-amber-200 bg-amber-50 px-3 py-2 text-xs text-amber-800"
|
||||
data-testid="shipping-audit-sensitive-redacted"
|
||||
>
|
||||
{{ t('admin.shippingAudit.sensitiveRedacted') }}
|
||||
</p>
|
||||
<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.filters.workflowId') }}</dt>
|
||||
<dd class="font-mono text-xs">{{ detail.workflow_id || '—' }}</dd>
|
||||
<dt>{{ t('admin.shippingAudit.filters.workflowItemId') }}</dt>
|
||||
<dd class="font-mono text-xs">{{ detail.workflow_item_id || '—' }}</dd>
|
||||
<dt>{{ t('admin.shippingAudit.columns.run') }}</dt>
|
||||
<dd class="font-mono text-xs">{{ detail.run_no || '—' }}</dd>
|
||||
<dt>{{ t('admin.shippingAudit.filters.documentId') }}</dt>
|
||||
<dd class="font-mono text-xs">{{ detail.document_id || '—' }}</dd>
|
||||
<dt>{{ t('admin.shippingAudit.filters.reviewCaseNo') }}</dt>
|
||||
<dd class="font-mono text-xs">{{ detail.review_case_no || '—' }}</dd>
|
||||
<dt>{{ t('admin.shippingAudit.columns.task') }}</dt>
|
||||
<dd class="font-mono text-xs">{{ detail.task_no || '—' }}</dd>
|
||||
<dt>{{ t('admin.shippingAudit.columns.result') }}</dt>
|
||||
<dd>{{ detail.result || '—' }}</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>
|
||||
<dt>{{ t('admin.shippingAudit.eventHash') }}</dt>
|
||||
<dd class="font-mono text-[10px] break-all">{{ detail.event_hash || '—' }}</dd>
|
||||
<dt>{{ t('admin.shippingAudit.previousEventHash') }}</dt>
|
||||
<dd class="font-mono text-[10px] break-all">{{ detail.previous_event_hash || '—' }}</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" data-testid="shipping-audit-diff-rows">
|
||||
<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>
|
||||
</template>
|
||||
+34
-20
@@ -48,7 +48,7 @@ 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);
|
||||
const pendingUpload = ref<{ intakeNo: string; filename: string; state: 'parsing' | 'failed'; errorCode?: string | null } | null>(null);
|
||||
let uploadPollingTimer: number | null = null;
|
||||
let availableSamplesController: AbortController | null = null;
|
||||
let availableSamplesTimeout: number | null = null;
|
||||
@@ -86,12 +86,16 @@ const failureDetails = computed(() => (suite.value?.latest_run?.failure_codes ||
|
||||
return { code, message: t('admin.shippingOrderProfiles.blindTest.failure.unknown', { sample: sampleName }) };
|
||||
}));
|
||||
/** 读取订单字段复核状态;候选加载完成时会初始化,默认值仅用于渲染过程中的安全兜底。 */
|
||||
function orderFieldReview(fieldCode: string): { correct: boolean; value: string } {
|
||||
return orderFieldReviews.value[fieldCode] || { correct: true, value: '' };
|
||||
function orderFieldReview(fieldKey: string): { correct: boolean; value: string } {
|
||||
return orderFieldReviews.value[fieldKey] || { correct: true, value: '' };
|
||||
}
|
||||
/** 更新单个订单字段的人工复核状态,保持其他字段复核结果不被输入事件覆盖。 */
|
||||
function updateOrderFieldReview(fieldCode: string, patch: Partial<{ correct: boolean; value: string }>): void {
|
||||
orderFieldReviews.value[fieldCode] = { ...orderFieldReview(fieldCode), ...patch };
|
||||
function updateOrderFieldReview(fieldKey: string, patch: Partial<{ correct: boolean; value: string }>): void {
|
||||
orderFieldReviews.value[fieldKey] = { ...orderFieldReview(fieldKey), ...patch };
|
||||
}
|
||||
/** 复核与服务端使用同一个 scope:field_code 键,避免同名 Header/Line 字段覆盖。 */
|
||||
function orderFieldKey(field: { scope: 'header'; field_code: string }): string {
|
||||
return `${field.scope}:${field.field_code}`;
|
||||
}
|
||||
|
||||
/** 将统一业务错误转换为安全的界面提示,不暴露盲测真值或内部布局数据。 */
|
||||
@@ -99,6 +103,15 @@ function report(error: unknown): void {
|
||||
const code = error instanceof BusinessError ? error.code : '';
|
||||
message.error(code ? t(`errors.${code}`, code) : t('admin.orderProfileValidation.failed'));
|
||||
}
|
||||
/** 将模板布局失败码转成盲测页可执行的提示,不向管理员回显内部快照数据。 */
|
||||
function sampleFailureMessage(errorCode?: string | null): string {
|
||||
const key = errorCode === 'mineru_cell_coordinates_missing'
|
||||
? 'sampleLayoutCoordinatesMissing'
|
||||
: errorCode === 'shipping_document_layout_snapshot_size_exceeded'
|
||||
? 'sampleLayoutSnapshotTooLarge'
|
||||
: 'sampleParseFailed';
|
||||
return t(`admin.shippingOrderProfiles.wizard.${key}`);
|
||||
}
|
||||
|
||||
/** 创建或读取当前草稿 checksum 对应的盲测集;候选样本按需加载,避免进入页面时扫描全部历史样本。 */
|
||||
async function loadSuite(): Promise<void> {
|
||||
@@ -174,7 +187,9 @@ async function pollUploadedSample(intakeNo: string): Promise<void> {
|
||||
return;
|
||||
}
|
||||
if (['failed', 'error'].includes(result.parse_status)) {
|
||||
pendingUpload.value = { intakeNo, filename: pendingUpload.value?.filename || '', state: 'failed' };
|
||||
pendingUpload.value = {
|
||||
intakeNo, filename: pendingUpload.value?.filename || '', state: 'failed', errorCode: result.error_code,
|
||||
};
|
||||
return;
|
||||
}
|
||||
uploadPollingTimer = window.setTimeout(() => void pollUploadedSample(intakeNo), 1500);
|
||||
@@ -215,7 +230,7 @@ async function previewSample(): Promise<void> {
|
||||
candidate.value = await previewOrderProfileBlindTestCandidate(suite.value.id, selectedSample.value);
|
||||
rowReviews.value = candidate.value.rows.map(() => ({ correct: true, correction: '' }));
|
||||
orderFieldReviews.value = Object.fromEntries(candidate.value.order_fields.map((field) => [
|
||||
field.field_code,
|
||||
orderFieldKey(field),
|
||||
{ correct: true, value: field.value == null ? '' : String(field.value) },
|
||||
]));
|
||||
} catch (error) {
|
||||
@@ -256,8 +271,8 @@ async function confirmReview(): Promise<void> {
|
||||
document_id: candidate.value.document_id,
|
||||
table_id: candidate.value.table_id,
|
||||
row_reviews: reviews,
|
||||
order_field_reviews: Object.fromEntries(Object.entries(orderFieldReviews.value).map(([fieldCode, review]) => [
|
||||
fieldCode,
|
||||
order_field_reviews: Object.fromEntries(Object.entries(orderFieldReviews.value).map(([fieldKey, review]) => [
|
||||
fieldKey,
|
||||
review.correct ? { correct: true } : { correct: false, value: review.value },
|
||||
])),
|
||||
});
|
||||
@@ -356,11 +371,10 @@ onBeforeUnmount(() => {
|
||||
</section>
|
||||
|
||||
<section v-if="suite.status === 'draft'" class="card">
|
||||
<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"><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>
|
||||
<div class="sample-heading"><h2>{{ t('admin.shippingOrderProfiles.blindTest.selectIndependentSample') }}</h2><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.blindTest.uploadSample') }}</span></label></div>
|
||||
<p v-if="availableSamplesLoaded && !availableSamples.length">{{ t('admin.shippingOrderProfiles.blindTest.noIndependentSamples') }}</p>
|
||||
<div class="sample-picker"><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.previewAndReview') }}</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') : sampleFailureMessage(pendingUpload.errorCode) }}</p>
|
||||
</section>
|
||||
|
||||
<section v-if="candidate" class="card candidate-card">
|
||||
@@ -373,10 +387,10 @@ onBeforeUnmount(() => {
|
||||
<textarea v-if="!rowReviews[index].correct" v-model="rowReviews[index].correction" class="input-field" :placeholder="t('admin.shippingOrderProfiles.blindTest.expectedRowsPlaceholder')" />
|
||||
</template>
|
||||
</article>
|
||||
<article v-for="field in candidate.order_fields" :key="field.field_code" class="review-item">
|
||||
<article v-for="field in candidate.order_fields" :key="field.field_id" class="review-item">
|
||||
<h3>{{ field.field_code }}</h3><code>{{ field.value ?? t('admin.shippingOrderProfiles.emptyCandidateValue') }}</code>
|
||||
<label><input :checked="orderFieldReview(field.field_code).correct" type="checkbox" @change="updateOrderFieldReview(field.field_code, { correct: ($event.target as HTMLInputElement).checked })">{{ t('admin.shippingOrderProfiles.blindTest.correct') }}</label>
|
||||
<input v-if="!orderFieldReview(field.field_code).correct" class="input-field" :value="orderFieldReview(field.field_code).value" :placeholder="t('admin.shippingOrderProfiles.blindTest.correctedValue')" @input="updateOrderFieldReview(field.field_code, { value: ($event.target as HTMLInputElement).value })">
|
||||
<label><input :checked="orderFieldReview(orderFieldKey(field)).correct" type="checkbox" @change="updateOrderFieldReview(orderFieldKey(field), { correct: ($event.target as HTMLInputElement).checked })">{{ t('admin.shippingOrderProfiles.blindTest.correct') }}</label>
|
||||
<input v-if="!orderFieldReview(orderFieldKey(field)).correct" class="input-field" :value="orderFieldReview(orderFieldKey(field)).value" :placeholder="t('admin.shippingOrderProfiles.blindTest.correctedValue')" @input="updateOrderFieldReview(orderFieldKey(field), { value: ($event.target as HTMLInputElement).value })">
|
||||
</article>
|
||||
<button type="button" class="btn-primary" :disabled="working || !candidate.rows.length" @click="confirmReview">{{ t('admin.shippingOrderProfiles.blindTest.confirmReview') }}</button>
|
||||
</section>
|
||||
@@ -390,16 +404,16 @@ onBeforeUnmount(() => {
|
||||
|
||||
<style scoped>
|
||||
.blind-test-page { padding: 24px; color: var(--text-secondary); }
|
||||
header, .suite-summary, .execution, .actions, .sample-picker, li { display: flex; align-items: center; justify-content: space-between; gap: 12px; }
|
||||
header, .suite-summary, .execution, .actions, .sample-heading, .sample-picker, li { display: flex; align-items: center; justify-content: space-between; gap: 12px; }
|
||||
header { align-items: flex-start; margin-bottom: 24px; } h1, h2, h3, p { margin: 0; } h2 { font-size: 16px; } h3 { font-size: 14px; } p:not(.section-desc) { margin-top: 6px; color: var(--text-muted); font-size: 13px; line-height: 1.5; }
|
||||
.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; }
|
||||
.sample-heading { align-items: center; }.sample-picker { justify-content: flex-start; }.sample-picker .select-field { flex: 1; min-width: 0; } .sample-picker button, .upload-sample { flex: 0 0 auto; white-space: nowrap; } .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; }
|
||||
.failure-details { border-color: var(--status-error-border); background: var(--status-error-bg); }.failure-details h2 { color: var(--status-error-fg); }.failure-details li { display: grid; gap: 4px; color: var(--status-error-fg); }.failure-details code { color: var(--status-error-fg); }
|
||||
.training-required { color: var(--status-warning-fg) !important; font-weight: 600; }
|
||||
@media (max-width: 700px) { header, .suite-summary, .execution, .sample-picker { align-items: stretch; flex-direction: column; } .sample-picker .select-field { min-width: 0; width: 100%; } }
|
||||
@media (max-width: 700px) { header, .suite-summary, .execution, .sample-heading, .sample-picker { align-items: stretch; flex-direction: column; } .sample-picker .select-field { min-width: 0; width: 100%; } }
|
||||
</style>
|
||||
+22
-4
@@ -5,7 +5,7 @@
|
||||
逻辑:首步仅收集业务名称和 Schema;最后一步由服务端生成系统编码并原子创建草稿、样本绑定、Revision 与 Lease。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, reactive, ref, watch } from 'vue';
|
||||
import { computed, onBeforeUnmount, onMounted, reactive, ref, watch } from 'vue';
|
||||
import { useRouter } from 'vue-router';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { ArrowLeft, ArrowRight, Check, FileText, Layers3, Sparkles } from 'lucide-vue-next';
|
||||
@@ -33,6 +33,7 @@ const identity = reactive<Identity>({ displayName: '', schemaId: 0 });
|
||||
const documentId = ref(0);
|
||||
const tableId = ref('');
|
||||
const browserSessionId = crypto.randomUUID();
|
||||
let sampleRefreshTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
const publishedSchemas = computed(() => schemas.value.filter((item) => item.status === 'published'));
|
||||
const canNext = computed(() => step.value === 1
|
||||
? Boolean(identity.displayName.trim() && identity.schemaId)
|
||||
@@ -59,10 +60,22 @@ async function loadContext(): Promise<void> {
|
||||
message.error(error instanceof BusinessError ? error.message : t('admin.shippingOrderProfiles.wizard.loadFailed'));
|
||||
}
|
||||
}
|
||||
/** 刷新上传后的样本库;样本解析未完成时只会留在样本库,不能产出半成品模板。 */
|
||||
async function refreshSamples(): Promise<void> {
|
||||
/** 刷新上传后的样本库;轮询失败静默处理,避免短暂网络异常持续弹出提示。 */
|
||||
async function refreshSamples(showError = true): Promise<void> {
|
||||
try { samples.value = await listOrderProfileSamples(); }
|
||||
catch { message.error(t('admin.shippingOrderProfiles.wizard.loadFailed')); }
|
||||
catch { if (showError) message.error(t('admin.shippingOrderProfiles.wizard.loadFailed')); }
|
||||
}
|
||||
/** 仅在第二步保持已解析文档列表为最新,离开步骤后立即停止。 */
|
||||
function stopSampleRefresh(): void {
|
||||
if (sampleRefreshTimer !== null) clearTimeout(sampleRefreshTimer);
|
||||
sampleRefreshTimer = null;
|
||||
}
|
||||
function scheduleSampleRefresh(): void {
|
||||
stopSampleRefresh();
|
||||
if (step.value !== 2) return;
|
||||
void refreshSamples(false).finally(() => {
|
||||
if (step.value === 2) sampleRefreshTimer = setTimeout(scheduleSampleRefresh, 2000);
|
||||
});
|
||||
}
|
||||
/** 加载选定样本的可用表格;单表场景由下一步直接作为订单明细表。 */
|
||||
async function loadTables(id: number): Promise<void> {
|
||||
@@ -75,6 +88,10 @@ watch(documentId, async (id) => {
|
||||
if (!id) return;
|
||||
await loadTables(id);
|
||||
});
|
||||
watch(step, (currentStep) => {
|
||||
if (currentStep === 2) scheduleSampleRefresh();
|
||||
else stopSampleRefresh();
|
||||
});
|
||||
/** 前进仅校验当前步骤;单表直接创建,多表才要求管理员确认订单明细表。 */
|
||||
async function next(): Promise<void> {
|
||||
if (!canNext.value) {
|
||||
@@ -117,6 +134,7 @@ async function finish(enterEditor: boolean): Promise<void> {
|
||||
} finally { saving.value = false; }
|
||||
}
|
||||
onMounted(loadContext);
|
||||
onBeforeUnmount(stopSampleRefresh);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
|
||||
+221
-82
@@ -1,8 +1,9 @@
|
||||
<!--
|
||||
features/admin/modules/shipping-order-document-profiles/OrderProfileEditorPage.vue
|
||||
用途:订单坐标 Profile v2 的独立草稿标注编辑页。
|
||||
依赖:受控预览 API、Schema API、DocumentCanvas、IssuePanel。
|
||||
逻辑:仅编辑由向导创建的草稿;撤销/重做、自动保存和建议决定均受当前标签租约保护。
|
||||
依赖:受控预览 API、Schema API、DocumentCanvas、IssuePanel、shippingOrderField.utils。
|
||||
逻辑:仅编辑由向导创建的草稿;起行锚点默认 customer_po_line_no(内部项次 line_no 亦可绑定);
|
||||
撤销/重做、自动保存和建议决定均受当前标签租约保护。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import {
|
||||
@@ -59,7 +60,10 @@ import {
|
||||
suggestFieldCodeFromHeaders,
|
||||
toOrderProfileAnchorId,
|
||||
buildOrderProfileRecognitionResults,
|
||||
groupUniqueOrderProfileLineFields,
|
||||
isOrderProfileAnchorRelativeCandidate,
|
||||
normalizeOrderProfileRelativeRegion,
|
||||
toOrderProfileAnchorRelativeRegion,
|
||||
} from "./orderProfileForm.utils";
|
||||
|
||||
const { t } = useI18n();
|
||||
@@ -94,6 +98,7 @@ const sampleTables = ref<
|
||||
const preview = ref<CoordinateReconstructionPreview | null>(null);
|
||||
const orderFieldValuePreviews = ref<OrderFieldValuePreview[]>([]);
|
||||
const orderFieldValueState = ref<'idle' | 'loading' | 'ready' | 'failed'>('idle');
|
||||
const orderFieldValueError = ref('');
|
||||
const previewError = ref("");
|
||||
const headerSuggestions = ref<
|
||||
Array<{
|
||||
@@ -141,6 +146,7 @@ let previewTimer: number | null = null;
|
||||
let orderFieldValueTimer: number | null = null;
|
||||
let pendingGestureId: string | null = null;
|
||||
let pendingFormEdit: OrderProfileCanvasRegion[] | null = null;
|
||||
let restoringProfile = false;
|
||||
|
||||
const form = reactive({
|
||||
profileCode: "",
|
||||
@@ -169,9 +175,22 @@ const lineFields = computed<ShippingOrderFieldConfig[]>(
|
||||
(item) =>
|
||||
item.enabled !== false &&
|
||||
item.scope === "line" &&
|
||||
item.field_code != null &&
|
||||
item.allowed_sources?.includes("pdf_coordinate"),
|
||||
) || [],
|
||||
);
|
||||
/** 根据当前主行映射自动选择起行字段,优先客户 PO 行号,避免暴露内部配置。 */
|
||||
const resolveLineStartFieldCode = (mainLineFieldCodes: Set<string>): string => {
|
||||
const availableFieldCodes = new Set(
|
||||
lineFields.value.map((field) => field.field_code).filter(Boolean),
|
||||
);
|
||||
const validMainLineCodes = [...mainLineFieldCodes].filter((fieldCode) =>
|
||||
availableFieldCodes.has(fieldCode),
|
||||
);
|
||||
return validMainLineCodes.includes("customer_po_line_no")
|
||||
? "customer_po_line_no"
|
||||
: validMainLineCodes[0] || "customer_po_line_no";
|
||||
};
|
||||
/** 订单单头区域只能绑定 Schema 中声明为 header 的坐标字段。 */
|
||||
const headerFields = computed<ShippingOrderFieldConfig[]>(
|
||||
() =>
|
||||
@@ -193,7 +212,7 @@ const selectedRegion = computed(
|
||||
/** 当前样本值只能来自本次按画布坐标回读的结果,禁止回退到旧的自动建议缓存。 */
|
||||
const selectedRegionSampleValue = computed(() => {
|
||||
const region = selectedRegion.value;
|
||||
if (!region || !['order_field', 'header_field'].includes(region.kind)) return null;
|
||||
if (!region || region.kind !== 'order_field') 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;
|
||||
@@ -201,7 +220,7 @@ const selectedRegionSampleValue = computed(() => {
|
||||
/** 右侧选区值与画布标签共享同一个读取状态,禁止以旧建议值回退。 */
|
||||
const selectedRegionSampleDisplay = computed(() => {
|
||||
if (orderFieldValueState.value === 'loading') return t('admin.shippingOrderProfiles.workbench.orderFieldValueReading');
|
||||
if (orderFieldValueState.value === 'failed') return t('admin.shippingOrderProfiles.workbench.orderFieldValueFailed');
|
||||
if (orderFieldValueState.value === 'failed') return orderFieldValueError.value || t('admin.shippingOrderProfiles.workbench.orderFieldValueFailed');
|
||||
return selectedRegionSampleValue.value || t('admin.shippingOrderProfiles.workbench.sampleValueUnavailable');
|
||||
});
|
||||
const orderFieldValues = computed<Record<string, string | null>>(() => Object.fromEntries(
|
||||
@@ -311,6 +330,23 @@ const issues = computed(() => {
|
||||
if (duplicateOrderFieldCodes.length) {
|
||||
result.push(`订单字段 ${[...new Set(duplicateOrderFieldCodes)].join(", ")} 已在其他区域绑定;请编辑原区域或先解除原绑定。`);
|
||||
}
|
||||
const pageNos = [...new Set(regions.value.filter((item) => item.kind === "line").map((item) => item.pageNo))];
|
||||
for (const regionPageNo of pageNos) {
|
||||
const pageLines = regions.value
|
||||
.filter((item) => item.pageNo === regionPageNo && item.kind === "line")
|
||||
.sort((left, right) => left.region.y0 - right.region.y0);
|
||||
const mainLine = pageLines[0];
|
||||
if (!mainLine) continue;
|
||||
const mainLineFieldCodes = regions.value
|
||||
.filter((item) => item.kind === "field" && item.parentId === mainLine.id && item.fieldCode)
|
||||
.map((item) => item.fieldCode!);
|
||||
if (!mainLineFieldCodes.length) continue;
|
||||
const startFieldCode = resolveLineStartFieldCode(new Set(mainLineFieldCodes));
|
||||
if (!mainLineFieldCodes.includes(startFieldCode)) {
|
||||
result.push(t("admin.shippingOrderProfiles.workbench.issues.lineStartAnchorRequired"));
|
||||
break;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
});
|
||||
/** 将 API 业务错误转换为工作台消息,避免内部错误详情出现在页面。 */
|
||||
@@ -341,6 +377,18 @@ const checkpoint = () => {
|
||||
markLocalChange();
|
||||
scheduleAutosave();
|
||||
};
|
||||
/**
|
||||
* 为订单字段及其标签锚点分配同一命名空间内的唯一序号。
|
||||
* 直接框选值和“标签 + 值”两种标注方式会共同写入 order_field_layouts,不能各自从 1 编号。
|
||||
*/
|
||||
const nextOrderFieldSequence = (targetPageNo: number): number => {
|
||||
const occupiedIds = new Set(
|
||||
regions.value.flatMap((region) => [region.id, region.orderFieldId].filter(Boolean)),
|
||||
);
|
||||
let sequence = 1;
|
||||
while (occupiedIds.has(`order_field_${targetPageNo}_${sequence}`)) sequence += 1;
|
||||
return sequence;
|
||||
};
|
||||
/** 记录输入控件编辑前的状态;只有值实际变化时才写入撤销历史。 */
|
||||
const beginFormEdit = () => {
|
||||
pendingFormEdit = snapshot();
|
||||
@@ -356,6 +404,17 @@ const finishFormEdit = () => {
|
||||
scheduleOrderFieldSuggestionValues();
|
||||
scheduleAutosave();
|
||||
};
|
||||
/**
|
||||
* 同步订单字段的可见标签与其 Schema 绑定,避免字段已改为送货地址而画布仍显示账款地址。
|
||||
* 表头/明细列保留原始文档文字,只有订单字段使用 Schema 业务名称作为稳定展示标签。
|
||||
*/
|
||||
const finishFieldBindingEdit = () => {
|
||||
const target = selectedRegion.value;
|
||||
if (target?.kind === 'order_field' && target.fieldCode) {
|
||||
target.label = schemaFieldLabel(target.fieldCode);
|
||||
}
|
||||
finishFormEdit();
|
||||
};
|
||||
/** 撤销上一项区域、字段或删除操作。 */
|
||||
const undo = () => {
|
||||
const prior = history.value.pop();
|
||||
@@ -439,7 +498,9 @@ const addRegion = (
|
||||
y1: 0.35 + count * 0.06,
|
||||
});
|
||||
// layout_id is persisted, so generate a contract-safe and non-reused identifier rather than using a timestamp.
|
||||
let sequence = count;
|
||||
let sequence = effectiveKind === 'order_field'
|
||||
? nextOrderFieldSequence(pageNo.value)
|
||||
: count;
|
||||
while (
|
||||
regions.value.some(
|
||||
(entry) => entry.id === `${effectiveKind}_${pageNo.value}_${sequence}`,
|
||||
@@ -554,7 +615,7 @@ const createDrawnRegion = async (region: OrderProfileRelativeRegion) => {
|
||||
}
|
||||
history.value.push(snapshot());
|
||||
future.value = [];
|
||||
const sequence = pageRegions.value.filter((item) => item.kind === 'order_anchor').length + 1;
|
||||
const sequence = nextOrderFieldSequence(pageNo.value);
|
||||
const orderFieldId = `order_field_${pageNo.value}_${sequence}`;
|
||||
const anchor: OrderProfileCanvasRegion = {
|
||||
id: `${orderFieldId}_anchor`, kind, label, region, orderFieldId, pageNo: pageNo.value,
|
||||
@@ -576,7 +637,10 @@ const createDrawnRegion = async (region: OrderProfileRelativeRegion) => {
|
||||
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,
|
||||
// The Schema selector uses null for its explicit "unbound" option. Do not
|
||||
// leave this undefined, otherwise a newly drawn value box can retain the
|
||||
// previous selected address field in the browser control.
|
||||
fieldCode: null, orderFieldId: anchor.orderFieldId, valueMode: 'single_line', suggestedValue: value, pageNo: pageNo.value,
|
||||
};
|
||||
regions.value.push(valueRegion);
|
||||
pendingOrderFieldAnchor.value = null;
|
||||
@@ -685,47 +749,39 @@ const updateRegion = (id: string, region: OrderProfileRelativeRegion) => {
|
||||
};
|
||||
/** 将区域编辑器转换为严格 v2 定义;浏览器只发送白名单 field_code/解析器和相对区域。 */
|
||||
const definition = () => {
|
||||
// 自动建议和历史草稿可能带有浮点边界误差;保存前统一裁剪,保证绝对值框合法。
|
||||
regions.value = regions.value.map((item) => ({
|
||||
// Build a normalized payload without mutating canvas state. Preview requests must
|
||||
// not turn an unsaved relative value box into a different local annotation.
|
||||
const normalizedRegions = regions.value.map((item) => ({
|
||||
...item,
|
||||
region: normalizedCanvasRegion(item.region) || item.region,
|
||||
}));
|
||||
const tableRegions = [...new Set(
|
||||
regions.value
|
||||
normalizedRegions
|
||||
.filter((item) => item.kind === "line" || item.kind === "header_field")
|
||||
.map((item) => item.pageNo),
|
||||
)]
|
||||
.sort((left, right) => left - right)
|
||||
.map((regionPageNo) => {
|
||||
const pageItems = regions.value.filter(
|
||||
const pageItems = normalizedRegions.filter(
|
||||
(item) => item.pageNo === regionPageNo,
|
||||
);
|
||||
const lineRegions = pageItems.filter((item) => item.kind === "line");
|
||||
const boundLineFieldRegionIds = new Set<string>();
|
||||
const boundLineFieldCodes = new Set<string>();
|
||||
const groupedLineFields = groupUniqueOrderProfileLineFields(
|
||||
pageItems,
|
||||
lineRegions.map((item) => item.id),
|
||||
);
|
||||
const boundLineFieldRegionIds = groupedLineFields.boundRegionIds;
|
||||
/** 将已分组的画布字段转换为 v2 字段区域;重复读取不会改变后续保存内容。 */
|
||||
const fieldRegionsFor = (layoutId: string): OrderProfileFieldRegion[] =>
|
||||
pageItems
|
||||
.filter(
|
||||
(item) =>
|
||||
item.kind === "field" &&
|
||||
item.parentId === layoutId &&
|
||||
item.fieldCode &&
|
||||
!boundLineFieldCodes.has(item.fieldCode),
|
||||
)
|
||||
.map((item) => {
|
||||
// The v2 contract assigns each Schema line field one coordinate source.
|
||||
// Continuation-row frames remain visible, but cannot duplicate that binding.
|
||||
boundLineFieldCodes.add(item.fieldCode!);
|
||||
boundLineFieldRegionIds.add(item.id);
|
||||
return {
|
||||
(groupedLineFields.fieldsByLayout.get(layoutId) || []).map((item) => ({
|
||||
field_id: "",
|
||||
field_code: item.fieldCode!,
|
||||
scope: "line" as const,
|
||||
region: item.region,
|
||||
extractor_key: "direct",
|
||||
allowed_sources: ["pdf_coordinate"],
|
||||
minimum_evidence_level: "coordinate",
|
||||
};
|
||||
});
|
||||
}));
|
||||
const headerLayouts = pageItems
|
||||
.filter((item) => item.kind === "header_field" && item.parentId)
|
||||
.reduce<string[]>((layoutIds, item) => {
|
||||
@@ -750,6 +806,7 @@ const definition = () => {
|
||||
.map((field) => ({
|
||||
field_id: "",
|
||||
field_code: field.fieldCode!,
|
||||
scope: "line" as const,
|
||||
region: field.region,
|
||||
extractor_key: "direct" as const,
|
||||
allowed_sources: ["pdf_coordinate" as const],
|
||||
@@ -769,11 +826,18 @@ const definition = () => {
|
||||
y1: Math.max(...layoutRegions.map((item) => item.region.y1)),
|
||||
}
|
||||
: { x0: 0.1, y0: 0.25, x1: 0.9, y1: 0.85 };
|
||||
const firstLineRegion = lineRegions[0];
|
||||
const mainLineFieldCodes = new Set(
|
||||
firstLineRegion
|
||||
? fieldRegionsFor(firstLineRegion.id).map((item) => item.field_code)
|
||||
: [],
|
||||
);
|
||||
return {
|
||||
region_id: `main_lines_page_${regionPageNo}`,
|
||||
page_scope: "exact_page" as const,
|
||||
page_no: regionPageNo,
|
||||
region: tableRegion,
|
||||
line_start_field_code: resolveLineStartFieldCode(mainLineFieldCodes),
|
||||
header_layouts: headerLayouts,
|
||||
line_layouts: lineRegions.map((line, index) => {
|
||||
const fieldRegions = fieldRegionsFor(line.id);
|
||||
@@ -821,19 +885,25 @@ const definition = () => {
|
||||
minimum_margin: documentMatch.minimumMargin,
|
||||
},
|
||||
table_regions: tableRegions,
|
||||
order_field_layouts: regions.value
|
||||
order_field_layouts: normalizedRegions
|
||||
.filter((item) => item.kind === "order_field" && item.fieldCode)
|
||||
.map((item) => {
|
||||
const anchor = regions.value.find(
|
||||
const anchor = normalizedRegions.find(
|
||||
(candidate) =>
|
||||
candidate.kind === "order_anchor" &&
|
||||
(candidate.id === item.parentId || candidate.orderFieldId === item.orderFieldId),
|
||||
);
|
||||
const anchorId = toOrderProfileAnchorId(anchor);
|
||||
const isAnchorRelative = Boolean(anchor && anchorId && ["right_of_anchor", "below_anchor"].includes(item.valueMode || "")
|
||||
&& isOrderProfileAnchorRelativeCandidate(item.region, anchor.region));
|
||||
const relativeValueRegion = isAnchorRelative && anchor
|
||||
? toOrderProfileAnchorRelativeRegion(item.region, anchor.region)
|
||||
: null;
|
||||
return {
|
||||
layout_id: item.orderFieldId || item.id,
|
||||
field_id: "",
|
||||
field_code: item.fieldCode!,
|
||||
scope: "header" as const,
|
||||
page_scope: "exact_page" as const,
|
||||
page_no: item.pageNo,
|
||||
// Historical unbound labels can lack a usable canvas ID. In that case,
|
||||
@@ -845,12 +915,13 @@ const definition = () => {
|
||||
aliases: [],
|
||||
match_mode: "exact" as const,
|
||||
region: anchor.region,
|
||||
position_locked: !isAnchorRelative,
|
||||
minimum_evidence_level: "coordinate" as const,
|
||||
}
|
||||
: null,
|
||||
// 画布框是读取边界;锚点只用于定位字段,不能再参与值框二次投影。
|
||||
value_region: null,
|
||||
absolute_value_region: anchor && anchorId ? item.region : null,
|
||||
value_region: relativeValueRegion,
|
||||
absolute_value_region: anchor && anchorId && !relativeValueRegion ? item.region : null,
|
||||
fallback_value_region: anchor && anchorId ? null : item.region,
|
||||
value_mode: item.valueMode || "single_line",
|
||||
stop_anchors:
|
||||
@@ -868,7 +939,7 @@ const definition = () => {
|
||||
minimum_evidence_level: item.evidenceSource === "ocr_coordinate" ? "ocr_coordinate" as const : "coordinate" as const,
|
||||
};
|
||||
}),
|
||||
draft_unbound_order_field_layouts: regions.value
|
||||
draft_unbound_order_field_layouts: normalizedRegions
|
||||
.filter(
|
||||
(item) =>
|
||||
item.kind === "order_field" &&
|
||||
@@ -876,11 +947,16 @@ const definition = () => {
|
||||
)
|
||||
.map((item) => {
|
||||
const layoutId = item.orderFieldId || item.id.replace(/^unbound-/, "");
|
||||
const anchor = regions.value.find(
|
||||
const anchor = normalizedRegions.find(
|
||||
(candidate) =>
|
||||
candidate.kind === "order_anchor" &&
|
||||
(candidate.id === item.parentId || candidate.orderFieldId === layoutId),
|
||||
);
|
||||
const isAnchorRelative = Boolean(anchor && ["right_of_anchor", "below_anchor"].includes(item.valueMode || "")
|
||||
&& isOrderProfileAnchorRelativeCandidate(item.region, anchor.region));
|
||||
const relativeValueRegion = isAnchorRelative && anchor
|
||||
? toOrderProfileAnchorRelativeRegion(item.region, anchor.region)
|
||||
: null;
|
||||
return {
|
||||
layout_id: layoutId,
|
||||
label: item.label,
|
||||
@@ -893,11 +969,12 @@ const definition = () => {
|
||||
aliases: [],
|
||||
match_mode: "exact" as const,
|
||||
region: anchor.region,
|
||||
position_locked: !isAnchorRelative,
|
||||
minimum_evidence_level: "coordinate" as const,
|
||||
}
|
||||
: null,
|
||||
value_region: null,
|
||||
absolute_value_region: anchor ? item.region : null,
|
||||
value_region: relativeValueRegion,
|
||||
absolute_value_region: anchor && !relativeValueRegion ? item.region : null,
|
||||
fallback_value_region: anchor ? null : item.region,
|
||||
value_mode: item.valueMode || "single_line",
|
||||
stop_anchors:
|
||||
@@ -972,7 +1049,13 @@ const save = async (automatic = false) => {
|
||||
} else {
|
||||
fail(error);
|
||||
}
|
||||
if (automatic && autosaveFailures < 3 && navigator.onLine) {
|
||||
// A definition validation error cannot recover without an administrator edit.
|
||||
// Retrying it only produces repeated toast notifications for the same canvas state.
|
||||
const retryable = !(error instanceof BusinessError && [
|
||||
'SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID',
|
||||
'SHIPPING.ORDER_DOCUMENT_PROFILE_FIELD_INVALID',
|
||||
].includes(error.code));
|
||||
if (automatic && retryable && autosaveFailures < 3 && navigator.onLine) {
|
||||
if (retryTimer) window.clearTimeout(retryTimer);
|
||||
retryTimer = window.setTimeout(() => void save(true), 1500 * autosaveFailures);
|
||||
}
|
||||
@@ -1048,6 +1131,7 @@ const suggestRegions = async () => {
|
||||
parentId: headerId,
|
||||
label: field.field_code || field.text || t("admin.shippingOrderProfiles.workbench.unboundColumn", { count: fieldIndex + 1 }),
|
||||
region: field.region,
|
||||
// 表头绑定表达列语义;运行期仅从明细行字段框读取实际业务值。
|
||||
fieldCode: field.field_code || null,
|
||||
pageNo: pageNo.value,
|
||||
});
|
||||
@@ -1157,7 +1241,10 @@ const suggestRegions = async () => {
|
||||
suggestingRegions.value = false;
|
||||
}
|
||||
};
|
||||
/** 接受、调整接受或拒绝当前待确认建议;重建议不会覆盖当前人工区域。 */
|
||||
/**
|
||||
* 接受、调整接受或拒绝当前待确认建议;重建议替换同页旧的自动表格区域,保留人工区域。
|
||||
* 自动区域 ID 使用稳定的 header_/line_ 前缀,借此避免重复自动标记叠加为无效 Profile。
|
||||
*/
|
||||
const decidePendingSuggestion = async (decision: 'accepted' | 'accepted_adjusted' | 'rejected') => {
|
||||
if (!pendingSuggestion.value || !active.value || !editLeaseToken.value) return;
|
||||
const item = pendingSuggestion.value;
|
||||
@@ -1175,8 +1262,39 @@ const decidePendingSuggestion = async (decision: 'accepted' | 'accepted_adjusted
|
||||
});
|
||||
if (decision !== 'rejected') {
|
||||
checkpoint();
|
||||
const suggestionPages = new Set(item.regions.map((region) => region.pageNo));
|
||||
const isReplaceableAutoTableRegion = (region: OrderProfileCanvasRegion) =>
|
||||
suggestionPages.has(region.pageNo) &&
|
||||
(region.id.startsWith(`header_${region.pageNo}_`) ||
|
||||
region.id.startsWith(`line_${region.pageNo}_`));
|
||||
// A new suggestion is a complete table layout for its page. Replace its
|
||||
// previous generated header/line frames before appending it, otherwise a
|
||||
// changed suggestion ID leaves geometrically overlapping regions behind.
|
||||
regions.value = regions.value.filter(
|
||||
(region) => !isReplaceableAutoTableRegion(region),
|
||||
);
|
||||
const existingIds = new Set(regions.value.map((region) => region.id));
|
||||
const acceptedRegions = item.regions.filter((region) => !existingIds.has(region.id)).map((region) => ({ ...region, fieldCode: decision === 'accepted_adjusted' && region.id === firstSuggestedField?.id ? replacementFieldCode : region.fieldCode }));
|
||||
const suggestedLines = acceptedRegions.filter((region) => region.kind === 'line');
|
||||
if (suggestedLines.length) {
|
||||
const fieldParentIds = new Set(
|
||||
regions.value
|
||||
.filter((region) => region.kind === 'field' && region.parentId)
|
||||
.map((region) => region.parentId!),
|
||||
);
|
||||
// The wizard starts with one full-table empty line purely to make a legal
|
||||
// draft. Once coordinate suggestion provides real rows, keeping it makes
|
||||
// the v2 non-overlap contract unsavable.
|
||||
regions.value = regions.value.filter((region) => !(
|
||||
region.kind === 'line' &&
|
||||
!fieldParentIds.has(region.id) &&
|
||||
suggestedLines.some((suggested) =>
|
||||
region.pageNo === suggested.pageNo &&
|
||||
region.region.x0 <= suggested.region.x0 && region.region.y0 <= suggested.region.y0 &&
|
||||
region.region.x1 >= suggested.region.x1 && region.region.y1 >= suggested.region.y1
|
||||
)
|
||||
));
|
||||
}
|
||||
regions.value.push(...acceptedRegions);
|
||||
selectedId.value = item.regions.find((region) => region.fieldCode)?.id || item.regions[0]?.id || null;
|
||||
}
|
||||
@@ -1193,6 +1311,7 @@ let orderFieldValueRequest = 0;
|
||||
const clearOrderFieldValuePreview = (state: 'idle' | 'loading' | 'failed') => {
|
||||
orderFieldValuePreviews.value = [];
|
||||
orderFieldValueState.value = state;
|
||||
orderFieldValueError.value = '';
|
||||
};
|
||||
/** 根据当前画布定义读取订单字段;过期请求不得覆盖更新后的值框结果。 */
|
||||
const refreshOrderFieldSuggestionValues = async () => {
|
||||
@@ -1212,8 +1331,13 @@ const refreshOrderFieldSuggestionValues = async () => {
|
||||
if (request !== orderFieldValueRequest) return;
|
||||
orderFieldValuePreviews.value = result.fields;
|
||||
orderFieldValueState.value = 'ready';
|
||||
} catch {
|
||||
if (request === orderFieldValueRequest) clearOrderFieldValuePreview('failed');
|
||||
} catch (error) {
|
||||
if (request === orderFieldValueRequest) {
|
||||
clearOrderFieldValuePreview('failed');
|
||||
orderFieldValueError.value = error instanceof BusinessError
|
||||
? error.message
|
||||
: t('admin.shippingOrderProfiles.workbench.orderFieldValueFailed');
|
||||
}
|
||||
}
|
||||
};
|
||||
/** 订单字段框或读取方式变化后延迟回读整页字符证据,避免地址字段停留在旧的空候选。 */
|
||||
@@ -1587,6 +1711,9 @@ const renewLeaseOnVisibility = (): void => {
|
||||
};
|
||||
/** 打开路由指定草稿并恢复冻结的标注上下文。 */
|
||||
const edit = async (profile: ShippingOrderDocumentProfile) => {
|
||||
// Suppress document/table watchers until both restored canvas regions and the
|
||||
// bound sample are ready; otherwise an old preview request can win the race.
|
||||
restoringProfile = true;
|
||||
active.value = profile;
|
||||
form.profileCode = profile.profile_code;
|
||||
form.displayName = profile.display_name;
|
||||
@@ -1616,9 +1743,13 @@ const edit = async (profile: ShippingOrderDocumentProfile) => {
|
||||
boundSamples.value.find((item) => item.sample_role === "annotation")?.document_id || 0;
|
||||
await loadSampleTables();
|
||||
await loadPages();
|
||||
await refreshOrderFieldSuggestionValues();
|
||||
} catch (error) {
|
||||
fail(error);
|
||||
} finally {
|
||||
restoringProfile = false;
|
||||
// Page preview grants are independent from coordinate extraction. A grant
|
||||
// failure must not leave the right-hand recognition panel at "waiting".
|
||||
await refreshOrderFieldSuggestionValues();
|
||||
}
|
||||
};
|
||||
/** 跳转到独立验证页;页面仍需当前标签持有租约,不能绕过草稿单写者保护。 */
|
||||
@@ -1712,11 +1843,14 @@ watch(
|
||||
pageGrant.value = null;
|
||||
pageGrants.value = [];
|
||||
canvasUnavailable.value = false;
|
||||
if (restoringProfile) return;
|
||||
void loadSampleTables();
|
||||
if (active.value) void loadPages();
|
||||
},
|
||||
);
|
||||
watch(() => form.tableId, schedulePreview);
|
||||
watch(() => form.tableId, () => {
|
||||
if (!restoringProfile) schedulePreview();
|
||||
});
|
||||
const beforeUnload = (event: BeforeUnloadEvent) => {
|
||||
if (!dirty.value) return;
|
||||
event.preventDefault();
|
||||
@@ -1841,38 +1975,35 @@ onBeforeUnmount(() => {
|
||||
</div>
|
||||
<div class="header-actions">
|
||||
<output class="save-status" :class="`save-status--${saveState}`">{{ t(`admin.shippingOrderProfiles.workbench.saveStatus.${saveState}`) }}</output>
|
||||
<template v-if="saveState === 'readonly'">
|
||||
<button type="button" class="btn-secondary" @click="downloadLocalDraft">{{ t('admin.shippingOrderProfiles.workbench.exportLocalDraft') }}</button>
|
||||
<button type="button" class="btn-secondary" @click="() => void recoverEditLease()">{{ t('admin.shippingOrderProfiles.workbench.recoverLease') }}</button>
|
||||
<button type="button" class="btn-secondary" @click="() => void recoverEditLease(true)">{{ t('admin.shippingOrderProfiles.workbench.takeOverLease') }}</button>
|
||||
</template>
|
||||
<div v-if="saveState === 'readonly'" class="header-actions__lease">
|
||||
<button type="button" class="btn-secondary" @click="downloadLocalDraft">{{ t('admin.shippingOrderProfiles.workbench.headerExport') }}</button>
|
||||
<button type="button" class="btn-secondary" @click="() => void recoverEditLease()">{{ t('admin.shippingOrderProfiles.workbench.headerRecoverLease') }}</button>
|
||||
<button type="button" class="btn-secondary" @click="() => void recoverEditLease(true)">{{ t('admin.shippingOrderProfiles.workbench.headerTakeOverLease') }}</button>
|
||||
</div>
|
||||
<output v-if="active && currentSampleIsTraining" class="training-sample-status">{{ t('admin.shippingOrderProfiles.workbench.headerTrainingSample') }}</output>
|
||||
<button
|
||||
v-if="active"
|
||||
v-else-if="active"
|
||||
type="button"
|
||||
class="btn-secondary"
|
||||
:disabled="!form.documentId || !form.tableId || currentSampleIsTraining || saveState === 'readonly'"
|
||||
:disabled="!form.documentId || !form.tableId || saveState === 'readonly'"
|
||||
@click="() => void addCurrentTrainingSample()"
|
||||
>{{ currentSampleIsTraining ? t('admin.shippingOrderProfiles.blindTest.trainingAdded') : t('admin.shippingOrderProfiles.blindTest.addTrainingSample') }}</button>
|
||||
<button
|
||||
v-if="active"
|
||||
type="button"
|
||||
:disabled="issues.length > 0 || saving || saveState === 'readonly'"
|
||||
class="btn-primary"
|
||||
@click="() => void save()"
|
||||
>
|
||||
{{
|
||||
saving
|
||||
? t("admin.shippingOrderProfiles.saving")
|
||||
: t("admin.shippingOrderProfiles.updateDraft")
|
||||
}}
|
||||
</button>
|
||||
<button
|
||||
v-if="active"
|
||||
type="button"
|
||||
class="btn-secondary"
|
||||
@click="validateProfile(active)"
|
||||
>{{ t('admin.orderProfileValidation.validateTemplate') }}</button>
|
||||
<button type="button" class="btn-secondary" @click="router.push({ name: 'AdminShippingOrderDocumentProfiles' })">{{ t('admin.shippingOrderProfiles.workbench.returnToLibrary') }}</button>
|
||||
>{{ t('admin.shippingOrderProfiles.workbench.headerAddTrainingSample') }}</button>
|
||||
<div class="header-actions__flow">
|
||||
<button
|
||||
v-if="active"
|
||||
type="button"
|
||||
:disabled="issues.length > 0 || saving || saveState === 'readonly'"
|
||||
class="btn-primary"
|
||||
@click="() => void save()"
|
||||
>{{ saving ? t("admin.shippingOrderProfiles.saving") : t("admin.shippingOrderProfiles.workbench.headerSaveDraft") }}</button>
|
||||
<button
|
||||
v-if="active"
|
||||
type="button"
|
||||
class="btn-secondary"
|
||||
@click="validateProfile(active)"
|
||||
>{{ t('admin.shippingOrderProfiles.workbench.headerValidate') }}</button>
|
||||
<button type="button" class="btn-secondary" @click="router.push({ name: 'AdminShippingOrderDocumentProfiles' })">{{ t('admin.shippingOrderProfiles.workbench.headerReturnToLibrary') }}</button>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
<div class="desk editor-desk">
|
||||
@@ -1935,7 +2066,7 @@ onBeforeUnmount(() => {
|
||||
<header>
|
||||
<span>{{ t("admin.shippingOrderProfiles.workbench.currentConfiguration") }}</span>
|
||||
</header>
|
||||
<section class="document-match-editor">
|
||||
<section v-if="!documentMatch.requiredAnchors.length || documentAnchorNotice" class="document-match-editor">
|
||||
<div class="document-match-editor__heading">
|
||||
<div>
|
||||
<strong>{{ t('admin.shippingOrderProfiles.workbench.documentMatchAnchorTool') }}</strong>
|
||||
@@ -1944,10 +2075,6 @@ onBeforeUnmount(() => {
|
||||
</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">
|
||||
@@ -1995,7 +2122,7 @@ onBeforeUnmount(() => {
|
||||
class="select-field"
|
||||
:disabled="compactEditor || saveState === 'readonly'"
|
||||
@focus="beginFormEdit"
|
||||
@change="finishFormEdit"
|
||||
@change="finishFieldBindingEdit"
|
||||
>
|
||||
<option :value="null">
|
||||
{{ t("admin.shippingOrderProfiles.workbench.selectField") }}
|
||||
@@ -2174,6 +2301,14 @@ onBeforeUnmount(() => {
|
||||
.schema-warning { color: #b91c1c; }
|
||||
.schema-hint { color: #047857; }
|
||||
.header-actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
justify-content: flex-end;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
.header-actions__lease,
|
||||
.header-actions__flow {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
@@ -2377,9 +2512,6 @@ onBeforeUnmount(() => {
|
||||
.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; }
|
||||
@@ -2509,8 +2641,10 @@ onBeforeUnmount(() => {
|
||||
background: rgb(15 23 42 / .48);
|
||||
padding: 1.5rem;
|
||||
}
|
||||
.save-status { border-radius: 999px; background: #e2e8f0; padding: .4rem .6rem; color: #334155; font-size: .72rem; }
|
||||
.save-status,
|
||||
.training-sample-status { border-radius: 999px; background: #e2e8f0; padding: .4rem .6rem; color: #334155; font-size: .72rem; }
|
||||
.save-status--saving { background: #dbeafe; color: #1d4ed8; }.save-status--failed,.save-status--readonly { background: #fee2e2; color: #b91c1c; }.save-status--saved { background: #dcfce7; color: #166534; }
|
||||
.training-sample-status { background: #dcfce7; color: #166534; }
|
||||
.editor-workbench { padding: 0; background: #0f172a; }
|
||||
.editor-workbench .bench-header { max-width: none; padding: .7rem 1rem; color: #e2e8f0; }
|
||||
.editor-workbench .bench-header p { color: #94a3b8; }
|
||||
@@ -2659,8 +2793,13 @@ onBeforeUnmount(() => {
|
||||
}
|
||||
.header-actions {
|
||||
width: 100%;
|
||||
justify-content: flex-start;
|
||||
}
|
||||
.header-actions > button {
|
||||
.header-actions__lease,
|
||||
.header-actions__flow {
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.header-actions button {
|
||||
flex: 1;
|
||||
}
|
||||
}
|
||||
|
||||
+25
-1
@@ -34,6 +34,13 @@ const filteredFamilies = computed(() => {
|
||||
return families.value.filter((item) => `${item.profile_code} ${item.display_name}`.toLowerCase().includes(keyword));
|
||||
});
|
||||
|
||||
/** 仅以服务端返回的不可变 Schema 身份决定复制或迁移,列表页不猜测兼容性。 */
|
||||
function schemaMigrationRequired(item: OrderProfileVersionFamilySummary): boolean {
|
||||
return item.published_schema_version_id != null
|
||||
&& item.current_schema_version_id != null
|
||||
&& item.published_schema_version_id !== item.current_schema_version_id;
|
||||
}
|
||||
|
||||
/** 加载模板族摘要;列表只显示聚合结果,不能将每个版本扁平为独立模板。 */
|
||||
async function loadFamilies(): Promise<void> {
|
||||
loading.value = true;
|
||||
@@ -88,6 +95,16 @@ function viewVersion(item: OrderProfileVersionFamilySummary): void {
|
||||
router.push({ name: 'AdminShippingOrderDocumentProfileVersionDetail', params: { profileCode: item.profile_code, version: item.default_version } });
|
||||
}
|
||||
|
||||
/** 打开已发布版本的 Schema 迁移决策;字段兼容性只能由详情接口安全计算。 */
|
||||
function openSchemaMigration(item: OrderProfileVersionFamilySummary): void {
|
||||
if (!item.published_version) return;
|
||||
router.push({
|
||||
name: 'AdminShippingOrderDocumentProfileVersionDetail',
|
||||
params: { profileCode: item.profile_code, version: item.published_version },
|
||||
query: { migrate: '1' },
|
||||
});
|
||||
}
|
||||
|
||||
onMounted(loadFamilies);
|
||||
</script>
|
||||
|
||||
@@ -128,11 +145,17 @@ onMounted(loadFamilies);
|
||||
<span class="status-badge" :class="{ draft: item.draft_profile_id, published: !item.draft_profile_id && item.published_profile_id }">
|
||||
{{ item.draft_profile_id ? t('admin.shippingOrderProfiles.library.draft') : item.published_profile_id ? t('admin.shippingOrderProfiles.library.published', { version: item.published_version }) : t('admin.shippingOrderProfiles.library.retired') }}
|
||||
</span>
|
||||
<small v-if="item.published_profile_id && item.current_schema_version" class="schema-status" :class="{ warning: schemaMigrationRequired(item) }">
|
||||
{{ schemaMigrationRequired(item)
|
||||
? t('admin.shippingOrderProfiles.schemaMigration.versionMismatch', { bound: item.published_schema_version, current: item.current_schema_version })
|
||||
: t('admin.shippingOrderProfiles.schemaMigration.versionMatched', { version: item.current_schema_version }) }}
|
||||
</small>
|
||||
</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 v-else-if="item.published_profile_id && !schemaMigrationRequired(item)" class="btn-secondary btn-sm" type="button" @click="createNewVersion(item)">{{ t('admin.shippingOrderProfiles.newVersion') }}</button>
|
||||
<button v-if="!item.draft_profile_id && item.published_profile_id && schemaMigrationRequired(item)" class="btn-secondary btn-sm" type="button" @click="openSchemaMigration(item)">{{ t('admin.shippingOrderProfiles.schemaMigration.listAction') }}</button>
|
||||
<button class="btn-ghost btn-sm" type="button" @click="viewVersion(item)">{{ t('admin.shippingOrderProfiles.versionCenter.viewVersion') }}</button>
|
||||
</td>
|
||||
</tr>
|
||||
@@ -171,6 +194,7 @@ onMounted(loadFamilies);
|
||||
.status-badge { display: inline-flex; border: 1px solid #cbd5e1; border-radius: 999px; background: #f8fafc; padding: 3px 8px; color: #64748b; font-size: 11px; font-weight: 600; white-space: nowrap; }
|
||||
.status-badge.draft { border-color: #bae6fd; background: #f0f9ff; color: #0369a1; }
|
||||
.status-badge.published { border-color: #bbf7d0; background: #f0fdf4; color: #15803d; }
|
||||
.schema-status { display: block; margin-top: 5px; color: #64748b; font-size: 11px; white-space: nowrap; }.schema-status.warning { color: #b45309; }
|
||||
.actions-heading { min-width: 190px; }
|
||||
.profile-library__actions { display: flex; flex-wrap: wrap; align-items: center; gap: 4px; }
|
||||
|
||||
|
||||
+139
-2
@@ -5,12 +5,17 @@
|
||||
逻辑:当前已接入配置概览、只读样本画布、服务端语义 diff、审计时间线与实际使用;后续仅剩盲测隔离与发布治理收口。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, ref } from "vue";
|
||||
import { computed, onMounted, ref, watch } from "vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import { useRoute, useRouter } from "vue-router";
|
||||
import { BusinessError } from "@/shared/api/client";
|
||||
import { useMessage } from "@/shared/composables/useMessage";
|
||||
import { cloneOrderDocumentProfile } from "@/features/admin/api/shipping-order-document-profile.api";
|
||||
import {
|
||||
cloneOrderDocumentProfile,
|
||||
migrateOrderDocumentProfileSchema,
|
||||
} from "@/features/admin/api/shipping-order-document-profile.api";
|
||||
import { getShippingOrderSchemaState } from "@/features/admin/api/shipping-order-schema.api";
|
||||
import type { ShippingOrderSchemaVersion } from "@/features/admin/types/shipping-order-schema.types";
|
||||
import OrderProfileReadOnlyCanvas from "./components/OrderProfileReadOnlyCanvas.vue";
|
||||
import OrderProfileAuditTimeline from "./components/OrderProfileAuditTimeline.vue";
|
||||
import OrderProfileVersionDiff from "./components/OrderProfileVersionDiff.vue";
|
||||
@@ -26,6 +31,10 @@ const route = useRoute();
|
||||
const router = useRouter();
|
||||
const message = useMessage();
|
||||
const cloning = ref(false);
|
||||
const migrating = ref(false);
|
||||
const migrationOpen = ref(false);
|
||||
const publishedSchema = ref<ShippingOrderSchemaVersion | null>(null);
|
||||
const migrationResolutions = ref<Record<string, { action: "unbind" } | { replacement_field_id: string }>>({});
|
||||
const {
|
||||
activeTab,
|
||||
detail,
|
||||
@@ -36,6 +45,92 @@ const {
|
||||
versions,
|
||||
} = useOrderProfileVersionDetail();
|
||||
|
||||
const canMigrateSchema = computed(() =>
|
||||
detail.value?.status === "published"
|
||||
&& publishedSchema.value !== null
|
||||
&& detail.value.schema_version_id !== publishedSchema.value.id,
|
||||
);
|
||||
|
||||
const breakingChanges = computed(() => detail.value?.schema_compatibility?.breaking_changes || []);
|
||||
|
||||
const loadPublishedSchema = async () => {
|
||||
try {
|
||||
const state = await getShippingOrderSchemaState();
|
||||
publishedSchema.value = state.versions.find((item) => item.status === "published") || null;
|
||||
} catch {
|
||||
publishedSchema.value = null;
|
||||
}
|
||||
};
|
||||
|
||||
const openSchemaMigration = () => {
|
||||
migrationResolutions.value = Object.fromEntries(
|
||||
breakingChanges.value.map((change) => [change.field_id, { action: "unbind" }]),
|
||||
);
|
||||
migrationOpen.value = true;
|
||||
};
|
||||
|
||||
const setMigrationResolution = (fieldId: string, replacementId: string) => {
|
||||
migrationResolutions.value[fieldId] = replacementId
|
||||
? { replacement_field_id: replacementId }
|
||||
: { action: "unbind" };
|
||||
};
|
||||
|
||||
const migrationReplacementId = (fieldId: string): string => {
|
||||
const resolution = migrationResolutions.value[fieldId];
|
||||
return resolution && "replacement_field_id" in resolution ? resolution.replacement_field_id : "";
|
||||
};
|
||||
|
||||
const migrationErrorMessage = (error: unknown): string => {
|
||||
if (!(error instanceof BusinessError)) return t("admin.shippingOrderProfiles.loadFailed");
|
||||
const reason = String(error.details.reason || "");
|
||||
if (reason === "duplicate_field_code") {
|
||||
return t("admin.shippingOrderProfiles.schemaMigration.duplicateSchemaField", {
|
||||
field: error.details.field_code || "-",
|
||||
existingScope: error.details.existing_scope || "-",
|
||||
duplicateScope: error.details.duplicate_scope || "-",
|
||||
});
|
||||
}
|
||||
if (reason === "line_start_field_unbound") {
|
||||
return t("admin.shippingOrderProfiles.schemaMigration.lineStartRequired", {
|
||||
field: error.details.line_start_field_code || "-",
|
||||
});
|
||||
}
|
||||
const fieldPath = String(error.details.field_path || "");
|
||||
return fieldPath
|
||||
? `${error.message} (${t("admin.shippingOrderProfiles.schemaMigration.invalidPath", { path: fieldPath })})`
|
||||
: error.message;
|
||||
};
|
||||
|
||||
const migrateSchema = async () => {
|
||||
if (!detail.value || !publishedSchema.value || migrating.value) return;
|
||||
migrating.value = true;
|
||||
try {
|
||||
const draft = await migrateOrderDocumentProfileSchema(
|
||||
detail.value.id,
|
||||
publishedSchema.value.id,
|
||||
migrationResolutions.value,
|
||||
);
|
||||
message.success(t("admin.shippingOrderProfiles.schemaMigration.created"));
|
||||
migrationOpen.value = false;
|
||||
void router.push({
|
||||
name: "AdminShippingOrderDocumentProfiles",
|
||||
query: { profileCode: draft.profile_code, profileId: String(draft.id) },
|
||||
});
|
||||
} catch (error) {
|
||||
message.error(migrationErrorMessage(error));
|
||||
} finally {
|
||||
migrating.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
onMounted(() => { void loadPublishedSchema(); });
|
||||
|
||||
watch([detail, publishedSchema, () => route.query.migrate], () => {
|
||||
if (route.query.migrate !== "1" || !canMigrateSchema.value || migrationOpen.value) return;
|
||||
openSchemaMigration();
|
||||
void router.replace({ query: { ...route.query, migrate: undefined } });
|
||||
});
|
||||
|
||||
const pageTitle = computed(() => {
|
||||
if (!detail.value) {
|
||||
return `${profileCode.value} · v${route.params.version || ""}`;
|
||||
@@ -153,6 +248,14 @@ const createNewVersion = async () => {
|
||||
: t("admin.shippingOrderProfiles.newVersion")
|
||||
}}
|
||||
</button>
|
||||
<button
|
||||
v-if="canMigrateSchema"
|
||||
type="button"
|
||||
class="btn-primary"
|
||||
@click="openSchemaMigration"
|
||||
>
|
||||
{{ t("admin.shippingOrderProfiles.schemaMigration.action", { version: publishedSchema?.version }) }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
@@ -209,6 +312,36 @@ const createNewVersion = async () => {
|
||||
</section>
|
||||
</div>
|
||||
</template>
|
||||
<div v-if="migrationOpen" class="migration-backdrop" role="presentation" @click.self="migrationOpen = false">
|
||||
<section class="migration-dialog" role="dialog" aria-modal="true" :aria-label="t('admin.shippingOrderProfiles.schemaMigration.title')">
|
||||
<h2>{{ t("admin.shippingOrderProfiles.schemaMigration.title") }}</h2>
|
||||
<p>{{ t("admin.shippingOrderProfiles.schemaMigration.description", { from: detail?.schema_version, to: publishedSchema?.version }) }}</p>
|
||||
<p class="migration-note">{{ t("admin.shippingOrderProfiles.schemaMigration.revalidation") }}</p>
|
||||
<div v-if="breakingChanges.length" class="migration-changes">
|
||||
<article v-for="change in breakingChanges" :key="change.field_id">
|
||||
<strong>{{ change.before || change.field_id }}</strong>
|
||||
<span>{{ t("admin.shippingOrderProfiles.schemaMigration.reason", { reason: change.reason }) }}</span>
|
||||
<label>
|
||||
{{ t("admin.shippingOrderProfiles.schemaMigration.resolution") }}
|
||||
<select
|
||||
:value="migrationReplacementId(change.field_id)"
|
||||
@change="setMigrationResolution(change.field_id, ($event.target as HTMLSelectElement).value)"
|
||||
>
|
||||
<option value="">{{ t("admin.shippingOrderProfiles.schemaMigration.unbind") }}</option>
|
||||
<option v-for="candidate in change.replacement_candidates || []" :key="candidate.field_id" :value="candidate.field_id">
|
||||
{{ candidate.display_name || candidate.field_code || candidate.field_id }}
|
||||
</option>
|
||||
</select>
|
||||
</label>
|
||||
</article>
|
||||
</div>
|
||||
<p v-else class="migration-note">{{ t("admin.shippingOrderProfiles.schemaMigration.noBreakingChanges") }}</p>
|
||||
<footer>
|
||||
<button type="button" class="btn-secondary" :disabled="migrating" @click="migrationOpen = false">{{ t("admin.shippingOrderProfiles.schemaMigration.cancel") }}</button>
|
||||
<button type="button" class="btn-primary" :disabled="migrating" @click="migrateSchema">{{ migrating ? t("admin.shippingOrderProfiles.saving") : t("admin.shippingOrderProfiles.schemaMigration.confirm") }}</button>
|
||||
</footer>
|
||||
</section>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
@@ -349,6 +482,10 @@ const createNewVersion = async () => {
|
||||
color: var(--status-error-fg);
|
||||
}
|
||||
|
||||
.migration-backdrop { position: fixed; z-index: 30; inset: 0; display: grid; place-items: center; padding: 1rem; background: rgb(15 23 42 / 45%); }
|
||||
.migration-dialog { display: grid; width: min(100%, 42rem); max-height: min(44rem, calc(100vh - 2rem)); gap: 1rem; overflow: auto; padding: 1.5rem; border-radius: 1rem; background: var(--bg-surface); box-shadow: 0 20px 40px rgb(15 23 42 / 25%); }
|
||||
.migration-dialog h2,.migration-dialog p { margin: 0; }.migration-note { color: var(--text-muted); font-size: .875rem; }.migration-changes { display: grid; gap: .75rem; }.migration-changes article { display: grid; gap: .45rem; padding: .85rem; border: 1px solid var(--border-default); border-radius: .75rem; }.migration-changes span { color: var(--text-muted); font-size: .8125rem; }.migration-changes label { display: grid; gap: .3rem; color: var(--text-secondary); font-size: .8125rem; font-weight: 600; }.migration-changes select { min-height: 2.25rem; border: 1px solid var(--border-default); border-radius: .5rem; background: var(--bg-surface); color: var(--text-primary); font: inherit; }.migration-dialog footer { display: flex; justify-content: flex-end; gap: .5rem; }
|
||||
|
||||
@media (max-width: 960px) {
|
||||
.header-main,
|
||||
.version-switcher {
|
||||
|
||||
+14
-3
@@ -19,12 +19,21 @@ const emit = defineEmits<{ 'update:modelValue': [value: number]; uploaded: []; }
|
||||
const { t } = useI18n();
|
||||
const message = useMessage();
|
||||
const uploading = ref(false);
|
||||
const pendingIntake = ref<{ intakeNo: string; filename: string; state: 'parsing' | 'failed' } | null>(null);
|
||||
const pendingIntake = ref<{ intakeNo: string; filename: string; state: 'parsing' | 'failed'; errorCode?: string | null } | null>(null);
|
||||
let pollingTimer: number | null = null;
|
||||
const selectedSample = computed(() => props.samples.find((item) => item.document_id === props.modelValue) || null);
|
||||
|
||||
/** 停止当前轮询;离开步骤或开始新上传时都不保留后台计时器。 */
|
||||
function stopPolling(): void { if (pollingTimer) window.clearTimeout(pollingTimer); pollingTimer = null; }
|
||||
/** 将模板布局失败码转成管理员可执行的提示,不把内部快照内容暴露到页面。 */
|
||||
function sampleFailureMessage(errorCode?: string | null): string {
|
||||
const key = errorCode === 'mineru_cell_coordinates_missing'
|
||||
? 'sampleLayoutCoordinatesMissing'
|
||||
: errorCode === 'shipping_document_layout_snapshot_size_exceeded'
|
||||
? 'sampleLayoutSnapshotTooLarge'
|
||||
: 'sampleParseFailed';
|
||||
return t(`admin.shippingOrderProfiles.wizard.${key}`);
|
||||
}
|
||||
/** 刷新样本列表后按 Intake 精确定位新文档,防止同名历史文件被误选。 */
|
||||
function selectUploadedSample(intakeNo: string): boolean {
|
||||
const sample = props.samples.find((item) => item.intake_no === intakeNo);
|
||||
@@ -46,7 +55,9 @@ async function pollIntake(intakeNo: string): Promise<void> {
|
||||
return;
|
||||
}
|
||||
if (['failed', 'error'].includes(result.parse_status)) {
|
||||
pendingIntake.value = { intakeNo, filename: pendingIntake.value?.filename || '', state: 'failed' };
|
||||
pendingIntake.value = {
|
||||
intakeNo, filename: pendingIntake.value?.filename || '', state: 'failed', errorCode: result.error_code,
|
||||
};
|
||||
return;
|
||||
}
|
||||
pollingTimer = window.setTimeout(() => void pollIntake(intakeNo), 1500);
|
||||
@@ -85,7 +96,7 @@ onBeforeUnmount(stopPolling);
|
||||
|
||||
<div v-if="pendingIntake" class="parse-status" :class="{ failed: pendingIntake.state === 'failed' }">
|
||||
<Clock3 v-if="pendingIntake.state === 'parsing'" :size="19" /><span v-else>!</span>
|
||||
<div><strong>{{ pendingIntake.filename }}</strong><p>{{ pendingIntake.state === 'parsing' ? t('admin.shippingOrderProfiles.wizard.sampleParsing') : t('admin.shippingOrderProfiles.wizard.sampleParseFailed') }}</p></div>
|
||||
<div><strong>{{ pendingIntake.filename }}</strong><p>{{ pendingIntake.state === 'parsing' ? t('admin.shippingOrderProfiles.wizard.sampleParsing') : sampleFailureMessage(pendingIntake.errorCode) }}</p></div>
|
||||
</div>
|
||||
|
||||
<div v-if="selectedSample" class="selected-sample"><CheckCircle2 :size="20" /><div><strong>{{ t('admin.shippingOrderProfiles.wizard.sampleSelected') }}</strong><span>{{ selectedSample.filename || selectedSample.intake_no }} · {{ selectedSample.table_count }} {{ t('admin.shippingOrderProfiles.tablesUnit') }}</span></div></div>
|
||||
|
||||
+49
-1
@@ -1,6 +1,6 @@
|
||||
/**
|
||||
* features/admin/modules/shipping-order-document-profiles/orderProfileForm.utils.spec.ts
|
||||
* 用途:验证可视化订单模板表单生成受控规则,并确保切换样本时配置入口不会消失。
|
||||
* 用途:验证可视化订单模板表单生成受控规则、明细字段分组,并确保切换样本时配置入口不会消失。
|
||||
* 依赖:Vitest、orderProfileForm.utils。
|
||||
* 逻辑:覆盖 direct、复合解析器开关及跨列冲突,避免无效配置进入后端。
|
||||
*/
|
||||
@@ -15,10 +15,37 @@ import {
|
||||
shouldShowStandardOrderProfilePreview,
|
||||
toOrderProfileAnchorId,
|
||||
buildOrderProfileRecognitionResults,
|
||||
isOrderProfileAnchorRelativeCandidate,
|
||||
normalizeOrderProfileRelativeRegion,
|
||||
toOrderProfileAnchorRelativeRegion,
|
||||
groupUniqueOrderProfileLineFields,
|
||||
} from './orderProfileForm.utils';
|
||||
|
||||
describe('order profile form rules', () => {
|
||||
it.each(['line_no', 'customer_po_line_no'])(
|
||||
'keeps %s available after resolving the main-line fields',
|
||||
(startFieldCode) => {
|
||||
const regions = [
|
||||
{ id: 'main', kind: 'line' as const, label: 'Main', pageNo: 1, region: { x0: .1, y0: .3, x1: .9, y1: .4 } },
|
||||
{ id: 'start', kind: 'field' as const, label: 'Start', fieldCode: startFieldCode, parentId: 'main', pageNo: 1, region: { x0: .1, y0: .3, x1: .2, y1: .4 } },
|
||||
{ id: 'part', kind: 'field' as const, label: 'Part', fieldCode: 'part_number', parentId: 'main', pageNo: 1, region: { x0: .2, y0: .3, x1: .5, y1: .4 } },
|
||||
];
|
||||
|
||||
const grouped = groupUniqueOrderProfileLineFields(regions, ['main']);
|
||||
|
||||
// 关键断言:起行字段选择和 line_layout 序列化复用同一结果时,字段不会被第一次读取消费。
|
||||
expect(grouped.fieldsByLayout.get('main')?.map((item) => item.fieldCode)).toEqual([
|
||||
startFieldCode,
|
||||
'part_number',
|
||||
]);
|
||||
expect(grouped.fieldsByLayout.get('main')?.map((item) => item.fieldCode)).toEqual([
|
||||
startFieldCode,
|
||||
'part_number',
|
||||
]);
|
||||
expect(grouped.boundRegionIds).toEqual(new Set(['start', 'part']));
|
||||
},
|
||||
);
|
||||
|
||||
it('builds only registered direct and composite rules', () => {
|
||||
const rules = buildOrderProfileColumnRules([
|
||||
{ extractor_key: 'direct', target: 'qty' },
|
||||
@@ -198,4 +225,25 @@ describe('order profile form rules', () => {
|
||||
// 完全落在页面外或零面积的框没有可解释的读取边界,必须由管理员重画。
|
||||
expect(normalizeOrderProfileRelativeRegion({ x0: 1.1, y0: .2, x1: 1.2, y1: .3 })).toBeNull();
|
||||
});
|
||||
|
||||
it('serializes a right-of-anchor value box as a movable anchor-relative region', () => {
|
||||
expect(toOrderProfileAnchorRelativeRegion(
|
||||
{ x0: .42, y0: .80, x1: .50, y1: .82 },
|
||||
{ x0: .30, y0: .80, x1: .41, y1: .82 },
|
||||
)).toEqual({ x0: expect.closeTo(1.090909), y0: 0, x1: expect.closeTo(1.818181), y1: 1 });
|
||||
});
|
||||
|
||||
it('keeps a remote legacy value box absolute instead of creating invalid relative offsets', () => {
|
||||
expect(isOrderProfileAnchorRelativeCandidate(
|
||||
{ x0: .33, y0: .58, x1: .72, y1: .60 },
|
||||
{ x0: .02, y0: .10, x1: .15, y1: .12 },
|
||||
)).toBe(false);
|
||||
});
|
||||
|
||||
it('keeps a same-row auto suggestion absolute when its tiny label makes the relative span exceed the contract', () => {
|
||||
expect(isOrderProfileAnchorRelativeCandidate(
|
||||
{ x0: .30, y0: .40, x1: .95, y1: .42 },
|
||||
{ x0: .20, y0: .40, x1: .21, y1: .42 },
|
||||
)).toBe(false);
|
||||
});
|
||||
});
|
||||
+70
-1
@@ -1,6 +1,6 @@
|
||||
/**
|
||||
* features/admin/modules/shipping-order-document-profiles/orderProfileForm.utils.ts
|
||||
* 用途:构造可视化订单模板的白名单列规则,并控制样本表格配置区的安全显示。
|
||||
* 用途:构造可视化订单模板的白名单列规则、明细字段分组,并控制样本表格配置区的安全显示。
|
||||
* 依赖:订单 Profile DTO。
|
||||
* 逻辑:页面状态只允许 direct 或已注册复合解析器;同一目标字段跨列只能出现一次。
|
||||
*/
|
||||
@@ -19,6 +19,38 @@ export interface OrderProfileColumnSelection {
|
||||
target: string;
|
||||
}
|
||||
|
||||
export interface OrderProfileLineFieldGroups {
|
||||
fieldsByLayout: Map<string, OrderProfileCanvasRegion[]>;
|
||||
boundRegionIds: Set<string>;
|
||||
}
|
||||
|
||||
/**
|
||||
* 按物理行顺序收集唯一的明细字段绑定,供起行字段选择和最终定义复用同一份结果。
|
||||
* 核心逻辑:每个 Schema 字段只归属首个物理行;返回结果可重复读取,不会因预览起行字段而消费绑定。
|
||||
* @param regions - 当前页面全部画布区域。
|
||||
* @param layoutIds - 按主行到续行排列的物理行 ID。
|
||||
* @returns 每个物理行的字段区域,以及已进入正式绑定的区域 ID。
|
||||
*/
|
||||
export const groupUniqueOrderProfileLineFields = (
|
||||
regions: OrderProfileCanvasRegion[],
|
||||
layoutIds: string[],
|
||||
): OrderProfileLineFieldGroups => {
|
||||
const claimedFieldCodes = new Set<string>();
|
||||
const boundRegionIds = new Set<string>();
|
||||
const fieldsByLayout = new Map<string, OrderProfileCanvasRegion[]>();
|
||||
layoutIds.forEach((layoutId) => {
|
||||
const fields = regions.filter((item) => {
|
||||
if (item.kind !== 'field' || item.parentId !== layoutId || !item.fieldCode) return false;
|
||||
if (claimedFieldCodes.has(item.fieldCode)) return false;
|
||||
claimedFieldCodes.add(item.fieldCode);
|
||||
boundRegionIds.add(item.id);
|
||||
return true;
|
||||
});
|
||||
fieldsByLayout.set(layoutId, fields);
|
||||
});
|
||||
return { fieldsByLayout, boundRegionIds };
|
||||
};
|
||||
|
||||
/**
|
||||
* 将画布或历史草稿的区域限制为页面归一化坐标。
|
||||
* @param region - 可能来自拖拽、自动建议或历史模板的页面区域。
|
||||
@@ -36,6 +68,43 @@ export const normalizeOrderProfileRelativeRegion = (
|
||||
return x0 < x1 && y0 < y1 ? { x0, y0, x1, y1 } : null;
|
||||
};
|
||||
|
||||
/** 将页面值框换算为锚点尺寸的相对偏移,供标签右侧字段随标签移动读取。 */
|
||||
export const toOrderProfileAnchorRelativeRegion = (
|
||||
valueRegion: OrderProfileRelativeRegion,
|
||||
anchorRegion: OrderProfileRelativeRegion,
|
||||
): OrderProfileRelativeRegion | null => {
|
||||
const width = anchorRegion.x1 - anchorRegion.x0;
|
||||
const height = anchorRegion.y1 - anchorRegion.y0;
|
||||
if (width <= 0 || height <= 0) return null;
|
||||
const relative = {
|
||||
x0: (valueRegion.x0 - anchorRegion.x0) / width,
|
||||
y0: (valueRegion.y0 - anchorRegion.y0) / height,
|
||||
x1: (valueRegion.x1 - anchorRegion.x0) / width,
|
||||
y1: (valueRegion.y1 - anchorRegion.y0) / height,
|
||||
};
|
||||
return Number.isFinite(relative.x0) && Number.isFinite(relative.y0)
|
||||
&& Number.isFinite(relative.x1) && Number.isFinite(relative.y1)
|
||||
&& relative.x0 < relative.x1 && relative.y0 < relative.y1 ? relative : null;
|
||||
};
|
||||
|
||||
/** 判断标签和值框是否是同一视觉行,只有这种画布关系可安全改为随标签移动。 */
|
||||
export const isOrderProfileAnchorRelativeCandidate = (
|
||||
valueRegion: OrderProfileRelativeRegion,
|
||||
anchorRegion: OrderProfileRelativeRegion,
|
||||
): boolean => {
|
||||
const anchorHeight = anchorRegion.y1 - anchorRegion.y0;
|
||||
const valueHeight = valueRegion.y1 - valueRegion.y0;
|
||||
if (anchorHeight <= 0 || valueHeight <= 0) return false;
|
||||
const tolerance = Math.max(anchorHeight, valueHeight) * 2;
|
||||
if (!(valueRegion.y0 <= anchorRegion.y1 + tolerance
|
||||
&& anchorRegion.y0 <= valueRegion.y1 + tolerance)) return false;
|
||||
const relative = toOrderProfileAnchorRelativeRegion(valueRegion, anchorRegion);
|
||||
// Backend intentionally bounds offsets to prevent a tiny auto-detected label
|
||||
// from producing an unbounded template rule. Fall back to the page box here.
|
||||
return relative !== null && [relative.x0, relative.y0, relative.x1, relative.y1]
|
||||
.every((value) => value >= -12 && value <= 12);
|
||||
};
|
||||
|
||||
/**
|
||||
* 判断是否显示普通表格预览;可直接创建 Profile 的表格不受上一张表多物理行状态影响。
|
||||
* @param profileCreationAllowed - 当前表格是否可直接创建 Profile
|
||||
|
||||
+348
-27
@@ -3,7 +3,7 @@
|
||||
用途:单一发货订单 Schema 的版本采用与版本级识别规则编辑;字段身份由全局字段资产库维护。
|
||||
依赖:shipping-order-schema.api、shipping-field-assets.api、FieldImpactDrawer、版本/审计抽屉组件、Vue I18n。
|
||||
逻辑:左侧勾选采用资产目录,右侧编辑已采用字段规则;草稿保存/发布与历史追溯由服务端冻结。无多族切换。
|
||||
自动建单总开关仅草稿可改,二次确认后写入本地,随保存草稿/发布版本生效。
|
||||
「Schema 级策略」分组收纳自动建单总开关与字段派生规则;仅草稿可改,随保存/发布生效;支持样本模拟。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, reactive, ref, watch } from 'vue';
|
||||
@@ -26,6 +26,8 @@ import {
|
||||
listShippingOrderSchemaVersions,
|
||||
publishShippingOrderSchemaDraft,
|
||||
saveShippingOrderSchemaDraft,
|
||||
simulateShippingOrderSchemaDerivation,
|
||||
listShippingOrderSchemaDerivationSimulateSamples,
|
||||
} from '@/features/admin/api/shipping-order-schema.api';
|
||||
import FieldImpactDrawer from '@/features/admin/modules/shipping-field-assets/components/FieldImpactDrawer.vue';
|
||||
import SchemaExtractionAuditDrawer from '@/features/admin/modules/shipping-order-schema/components/SchemaExtractionAuditDrawer.vue';
|
||||
@@ -34,6 +36,9 @@ import SchemaVersionHistoryDrawer from '@/features/admin/modules/shipping-order-
|
||||
import SchemaVersionUsageDrawer from '@/features/admin/modules/shipping-order-schema/components/SchemaVersionUsageDrawer.vue';
|
||||
import type { ShippingFieldAsset, ShippingFieldAssetImpact } from '@/features/admin/types/shipping-field-assets.types';
|
||||
import type {
|
||||
ShippingOrderDerivationRule,
|
||||
ShippingOrderDerivationSimulateResult,
|
||||
ShippingOrderDerivationSimulateSampleItem,
|
||||
ShippingOrderField,
|
||||
ShippingOrderFieldConfig,
|
||||
ShippingOrderExtractionAudit,
|
||||
@@ -70,6 +75,20 @@ const autoCreationConfirmOpen = ref(false);
|
||||
const pendingAutoCreationEnabled = ref(false);
|
||||
const changeNote = ref('');
|
||||
const selectedDraftFieldId = ref<string | null>(null);
|
||||
const derivationRules = ref<ShippingOrderDerivationRule[]>([]);
|
||||
const derivationPanelOpen = ref(true);
|
||||
const simulateOpen = ref(false);
|
||||
const simulating = ref(false);
|
||||
const simulateMode = ref<'history' | 'inline'>('history');
|
||||
const simulateSamples = ref<ShippingOrderDerivationSimulateSampleItem[]>([]);
|
||||
const simulateSampleRef = ref('');
|
||||
const simulateSamplesLoading = ref(false);
|
||||
const simulateSampleJson = ref(`[
|
||||
{"customer_po_line_no": "00010", "line_no": null},
|
||||
{"customer_po_line_no": "00020", "line_no": "20"},
|
||||
{"customer_po_line_no": "ABC", "line_no": null}
|
||||
]`);
|
||||
const simulateResult = ref<ShippingOrderDerivationSimulateResult | null>(null);
|
||||
const fieldSearch = ref('');
|
||||
const expandedGroups = reactive<Record<AdoptionGroupKey, boolean>>({
|
||||
headerStandard: true,
|
||||
@@ -252,6 +271,19 @@ const syncDraftFields = (): void => {
|
||||
autoCreationEnabled.value = typeof draftPolicy === 'boolean'
|
||||
? draftPolicy
|
||||
: state.value?.schema?.auto_creation_policy?.enabled === true;
|
||||
const sourceRules = draft.value?.definition?.derivation_rules
|
||||
|| published.value?.definition?.derivation_rules
|
||||
|| [];
|
||||
derivationRules.value = sourceRules.length
|
||||
? sourceRules.map((rule) => ({ ...rule }))
|
||||
: [{
|
||||
rule_id: 'R-LINE-NO-FROM-CUSTOMER-PO',
|
||||
enabled: false,
|
||||
source_field_code: 'customer_po_line_no',
|
||||
target_field_code: 'line_no',
|
||||
strategy: 'copy_if_empty',
|
||||
scope: 'line',
|
||||
}];
|
||||
const existing = draft.value?.definition?.fields || published.value?.definition?.fields || [];
|
||||
const byId = new Map(existing.map((item) => [item.field_id, item]));
|
||||
draftFields.value = (state.value?.fields || [])
|
||||
@@ -409,7 +441,7 @@ const toggleAdoption = (field: ShippingOrderField, enabled: boolean): void => {
|
||||
}
|
||||
};
|
||||
|
||||
/** 保存草稿的全部已采用字段规则与自动建单策略;未采用字段不会进入发布契约。 */
|
||||
/** 保存草稿的全部已采用字段规则、派生规则与自动建单策略;未采用字段不会进入发布契约。 */
|
||||
const saveDraft = async (): Promise<void> => {
|
||||
if (!draft.value) return;
|
||||
saving.value = true;
|
||||
@@ -418,12 +450,16 @@ const saveDraft = async (): Promise<void> => {
|
||||
const saved = await saveShippingOrderSchemaDraft(draft.value.id, {
|
||||
fields,
|
||||
auto_creation_policy: { enabled: autoCreationEnabled.value },
|
||||
derivation_rules: derivationRules.value.map((item) => ({ ...item })),
|
||||
change_note: changeNote.value,
|
||||
expected_lock_version: draft.value.lock_version,
|
||||
});
|
||||
if (state.value) {
|
||||
state.value.versions = state.value.versions.map((item) => (item.id === saved.id ? saved : item));
|
||||
}
|
||||
if (saved.definition?.derivation_rules) {
|
||||
derivationRules.value = saved.definition.derivation_rules.map((item) => ({ ...item }));
|
||||
}
|
||||
message.success(t('admin.shippingOrderSchema.draftSaved'));
|
||||
} catch (error) {
|
||||
await handleWriteError(error);
|
||||
@@ -432,6 +468,82 @@ const saveDraft = async (): Promise<void> => {
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 切换派生规则启用状态(仅草稿可改)。
|
||||
* @param index - 规则下标
|
||||
* @param event - checkbox 事件
|
||||
*/
|
||||
const onDerivationEnabledChange = (index: number, event: Event): void => {
|
||||
if (!draft.value) return;
|
||||
const checked = (event.target as HTMLInputElement).checked;
|
||||
const current = derivationRules.value[index];
|
||||
if (!current) return;
|
||||
derivationRules.value[index] = { ...current, enabled: checked };
|
||||
};
|
||||
|
||||
/**
|
||||
* 打开派生规则模拟弹窗并加载历史 Extraction 样本列表。
|
||||
*/
|
||||
const openDerivationSimulate = async (): Promise<void> => {
|
||||
simulateResult.value = null;
|
||||
simulateMode.value = 'history';
|
||||
simulateOpen.value = true;
|
||||
simulateSamplesLoading.value = true;
|
||||
try {
|
||||
const response = await listShippingOrderSchemaDerivationSimulateSamples(20);
|
||||
simulateSamples.value = response.items || [];
|
||||
simulateSampleRef.value = simulateSamples.value[0]?.sample_ref || '';
|
||||
if (!simulateSamples.value.length) {
|
||||
simulateMode.value = 'inline';
|
||||
}
|
||||
} catch (error) {
|
||||
await handleWriteError(error);
|
||||
simulateMode.value = 'inline';
|
||||
} finally {
|
||||
simulateSamplesLoading.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 运行派生规则模拟:优先使用历史 Extraction 样本,亦可手工 JSON。
|
||||
*/
|
||||
const runDerivationSimulate = async (): Promise<void> => {
|
||||
if (!draft.value && !published.value) return;
|
||||
const versionId = draft.value?.id || published.value?.id;
|
||||
if (!versionId) return;
|
||||
simulating.value = true;
|
||||
try {
|
||||
if (simulateMode.value === 'history') {
|
||||
if (!simulateSampleRef.value) {
|
||||
message.error(t('admin.shippingOrderSchema.derivationSimulateSampleRequired'));
|
||||
return;
|
||||
}
|
||||
simulateResult.value = await simulateShippingOrderSchemaDerivation(versionId, {
|
||||
sample_ref: simulateSampleRef.value,
|
||||
derivation_rules: derivationRules.value,
|
||||
});
|
||||
return;
|
||||
}
|
||||
const lines = JSON.parse(simulateSampleJson.value) as Array<Record<string, string | number | null>>;
|
||||
if (!Array.isArray(lines)) {
|
||||
throw new Error('invalid sample');
|
||||
}
|
||||
simulateResult.value = await simulateShippingOrderSchemaDerivation(versionId, {
|
||||
lines,
|
||||
derivation_rules: derivationRules.value,
|
||||
sample_ref: 'schema-admin-inline-sample',
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof SyntaxError || (error instanceof Error && error.message === 'invalid sample')) {
|
||||
message.error(t('admin.shippingOrderSchema.derivationSimulateSampleInvalid'));
|
||||
} else {
|
||||
await handleWriteError(error);
|
||||
}
|
||||
} finally {
|
||||
simulating.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 拦截自动建单开关变更:仅草稿可改,且须二次确认;确认后仅写入本地,随保存草稿/发布生效。
|
||||
* @param event - checkbox change 事件
|
||||
@@ -895,32 +1007,91 @@ onMounted(async () => {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<label class="auto-creation-switch">
|
||||
<input
|
||||
:checked="autoCreationEnabled"
|
||||
:disabled="saving || !draft"
|
||||
type="checkbox"
|
||||
@change="onAutoCreationToggle"
|
||||
>
|
||||
<span>
|
||||
<strong>{{ t('admin.shippingOrderSchema.autoCreationEnabled') }}</strong>
|
||||
<small>{{ t('admin.shippingOrderSchema.autoCreationHint') }}</small>
|
||||
<small class="auto-creation-effective">
|
||||
{{ t('admin.shippingOrderSchema.autoCreationPublished', {
|
||||
state: publishedAutoCreationEnabled
|
||||
? t('admin.shippingOrderSchema.autoCreationOn')
|
||||
: t('admin.shippingOrderSchema.autoCreationOff'),
|
||||
}) }}
|
||||
<template v-if="autoCreationPendingPublish">
|
||||
· {{ t('admin.shippingOrderSchema.autoCreationDraftPending', {
|
||||
state: autoCreationEnabled
|
||||
<section class="schema-policy-group" data-testid="schema-policy-group">
|
||||
<header class="schema-policy-heading">
|
||||
<div>
|
||||
<h2>{{ t('admin.shippingOrderSchema.schemaPolicyGroupTitle') }}</h2>
|
||||
<p>{{ t('admin.shippingOrderSchema.schemaPolicyGroupHint') }}</p>
|
||||
</div>
|
||||
<span v-if="draft" class="schema-policy-badge">
|
||||
{{ t('admin.shippingOrderSchema.schemaPolicyDraftBadge') }}
|
||||
</span>
|
||||
<span v-else class="schema-policy-badge is-readonly">
|
||||
{{ t('admin.shippingOrderSchema.schemaPolicyPublishedBadge') }}
|
||||
</span>
|
||||
</header>
|
||||
|
||||
<label class="auto-creation-switch">
|
||||
<input
|
||||
:checked="autoCreationEnabled"
|
||||
:disabled="saving || !draft"
|
||||
type="checkbox"
|
||||
@change="onAutoCreationToggle"
|
||||
>
|
||||
<span>
|
||||
<strong>{{ t('admin.shippingOrderSchema.autoCreationEnabled') }}</strong>
|
||||
<small>{{ t('admin.shippingOrderSchema.autoCreationHint') }}</small>
|
||||
<small class="auto-creation-effective">
|
||||
{{ t('admin.shippingOrderSchema.autoCreationPublished', {
|
||||
state: publishedAutoCreationEnabled
|
||||
? t('admin.shippingOrderSchema.autoCreationOn')
|
||||
: t('admin.shippingOrderSchema.autoCreationOff'),
|
||||
}) }}
|
||||
</template>
|
||||
</small>
|
||||
</span>
|
||||
</label>
|
||||
<template v-if="autoCreationPendingPublish">
|
||||
· {{ t('admin.shippingOrderSchema.autoCreationDraftPending', {
|
||||
state: autoCreationEnabled
|
||||
? t('admin.shippingOrderSchema.autoCreationOn')
|
||||
: t('admin.shippingOrderSchema.autoCreationOff'),
|
||||
}) }}
|
||||
</template>
|
||||
</small>
|
||||
</span>
|
||||
</label>
|
||||
<p class="schema-gate-note">{{ t('admin.shippingOrderSchema.effectiveReservationGate') }}</p>
|
||||
|
||||
<details class="derivation-panel" :open="derivationPanelOpen" @toggle="derivationPanelOpen = ($event.target as HTMLDetailsElement).open">
|
||||
<summary>
|
||||
<strong>{{ t('admin.shippingOrderSchema.derivationRulesTitle') }}</strong>
|
||||
<span>{{ t('admin.shippingOrderSchema.derivationRulesHint') }}</span>
|
||||
</summary>
|
||||
<div class="derivation-toolbar">
|
||||
<button
|
||||
type="button"
|
||||
class="btn-secondary btn-sm"
|
||||
:disabled="simulating || (!draft && !published)"
|
||||
@click="openDerivationSimulate"
|
||||
>
|
||||
{{ t('admin.shippingOrderSchema.derivationSimulate') }}
|
||||
</button>
|
||||
</div>
|
||||
<table class="derivation-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>{{ t('admin.shippingOrderSchema.derivationEnabled') }}</th>
|
||||
<th>{{ t('admin.shippingOrderSchema.derivationSource') }}</th>
|
||||
<th>{{ t('admin.shippingOrderSchema.derivationTarget') }}</th>
|
||||
<th>{{ t('admin.shippingOrderSchema.derivationStrategy') }}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-for="(rule, index) in derivationRules" :key="rule.rule_id">
|
||||
<td>
|
||||
<input
|
||||
type="checkbox"
|
||||
:checked="rule.enabled"
|
||||
:disabled="!draft || saving"
|
||||
@change="onDerivationEnabledChange(index, $event)"
|
||||
>
|
||||
</td>
|
||||
<td><code>{{ rule.source_field_code }}</code></td>
|
||||
<td><code>{{ rule.target_field_code }}</code></td>
|
||||
<td>{{ t('admin.shippingOrderSchema.derivationStrategyCopyIfEmpty') }}</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<p class="derivation-note">{{ t('admin.shippingOrderSchema.derivationRulesNote') }}</p>
|
||||
</details>
|
||||
</section>
|
||||
|
||||
<div class="schema-workbench">
|
||||
<aside class="field-panel">
|
||||
@@ -1337,6 +1508,97 @@ onMounted(async () => {
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<div v-if="simulateOpen" class="impact-overlay" @click.self="simulateOpen = false">
|
||||
<section class="impact-dialog derivation-simulate-dialog">
|
||||
<header>
|
||||
<h2>{{ t('admin.shippingOrderSchema.derivationSimulateTitle') }}</h2>
|
||||
<button type="button" class="btn-ghost btn-sm" @click="simulateOpen = false">{{ t('common.close') }}</button>
|
||||
</header>
|
||||
<p class="simulate-hint">{{ t('admin.shippingOrderSchema.derivationSimulateNoMutate') }}</p>
|
||||
<div class="simulate-mode-row">
|
||||
<label>
|
||||
<input v-model="simulateMode" type="radio" value="history">
|
||||
{{ t('admin.shippingOrderSchema.derivationSimulateModeHistory') }}
|
||||
</label>
|
||||
<label>
|
||||
<input v-model="simulateMode" type="radio" value="inline">
|
||||
{{ t('admin.shippingOrderSchema.derivationSimulateModeInline') }}
|
||||
</label>
|
||||
</div>
|
||||
<label v-if="simulateMode === 'history'" class="simulate-sample">
|
||||
<span>{{ t('admin.shippingOrderSchema.derivationSimulateHistorySample') }}</span>
|
||||
<select v-model="simulateSampleRef" :disabled="simulateSamplesLoading || !simulateSamples.length">
|
||||
<option disabled value="">
|
||||
{{ simulateSamplesLoading
|
||||
? t('admin.shippingOrderSchema.derivationSimulateSamplesLoading')
|
||||
: t('admin.shippingOrderSchema.derivationSimulateSamplesEmpty') }}
|
||||
</option>
|
||||
<option
|
||||
v-for="item in simulateSamples"
|
||||
:key="item.sample_ref"
|
||||
:value="item.sample_ref"
|
||||
>
|
||||
{{ t('admin.shippingOrderSchema.derivationSimulateSampleOption', {
|
||||
id: item.extraction_id,
|
||||
lines: item.line_count,
|
||||
status: item.status,
|
||||
}) }}
|
||||
</option>
|
||||
</select>
|
||||
</label>
|
||||
<label v-else class="simulate-sample">
|
||||
<span>{{ t('admin.shippingOrderSchema.derivationSimulateSample') }}</span>
|
||||
<textarea v-model="simulateSampleJson" rows="8" />
|
||||
</label>
|
||||
<footer>
|
||||
<button type="button" class="btn-secondary" @click="simulateOpen = false">{{ t('common.cancel') }}</button>
|
||||
<button type="button" class="btn-primary" :disabled="simulating" @click="runDerivationSimulate">
|
||||
{{ t('admin.shippingOrderSchema.derivationSimulateRun') }}
|
||||
</button>
|
||||
</footer>
|
||||
<div v-if="simulateResult" class="simulate-result">
|
||||
<p>
|
||||
{{ t('admin.shippingOrderSchema.derivationSimulateSummary', {
|
||||
version: simulateResult.schema_version,
|
||||
checksum: simulateResult.rules_checksum.slice(0, 12),
|
||||
derived: simulateResult.derived_count,
|
||||
skipped: simulateResult.skipped_count,
|
||||
}) }}
|
||||
</p>
|
||||
<div class="simulate-result-scroll" data-testid="derivation-simulate-result-scroll">
|
||||
<table class="derivation-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>#</th>
|
||||
<th>{{ t('admin.shippingOrderSchema.derivationSource') }}</th>
|
||||
<th>{{ t('admin.shippingOrderSchema.derivationBefore') }}</th>
|
||||
<th>{{ t('admin.shippingOrderSchema.derivationAfter') }}</th>
|
||||
<th>{{ t('admin.shippingOrderSchema.derivationResult') }}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-for="row in simulateResult.results" :key="`${row.line_index}-${row.rule_id}`">
|
||||
<td>{{ row.line_index + 1 }}</td>
|
||||
<td>{{ row.before_source ?? '—' }}</td>
|
||||
<td>{{ row.before_target ?? '—' }}</td>
|
||||
<td>{{ row.after_target ?? '—' }}</td>
|
||||
<td>
|
||||
<template v-if="row.status === 'derived'">
|
||||
{{ t('admin.shippingOrderSchema.derivationStatusDerived') }}
|
||||
</template>
|
||||
<template v-else>
|
||||
{{ t('admin.shippingOrderSchema.derivationStatusSkipped', { reason: row.skip_reason || '' }) }}
|
||||
</template>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<p class="muted">{{ t('admin.shippingOrderSchema.derivationSimulateNoMutate') }}</p>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<div v-if="profileImpactOpen && profileImpact" class="impact-overlay" @click.self="profileImpactOpen = false">
|
||||
<section class="impact-dialog">
|
||||
<header>
|
||||
@@ -1430,12 +1692,71 @@ onMounted(async () => {
|
||||
.schema-toolbar span { color: #94a3b8; font-size: 12px; }
|
||||
.toolbar-actions { display: flex; flex-wrap: wrap; gap: 8px; }
|
||||
.schema-workbench { display: grid; height: min(700px, calc(100vh - 280px)); min-height: 540px; grid-template-columns: 320px minmax(0, 1fr); overflow: hidden; border: 1px solid #dfe7ef; border-radius: 10px; background: #fff; box-shadow: 0 1px 2px rgb(15 23 42 / 3%); }
|
||||
.auto-creation-switch { display: flex; align-items: center; gap: 9px; margin: 0 0 16px; border: 1px solid #dbe6ef; border-radius: 8px; background: #fbfdff; padding: 11px 14px; color: #475569; cursor: pointer; }
|
||||
.schema-policy-group {
|
||||
margin: 0 0 18px;
|
||||
border: 1px solid #cfe0ef;
|
||||
border-radius: 10px;
|
||||
background: linear-gradient(180deg, #f8fbff 0%, #f3f8fc 100%);
|
||||
padding: 14px 14px 8px;
|
||||
}
|
||||
.schema-policy-heading {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
.schema-policy-heading h2 { margin: 0; color: #0f172a; font-size: 14px; }
|
||||
.schema-policy-heading p { margin: 4px 0 0; color: #64748b; font-size: 12px; line-height: 1.45; }
|
||||
.schema-policy-badge {
|
||||
flex-shrink: 0;
|
||||
border-radius: 999px;
|
||||
background: #e0f2fe;
|
||||
color: #0369a1;
|
||||
font-size: 11px;
|
||||
padding: 4px 8px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.schema-policy-badge.is-readonly { background: #e2e8f0; color: #475569; }
|
||||
.auto-creation-switch { display: flex; align-items: center; gap: 9px; margin: 0 0 12px; border: 1px solid #dbe6ef; border-radius: 8px; background: #fff; padding: 11px 14px; color: #475569; cursor: pointer; }
|
||||
.auto-creation-switch input { width: 16px; height: 16px; margin: 0; accent-color: #0ea5e9; }
|
||||
.auto-creation-switch span { display: grid; gap: 3px; }
|
||||
.auto-creation-switch strong { color: #334155; font-size: 13px; }
|
||||
.auto-creation-switch small { color: #64748b; font-size: 11px; }
|
||||
.auto-creation-effective { display: block; color: #0f766e; }
|
||||
.schema-gate-note { margin: 0 0 12px; color: #475569; font-size: 12px; line-height: 1.5; }
|
||||
.derivation-panel { margin: 0 0 8px; border: 1px solid #dbe6ef; border-radius: 8px; background: #fff; padding: 12px 14px; }
|
||||
.derivation-panel summary { cursor: pointer; display: grid; gap: 4px; color: #334155; }
|
||||
.derivation-panel summary span { color: #64748b; font-size: 12px; }
|
||||
.derivation-toolbar { display: flex; justify-content: flex-end; margin: 12px 0; }
|
||||
.derivation-table { width: 100%; border-collapse: collapse; font-size: 12px; }
|
||||
.derivation-table th, .derivation-table td { border-bottom: 1px solid #e2e8f0; padding: 8px 6px; text-align: left; vertical-align: middle; }
|
||||
.derivation-note { margin: 10px 0 0; color: #64748b; font-size: 12px; }
|
||||
.simulate-hint { margin: 0 0 10px; color: #64748b; font-size: 12px; }
|
||||
.simulate-mode-row { display: flex; gap: 16px; margin-bottom: 10px; font-size: 13px; color: #334155; }
|
||||
.simulate-mode-row label { display: inline-flex; align-items: center; gap: 6px; }
|
||||
.derivation-simulate-dialog {
|
||||
max-width: 760px;
|
||||
width: min(760px, 92vw);
|
||||
overflow: auto;
|
||||
align-content: start;
|
||||
}
|
||||
.simulate-sample { display: grid; gap: 8px; margin: 12px 0; color: #475569; font-size: 13px; }
|
||||
.simulate-sample textarea,
|
||||
.simulate-sample select { width: 100%; font-size: 12px; border: 1px solid #cbd5e1; border-radius: 8px; padding: 10px; box-sizing: border-box; }
|
||||
.simulate-sample textarea { font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; }
|
||||
.simulate-result { margin-top: 14px; display: grid; gap: 10px; min-width: 0; }
|
||||
.simulate-result-scroll {
|
||||
max-width: 100%;
|
||||
overflow-x: auto;
|
||||
-webkit-overflow-scrolling: touch;
|
||||
border: 1px solid #e2e8f0;
|
||||
border-radius: 8px;
|
||||
}
|
||||
.simulate-result-scroll .derivation-table {
|
||||
margin: 0;
|
||||
min-width: 520px;
|
||||
}
|
||||
.muted { margin: 0; color: #64748b; font-size: 12px; }
|
||||
.field-panel { display: flex; min-width: 0; min-height: 0; flex-direction: column; border-right: 1px solid #e5ebf1; background: #fbfcfe; }
|
||||
.panel-heading { display: flex; align-items: flex-start; justify-content: space-between; gap: 12px; padding: 16px 16px 10px; }
|
||||
@@ -1480,7 +1801,7 @@ onMounted(async () => {
|
||||
.field-title-line { display: flex; min-width: 0; align-items: baseline; gap: 10px; }
|
||||
.field-title-line h2 { overflow: hidden; font-size: 17px; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.field-title-line code { color: #64748b; font-family: ui-monospace, SFMono-Regular, Consolas, monospace; font-size: 11px; }
|
||||
.read-only-badge { border: 1px solid #cbd5e1; border-radius: 999px; background: #f8fafc; padding: 4px 9px; color: #64748b; font-size: 11px; font-weight: 600; }
|
||||
.read-only-badge,
|
||||
.rule-body { display: grid; min-height: 0; flex: 1 1 auto; align-content: start; gap: 12px; overflow-x: hidden; overflow-y: auto; overscroll-behavior: contain; padding: 14px 18px 20px; scrollbar-gutter: stable; }
|
||||
.rule-basics, .rule-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 10px 12px; }
|
||||
.rule-basics .span-two { grid-column: 1 / -1; }
|
||||
|
||||
-339
@@ -1,339 +0,0 @@
|
||||
<!--
|
||||
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>
|
||||
@@ -17,7 +17,6 @@ const shippingRoutes = adminRoutes[0].children?.filter((route) =>
|
||||
|| route.name === 'AdminShippingIdentityRules'
|
||||
|| route.name === 'AdminShippingOrderExtractionRuns'
|
||||
|| route.name === 'AdminShippingAudit'
|
||||
|| route.name === 'AdminShippingReviewSupervision'
|
||||
|| route.name === 'AdminShippingOrderDocumentProfiles',
|
||||
) ?? [];
|
||||
|
||||
@@ -33,7 +32,7 @@ describe('shipping configuration navigation contract', () => {
|
||||
});
|
||||
|
||||
it('registers all shipping configuration subpages with discoverable deep links', () => {
|
||||
// 关键断言:导航注册表与深链路由必须一一对应,避免后台入口不可发现。
|
||||
// 关键断言:导航注册表与深链路由必须一一对应,避免后台入口不可发现;复核监管台已移除。
|
||||
expect(SHIPPING_CONFIG_SUB_MODULE_METAS).toEqual([
|
||||
{ id: 'field_assets', routeName: 'AdminShippingFieldAssets', path: 'shipping-field-assets', labelKey: 'admin.nav.shippingFieldAssets', groupKey: 'admin.nav.shippingOrderRecognition' },
|
||||
{ id: 'order_schema', routeName: 'AdminShippingOrderSchema', path: 'shipping-order-schema', labelKey: 'admin.nav.shippingOrderSchema', groupKey: 'admin.nav.shippingOrderRecognition' },
|
||||
@@ -47,11 +46,11 @@ describe('shipping configuration navigation contract', () => {
|
||||
{ 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(8);
|
||||
expect(shippingRoutes).toHaveLength(7);
|
||||
expect(shippingRoutes.some((route) => route.name === 'AdminShippingReviewSupervision')).toBe(false);
|
||||
});
|
||||
|
||||
it('keeps exactly three ordered accordion groups', () => {
|
||||
@@ -73,7 +72,6 @@ describe('shipping configuration navigation contract', () => {
|
||||
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' }),
|
||||
]);
|
||||
});
|
||||
|
||||
@@ -28,7 +28,6 @@ export type ShippingConfigSubModuleId =
|
||||
| 'identity_rules'
|
||||
| 'order_extraction_runs'
|
||||
| 'shipping_audit'
|
||||
| 'shipping_review_supervision'
|
||||
| 'inventory_fields'
|
||||
| 'connections'
|
||||
| 'inventory_sites'
|
||||
|
||||
@@ -27,13 +27,13 @@ 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; }
|
||||
export interface OrderProfileAnchorRule { anchor_id: string; text: string; aliases?: string[]; match_mode: 'exact' | 'contains'; region?: OrderProfileRelativeRegion | null; position_locked?: boolean; minimum_evidence_level: OrderProfileEvidenceLevel; }
|
||||
export interface OrderProfileFieldRegion { field_id: string; field_code: string; scope: 'header' | 'line'; region: OrderProfileRelativeRegion; extractor_key: OrderProfileExtractorKey; allowed_sources: OrderProfileAllowedSource[]; minimum_evidence_level: OrderProfileEvidenceLevel; target_fields?: Array<{ field_id: string; field_code: string; scope: 'header' | 'line' }>; }
|
||||
export interface OrderProfileOrderFieldLayout { layout_id: string; field_id: string; field_code: string; scope: 'header'; page_scope: 'first_page' | 'all_pages' | 'exact_page'; page_no?: number | null; anchor?: OrderProfileAnchorRule | null; value_region?: OrderProfileAnchorRelativeRegion | null; absolute_value_region?: OrderProfileRelativeRegion | null; fallback_value_region?: OrderProfileRelativeRegion | null; value_mode: 'single_line' | 'multi_line' | 'right_of_anchor' | 'below_anchor'; stop_anchors: OrderProfileAnchorRule[]; normalizer_key?: string | null; required: boolean; minimum_evidence_level: OrderProfileEvidenceLevel; }
|
||||
export interface OrderProfileDraftUnboundOrderFieldLayout { layout_id: string; label: string; page_scope: 'first_page' | 'all_pages' | 'exact_page'; page_no?: number | null; anchor?: OrderProfileAnchorRule | null; value_region?: OrderProfileAnchorRelativeRegion | null; absolute_value_region?: OrderProfileRelativeRegion | null; fallback_value_region?: OrderProfileRelativeRegion | null; value_mode: 'single_line' | 'multi_line' | 'right_of_anchor' | 'below_anchor'; stop_anchors: OrderProfileAnchorRule[]; minimum_evidence_level: OrderProfileEvidenceLevel; }
|
||||
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 OrderProfileTableRegion { region_id: string; page_scope: 'first_page' | 'all_pages' | 'continuation_pages' | 'exact_page'; page_no?: number | null; region: OrderProfileRelativeRegion; /** 逻辑明细起行锚点;默认 customer_po_line_no;line_no 为可识别内部项次亦可绑定。 */ line_start_field_code?: string; 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: OrderProfileDocumentMatchAnchor[]; optional_anchors: OrderProfileDocumentMatchAnchor[]; minimum_score: number; minimum_margin: number; }
|
||||
|
||||
/** 阶段 3 重构前仅用于让旧工作台编译;不能作为 v2 API 请求或持久化定义。 */
|
||||
@@ -199,6 +199,10 @@ export interface OrderProfileVersionFamilySummary {
|
||||
draft_version?: number | null;
|
||||
published_profile_id?: number | null;
|
||||
published_version?: number | null;
|
||||
published_schema_version_id?: number | null;
|
||||
published_schema_version?: number | null;
|
||||
current_schema_version_id?: number | null;
|
||||
current_schema_version?: number | null;
|
||||
latest_profile_id: number;
|
||||
latest_version: number;
|
||||
default_profile_id: number;
|
||||
@@ -403,7 +407,7 @@ export interface OrderProfileBlindTestAvailableSample {
|
||||
}
|
||||
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[] }>;
|
||||
order_fields: Array<{ field_id: string; field_code: string; scope: 'header'; value: unknown; status: 'confirmed' | 'needs_review' | 'unavailable'; page_no: number | null; issues: string[] }>;
|
||||
}
|
||||
|
||||
/** 工作台的本地几何状态;保存前转为 v2 相对区域定义。 */
|
||||
|
||||
@@ -91,9 +91,69 @@ export interface ShippingOrderSchemaVersion {
|
||||
definition?: {
|
||||
fields: ShippingOrderFieldConfig[];
|
||||
auto_creation_policy?: { enabled: boolean };
|
||||
derivation_rules?: ShippingOrderDerivationRule[];
|
||||
derivation_rules_checksum?: string;
|
||||
};
|
||||
}
|
||||
|
||||
/** Schema 级明细字段派生规则(首期仅 copy_if_empty → line_no)。 */
|
||||
export interface ShippingOrderDerivationRule {
|
||||
rule_id: string;
|
||||
enabled: boolean;
|
||||
source_field_code: string;
|
||||
target_field_code: string;
|
||||
strategy: 'copy_if_empty';
|
||||
scope: 'line';
|
||||
}
|
||||
|
||||
export interface ShippingOrderDerivationSimulateRequest {
|
||||
lines?: Array<Record<string, string | number | null | undefined>>;
|
||||
derivation_rules?: ShippingOrderDerivationRule[];
|
||||
/** 可追溯样本;`extraction:<id>` 时后端加载历史明细,可省略 lines。 */
|
||||
sample_ref?: string;
|
||||
}
|
||||
|
||||
export interface ShippingOrderDerivationSimulateSampleItem {
|
||||
sample_ref: string;
|
||||
extraction_id: number;
|
||||
line_count: number;
|
||||
status: string;
|
||||
schema_version_id: number;
|
||||
created_at?: string | null;
|
||||
}
|
||||
|
||||
export interface ShippingOrderDerivationSimulateResult {
|
||||
schema_version_id: number;
|
||||
schema_version: number;
|
||||
schema_version_status: string;
|
||||
rules_checksum: string;
|
||||
rules: ShippingOrderDerivationRule[];
|
||||
derived_count: number;
|
||||
skipped_count: number;
|
||||
results: Array<{
|
||||
line_index: number;
|
||||
rule_id: string;
|
||||
source_field_code: string;
|
||||
target_field_code: string;
|
||||
strategy: string;
|
||||
before_source: unknown;
|
||||
before_target: unknown;
|
||||
after_target: unknown;
|
||||
status: 'derived' | 'skipped';
|
||||
skip_reason: string | null;
|
||||
}>;
|
||||
lines_after: Array<Record<string, unknown>>;
|
||||
sample_ref?: string | null;
|
||||
sample_source?: {
|
||||
kind?: string;
|
||||
extraction_id?: number;
|
||||
schema_version_id?: number;
|
||||
intake_id?: number;
|
||||
status?: string;
|
||||
} | null;
|
||||
mutates_orders: boolean;
|
||||
}
|
||||
|
||||
export interface SchemaVersionActor {
|
||||
id: number;
|
||||
display_name: string;
|
||||
|
||||
@@ -32,11 +32,12 @@ import type {
|
||||
ShippingOrderReviewCase,
|
||||
ShippingOrderReviewDraftWrite,
|
||||
ShippingOrderReviewEvidence,
|
||||
ShippingOrderReviewInventoryCandidatesWrite,
|
||||
ShippingOrderReviewReparseResponse,
|
||||
ShippingOrderReviewRun,
|
||||
ShippingSessionWorkItem,
|
||||
ShippingSessionWorkItemSummary,
|
||||
ShippingSessionWorkItemVersion,
|
||||
ShippingWorkflow,
|
||||
ShippingWorkflowConversationProjection,
|
||||
ShippingWorkflowItem,
|
||||
ShippingTaskUiState,
|
||||
} from '../types/shipping.api.types';
|
||||
|
||||
@@ -290,6 +291,22 @@ export const validateWorkspaceShippingOrderReviewDraft = (caseNo: string, expect
|
||||
{ method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ expected_draft_version: expectedDraftVersion }) },
|
||||
);
|
||||
|
||||
/**
|
||||
* 为复核明细人工选定一个或多个已启用库存源候选。
|
||||
* 核心逻辑:携带 expected_draft_version 乐观锁;服务端写入行级 inventory_routing 后重跑资格校验。
|
||||
* @param caseNo - 复核 Case 编号
|
||||
* @param lineKey - Draft 行稳定标识 line_key
|
||||
* @param payload - 候选编码与强制说明
|
||||
*/
|
||||
export const putWorkspaceShippingOrderReviewInventoryCandidates = (
|
||||
caseNo: string,
|
||||
lineKey: string,
|
||||
payload: ShippingOrderReviewInventoryCandidatesWrite,
|
||||
) => requestJson<ShippingOrderReviewCase>(
|
||||
`/api/workspace/shipping-notice/order-review-cases/${encodeURIComponent(caseNo)}/draft/lines/${encodeURIComponent(lineKey)}/inventory-candidates`,
|
||||
{ method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) },
|
||||
);
|
||||
|
||||
/** 确认当前 PDF 的已校验草稿;服务端以版本和幂等键确保只创建一张 Task。 */
|
||||
export const confirmWorkspaceShippingOrderReviewCase = (
|
||||
caseNo: string,
|
||||
@@ -372,33 +389,91 @@ export const markWorkspaceShippingOrderExtractionRunSeen = (runNo: string) =>
|
||||
jsonPost(),
|
||||
);
|
||||
|
||||
/** 拉取会话级 PDF 工作项工作台;右侧「本次处理」唯一列表事实源。 */
|
||||
export const listWorkspaceShippingSessionWorkItems = (
|
||||
/**
|
||||
* 列出会话开放 Workflow 与 Items(版面阶段 Item 已存在)。
|
||||
* @param conversationId - 聊天会话 ID
|
||||
* @param options.signal - 可选中止信号(轮询超时)
|
||||
*/
|
||||
export const listWorkspaceShippingWorkflows = (
|
||||
conversationId: string,
|
||||
options?: { open_only?: boolean; signal?: AbortSignal },
|
||||
options?: { 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()}`,
|
||||
return requestJson<ShippingWorkflowConversationProjection>(
|
||||
`/api/workspace/shipping-notice/workflows?${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`,
|
||||
/**
|
||||
* 读取单个 Workflow 详情(含 Items 摘要)。
|
||||
* @param workflowNo - Workflow 业务编号
|
||||
*/
|
||||
export const getWorkspaceShippingWorkflow = (
|
||||
workflowNo: string,
|
||||
options?: { signal?: AbortSignal },
|
||||
) =>
|
||||
requestJson<ShippingWorkflow>(
|
||||
`/api/workspace/shipping-notice/workflows/${encodeURIComponent(workflowNo)}`,
|
||||
{ signal: options?.signal },
|
||||
);
|
||||
|
||||
/** 关闭(取消)会话 PDF 工作项;需携带 reason 与可选乐观锁版本。 */
|
||||
export const closeWorkspaceShippingSessionWorkItem = (
|
||||
/**
|
||||
* 读取单个 WorkflowItem 详情(默认含 events)。
|
||||
* @param itemNo - Item 业务编号
|
||||
* @param options.include_events - 是否附带事件时间线;默认 true
|
||||
* @param options.signal - 可选中止信号
|
||||
*/
|
||||
export const getWorkspaceShippingWorkflowItem = (
|
||||
itemNo: string,
|
||||
options?: { signal?: AbortSignal; include_events?: boolean },
|
||||
) => {
|
||||
const params = new URLSearchParams();
|
||||
if (options?.include_events === false) {
|
||||
params.set('include_events', 'false');
|
||||
} else if (options?.include_events === true) {
|
||||
params.set('include_events', 'true');
|
||||
}
|
||||
const query = params.toString();
|
||||
return requestJson<ShippingWorkflowItem>(
|
||||
`/api/workspace/shipping-notice/workflow-items/${encodeURIComponent(itemNo)}${query ? `?${query}` : ''}`,
|
||||
{ signal: options?.signal },
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* 取消单个 WorkflowItem;须填写 reason,可选乐观锁。
|
||||
* @param itemNo - Item 业务编号
|
||||
* @param payload.reason - 取消原因(必填)
|
||||
* @param payload.expected_lock_version - 可选乐观锁版本
|
||||
*/
|
||||
export const cancelWorkspaceShippingWorkflowItem = (
|
||||
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),
|
||||
);
|
||||
) =>
|
||||
requestJson<{ item: ShippingWorkflowItem }>(
|
||||
`/api/workspace/shipping-notice/workflow-items/${encodeURIComponent(itemNo)}/cancel`,
|
||||
jsonPost(payload),
|
||||
);
|
||||
|
||||
/**
|
||||
* 对单个 WorkflowItem 发起重试/重新识别。
|
||||
* 核心逻辑:POST reparse;后端可能并行补齐,客户端契约先行对齐。
|
||||
* @param itemNo - Item 业务编号
|
||||
* @param payload.reason - 重识别原因(必填)
|
||||
* @param payload.comment - 可选补充说明
|
||||
*/
|
||||
export const reparseWorkspaceShippingWorkflowItem = (
|
||||
itemNo: string,
|
||||
payload: { reason: string; comment?: string | null },
|
||||
) =>
|
||||
requestJson<{ item: ShippingWorkflowItem; reused?: boolean }>(
|
||||
`/api/workspace/shipping-notice/workflow-items/${encodeURIComponent(itemNo)}/reparse`,
|
||||
jsonPost({
|
||||
reason: payload.reason,
|
||||
comment: payload.comment ?? undefined,
|
||||
}),
|
||||
);
|
||||
|
||||
/** 按会话恢复订单抽取 Run,刷新页面后不依赖聊天 SSE 历史。 */
|
||||
export const listWorkspaceShippingOrderExtractionRuns = (
|
||||
|
||||
@@ -2,18 +2,18 @@
|
||||
|
||||
* features/chat/components/ChatViewContent.vue
|
||||
|
||||
* 用途:对话页主区域,组合侧栏、消息列表、输入栏、货代会话任务摘要与内置浏览器。
|
||||
* 用途:对话页主区域,组合侧栏、消息列表、输入栏、货代会话 Workflow 时间线与内置浏览器。
|
||||
|
||||
* 依赖:ChatSidebar、ChatMessageList、ChatInputBar、ShippingSessionSummaryPanel、chat.context。
|
||||
* 依赖:ChatSidebar、ChatMessageList、ChatInputBar、ShippingWorkflowTimeline、chat.context。
|
||||
|
||||
* 逻辑:本文件只做页面结构编排;货代 Chat 仅上传/进度通知,履约写操作不在本页;
|
||||
* 右侧「本次处理」由 conversationId 驱动 session-work-items,extractionRunNo 仅作进度装饰。
|
||||
* 右侧「本次处理」由 conversationId 驱动 Workflow projection,extractionRunNo 仅作进度装饰。
|
||||
|
||||
*/
|
||||
|
||||
<script setup lang="ts">
|
||||
|
||||
import { computed, ref, watch } from 'vue';
|
||||
import { computed, provide, ref, watch } from 'vue';
|
||||
|
||||
import { useRoute } from 'vue-router';
|
||||
|
||||
@@ -31,7 +31,7 @@ import ChatMobileHeader from '@/features/chat/components/ChatMobileHeader.vue';
|
||||
|
||||
import ChatBrowserPanel from '@/features/chat/components/ChatBrowserPanel.vue';
|
||||
|
||||
import ShippingSessionSummaryPanel from '@/features/chat/components/ShippingSessionSummaryPanel.vue';
|
||||
import ShippingWorkflowTimeline from '@/features/chat/components/shipping/ShippingWorkflowTimeline.vue';
|
||||
|
||||
import TrainingWorkspacePanel from '@/features/chat/components/TrainingWorkspacePanel.vue';
|
||||
|
||||
@@ -47,6 +47,11 @@ import { matchesTrainingAgent } from '@/features/chat/training/trainingWorkspace
|
||||
|
||||
import { agentHasIntentUiProfile } from '@/shared/utils/agent-registry.utils';
|
||||
|
||||
import {
|
||||
SHIPPING_WORKFLOW_KEY,
|
||||
useShippingNoticeWorkflow,
|
||||
} from '@/features/chat/shipping/useShippingNoticeWorkflow';
|
||||
|
||||
import type { MaintenanceDevice } from '@/features/maintenance/types/ledger.types';
|
||||
|
||||
import type { MaintenanceRecord } from '@/features/maintenance/types/record.types';
|
||||
@@ -77,6 +82,13 @@ type MaintenanceRecordPanelCommand = {
|
||||
|
||||
const page = useChatPageContext();
|
||||
|
||||
const shippingWorkflow = useShippingNoticeWorkflow({
|
||||
conversationId: () => page.conversationId,
|
||||
refreshTrigger: () => page.workflowRefreshTrigger,
|
||||
});
|
||||
provide(SHIPPING_WORKFLOW_KEY, shippingWorkflow);
|
||||
|
||||
|
||||
const route = useRoute();
|
||||
|
||||
const isOrderReviewMode = computed(() => route.query.mode === 'order-review' && typeof route.query.run_no === 'string' && route.query.run_no.length > 0);
|
||||
@@ -139,7 +151,7 @@ const activeExtractionRunNo = computed(() => {
|
||||
|
||||
|
||||
|
||||
const showShippingSessionSummary = computed(() => (
|
||||
const showShippingWorkflowTimeline = computed(() => (
|
||||
page.isShippingNoticeAgent
|
||||
&& Boolean(
|
||||
page.conversationId
|
||||
@@ -655,26 +667,11 @@ watch(() => page.currentAgentId, () => {
|
||||
|
||||
|
||||
|
||||
<ShippingSessionSummaryPanel
|
||||
|
||||
v-if="showShippingSessionSummary"
|
||||
|
||||
<ShippingWorkflowTimeline
|
||||
v-if="showShippingWorkflowTimeline"
|
||||
:conversation-id="page.conversationId"
|
||||
|
||||
:conversation-workspace="page.shippingConversationWorkspace"
|
||||
|
||||
:active-batch-no="page.activeShippingBatchNo"
|
||||
|
||||
:batch-summary="page.shippingBatchSummary"
|
||||
|
||||
:batch-tasks="page.shippingBatchTasks"
|
||||
|
||||
:active-task-detail="page.activeShippingTaskDetail"
|
||||
|
||||
:extraction-run-no="activeExtractionRunNo"
|
||||
|
||||
:refresh-trigger="page.sessionWorkItemsRefreshTrigger"
|
||||
|
||||
:refresh-trigger="page.workflowRefreshTrigger"
|
||||
:controller="shippingWorkflow"
|
||||
/>
|
||||
|
||||
|
||||
|
||||
@@ -1,174 +0,0 @@
|
||||
/**
|
||||
* 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,720 +0,0 @@
|
||||
/**
|
||||
* features/chat/components/ShippingSessionSummaryPanel.vue
|
||||
* 用途:聊天页右侧「本次处理」面板——以会话级 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 {
|
||||
closeWorkspaceShippingSessionWorkItem,
|
||||
getWorkspaceShippingOrderExtractionRun,
|
||||
listWorkspaceShippingSessionWorkItemVersions,
|
||||
listWorkspaceShippingSessionWorkItems,
|
||||
markWorkspaceShippingOrderReviewNonOrder,
|
||||
reparseWorkspaceShippingOrderReviewDocument,
|
||||
type ShippingBatchSummary,
|
||||
type ShippingConversationWorkspace,
|
||||
type ShippingTaskDetail,
|
||||
type ShippingTaskSummary,
|
||||
} from '@/features/chat/api/shipping.api';
|
||||
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,仅用于 Run 级 handling_items 装饰,不驱动 PDF 列表。 */
|
||||
extractionRunNo?: string | null;
|
||||
/** 父级递增以触发立即刷新(终态/重识别/会话恢复后)。 */
|
||||
refreshTrigger?: number;
|
||||
}>();
|
||||
|
||||
const { t, te, locale } = useI18n();
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
const msg = useMessage();
|
||||
const collapsed = ref(false);
|
||||
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 FOREGROUND_POLL_MS = 2000;
|
||||
const BACKGROUND_POLL_MS = 8000;
|
||||
|
||||
/**
|
||||
* 按页面可见性选择工作项轮询间隔。
|
||||
*/
|
||||
function resolveWorkItemsPollMs(): number {
|
||||
if (typeof document !== 'undefined' && document.visibilityState === 'hidden') {
|
||||
return BACKGROUND_POLL_MS;
|
||||
}
|
||||
return FOREGROUND_POLL_MS;
|
||||
}
|
||||
|
||||
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 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,
|
||||
}));
|
||||
|
||||
/**
|
||||
* 解析 Run 级处理事项标题。
|
||||
*/
|
||||
function handlingTitle(category: string): string {
|
||||
const key = `chat.shippingOrderExtractionHandling.category.${category}`;
|
||||
return te(key) ? t(key) : category;
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析原因码文案。
|
||||
*/
|
||||
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;
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析工作项生命周期状态文案。
|
||||
*/
|
||||
function lifecycleStatusLabel(status: string): string {
|
||||
const key = `chat.shippingSessionWorkItem.status.${status}`;
|
||||
return te(key) ? t(key) : status;
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析工作项关闭原因文案。
|
||||
*/
|
||||
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;
|
||||
}
|
||||
|
||||
/**
|
||||
* 格式化 updated_at 为「更新于 HH:mm」。
|
||||
*/
|
||||
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 [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);
|
||||
})(),
|
||||
]);
|
||||
if (controller.signal.aborted) return;
|
||||
workbench.value = summaryResponse;
|
||||
extractionRun.value = runResponse;
|
||||
if (!closedExpanded.value) {
|
||||
closedExpanded.value = false;
|
||||
}
|
||||
} catch {
|
||||
/* 右侧失败不打断聊天 */
|
||||
} finally {
|
||||
if (workItemsRequestController === controller) {
|
||||
workItemsRequestController = null;
|
||||
}
|
||||
workItemsLoading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
function stopWorkItemsPolling() {
|
||||
if (workItemsTimer) clearTimeout(workItemsTimer);
|
||||
workItemsTimer = null;
|
||||
workItemsRequestController?.abort();
|
||||
workItemsRequestController = null;
|
||||
workItemsPollGeneration += 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* 可见性感知的工作项轮询;前台 2s,后台 8s。
|
||||
*/
|
||||
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);
|
||||
}
|
||||
|
||||
/**
|
||||
* 打开版本历史面板并拉取时间线。
|
||||
*/
|
||||
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: runNo,
|
||||
};
|
||||
if (caseNo) query.case = caseNo;
|
||||
await router.push({
|
||||
name: 'Chat',
|
||||
params: { agentId: String(route.params.agentId || '') },
|
||||
query,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 按 Run 级处理事项受影响对象跳转。
|
||||
*/
|
||||
async function openAffectedRef(target: ShippingHandlingRefTarget, runNo?: string) {
|
||||
if (target.kind === 'task') {
|
||||
await router.push({
|
||||
name: 'workspace-shipping-tasks',
|
||||
params: { taskNo: target.taskNo },
|
||||
});
|
||||
return;
|
||||
}
|
||||
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>
|
||||
<aside
|
||||
class="flex w-72 shrink-0 flex-col border-l border-default bg-surface shadow-[-8px_0_24px_rgba(15,23,42,0.04)]"
|
||||
data-testid="shipping-session-summary"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
class="flex w-full items-center justify-between gap-2 border-b border-default px-3 py-3 text-left"
|
||||
@click="collapsed = !collapsed"
|
||||
>
|
||||
<div class="min-w-0">
|
||||
<div class="text-sm font-semibold text-primary">
|
||||
{{ t('chat.shippingSessionSummary.title') }}
|
||||
</div>
|
||||
<div class="mt-0.5 text-xs text-secondary">
|
||||
{{ t('chat.shippingSessionSummary.pdfCount', { count: processSummary.total || displayOpenItems.length }) }}
|
||||
</div>
|
||||
</div>
|
||||
<ChevronDown v-if="!collapsed" class="h-4 w-4 shrink-0 text-muted" />
|
||||
<ChevronRight v-else class="h-4 w-4 shrink-0 text-muted" />
|
||||
</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 }) }}
|
||||
</span>
|
||||
<span class="rounded-md bg-sky-50 px-2 py-0.5 text-sky-700 dark:bg-sky-950/40 dark:text-sky-200">
|
||||
{{ t('chat.shippingSessionSummary.running', { count: processSummary.running }) }}
|
||||
</span>
|
||||
<span
|
||||
v-if="processSummary.needsHuman > 0"
|
||||
class="rounded-md bg-amber-50 px-2 py-0.5 text-amber-700 dark:bg-amber-950/40 dark:text-amber-200"
|
||||
>
|
||||
{{ t('chat.shippingSessionSummary.needsHuman', { count: processSummary.needsHuman }) }}
|
||||
</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"
|
||||
>
|
||||
{{ t('chat.shippingSessionSummary.failed', { count: processSummary.failed }) }}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div v-if="!displayOpenItems.length && !closedItems.length" class="text-xs text-muted">
|
||||
{{ workItemsLoading
|
||||
? t('chat.shippingSessionWorkItem.loading')
|
||||
: t('chat.shippingSessionSummary.empty') }}
|
||||
</div>
|
||||
|
||||
<ul v-if="displayOpenItems.length" class="space-y-2" data-testid="shipping-session-open-items">
|
||||
<li
|
||||
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">
|
||||
{{ 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 }) }}
|
||||
</div>
|
||||
</div>
|
||||
<span
|
||||
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',
|
||||
}"
|
||||
>
|
||||
{{ lifecycleStatusLabel(String(item.lifecycle_status || '')) }}
|
||||
</span>
|
||||
</div>
|
||||
<div v-if="item.version_replaced" class="mt-1 text-[11px] text-secondary">
|
||||
{{ t('chat.shippingSessionWorkItem.versionReplaced') }}
|
||||
</div>
|
||||
<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="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"
|
||||
:disabled="actionBusyItemNo === item.item_no"
|
||||
data-testid="shipping-session-action-review"
|
||||
@click="openManualReview(item)"
|
||||
>
|
||||
<ExternalLink class="h-3 w-3" />
|
||||
{{ t('chat.shippingSessionWorkItem.enterManualReview') }}
|
||||
</button>
|
||||
<button
|
||||
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"
|
||||
data-testid="shipping-session-action-versions"
|
||||
@click="openVersionHistory(item)"
|
||||
>
|
||||
{{ 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>
|
||||
@@ -2,7 +2,8 @@
|
||||
* features/chat/components/messages/ShippingMatchResultCard.vue
|
||||
* 用途:出货 Agent 对话区与工作台共用的库存匹配/缺口结果卡片。
|
||||
* 依赖:shipping.api.types、vue-i18n。
|
||||
* 逻辑:由 Chat 消息区和 ShippingNoticeView 传入匹配结果;本组件只负责结构化展示状态、缺口与操作按钮。
|
||||
* 逻辑:由 Chat 消息区和 ShippingNoticeView 传入匹配结果;本组件只负责结构化展示;
|
||||
* line_status 含 ok/partial/shortage/conflict(含 multi_file_conflict 别名),经 i18n rowStatus 映射。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import { useI18n } from 'vue-i18n';
|
||||
@@ -33,6 +34,9 @@ const rowStatusLabel = (status?: string | null) => {
|
||||
if (status === 'ok') return t('chat.shippingNoticeUi.rowStatus.ok');
|
||||
if (status === 'partial') return t('chat.shippingNoticeUi.rowStatus.partial');
|
||||
if (status === 'shortage') return t('chat.shippingNoticeUi.rowStatus.shortage');
|
||||
if (status === 'conflict' || status === 'multi_file_conflict') {
|
||||
return t('chat.shippingNoticeUi.rowStatus.conflict');
|
||||
}
|
||||
return status || '-';
|
||||
};
|
||||
|
||||
|
||||
+167
@@ -0,0 +1,167 @@
|
||||
<!--
|
||||
features/chat/components/shipping-review/ReviewBuildEligibilityPanel.vue
|
||||
用途:展示建单前资格摘要(can_build、阻断原因、行级 Reservation 与库存候选)。
|
||||
依赖:vue-i18n、ShippingOrderReviewBuildEligibility 类型。
|
||||
逻辑:ShippingOrderReviewView 传入 draft.build_eligibility;只读展示,不发起写请求。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import type { ShippingOrderReviewBuildEligibility } from '@/features/chat/types/shipping.api.types';
|
||||
|
||||
const props = defineProps<{
|
||||
eligibility: ShippingOrderReviewBuildEligibility | null;
|
||||
}>();
|
||||
|
||||
const { t, te } = useI18n();
|
||||
|
||||
/**
|
||||
* 解析建单资格状态文案。
|
||||
*/
|
||||
function statusLabel(status: string): string {
|
||||
const key = `chat.shippingOrderReview.buildEligibility.status.${status}`;
|
||||
return te(key) ? t(key) : status;
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析行级阻断原因文案。
|
||||
*/
|
||||
function blockReasonLabel(reason?: string | null): string {
|
||||
const normalized = String(reason || '').trim();
|
||||
if (!normalized) return '—';
|
||||
const key = `chat.shippingOrderReview.buildEligibility.blockReasons.${normalized}`;
|
||||
return te(key) ? t(key) : normalized;
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析路由状态文案。
|
||||
*/
|
||||
function routingStatusLabel(status?: string | null): string {
|
||||
const normalized = String(status || '').trim();
|
||||
if (!normalized) return '—';
|
||||
const key = `chat.shippingOrderReview.buildEligibility.routingStatus.${normalized}`;
|
||||
return te(key) ? t(key) : normalized;
|
||||
}
|
||||
|
||||
/** 未满足建单资格的明细行。 */
|
||||
const blockedLines = computed(() =>
|
||||
(props.eligibility?.line_projections || []).filter((line) => line.can_build === false),
|
||||
);
|
||||
|
||||
/** 阻断摘要:按 block_reason 聚合行数。 */
|
||||
const blockingSummary = computed(() => {
|
||||
const counts = new Map<string, number>();
|
||||
for (const line of blockedLines.value) {
|
||||
const reason = String(line.block_reason || 'unknown').trim() || 'unknown';
|
||||
counts.set(reason, (counts.get(reason) || 0) + 1);
|
||||
}
|
||||
return [...counts.entries()].map(([reason, count]) => ({ reason, count }));
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section
|
||||
v-if="eligibility"
|
||||
class="rounded-xl border border-slate-200 bg-white p-4 shadow-sm dark:border-slate-800 dark:bg-slate-900"
|
||||
data-testid="review-build-eligibility-panel"
|
||||
>
|
||||
<header class="mb-3 flex flex-wrap items-center justify-between gap-2">
|
||||
<div>
|
||||
<h2 class="text-sm font-semibold">{{ t('chat.shippingOrderReview.buildEligibility.title') }}</h2>
|
||||
<p class="mt-0.5 text-xs text-slate-500 dark:text-slate-400">
|
||||
{{ t('chat.shippingOrderReview.buildEligibility.subtitle') }}
|
||||
</p>
|
||||
</div>
|
||||
<span
|
||||
class="rounded-full px-2.5 py-1 text-xs font-medium"
|
||||
:class="eligibility.can_build
|
||||
? 'bg-emerald-100 text-emerald-800 dark:bg-emerald-950 dark:text-emerald-100'
|
||||
: 'bg-amber-100 text-amber-900 dark:bg-amber-950 dark:text-amber-100'"
|
||||
data-testid="review-build-eligibility-badge"
|
||||
>
|
||||
{{
|
||||
eligibility.can_build
|
||||
? t('chat.shippingOrderReview.buildEligibility.canBuildYes')
|
||||
: t('chat.shippingOrderReview.buildEligibility.canBuildNo')
|
||||
}}
|
||||
</span>
|
||||
</header>
|
||||
|
||||
<dl class="grid gap-2 text-xs text-slate-600 dark:text-slate-400 sm:grid-cols-2">
|
||||
<div>
|
||||
<dt class="inline font-medium">{{ t('chat.shippingOrderReview.buildEligibility.statusLabel') }}:</dt>
|
||||
<dd class="inline">{{ statusLabel(eligibility.status) }}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
|
||||
<div
|
||||
v-if="!eligibility.can_build && blockingSummary.length"
|
||||
class="mt-3 rounded-lg border border-amber-200 bg-amber-50 p-3 text-xs text-amber-950 dark:border-amber-900 dark:bg-amber-950/30 dark:text-amber-100"
|
||||
data-testid="review-build-eligibility-blocking-summary"
|
||||
>
|
||||
<div class="font-semibold">{{ t('chat.shippingOrderReview.buildEligibility.blockingSummary') }}</div>
|
||||
<ul class="mt-1 list-disc space-y-0.5 pl-4">
|
||||
<li v-for="item in blockingSummary" :key="item.reason">
|
||||
{{ blockReasonLabel(item.reason) }}
|
||||
<span class="text-amber-800 dark:text-amber-200">× {{ item.count }}</span>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div v-if="eligibility.line_projections.length" class="mt-3 space-y-2">
|
||||
<div class="text-xs font-semibold text-slate-500 dark:text-slate-400">
|
||||
{{ t('chat.shippingOrderReview.buildEligibility.lineProjections') }}
|
||||
</div>
|
||||
<article
|
||||
v-for="line in eligibility.line_projections"
|
||||
:key="String(line.line_key || line.line_index)"
|
||||
class="rounded-lg border border-slate-200 p-3 text-xs dark:border-slate-700"
|
||||
:data-testid="`review-build-eligibility-line-${line.line_key || line.line_index}`"
|
||||
>
|
||||
<div class="flex flex-wrap items-center justify-between gap-2">
|
||||
<span class="font-medium">
|
||||
{{ t('chat.shippingOrderReview.line', { index: (line.line_index ?? 0) + 1 }) }}
|
||||
</span>
|
||||
<span
|
||||
class="rounded-full px-2 py-0.5 text-[11px]"
|
||||
:class="line.can_build
|
||||
? 'bg-emerald-100 text-emerald-800 dark:bg-emerald-950 dark:text-emerald-100'
|
||||
: 'bg-rose-100 text-rose-800 dark:bg-rose-950 dark:text-rose-100'"
|
||||
>
|
||||
{{
|
||||
line.can_build
|
||||
? t('chat.shippingOrderReview.buildEligibility.lineCanBuild')
|
||||
: t('chat.shippingOrderReview.buildEligibility.lineBlocked')
|
||||
}}
|
||||
</span>
|
||||
</div>
|
||||
<dl class="mt-2 grid gap-1 sm:grid-cols-2">
|
||||
<div>
|
||||
<dt class="inline text-slate-500">{{ t('chat.shippingOrderReview.buildEligibility.reservation') }}:</dt>
|
||||
<dd class="inline font-mono">{{ line.effective_reservation_id || '—' }}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt class="inline text-slate-500">{{ t('chat.shippingOrderReview.buildEligibility.routingStatusLabel') }}:</dt>
|
||||
<dd class="inline">{{ routingStatusLabel(line.routing_status) }}</dd>
|
||||
</div>
|
||||
<div v-if="line.inventory_source_hint" class="sm:col-span-2">
|
||||
<dt class="inline text-slate-500">{{ t('chat.shippingOrderReview.buildEligibility.sourceHint') }}:</dt>
|
||||
<dd class="inline">{{ line.inventory_source_hint }}</dd>
|
||||
</div>
|
||||
<div v-if="line.candidate_inventory_source_codes?.length" class="sm:col-span-2">
|
||||
<dt class="inline text-slate-500">{{ t('chat.shippingOrderReview.buildEligibility.candidates') }}:</dt>
|
||||
<dd class="inline font-mono">{{ line.candidate_inventory_source_codes.join(', ') }}</dd>
|
||||
</div>
|
||||
<div v-if="line.block_reason" class="sm:col-span-2">
|
||||
<dt class="inline text-slate-500">{{ t('chat.shippingOrderReview.buildEligibility.blockReason') }}:</dt>
|
||||
<dd class="inline">{{ blockReasonLabel(line.block_reason) }}</dd>
|
||||
</div>
|
||||
<div v-if="line.selection_mode === 'manual' && line.manual_reason" class="sm:col-span-2">
|
||||
<dt class="inline text-slate-500">{{ t('chat.shippingOrderReview.buildEligibility.manualReason') }}:</dt>
|
||||
<dd class="inline">{{ line.manual_reason }}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
</article>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
+176
@@ -0,0 +1,176 @@
|
||||
<!--
|
||||
features/chat/components/shipping-review/ReviewInventoryCandidatesPanel.vue
|
||||
用途:为库存路由未决的明细行提供多选候选源与强制原因的人工提交表单。
|
||||
依赖:vue-i18n、ShippingOrderReviewBuildEligibilityLineProjection 类型。
|
||||
逻辑:规则候选优先;零候选时回退到已启用库存源列表;emit submit 由 composable 写 API。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { reactive } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import type { ShippingOrderReviewBuildEligibilityLineProjection } from '@/features/chat/types/shipping.api.types';
|
||||
|
||||
const props = defineProps<{
|
||||
lines: ShippingOrderReviewBuildEligibilityLineProjection[];
|
||||
/** 已启用库存源;规则零候选时作为可选列表 */
|
||||
enabledSourceCodes?: string[];
|
||||
editable?: boolean;
|
||||
saving?: boolean;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
(e: 'submit', payload: { lineKey: string; sourceCodes: string[]; reason: string }): void;
|
||||
}>();
|
||||
|
||||
const { t, te } = useI18n();
|
||||
|
||||
/** 每行本地表单状态:已选候选与原因。 */
|
||||
const formState = reactive<Record<string, { selected: string[]; reason: string }>>({});
|
||||
|
||||
/**
|
||||
* 行级可选源:规则候选优先,否则回退已启用库存源。
|
||||
*/
|
||||
function selectableCodes(line: ShippingOrderReviewBuildEligibilityLineProjection): string[] {
|
||||
const candidates = (line.candidate_inventory_source_codes || [])
|
||||
.map((code) => String(code || '').trim().toUpperCase())
|
||||
.filter(Boolean);
|
||||
if (candidates.length) return candidates;
|
||||
return (props.enabledSourceCodes || [])
|
||||
.map((code) => String(code || '').trim().toUpperCase())
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取或初始化某行的表单状态。
|
||||
*/
|
||||
function getForm(line: ShippingOrderReviewBuildEligibilityLineProjection) {
|
||||
const key = String(line.line_key || (line.line_index ?? ''));
|
||||
if (!formState[key]) {
|
||||
const ruleCandidates = (line.candidate_inventory_source_codes || []).map(String);
|
||||
formState[key] = {
|
||||
selected: [...ruleCandidates],
|
||||
reason: String(line.manual_reason || ''),
|
||||
};
|
||||
}
|
||||
return formState[key];
|
||||
}
|
||||
|
||||
/**
|
||||
* 切换候选编码勾选状态。
|
||||
*/
|
||||
function toggleCode(line: ShippingOrderReviewBuildEligibilityLineProjection, code: string) {
|
||||
const form = getForm(line);
|
||||
const index = form.selected.indexOf(code);
|
||||
if (index >= 0) form.selected.splice(index, 1);
|
||||
else form.selected.push(code);
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析阻断原因展示文案。
|
||||
*/
|
||||
function blockReasonLabel(reason?: string | null): string {
|
||||
const normalized = String(reason || '').trim();
|
||||
if (!normalized) return '';
|
||||
const key = `chat.shippingOrderReview.buildEligibility.blockReasons.${normalized}`;
|
||||
return te(key) ? t(key) : normalized;
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验并提交指定行的人工候选选择。
|
||||
*/
|
||||
function submitLine(line: ShippingOrderReviewBuildEligibilityLineProjection) {
|
||||
const lineKey = String(line.line_key || '').trim();
|
||||
if (!lineKey) return;
|
||||
const form = getForm(line);
|
||||
emit('submit', {
|
||||
lineKey,
|
||||
sourceCodes: [...form.selected],
|
||||
reason: form.reason.trim(),
|
||||
});
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section
|
||||
v-if="lines.length"
|
||||
class="rounded-xl border border-sky-200 bg-sky-50/60 p-4 shadow-sm dark:border-sky-900 dark:bg-sky-950/20"
|
||||
data-testid="review-inventory-candidates-panel"
|
||||
>
|
||||
<header class="mb-3">
|
||||
<h2 class="text-sm font-semibold">{{ t('chat.shippingOrderReview.inventoryCandidates.title') }}</h2>
|
||||
<p class="mt-0.5 text-xs text-slate-600 dark:text-slate-400">
|
||||
{{ t('chat.shippingOrderReview.inventoryCandidates.subtitle') }}
|
||||
</p>
|
||||
</header>
|
||||
|
||||
<article
|
||||
v-for="line in lines"
|
||||
:key="String(line.line_key || line.line_index)"
|
||||
class="mb-3 rounded-lg border border-slate-200 bg-white p-3 last:mb-0 dark:border-slate-700 dark:bg-slate-900"
|
||||
:data-testid="`review-inventory-candidates-line-${line.line_key || line.line_index}`"
|
||||
>
|
||||
<div class="flex flex-wrap items-center justify-between gap-2 text-sm">
|
||||
<span class="font-medium">
|
||||
{{ t('chat.shippingOrderReview.line', { index: (line.line_index ?? 0) + 1 }) }}
|
||||
<span v-if="line.effective_reservation_id" class="ml-1 font-mono text-xs text-slate-500">
|
||||
{{ line.effective_reservation_id }}
|
||||
</span>
|
||||
</span>
|
||||
<span v-if="line.block_reason" class="text-xs text-amber-800 dark:text-amber-200">
|
||||
{{ blockReasonLabel(line.block_reason) }}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div v-if="selectableCodes(line).length" class="mt-3">
|
||||
<div class="text-xs font-medium text-slate-600 dark:text-slate-300">
|
||||
{{
|
||||
(line.candidate_inventory_source_codes || []).length
|
||||
? t('chat.shippingOrderReview.inventoryCandidates.selectSources')
|
||||
: t('chat.shippingOrderReview.inventoryCandidates.selectEnabledSources')
|
||||
}}
|
||||
</div>
|
||||
<div class="mt-2 flex flex-wrap gap-2">
|
||||
<label
|
||||
v-for="code in selectableCodes(line)"
|
||||
:key="code"
|
||||
class="inline-flex cursor-pointer items-center gap-1.5 rounded border border-slate-200 px-2 py-1 text-xs dark:border-slate-600"
|
||||
>
|
||||
<input
|
||||
type="checkbox"
|
||||
:checked="getForm(line).selected.includes(code)"
|
||||
:disabled="!editable || saving"
|
||||
@change="toggleCode(line, code)"
|
||||
>
|
||||
<span class="font-mono">{{ code }}</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
<p v-else class="mt-2 text-xs text-rose-600 dark:text-rose-300">
|
||||
{{ t('chat.shippingOrderReview.inventoryCandidates.noEnabledSources') }}
|
||||
</p>
|
||||
|
||||
<label class="mt-3 block text-xs font-medium text-slate-600 dark:text-slate-300">
|
||||
{{ t('chat.shippingOrderReview.inventoryCandidates.reasonLabel') }}
|
||||
<textarea
|
||||
:value="getForm(line).reason"
|
||||
:disabled="!editable || saving"
|
||||
rows="2"
|
||||
class="mt-1 w-full rounded-md border border-slate-300 bg-white px-2 py-1.5 text-xs dark:border-slate-600 dark:bg-slate-950"
|
||||
:placeholder="t('chat.shippingOrderReview.inventoryCandidates.reasonPlaceholder')"
|
||||
@input="getForm(line).reason = ($event.target as HTMLTextAreaElement).value"
|
||||
/>
|
||||
</label>
|
||||
|
||||
<div class="mt-3 flex justify-end">
|
||||
<button
|
||||
type="button"
|
||||
class="rounded bg-sky-600 px-3 py-1.5 text-xs text-white disabled:opacity-50"
|
||||
data-testid="review-inventory-candidates-submit"
|
||||
:disabled="!editable || saving || !getForm(line).selected.length || !getForm(line).reason.trim()"
|
||||
@click="submitLine(line)"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.inventoryCandidates.submit') }}
|
||||
</button>
|
||||
</div>
|
||||
</article>
|
||||
</section>
|
||||
</template>
|
||||
@@ -0,0 +1,259 @@
|
||||
<!--
|
||||
features/chat/components/shipping-review/ReviewLineNoOverrideDialog.vue
|
||||
用途:复核页编辑内部项次 line_no 时的强制原因弹窗(覆盖须审计)。
|
||||
依赖:vue-i18n、dialog-overlay / dialog-panel。
|
||||
逻辑:ShippingOrderReviewView 拦截 line_no 输入变更;确认后携带 reasonCode/reasonText 调用 patchLine。
|
||||
确认仅发出事件,不自行关闭;父组件成功后再关,失败时保留原因选择与说明。
|
||||
打开时聚焦原因选择框,Tab 焦点陷阱在弹窗内,关闭后恢复先前焦点。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, nextTick, onBeforeUnmount, ref, watch } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
|
||||
/** 与后端 LINE_NO_OVERRIDE_REASON_CODES 对齐的稳定原因码。 */
|
||||
const LINE_NO_OVERRIDE_REASON_CODES = [
|
||||
'recognition_error',
|
||||
'customer_line_exception',
|
||||
'business_correction',
|
||||
'other',
|
||||
] as const;
|
||||
|
||||
type LineNoOverrideReasonCode = (typeof LINE_NO_OVERRIDE_REASON_CODES)[number];
|
||||
|
||||
/** 内部项次覆盖确认载荷;供复核页 confirm 事件消费。 */
|
||||
export type LineNoOverridePayload = {
|
||||
value: string;
|
||||
reasonCode: LineNoOverrideReasonCode;
|
||||
reasonText: string;
|
||||
};
|
||||
|
||||
interface Props {
|
||||
modelValue: boolean;
|
||||
/** 用户拟写入的新项次值(已在输入框中编辑)。 */
|
||||
pendingValue: string;
|
||||
confirmLoading?: boolean;
|
||||
}
|
||||
|
||||
const props = withDefaults(defineProps<Props>(), {
|
||||
confirmLoading: false,
|
||||
});
|
||||
|
||||
const emit = defineEmits<{
|
||||
(e: 'update:modelValue', value: boolean): void;
|
||||
(e: 'confirm', payload: LineNoOverridePayload): void;
|
||||
(e: 'cancel'): void;
|
||||
}>();
|
||||
|
||||
const { t } = useI18n();
|
||||
const reasonCode = ref<LineNoOverrideReasonCode>('recognition_error');
|
||||
const reasonText = ref('');
|
||||
const reasonMissing = ref(false);
|
||||
const textMissing = ref(false);
|
||||
const panelRef = ref<HTMLElement | null>(null);
|
||||
const reasonSelectRef = ref<HTMLSelectElement | null>(null);
|
||||
let previouslyFocused: HTMLElement | null = null;
|
||||
|
||||
const FOCUSABLE_SELECTOR = [
|
||||
'a[href]',
|
||||
'button:not([disabled])',
|
||||
'textarea:not([disabled])',
|
||||
'input:not([disabled])',
|
||||
'select:not([disabled])',
|
||||
'[tabindex]:not([tabindex="-1"])',
|
||||
].join(',');
|
||||
|
||||
const title = computed(() => t('chat.shippingOrderReview.lineNoOverrideDialog.title'));
|
||||
const impact = computed(() => t('chat.shippingOrderReview.lineNoOverrideDialog.impact'));
|
||||
|
||||
/**
|
||||
* 原因码展示文案。
|
||||
* @param code - 后端允许的覆盖原因码
|
||||
*/
|
||||
const reasonLabel = (code: string) =>
|
||||
t(`chat.shippingOrderReview.lineNoOverrideDialog.reasons.${code}`);
|
||||
|
||||
/** 收集弹窗内可聚焦控件,供 Tab 陷阱使用。 */
|
||||
const focusableNodes = (): HTMLElement[] => {
|
||||
if (!panelRef.value) return [];
|
||||
return Array.from(panelRef.value.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR))
|
||||
.filter((node) => !node.hasAttribute('disabled') && node.getAttribute('aria-hidden') !== 'true');
|
||||
};
|
||||
|
||||
/** 关闭弹窗并同步 v-model。 */
|
||||
const closeDialog = () => {
|
||||
emit('update:modelValue', false);
|
||||
};
|
||||
|
||||
const handleCancel = () => {
|
||||
if (props.confirmLoading) return;
|
||||
emit('cancel');
|
||||
closeDialog();
|
||||
};
|
||||
|
||||
/**
|
||||
* 校验原因码与「其他」说明后提交覆盖。
|
||||
* 核心逻辑:other 强制补充说明;确认后不关闭,由父组件在保存成功后再关,失败时保留表单。
|
||||
*/
|
||||
const handleConfirm = () => {
|
||||
if (props.confirmLoading) return;
|
||||
reasonMissing.value = false;
|
||||
textMissing.value = false;
|
||||
if (!reasonCode.value) {
|
||||
reasonMissing.value = true;
|
||||
return;
|
||||
}
|
||||
const trimmed = reasonText.value.trim();
|
||||
if (reasonCode.value === 'other' && !trimmed) {
|
||||
textMissing.value = true;
|
||||
return;
|
||||
}
|
||||
emit('confirm', {
|
||||
value: String(props.pendingValue ?? '').trim(),
|
||||
reasonCode: reasonCode.value,
|
||||
reasonText: trimmed,
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Escape 关闭;Tab / Shift+Tab 在弹窗内循环,阻止焦点逃逸到背景页。
|
||||
*/
|
||||
const onKeydown = (event: KeyboardEvent) => {
|
||||
if (!props.modelValue) return;
|
||||
if (event.key === 'Escape' && !props.confirmLoading) {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
handleCancel();
|
||||
return;
|
||||
}
|
||||
if (event.key !== 'Tab') return;
|
||||
const nodes = focusableNodes();
|
||||
const first = nodes[0];
|
||||
const last = nodes[nodes.length - 1];
|
||||
// noUncheckedIndexedAccess:空数组或下标越界时 first/last 可能为 undefined。
|
||||
if (!first || !last) {
|
||||
event.preventDefault();
|
||||
return;
|
||||
}
|
||||
const active = document.activeElement as HTMLElement | null;
|
||||
const inside = Boolean(active && panelRef.value?.contains(active));
|
||||
if (event.shiftKey) {
|
||||
if (!inside || active === first) {
|
||||
event.preventDefault();
|
||||
last.focus();
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (!inside || active === last) {
|
||||
event.preventDefault();
|
||||
first.focus();
|
||||
}
|
||||
};
|
||||
|
||||
watch(
|
||||
() => props.modelValue,
|
||||
async (open, wasOpen) => {
|
||||
if (typeof document === 'undefined') return;
|
||||
if (open && !wasOpen) {
|
||||
reasonCode.value = 'recognition_error';
|
||||
reasonText.value = '';
|
||||
reasonMissing.value = false;
|
||||
textMissing.value = false;
|
||||
previouslyFocused = document.activeElement instanceof HTMLElement
|
||||
? document.activeElement
|
||||
: null;
|
||||
document.addEventListener('keydown', onKeydown, true);
|
||||
await nextTick();
|
||||
(reasonSelectRef.value || focusableNodes()[0])?.focus();
|
||||
return;
|
||||
}
|
||||
if (!open && wasOpen) {
|
||||
document.removeEventListener('keydown', onKeydown, true);
|
||||
const restoreTarget = previouslyFocused;
|
||||
previouslyFocused = null;
|
||||
await nextTick();
|
||||
restoreTarget?.focus?.();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
if (typeof document !== 'undefined') {
|
||||
document.removeEventListener('keydown', onKeydown, true);
|
||||
}
|
||||
});
|
||||
</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-line-no-override-dialog"
|
||||
@click.self="handleCancel"
|
||||
>
|
||||
<div ref="panelRef" class="dialog-panel w-full max-w-md space-y-4 p-5">
|
||||
<header>
|
||||
<h2 class="text-base font-semibold text-primary" id="review-line-no-override-title">{{ title }}</h2>
|
||||
<p class="mt-2 text-sm text-secondary">{{ impact }}</p>
|
||||
<p class="mt-2 text-sm text-primary">
|
||||
{{ t('chat.shippingOrderReview.lineNoOverrideDialog.newValue', { value: pendingValue || '—' }) }}
|
||||
</p>
|
||||
</header>
|
||||
|
||||
<label class="block space-y-1 text-sm">
|
||||
<span class="text-secondary">{{ t('chat.shippingOrderReview.lineNoOverrideDialog.reasonCodeLabel') }}</span>
|
||||
<select
|
||||
ref="reasonSelectRef"
|
||||
v-model="reasonCode"
|
||||
class="select-field w-full text-sm"
|
||||
data-testid="review-line-no-reason-code"
|
||||
:disabled="confirmLoading"
|
||||
:aria-labelledby="'review-line-no-override-title'"
|
||||
@change="reasonMissing = false"
|
||||
>
|
||||
<option v-for="code in LINE_NO_OVERRIDE_REASON_CODES" :key="code" :value="code">
|
||||
{{ reasonLabel(code) }}
|
||||
</option>
|
||||
</select>
|
||||
<p v-if="reasonMissing" class="text-xs text-rose-600 dark:text-rose-400">
|
||||
{{ t('chat.shippingOrderReview.lineNoOverrideDialog.reasonCodeRequired') }}
|
||||
</p>
|
||||
</label>
|
||||
|
||||
<label class="block space-y-1 text-sm">
|
||||
<span class="text-secondary">{{ t('chat.shippingOrderReview.lineNoOverrideDialog.reasonTextLabel') }}</span>
|
||||
<textarea
|
||||
v-model="reasonText"
|
||||
rows="3"
|
||||
class="input-field w-full resize-y text-sm"
|
||||
:placeholder="t('chat.shippingOrderReview.lineNoOverrideDialog.reasonTextPlaceholder')"
|
||||
data-testid="review-line-no-reason-text"
|
||||
:disabled="confirmLoading"
|
||||
@input="textMissing = false"
|
||||
/>
|
||||
<p v-if="textMissing" class="text-xs text-rose-600 dark:text-rose-400">
|
||||
{{ t('chat.shippingOrderReview.lineNoOverrideDialog.reasonTextRequired') }}
|
||||
</p>
|
||||
</label>
|
||||
|
||||
<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="btn-primary btn-sm"
|
||||
:disabled="confirmLoading"
|
||||
data-testid="review-line-no-override-submit"
|
||||
@click="handleConfirm"
|
||||
>
|
||||
{{ confirmLoading ? t('chat.shippingOrderReview.saving') : t('chat.shippingOrderReview.lineNoOverrideDialog.confirm') }}
|
||||
</button>
|
||||
</footer>
|
||||
</div>
|
||||
</div>
|
||||
</Teleport>
|
||||
</template>
|
||||
+18
-17
@@ -1,16 +1,16 @@
|
||||
<!--
|
||||
features/chat/components/shipping-review/ReviewVersionHistoryPanel.vue
|
||||
用途:复核页工作项版本历史时间线;支持只读跳转至历史 Case。
|
||||
依赖:vue-i18n、ShippingSessionWorkItemVersion 类型。
|
||||
逻辑:ShippingOrderReviewView 传入 versions;emit select 供父级切换 case_no。
|
||||
用途:复核页 WorkflowItem 版本历史时间线;支持只读跳转至历史 Case。
|
||||
依赖:vue-i18n、ShippingWorkflowItemVersion 类型。
|
||||
逻辑:ShippingOrderReviewView 传入 versions(由 WorkflowItem 派生);emit select 供父级切换 case_no。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import type { ShippingSessionWorkItemVersion } from '@/features/chat/types/shipping.api.types';
|
||||
import type { ShippingWorkflowItemVersion } from '@/features/chat/types/shipping.api.types';
|
||||
|
||||
const props = defineProps<{
|
||||
itemNo?: string | null;
|
||||
versions: ShippingSessionWorkItemVersion[];
|
||||
versions: ShippingWorkflowItemVersion[];
|
||||
loading?: boolean;
|
||||
activeCaseNo?: string | null;
|
||||
}>();
|
||||
@@ -43,7 +43,7 @@ function formatTime(value?: string | null): string {
|
||||
/**
|
||||
* 跳转至指定版本;历史版本以只读模式打开。
|
||||
*/
|
||||
function selectVersion(version: ShippingSessionWorkItemVersion) {
|
||||
function selectVersion(version: ShippingWorkflowItemVersion) {
|
||||
const caseNo = String(version.case_no || '').trim();
|
||||
if (!caseNo) return;
|
||||
emit('select', caseNo, Boolean(version.is_readonly));
|
||||
@@ -65,12 +65,16 @@ function selectVersion(version: ShippingSessionWorkItemVersion) {
|
||||
</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>
|
||||
<div v-if="loading" class="py-4 text-sm text-slate-500">{{ t('chat.shippingWorkflow.loading') }}</div>
|
||||
<template v-else>
|
||||
<p class="mb-2 text-xs text-slate-500 dark:text-slate-400">
|
||||
{{ t('chat.shippingWorkflow.versionHistoryNote') }}
|
||||
</p>
|
||||
<p v-if="!versions.length" class="py-4 text-sm text-slate-500">
|
||||
{{ t('chat.shippingSessionWorkItem.noVersions') }}
|
||||
</p>
|
||||
|
||||
<ol v-else class="space-y-2">
|
||||
<ol v-else class="space-y-2">
|
||||
<li
|
||||
v-for="version in versions"
|
||||
:key="version.case_no"
|
||||
@@ -84,7 +88,7 @@ function selectVersion(version: ShippingSessionWorkItemVersion) {
|
||||
<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: '?' }) }}
|
||||
{{ version.version_label || t('chat.shippingWorkflow.versionLabel', { version: version.version_no || '?' }) }}
|
||||
</span>
|
||||
<span
|
||||
v-if="version.is_current"
|
||||
@@ -100,7 +104,7 @@ function selectVersion(version: ShippingSessionWorkItemVersion) {
|
||||
</span>
|
||||
</div>
|
||||
<p class="mt-1 truncate text-xs text-slate-500 dark:text-slate-400">
|
||||
{{ version.document_filename || version.case_no }}
|
||||
{{ version.run_no || version.case_no }}
|
||||
</p>
|
||||
</div>
|
||||
<button
|
||||
@@ -124,12 +128,9 @@ function selectVersion(version: ShippingSessionWorkItemVersion) {
|
||||
<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>
|
||||
</template>
|
||||
</section>
|
||||
</template>
|
||||
+83
@@ -0,0 +1,83 @@
|
||||
/**
|
||||
* features/chat/components/shipping-review/ReviewWorkflowProgressPanel.spec.ts
|
||||
* 用途:确认后自动进度面板节点状态与无货代上传按钮契约。
|
||||
* 依赖:vitest、@vue/test-utils、vue-i18n stub、RouterLink stub。
|
||||
* 逻辑:按 lifecycle_status 断言 done/active/pending;待登记时展示下一步说明与任务处理台入口。
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { mount } from '@vue/test-utils';
|
||||
import { createI18n } from 'vue-i18n';
|
||||
import ReviewWorkflowProgressPanel from './ReviewWorkflowProgressPanel.vue';
|
||||
import type { ShippingWorkflowItem } from '@/features/chat/types/shipping.api.types';
|
||||
|
||||
const messages = {
|
||||
en: {
|
||||
chat: {
|
||||
shippingOrderReview: {
|
||||
workflowProgress: {
|
||||
title: 'Auto progress',
|
||||
subtitle: 'Stops at waiting for manual upload registration',
|
||||
polling: 'Refreshing…',
|
||||
taskNo: 'Task {taskNo}',
|
||||
openTaskWorkbench: 'Open task workbench to register',
|
||||
noUploadHint: 'Register credentials in the task workbench',
|
||||
nextStepsManualUpload:
|
||||
'Next: download Excel → upload on freight platform → submit evidence and receipt',
|
||||
nodes: {
|
||||
building_order: 'Create task',
|
||||
inventory_matching: 'Match inventory',
|
||||
generating_excel: 'Generate Excel',
|
||||
manual_upload_pending: 'Awaiting upload registration',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* 挂载进度面板。
|
||||
*/
|
||||
function mountPanel(item: Partial<ShippingWorkflowItem> | null, extras?: { taskNo?: string; polling?: boolean }) {
|
||||
const i18n = createI18n({ legacy: false, locale: 'en', messages });
|
||||
return mount(ReviewWorkflowProgressPanel, {
|
||||
props: {
|
||||
item: item as ShippingWorkflowItem | null,
|
||||
taskNo: extras?.taskNo ?? 'SN-1',
|
||||
polling: extras?.polling ?? true,
|
||||
},
|
||||
global: {
|
||||
plugins: [i18n],
|
||||
stubs: {
|
||||
RouterLink: {
|
||||
props: ['to'],
|
||||
template: '<a :href="JSON.stringify(to)"><slot /></a>',
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
describe('ReviewWorkflowProgressPanel', () => {
|
||||
it('marks earlier nodes done and current active', () => {
|
||||
const wrapper = mountPanel({ lifecycle_status: 'generating_excel', current_stage: 'generating_excel' });
|
||||
expect(wrapper.get('[data-testid="review-workflow-progress-node-building_order"]').attributes('data-state')).toBe('done');
|
||||
expect(wrapper.get('[data-testid="review-workflow-progress-node-inventory_matching"]').attributes('data-state')).toBe('done');
|
||||
expect(wrapper.get('[data-testid="review-workflow-progress-node-generating_excel"]').attributes('data-state')).toBe('active');
|
||||
expect(wrapper.get('[data-testid="review-workflow-progress-node-manual_upload_pending"]').attributes('data-state')).toBe('pending');
|
||||
expect(wrapper.find('[data-testid="review-open-task-workbench"]').exists()).toBe(false);
|
||||
expect(wrapper.find('[data-testid="review-manual-upload-next-steps"]').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it('shows manual_upload_pending next steps and task workbench link', () => {
|
||||
const wrapper = mountPanel({ lifecycle_status: 'manual_upload_pending' }, { polling: false });
|
||||
expect(wrapper.get('[data-testid="review-workflow-progress-node-manual_upload_pending"]').attributes('data-state')).toBe('active');
|
||||
expect(wrapper.get('[data-testid="review-manual-upload-next-steps"]').text()).toContain('download Excel');
|
||||
const link = wrapper.get('[data-testid="review-open-task-workbench"]');
|
||||
expect(link.text()).toContain('Open task workbench to register');
|
||||
expect(link.attributes('href')).toContain('workspace-shipping-my-tasks');
|
||||
expect(link.attributes('href')).toContain('SN-1');
|
||||
expect(wrapper.find('[data-testid="review-upload-freight"]').exists()).toBe(false);
|
||||
expect(wrapper.find('[data-testid="review-workflow-progress-polling"]').exists()).toBe(false);
|
||||
});
|
||||
});
|
||||
+150
@@ -0,0 +1,150 @@
|
||||
<!--
|
||||
features/chat/components/shipping-review/ReviewWorkflowProgressPanel.vue
|
||||
用途:复核确认后展示自动进度节点:创建任务 → 库存匹配 → 生成 Excel → 待人工上传登记。
|
||||
依赖:vue-i18n、vue-router、ShippingWorkflowItem。
|
||||
逻辑:ShippingOrderReviewView 在确认后挂载;按 lifecycle_status / current_stage 点亮节点;
|
||||
无货代上传按钮;待登记时说明下一步并提供跳转任务处理台入口;
|
||||
轮询由父级 composable 负责。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { RouterLink } from 'vue-router';
|
||||
import type { ShippingWorkflowItem } from '@/features/chat/types/shipping.api.types';
|
||||
|
||||
const props = defineProps<{
|
||||
item: ShippingWorkflowItem | null;
|
||||
taskNo?: string | null;
|
||||
polling?: boolean;
|
||||
}>();
|
||||
|
||||
const { t } = useI18n();
|
||||
|
||||
/** 进度节点稳定键;与 WorkflowItem lifecycle 对齐。 */
|
||||
type ReviewProgressNodeKey =
|
||||
| 'building_order'
|
||||
| 'inventory_matching'
|
||||
| 'generating_excel'
|
||||
| 'manual_upload_pending';
|
||||
|
||||
const NODES: ReviewProgressNodeKey[] = [
|
||||
'building_order',
|
||||
'inventory_matching',
|
||||
'generating_excel',
|
||||
'manual_upload_pending',
|
||||
];
|
||||
|
||||
/**
|
||||
* 将 Item 生命周期映射到进度节点索引(0..3);未知时按建单中。
|
||||
*/
|
||||
function nodeIndex(status?: string | null): number {
|
||||
const normalized = String(status || '').trim();
|
||||
const idx = NODES.indexOf(normalized as ReviewProgressNodeKey);
|
||||
if (idx >= 0) return idx;
|
||||
if (['closed', 'cancelled'].includes(normalized)) return NODES.length - 1;
|
||||
if (['pending_review', 'queued', 'layout_parsing', 'extracting'].includes(normalized)) return -1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
const activeIndex = computed(() =>
|
||||
nodeIndex(props.item?.lifecycle_status || props.item?.current_stage),
|
||||
);
|
||||
|
||||
const showTaskWorkbenchLink = computed(() => {
|
||||
const status = String(props.item?.lifecycle_status || props.item?.current_stage || '').trim();
|
||||
return status === 'manual_upload_pending' && Boolean(String(props.taskNo || '').trim());
|
||||
});
|
||||
|
||||
/**
|
||||
* 任务处理台路由:带 task_no,便于直接定位待登记任务。
|
||||
*/
|
||||
const taskWorkbenchTo = computed(() => ({
|
||||
name: 'workspace-shipping-my-tasks',
|
||||
query: {
|
||||
task_no: String(props.taskNo || '').trim(),
|
||||
},
|
||||
}));
|
||||
|
||||
/**
|
||||
* 节点展示态:done / active / pending。
|
||||
*/
|
||||
function nodeState(index: number): 'done' | 'active' | 'pending' {
|
||||
const current = activeIndex.value;
|
||||
if (current < 0) return 'pending';
|
||||
if (index < current) return 'done';
|
||||
if (index === current) return 'active';
|
||||
return 'pending';
|
||||
}
|
||||
</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-workflow-progress-panel"
|
||||
>
|
||||
<header class="mb-3 flex flex-wrap items-center justify-between gap-2">
|
||||
<div>
|
||||
<h2 class="text-sm font-semibold">{{ t('chat.shippingOrderReview.workflowProgress.title') }}</h2>
|
||||
<p class="mt-0.5 text-xs text-slate-500 dark:text-slate-400">
|
||||
{{ t('chat.shippingOrderReview.workflowProgress.subtitle') }}
|
||||
</p>
|
||||
</div>
|
||||
<span
|
||||
v-if="polling"
|
||||
class="text-xs text-sky-700 dark:text-sky-300"
|
||||
data-testid="review-workflow-progress-polling"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.workflowProgress.polling') }}
|
||||
</span>
|
||||
</header>
|
||||
|
||||
<div
|
||||
v-if="taskNo"
|
||||
class="mb-3 flex flex-wrap items-center gap-2 text-xs text-slate-600 dark:text-slate-400"
|
||||
>
|
||||
<span>{{ t('chat.shippingOrderReview.workflowProgress.taskNo', { taskNo }) }}</span>
|
||||
<RouterLink
|
||||
v-if="showTaskWorkbenchLink"
|
||||
:to="taskWorkbenchTo"
|
||||
class="inline-flex items-center rounded-lg bg-brand-600 px-2.5 py-1 text-xs font-medium text-white hover:bg-brand-700"
|
||||
data-testid="review-open-task-workbench"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.workflowProgress.openTaskWorkbench') }}
|
||||
</RouterLink>
|
||||
</div>
|
||||
|
||||
<ol class="space-y-2" data-testid="review-workflow-progress-nodes">
|
||||
<li
|
||||
v-for="(key, index) in NODES"
|
||||
:key="key"
|
||||
class="flex items-center gap-3 rounded-lg border px-3 py-2 text-sm"
|
||||
:class="{
|
||||
'border-emerald-200 bg-emerald-50 text-emerald-900 dark:border-emerald-900 dark:bg-emerald-950/40 dark:text-emerald-100': nodeState(index) === 'done',
|
||||
'border-sky-200 bg-sky-50 text-sky-950 dark:border-sky-900 dark:bg-sky-950/40 dark:text-sky-100': nodeState(index) === 'active',
|
||||
'border-slate-200 bg-slate-50 text-slate-500 dark:border-slate-800 dark:bg-slate-950/40 dark:text-slate-400': nodeState(index) === 'pending',
|
||||
}"
|
||||
:data-testid="`review-workflow-progress-node-${key}`"
|
||||
:data-state="nodeState(index)"
|
||||
>
|
||||
<span class="inline-flex h-6 w-6 shrink-0 items-center justify-center rounded-full border text-xs font-semibold">
|
||||
{{ index + 1 }}
|
||||
</span>
|
||||
<span>{{ t(`chat.shippingOrderReview.workflowProgress.nodes.${key}`) }}</span>
|
||||
</li>
|
||||
</ol>
|
||||
|
||||
<p
|
||||
v-if="showTaskWorkbenchLink"
|
||||
class="mt-3 rounded-lg border border-amber-200 bg-amber-50 px-3 py-2 text-xs text-amber-900 dark:border-amber-900/60 dark:bg-amber-950/40 dark:text-amber-100"
|
||||
data-testid="review-manual-upload-next-steps"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.workflowProgress.nextStepsManualUpload') }}
|
||||
</p>
|
||||
<p
|
||||
v-else
|
||||
class="mt-3 text-xs text-slate-500 dark:text-slate-400"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.workflowProgress.noUploadHint') }}
|
||||
</p>
|
||||
</section>
|
||||
</template>
|
||||
@@ -1,11 +1,12 @@
|
||||
/**
|
||||
* features/chat/components/shipping/ShippingOrderExtractionCard.vue
|
||||
* 用途:聊天主区批次进度卡——摘要计数、Run 级处理事项、当前文件阶段、健康提醒与动作。
|
||||
* 依赖:订单抽取 Run 状态卡 DTO、orderExtractionProgressDisplay、vue-router、vue-i18n。
|
||||
* 逻辑:事实一律来自后端 handling_items / primary_notice;右侧 ShippingSessionSummaryPanel 承接逐 PDF 明细。
|
||||
* 依赖:订单抽取 Run 状态卡 DTO、orderExtractionProgressDisplay、Workflow 计数投影、vue-router、vue-i18n。
|
||||
* 逻辑:有 Workflow 投影时优先展示统一 counts;否则回退 handling_items / primary_notice;
|
||||
* 右侧 ShippingWorkflowTimeline 承接逐 PDF 明细;禁止发明百分比与 ETA。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import { computed, ref } from 'vue';
|
||||
import { computed, inject, ref } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { useRoute, useRouter } from 'vue-router';
|
||||
import { CircleCheck, CircleX, LoaderCircle, TriangleAlert } from 'lucide-vue-next';
|
||||
@@ -13,6 +14,7 @@ import type {
|
||||
ShippingOrderExtractionHandlingItemState,
|
||||
ShippingOrderExtractionState,
|
||||
} from '../../types/chat.types';
|
||||
import type { ShippingWorkflowItemCounts } from '../../types/shipping.api.types';
|
||||
import {
|
||||
formatOrderExtractionElapsed,
|
||||
resolveOrderExtractionUserStageKey,
|
||||
@@ -22,6 +24,7 @@ import {
|
||||
type ShippingHandlingAffectedRef,
|
||||
type ShippingHandlingRefTarget,
|
||||
} from '../../shipping/orderExtractionHandlingRefs';
|
||||
import { SHIPPING_WORKFLOW_KEY } from '../../shipping/useShippingNoticeWorkflow';
|
||||
|
||||
const props = defineProps<{
|
||||
state: ShippingOrderExtractionState;
|
||||
@@ -29,6 +32,8 @@ const props = defineProps<{
|
||||
retrying?: boolean;
|
||||
refreshing?: boolean;
|
||||
cancelling?: boolean;
|
||||
/** 可选:父级传入的 Workflow 计数;优先于 Run summary。 */
|
||||
workflowSummary?: ShippingWorkflowItemCounts | null;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
@@ -42,6 +47,49 @@ const route = useRoute();
|
||||
const router = useRouter();
|
||||
const confirmCancelOpen = ref(false);
|
||||
const cancelReason = ref('');
|
||||
const injectedWorkflow = inject(SHIPPING_WORKFLOW_KEY, null);
|
||||
|
||||
/**
|
||||
* 统一计数:优先 props.workflowSummary,其次 inject 的 Workflow.counts,最后回退 Run summary。
|
||||
*/
|
||||
const unifiedCounts = computed(() => {
|
||||
const fromProp = props.workflowSummary;
|
||||
if (fromProp && Number(fromProp.total || 0) > 0) return fromProp;
|
||||
const fromInject = injectedWorkflow?.workflow.value?.counts;
|
||||
if (fromInject && Number(fromInject.total || 0) > 0) return fromInject;
|
||||
return null;
|
||||
});
|
||||
|
||||
const displaySummary = computed(() => {
|
||||
const counts = unifiedCounts.value;
|
||||
if (!counts) return props.state.summary;
|
||||
return {
|
||||
totalDocuments: counts.total,
|
||||
processingDocuments: counts.processing,
|
||||
pendingDocuments: 0,
|
||||
completedDocuments: counts.completed,
|
||||
reviewRequiredDocuments: counts.pending_review,
|
||||
failedDocuments: counts.failed,
|
||||
cancelledDocuments: 0,
|
||||
candidateCount: props.state.summary.candidateCount,
|
||||
openedExistingCount: props.state.summary.openedExistingCount,
|
||||
};
|
||||
});
|
||||
|
||||
const workflowStageLabel = computed(() => {
|
||||
const stage = String(injectedWorkflow?.workflow.value?.current_stage || '').trim();
|
||||
if (!stage) return '';
|
||||
const key = `chat.shippingWorkflow.itemStatus.${stage}`;
|
||||
return te(key) ? t(key) : stage;
|
||||
});
|
||||
|
||||
const workflowLastActivityLabel = computed(() => {
|
||||
const raw = injectedWorkflow?.workflow.value?.last_activity_at;
|
||||
if (!raw) return '';
|
||||
const date = new Date(String(raw));
|
||||
if (Number.isNaN(date.getTime())) return '';
|
||||
return date.toLocaleString();
|
||||
});
|
||||
|
||||
const handlingItems = computed(() => props.state.handlingItems || []);
|
||||
|
||||
@@ -50,10 +98,10 @@ 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));
|
||||
const opened = Math.max(0, Number(displaySummary.value.openedExistingCount || 0));
|
||||
if (opened <= 0) return false;
|
||||
const review = Math.max(0, Number(props.state.summary.reviewRequiredDocuments || 0));
|
||||
const failed = Math.max(0, Number(props.state.summary.failedDocuments || 0));
|
||||
const review = Math.max(0, Number(displaySummary.value.reviewRequiredDocuments || 0));
|
||||
const failed = Math.max(0, Number(displaySummary.value.failedDocuments || 0));
|
||||
return review === 0 && failed === 0;
|
||||
});
|
||||
|
||||
@@ -163,7 +211,7 @@ const activityKey = computed(() => {
|
||||
|
||||
const showRetry = computed(() => (
|
||||
props.state.availableActions.includes('retry_failed_attachments')
|
||||
|| props.state.summary.failedDocuments > 0
|
||||
|| displaySummary.value.failedDocuments > 0
|
||||
));
|
||||
const showRefresh = computed(() => props.state.availableActions.includes('refresh_status'));
|
||||
const showCancel = computed(() => (
|
||||
@@ -319,31 +367,40 @@ function openCancelConfirm() {
|
||||
<div class="text-sm font-medium">{{ compactLine }}</div>
|
||||
|
||||
<div
|
||||
v-if="state.summary.totalDocuments > 0"
|
||||
v-if="displaySummary.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>{{ t('chat.shippingOrderExtractionSummary.total', { count: displaySummary.totalDocuments }) }}</span>
|
||||
<span v-if="displaySummary.processingDocuments > 0">
|
||||
{{ t('chat.shippingOrderExtractionSummary.processing', { count: displaySummary.processingDocuments }) }}
|
||||
</span>
|
||||
<span v-if="state.summary.pendingDocuments > 0">
|
||||
{{ t('chat.shippingOrderExtractionSummary.pending', { count: state.summary.pendingDocuments }) }}
|
||||
<span v-if="displaySummary.pendingDocuments > 0">
|
||||
{{ t('chat.shippingOrderExtractionSummary.pending', { count: displaySummary.pendingDocuments }) }}
|
||||
</span>
|
||||
<span v-if="state.summary.completedDocuments > 0">
|
||||
{{ t('chat.shippingOrderExtractionSummary.completed', { count: state.summary.completedDocuments }) }}
|
||||
<span v-if="displaySummary.completedDocuments > 0">
|
||||
{{ t('chat.shippingOrderExtractionSummary.completed', { count: displaySummary.completedDocuments }) }}
|
||||
</span>
|
||||
<span v-if="state.summary.reviewRequiredDocuments > 0">
|
||||
{{ t('chat.shippingOrderExtractionSummary.reviewRequired', { count: state.summary.reviewRequiredDocuments }) }}
|
||||
<span v-if="displaySummary.reviewRequiredDocuments > 0">
|
||||
{{ t('chat.shippingOrderExtractionSummary.reviewRequired', { count: displaySummary.reviewRequiredDocuments }) }}
|
||||
</span>
|
||||
<span v-if="state.summary.failedDocuments > 0">
|
||||
{{ t('chat.shippingOrderExtractionSummary.failed', { count: state.summary.failedDocuments }) }}
|
||||
<span v-if="displaySummary.failedDocuments > 0">
|
||||
{{ t('chat.shippingOrderExtractionSummary.failed', { count: displaySummary.failedDocuments }) }}
|
||||
</span>
|
||||
<span v-if="(state.summary.cancelledDocuments || 0) > 0">
|
||||
{{ t('chat.shippingOrderExtractionSummary.cancelled', { count: state.summary.cancelledDocuments }) }}
|
||||
<span v-if="(displaySummary.cancelledDocuments || 0) > 0">
|
||||
{{ t('chat.shippingOrderExtractionSummary.cancelled', { count: displaySummary.cancelledDocuments }) }}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="workflowStageLabel || workflowLastActivityLabel"
|
||||
class="mt-1 text-[11px] opacity-80"
|
||||
data-testid="shipping-order-extraction-workflow-meta"
|
||||
>
|
||||
<span v-if="workflowStageLabel">{{ workflowStageLabel }}</span>
|
||||
<span v-if="workflowLastActivityLabel" class="ml-1">· {{ workflowLastActivityLabel }}</span>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="handlingItems.length"
|
||||
class="mt-2 space-y-1.5"
|
||||
|
||||
+113
@@ -0,0 +1,113 @@
|
||||
/**
|
||||
* features/chat/components/shipping/ShippingWorkflowItemDetailDrawer.spec.ts
|
||||
* 用途:覆盖单个 WorkflowItem 详情抽屉的文件名/阶段/事件展示与取消/重识别入口。
|
||||
* 依赖:Vitest、Vue Test Utils、vue-i18n。
|
||||
* 逻辑:断言打开时展示 filename 与事件;终态隐藏取消;emit close/cancel/reparse。
|
||||
* Teleport 到 body 后通过 document.querySelector 读取抽屉根节点。
|
||||
*/
|
||||
import { mount } from '@vue/test-utils';
|
||||
import { afterEach, describe, expect, it } from 'vitest';
|
||||
import { createI18n } from 'vue-i18n';
|
||||
import chatZhCn from '@/locales/zh-CN/chat.json';
|
||||
import ShippingWorkflowItemDetailDrawer from './ShippingWorkflowItemDetailDrawer.vue';
|
||||
import type { ShippingWorkflowItem } from '../../types/shipping.api.types';
|
||||
|
||||
const i18n = createI18n({
|
||||
legacy: false,
|
||||
locale: 'zh-CN',
|
||||
messages: { 'zh-CN': { chat: chatZhCn } },
|
||||
});
|
||||
|
||||
function buildItem(patch: Partial<ShippingWorkflowItem> = {}): ShippingWorkflowItem {
|
||||
return {
|
||||
item_no: 'SWI-DETAIL',
|
||||
workflow_no: 'SNWF-1',
|
||||
conversation_id: 'conv-1',
|
||||
root_document_id: 1,
|
||||
current_document_id: 1,
|
||||
current_document_filename: 'order-detail.pdf',
|
||||
current_version_no: 2,
|
||||
current_run_no: 'SNER-9',
|
||||
lifecycle_status: 'extracting',
|
||||
current_stage: 'extracting',
|
||||
lock_version: 1,
|
||||
events: [
|
||||
{
|
||||
seq_no: 1,
|
||||
event_code: 'item_created',
|
||||
actor_type: 'system',
|
||||
occurred_at: '2026-07-30T10:00:00Z',
|
||||
},
|
||||
],
|
||||
...patch,
|
||||
};
|
||||
}
|
||||
|
||||
/** Teleport 后从 document 取抽屉根节点。 */
|
||||
function drawerRoot(): HTMLElement | null {
|
||||
return document.querySelector('[data-testid="shipping-workflow-item-drawer"]');
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
document.body.innerHTML = '';
|
||||
});
|
||||
|
||||
describe('ShippingWorkflowItemDetailDrawer', () => {
|
||||
it('renders filename, stage and events when open', () => {
|
||||
const wrapper = mount(ShippingWorkflowItemDetailDrawer, {
|
||||
props: { open: true, item: buildItem() },
|
||||
global: { plugins: [i18n] },
|
||||
attachTo: document.body,
|
||||
});
|
||||
const root = drawerRoot();
|
||||
expect(root).not.toBeNull();
|
||||
expect(root?.getAttribute('role')).toBe('dialog');
|
||||
expect(root?.getAttribute('aria-modal')).toBe('true');
|
||||
expect(root?.textContent).toContain('order-detail.pdf');
|
||||
expect(root?.textContent).toContain('SNER-9');
|
||||
expect(root?.querySelector('[data-testid="shipping-workflow-item-events"]')).not.toBeNull();
|
||||
expect(root?.querySelector('[data-testid="shipping-workflow-item-drawer-cancel"]')).not.toBeNull();
|
||||
expect(root?.querySelector('[data-testid="shipping-workflow-item-drawer-reparse"]')).toBeNull();
|
||||
wrapper.unmount();
|
||||
});
|
||||
|
||||
it('shows reparse for failed items and emits reparse', async () => {
|
||||
const wrapper = mount(ShippingWorkflowItemDetailDrawer, {
|
||||
props: {
|
||||
open: true,
|
||||
item: buildItem({ lifecycle_status: 'failed', current_document_filename: 'fail.pdf' }),
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
attachTo: document.body,
|
||||
});
|
||||
const reparseBtn = drawerRoot()?.querySelector(
|
||||
'[data-testid="shipping-workflow-item-drawer-reparse"]',
|
||||
) as HTMLButtonElement | null;
|
||||
expect(reparseBtn).not.toBeNull();
|
||||
reparseBtn?.click();
|
||||
await wrapper.vm.$nextTick();
|
||||
expect(wrapper.emitted('reparse')?.[0]?.[0]).toMatchObject({ item_no: 'SWI-DETAIL' });
|
||||
wrapper.unmount();
|
||||
});
|
||||
|
||||
it('hides cancel for closed items and emits close', async () => {
|
||||
const wrapper = mount(ShippingWorkflowItemDetailDrawer, {
|
||||
props: {
|
||||
open: true,
|
||||
item: buildItem({ lifecycle_status: 'closed', closed_reason: 'user_cancelled' }),
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
attachTo: document.body,
|
||||
});
|
||||
const root = drawerRoot();
|
||||
expect(root?.querySelector('[data-testid="shipping-workflow-item-drawer-cancel"]')).toBeNull();
|
||||
const closeBtn = root?.querySelector(
|
||||
'[data-testid="shipping-workflow-item-drawer-close"]',
|
||||
) as HTMLButtonElement | null;
|
||||
expect(closeBtn).not.toBeNull();
|
||||
closeBtn?.click();
|
||||
await wrapper.vm.$nextTick();
|
||||
expect(wrapper.emitted('close')).toBeTruthy();
|
||||
wrapper.unmount();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,312 @@
|
||||
/**
|
||||
* features/chat/components/shipping/ShippingWorkflowItemDetailDrawer.vue
|
||||
* 用途:单个 WorkflowItem(PDF)详情抽屉——文件名、阶段、事件时间线、取消/重识别入口。
|
||||
* 依赖:vue-i18n、ShippingWorkflowItem / Event 类型、lucide-vue-next。
|
||||
* 逻辑:由 ShippingWorkflowTimeline 打开;展示 filename / current_stage / events;
|
||||
* 取消与重识别仅 emit,由父级用应用内原因弹窗收集;禁止发明百分比与 ETA。
|
||||
* 以模态对话框语义呈现:初始焦点、Tab 陷阱、Escape/关闭后焦点恢复。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import { computed, nextTick, onBeforeUnmount, ref, watch } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { X } from 'lucide-vue-next';
|
||||
import type { ShippingWorkflowEvent, ShippingWorkflowItem } from '@/features/chat/types/shipping.api.types';
|
||||
|
||||
const props = defineProps<{
|
||||
open: boolean;
|
||||
item: ShippingWorkflowItem | null;
|
||||
loading?: boolean;
|
||||
cancelling?: boolean;
|
||||
reparsing?: boolean;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
close: [];
|
||||
cancel: [item: ShippingWorkflowItem];
|
||||
reparse: [item: ShippingWorkflowItem];
|
||||
}>();
|
||||
|
||||
const { t, te, locale } = useI18n();
|
||||
const panelRef = ref<HTMLElement | null>(null);
|
||||
const closeButtonRef = ref<HTMLButtonElement | null>(null);
|
||||
let previouslyFocused: HTMLElement | null = null;
|
||||
|
||||
const FOCUSABLE_SELECTOR = [
|
||||
'a[href]',
|
||||
'button:not([disabled])',
|
||||
'textarea:not([disabled])',
|
||||
'input:not([disabled])',
|
||||
'select:not([disabled])',
|
||||
'[tabindex]:not([tabindex="-1"])',
|
||||
].join(',');
|
||||
|
||||
const events = computed((): ShippingWorkflowEvent[] => (
|
||||
Array.isArray(props.item?.events) ? props.item!.events! : []
|
||||
));
|
||||
|
||||
const canCancel = computed(() => {
|
||||
const status = String(props.item?.lifecycle_status || '').trim();
|
||||
return Boolean(props.item) && !['closed', 'cancelled'].includes(status);
|
||||
});
|
||||
|
||||
const canReparse = computed(() => {
|
||||
const status = String(props.item?.lifecycle_status || '').trim();
|
||||
return Boolean(props.item) && ['failed', 'reparse_failed', 'pending_review'].includes(status);
|
||||
});
|
||||
|
||||
const filename = computed(() => {
|
||||
const name = String(props.item?.current_document_filename || '').trim();
|
||||
if (name) return name;
|
||||
if (!props.item) return '';
|
||||
return t('chat.shippingWorkflow.filenameFallback', {
|
||||
docId: props.item.current_document_id,
|
||||
});
|
||||
});
|
||||
|
||||
const title = computed(() => t('chat.shippingWorkflow.detail.title'));
|
||||
|
||||
/**
|
||||
* 解析生命周期 / 阶段文案。
|
||||
*/
|
||||
function statusLabel(status?: string | null): string {
|
||||
const normalized = String(status || '').trim();
|
||||
if (!normalized) return '';
|
||||
const key = `chat.shippingWorkflow.itemStatus.${normalized}`;
|
||||
return te(key) ? t(key) : normalized;
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析事件码文案。
|
||||
*/
|
||||
function eventLabel(event: ShippingWorkflowEvent): string {
|
||||
const code = String(event.message_code || event.event_code || '').trim();
|
||||
if (!code) return '—';
|
||||
const key = `chat.shippingWorkflow.event.${code}`;
|
||||
return te(key) ? t(key) : code;
|
||||
}
|
||||
|
||||
/**
|
||||
* 格式化时间为本地短时间。
|
||||
*/
|
||||
function formatTime(value?: string | null): string {
|
||||
const date = new Date(String(value || ''));
|
||||
if (Number.isNaN(date.getTime())) return '';
|
||||
return new Intl.DateTimeFormat(String(locale.value || 'zh-CN'), {
|
||||
month: '2-digit',
|
||||
day: '2-digit',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
hour12: false,
|
||||
}).format(date);
|
||||
}
|
||||
|
||||
/** 收集抽屉内可聚焦控件。 */
|
||||
function focusableNodes(): HTMLElement[] {
|
||||
if (!panelRef.value) return [];
|
||||
return Array.from(panelRef.value.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR))
|
||||
.filter((node) => !node.hasAttribute('disabled') && node.getAttribute('aria-hidden') !== 'true');
|
||||
}
|
||||
|
||||
/** 关闭抽屉。 */
|
||||
function handleClose(): void {
|
||||
emit('close');
|
||||
}
|
||||
|
||||
/**
|
||||
* Escape 关闭;Tab 在抽屉内循环,阻止焦点逃逸到背景页。
|
||||
*/
|
||||
function onKeydown(event: KeyboardEvent): void {
|
||||
if (!props.open) return;
|
||||
if (event.key === 'Escape') {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
handleClose();
|
||||
return;
|
||||
}
|
||||
if (event.key !== 'Tab') return;
|
||||
const nodes = focusableNodes();
|
||||
const first = nodes[0];
|
||||
const last = nodes[nodes.length - 1];
|
||||
// noUncheckedIndexedAccess:空数组或下标越界时 first/last 可能为 undefined。
|
||||
if (!first || !last) {
|
||||
event.preventDefault();
|
||||
return;
|
||||
}
|
||||
const active = document.activeElement as HTMLElement | null;
|
||||
const inside = Boolean(active && panelRef.value?.contains(active));
|
||||
if (event.shiftKey) {
|
||||
if (!inside || active === first) {
|
||||
event.preventDefault();
|
||||
last.focus();
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (!inside || active === last) {
|
||||
event.preventDefault();
|
||||
first.focus();
|
||||
}
|
||||
}
|
||||
|
||||
watch(
|
||||
() => props.open,
|
||||
async (open, wasOpen) => {
|
||||
if (typeof document === 'undefined') return;
|
||||
if (open && !wasOpen) {
|
||||
previouslyFocused = document.activeElement instanceof HTMLElement
|
||||
? document.activeElement
|
||||
: null;
|
||||
document.addEventListener('keydown', onKeydown, true);
|
||||
await nextTick();
|
||||
(closeButtonRef.value || focusableNodes()[0])?.focus();
|
||||
return;
|
||||
}
|
||||
if (!open && wasOpen) {
|
||||
document.removeEventListener('keydown', onKeydown, true);
|
||||
const restoreTarget = previouslyFocused;
|
||||
previouslyFocused = null;
|
||||
await nextTick();
|
||||
restoreTarget?.focus?.();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
if (typeof document !== 'undefined') {
|
||||
document.removeEventListener('keydown', onKeydown, true);
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Teleport to="body">
|
||||
<div
|
||||
v-if="open"
|
||||
class="fixed inset-0 z-40 flex justify-end bg-black/30"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-labelledby="shipping-workflow-item-drawer-title"
|
||||
data-testid="shipping-workflow-item-drawer"
|
||||
@click.self="handleClose"
|
||||
>
|
||||
<aside
|
||||
ref="panelRef"
|
||||
class="flex h-full w-full max-w-md flex-col border-l border-default bg-surface shadow-xl"
|
||||
>
|
||||
<header class="flex items-start justify-between gap-2 border-b border-default px-4 py-3">
|
||||
<div class="min-w-0">
|
||||
<h2 id="shipping-workflow-item-drawer-title" class="text-sm font-semibold text-primary">
|
||||
{{ title }}
|
||||
</h2>
|
||||
<p
|
||||
v-if="item"
|
||||
class="mt-0.5 truncate text-xs text-secondary"
|
||||
data-testid="shipping-workflow-item-drawer-filename"
|
||||
>
|
||||
{{ filename }}
|
||||
· V{{ item.current_version_no }}
|
||||
</p>
|
||||
</div>
|
||||
<button
|
||||
ref="closeButtonRef"
|
||||
type="button"
|
||||
class="rounded-md p-1 text-muted hover:bg-surface-muted"
|
||||
:aria-label="t('chat.shippingWorkflow.detail.close')"
|
||||
data-testid="shipping-workflow-item-drawer-close"
|
||||
@click="handleClose"
|
||||
>
|
||||
<X class="h-4 w-4" />
|
||||
</button>
|
||||
</header>
|
||||
|
||||
<div class="min-h-0 flex-1 overflow-auto p-4">
|
||||
<div v-if="loading" class="text-xs text-muted">
|
||||
{{ t('chat.shippingWorkflow.loading') }}
|
||||
</div>
|
||||
<template v-else-if="item">
|
||||
<dl class="space-y-2 text-xs">
|
||||
<div class="flex justify-between gap-2">
|
||||
<dt class="text-secondary">{{ t('chat.shippingWorkflow.detail.filename') }}</dt>
|
||||
<dd class="max-w-[60%] truncate font-medium text-primary" :title="filename">{{ filename }}</dd>
|
||||
</div>
|
||||
<div class="flex justify-between gap-2">
|
||||
<dt class="text-secondary">{{ t('chat.shippingWorkflow.detail.status') }}</dt>
|
||||
<dd class="font-medium text-primary">{{ statusLabel(item.lifecycle_status) }}</dd>
|
||||
</div>
|
||||
<div class="flex justify-between gap-2">
|
||||
<dt class="text-secondary">{{ t('chat.shippingWorkflow.detail.stage') }}</dt>
|
||||
<dd class="font-medium text-primary">{{ statusLabel(item.current_stage) || item.current_stage }}</dd>
|
||||
</div>
|
||||
<div v-if="item.current_run_no" class="flex justify-between gap-2">
|
||||
<dt class="text-secondary">{{ t('chat.shippingWorkflow.detail.runNo') }}</dt>
|
||||
<dd class="font-medium text-primary">{{ item.current_run_no }}</dd>
|
||||
</div>
|
||||
<div v-if="item.current_case_no" class="flex justify-between gap-2">
|
||||
<dt class="text-secondary">{{ t('chat.shippingWorkflow.detail.caseNo') }}</dt>
|
||||
<dd class="font-medium text-primary">{{ item.current_case_no }}</dd>
|
||||
</div>
|
||||
<div v-if="item.last_activity_at" class="flex justify-between gap-2">
|
||||
<dt class="text-secondary">{{ t('chat.shippingWorkflow.detail.lastActivity') }}</dt>
|
||||
<dd class="font-medium text-primary">{{ formatTime(item.last_activity_at) }}</dd>
|
||||
</div>
|
||||
<div v-if="item.closed_reason" class="flex justify-between gap-2">
|
||||
<dt class="text-secondary">{{ t('chat.shippingWorkflow.detail.closedReason') }}</dt>
|
||||
<dd class="font-medium text-primary">
|
||||
{{ te(`chat.shippingWorkflow.closedReason.${item.closed_reason}`)
|
||||
? t(`chat.shippingWorkflow.closedReason.${item.closed_reason}`)
|
||||
: item.closed_reason }}
|
||||
</dd>
|
||||
</div>
|
||||
</dl>
|
||||
|
||||
<section class="mt-4">
|
||||
<h3 class="text-xs font-semibold text-secondary">
|
||||
{{ t('chat.shippingWorkflow.detail.eventsTitle') }}
|
||||
</h3>
|
||||
<ul v-if="events.length" class="mt-2 space-y-2" data-testid="shipping-workflow-item-events">
|
||||
<li
|
||||
v-for="event in events"
|
||||
:key="`${event.seq_no}-${event.event_code}`"
|
||||
class="rounded-md border border-default bg-surface-muted/40 px-2.5 py-2 text-xs"
|
||||
>
|
||||
<div class="font-medium text-primary">{{ eventLabel(event) }}</div>
|
||||
<div class="mt-0.5 text-[11px] text-muted">
|
||||
<span v-if="event.occurred_at">{{ formatTime(event.occurred_at) }}</span>
|
||||
<span v-if="event.stage_code" class="ml-1">· {{ event.stage_code }}</span>
|
||||
</div>
|
||||
<div v-if="event.reason" class="mt-1 text-[11px] text-secondary">{{ event.reason }}</div>
|
||||
</li>
|
||||
</ul>
|
||||
<p v-else class="mt-2 text-xs text-muted">
|
||||
{{ t('chat.shippingWorkflow.detail.eventsEmpty') }}
|
||||
</p>
|
||||
</section>
|
||||
</template>
|
||||
<p v-else class="text-xs text-muted">{{ t('chat.shippingWorkflow.detail.empty') }}</p>
|
||||
</div>
|
||||
|
||||
<footer v-if="item && (canCancel || canReparse)" class="space-y-2 border-t border-default p-3">
|
||||
<button
|
||||
v-if="canReparse"
|
||||
type="button"
|
||||
class="w-full rounded-md border border-amber-200 bg-amber-50 px-3 py-2 text-xs font-medium text-amber-800 hover:bg-amber-100 disabled:opacity-50 dark:border-amber-900/50 dark:bg-amber-950/40 dark:text-amber-100"
|
||||
:disabled="reparsing || cancelling"
|
||||
data-testid="shipping-workflow-item-drawer-reparse"
|
||||
@click="emit('reparse', item)"
|
||||
>
|
||||
{{ t('chat.shippingWorkflow.actions.reparse') }}
|
||||
</button>
|
||||
<button
|
||||
v-if="canCancel"
|
||||
type="button"
|
||||
class="w-full rounded-md border border-rose-200 bg-rose-50 px-3 py-2 text-xs font-medium text-rose-700 hover:bg-rose-100 disabled:opacity-50 dark:border-rose-900/50 dark:bg-rose-950/40 dark:text-rose-200"
|
||||
:disabled="cancelling || reparsing"
|
||||
data-testid="shipping-workflow-item-drawer-cancel"
|
||||
@click="emit('cancel', item)"
|
||||
>
|
||||
{{ t('chat.shippingWorkflow.actions.cancelFile') }}
|
||||
</button>
|
||||
</footer>
|
||||
</aside>
|
||||
</div>
|
||||
</Teleport>
|
||||
</template>
|
||||
@@ -0,0 +1,189 @@
|
||||
<!--
|
||||
features/chat/components/shipping/ShippingWorkflowReasonDialog.vue
|
||||
用途:Workflow Item 取消 / 重识别的轻量原因确认弹窗(必填 reason)。
|
||||
依赖:vue-i18n、dialog-overlay / dialog-panel 设计系统样式。
|
||||
逻辑:由 ShippingWorkflowTimeline / DetailDrawer 以 v-model 控制;确认前校验非空原因。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, nextTick, onBeforeUnmount, ref, watch } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
|
||||
export type ShippingWorkflowReasonAction = 'cancel' | 'reparse';
|
||||
|
||||
const props = withDefaults(defineProps<{
|
||||
modelValue: boolean;
|
||||
action: ShippingWorkflowReasonAction;
|
||||
confirmLoading?: boolean;
|
||||
}>(), {
|
||||
confirmLoading: false,
|
||||
});
|
||||
|
||||
const emit = defineEmits<{
|
||||
'update:modelValue': [value: boolean];
|
||||
confirm: [payload: { reason: string; comment?: string }];
|
||||
cancel: [];
|
||||
}>();
|
||||
|
||||
const { t } = useI18n();
|
||||
const reason = ref('');
|
||||
const comment = ref('');
|
||||
const reasonMissing = ref(false);
|
||||
const reasonInputRef = ref<HTMLTextAreaElement | null>(null);
|
||||
|
||||
const title = computed(() => (
|
||||
props.action === 'reparse'
|
||||
? t('chat.shippingWorkflow.reasonDialog.reparseTitle')
|
||||
: t('chat.shippingWorkflow.reasonDialog.cancelTitle')
|
||||
));
|
||||
|
||||
const confirmLabel = computed(() => (
|
||||
props.action === 'reparse'
|
||||
? t('chat.shippingWorkflow.reasonDialog.reparseConfirm')
|
||||
: t('chat.shippingWorkflow.reasonDialog.cancelConfirm')
|
||||
));
|
||||
|
||||
const reasonLabel = computed(() => t('chat.shippingWorkflow.reasonDialog.reasonLabel'));
|
||||
const reasonRequiredHint = computed(() => t('chat.shippingWorkflow.reasonRequired'));
|
||||
|
||||
/**
|
||||
* 关闭弹窗并重置本地表单。
|
||||
*/
|
||||
function closeDialog() {
|
||||
emit('update:modelValue', false);
|
||||
}
|
||||
|
||||
/**
|
||||
* 取消:关闭并通知父级。
|
||||
*/
|
||||
function handleCancel() {
|
||||
emit('cancel');
|
||||
closeDialog();
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验必填原因后提交。
|
||||
*/
|
||||
function handleConfirm() {
|
||||
reasonMissing.value = false;
|
||||
const trimmed = reason.value.trim();
|
||||
if (!trimmed) {
|
||||
reasonMissing.value = true;
|
||||
return;
|
||||
}
|
||||
const trimmedComment = comment.value.trim();
|
||||
emit('confirm', {
|
||||
reason: trimmed,
|
||||
comment: trimmedComment || undefined,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Escape 关闭弹窗。
|
||||
*/
|
||||
function onKeydown(event: KeyboardEvent) {
|
||||
if (!props.modelValue) return;
|
||||
if (event.key === 'Escape') {
|
||||
event.preventDefault();
|
||||
handleCancel();
|
||||
}
|
||||
}
|
||||
|
||||
watch(
|
||||
() => props.modelValue,
|
||||
async (open) => {
|
||||
if (typeof document === 'undefined') return;
|
||||
if (open) {
|
||||
reason.value = '';
|
||||
comment.value = '';
|
||||
reasonMissing.value = false;
|
||||
document.addEventListener('keydown', onKeydown, true);
|
||||
await nextTick();
|
||||
reasonInputRef.value?.focus();
|
||||
return;
|
||||
}
|
||||
document.removeEventListener('keydown', onKeydown, true);
|
||||
},
|
||||
);
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
if (typeof document !== 'undefined') {
|
||||
document.removeEventListener('keydown', onKeydown, true);
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Teleport to="body">
|
||||
<div
|
||||
v-if="modelValue"
|
||||
class="dialog-overlay z-50 flex items-center justify-center p-4"
|
||||
data-testid="shipping-workflow-reason-dialog"
|
||||
@click.self="handleCancel"
|
||||
>
|
||||
<div
|
||||
class="dialog-panel w-full max-w-md space-y-3 p-5"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
:aria-label="title"
|
||||
>
|
||||
<h3 class="text-sm font-semibold text-primary">{{ title }}</h3>
|
||||
<p class="mt-1 text-xs text-secondary">
|
||||
{{ t('chat.shippingWorkflow.reasonDialog.impact') }}
|
||||
</p>
|
||||
|
||||
<label class="mt-3 block text-xs text-secondary">
|
||||
{{ reasonLabel }}
|
||||
<span class="text-rose-600">*</span>
|
||||
<textarea
|
||||
ref="reasonInputRef"
|
||||
v-model="reason"
|
||||
rows="3"
|
||||
class="input-field mt-1 w-full py-1.5 text-xs"
|
||||
:aria-invalid="reasonMissing"
|
||||
data-testid="shipping-workflow-reason-input"
|
||||
:placeholder="t('chat.shippingWorkflow.reasonDialog.reasonPlaceholder')"
|
||||
/>
|
||||
</label>
|
||||
<p v-if="reasonMissing" class="mt-1 text-[11px] text-rose-600" data-testid="shipping-workflow-reason-missing">
|
||||
{{ reasonRequiredHint }}
|
||||
</p>
|
||||
|
||||
<label
|
||||
v-if="action === 'reparse'"
|
||||
class="mt-2 block text-xs text-secondary"
|
||||
>
|
||||
{{ t('chat.shippingWorkflow.reasonDialog.commentOptional') }}
|
||||
<textarea
|
||||
v-model="comment"
|
||||
rows="2"
|
||||
class="input-field mt-1 w-full py-1.5 text-xs"
|
||||
data-testid="shipping-workflow-comment-input"
|
||||
/>
|
||||
</label>
|
||||
|
||||
<div class="mt-4 flex flex-wrap justify-end gap-2">
|
||||
<button
|
||||
type="button"
|
||||
class="btn-secondary btn-sm"
|
||||
:disabled="confirmLoading"
|
||||
data-testid="shipping-workflow-reason-cancel"
|
||||
@click="handleCancel"
|
||||
>
|
||||
{{ t('chat.shippingWorkflow.reasonDialog.dismiss') }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="btn-danger btn-sm"
|
||||
:disabled="confirmLoading"
|
||||
data-testid="shipping-workflow-reason-confirm"
|
||||
@click="handleConfirm"
|
||||
>
|
||||
{{ confirmLoading
|
||||
? t('chat.shippingWorkflow.reasonDialog.submitting')
|
||||
: confirmLabel }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Teleport>
|
||||
</template>
|
||||
@@ -0,0 +1,223 @@
|
||||
/**
|
||||
* features/chat/components/shipping/ShippingWorkflowTimeline.spec.ts
|
||||
* 用途:验证右侧 Workflow 时间线分组、文件名、批次切换、过滤与取消/重识别弹窗。
|
||||
* 依赖:Vitest、Vue Test Utils、vue-i18n、shipping.api mock。
|
||||
* 逻辑:断言 layout_parsing 可见;文件名优先;仅看待处理过滤;原因弹窗提交 cancelItem。
|
||||
*/
|
||||
import { mount, flushPromises } from '@vue/test-utils';
|
||||
import { describe, expect, it, vi, beforeEach } from 'vitest';
|
||||
import { createI18n } from 'vue-i18n';
|
||||
import { ref } from 'vue';
|
||||
import chatZhCn from '@/locales/zh-CN/chat.json';
|
||||
import ShippingWorkflowTimeline from './ShippingWorkflowTimeline.vue';
|
||||
import type { ShippingWorkflow, ShippingWorkflowItem } from '../../types/shipping.api.types';
|
||||
import type { UseShippingNoticeWorkflowReturn } from '../../shipping/useShippingNoticeWorkflow';
|
||||
|
||||
vi.mock('@/features/chat/api/shipping.api', () => ({
|
||||
getWorkspaceShippingWorkflowItem: vi.fn(async (itemNo: string) => ({
|
||||
item_no: itemNo,
|
||||
workflow_no: 'SNWF-1',
|
||||
conversation_id: 'conv-1',
|
||||
root_document_id: 1,
|
||||
current_document_id: 1,
|
||||
current_document_filename: 'detail.pdf',
|
||||
current_version_no: 1,
|
||||
lifecycle_status: 'layout_parsing',
|
||||
current_stage: 'layout_parsing',
|
||||
lock_version: 1,
|
||||
events: [],
|
||||
})),
|
||||
listWorkspaceShippingWorkflows: vi.fn(),
|
||||
cancelWorkspaceShippingWorkflowItem: vi.fn(),
|
||||
reparseWorkspaceShippingWorkflowItem: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('@/shared/composables/useMessage', () => ({
|
||||
useMessage: () => ({
|
||||
success: vi.fn(),
|
||||
error: vi.fn(),
|
||||
warning: vi.fn(),
|
||||
info: vi.fn(),
|
||||
}),
|
||||
}));
|
||||
|
||||
const i18n = createI18n({
|
||||
legacy: false,
|
||||
locale: 'zh-CN',
|
||||
messages: { 'zh-CN': { chat: chatZhCn, errors: { generic: '错误' } } },
|
||||
});
|
||||
|
||||
function buildItem(patch: Partial<ShippingWorkflowItem> = {}): ShippingWorkflowItem {
|
||||
return {
|
||||
item_no: 'SWI-1',
|
||||
workflow_no: 'SNWF-1',
|
||||
conversation_id: 'conv-1',
|
||||
root_document_id: 10,
|
||||
current_document_id: 10,
|
||||
current_document_filename: 'shipping-notice.pdf',
|
||||
current_version_no: 1,
|
||||
lifecycle_status: 'layout_parsing',
|
||||
current_stage: 'layout_parsing',
|
||||
lock_version: 1,
|
||||
...patch,
|
||||
};
|
||||
}
|
||||
|
||||
function buildController(
|
||||
items: ShippingWorkflowItem[],
|
||||
extras?: { workflows?: ShippingWorkflow[] },
|
||||
): UseShippingNoticeWorkflowReturn {
|
||||
const workflowList = extras?.workflows ?? [{
|
||||
workflow_no: 'SNWF-1',
|
||||
conversation_id: 'conv-1',
|
||||
status: 'open',
|
||||
current_stage: 'layout_parsing',
|
||||
lock_version: 1,
|
||||
counts: {
|
||||
total: items.length,
|
||||
processing: items.filter((i) => i.lifecycle_status === 'layout_parsing' || i.lifecycle_status === 'extracting').length,
|
||||
pending_review: items.filter((i) => i.lifecycle_status === 'pending_review').length,
|
||||
failed: items.filter((i) => i.lifecycle_status === 'failed' || i.lifecycle_status === 'reparse_failed').length,
|
||||
completed: items.filter((i) => i.lifecycle_status === 'closed').length,
|
||||
},
|
||||
items,
|
||||
}];
|
||||
const selectedWorkflowNo = ref(workflowList[0]?.workflow_no || null);
|
||||
const workflows = ref(workflowList);
|
||||
const workflow = ref(workflowList[0] || null);
|
||||
const itemRef = ref(items);
|
||||
return {
|
||||
workflows,
|
||||
selectedWorkflowNo,
|
||||
selectWorkflow: vi.fn((no: string) => {
|
||||
selectedWorkflowNo.value = no;
|
||||
workflow.value = workflows.value.find((row) => row.workflow_no === no) || null;
|
||||
itemRef.value = workflow.value?.items || [];
|
||||
}),
|
||||
workflow,
|
||||
items: itemRef,
|
||||
loading: ref(false),
|
||||
error: ref(null),
|
||||
refresh: vi.fn(async () => undefined),
|
||||
cancelItem: vi.fn(async () => null),
|
||||
reparseItem: vi.fn(async () => null),
|
||||
stop: vi.fn(),
|
||||
};
|
||||
}
|
||||
|
||||
describe('ShippingWorkflowTimeline', () => {
|
||||
beforeEach(() => {
|
||||
document.body.innerHTML = '';
|
||||
});
|
||||
|
||||
it('shows layout_parsing items with filename before review case exists', async () => {
|
||||
const controller = buildController([
|
||||
buildItem({
|
||||
item_no: 'SWI-LAYOUT',
|
||||
lifecycle_status: 'layout_parsing',
|
||||
current_case_no: null,
|
||||
current_document_filename: 'layout.pdf',
|
||||
}),
|
||||
buildItem({ item_no: 'SWI-REVIEW', lifecycle_status: 'pending_review', current_case_no: 'SNRC-1' }),
|
||||
]);
|
||||
const wrapper = mount(ShippingWorkflowTimeline, {
|
||||
props: { conversationId: 'conv-1', controller },
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
await flushPromises();
|
||||
expect(wrapper.find('[data-testid="shipping-workflow-item-SWI-LAYOUT"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="shipping-workflow-item-SWI-LAYOUT"]').text()).toContain('layout.pdf');
|
||||
expect(wrapper.text()).toContain('尚无复核单');
|
||||
expect(wrapper.find('[data-testid="shipping-workflow-group-processing"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="shipping-workflow-group-pending_review"]').exists()).toBe(true);
|
||||
});
|
||||
|
||||
it('filters to actionable items when pending-only is checked', async () => {
|
||||
const controller = buildController([
|
||||
buildItem({ item_no: 'SWI-A', lifecycle_status: 'extracting' }),
|
||||
buildItem({ item_no: 'SWI-B', lifecycle_status: 'pending_review' }),
|
||||
]);
|
||||
const wrapper = mount(ShippingWorkflowTimeline, {
|
||||
props: { conversationId: 'conv-1', controller },
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
await flushPromises();
|
||||
await wrapper.find('[data-testid="shipping-workflow-pending-only-filter"]').setValue(true);
|
||||
expect(wrapper.find('[data-testid="shipping-workflow-item-SWI-B"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="shipping-workflow-item-SWI-A"]').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it('cancels an item via in-app reason dialog', async () => {
|
||||
const controller = buildController([
|
||||
buildItem({ item_no: 'SWI-CANCEL', lifecycle_status: 'extracting', lock_version: 3 }),
|
||||
]);
|
||||
const wrapper = mount(ShippingWorkflowTimeline, {
|
||||
props: { conversationId: 'conv-1', controller },
|
||||
global: {
|
||||
plugins: [i18n],
|
||||
stubs: {
|
||||
// 让 Teleport 就地渲染,便于 setValue / trigger
|
||||
teleport: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
await flushPromises();
|
||||
await wrapper.find('[data-testid="shipping-workflow-action-cancel"]').trigger('click');
|
||||
await flushPromises();
|
||||
const reasonInput = wrapper.find('[data-testid="shipping-workflow-reason-input"]');
|
||||
expect(reasonInput.exists()).toBe(true);
|
||||
await reasonInput.setValue('cancel reason');
|
||||
await wrapper.find('[data-testid="shipping-workflow-reason-confirm"]').trigger('click');
|
||||
await flushPromises();
|
||||
expect(controller.cancelItem).toHaveBeenCalledWith('SWI-CANCEL', {
|
||||
reason: 'cancel reason',
|
||||
expected_lock_version: 3,
|
||||
});
|
||||
});
|
||||
|
||||
it('shows batch switcher for multiple workflows', async () => {
|
||||
const itemsA = [buildItem({ item_no: 'SWI-A', workflow_no: 'SNWF-A' })];
|
||||
const itemsB = [buildItem({ item_no: 'SWI-B', workflow_no: 'SNWF-B', lifecycle_status: 'failed' })];
|
||||
const workflows = [
|
||||
{
|
||||
workflow_no: 'SNWF-A',
|
||||
conversation_id: 'conv-1',
|
||||
status: 'open',
|
||||
current_stage: 'layout_parsing',
|
||||
lock_version: 1,
|
||||
counts: { total: 1, processing: 1, pending_review: 0, failed: 0, completed: 0 },
|
||||
items: itemsA,
|
||||
},
|
||||
{
|
||||
workflow_no: 'SNWF-B',
|
||||
conversation_id: 'conv-1',
|
||||
status: 'open',
|
||||
current_stage: 'failed',
|
||||
lock_version: 1,
|
||||
counts: { total: 1, processing: 0, pending_review: 0, failed: 1, completed: 0 },
|
||||
items: itemsB,
|
||||
},
|
||||
];
|
||||
const controller = buildController(itemsA, { workflows });
|
||||
const wrapper = mount(ShippingWorkflowTimeline, {
|
||||
props: { conversationId: 'conv-1', controller },
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
await flushPromises();
|
||||
expect(wrapper.find('[data-testid="shipping-workflow-batch-switcher"]').exists()).toBe(true);
|
||||
await wrapper.find('[data-testid="shipping-workflow-batch-SNWF-B"]').trigger('click');
|
||||
expect(controller.selectWorkflow).toHaveBeenCalledWith('SNWF-B');
|
||||
});
|
||||
|
||||
it('shows reparse action for failed items', async () => {
|
||||
const controller = buildController([
|
||||
buildItem({ item_no: 'SWI-FAIL', lifecycle_status: 'failed', current_document_filename: 'bad.pdf' }),
|
||||
]);
|
||||
const wrapper = mount(ShippingWorkflowTimeline, {
|
||||
props: { conversationId: 'conv-1', controller },
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
await flushPromises();
|
||||
expect(wrapper.find('[data-testid="shipping-workflow-action-reparse"]').exists()).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,568 @@
|
||||
/**
|
||||
* features/chat/components/shipping/ShippingWorkflowTimeline.vue
|
||||
* 用途:聊天页右侧「本次处理」面板——以会话 Workflow / Items 为列表事实源。
|
||||
* 依赖:vue-i18n、useMessage、useShippingNoticeWorkflow(inject 或自建)、DetailDrawer、ReasonDialog。
|
||||
* 逻辑:多批次时展示切换器;Items 以文件名为主标题;
|
||||
* 分组进行中/待处理/待复核/待人工上传登记/失败/已完成(登记前不得进已完成);
|
||||
* 「仅看待处理」过滤;查看进度 / 取消 / 重试重识别;取消与重识别用应用内原因弹窗。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import { computed, inject, ref, watch } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { ChevronDown, ChevronRight, RefreshCw } from 'lucide-vue-next';
|
||||
import { BusinessError } from '@/shared/api/client';
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
import {
|
||||
getWorkspaceShippingWorkflowItem,
|
||||
} from '@/features/chat/api/shipping.api';
|
||||
import type {
|
||||
ShippingWorkflow,
|
||||
ShippingWorkflowItem,
|
||||
} from '@/features/chat/types/shipping.api.types';
|
||||
import {
|
||||
SHIPPING_WORKFLOW_KEY,
|
||||
useShippingNoticeWorkflow,
|
||||
type UseShippingNoticeWorkflowReturn,
|
||||
} from '@/features/chat/shipping/useShippingNoticeWorkflow';
|
||||
import ShippingWorkflowItemDetailDrawer from './ShippingWorkflowItemDetailDrawer.vue';
|
||||
import ShippingWorkflowReasonDialog, {
|
||||
type ShippingWorkflowReasonAction,
|
||||
} from './ShippingWorkflowReasonDialog.vue';
|
||||
|
||||
const props = defineProps<{
|
||||
conversationId?: string | null;
|
||||
/** 父级递增以触发立即刷新。 */
|
||||
refreshTrigger?: number;
|
||||
/** 测试或父级注入时可直接传入控制器,跳过自建轮询。 */
|
||||
controller?: UseShippingNoticeWorkflowReturn | null;
|
||||
}>();
|
||||
|
||||
const { t, te, locale } = useI18n();
|
||||
const msg = useMessage();
|
||||
|
||||
const injected = inject(SHIPPING_WORKFLOW_KEY, null);
|
||||
/** 父级已 provide/传入时本地 composable 以空 conversationId 待机,避免双轮询。 */
|
||||
const localController = useShippingNoticeWorkflow({
|
||||
conversationId: () => (
|
||||
props.controller || injected ? null : props.conversationId
|
||||
),
|
||||
refreshTrigger: () => (
|
||||
props.controller || injected ? undefined : props.refreshTrigger
|
||||
),
|
||||
});
|
||||
const ctl = computed((): UseShippingNoticeWorkflowReturn => (
|
||||
props.controller || injected || localController
|
||||
));
|
||||
|
||||
const collapsed = ref(false);
|
||||
const pendingOnlyFilter = ref(false);
|
||||
const actionBusyItemNo = ref<string | null>(null);
|
||||
const detailOpen = ref(false);
|
||||
const detailLoading = ref(false);
|
||||
const detailItem = ref<ShippingWorkflowItem | null>(null);
|
||||
|
||||
const reasonDialogOpen = ref(false);
|
||||
const reasonDialogAction = ref<ShippingWorkflowReasonAction>('cancel');
|
||||
const reasonDialogItem = ref<ShippingWorkflowItem | null>(null);
|
||||
|
||||
const workflows = computed((): ShippingWorkflow[] => ctl.value.workflows.value);
|
||||
const selectedWorkflowNo = computed(() => ctl.value.selectedWorkflowNo.value);
|
||||
const workflow = computed((): ShippingWorkflow | null => ctl.value.workflow.value);
|
||||
const items = computed((): ShippingWorkflowItem[] => ctl.value.items.value);
|
||||
const loading = computed(() => ctl.value.loading.value);
|
||||
const error = computed(() => ctl.value.error.value);
|
||||
|
||||
const counts = computed(() => workflow.value?.counts || {
|
||||
total: items.value.length,
|
||||
processing: 0,
|
||||
pending_review: 0,
|
||||
waiting_manual_upload: 0,
|
||||
failed: 0,
|
||||
completed: 0,
|
||||
});
|
||||
|
||||
const showBatchSwitcher = computed(() => workflows.value.length > 1);
|
||||
|
||||
type ItemGroupKey =
|
||||
| 'processing'
|
||||
| 'queued'
|
||||
| 'completed'
|
||||
| 'pending_review'
|
||||
| 'failed'
|
||||
| 'waiting_manual_upload';
|
||||
|
||||
const PROCESSING_STATUSES = new Set([
|
||||
'layout_parsing',
|
||||
'extracting',
|
||||
'building_order',
|
||||
'inventory_matching',
|
||||
'generating_excel',
|
||||
]);
|
||||
const QUEUED_STATUSES = new Set(['queued']);
|
||||
const FAILED_STATUSES = new Set(['failed', 'reparse_failed']);
|
||||
/** 真正完成/取消;待人工登记不是完成。 */
|
||||
const COMPLETED_STATUSES = new Set(['closed', 'cancelled']);
|
||||
const WAITING_MANUAL_UPLOAD_STATUSES = new Set(['manual_upload_pending']);
|
||||
const PENDING_REVIEW_STATUSES = new Set(['pending_review']);
|
||||
const ACTIONABLE_FILTER_STATUSES = new Set([
|
||||
'pending_review',
|
||||
'failed',
|
||||
'reparse_failed',
|
||||
'queued',
|
||||
'manual_upload_pending',
|
||||
]);
|
||||
const REPARSE_STATUSES = new Set(['failed', 'reparse_failed', 'pending_review']);
|
||||
|
||||
/**
|
||||
* 将 Item 归入展示分组。
|
||||
*/
|
||||
function resolveGroup(item: ShippingWorkflowItem): ItemGroupKey {
|
||||
const status = String(item.lifecycle_status || '').trim();
|
||||
if (PENDING_REVIEW_STATUSES.has(status)) return 'pending_review';
|
||||
if (FAILED_STATUSES.has(status)) return 'failed';
|
||||
if (WAITING_MANUAL_UPLOAD_STATUSES.has(status)) return 'waiting_manual_upload';
|
||||
if (COMPLETED_STATUSES.has(status)) return 'completed';
|
||||
if (QUEUED_STATUSES.has(status)) return 'queued';
|
||||
if (PROCESSING_STATUSES.has(status)) return 'processing';
|
||||
return 'processing';
|
||||
}
|
||||
|
||||
/**
|
||||
* 是否允许取消(非 closed/cancelled)。
|
||||
*/
|
||||
function canCancel(item: ShippingWorkflowItem): boolean {
|
||||
return !COMPLETED_STATUSES.has(String(item.lifecycle_status || '').trim());
|
||||
}
|
||||
|
||||
/**
|
||||
* 是否允许重试/重新识别。
|
||||
*/
|
||||
function canReparse(item: ShippingWorkflowItem): boolean {
|
||||
return REPARSE_STATUSES.has(String(item.lifecycle_status || '').trim());
|
||||
}
|
||||
|
||||
/**
|
||||
* 列表主标题:优先文件名。
|
||||
*/
|
||||
function itemTitle(item: ShippingWorkflowItem): string {
|
||||
const filename = String(item.current_document_filename || '').trim();
|
||||
if (filename) return filename;
|
||||
return t('chat.shippingWorkflow.filenameFallback', {
|
||||
docId: item.current_document_id,
|
||||
});
|
||||
}
|
||||
|
||||
const filteredItems = computed(() => {
|
||||
if (!pendingOnlyFilter.value) return items.value;
|
||||
return items.value.filter((item) =>
|
||||
ACTIONABLE_FILTER_STATUSES.has(String(item.lifecycle_status || '').trim()),
|
||||
);
|
||||
});
|
||||
|
||||
const grouped = computed(() => {
|
||||
const buckets: Record<ItemGroupKey, ShippingWorkflowItem[]> = {
|
||||
processing: [],
|
||||
queued: [],
|
||||
pending_review: [],
|
||||
waiting_manual_upload: [],
|
||||
failed: [],
|
||||
completed: [],
|
||||
};
|
||||
for (const item of filteredItems.value) {
|
||||
buckets[resolveGroup(item)].push(item);
|
||||
}
|
||||
return buckets;
|
||||
});
|
||||
|
||||
const groupOrder: ItemGroupKey[] = [
|
||||
'processing',
|
||||
'queued',
|
||||
'pending_review',
|
||||
'waiting_manual_upload',
|
||||
'failed',
|
||||
'completed',
|
||||
];
|
||||
|
||||
/**
|
||||
* 解析生命周期状态文案。
|
||||
*/
|
||||
function statusLabel(status: string): string {
|
||||
const key = `chat.shippingWorkflow.itemStatus.${status}`;
|
||||
return te(key) ? t(key) : status;
|
||||
}
|
||||
|
||||
/**
|
||||
* 格式化更新时间。
|
||||
*/
|
||||
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 });
|
||||
}
|
||||
|
||||
/**
|
||||
* 格式化批次活动时间(切换器副文案)。
|
||||
*/
|
||||
function formatBatchTime(value?: string | null): string {
|
||||
const date = new Date(String(value || ''));
|
||||
if (Number.isNaN(date.getTime())) return '';
|
||||
return new Intl.DateTimeFormat(String(locale.value || 'zh-CN'), {
|
||||
month: '2-digit',
|
||||
day: '2-digit',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
hour12: false,
|
||||
}).format(date);
|
||||
}
|
||||
|
||||
/**
|
||||
* 手动刷新。
|
||||
*/
|
||||
async function onRefresh() {
|
||||
await ctl.value.refresh();
|
||||
}
|
||||
|
||||
/**
|
||||
* 切换批次。
|
||||
*/
|
||||
function onSelectWorkflow(workflowNo: string) {
|
||||
ctl.value.selectWorkflow(workflowNo);
|
||||
}
|
||||
|
||||
/**
|
||||
* 打开详情:优先拉取含 events 的 Item 详情。
|
||||
*/
|
||||
async function openDetail(item: ShippingWorkflowItem) {
|
||||
const itemNo = String(item.item_no || '').trim();
|
||||
if (!itemNo) return;
|
||||
detailOpen.value = true;
|
||||
detailItem.value = item;
|
||||
detailLoading.value = true;
|
||||
try {
|
||||
detailItem.value = await getWorkspaceShippingWorkflowItem(itemNo, {
|
||||
include_events: true,
|
||||
});
|
||||
} catch {
|
||||
/* 列表投影仍可展示 */
|
||||
} finally {
|
||||
detailLoading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 打开取消原因弹窗。
|
||||
*/
|
||||
function openCancelDialog(item: ShippingWorkflowItem) {
|
||||
reasonDialogItem.value = item;
|
||||
reasonDialogAction.value = 'cancel';
|
||||
reasonDialogOpen.value = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 打开重识别原因弹窗。
|
||||
*/
|
||||
function openReparseDialog(item: ShippingWorkflowItem) {
|
||||
reasonDialogItem.value = item;
|
||||
reasonDialogAction.value = 'reparse';
|
||||
reasonDialogOpen.value = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 原因弹窗确认:按 action 取消或重识别。
|
||||
*/
|
||||
async function onReasonConfirm(payload: { reason: string; comment?: string }) {
|
||||
const item = reasonDialogItem.value;
|
||||
const itemNo = String(item?.item_no || '').trim();
|
||||
if (!item || !itemNo || actionBusyItemNo.value) return;
|
||||
actionBusyItemNo.value = itemNo;
|
||||
try {
|
||||
if (reasonDialogAction.value === 'reparse') {
|
||||
await ctl.value.reparseItem(itemNo, {
|
||||
reason: payload.reason,
|
||||
comment: payload.comment,
|
||||
});
|
||||
} else {
|
||||
await ctl.value.cancelItem(itemNo, {
|
||||
reason: payload.reason,
|
||||
expected_lock_version: item.lock_version,
|
||||
});
|
||||
}
|
||||
reasonDialogOpen.value = false;
|
||||
reasonDialogItem.value = null;
|
||||
if (detailItem.value?.item_no === itemNo) {
|
||||
detailOpen.value = false;
|
||||
detailItem.value = null;
|
||||
}
|
||||
} catch (err) {
|
||||
const message = err instanceof BusinessError ? err.message : t('errors.generic');
|
||||
msg.error(message);
|
||||
} finally {
|
||||
actionBusyItemNo.value = null;
|
||||
}
|
||||
}
|
||||
|
||||
watch(
|
||||
() => error.value,
|
||||
() => {
|
||||
/* 面板内展示 network_recoverable,不弹 toast */
|
||||
},
|
||||
);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<aside
|
||||
class="flex w-72 shrink-0 flex-col border-l border-default bg-surface shadow-[-8px_0_24px_rgba(15,23,42,0.04)]"
|
||||
data-testid="shipping-workflow-timeline"
|
||||
>
|
||||
<div class="flex w-full items-center gap-1 border-b border-default px-2 py-2">
|
||||
<button
|
||||
type="button"
|
||||
class="flex min-w-0 flex-1 items-center justify-between gap-2 rounded-md px-1 py-1 text-left hover:bg-surface-muted/60"
|
||||
@click="collapsed = !collapsed"
|
||||
>
|
||||
<div class="min-w-0">
|
||||
<div class="text-sm font-semibold text-primary">
|
||||
{{ t('chat.shippingWorkflow.title') }}
|
||||
</div>
|
||||
<div class="mt-0.5 text-xs text-secondary">
|
||||
{{ t('chat.shippingWorkflow.pdfCount', { count: counts.total }) }}
|
||||
</div>
|
||||
</div>
|
||||
<ChevronDown v-if="!collapsed" class="h-4 w-4 shrink-0 text-muted" />
|
||||
<ChevronRight v-else class="h-4 w-4 shrink-0 text-muted" />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="shrink-0 rounded-md p-1.5 text-muted hover:bg-surface-muted hover:text-primary disabled:opacity-50"
|
||||
:disabled="loading"
|
||||
:title="t('chat.shippingWorkflow.actions.refresh')"
|
||||
data-testid="shipping-workflow-refresh"
|
||||
@click="onRefresh"
|
||||
>
|
||||
<RefreshCw class="h-3.5 w-3.5" :class="{ 'animate-spin': loading }" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div v-if="!collapsed" class="min-h-0 flex-1 overflow-auto p-3">
|
||||
<div
|
||||
v-if="showBatchSwitcher"
|
||||
class="mb-3 space-y-1.5"
|
||||
data-testid="shipping-workflow-batch-switcher"
|
||||
>
|
||||
<div class="text-[11px] font-semibold uppercase tracking-wide text-secondary">
|
||||
{{ t('chat.shippingWorkflow.batchSwitcherTitle') }}
|
||||
</div>
|
||||
<button
|
||||
v-for="batch in workflows"
|
||||
:key="batch.workflow_no"
|
||||
type="button"
|
||||
class="w-full rounded-lg border px-2.5 py-2 text-left transition"
|
||||
:class="batch.workflow_no === selectedWorkflowNo
|
||||
? 'border-brand-500 bg-brand-50/80 dark:border-brand-400 dark:bg-brand-950/30'
|
||||
: 'border-default bg-surface-soft/80 hover:bg-surface-muted/50'"
|
||||
:data-testid="`shipping-workflow-batch-${batch.workflow_no}`"
|
||||
@click="onSelectWorkflow(batch.workflow_no)"
|
||||
>
|
||||
<div class="truncate text-xs font-semibold text-primary">
|
||||
{{ batch.workflow_no }}
|
||||
</div>
|
||||
<div class="mt-0.5 text-[11px] text-secondary">
|
||||
{{ statusLabel(batch.current_stage) || batch.current_stage }}
|
||||
· {{ t('chat.shippingWorkflow.batchCounts', {
|
||||
processing: batch.counts.processing,
|
||||
pending: batch.counts.pending_review,
|
||||
waiting: batch.counts.waiting_manual_upload || 0,
|
||||
failed: batch.counts.failed,
|
||||
completed: batch.counts.completed,
|
||||
}) }}
|
||||
</div>
|
||||
<div v-if="batch.last_activity_at" class="mt-0.5 text-[11px] text-muted">
|
||||
{{ formatBatchTime(batch.last_activity_at) }}
|
||||
</div>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<label class="mb-3 flex cursor-pointer items-center gap-2 text-[11px] text-secondary">
|
||||
<input
|
||||
v-model="pendingOnlyFilter"
|
||||
type="checkbox"
|
||||
class="rounded border-default"
|
||||
data-testid="shipping-workflow-pending-only-filter"
|
||||
/>
|
||||
{{ t('chat.shippingWorkflow.pendingOnlyFilter') }}
|
||||
</label>
|
||||
|
||||
<div class="mb-3 flex flex-wrap gap-1.5 text-[11px]">
|
||||
<span class="rounded-md bg-sky-50 px-2 py-0.5 text-sky-700 dark:bg-sky-950/40 dark:text-sky-200">
|
||||
{{ t('chat.shippingWorkflow.counts.processing', { count: counts.processing }) }}
|
||||
</span>
|
||||
<span
|
||||
v-if="counts.pending_review > 0"
|
||||
class="rounded-md bg-amber-50 px-2 py-0.5 text-amber-700 dark:bg-amber-950/40 dark:text-amber-200"
|
||||
>
|
||||
{{ t('chat.shippingWorkflow.counts.pendingReview', { count: counts.pending_review }) }}
|
||||
</span>
|
||||
<span
|
||||
v-if="(counts.waiting_manual_upload || 0) > 0"
|
||||
class="rounded-md bg-amber-50 px-2 py-0.5 text-amber-800 dark:bg-amber-950/40 dark:text-amber-100"
|
||||
>
|
||||
{{ t('chat.shippingWorkflow.counts.waitingManualUpload', {
|
||||
count: counts.waiting_manual_upload || 0,
|
||||
}) }}
|
||||
</span>
|
||||
<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.shippingWorkflow.counts.completed', { count: counts.completed }) }}
|
||||
</span>
|
||||
<span
|
||||
v-if="counts.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"
|
||||
>
|
||||
{{ t('chat.shippingWorkflow.counts.failed', { count: counts.failed }) }}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="workflow?.current_stage || workflow?.last_activity_at"
|
||||
class="mb-3 text-[11px] text-secondary"
|
||||
data-testid="shipping-workflow-stage-summary"
|
||||
>
|
||||
<span v-if="workflow?.current_stage">
|
||||
{{ t('chat.shippingWorkflow.currentStage', {
|
||||
stage: statusLabel(workflow.current_stage) || workflow.current_stage,
|
||||
}) }}
|
||||
</span>
|
||||
<span v-if="workflow?.last_activity_at" class="ml-1">
|
||||
· {{ formatUpdatedLabel(workflow.last_activity_at) }}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="error === 'network_recoverable'"
|
||||
class="mb-3 rounded-md border border-amber-200 bg-amber-50 px-2.5 py-2 text-[11px] text-amber-900 dark:border-amber-900/60 dark:bg-amber-950/40 dark:text-amber-100"
|
||||
data-testid="shipping-workflow-network-error"
|
||||
>
|
||||
{{ t('chat.shippingWorkflow.networkRecoverable') }}
|
||||
</div>
|
||||
<div
|
||||
v-else-if="error"
|
||||
class="mb-3 rounded-md border border-rose-200 bg-rose-50 px-2.5 py-2 text-[11px] text-rose-800 dark:border-rose-900/60 dark:bg-rose-950/40 dark:text-rose-100"
|
||||
>
|
||||
{{ error }}
|
||||
</div>
|
||||
|
||||
<div v-if="!filteredItems.length" class="text-xs text-muted">
|
||||
{{ loading ? t('chat.shippingWorkflow.loading') : t('chat.shippingWorkflow.empty') }}
|
||||
</div>
|
||||
|
||||
<template v-for="groupKey in groupOrder" :key="groupKey">
|
||||
<section
|
||||
v-if="grouped[groupKey].length"
|
||||
class="mb-3"
|
||||
:data-testid="`shipping-workflow-group-${groupKey}`"
|
||||
>
|
||||
<h3 class="mb-1.5 text-[11px] font-semibold uppercase tracking-wide text-secondary">
|
||||
{{ t(`chat.shippingWorkflow.groups.${groupKey}`) }}
|
||||
</h3>
|
||||
<ul class="space-y-2">
|
||||
<li
|
||||
v-for="item in grouped[groupKey]"
|
||||
:key="item.item_no"
|
||||
class="rounded-lg border border-default bg-surface-soft/80 px-2.5 py-2"
|
||||
:data-testid="`shipping-workflow-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"
|
||||
:title="itemTitle(item)"
|
||||
data-testid="shipping-workflow-item-filename"
|
||||
>
|
||||
{{ itemTitle(item) }}
|
||||
</div>
|
||||
<div class="mt-0.5 text-[11px] text-muted">
|
||||
{{ t('chat.shippingWorkflow.versionLabel', { version: item.current_version_no }) }}
|
||||
· {{ statusLabel(String(item.current_stage || item.lifecycle_status || '')) }}
|
||||
<span v-if="!item.current_case_no" class="ml-1 text-secondary">
|
||||
· {{ t('chat.shippingWorkflow.noReviewCaseYet') }}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<span
|
||||
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':
|
||||
groupKey === 'pending_review'
|
||||
|| groupKey === 'failed'
|
||||
|| groupKey === 'waiting_manual_upload',
|
||||
'bg-sky-100 text-sky-800 dark:bg-sky-900/50 dark:text-sky-100':
|
||||
groupKey === 'processing' || groupKey === 'queued',
|
||||
'bg-emerald-100 text-emerald-800 dark:bg-emerald-900/50 dark:text-emerald-100':
|
||||
groupKey === 'completed',
|
||||
}"
|
||||
>
|
||||
{{ statusLabel(String(item.lifecycle_status || '')) }}
|
||||
</span>
|
||||
</div>
|
||||
<div v-if="item.last_activity_at || item.updated_at" class="mt-0.5 text-[11px] text-muted">
|
||||
{{ formatUpdatedLabel(item.last_activity_at || item.updated_at) }}
|
||||
</div>
|
||||
<div class="mt-2 flex flex-wrap gap-2">
|
||||
<button
|
||||
type="button"
|
||||
class="inline-flex items-center gap-1 text-[11px] font-medium text-brand-700 hover:underline"
|
||||
data-testid="shipping-workflow-action-view"
|
||||
@click="openDetail(item)"
|
||||
>
|
||||
{{ t('chat.shippingWorkflow.actions.viewProgress') }}
|
||||
</button>
|
||||
<button
|
||||
v-if="canReparse(item)"
|
||||
type="button"
|
||||
class="inline-flex items-center gap-1 text-[11px] font-medium text-amber-800 hover:underline disabled:opacity-50 dark:text-amber-200"
|
||||
:disabled="actionBusyItemNo === item.item_no"
|
||||
data-testid="shipping-workflow-action-reparse"
|
||||
@click="openReparseDialog(item)"
|
||||
>
|
||||
{{ t('chat.shippingWorkflow.actions.reparse') }}
|
||||
</button>
|
||||
<button
|
||||
v-if="canCancel(item)"
|
||||
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-workflow-action-cancel"
|
||||
@click="openCancelDialog(item)"
|
||||
>
|
||||
{{ t('chat.shippingWorkflow.actions.cancelFile') }}
|
||||
</button>
|
||||
</div>
|
||||
</li>
|
||||
</ul>
|
||||
</section>
|
||||
</template>
|
||||
</div>
|
||||
|
||||
<ShippingWorkflowItemDetailDrawer
|
||||
:open="detailOpen"
|
||||
:item="detailItem"
|
||||
:loading="detailLoading"
|
||||
:cancelling="Boolean(detailItem && actionBusyItemNo === detailItem.item_no && reasonDialogAction === 'cancel')"
|
||||
:reparsing="Boolean(detailItem && actionBusyItemNo === detailItem.item_no && reasonDialogAction === 'reparse')"
|
||||
@close="detailOpen = false; detailItem = null"
|
||||
@cancel="openCancelDialog"
|
||||
@reparse="openReparseDialog"
|
||||
/>
|
||||
|
||||
<ShippingWorkflowReasonDialog
|
||||
v-model="reasonDialogOpen"
|
||||
:action="reasonDialogAction"
|
||||
:confirm-loading="Boolean(actionBusyItemNo)"
|
||||
@confirm="onReasonConfirm"
|
||||
/>
|
||||
</aside>
|
||||
</template>
|
||||
@@ -625,7 +625,7 @@ export function useChatPage() {
|
||||
shippingBatchTasks: shipping.shippingBatchTasks,
|
||||
activeShippingTaskDetail: shipping.activeShippingTaskDetail,
|
||||
getActiveOrderExtractionRunNo: shipping.getActiveOrderExtractionRunNo,
|
||||
sessionWorkItemsRefreshTrigger: shipping.sessionWorkItemsRefreshTrigger,
|
||||
workflowRefreshTrigger: shipping.workflowRefreshTrigger,
|
||||
shippingInventorySelectionActive: shipping.shippingInventorySelectionActive,
|
||||
shippingInventorySelectionTaskId: shipping.shippingInventorySelectionTaskId,
|
||||
switchShippingBatch: shipping.switchShippingBatch,
|
||||
|
||||
@@ -792,9 +792,9 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
msg,
|
||||
t,
|
||||
});
|
||||
const sessionWorkItemsRefreshTrigger = ref(0);
|
||||
const bumpSessionWorkItemsRefresh = () => {
|
||||
sessionWorkItemsRefreshTrigger.value += 1;
|
||||
const workflowRefreshTrigger = ref(0);
|
||||
const bumpWorkflowRefresh = () => {
|
||||
workflowRefreshTrigger.value += 1;
|
||||
};
|
||||
const shippingOrderExtractionRuns = useShippingOrderExtractionRuns({
|
||||
messages,
|
||||
@@ -817,7 +817,7 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
});
|
||||
},
|
||||
onRetryError: (message) => msg.error(message),
|
||||
onSessionWorkItemsRefresh: bumpSessionWorkItemsRefresh,
|
||||
onWorkflowRefresh: bumpWorkflowRefresh,
|
||||
t,
|
||||
});
|
||||
|
||||
@@ -1394,7 +1394,7 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
cancelOrderExtractionUnit: shippingOrderExtractionRuns.cancelUnit,
|
||||
reparseOrderExtractionRun: shippingOrderExtractionRuns.reparseRun,
|
||||
getActiveOrderExtractionRunNo: shippingOrderExtractionRuns.getActiveRunNo,
|
||||
sessionWorkItemsRefreshTrigger,
|
||||
workflowRefreshTrigger,
|
||||
shippingNoticeAllReadyForConfirmation: shippingIntakes.allReadyForConfirmation,
|
||||
setShippingCandidateSelected,
|
||||
resolveShippingCandidateDuplicate,
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
/**
|
||||
* features/chat/shipping-review/deriveWorkflowItemVersions.ts
|
||||
* 用途:从 WorkflowItem 详情派生复核页版本历史行(后端暂无独立 versions 接口)。
|
||||
* 依赖:ShippingWorkflowItem / ShippingWorkflowItemVersion 类型。
|
||||
* 逻辑:由 useShippingOrderReview 调用;优先用 current_case_no + current_version_no 生成当前版本占位。
|
||||
*/
|
||||
|
||||
import type {
|
||||
ShippingWorkflowItem,
|
||||
ShippingWorkflowItemVersion,
|
||||
} from '../types/shipping.api.types';
|
||||
|
||||
/**
|
||||
* 由 WorkflowItem 投影派生版本历史;无 case 时返回空列表(面板展示说明文案)。
|
||||
* @param item - getWorkspaceShippingWorkflowItem 详情
|
||||
*/
|
||||
export function deriveWorkflowItemVersions(
|
||||
item: ShippingWorkflowItem | null | undefined,
|
||||
): ShippingWorkflowItemVersion[] {
|
||||
if (!item) return [];
|
||||
const caseNo = String(item.current_case_no || '').trim();
|
||||
if (!caseNo) return [];
|
||||
const versionNo = Number(item.current_version_no || 1);
|
||||
return [{
|
||||
case_no: caseNo,
|
||||
case_status: item.lifecycle_status,
|
||||
run_no: item.current_run_no || null,
|
||||
document_id: item.current_document_id,
|
||||
is_current: true,
|
||||
is_readonly: ['closed', 'cancelled', 'manual_upload_pending'].includes(
|
||||
String(item.lifecycle_status || '').trim(),
|
||||
),
|
||||
version_label: `V${versionNo}`,
|
||||
version_no: versionNo,
|
||||
created_at: item.updated_at || item.created_at || null,
|
||||
note: 'version_history_limited',
|
||||
}];
|
||||
}
|
||||
@@ -1,31 +1,580 @@
|
||||
/**
|
||||
|
||||
* features/chat/shipping-review/useShippingOrderReview.spec.ts
|
||||
* 用途:阶段 3 复核页历史版本只读契约冒烟。
|
||||
* 依赖:isReviewCaseHistorical 纯函数。
|
||||
* 逻辑:断言 superseded / 非当前 case_no 时强制只读。
|
||||
|
||||
* 用途:阶段 3 复核页历史版本只读、草稿版本冲突、建单资格门禁与库存候选写入冒烟。
|
||||
|
||||
* 依赖:isReviewCaseHistorical / isDraftVersionMismatchError / summarizeDraftConflictDiff /
|
||||
|
||||
* isBuildConfirmBlocked / lineNeedsManualInventorySelection、useShippingOrderReview。
|
||||
|
||||
* 逻辑:断言 superseded 只读、版本冲突码识别、差异摘要、confirm 门禁与 inventory PUT happy path。
|
||||
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { isReviewCaseHistorical } from './useShippingOrderReview';
|
||||
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { BusinessError } from '@/shared/api/client';
|
||||
|
||||
import {
|
||||
|
||||
isBuildConfirmBlocked,
|
||||
|
||||
isDraftVersionMismatchError,
|
||||
|
||||
isReviewCaseHistorical,
|
||||
|
||||
isReviewReadOnly,
|
||||
|
||||
isReviewWorkItemClosed,
|
||||
|
||||
lineNeedsManualInventorySelection,
|
||||
|
||||
REVIEW_BUILD_ELIGIBILITY_BLOCKED,
|
||||
|
||||
REVIEW_DRAFT_VERSION_MISMATCH,
|
||||
|
||||
summarizeDraftConflictDiff,
|
||||
|
||||
useShippingOrderReview,
|
||||
|
||||
} from './useShippingOrderReview';
|
||||
|
||||
import type { ShippingOrderReviewCase } from '../types/shipping.api.types';
|
||||
|
||||
|
||||
|
||||
const api = vi.hoisted(() => ({
|
||||
|
||||
getCase: vi.fn(),
|
||||
|
||||
getRun: vi.fn(),
|
||||
|
||||
getEvidence: vi.fn(),
|
||||
|
||||
getPreview: vi.fn(),
|
||||
|
||||
listWorkflows: vi.fn(),
|
||||
getWorkflowItem: vi.fn(),
|
||||
|
||||
putInventoryCandidates: vi.fn(),
|
||||
|
||||
confirmCase: vi.fn(),
|
||||
|
||||
}));
|
||||
|
||||
|
||||
|
||||
vi.mock('../api/shipping.api', () => ({
|
||||
|
||||
getWorkspaceShippingOrderReviewCase: api.getCase,
|
||||
|
||||
getWorkspaceShippingOrderReviewRun: api.getRun,
|
||||
|
||||
getWorkspaceShippingOrderReviewEvidence: api.getEvidence,
|
||||
|
||||
getWorkspaceShippingOrderReviewPreview: api.getPreview,
|
||||
|
||||
listWorkspaceShippingWorkflows: api.listWorkflows,
|
||||
|
||||
getWorkspaceShippingWorkflowItem: api.getWorkflowItem,
|
||||
|
||||
putWorkspaceShippingOrderReviewInventoryCandidates: api.putInventoryCandidates,
|
||||
|
||||
confirmWorkspaceShippingOrderReviewCase: api.confirmCase,
|
||||
|
||||
patchWorkspaceShippingOrderReviewHeaderField: vi.fn(),
|
||||
|
||||
patchWorkspaceShippingOrderReviewLineField: vi.fn(),
|
||||
|
||||
addWorkspaceShippingOrderReviewLine: vi.fn(),
|
||||
|
||||
copyWorkspaceShippingOrderReviewLine: vi.fn(),
|
||||
|
||||
deleteWorkspaceShippingOrderReviewLine: vi.fn(),
|
||||
|
||||
validateWorkspaceShippingOrderReviewDraft: vi.fn(),
|
||||
|
||||
createWorkspaceShippingOrderReviewManualDraft: vi.fn(),
|
||||
|
||||
markWorkspaceShippingOrderReviewNonOrder: vi.fn(),
|
||||
|
||||
markWorkspaceShippingOrderReviewQualityIssue: vi.fn(),
|
||||
|
||||
reparseWorkspaceShippingOrderReviewDocument: vi.fn(),
|
||||
|
||||
createWorkspaceShippingOrderReviewReplacementIntake: vi.fn(),
|
||||
|
||||
createWorkspaceShippingOrderReviewReplacementRun: vi.fn(),
|
||||
|
||||
}));
|
||||
|
||||
|
||||
|
||||
const buildCase = (patch: Partial<ShippingOrderReviewCase> = {}): ShippingOrderReviewCase => ({
|
||||
|
||||
case_no: 'CASE-1',
|
||||
|
||||
run_no: 'RUN-1',
|
||||
|
||||
document: { id: 1, file_name: 'order.pdf' },
|
||||
|
||||
status: 'draft',
|
||||
|
||||
schema: { schema_version_id: 1, fields: [] },
|
||||
|
||||
draft: {
|
||||
|
||||
draft_version: 2,
|
||||
|
||||
header_values: {},
|
||||
|
||||
lines: [{ line_key: 'line-1' }],
|
||||
|
||||
issues: [],
|
||||
|
||||
validation: {},
|
||||
|
||||
build_eligibility: {
|
||||
|
||||
can_build: false,
|
||||
|
||||
status: 'needs_review',
|
||||
|
||||
line_projections: [{
|
||||
|
||||
line_key: 'line-1',
|
||||
|
||||
line_index: 0,
|
||||
|
||||
effective_reservation_id: '3000000001',
|
||||
|
||||
candidate_inventory_source_codes: ['DSV360_AWSDU', 'DSV360_AWSHK'],
|
||||
|
||||
routing_status: 'conflicted',
|
||||
|
||||
can_build: false,
|
||||
|
||||
block_reason: 'require_manual_review',
|
||||
|
||||
}],
|
||||
|
||||
},
|
||||
|
||||
},
|
||||
|
||||
available_actions: ['edit_draft', 'validate', 'confirm'],
|
||||
|
||||
...patch,
|
||||
|
||||
});
|
||||
|
||||
|
||||
|
||||
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);
|
||||
|
||||
});
|
||||
|
||||
|
||||
|
||||
it('forces readonly when session work item is closed', () => {
|
||||
|
||||
expect(isReviewWorkItemClosed({ lifecycle_status: 'closed', current_case_no: 'CASE-1' })).toBe(true);
|
||||
|
||||
expect(isReviewReadOnly(
|
||||
|
||||
{ case_no: 'CASE-1', status: 'draft' },
|
||||
|
||||
{ current_case_no: 'CASE-1', lifecycle_status: 'closed' },
|
||||
|
||||
)).toBe(true);
|
||||
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
|
||||
|
||||
describe('draft version conflict helpers', () => {
|
||||
|
||||
it('recognizes REVIEW_DRAFT_VERSION_MISMATCH BusinessError', () => {
|
||||
|
||||
expect(isDraftVersionMismatchError(
|
||||
|
||||
new BusinessError({ message: 'stale', code: REVIEW_DRAFT_VERSION_MISMATCH }),
|
||||
|
||||
)).toBe(true);
|
||||
|
||||
expect(isDraftVersionMismatchError(
|
||||
|
||||
new BusinessError({ message: 'other', code: 'SHIPPING.REVIEW_FIELD_INVALID' }),
|
||||
|
||||
)).toBe(false);
|
||||
|
||||
expect(isDraftVersionMismatchError(new Error('nope'))).toBe(false);
|
||||
|
||||
});
|
||||
|
||||
|
||||
|
||||
it('summarizes local vs server draft version and header values', () => {
|
||||
|
||||
const local = {
|
||||
|
||||
status: 'draft',
|
||||
|
||||
draft: {
|
||||
|
||||
draft_version: 3,
|
||||
|
||||
issues: [],
|
||||
|
||||
header_values: { values: { 'po-id': { value: 'PO-LOCAL' } } },
|
||||
|
||||
},
|
||||
|
||||
} as unknown as ShippingOrderReviewCase;
|
||||
|
||||
const server = {
|
||||
|
||||
status: 'ready',
|
||||
|
||||
draft: {
|
||||
|
||||
draft_version: 5,
|
||||
|
||||
issues: [{ code: 'x' }],
|
||||
|
||||
header_values: { values: { 'po-id': { value: 'PO-SERVER' } } },
|
||||
|
||||
},
|
||||
|
||||
} as unknown as ShippingOrderReviewCase;
|
||||
|
||||
const lines = summarizeDraftConflictDiff(local, server);
|
||||
|
||||
expect(lines.some((line) => line.includes('draft_version'))).toBe(true);
|
||||
|
||||
expect(lines.some((line) => line.includes('header.po-id'))).toBe(true);
|
||||
|
||||
expect(lines.some((line) => line.includes('status'))).toBe(true);
|
||||
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
|
||||
|
||||
describe('build eligibility helpers', () => {
|
||||
|
||||
it('blocks confirm only when can_build is explicitly false', () => {
|
||||
|
||||
expect(isBuildConfirmBlocked(null)).toBe(false);
|
||||
|
||||
expect(isBuildConfirmBlocked(undefined)).toBe(false);
|
||||
|
||||
expect(isBuildConfirmBlocked({ can_build: true, status: 'ready', line_projections: [] })).toBe(false);
|
||||
|
||||
expect(isBuildConfirmBlocked({ can_build: false, status: 'needs_review', line_projections: [] })).toBe(true);
|
||||
|
||||
});
|
||||
|
||||
|
||||
|
||||
it('detects lines needing manual inventory selection', () => {
|
||||
|
||||
expect(lineNeedsManualInventorySelection({ can_build: true })).toBe(false);
|
||||
|
||||
expect(lineNeedsManualInventorySelection({
|
||||
|
||||
can_build: false,
|
||||
|
||||
candidate_inventory_source_codes: ['DSV360_AWSDU'],
|
||||
|
||||
})).toBe(true);
|
||||
|
||||
expect(lineNeedsManualInventorySelection({
|
||||
|
||||
can_build: false,
|
||||
|
||||
block_reason: 'require_manual_review',
|
||||
|
||||
})).toBe(true);
|
||||
|
||||
expect(lineNeedsManualInventorySelection({
|
||||
|
||||
can_build: false,
|
||||
|
||||
block_reason: 'customer_unresolved',
|
||||
|
||||
})).toBe(false);
|
||||
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
|
||||
|
||||
describe('useShippingOrderReview build eligibility writes', () => {
|
||||
|
||||
beforeEach(() => {
|
||||
|
||||
api.getRun.mockResolvedValue({
|
||||
|
||||
run_no: 'RUN-1',
|
||||
|
||||
items: [{ case_no: 'CASE-1', status: 'draft', issue_count: 0 }],
|
||||
|
||||
});
|
||||
|
||||
api.getEvidence.mockResolvedValue({ items: [] });
|
||||
|
||||
api.getPreview.mockRejectedValue(new Error('preview unavailable'));
|
||||
|
||||
api.listWorkflows.mockResolvedValue({ conversation_id: 'conv-1', workflows: [] });
|
||||
|
||||
api.getWorkflowItem.mockResolvedValue({
|
||||
item_no: 'SWI-1',
|
||||
workflow_no: 'SNWF-1',
|
||||
conversation_id: 'conv-1',
|
||||
root_document_id: 1,
|
||||
current_document_id: 1,
|
||||
current_version_no: 1,
|
||||
current_case_no: 'CASE-1',
|
||||
lifecycle_status: 'pending_review',
|
||||
current_stage: 'pending_review',
|
||||
lock_version: 1,
|
||||
});
|
||||
|
||||
api.getCase.mockResolvedValue(buildCase());
|
||||
|
||||
});
|
||||
|
||||
|
||||
|
||||
afterEach(() => {
|
||||
|
||||
vi.clearAllMocks();
|
||||
|
||||
});
|
||||
|
||||
|
||||
|
||||
it('exposes buildEligibility and manualInventoryLines from active case draft', async () => {
|
||||
|
||||
const review = useShippingOrderReview();
|
||||
|
||||
await review.load('RUN-1', 'CASE-1');
|
||||
|
||||
expect(review.buildEligibility.value?.can_build).toBe(false);
|
||||
|
||||
expect(review.canConfirmBuild.value).toBe(false);
|
||||
|
||||
expect(review.manualInventoryLines.value).toHaveLength(1);
|
||||
|
||||
expect(review.manualInventoryLines.value[0]?.line_key).toBe('line-1');
|
||||
|
||||
});
|
||||
|
||||
|
||||
|
||||
it('submits inventory candidates via PUT and refreshes case', async () => {
|
||||
|
||||
const updated = buildCase({
|
||||
|
||||
draft: {
|
||||
|
||||
...buildCase().draft!,
|
||||
|
||||
draft_version: 3,
|
||||
|
||||
build_eligibility: {
|
||||
|
||||
can_build: true,
|
||||
|
||||
status: 'ready',
|
||||
|
||||
line_projections: [{
|
||||
|
||||
line_key: 'line-1',
|
||||
|
||||
line_index: 0,
|
||||
|
||||
can_build: true,
|
||||
|
||||
selection_mode: 'manual',
|
||||
|
||||
manual_reason: 'Confirmed with planner',
|
||||
|
||||
candidate_inventory_source_codes: ['DSV360_AWSDU'],
|
||||
|
||||
}],
|
||||
|
||||
},
|
||||
|
||||
},
|
||||
|
||||
});
|
||||
|
||||
api.putInventoryCandidates.mockResolvedValue(updated);
|
||||
|
||||
|
||||
|
||||
const review = useShippingOrderReview();
|
||||
|
||||
await review.load('RUN-1', 'CASE-1');
|
||||
|
||||
await review.setLineInventoryCandidates('line-1', ['DSV360_AWSDU'], 'Confirmed with planner');
|
||||
|
||||
|
||||
|
||||
expect(api.putInventoryCandidates).toHaveBeenCalledWith('CASE-1', 'line-1', {
|
||||
|
||||
expected_draft_version: 2,
|
||||
|
||||
source_codes: ['DSV360_AWSDU'],
|
||||
|
||||
reason: 'Confirmed with planner',
|
||||
|
||||
});
|
||||
|
||||
expect(review.activeCase.value?.draft?.draft_version).toBe(3);
|
||||
|
||||
expect(review.buildEligibility.value?.can_build).toBe(true);
|
||||
|
||||
expect(review.canConfirmBuild.value).toBe(true);
|
||||
|
||||
});
|
||||
|
||||
|
||||
|
||||
it('blocks confirm when build eligibility cannot build', async () => {
|
||||
|
||||
const review = useShippingOrderReview();
|
||||
|
||||
await review.load('RUN-1', 'CASE-1');
|
||||
|
||||
|
||||
|
||||
await expect(review.confirm()).rejects.toMatchObject({
|
||||
|
||||
code: REVIEW_BUILD_ELIGIBILITY_BLOCKED,
|
||||
|
||||
});
|
||||
|
||||
expect(api.confirmCase).not.toHaveBeenCalled();
|
||||
|
||||
});
|
||||
|
||||
it('starts workflow progress polling after successful confirm', async () => {
|
||||
vi.useFakeTimers();
|
||||
const readyCase: ShippingOrderReviewCase = {
|
||||
case_no: 'CASE-1',
|
||||
run_no: 'RUN-1',
|
||||
document: { id: 1, file_name: 'a.pdf' },
|
||||
status: 'ready',
|
||||
schema: { schema_version_id: 1, fields: [] },
|
||||
draft: {
|
||||
draft_version: 2,
|
||||
header_values: { values: {} },
|
||||
lines: [],
|
||||
issues: [],
|
||||
validation: {},
|
||||
build_eligibility: {
|
||||
can_build: true,
|
||||
status: 'ready',
|
||||
line_projections: [],
|
||||
},
|
||||
},
|
||||
available_actions: ['edit_draft', 'confirm'],
|
||||
};
|
||||
api.getCase.mockResolvedValue(readyCase);
|
||||
api.getRun.mockResolvedValue({
|
||||
run_no: 'RUN-1',
|
||||
summary: {},
|
||||
items: [{ case_no: 'CASE-1', document_id: 1, status: 'ready', available_actions: ['confirm'] }],
|
||||
});
|
||||
api.getEvidence.mockResolvedValue({ items: [] });
|
||||
api.getPreview.mockResolvedValue({ preview_url: '' });
|
||||
api.listWorkflows.mockResolvedValue({ conversation_id: 'conv-1', workflows: [] });
|
||||
api.getWorkflowItem.mockResolvedValue({
|
||||
item_no: 'WFI-1',
|
||||
workflow_no: 'WF-1',
|
||||
lifecycle_status: 'building_order',
|
||||
current_stage: 'building_order',
|
||||
current_task_no: 'SN-1',
|
||||
current_version_no: 1,
|
||||
});
|
||||
api.confirmCase.mockResolvedValue({
|
||||
task_no: 'SN-1',
|
||||
idempotent_replay: false,
|
||||
workflow_id: 'WF-1',
|
||||
workflow_item_id: 'WFI-1',
|
||||
case: { ...readyCase, status: 'confirmed' },
|
||||
auto_progress_started: true,
|
||||
});
|
||||
|
||||
const review = useShippingOrderReview();
|
||||
await review.load('RUN-1', 'CASE-1', { conversationId: 'conv-1', itemNo: 'WFI-1' });
|
||||
const response = await review.confirm();
|
||||
|
||||
expect(response?.workflow_item_id).toBe('WFI-1');
|
||||
expect(review.showWorkflowProgress.value).toBe(true);
|
||||
expect(review.workflowProgressPolling.value).toBe(true);
|
||||
expect(api.getWorkflowItem).toHaveBeenCalled();
|
||||
|
||||
api.getWorkflowItem.mockResolvedValue({
|
||||
item_no: 'WFI-1',
|
||||
workflow_no: 'WF-1',
|
||||
lifecycle_status: 'manual_upload_pending',
|
||||
current_stage: 'manual_upload_pending',
|
||||
current_task_no: 'SN-1',
|
||||
current_version_no: 1,
|
||||
});
|
||||
await vi.advanceTimersByTimeAsync(2600);
|
||||
expect(review.workItem.value?.lifecycle_status).toBe('manual_upload_pending');
|
||||
expect(review.workflowProgressPolling.value).toBe(false);
|
||||
|
||||
review.stopWorkflowProgressPolling();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
});
|
||||
@@ -1,10 +1,14 @@
|
||||
/**
|
||||
* features/chat/shipping-review/useShippingOrderReview.ts
|
||||
* 用途:加载建单前复核 Run、当前 PDF Case 与会话工作项版本上下文。
|
||||
* 依赖:shipping API session-work-items / versions、Vue 响应式状态。
|
||||
* 逻辑:路由刷新后以 runNo 重建列表;阶段 3 写入后刷新工作项;历史版本强制只读。
|
||||
* 用途:加载建单前复核 Run、当前 PDF Case 与 WorkflowItem 版本上下文。
|
||||
* 依赖:shipping API workflows / workflow-items、Vue 响应式状态、BusinessError。
|
||||
* 逻辑:路由刷新后以 runNo 重建列表;阶段 3 写入后刷新 WorkflowItem;历史版本与已关闭项强制只读;
|
||||
* 识别 REVIEW_DRAFT_VERSION_MISMATCH 后引导重新加载服务端最新草稿;
|
||||
* build_eligibility 投影驱动建单门禁与行级库存候选人工选择;
|
||||
* 确认后挂载进度轮询直至 manual_upload_pending / 路由离开;版本历史由 Item 派生。
|
||||
*/
|
||||
import { computed, ref } from 'vue';
|
||||
import { computed, getCurrentInstance, onBeforeUnmount, ref } from 'vue';
|
||||
import { BusinessError } from '@/shared/api/client';
|
||||
import {
|
||||
addWorkspaceShippingOrderReviewLine,
|
||||
createWorkspaceShippingOrderReviewManualDraft,
|
||||
@@ -18,29 +22,109 @@ import {
|
||||
getWorkspaceShippingOrderReviewPreview,
|
||||
getShippingNoticeIntake,
|
||||
getWorkspaceShippingOrderReviewRun,
|
||||
listWorkspaceShippingSessionWorkItemVersions,
|
||||
listWorkspaceShippingSessionWorkItems,
|
||||
getWorkspaceShippingWorkflowItem,
|
||||
listWorkspaceShippingWorkflows,
|
||||
patchWorkspaceShippingOrderReviewHeaderField,
|
||||
patchWorkspaceShippingOrderReviewLineField,
|
||||
markWorkspaceShippingOrderReviewNonOrder,
|
||||
markWorkspaceShippingOrderReviewQualityIssue,
|
||||
putWorkspaceShippingOrderReviewInventoryCandidates,
|
||||
reparseWorkspaceShippingOrderReviewDocument,
|
||||
validateWorkspaceShippingOrderReviewDraft,
|
||||
} from '../api/shipping.api';
|
||||
import type {
|
||||
ShippingOrderReviewBuildEligibility,
|
||||
ShippingOrderReviewBuildEligibilityLineProjection,
|
||||
ShippingOrderReviewCase,
|
||||
ShippingOrderReviewEvidence,
|
||||
ShippingOrderReviewRun,
|
||||
ShippingSessionWorkItem,
|
||||
ShippingSessionWorkItemVersion,
|
||||
ShippingWorkflowItem,
|
||||
ShippingWorkflowItemVersion,
|
||||
} from '../types/shipping.api.types';
|
||||
import { uploadFileAsset } from '@/shared/api/file-assets.api';
|
||||
import { deriveWorkflowItemVersions } from './deriveWorkflowItemVersions';
|
||||
|
||||
/** 复核页顶部状态横幅类型。 */
|
||||
export type ReviewStatusMessage = 'superseded' | 'reparse_in_progress' | 'restored' | null;
|
||||
export type ReviewStatusMessage =
|
||||
| 'superseded'
|
||||
| 'work_item_closed'
|
||||
| 'reparse_in_progress'
|
||||
| 'restored'
|
||||
| 'draft_version_conflict'
|
||||
| null;
|
||||
|
||||
/** 服务端草稿版本冲突错误码(与后端 ConflictError.code 对齐)。 */
|
||||
export const REVIEW_DRAFT_VERSION_MISMATCH = 'SHIPPING.REVIEW_DRAFT_VERSION_MISMATCH';
|
||||
|
||||
/** 建单资格未满足时 confirm 阻断错误码。 */
|
||||
export const REVIEW_BUILD_ELIGIBILITY_BLOCKED = 'SHIPPING.REVIEW_BUILD_ELIGIBILITY_BLOCKED';
|
||||
|
||||
/** 库存相关建单阻断原因码;用于筛选需人工选源的行。 */
|
||||
const INVENTORY_BLOCK_REASONS = new Set([
|
||||
'require_manual_review',
|
||||
'no_inventory_source_candidates',
|
||||
'manual_inventory_source_reason_required',
|
||||
'manual_inventory_source_invalid',
|
||||
'inventory_source_unresolved',
|
||||
]);
|
||||
|
||||
/** 草稿版本冲突上下文:保留本地过期草稿与已拉取的服务端最新 Case,供自助恢复。 */
|
||||
export type DraftVersionConflict = {
|
||||
localVersion: number;
|
||||
serverVersion: number | null;
|
||||
serverCase: ShippingOrderReviewCase | null;
|
||||
showDiff: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* 判断写路径错误是否为草稿乐观锁冲突。
|
||||
* @param error - 捕获的未知错误
|
||||
*/
|
||||
export function isDraftVersionMismatchError(error: unknown): boolean {
|
||||
return error instanceof BusinessError && error.code === REVIEW_DRAFT_VERSION_MISMATCH;
|
||||
}
|
||||
|
||||
/**
|
||||
* 汇总本地与服务端草稿的粗粒度差异(版本/状态/问题数/头字段值),供冲突提示。
|
||||
* @param localCase - 页面仍持有的过期 Case
|
||||
* @param serverCase - 刚拉取的服务端最新 Case
|
||||
*/
|
||||
export function summarizeDraftConflictDiff(
|
||||
localCase: ShippingOrderReviewCase | null,
|
||||
serverCase: ShippingOrderReviewCase | null,
|
||||
): string[] {
|
||||
if (!localCase || !serverCase) return [];
|
||||
const lines: string[] = [];
|
||||
const localVer = localCase.draft?.draft_version;
|
||||
const serverVer = serverCase.draft?.draft_version;
|
||||
if (localVer !== serverVer) {
|
||||
lines.push(`draft_version: local=${localVer ?? '-'} server=${serverVer ?? '-'}`);
|
||||
}
|
||||
if (localCase.status !== serverCase.status) {
|
||||
lines.push(`status: local=${localCase.status} server=${serverCase.status}`);
|
||||
}
|
||||
const localIssues = localCase.draft?.issues?.length ?? 0;
|
||||
const serverIssues = serverCase.draft?.issues?.length ?? 0;
|
||||
if (localIssues !== serverIssues) {
|
||||
lines.push(`issues: local=${localIssues} server=${serverIssues}`);
|
||||
}
|
||||
const localHeader = (localCase.draft?.header_values?.values || {}) as Record<string, { value?: unknown }>;
|
||||
const serverHeader = (serverCase.draft?.header_values?.values || {}) as Record<string, { value?: unknown }>;
|
||||
const fieldIds = new Set([...Object.keys(localHeader), ...Object.keys(serverHeader)]);
|
||||
for (const fieldId of fieldIds) {
|
||||
const left = String(localHeader[fieldId]?.value ?? '');
|
||||
const right = String(serverHeader[fieldId]?.value ?? '');
|
||||
if (left !== right) lines.push(`header.${fieldId}: local=${left || '∅'} server=${right || '∅'}`);
|
||||
}
|
||||
return lines.slice(0, 12);
|
||||
}
|
||||
|
||||
type ReviewCaseRef = { case_no: string; status: string } | null | undefined;
|
||||
type WorkItemRef = { current_case_no?: string | null; version_replaced?: boolean } | null | undefined;
|
||||
type WorkItemRef = {
|
||||
current_case_no?: string | null;
|
||||
version_replaced?: boolean;
|
||||
lifecycle_status?: string | null;
|
||||
} | null | undefined;
|
||||
|
||||
/**
|
||||
* 判断当前 Case 是否为历史/被替代版本(强制只读)。
|
||||
@@ -53,21 +137,116 @@ export function isReviewCaseHistorical(activeCase: ReviewCaseRef, workItem: Work
|
||||
return Boolean(workItem?.version_replaced && currentCaseNo && caseNo !== currentCaseNo);
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断关联 WorkflowItem 是否已关闭(取消/确认/非订单/管理员终止)。
|
||||
*/
|
||||
export function isReviewWorkItemClosed(workItem: WorkItemRef): boolean {
|
||||
const status = String(workItem?.lifecycle_status || '').trim();
|
||||
return status === 'closed'
|
||||
|| status === 'cancelled'
|
||||
|| status === 'manual_upload_pending';
|
||||
}
|
||||
|
||||
/**
|
||||
* 复核页是否应强制只读:历史版本或工作项已关闭。
|
||||
*/
|
||||
export function isReviewReadOnly(activeCase: ReviewCaseRef, workItem: WorkItemRef): boolean {
|
||||
return isReviewCaseHistorical(activeCase, workItem) || isReviewWorkItemClosed(workItem);
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断整单 build_eligibility 是否阻断确认建单。
|
||||
* @param eligibility - Case draft 投影的建单资格;缺省时不阻断。
|
||||
*/
|
||||
export function isBuildConfirmBlocked(eligibility?: ShippingOrderReviewBuildEligibility | null): boolean {
|
||||
return Boolean(eligibility && eligibility.can_build === false);
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断明细是否因库存路由需人工选择候选源。
|
||||
* 核心逻辑:行级 can_build 为 false 且存在可选候选或库存阻断原因码。
|
||||
*/
|
||||
export function lineNeedsManualInventorySelection(
|
||||
line: ShippingOrderReviewBuildEligibilityLineProjection,
|
||||
): boolean {
|
||||
if (line.can_build !== false) return false;
|
||||
const codes = line.candidate_inventory_source_codes || [];
|
||||
if (codes.length > 0) return true;
|
||||
return INVENTORY_BLOCK_REASONS.has(String(line.block_reason || '').trim());
|
||||
}
|
||||
|
||||
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 workItem = ref<ShippingWorkflowItem | null>(null);
|
||||
const versions = ref<ShippingWorkflowItemVersion[]>([]);
|
||||
const statusMessage = ref<ReviewStatusMessage>(null);
|
||||
const loading = ref(false);
|
||||
const loadFailed = ref(false);
|
||||
const saving = ref(false);
|
||||
const saveFailed = ref(false);
|
||||
/** 草稿版本冲突上下文;非空时顶部横幅优先展示冲突恢复入口。 */
|
||||
const draftConflict = ref<DraftVersionConflict | null>(null);
|
||||
const versionsLoading = ref(false);
|
||||
const evidence = ref<ShippingOrderReviewEvidence[]>([]);
|
||||
const previewUrl = ref('');
|
||||
/** 确认后是否展示并轮询 Workflow 自动进度。 */
|
||||
const showWorkflowProgress = ref(false);
|
||||
const workflowProgressPolling = ref(false);
|
||||
let contextConversationId = '';
|
||||
let contextItemNo = '';
|
||||
let progressPollTimer: ReturnType<typeof window.setInterval> | null = null;
|
||||
const PROGRESS_POLL_MS = 2500;
|
||||
const PROGRESS_TERMINAL = new Set([
|
||||
'manual_upload_pending',
|
||||
'closed',
|
||||
'cancelled',
|
||||
'failed',
|
||||
]);
|
||||
|
||||
/**
|
||||
* 停止确认后 WorkflowItem 进度轮询(路由离开 / 终态时调用)。
|
||||
*/
|
||||
const stopWorkflowProgressPolling = () => {
|
||||
if (progressPollTimer != null) {
|
||||
window.clearInterval(progressPollTimer);
|
||||
progressPollTimer = null;
|
||||
}
|
||||
workflowProgressPolling.value = false;
|
||||
};
|
||||
|
||||
/**
|
||||
* 确认建单后持续刷新 WorkflowItem,直至待上传或失败终态。
|
||||
* 核心逻辑:仅轮询已绑定 item_no;离开页面由 onBeforeUnmount 清理。
|
||||
*/
|
||||
const startWorkflowProgressPolling = (itemNo?: string | null) => {
|
||||
stopWorkflowProgressPolling();
|
||||
const target = String(itemNo || workItem.value?.item_no || contextItemNo || '').trim();
|
||||
if (!target) return;
|
||||
showWorkflowProgress.value = true;
|
||||
workflowProgressPolling.value = true;
|
||||
const tick = async () => {
|
||||
try {
|
||||
const latest = await getWorkspaceShippingWorkflowItem(target);
|
||||
workItem.value = latest;
|
||||
versions.value = deriveWorkflowItemVersions(latest);
|
||||
if (PROGRESS_TERMINAL.has(String(latest.lifecycle_status || '').trim())) {
|
||||
stopWorkflowProgressPolling();
|
||||
}
|
||||
} catch {
|
||||
/* 瞬时失败保留上一帧,下一轮继续。 */
|
||||
}
|
||||
};
|
||||
void tick();
|
||||
progressPollTimer = window.setInterval(() => { void tick(); }, PROGRESS_POLL_MS);
|
||||
};
|
||||
|
||||
// 仅在组件 setup 内注册;单测直接调用 composable 时跳过,避免 Vue warn。
|
||||
if (getCurrentInstance()) {
|
||||
onBeforeUnmount(() => {
|
||||
stopWorkflowProgressPolling();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 是否正在查看非当前版本或已被替代的 Case。
|
||||
@@ -76,61 +255,94 @@ export function useShippingOrderReview() {
|
||||
isReviewCaseHistorical(activeCase.value, workItem.value),
|
||||
);
|
||||
|
||||
/** 关联工作项是否已关闭(仅保留追溯)。 */
|
||||
const isWorkItemClosed = computed(() => isReviewWorkItemClosed(workItem.value));
|
||||
|
||||
/** 历史版本或已关闭工作项均强制只读。 */
|
||||
const isReadOnly = computed(() => isReviewReadOnly(activeCase.value, workItem.value));
|
||||
|
||||
/**
|
||||
* 编辑权限:历史版本或后端未开放 edit_draft 时强制只读。
|
||||
* 编辑权限:历史版本、已关闭工作项或后端未开放 edit_draft 时强制只读。
|
||||
*/
|
||||
const editable = computed(() => {
|
||||
if (isViewingHistoricalVersion.value) return false;
|
||||
if (isReadOnly.value) return false;
|
||||
return activeCase.value?.available_actions.includes('edit_draft') || false;
|
||||
});
|
||||
|
||||
/**
|
||||
* 根据工作项与 Case 状态刷新顶部横幅文案键。
|
||||
* 核心逻辑:未解除的草稿版本冲突优先于其他状态横幅。
|
||||
*/
|
||||
const refreshStatusMessage = () => {
|
||||
if (draftConflict.value) {
|
||||
statusMessage.value = 'draft_version_conflict';
|
||||
return;
|
||||
}
|
||||
if (isViewingHistoricalVersion.value || activeCase.value?.status === 'superseded') {
|
||||
statusMessage.value = 'superseded';
|
||||
return;
|
||||
}
|
||||
if (isWorkItemClosed.value) {
|
||||
statusMessage.value = 'work_item_closed';
|
||||
return;
|
||||
}
|
||||
if (
|
||||
activeCase.value?.status === 'reparse_pending'
|
||||
|| workItem.value?.lifecycle_status === 'extracting'
|
||||
|| workItem.value?.lifecycle_status === 'layout_parsing'
|
||||
) {
|
||||
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 draftConflictDiffLines = computed(() =>
|
||||
summarizeDraftConflictDiff(activeCase.value, draftConflict.value?.serverCase || null),
|
||||
);
|
||||
|
||||
/** 当前 Case 草稿上的建单资格投影;validate 后刷新。 */
|
||||
const buildEligibility = computed(
|
||||
() => activeCase.value?.draft?.build_eligibility ?? null,
|
||||
);
|
||||
|
||||
/** 存在 build_eligibility 且 can_build 为 false 时禁止确认建单。 */
|
||||
const canConfirmBuild = computed(() => !isBuildConfirmBlocked(buildEligibility.value));
|
||||
|
||||
/** 需人工选择库存源候选的明细行投影。 */
|
||||
const manualInventoryLines = computed(() =>
|
||||
(buildEligibility.value?.line_projections || []).filter(lineNeedsManualInventorySelection),
|
||||
);
|
||||
|
||||
/**
|
||||
* 从会话 Workflow 投影解析 Item;优先 item_no,再按 current_case_no 匹配。
|
||||
*/
|
||||
const resolveWorkItem = async (
|
||||
conversationId: string,
|
||||
options?: { itemNo?: string; caseNo?: string },
|
||||
): Promise<ShippingSessionWorkItem | null> => {
|
||||
): Promise<ShippingWorkflowItem | 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;
|
||||
try {
|
||||
return await getWorkspaceShippingWorkflowItem(explicitItemNo);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
const projection = await listWorkspaceShippingWorkflows(conversation);
|
||||
const allItems = (projection.workflows || []).flatMap((row) => row.items || []);
|
||||
const caseNo = String(options?.caseNo || activeCase.value?.case_no || '').trim();
|
||||
if (!caseNo) return null;
|
||||
return allItems.find((item) => item.current_case_no === caseNo) || null;
|
||||
};
|
||||
|
||||
/**
|
||||
* 拉取工作项与版本时间线;写入后或路由变化时复用。
|
||||
* 拉取 WorkflowItem 与派生版本时间线;写入后或路由变化时复用。
|
||||
*/
|
||||
const refreshWorkItemContext = async (conversationId?: string, itemNo?: string) => {
|
||||
const conversation = String(conversationId || contextConversationId || '').trim();
|
||||
@@ -150,8 +362,14 @@ export function useShippingOrderReview() {
|
||||
}
|
||||
contextItemNo = item.item_no;
|
||||
versionsLoading.value = true;
|
||||
const response = await listWorkspaceShippingSessionWorkItemVersions(item.item_no);
|
||||
versions.value = response.versions || [];
|
||||
let detail = item;
|
||||
try {
|
||||
detail = await getWorkspaceShippingWorkflowItem(item.item_no);
|
||||
workItem.value = detail;
|
||||
} catch {
|
||||
/* 列表投影仍可用于只读门禁 */
|
||||
}
|
||||
versions.value = deriveWorkflowItemVersions(detail);
|
||||
} catch {
|
||||
workItem.value = null;
|
||||
versions.value = [];
|
||||
@@ -169,6 +387,8 @@ export function useShippingOrderReview() {
|
||||
) => {
|
||||
loading.value = true;
|
||||
loadFailed.value = false;
|
||||
draftConflict.value = null;
|
||||
saveFailed.value = false;
|
||||
if (options?.conversationId) contextConversationId = options.conversationId;
|
||||
if (options?.itemNo) contextItemNo = options.itemNo;
|
||||
try {
|
||||
@@ -222,8 +442,10 @@ export function useShippingOrderReview() {
|
||||
const save = async (action: () => Promise<ShippingOrderReviewCase>) => {
|
||||
saving.value = true;
|
||||
saveFailed.value = false;
|
||||
const localVersion = version();
|
||||
try {
|
||||
activeCase.value = await action();
|
||||
draftConflict.value = null;
|
||||
if (reviewRun.value && activeCase.value) {
|
||||
const item = reviewRun.value.items.find((row) => row.case_no === activeCase.value?.case_no);
|
||||
if (item) {
|
||||
@@ -234,45 +456,156 @@ export function useShippingOrderReview() {
|
||||
}
|
||||
await refreshWorkItemContext();
|
||||
} catch (error) {
|
||||
saveFailed.value = true;
|
||||
await markWriteFailure(error, localVersion);
|
||||
throw error;
|
||||
} finally {
|
||||
saving.value = false;
|
||||
}
|
||||
};
|
||||
const version = () => activeCase.value?.draft?.draft_version || 0;
|
||||
|
||||
/**
|
||||
* 识别草稿版本冲突并拉取服务端最新 Case,供横幅展示恢复入口。
|
||||
* 核心逻辑:非版本冲突仅置 saveFailed;冲突时额外写入 draftConflict 与横幅状态。
|
||||
* @param error - 写路径抛出的错误
|
||||
* @param localVersion - 请求时使用的本地草稿版本
|
||||
*/
|
||||
const markWriteFailure = async (error: unknown, localVersion: number) => {
|
||||
saveFailed.value = true;
|
||||
if (!isDraftVersionMismatchError(error) || !activeCase.value) {
|
||||
refreshStatusMessage();
|
||||
return;
|
||||
}
|
||||
let serverCase: ShippingOrderReviewCase | null = null;
|
||||
let serverVersion: number | null = null;
|
||||
try {
|
||||
serverCase = await getWorkspaceShippingOrderReviewCase(activeCase.value.case_no);
|
||||
serverVersion = serverCase.draft?.draft_version ?? null;
|
||||
} catch {
|
||||
/* 拉取失败仍展示冲突横幅,用户可重试重新加载。 */
|
||||
}
|
||||
draftConflict.value = {
|
||||
localVersion,
|
||||
serverVersion,
|
||||
serverCase,
|
||||
showDiff: false,
|
||||
};
|
||||
statusMessage.value = 'draft_version_conflict';
|
||||
};
|
||||
|
||||
/**
|
||||
* 用服务端最新 Case 替换本地过期草稿,清除冲突态后恢复可编辑。
|
||||
*/
|
||||
const reloadLatestDraft = async () => {
|
||||
if (!activeCase.value) return;
|
||||
const caseNo = activeCase.value.case_no;
|
||||
saving.value = true;
|
||||
try {
|
||||
if (draftConflict.value?.serverCase) {
|
||||
activeCase.value = draftConflict.value.serverCase;
|
||||
evidence.value = (await getWorkspaceShippingOrderReviewEvidence(caseNo)).items;
|
||||
} else {
|
||||
await selectCase(caseNo);
|
||||
}
|
||||
if (reviewRun.value && activeCase.value) {
|
||||
const item = reviewRun.value.items.find((row) => row.case_no === caseNo);
|
||||
if (item) {
|
||||
item.status = activeCase.value.status;
|
||||
item.draft_version = activeCase.value.draft?.draft_version;
|
||||
item.issue_count = activeCase.value.draft?.issues.length || 0;
|
||||
}
|
||||
}
|
||||
draftConflict.value = null;
|
||||
saveFailed.value = false;
|
||||
await refreshWorkItemContext();
|
||||
} finally {
|
||||
saving.value = false;
|
||||
refreshStatusMessage();
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 切换冲突差异面板显隐。
|
||||
*/
|
||||
const toggleConflictDiff = () => {
|
||||
if (!draftConflict.value) return;
|
||||
draftConflict.value = {
|
||||
...draftConflict.value,
|
||||
showDiff: !draftConflict.value.showDiff,
|
||||
};
|
||||
};
|
||||
|
||||
const patchHeader = (fieldId: string, value: unknown, restoreMachine = false) => {
|
||||
if (!activeCase.value) return Promise.resolve();
|
||||
return save(() => patchWorkspaceShippingOrderReviewHeaderField(activeCase.value!.case_no, fieldId, {
|
||||
expected_draft_version: version(), value, restore_machine: restoreMachine,
|
||||
}));
|
||||
};
|
||||
const patchLine = (lineKey: string, fieldId: string, value: unknown, restoreMachine = false) => {
|
||||
const patchLine = (
|
||||
lineKey: string,
|
||||
fieldId: string,
|
||||
value: unknown,
|
||||
restoreMachine = false,
|
||||
override?: { override_reason_code?: string; override_reason_text?: string },
|
||||
) => {
|
||||
if (!activeCase.value) return Promise.resolve();
|
||||
return save(() => patchWorkspaceShippingOrderReviewLineField(activeCase.value!.case_no, lineKey, fieldId, {
|
||||
expected_draft_version: version(), value, restore_machine: restoreMachine,
|
||||
expected_draft_version: version(),
|
||||
value,
|
||||
restore_machine: restoreMachine,
|
||||
override_reason_code: override?.override_reason_code,
|
||||
override_reason_text: override?.override_reason_text,
|
||||
}));
|
||||
};
|
||||
const addLine = () => activeCase.value && save(() => addWorkspaceShippingOrderReviewLine(activeCase.value!.case_no, version()));
|
||||
const copyLine = (lineKey: string) => activeCase.value && save(() => copyWorkspaceShippingOrderReviewLine(activeCase.value!.case_no, lineKey, version()));
|
||||
const deleteLine = (lineKey: string) => activeCase.value && save(() => deleteWorkspaceShippingOrderReviewLine(activeCase.value!.case_no, lineKey, version()));
|
||||
const validate = () => activeCase.value && save(() => validateWorkspaceShippingOrderReviewDraft(activeCase.value!.case_no, version()));
|
||||
|
||||
/**
|
||||
* 为指定明细提交人工库存源候选并刷新 Case。
|
||||
* @param lineKey - Draft 行 line_key
|
||||
* @param sourceCodes - 已启用库存源编码(可多选)
|
||||
* @param reason - 强制人工说明
|
||||
*/
|
||||
const setLineInventoryCandidates = (lineKey: string, sourceCodes: string[], reason: string) => {
|
||||
if (!activeCase.value) return Promise.resolve();
|
||||
return save(() => putWorkspaceShippingOrderReviewInventoryCandidates(activeCase.value!.case_no, lineKey, {
|
||||
expected_draft_version: version(),
|
||||
source_codes: sourceCodes,
|
||||
reason,
|
||||
}));
|
||||
};
|
||||
|
||||
/** 确认动作不复用自动保存:服务端返回 Task 与只读 Case,而不是仅草稿 DTO。 */
|
||||
const confirm = async () => {
|
||||
if (!activeCase.value) return null;
|
||||
if (isBuildConfirmBlocked(buildEligibility.value)) {
|
||||
throw new BusinessError({
|
||||
message: 'Build eligibility blocked',
|
||||
code: REVIEW_BUILD_ELIGIBILITY_BLOCKED,
|
||||
});
|
||||
}
|
||||
saving.value = true;
|
||||
saveFailed.value = false;
|
||||
const localVersion = version();
|
||||
try {
|
||||
const response = await confirmWorkspaceShippingOrderReviewCase(activeCase.value.case_no, {
|
||||
expected_draft_version: version(),
|
||||
expected_draft_version: localVersion,
|
||||
idempotency_key: crypto.randomUUID(),
|
||||
});
|
||||
activeCase.value = response.case;
|
||||
draftConflict.value = null;
|
||||
if (reviewRun.value) reviewRun.value = await getWorkspaceShippingOrderReviewRun(reviewRun.value.run_no);
|
||||
await refreshWorkItemContext();
|
||||
const itemNo = String(
|
||||
response.workflow_item_id || workItem.value?.item_no || contextItemNo || '',
|
||||
).trim();
|
||||
if (itemNo) contextItemNo = itemNo;
|
||||
startWorkflowProgressPolling(itemNo || null);
|
||||
return response;
|
||||
} catch (error) {
|
||||
saveFailed.value = true;
|
||||
await markWriteFailure(error, localVersion);
|
||||
throw error;
|
||||
} finally {
|
||||
saving.value = false;
|
||||
@@ -371,10 +704,19 @@ export function useShippingOrderReview() {
|
||||
workItem,
|
||||
versions,
|
||||
statusMessage,
|
||||
draftConflict,
|
||||
draftConflictDiffLines,
|
||||
buildEligibility,
|
||||
canConfirmBuild,
|
||||
manualInventoryLines,
|
||||
isViewingHistoricalVersion,
|
||||
isWorkItemClosed,
|
||||
isReadOnly,
|
||||
editable,
|
||||
evidence,
|
||||
previewUrl,
|
||||
showWorkflowProgress,
|
||||
workflowProgressPolling,
|
||||
loading,
|
||||
loadFailed,
|
||||
saving,
|
||||
@@ -385,13 +727,18 @@ export function useShippingOrderReview() {
|
||||
refreshWorkItemContext,
|
||||
currentVersionTarget,
|
||||
openCurrentVersion,
|
||||
reloadLatestDraft,
|
||||
toggleConflictDiff,
|
||||
patchHeader,
|
||||
patchLine,
|
||||
addLine,
|
||||
copyLine,
|
||||
deleteLine,
|
||||
validate,
|
||||
setLineInventoryCandidates,
|
||||
confirm,
|
||||
startWorkflowProgressPolling,
|
||||
stopWorkflowProgressPolling,
|
||||
createManualDraft,
|
||||
markNonOrder,
|
||||
markQualityIssue,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/**
|
||||
* features/chat/shipping/orderExtractionHandlingRefs.ts
|
||||
* 用途:Run 级 handling_items.affected_refs 的展示文案与跳转目标解析。
|
||||
* 依赖:无业务 API;由 ShippingOrderExtractionCard / ShippingSessionSummaryPanel 调用。
|
||||
* 依赖:无业务 API;由 ShippingOrderExtractionCard / ShippingWorkflowTimeline 调用。
|
||||
* 逻辑:只消费后端受控引用(task/candidate/document/attachment),禁止前端发明对象标识。
|
||||
*/
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/**
|
||||
* features/chat/shipping/orderExtractionProgressDisplay.ts
|
||||
* 用途:订单抽取进度展示的纯函数(阶段文案 key、耗时格式化),禁止前端发明阶段码。
|
||||
* 依赖:无;由 ShippingOrderExtractionCard / ShippingSessionSummaryPanel 调用。
|
||||
* 依赖:无;由 ShippingOrderExtractionCard / ShippingWorkflowTimeline 调用。
|
||||
* 逻辑:仅映射后端投影字段到 i18n key 与可读耗时;阈值与阶段判定一律以后端为准。
|
||||
*/
|
||||
|
||||
|
||||
@@ -0,0 +1,201 @@
|
||||
/**
|
||||
* features/chat/shipping/useShippingNoticeWorkflow.spec.ts
|
||||
* 用途:覆盖 Workflow 轮询退避、多批次选择、停轮询条件与取消/重识别后刷新。
|
||||
* 依赖:Vitest、vue、shipping.api mock。
|
||||
* 逻辑:断言 backoff 封顶、终态停轮询、选中保留、cancelItem/reparseItem 调 API 后 refresh。
|
||||
*/
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { nextTick, ref } from 'vue';
|
||||
import {
|
||||
resolveSelectedWorkflowNo,
|
||||
resolveWorkflowPollBackoffMs,
|
||||
shouldContinueWorkflowPolling,
|
||||
useShippingNoticeWorkflow,
|
||||
} from './useShippingNoticeWorkflow';
|
||||
import type { ShippingWorkflow, ShippingWorkflowItem } from '../types/shipping.api.types';
|
||||
|
||||
const api = vi.hoisted(() => ({
|
||||
listWorkflows: vi.fn(),
|
||||
cancelItem: vi.fn(),
|
||||
reparseItem: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('../api/shipping.api', () => ({
|
||||
listWorkspaceShippingWorkflows: api.listWorkflows,
|
||||
cancelWorkspaceShippingWorkflowItem: api.cancelItem,
|
||||
reparseWorkspaceShippingWorkflowItem: api.reparseItem,
|
||||
}));
|
||||
|
||||
function buildItem(patch: Partial<ShippingWorkflowItem> = {}): ShippingWorkflowItem {
|
||||
return {
|
||||
item_no: 'SWI-1',
|
||||
workflow_no: 'SNWF-1',
|
||||
conversation_id: 'conv-1',
|
||||
root_document_id: 1,
|
||||
current_document_id: 1,
|
||||
current_document_filename: 'notice-a.pdf',
|
||||
current_version_no: 1,
|
||||
lifecycle_status: 'layout_parsing',
|
||||
current_stage: 'layout_parsing',
|
||||
lock_version: 1,
|
||||
...patch,
|
||||
};
|
||||
}
|
||||
|
||||
function buildWorkflow(patch: Partial<ShippingWorkflow> = {}): ShippingWorkflow {
|
||||
const items = patch.items ?? [buildItem()];
|
||||
return {
|
||||
workflow_no: 'SNWF-1',
|
||||
conversation_id: 'conv-1',
|
||||
status: 'open',
|
||||
current_stage: 'layout_parsing',
|
||||
lock_version: 1,
|
||||
counts: {
|
||||
total: items.length,
|
||||
processing: items.length,
|
||||
pending_review: 0,
|
||||
failed: 0,
|
||||
completed: 0,
|
||||
},
|
||||
items,
|
||||
...patch,
|
||||
};
|
||||
}
|
||||
|
||||
describe('useShippingNoticeWorkflow helpers', () => {
|
||||
it('caps failure backoff at 8s', () => {
|
||||
expect(resolveWorkflowPollBackoffMs(1)).toBe(2000);
|
||||
expect(resolveWorkflowPollBackoffMs(2)).toBe(4000);
|
||||
expect(resolveWorkflowPollBackoffMs(3)).toBe(8000);
|
||||
expect(resolveWorkflowPollBackoffMs(10)).toBe(8000);
|
||||
});
|
||||
|
||||
it('stops polling on terminal workflow status', () => {
|
||||
const workflow = buildWorkflow({ status: 'completed' });
|
||||
expect(shouldContinueWorkflowPolling([workflow])).toBe(false);
|
||||
});
|
||||
|
||||
it('continues while layout_parsing items remain', () => {
|
||||
const items = [buildItem({ lifecycle_status: 'layout_parsing' })];
|
||||
const workflow = buildWorkflow({ status: 'open', items });
|
||||
expect(shouldContinueWorkflowPolling([workflow])).toBe(true);
|
||||
});
|
||||
|
||||
it('stops when open workflow has only closed items', () => {
|
||||
const items = [buildItem({ lifecycle_status: 'closed' })];
|
||||
const workflow = buildWorkflow({ status: 'open', items });
|
||||
expect(shouldContinueWorkflowPolling([workflow])).toBe(false);
|
||||
});
|
||||
|
||||
it('keeps previous selection when still present, else first', () => {
|
||||
const a = buildWorkflow({ workflow_no: 'SNWF-A' });
|
||||
const b = buildWorkflow({ workflow_no: 'SNWF-B' });
|
||||
expect(resolveSelectedWorkflowNo([a, b], 'SNWF-B')).toBe('SNWF-B');
|
||||
expect(resolveSelectedWorkflowNo([a, b], 'SNWF-GONE')).toBe('SNWF-A');
|
||||
expect(resolveSelectedWorkflowNo([a, b], 'SNWF-A', 'SNWF-B')).toBe('SNWF-B');
|
||||
});
|
||||
});
|
||||
|
||||
describe('useShippingNoticeWorkflow', () => {
|
||||
beforeEach(() => {
|
||||
api.listWorkflows.mockReset();
|
||||
api.cancelItem.mockReset();
|
||||
api.reparseItem.mockReset();
|
||||
vi.useFakeTimers();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it('loads open workflow items and exposes cancelItem refresh', async () => {
|
||||
const workflow = buildWorkflow({
|
||||
items: [
|
||||
buildItem({ item_no: 'SWI-A', lifecycle_status: 'extracting' }),
|
||||
buildItem({ item_no: 'SWI-B', lifecycle_status: 'pending_review' }),
|
||||
],
|
||||
});
|
||||
api.listWorkflows.mockResolvedValue({
|
||||
conversation_id: 'conv-1',
|
||||
workflows: [workflow],
|
||||
});
|
||||
api.cancelItem.mockResolvedValue({
|
||||
item: buildItem({ item_no: 'SWI-A', lifecycle_status: 'cancelled' }),
|
||||
});
|
||||
|
||||
const conversationId = ref('conv-1');
|
||||
const ctl = useShippingNoticeWorkflow({ conversationId });
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
await nextTick();
|
||||
await Promise.resolve();
|
||||
|
||||
expect(api.listWorkflows).toHaveBeenCalled();
|
||||
expect(ctl.items.value.map((row) => row.item_no)).toEqual(['SWI-A', 'SWI-B']);
|
||||
expect(ctl.selectedWorkflowNo.value).toBe('SNWF-1');
|
||||
|
||||
await ctl.cancelItem('SWI-A', { reason: 'user cancel', expected_lock_version: 1 });
|
||||
expect(api.cancelItem).toHaveBeenCalledWith('SWI-A', {
|
||||
reason: 'user cancel',
|
||||
expected_lock_version: 1,
|
||||
});
|
||||
expect(api.listWorkflows.mock.calls.length).toBeGreaterThanOrEqual(2);
|
||||
|
||||
ctl.stop();
|
||||
});
|
||||
|
||||
it('selects among multiple workflows and reparses', async () => {
|
||||
const first = buildWorkflow({
|
||||
workflow_no: 'SNWF-1',
|
||||
items: [buildItem({ item_no: 'SWI-1', workflow_no: 'SNWF-1' })],
|
||||
});
|
||||
const second = buildWorkflow({
|
||||
workflow_no: 'SNWF-2',
|
||||
items: [
|
||||
buildItem({
|
||||
item_no: 'SWI-2',
|
||||
workflow_no: 'SNWF-2',
|
||||
lifecycle_status: 'failed',
|
||||
current_document_filename: 'fail.pdf',
|
||||
}),
|
||||
],
|
||||
});
|
||||
api.listWorkflows.mockResolvedValue({
|
||||
conversation_id: 'conv-1',
|
||||
workflows: [first, second],
|
||||
});
|
||||
api.reparseItem.mockResolvedValue({
|
||||
item: buildItem({ item_no: 'SWI-2', lifecycle_status: 'extracting' }),
|
||||
});
|
||||
|
||||
const conversationId = ref('conv-1');
|
||||
const ctl = useShippingNoticeWorkflow({ conversationId });
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
await nextTick();
|
||||
await Promise.resolve();
|
||||
|
||||
expect(ctl.workflows.value).toHaveLength(2);
|
||||
expect(ctl.selectedWorkflowNo.value).toBe('SNWF-1');
|
||||
ctl.selectWorkflow('SNWF-2');
|
||||
expect(ctl.selectedWorkflowNo.value).toBe('SNWF-2');
|
||||
expect(ctl.items.value[0]?.item_no).toBe('SWI-2');
|
||||
|
||||
await ctl.reparseItem('SWI-2', { reason: 'retry', comment: 'note' });
|
||||
expect(api.reparseItem).toHaveBeenCalledWith('SWI-2', {
|
||||
reason: 'retry',
|
||||
comment: 'note',
|
||||
});
|
||||
|
||||
ctl.stop();
|
||||
});
|
||||
|
||||
it('records recoverable error without throwing', async () => {
|
||||
api.listWorkflows.mockRejectedValue(new Error('network down'));
|
||||
const conversationId = ref('conv-1');
|
||||
const ctl = useShippingNoticeWorkflow({ conversationId });
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
await nextTick();
|
||||
await Promise.resolve();
|
||||
expect(ctl.error.value).toBe('network_recoverable');
|
||||
ctl.stop();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,403 @@
|
||||
/**
|
||||
* features/chat/shipping/useShippingNoticeWorkflow.ts
|
||||
* 用途:会话级 Shipping Notice Workflow 前台轮询、批次选择与取消/重识别编排。
|
||||
* 依赖:shipping.api workflows / workflow-items、Vue 响应式、BusinessError。
|
||||
* 逻辑:由 ChatViewContent / ShippingWorkflowTimeline 消费;支持多批次 workflows[];
|
||||
* 选中优先显式选择,否则保留仍在列表中的上一选,否则取首个;
|
||||
* 前台 2s / 后台 8s;请求 10s AbortController 超时;失败指数退避至 8s;终态停轮询。
|
||||
*/
|
||||
import {
|
||||
computed,
|
||||
getCurrentInstance,
|
||||
onBeforeUnmount,
|
||||
ref,
|
||||
unref,
|
||||
watch,
|
||||
type InjectionKey,
|
||||
type MaybeRefOrGetter,
|
||||
type Ref,
|
||||
} from 'vue';
|
||||
import { BusinessError } from '@/shared/api/client';
|
||||
import {
|
||||
cancelWorkspaceShippingWorkflowItem,
|
||||
listWorkspaceShippingWorkflows,
|
||||
reparseWorkspaceShippingWorkflowItem,
|
||||
} from '../api/shipping.api';
|
||||
import type {
|
||||
ShippingWorkflow,
|
||||
ShippingWorkflowItem,
|
||||
} from '../types/shipping.api.types';
|
||||
|
||||
const FOREGROUND_POLL_MS = 2000;
|
||||
const BACKGROUND_POLL_MS = 8000;
|
||||
const REQUEST_TIMEOUT_MS = 10000;
|
||||
const MAX_BACKOFF_MS = 8000;
|
||||
|
||||
/** 仍需轮询的 Item 生命周期(含待人工上传登记;仅 closed/cancelled 为终态)。 */
|
||||
const OPEN_ACTIVE_STATUSES = new Set([
|
||||
'queued',
|
||||
'layout_parsing',
|
||||
'extracting',
|
||||
'building_order',
|
||||
'inventory_matching',
|
||||
'generating_excel',
|
||||
'pending_review',
|
||||
'manual_upload_pending',
|
||||
'reparse_failed',
|
||||
'failed',
|
||||
]);
|
||||
|
||||
/** Workflow 批次终态。 */
|
||||
const TERMINAL_WORKFLOW_STATUSES = new Set(['completed', 'cancelled', 'failed']);
|
||||
|
||||
export type UseShippingNoticeWorkflowOptions = {
|
||||
/** 当前会话 ID;空则停轮询并清空。 */
|
||||
conversationId: MaybeRefOrGetter<string | null | undefined>;
|
||||
/** 父级递增以触发立即刷新(终态/重识别后)。 */
|
||||
refreshTrigger?: MaybeRefOrGetter<number | undefined>;
|
||||
};
|
||||
|
||||
export type UseShippingNoticeWorkflowReturn = {
|
||||
/** 会话内全部开放 Workflow。 */
|
||||
workflows: Ref<ShippingWorkflow[]>;
|
||||
/** 当前选中的 Workflow 编号。 */
|
||||
selectedWorkflowNo: Ref<string | null>;
|
||||
/** 切换选中批次。 */
|
||||
selectWorkflow: (workflowNo: string) => void;
|
||||
/** 当前选中的 Workflow(或 null)。 */
|
||||
workflow: Ref<ShippingWorkflow | null>;
|
||||
/** 当前选中 Workflow 下的 Items。 */
|
||||
items: Ref<ShippingWorkflowItem[]>;
|
||||
loading: Ref<boolean>;
|
||||
error: Ref<string | null>;
|
||||
refresh: () => Promise<void>;
|
||||
cancelItem: (
|
||||
itemNo: string,
|
||||
payload: { reason: string; expected_lock_version?: number | null },
|
||||
) => Promise<ShippingWorkflowItem | null>;
|
||||
reparseItem: (
|
||||
itemNo: string,
|
||||
payload: { reason: string; comment?: string | null },
|
||||
) => Promise<ShippingWorkflowItem | null>;
|
||||
stop: () => void;
|
||||
};
|
||||
|
||||
/** ChatViewContent provide → Timeline / ExtractionCard inject。 */
|
||||
export const SHIPPING_WORKFLOW_KEY: InjectionKey<UseShippingNoticeWorkflowReturn> = Symbol(
|
||||
'shippingNoticeWorkflow',
|
||||
);
|
||||
|
||||
/**
|
||||
* 解析 conversationId / refreshTrigger 的 MaybeRefOrGetter。
|
||||
*/
|
||||
function readOption<T>(source: MaybeRefOrGetter<T>): T {
|
||||
return typeof source === 'function' ? (source as () => T)() : unref(source);
|
||||
}
|
||||
|
||||
/**
|
||||
* 按页面可见性选择轮询间隔。
|
||||
*/
|
||||
function resolvePollMs(): number {
|
||||
if (typeof document !== 'undefined' && document.visibilityState === 'hidden') {
|
||||
return BACKGROUND_POLL_MS;
|
||||
}
|
||||
return FOREGROUND_POLL_MS;
|
||||
}
|
||||
|
||||
/**
|
||||
* 失败退避:2s → 4s → 8s(封顶)。
|
||||
* @param failureCount - 连续失败次数(≥1)
|
||||
*/
|
||||
export function resolveWorkflowPollBackoffMs(failureCount: number): number {
|
||||
const n = Math.max(1, Math.floor(failureCount));
|
||||
return Math.min(FOREGROUND_POLL_MS * (2 ** (n - 1)), MAX_BACKOFF_MS);
|
||||
}
|
||||
|
||||
/**
|
||||
* 在列表中解析应保留的选中 Workflow 编号。
|
||||
* 核心逻辑:显式 preferred → 仍在列表中的 previous → 首个。
|
||||
*/
|
||||
export function resolveSelectedWorkflowNo(
|
||||
list: ShippingWorkflow[],
|
||||
previous: string | null | undefined,
|
||||
preferred?: string | null,
|
||||
): string | null {
|
||||
if (!list.length) return null;
|
||||
const preferredNo = String(preferred || '').trim();
|
||||
if (preferredNo && list.some((row) => row.workflow_no === preferredNo)) {
|
||||
return preferredNo;
|
||||
}
|
||||
const previousNo = String(previous || '').trim();
|
||||
if (previousNo && list.some((row) => row.workflow_no === previousNo)) {
|
||||
return previousNo;
|
||||
}
|
||||
return String(list[0]?.workflow_no || '').trim() || null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断是否应继续轮询。
|
||||
* 核心逻辑:任一非终态 Workflow 仍有开放处理项则继续;空列表停止(等 refreshTrigger 重启)。
|
||||
*/
|
||||
export function shouldContinueWorkflowPolling(
|
||||
workflows: ShippingWorkflow[],
|
||||
): boolean {
|
||||
if (!workflows.length) return false;
|
||||
return workflows.some((workflow) => {
|
||||
const status = String(workflow.status || '').trim();
|
||||
if (TERMINAL_WORKFLOW_STATUSES.has(status)) return false;
|
||||
const items = Array.isArray(workflow.items) ? workflow.items : [];
|
||||
const hasOpen = items.some((item) =>
|
||||
OPEN_ACTIVE_STATUSES.has(String(item.lifecycle_status || '').trim()),
|
||||
);
|
||||
return hasOpen || items.length === 0;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 会话 Workflow 轮询 composable。
|
||||
*
|
||||
* @param options.conversationId - 会话 ID
|
||||
* @param options.refreshTrigger - 外部刷新触发器
|
||||
* @returns workflows / selectedWorkflowNo / selectWorkflow / workflow / items / …
|
||||
*/
|
||||
export function useShippingNoticeWorkflow(
|
||||
options: UseShippingNoticeWorkflowOptions,
|
||||
): UseShippingNoticeWorkflowReturn {
|
||||
const workflows = ref<ShippingWorkflow[]>([]);
|
||||
const selectedWorkflowNo = ref<string | null>(null);
|
||||
/** 用户显式点选后锁定,直到会话切换或列表不再包含该编号。 */
|
||||
const explicitSelectionNo = ref<string | null>(null);
|
||||
const loading = ref(false);
|
||||
const error = ref<string | null>(null);
|
||||
|
||||
let pollTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
let pollGeneration = 0;
|
||||
let requestController: AbortController | null = null;
|
||||
let failureCount = 0;
|
||||
let pollingStopped = false;
|
||||
|
||||
const normalizedConversationId = computed(() =>
|
||||
String(readOption(options.conversationId) || '').trim(),
|
||||
);
|
||||
|
||||
const workflow = computed((): ShippingWorkflow | null => {
|
||||
const no = selectedWorkflowNo.value;
|
||||
if (!no) return null;
|
||||
return workflows.value.find((row) => row.workflow_no === no) || null;
|
||||
});
|
||||
|
||||
const items = computed((): ShippingWorkflowItem[] => (
|
||||
Array.isArray(workflow.value?.items) ? [...workflow.value!.items!] : []
|
||||
));
|
||||
|
||||
/**
|
||||
* 中止进行中的请求与定时器。
|
||||
*/
|
||||
function stop() {
|
||||
pollingStopped = true;
|
||||
if (pollTimer) clearTimeout(pollTimer);
|
||||
pollTimer = null;
|
||||
requestController?.abort();
|
||||
requestController = null;
|
||||
pollGeneration += 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建带超时的 AbortController。
|
||||
*/
|
||||
function createRequestController(): AbortController {
|
||||
requestController?.abort();
|
||||
const controller = new AbortController();
|
||||
requestController = controller;
|
||||
const timeout = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
|
||||
controller.signal.addEventListener('abort', () => clearTimeout(timeout), { once: true });
|
||||
return controller;
|
||||
}
|
||||
|
||||
/**
|
||||
* 用户显式切换批次;写入 preferred 并刷新派生选中项。
|
||||
*/
|
||||
function selectWorkflow(workflowNo: string) {
|
||||
const normalized = String(workflowNo || '').trim();
|
||||
if (!normalized) return;
|
||||
if (!workflows.value.some((row) => row.workflow_no === normalized)) return;
|
||||
explicitSelectionNo.value = normalized;
|
||||
selectedWorkflowNo.value = normalized;
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据列表与显式选择同步 selectedWorkflowNo。
|
||||
*/
|
||||
function syncSelection(list: ShippingWorkflow[]) {
|
||||
const next = resolveSelectedWorkflowNo(
|
||||
list,
|
||||
selectedWorkflowNo.value,
|
||||
explicitSelectionNo.value,
|
||||
);
|
||||
if (explicitSelectionNo.value && next !== explicitSelectionNo.value) {
|
||||
explicitSelectionNo.value = null;
|
||||
}
|
||||
selectedWorkflowNo.value = next;
|
||||
}
|
||||
|
||||
/**
|
||||
* 拉取会话开放 Workflow 列表,并保持选中策略。
|
||||
*/
|
||||
async function refresh(): Promise<void> {
|
||||
const conversationId = normalizedConversationId.value;
|
||||
if (!conversationId) {
|
||||
workflows.value = [];
|
||||
selectedWorkflowNo.value = null;
|
||||
explicitSelectionNo.value = null;
|
||||
error.value = null;
|
||||
return;
|
||||
}
|
||||
if (loading.value) return;
|
||||
loading.value = true;
|
||||
const controller = createRequestController();
|
||||
try {
|
||||
const projection = await listWorkspaceShippingWorkflows(conversationId, {
|
||||
signal: controller.signal,
|
||||
});
|
||||
if (controller.signal.aborted) return;
|
||||
const list = Array.isArray(projection.workflows) ? [...projection.workflows] : [];
|
||||
workflows.value = list;
|
||||
syncSelection(list);
|
||||
error.value = null;
|
||||
failureCount = 0;
|
||||
} catch (err) {
|
||||
if (controller.signal.aborted) return;
|
||||
failureCount += 1;
|
||||
error.value = err instanceof BusinessError
|
||||
? err.message
|
||||
: 'network_recoverable';
|
||||
} finally {
|
||||
if (requestController === controller) requestController = null;
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 取消单个 Item 后刷新列表。
|
||||
*/
|
||||
async function cancelItem(
|
||||
itemNo: string,
|
||||
payload: { reason: string; expected_lock_version?: number | null },
|
||||
): Promise<ShippingWorkflowItem | null> {
|
||||
const normalized = String(itemNo || '').trim();
|
||||
const reason = String(payload.reason || '').trim();
|
||||
if (!normalized || !reason) return null;
|
||||
const response = await cancelWorkspaceShippingWorkflowItem(normalized, {
|
||||
reason,
|
||||
expected_lock_version: payload.expected_lock_version,
|
||||
});
|
||||
await refresh();
|
||||
return response.item || null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 重试/重新识别单个 Item 后刷新列表。
|
||||
*/
|
||||
async function reparseItem(
|
||||
itemNo: string,
|
||||
payload: { reason: string; comment?: string | null },
|
||||
): Promise<ShippingWorkflowItem | null> {
|
||||
const normalized = String(itemNo || '').trim();
|
||||
const reason = String(payload.reason || '').trim();
|
||||
if (!normalized || !reason) return null;
|
||||
const response = await reparseWorkspaceShippingWorkflowItem(normalized, {
|
||||
reason,
|
||||
comment: payload.comment,
|
||||
});
|
||||
await refresh();
|
||||
return response.item || null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 调度下一次轮询;失败时按退避间隔。
|
||||
*/
|
||||
function schedulePoll(generation: number, delayMs: number) {
|
||||
if (pollTimer) clearTimeout(pollTimer);
|
||||
pollTimer = setTimeout(async () => {
|
||||
if (generation !== pollGeneration || pollingStopped) return;
|
||||
await refresh();
|
||||
if (generation !== pollGeneration || pollingStopped) return;
|
||||
if (!normalizedConversationId.value) return;
|
||||
if (!shouldContinueWorkflowPolling(workflows.value)) {
|
||||
return;
|
||||
}
|
||||
const nextDelay = failureCount > 0
|
||||
? resolveWorkflowPollBackoffMs(failureCount)
|
||||
: resolvePollMs();
|
||||
schedulePoll(generation, nextDelay);
|
||||
}, delayMs);
|
||||
}
|
||||
|
||||
/**
|
||||
* 重启轮询生命周期。
|
||||
*/
|
||||
function restartPolling() {
|
||||
stop();
|
||||
pollingStopped = false;
|
||||
const conversationId = normalizedConversationId.value;
|
||||
if (!conversationId) {
|
||||
workflows.value = [];
|
||||
selectedWorkflowNo.value = null;
|
||||
explicitSelectionNo.value = null;
|
||||
error.value = null;
|
||||
return;
|
||||
}
|
||||
const generation = pollGeneration;
|
||||
void refresh().then(() => {
|
||||
if (generation !== pollGeneration || pollingStopped) return;
|
||||
if (!shouldContinueWorkflowPolling(workflows.value)) return;
|
||||
schedulePoll(generation, resolvePollMs());
|
||||
});
|
||||
}
|
||||
|
||||
function onVisibilityChange() {
|
||||
if (typeof document === 'undefined' || document.visibilityState !== 'visible') return;
|
||||
if (!normalizedConversationId.value || pollingStopped) return;
|
||||
schedulePoll(pollGeneration, 0);
|
||||
}
|
||||
|
||||
watch(normalizedConversationId, () => {
|
||||
explicitSelectionNo.value = null;
|
||||
restartPolling();
|
||||
}, { immediate: true });
|
||||
|
||||
watch(
|
||||
() => readOption(options.refreshTrigger ?? 0),
|
||||
() => {
|
||||
if (!normalizedConversationId.value) return;
|
||||
pollingStopped = false;
|
||||
schedulePoll(pollGeneration, 0);
|
||||
},
|
||||
);
|
||||
|
||||
if (typeof document !== 'undefined') {
|
||||
document.addEventListener('visibilitychange', onVisibilityChange);
|
||||
}
|
||||
if (getCurrentInstance()) {
|
||||
onBeforeUnmount(() => {
|
||||
if (typeof document !== 'undefined') {
|
||||
document.removeEventListener('visibilitychange', onVisibilityChange);
|
||||
}
|
||||
stop();
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
workflows,
|
||||
selectedWorkflowNo,
|
||||
selectWorkflow,
|
||||
workflow,
|
||||
items,
|
||||
loading,
|
||||
error,
|
||||
refresh,
|
||||
cancelItem,
|
||||
reparseItem,
|
||||
stop,
|
||||
};
|
||||
}
|
||||
@@ -73,7 +73,7 @@ const createHarness = () => {
|
||||
loadHistory: vi.fn(async () => undefined),
|
||||
onConversationResolved: vi.fn(async () => undefined),
|
||||
onRetryError: vi.fn(),
|
||||
onSessionWorkItemsRefresh: vi.fn(),
|
||||
onWorkflowRefresh: vi.fn(),
|
||||
t: (key: string) => key,
|
||||
};
|
||||
return { messages, conversationId, options, runs: useShippingOrderExtractionRuns(options) };
|
||||
@@ -177,7 +177,7 @@ describe('useShippingOrderExtractionRuns lifecycle', () => {
|
||||
const harness = createHarness();
|
||||
harness.conversationId.value = 'conv-1';
|
||||
await harness.runs.restoreForConversation('conv-1');
|
||||
expect(harness.options.onSessionWorkItemsRefresh).toHaveBeenCalled();
|
||||
expect(harness.options.onWorkflowRefresh).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('aborts a hanging Run query after ten seconds and keeps polling as a transport failure', async () => {
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
* 用途:把货代订单抽取作为独立 Run 启动、轮询并投影到聊天状态消息。
|
||||
* 依赖:shipping.api Run 接口、chat.types、Vue refs。
|
||||
* 逻辑:发送处理器调用 startRun;本模块持久化本地消息并轮询 Run;终态后仍保留 run_no 供状态卡展示。
|
||||
* 右侧「本次处理」列表由 session-work-items API 驱动,本模块仅在终态/重识别后触发其刷新。
|
||||
* 右侧「本次处理」由 Workflow 投影驱动,本模块仅在终态/重识别后触发其刷新回调。
|
||||
* 轮询前台 2s / 后台 5–10s;取消走请求语义 API,刷新为只读 GET。
|
||||
* 持久化去重签名必须包含 handling_items / primary_notice,避免处理说明变化后历史会话仍读到旧卡。
|
||||
*/
|
||||
@@ -36,8 +36,8 @@ interface UseShippingOrderExtractionRunsOptions {
|
||||
loadHistory: () => Promise<void>;
|
||||
onConversationResolved: (conversationId: string) => Promise<void> | void;
|
||||
onRetryError: (message: string) => void;
|
||||
/** 终态/重识别/恢复后通知右侧面板立即刷新会话工作项。 */
|
||||
onSessionWorkItemsRefresh?: () => void;
|
||||
/** 终态/重识别/恢复后通知右侧 Workflow 面板立即刷新。 */
|
||||
onWorkflowRefresh?: () => void;
|
||||
t: (key: string, params?: Record<string, unknown>) => string;
|
||||
}
|
||||
|
||||
@@ -325,7 +325,7 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
|
||||
// Run 状态卡已持久化;工作台可由页面下一次刷新继续恢复。
|
||||
}
|
||||
await Promise.allSettled([options.loadHistory()]);
|
||||
options.onSessionWorkItemsRefresh?.();
|
||||
options.onWorkflowRefresh?.();
|
||||
return reviewAttachments;
|
||||
};
|
||||
|
||||
@@ -454,7 +454,7 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
|
||||
await upsertRunMessage(response.run);
|
||||
await acknowledgeTerminalRunWhenVisible(response.run);
|
||||
await Promise.allSettled([options.refreshNoticeIntakeStatuses()]);
|
||||
options.onSessionWorkItemsRefresh?.();
|
||||
options.onWorkflowRefresh?.();
|
||||
if (ACTIVE_RUN_STATUSES.has(response.run.status)) {
|
||||
beginPolling(response.run.run_no, 1000);
|
||||
}
|
||||
@@ -569,7 +569,7 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
|
||||
await upsertRunMessage(response.run);
|
||||
await acknowledgeTerminalRunWhenVisible(response.run);
|
||||
await Promise.allSettled([options.refreshNoticeIntakeStatuses(), options.refreshShippingActions()]);
|
||||
options.onSessionWorkItemsRefresh?.();
|
||||
options.onWorkflowRefresh?.();
|
||||
if (ACTIVE_RUN_STATUSES.has(response.run.status)) beginPolling(response.run.run_no, 1000);
|
||||
return true;
|
||||
} catch (error) {
|
||||
@@ -600,7 +600,7 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
|
||||
}));
|
||||
};
|
||||
|
||||
/** 刷新或进入既有会话时恢复最新 Run 状态卡;活动 Run 继续轮询。右侧面板列表由 session-work-items 独立恢复。 */
|
||||
/** 刷新或进入既有会话时恢复最新 Run 状态卡;活动 Run 继续轮询。右侧 Workflow 面板由独立投影恢复。 */
|
||||
const restoreForConversation = async (conversationId: string): Promise<void> => {
|
||||
clearActiveRun();
|
||||
try {
|
||||
@@ -617,7 +617,7 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
|
||||
if (options.conversationId.value !== conversationId) return;
|
||||
await upsertRunMessage(latest, reviewAttachments);
|
||||
await acknowledgeTerminalRunWhenVisible(latest);
|
||||
options.onSessionWorkItemsRefresh?.();
|
||||
options.onWorkflowRefresh?.();
|
||||
if (options.conversationId.value !== conversationId) return;
|
||||
if (ACTIVE_RUN_STATUSES.has(latest.status)) {
|
||||
beginPolling(latest.run_no, 1000);
|
||||
|
||||
@@ -387,6 +387,8 @@ export interface ShippingTaskDetail extends ShippingTaskSummary {
|
||||
export_artifacts?: ShippingExportArtifact[];
|
||||
upload_attempts?: ShippingUploadAttempt[];
|
||||
events: ShippingTaskEvent[];
|
||||
/** 绑定的 WorkflowItem(含可见 Workflow Event);未绑定时为 null。 */
|
||||
workflow_item?: ShippingWorkflowItem | null;
|
||||
ui_state?: ShippingTaskUiState;
|
||||
}
|
||||
|
||||
@@ -411,6 +413,33 @@ export interface ShippingWorkflowStep {
|
||||
status: 'completed' | 'current' | 'pending' | 'blocked' | string;
|
||||
}
|
||||
|
||||
export interface ShippingStpFacts {
|
||||
inventory_source_status?: string | null;
|
||||
inventory_source_code?: string | null;
|
||||
inventory_source_method?: string | null;
|
||||
frozen_candidate_codes?: string[] | null;
|
||||
resolution_counts?: Record<string, number> | null;
|
||||
line_resolutions?: Array<{
|
||||
line_index?: number | null;
|
||||
line_key?: string | null;
|
||||
disposition?: string | null;
|
||||
effective_reservation_id?: string | null;
|
||||
part_number?: string | null;
|
||||
resolved_inventory_source_code?: string | null;
|
||||
inventory_file_no?: string | null;
|
||||
inventory_row_ref?: {
|
||||
reservation_id?: string | null;
|
||||
part_number?: string | null;
|
||||
source_code?: string | null;
|
||||
} | null;
|
||||
}> | null;
|
||||
multi_source_excel_block?: boolean | null;
|
||||
resolved_ok_source_codes?: string[] | null;
|
||||
/** 多源/多文件冲突时可人工指定的恢复候选;与服务端 multi_source_recovery_source_codes 对齐 */
|
||||
recovery_source_codes?: string[] | null;
|
||||
match_status?: string | null;
|
||||
}
|
||||
|
||||
export interface ShippingTaskUiState {
|
||||
task_no: string;
|
||||
batch_no?: string | null;
|
||||
@@ -437,6 +466,8 @@ export interface ShippingTaskUiState {
|
||||
event_at?: string | null;
|
||||
entry_surface?: 'review_workbench' | 'task_workbench' | 'none' | string | null;
|
||||
allowed_actions?: string[] | null;
|
||||
/** STP 履约事实;仅后端投影,前端禁止二次推导 */
|
||||
stp_facts?: ShippingStpFacts | null;
|
||||
};
|
||||
action_buttons: ShippingChatAction[];
|
||||
updated_at?: string | null;
|
||||
@@ -979,6 +1010,34 @@ export interface ShippingOrderReviewSchemaField {
|
||||
options: unknown[];
|
||||
}
|
||||
|
||||
/** 草稿字段值来源元数据;与后端 order_review_projection.field_meta 对齐。 */
|
||||
export type ShippingOrderReviewValueSource =
|
||||
| 'machine'
|
||||
| 'manual'
|
||||
| 'manual_override'
|
||||
| 'derived'
|
||||
| 'skipped';
|
||||
|
||||
export interface ShippingOrderReviewDraftFieldMeta {
|
||||
value_source?: ShippingOrderReviewValueSource;
|
||||
locked?: boolean;
|
||||
override_reason_code?: string;
|
||||
override_reason_text?: string;
|
||||
derivation?: {
|
||||
rule_id?: string | null;
|
||||
skip_reason?: string | null;
|
||||
source_field_code?: string | null;
|
||||
};
|
||||
}
|
||||
|
||||
export interface ShippingOrderReviewDraftLine {
|
||||
line_key?: string;
|
||||
machine_fields?: Array<Record<string, unknown>>;
|
||||
values?: Record<string, { value?: unknown; source?: string; locked?: boolean }>;
|
||||
field_meta?: Record<string, ShippingOrderReviewDraftFieldMeta>;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface ShippingOrderReviewCaseSummary {
|
||||
case_no: string;
|
||||
document_id: number;
|
||||
@@ -996,6 +1055,38 @@ export interface ShippingOrderReviewRun {
|
||||
items: ShippingOrderReviewCaseSummary[];
|
||||
}
|
||||
|
||||
/** 建单前资格行级投影;与后端 validation.line_projections 对齐。 */
|
||||
export interface ShippingOrderReviewBuildEligibilityLineProjection {
|
||||
line_key?: string | null;
|
||||
line_index?: number;
|
||||
effective_reservation_id?: string | null;
|
||||
inventory_source_hint?: string | null;
|
||||
candidate_inventory_source_codes?: string[];
|
||||
routing_status?: string;
|
||||
can_build?: boolean;
|
||||
block_reason?: string | null;
|
||||
selection_mode?: string;
|
||||
manual_reason?: string;
|
||||
}
|
||||
|
||||
/** 建单前整单资格摘要;Draft 校验后由后端投影至 Case DTO。 */
|
||||
export interface ShippingOrderReviewBuildEligibility {
|
||||
can_build: boolean;
|
||||
can_auto_create?: boolean;
|
||||
status: string;
|
||||
gates?: Record<string, boolean>;
|
||||
failed_gates?: string[];
|
||||
line_projections: ShippingOrderReviewBuildEligibilityLineProjection[];
|
||||
/** 已启用库存源编码;零规则候选时供人工选择 */
|
||||
enabled_inventory_source_codes?: string[];
|
||||
}
|
||||
|
||||
export interface ShippingOrderReviewInventoryCandidatesWrite {
|
||||
expected_draft_version: number;
|
||||
source_codes: string[];
|
||||
reason: string;
|
||||
}
|
||||
|
||||
export interface ShippingOrderReviewCase {
|
||||
case_no: string;
|
||||
run_no: string;
|
||||
@@ -1007,10 +1098,13 @@ export interface ShippingOrderReviewCase {
|
||||
schema: { schema_version_id: number; fields: ShippingOrderReviewSchemaField[] };
|
||||
draft?: {
|
||||
draft_version: number;
|
||||
header_values: Record<string, unknown>;
|
||||
lines: Array<Record<string, unknown>>;
|
||||
header_values: Record<string, unknown> & {
|
||||
field_meta?: Record<string, ShippingOrderReviewDraftFieldMeta>;
|
||||
};
|
||||
lines: ShippingOrderReviewDraftLine[];
|
||||
issues: Array<{ code?: string; severity?: string }>;
|
||||
validation: Record<string, unknown>;
|
||||
build_eligibility?: ShippingOrderReviewBuildEligibility;
|
||||
} | null;
|
||||
available_actions: string[];
|
||||
}
|
||||
@@ -1019,6 +1113,10 @@ export interface ShippingOrderReviewConfirmResponse {
|
||||
task_no?: string | null;
|
||||
idempotent_replay: boolean;
|
||||
case: ShippingOrderReviewCase;
|
||||
/** Workflow 业务编号(workflow_no) */
|
||||
workflow_id?: string | null;
|
||||
/** WorkflowItem 业务编号(item_no) */
|
||||
workflow_item_id?: string | null;
|
||||
/** 确认后已触发与 STP 相同的 auto_progress */
|
||||
auto_progress_started?: boolean;
|
||||
auto_progress?: {
|
||||
@@ -1037,6 +1135,10 @@ export interface ShippingOrderReviewDraftWrite {
|
||||
expected_draft_version: number;
|
||||
value?: unknown;
|
||||
restore_machine?: boolean;
|
||||
/** 内部项次 line_no 人工覆盖原因分类(recognition_error / customer_line_exception / business_correction / other)。 */
|
||||
override_reason_code?: string;
|
||||
/** 「其他」时必填的补充说明。 */
|
||||
override_reason_text?: string;
|
||||
}
|
||||
|
||||
export interface ShippingOrderReviewEvidence {
|
||||
@@ -1128,69 +1230,123 @@ export interface ShippingDuplicateResult {
|
||||
|
||||
export interface ShippingCreateBatchFromIntakesResponse extends ShippingNoticeUploadResponse {}
|
||||
|
||||
/** 会话 PDF 工作项生命周期;禁止前端按最新 Run 推断。 */
|
||||
export type ShippingSessionWorkItemLifecycleStatus =
|
||||
| 'pending_review'
|
||||
/** Workflow 批次状态;与后端 ShippingNoticeWorkflow.status 对齐。 */
|
||||
export type ShippingWorkflowStatus =
|
||||
| 'open'
|
||||
| 'completed'
|
||||
| 'cancelled'
|
||||
| 'failed'
|
||||
| string;
|
||||
|
||||
/**
|
||||
* WorkflowItem 生命周期;与 workflow_progress_projection / ledger 对齐。
|
||||
* 含 layout_parsing 等版面阶段(尚无 Review Case)。
|
||||
*/
|
||||
export type ShippingWorkflowItemLifecycleStatus =
|
||||
| 'queued'
|
||||
| 'layout_parsing'
|
||||
| 'extracting'
|
||||
| 'building_order'
|
||||
| 'inventory_matching'
|
||||
| 'generating_excel'
|
||||
| 'pending_review'
|
||||
| 'reparse_failed'
|
||||
| 'closed';
|
||||
| 'failed'
|
||||
| 'closed'
|
||||
| 'cancelled'
|
||||
| 'manual_upload_pending'
|
||||
| string;
|
||||
|
||||
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;
|
||||
/** Workflow 内 Item 用户态计数;与后端 _item_counts 对齐。 */
|
||||
export interface ShippingWorkflowItemCounts {
|
||||
total: number;
|
||||
processing: number;
|
||||
pending_review: number;
|
||||
/** 待人工上传登记;非完成。 */
|
||||
waiting_manual_upload: number;
|
||||
failed: number;
|
||||
completed: number;
|
||||
}
|
||||
|
||||
/** 工作项版本历史行;只读时间线投影。 */
|
||||
export interface ShippingSessionWorkItemVersion {
|
||||
/** 单条用户可见 WorkflowEvent;与 serialize_workflow_event 对齐。 */
|
||||
export interface ShippingWorkflowEvent {
|
||||
seq_no: number;
|
||||
event_code: string;
|
||||
stage_code?: string | null;
|
||||
message_code?: string | null;
|
||||
item_no?: string | null;
|
||||
version_no?: number | null;
|
||||
actor_type: string;
|
||||
/** 操作者标识(用户 ID / system 标识);与 actor_type 一并展示便于审计追溯。 */
|
||||
actor_id?: string | null;
|
||||
reason?: string | null;
|
||||
payload?: Record<string, unknown> | null;
|
||||
occurred_at?: string | null;
|
||||
}
|
||||
|
||||
/** 单条 WorkflowItem 用户态投影;与 serialize_workflow_item 对齐。 */
|
||||
export interface ShippingWorkflowItem {
|
||||
item_no: string;
|
||||
workflow_no: string;
|
||||
conversation_id: string;
|
||||
root_document_id: number;
|
||||
current_document_id: number;
|
||||
/** 当前文档文件名;列表主标题优先展示,缺失时回退展示。 */
|
||||
current_document_filename?: string | null;
|
||||
current_version_no: number;
|
||||
current_run_no?: string | null;
|
||||
current_case_no?: string | null;
|
||||
current_task_no?: string | null;
|
||||
lifecycle_status: ShippingWorkflowItemLifecycleStatus;
|
||||
current_stage: string;
|
||||
closed_reason?: string | null;
|
||||
lock_version: number;
|
||||
last_activity_at?: string | null;
|
||||
closed_at?: string | null;
|
||||
created_at?: string | null;
|
||||
updated_at?: string | null;
|
||||
/** 详情接口 include_events=true 时附带。 */
|
||||
events?: ShippingWorkflowEvent[];
|
||||
}
|
||||
|
||||
/** Workflow 批次投影;与 serialize_workflow 对齐。 */
|
||||
export interface ShippingWorkflow {
|
||||
workflow_no: string;
|
||||
conversation_id: string;
|
||||
status: ShippingWorkflowStatus;
|
||||
current_stage: string;
|
||||
closed_reason?: string | null;
|
||||
lock_version: number;
|
||||
counts: ShippingWorkflowItemCounts;
|
||||
last_activity_at?: string | null;
|
||||
closed_at?: string | null;
|
||||
created_at?: string | null;
|
||||
updated_at?: string | null;
|
||||
items?: ShippingWorkflowItem[];
|
||||
}
|
||||
|
||||
/** 会话开放 Workflow 列表投影;与 project_conversation_workflows 对齐。 */
|
||||
export interface ShippingWorkflowConversationProjection {
|
||||
conversation_id: string;
|
||||
workflows: ShippingWorkflow[];
|
||||
}
|
||||
|
||||
/**
|
||||
* 复核页版本历史行;后端暂无独立 versions 接口时由 WorkflowItem 派生。
|
||||
* 保留 case_no 以便 ReviewVersionHistoryPanel 跳转。
|
||||
*/
|
||||
export interface ShippingWorkflowItemVersion {
|
||||
case_no: string;
|
||||
case_status?: string | null;
|
||||
run_id?: number | null;
|
||||
run_no?: string | null;
|
||||
document_id?: number | null;
|
||||
document_filename?: string | null;
|
||||
is_current?: boolean;
|
||||
is_readonly?: boolean;
|
||||
version_label?: string | null;
|
||||
version_no?: number | 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;
|
||||
/** 说明:完整多版本时间线待后端补齐。 */
|
||||
note?: string | null;
|
||||
}
|
||||
|
||||
export interface ShippingDecisionResponse {
|
||||
|
||||
@@ -1,7 +1,11 @@
|
||||
<!--
|
||||
用途:提供按 PDF 独立处理的建单前订单人工复核工作台(阶段 3:工作项版本中心)。
|
||||
依赖:路由参数、复核 composable、ReviewDocumentPreview、ReviewVersionHistoryPanel、ReviewActionConfirmDialog。
|
||||
逻辑:左侧 PDF 原件预览 + 字段证据定位;中部编辑;右侧版本历史;破坏性操作(含质量异常)二次确认;历史版本强制只读。
|
||||
依赖:路由参数、复核 composable、ReviewDocumentPreview、ReviewVersionHistoryPanel、ReviewActionConfirmDialog、
|
||||
ReviewLineNoOverrideDialog、ReviewBuildEligibilityPanel、ReviewInventoryCandidatesPanel、
|
||||
ReviewWorkflowProgressPanel。
|
||||
逻辑:左 PDF 预览 + 中部订单编辑 + 右侧独立建单资格/库存候选门禁区(sticky);
|
||||
build_eligibility 驱动建单门禁与零候选时已启用库存源选择;破坏性操作二次确认;
|
||||
确认后挂载自动进度面板并轮询 Workflow Item;内部项次 line_no 编辑须经覆盖原因弹窗。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, ref, watch } from 'vue';
|
||||
@@ -15,10 +19,20 @@ import ReviewActionConfirmDialog, {
|
||||
type ReviewConfirmAction,
|
||||
type ReviewConfirmPayload,
|
||||
} from '../components/shipping-review/ReviewActionConfirmDialog.vue';
|
||||
import ReviewBuildEligibilityPanel from '../components/shipping-review/ReviewBuildEligibilityPanel.vue';
|
||||
import ReviewDocumentPreview from '../components/shipping-review/ReviewDocumentPreview.vue';
|
||||
import ReviewInventoryCandidatesPanel from '../components/shipping-review/ReviewInventoryCandidatesPanel.vue';
|
||||
import ReviewLineNoOverrideDialog, {
|
||||
type LineNoOverridePayload,
|
||||
} from '../components/shipping-review/ReviewLineNoOverrideDialog.vue';
|
||||
import ReviewVersionHistoryPanel from '../components/shipping-review/ReviewVersionHistoryPanel.vue';
|
||||
import { useShippingOrderReview } from '../shipping-review/useShippingOrderReview';
|
||||
import type { ShippingOrderReviewEvidence } from '../types/shipping.api.types';
|
||||
import ReviewWorkflowProgressPanel from '../components/shipping-review/ReviewWorkflowProgressPanel.vue';
|
||||
import { REVIEW_BUILD_ELIGIBILITY_BLOCKED, useShippingOrderReview } from '../shipping-review/useShippingOrderReview';
|
||||
import type {
|
||||
ShippingOrderReviewDraftFieldMeta,
|
||||
ShippingOrderReviewEvidence,
|
||||
ShippingOrderReviewValueSource,
|
||||
} from '../types/shipping.api.types';
|
||||
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
@@ -30,7 +44,13 @@ const {
|
||||
workItem,
|
||||
versions,
|
||||
statusMessage,
|
||||
draftConflict,
|
||||
draftConflictDiffLines,
|
||||
buildEligibility,
|
||||
canConfirmBuild,
|
||||
manualInventoryLines,
|
||||
isViewingHistoricalVersion,
|
||||
isReadOnly,
|
||||
loading,
|
||||
loadFailed,
|
||||
saving,
|
||||
@@ -42,12 +62,15 @@ const {
|
||||
selectCase,
|
||||
refreshWorkItemContext,
|
||||
openCurrentVersion,
|
||||
reloadLatestDraft,
|
||||
toggleConflictDiff,
|
||||
patchHeader,
|
||||
patchLine,
|
||||
addLine,
|
||||
copyLine,
|
||||
deleteLine,
|
||||
validate,
|
||||
setLineInventoryCandidates,
|
||||
confirm,
|
||||
createManualDraft,
|
||||
markNonOrder,
|
||||
@@ -55,6 +78,8 @@ const {
|
||||
reparseDocument,
|
||||
uploadReplacement,
|
||||
editable,
|
||||
showWorkflowProgress,
|
||||
workflowProgressPolling,
|
||||
} = useShippingOrderReview();
|
||||
const msg = useMessage();
|
||||
|
||||
@@ -117,6 +142,98 @@ const draftValue = (container: Record<string, unknown>, fieldId: string) => {
|
||||
const machine = Array.isArray(container.machine_fields) ? container.machine_fields as Array<Record<string, unknown>> : [];
|
||||
return machineValueByIdFor(machine, fieldId);
|
||||
};
|
||||
|
||||
/**
|
||||
* 读取投影字段元数据(值来源 / 锁定 / 覆盖原因)。
|
||||
* @param container - 表头或明细草稿容器
|
||||
* @param fieldId - Schema field_id
|
||||
*/
|
||||
const draftFieldMeta = (
|
||||
container: Record<string, unknown> | undefined,
|
||||
fieldId: string,
|
||||
): ShippingOrderReviewDraftFieldMeta => {
|
||||
const metaMap = container?.field_meta as Record<string, ShippingOrderReviewDraftFieldMeta> | undefined;
|
||||
if (metaMap?.[fieldId]) return metaMap[fieldId];
|
||||
const values = container?.values as Record<string, { source?: string; locked?: boolean }> | undefined;
|
||||
const entry = values?.[fieldId];
|
||||
if (entry && typeof entry === 'object') {
|
||||
const source = String(entry.source || 'manual') as ShippingOrderReviewValueSource;
|
||||
return { value_source: source, locked: Boolean(entry.locked) };
|
||||
}
|
||||
return { value_source: 'machine', locked: false };
|
||||
};
|
||||
|
||||
/**
|
||||
* 将 value_source 映射为复核页来源文案。
|
||||
* @param source - 后端投影来源枚举
|
||||
*/
|
||||
const valueSourceLabel = (source?: ShippingOrderReviewValueSource | string) => {
|
||||
const normalized = String(source || 'machine');
|
||||
const key = `chat.shippingOrderReview.valueSources.${normalized}`;
|
||||
return te(key) ? t(key) : t('chat.shippingOrderReview.valueSources.machine');
|
||||
};
|
||||
|
||||
/**
|
||||
* 组装字段血缘/覆盖详情说明,供来源徽章 title 与无障碍文案。
|
||||
* @param meta - 投影字段元数据
|
||||
*/
|
||||
const fieldMetaDetail = (meta: ShippingOrderReviewDraftFieldMeta) => {
|
||||
return fieldMetaLineageRows(meta)
|
||||
.map((row) => `${row.label}: ${row.value}`)
|
||||
.join(' · ');
|
||||
};
|
||||
|
||||
/**
|
||||
* 将 field_meta 拆成结构化血缘行,供 line_no 来源徽章浮层展示。
|
||||
* @param meta - 投影字段元数据
|
||||
*/
|
||||
const fieldMetaLineageRows = (meta: ShippingOrderReviewDraftFieldMeta) => {
|
||||
const rows: Array<{ label: string; value: string }> = [
|
||||
{
|
||||
label: t('chat.shippingOrderReview.lineage.source'),
|
||||
value: valueSourceLabel(meta.value_source),
|
||||
},
|
||||
];
|
||||
if (meta.locked) {
|
||||
rows.push({
|
||||
label: t('chat.shippingOrderReview.lineage.locked'),
|
||||
value: t('chat.shippingOrderReview.lockedHint'),
|
||||
});
|
||||
}
|
||||
if (meta.override_reason_code) {
|
||||
const reasonKey = `chat.shippingOrderReview.lineNoOverrideDialog.reasons.${meta.override_reason_code}`;
|
||||
rows.push({
|
||||
label: t('chat.shippingOrderReview.lineage.overrideReason'),
|
||||
value: te(reasonKey) ? t(reasonKey) : meta.override_reason_code,
|
||||
});
|
||||
}
|
||||
if (meta.override_reason_text) {
|
||||
rows.push({
|
||||
label: t('chat.shippingOrderReview.lineage.overrideNote'),
|
||||
value: meta.override_reason_text,
|
||||
});
|
||||
}
|
||||
if (meta.derivation?.source_field_code) {
|
||||
rows.push({
|
||||
label: t('chat.shippingOrderReview.lineage.derivedFrom'),
|
||||
value: String(meta.derivation.source_field_code),
|
||||
});
|
||||
}
|
||||
if (meta.derivation?.rule_id) {
|
||||
rows.push({
|
||||
label: t('chat.shippingOrderReview.lineage.ruleId'),
|
||||
value: String(meta.derivation.rule_id),
|
||||
});
|
||||
}
|
||||
if (meta.derivation?.skip_reason) {
|
||||
rows.push({
|
||||
label: t('chat.shippingOrderReview.lineage.skipReason'),
|
||||
value: String(meta.derivation.skip_reason),
|
||||
});
|
||||
}
|
||||
return rows;
|
||||
};
|
||||
|
||||
const machineValueByIdFor = (fields: Array<Record<string, unknown>>, fieldId: string) => {
|
||||
const field = fields.find((item) => String(item.field_id || '') === fieldId);
|
||||
return field ? machineValue(field) : '';
|
||||
@@ -146,6 +263,8 @@ const confirmSuccess = ref<{
|
||||
const pendingAction = ref<ReviewConfirmAction | null>(null);
|
||||
const pendingReplaceFile = ref<File | null>(null);
|
||||
const actionDialogOpen = ref(false);
|
||||
const lineNoOverrideOpen = ref(false);
|
||||
const pendingLineNoEdit = ref<{ lineKey: string; fieldId: string; value: string } | null>(null);
|
||||
|
||||
/** 将自动推进结果映射为本地化状态;服务端 message 继续作为具体停留原因。 */
|
||||
const autoProgressStatusLabel = (status: string) => {
|
||||
@@ -164,24 +283,143 @@ const openTaskProgress = (taskNo: string) => {
|
||||
const reportSave = async (action: () => Promise<unknown> | null) => {
|
||||
try { await action(); }
|
||||
catch (error) {
|
||||
const message = error instanceof BusinessError ? error.message : t('errors.generic');
|
||||
const message = resolveReviewErrorMessage(error);
|
||||
msg.error(message);
|
||||
}
|
||||
};
|
||||
const reportDisposition = async (action: () => Promise<unknown> | null) => {
|
||||
try { await action(); }
|
||||
catch (error) {
|
||||
const message = error instanceof BusinessError ? error.message : t('errors.generic');
|
||||
const message = resolveReviewErrorMessage(error);
|
||||
msg.error(message);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 将复核写路径错误映射为用户可见文案;建单资格阻断使用专用 i18n。
|
||||
*/
|
||||
const resolveReviewErrorMessage = (error: unknown) => {
|
||||
if (error instanceof BusinessError && error.code === REVIEW_BUILD_ELIGIBILITY_BLOCKED) {
|
||||
return t('chat.shippingOrderReview.buildEligibility.confirmBlocked');
|
||||
}
|
||||
return error instanceof BusinessError ? error.message : t('errors.generic');
|
||||
};
|
||||
|
||||
/**
|
||||
* 提交行级人工库存源候选并刷新 build_eligibility。
|
||||
*/
|
||||
const submitInventoryCandidates = async (payload: { lineKey: string; sourceCodes: string[]; reason: string }) => {
|
||||
await reportSave(() => setLineInventoryCandidates(payload.lineKey, payload.sourceCodes, payload.reason));
|
||||
};
|
||||
|
||||
/** 打开指定类型的二次确认弹窗。 */
|
||||
const openActionDialog = (action: ReviewConfirmAction) => {
|
||||
pendingAction.value = action;
|
||||
actionDialogOpen.value = true;
|
||||
};
|
||||
|
||||
/**
|
||||
* 明细字段变更:内部项次 line_no 走覆盖原因弹窗,其余字段直接 patch。
|
||||
* @param line - 当前明细行
|
||||
* @param field - Schema 字段
|
||||
* @param value - 输入框新值
|
||||
*/
|
||||
const onLineFieldChange = (
|
||||
line: Record<string, unknown>,
|
||||
field: { field_id: string; field_code: string },
|
||||
value: string,
|
||||
) => {
|
||||
const lineKey = String(line.line_key || '');
|
||||
if (!lineKey) return;
|
||||
if (field.field_code === 'line_no') {
|
||||
pendingLineNoEdit.value = { lineKey, fieldId: field.field_id, value };
|
||||
lineNoOverrideOpen.value = true;
|
||||
return;
|
||||
}
|
||||
void reportSave(() => patchLine(lineKey, field.field_id, value));
|
||||
};
|
||||
|
||||
/**
|
||||
* 内部项次输入中:立即记录待提交值,提示尚未保存,失焦后再弹覆盖原因。
|
||||
* @param line - 当前明细行
|
||||
* @param field - Schema 字段
|
||||
* @param value - 当前输入
|
||||
*/
|
||||
const onLineNoInput = (
|
||||
line: Record<string, unknown>,
|
||||
field: { field_id: string; field_code: string },
|
||||
value: string,
|
||||
) => {
|
||||
const lineKey = String(line.line_key || '');
|
||||
if (!lineKey) return;
|
||||
const committed = draftValue(line, field.field_id);
|
||||
if (value === committed && !lineNoOverrideOpen.value) {
|
||||
if (pendingLineNoEdit.value?.lineKey === lineKey && pendingLineNoEdit.value.fieldId === field.field_id) {
|
||||
pendingLineNoEdit.value = null;
|
||||
}
|
||||
return;
|
||||
}
|
||||
pendingLineNoEdit.value = { lineKey, fieldId: field.field_id, value };
|
||||
};
|
||||
|
||||
/**
|
||||
* 明细输入过程回调;仅内部项次需要即时未保存提示。
|
||||
*/
|
||||
const onLineFieldInput = (
|
||||
line: Record<string, unknown>,
|
||||
field: { field_id: string; field_code: string },
|
||||
value: string,
|
||||
) => {
|
||||
if (field.field_code === 'line_no') {
|
||||
onLineNoInput(line, field, value);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 明细单元格展示值:覆盖弹窗打开或编辑中时优先显示待提交值,避免与草稿真值漂移。
|
||||
*/
|
||||
const lineFieldDisplayValue = (
|
||||
line: Record<string, unknown>,
|
||||
field: { field_id: string; field_code: string },
|
||||
) => {
|
||||
const lineKey = String(line.line_key || '');
|
||||
if (
|
||||
field.field_code === 'line_no'
|
||||
&& pendingLineNoEdit.value
|
||||
&& pendingLineNoEdit.value.lineKey === lineKey
|
||||
&& pendingLineNoEdit.value.fieldId === field.field_id
|
||||
) {
|
||||
return pendingLineNoEdit.value.value;
|
||||
}
|
||||
return draftValue(line, field.field_id);
|
||||
};
|
||||
|
||||
/**
|
||||
* 确认内部项次覆盖:携带原因码写入 manual_override 并锁定。
|
||||
* 核心逻辑:仅成功后关闭弹窗并清空 pending;失败保留原因表单与输入框待提交值。
|
||||
* @param payload - 弹窗确认载荷
|
||||
*/
|
||||
const submitLineNoOverride = async (payload: LineNoOverridePayload) => {
|
||||
const pending = pendingLineNoEdit.value;
|
||||
if (!pending) return;
|
||||
try {
|
||||
await patchLine(pending.lineKey, pending.fieldId, payload.value, false, {
|
||||
override_reason_code: payload.reasonCode,
|
||||
override_reason_text: payload.reasonText,
|
||||
});
|
||||
pendingLineNoEdit.value = null;
|
||||
lineNoOverrideOpen.value = false;
|
||||
} catch (error) {
|
||||
msg.error(resolveReviewErrorMessage(error));
|
||||
}
|
||||
};
|
||||
|
||||
/** 取消项次覆盖时丢弃待提交值,输入框回退为草稿真值。 */
|
||||
const cancelLineNoOverride = () => {
|
||||
pendingLineNoEdit.value = null;
|
||||
lineNoOverrideOpen.value = false;
|
||||
};
|
||||
|
||||
/**
|
||||
* 确认弹窗提交:按 action 分发至对应写操作。
|
||||
* 核心逻辑:质量异常/非订单/重识别携带 reasonCode + comment,供后端统一审计复盘。
|
||||
@@ -192,6 +430,10 @@ const submitPendingAction = async (payload: ReviewConfirmPayload) => {
|
||||
if (!action) return;
|
||||
try {
|
||||
if (action === 'confirm') {
|
||||
if (!canConfirmBuild.value) {
|
||||
msg.error(t('chat.shippingOrderReview.buildEligibility.confirmBlocked'));
|
||||
return;
|
||||
}
|
||||
const response = await confirm();
|
||||
if (response?.task_no) {
|
||||
confirmSuccess.value = {
|
||||
@@ -232,7 +474,7 @@ const submitPendingAction = async (payload: ReviewConfirmPayload) => {
|
||||
pendingReplaceFile.value = null;
|
||||
}
|
||||
} catch (error) {
|
||||
const message = error instanceof BusinessError ? error.message : t('errors.generic');
|
||||
const message = resolveReviewErrorMessage(error);
|
||||
msg.error(message);
|
||||
} finally {
|
||||
pendingAction.value = null;
|
||||
@@ -279,6 +521,19 @@ const jumpToCurrentVersion = async () => {
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* 草稿版本冲突后重新加载服务端最新 Case,丢弃本地过期编辑。
|
||||
*/
|
||||
const onReloadLatestDraft = async () => {
|
||||
try {
|
||||
await reloadLatestDraft();
|
||||
msg.success(t('chat.shippingOrderReview.versionConflict.reloaded'));
|
||||
} catch (error) {
|
||||
const message = error instanceof BusinessError ? error.message : t('errors.generic');
|
||||
msg.error(message);
|
||||
}
|
||||
};
|
||||
|
||||
/** 退出复核模式回到「本次处理」侧栏视图。 */
|
||||
const back = () => router.replace({
|
||||
name: 'Chat',
|
||||
@@ -321,7 +576,7 @@ watch(
|
||||
<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'"
|
||||
:data-readonly="isReadOnly ? '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">
|
||||
@@ -339,8 +594,22 @@ watch(
|
||||
<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
|
||||
class="shrink-0 rounded-full px-2.5 py-1 text-xs"
|
||||
:class="draftConflict
|
||||
? 'bg-amber-100 text-amber-900 dark:bg-amber-950 dark:text-amber-100'
|
||||
: 'bg-sky-100 text-sky-800 dark:bg-sky-950 dark:text-sky-100'"
|
||||
data-testid="review-save-status"
|
||||
>
|
||||
{{
|
||||
saving
|
||||
? t('chat.shippingOrderReview.saving')
|
||||
: draftConflict
|
||||
? t('chat.shippingOrderReview.versionConflict.badge')
|
||||
: saveFailed
|
||||
? t('chat.shippingOrderReview.saveFailed')
|
||||
: t('chat.shippingOrderReview.saved')
|
||||
}}
|
||||
</span>
|
||||
</header>
|
||||
|
||||
@@ -350,17 +619,66 @@ watch(
|
||||
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 class="min-w-0 flex-1 space-y-1">
|
||||
<span>{{ statusBannerText }}</span>
|
||||
<p
|
||||
v-if="draftConflict"
|
||||
class="text-xs text-amber-800 dark:text-amber-200"
|
||||
data-testid="review-version-conflict-hint"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.versionConflict.hint', {
|
||||
local: draftConflict.localVersion,
|
||||
server: draftConflict.serverVersion ?? t('chat.shippingOrderReview.versionConflict.unknownServer'),
|
||||
}) }}
|
||||
</p>
|
||||
</div>
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<button
|
||||
v-if="draftConflict"
|
||||
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="reload-latest-draft"
|
||||
:disabled="saving"
|
||||
@click="onReloadLatestDraft"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.versionConflict.reload') }}
|
||||
</button>
|
||||
<button
|
||||
v-if="draftConflict"
|
||||
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="toggle-draft-conflict-diff"
|
||||
@click="toggleConflictDiff"
|
||||
>
|
||||
{{ draftConflict.showDiff
|
||||
? t('chat.shippingOrderReview.versionConflict.hideDiff')
|
||||
: t('chat.shippingOrderReview.versionConflict.viewDiff') }}
|
||||
</button>
|
||||
<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>
|
||||
<ul
|
||||
v-if="draftConflict?.showDiff && draftConflictDiffLines.length"
|
||||
class="mt-2 list-disc space-y-0.5 pl-5 text-xs"
|
||||
data-testid="review-version-conflict-diff"
|
||||
>
|
||||
<li v-for="line in draftConflictDiffLines" :key="line">{{ line }}</li>
|
||||
</ul>
|
||||
<p
|
||||
v-else-if="draftConflict?.showDiff"
|
||||
class="mt-2 text-xs"
|
||||
data-testid="review-version-conflict-diff-empty"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.versionConflict.diffUnavailable') }}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div
|
||||
@@ -391,13 +709,21 @@ watch(
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="showWorkflowProgress" class="mx-4 mt-3">
|
||||
<ReviewWorkflowProgressPanel
|
||||
:item="workItem"
|
||||
:task-no="confirmSuccess?.taskNo || workItem?.current_task_no"
|
||||
:polling="workflowProgressPolling"
|
||||
/>
|
||||
</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)]">
|
||||
<div class="grid gap-4 xl:grid-cols-[minmax(360px,1fr)_minmax(420px,1.15fr)_minmax(300px,0.9fr)]">
|
||||
<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"
|
||||
@@ -474,7 +800,7 @@ watch(
|
||||
<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">
|
||||
<span v-if="isReadOnly" 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>
|
||||
@@ -499,7 +825,7 @@ watch(
|
||||
@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>
|
||||
<span>{{ valueSourceLabel(draftFieldMeta(activeCase?.draft?.header_values as Record<string, unknown> | undefined, field.field_id).value_source) }}</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>
|
||||
@@ -546,13 +872,59 @@ watch(
|
||||
<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))"
|
||||
<div class="relative min-w-0 flex-1">
|
||||
<input
|
||||
:value="lineFieldDisplayValue(line, field)"
|
||||
:disabled="!editable || saving || (field.field_code === 'line_no' && Boolean(draftFieldMeta(line, field.field_id).locked))"
|
||||
class="w-full rounded border border-slate-300 bg-white px-1.5 py-1 text-xs dark:border-slate-600 dark:bg-slate-950"
|
||||
:class="{
|
||||
'border-amber-400 ring-1 ring-amber-300 dark:border-amber-500': field.field_code === 'line_no'
|
||||
&& pendingLineNoEdit?.lineKey === String(line.line_key || '')
|
||||
&& pendingLineNoEdit.fieldId === field.field_id
|
||||
&& !lineNoOverrideOpen,
|
||||
}"
|
||||
@focus="focusFieldEvidence(field.field_id, index)"
|
||||
@input="onLineFieldInput(line, field, ($event.target as HTMLInputElement).value)"
|
||||
@change="onLineFieldChange(line, field, ($event.target as HTMLInputElement).value)"
|
||||
>
|
||||
<p
|
||||
v-if="field.field_code === 'line_no'
|
||||
&& pendingLineNoEdit?.lineKey === String(line.line_key || '')
|
||||
&& pendingLineNoEdit.fieldId === field.field_id
|
||||
&& !lineNoOverrideOpen"
|
||||
class="mt-0.5 text-[10px] text-amber-600 dark:text-amber-400"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.lineNoUnsavedHint') }}
|
||||
</p>
|
||||
</div>
|
||||
<details
|
||||
v-if="field.field_code === 'line_no' || draftFieldMeta(line, field.field_id).value_source !== 'machine'"
|
||||
class="relative shrink-0"
|
||||
data-testid="review-field-lineage"
|
||||
>
|
||||
<summary
|
||||
class="cursor-pointer list-none whitespace-nowrap rounded bg-slate-100 px-1.5 py-0.5 text-[10px] text-slate-600 marker:content-none dark:bg-slate-800 dark:text-slate-300 [&::-webkit-details-marker]:hidden"
|
||||
:title="fieldMetaDetail(draftFieldMeta(line, field.field_id))"
|
||||
:aria-label="fieldMetaDetail(draftFieldMeta(line, field.field_id))"
|
||||
>
|
||||
{{ valueSourceLabel(draftFieldMeta(line, field.field_id).value_source) }}
|
||||
</summary>
|
||||
<div
|
||||
class="absolute left-0 top-full z-30 mt-1 w-56 rounded-md border border-slate-200 bg-white p-2 shadow-md dark:border-slate-700 dark:bg-slate-900"
|
||||
role="tooltip"
|
||||
>
|
||||
<dl class="grid gap-1.5">
|
||||
<div
|
||||
v-for="row in fieldMetaLineageRows(draftFieldMeta(line, field.field_id))"
|
||||
:key="`${row.label}:${row.value}`"
|
||||
class="min-w-0"
|
||||
>
|
||||
<dt class="text-[10px] font-medium text-slate-500 dark:text-slate-400">{{ row.label }}</dt>
|
||||
<dd class="break-words text-[11px] text-slate-700 dark:text-slate-200">{{ row.value }}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
</div>
|
||||
</details>
|
||||
<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"
|
||||
@@ -562,6 +934,14 @@ watch(
|
||||
@click="focusFieldEvidence(field.field_id, index)"
|
||||
><Crosshair class="h-3 w-3" /></button>
|
||||
</div>
|
||||
<button
|
||||
v-if="editable && field.field_code === 'line_no' && draftFieldMeta(line, field.field_id).locked"
|
||||
type="button"
|
||||
class="mt-0.5 text-[10px] text-sky-600 hover:underline"
|
||||
@click="reportSave(() => patchLine(String(line.line_key), field.field_id, null, true))"
|
||||
>
|
||||
<Undo2 class="mr-0.5 inline h-2.5 w-2.5" />{{ t('chat.shippingOrderReview.restorePriorProjection') }}
|
||||
</button>
|
||||
</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)))">
|
||||
@@ -583,12 +963,26 @@ watch(
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<aside
|
||||
class="order-3 min-w-0 space-y-4 xl:sticky xl:top-4 xl:h-[calc(100vh-11rem)] xl:overflow-y-auto"
|
||||
data-testid="review-build-gate-rail"
|
||||
:aria-label="t('chat.shippingOrderReview.buildGateRail')"
|
||||
>
|
||||
<ReviewBuildEligibilityPanel :eligibility="buildEligibility" />
|
||||
<ReviewInventoryCandidatesPanel
|
||||
:lines="manualInventoryLines"
|
||||
:enabled-source-codes="buildEligibility?.enabled_inventory_source_codes || []"
|
||||
:editable="editable"
|
||||
:saving="saving"
|
||||
@submit="submitInventoryCandidates"
|
||||
/>
|
||||
</aside>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<footer
|
||||
v-if="activeCase?.draft && !isViewingHistoricalVersion"
|
||||
v-if="activeCase?.draft && !isReadOnly"
|
||||
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')">
|
||||
@@ -607,7 +1001,15 @@ watch(
|
||||
<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')">
|
||||
<button
|
||||
v-if="activeCase?.available_actions.includes('confirm')"
|
||||
type="button"
|
||||
:disabled="saving || !canConfirmBuild"
|
||||
class="rounded bg-emerald-600 px-3 py-2 text-sm text-white disabled:opacity-50"
|
||||
data-testid="review-confirm-create"
|
||||
:title="!canConfirmBuild ? t('chat.shippingOrderReview.buildEligibility.confirmBlocked') : undefined"
|
||||
@click="openActionDialog('confirm')"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.confirmCreate') }}
|
||||
</button>
|
||||
</footer>
|
||||
@@ -620,5 +1022,12 @@ watch(
|
||||
@confirm="submitPendingAction"
|
||||
@cancel="pendingReplaceFile = null"
|
||||
/>
|
||||
<ReviewLineNoOverrideDialog
|
||||
v-model="lineNoOverrideOpen"
|
||||
:pending-value="pendingLineNoEdit?.value || ''"
|
||||
:confirm-loading="saving"
|
||||
@confirm="submitLineNoOverride"
|
||||
@cancel="cancelLineNoOverride"
|
||||
/>
|
||||
</main>
|
||||
</template>
|
||||
+117
@@ -0,0 +1,117 @@
|
||||
/**
|
||||
* features/workspace/shipping-task-center/ManualUploadEvidenceDialog.spec.ts
|
||||
* 用途:锁定人工上传登记弹窗无障碍与必填校验契约。
|
||||
* 依赖:vitest、@vue/test-utils、vue-i18n、file-assets / shipping-tasks API mock。
|
||||
* 逻辑:打开时具备 dialog 角色;Escape 关闭;缺少回执号不得提交;关闭后恢复先前焦点。
|
||||
*/
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { mount, flushPromises } from '@vue/test-utils';
|
||||
import { createI18n } from 'vue-i18n';
|
||||
import { nextTick } from 'vue';
|
||||
import ManualUploadEvidenceDialog from './ManualUploadEvidenceDialog.vue';
|
||||
|
||||
vi.mock('@/shared/api/file-assets.api', () => ({
|
||||
uploadFileAsset: vi.fn(async () => ({ asset_no: 'FA-TEST-1' })),
|
||||
}));
|
||||
|
||||
vi.mock('@/features/workspace/api/shipping-tasks.api', () => ({
|
||||
markWorkspaceShippingManualUploaded: vi.fn(async () => ({})),
|
||||
}));
|
||||
|
||||
const messages = {
|
||||
'zh-CN': {
|
||||
workspace: {
|
||||
shippingNotice: {
|
||||
actions: { failed: '失败' },
|
||||
manualUpload: {
|
||||
title: '登记人工上传',
|
||||
hint: '请上传凭据并填写回执号',
|
||||
evidenceLabel: '证据文件',
|
||||
freightRefLabel: '货代回执号',
|
||||
evidenceRequired: '请先选择证据文件',
|
||||
freightRefRequired: '请填写货代回执号',
|
||||
cancel: '取消',
|
||||
submit: '确认已上传',
|
||||
submitting: '提交中…',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* 挂载人工上传登记弹窗。
|
||||
*/
|
||||
function mountDialog(open = true) {
|
||||
const i18n = createI18n({ legacy: false, locale: 'zh-CN', messages });
|
||||
return mount(ManualUploadEvidenceDialog, {
|
||||
props: {
|
||||
open,
|
||||
taskNo: 'SN-DIALOG-1',
|
||||
artifactId: 9,
|
||||
},
|
||||
attachTo: document.body,
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
}
|
||||
|
||||
describe('ManualUploadEvidenceDialog', () => {
|
||||
beforeEach(() => {
|
||||
document.body.innerHTML = '';
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
document.body.innerHTML = '';
|
||||
});
|
||||
|
||||
it('exposes dialog accessibility attributes when open', async () => {
|
||||
const wrapper = mountDialog(true);
|
||||
await nextTick();
|
||||
const dialog = wrapper.get('[data-testid="manual-upload-evidence-dialog"]');
|
||||
expect(dialog.attributes('role')).toBe('dialog');
|
||||
expect(dialog.attributes('aria-modal')).toBe('true');
|
||||
wrapper.unmount();
|
||||
});
|
||||
|
||||
it('closes on Escape and restores prior focus', async () => {
|
||||
const trigger = document.createElement('button');
|
||||
trigger.type = 'button';
|
||||
trigger.textContent = 'open';
|
||||
document.body.appendChild(trigger);
|
||||
trigger.focus();
|
||||
expect(document.activeElement).toBe(trigger);
|
||||
|
||||
const wrapper = mountDialog(true);
|
||||
await nextTick();
|
||||
await flushPromises();
|
||||
|
||||
document.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true }));
|
||||
await nextTick();
|
||||
await flushPromises();
|
||||
|
||||
expect(wrapper.emitted('update:open')?.at(-1)).toEqual([false]);
|
||||
await wrapper.setProps({ open: false });
|
||||
await nextTick();
|
||||
await flushPromises();
|
||||
expect(document.activeElement).toBe(trigger);
|
||||
wrapper.unmount();
|
||||
});
|
||||
|
||||
it('requires freight receipt before submit when evidence is selected', async () => {
|
||||
const wrapper = mountDialog(true);
|
||||
await nextTick();
|
||||
const fileInput = wrapper.get('input[type="file"]');
|
||||
const file = new File(['evidence'], 'shot.png', { type: 'image/png' });
|
||||
Object.defineProperty(fileInput.element, 'files', {
|
||||
value: [file],
|
||||
configurable: true,
|
||||
});
|
||||
await fileInput.trigger('change');
|
||||
await nextTick();
|
||||
|
||||
const submit = wrapper.findAll('button').find((btn) => btn.text().includes('确认已上传'));
|
||||
expect(submit).toBeTruthy();
|
||||
expect(submit!.attributes('disabled')).toBeDefined();
|
||||
wrapper.unmount();
|
||||
});
|
||||
});
|
||||
+113
-10
@@ -1,11 +1,12 @@
|
||||
/**
|
||||
* features/workspace/shipping-task-center/ManualUploadEvidenceDialog.vue
|
||||
* 用途:人工上传凭据对话框;截图/PDF 证据必填,回执号可选。
|
||||
* 依赖:uploadFileAsset、workspace shipping-tasks.api。
|
||||
* 逻辑:由 TaskTodoPanel 在 mark_manual_uploaded 动作时打开;禁止触发 RPA 上传。
|
||||
* 用途:人工上传凭据对话框;截图/PDF 证据与货代回执号均必填。
|
||||
* 依赖:uploadFileAsset、workspace shipping-tasks.api、Vue watch/nextTick。
|
||||
* 逻辑:由 TaskTodoPanel 在 mark_manual_uploaded 动作时打开;禁止触发 RPA 上传;
|
||||
* 对齐复核弹层无障碍:role=dialog、aria-modal、焦点陷阱、Escape、关闭后焦点恢复。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import { ref } from 'vue';
|
||||
import { nextTick, onBeforeUnmount, ref, watch } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { uploadFileAsset } from '@/shared/api/file-assets.api';
|
||||
import { markWorkspaceShippingManualUploaded } from '@/features/workspace/api/shipping-tasks.api';
|
||||
@@ -27,6 +28,26 @@ const busy = ref(false);
|
||||
const error = ref('');
|
||||
const evidenceFile = ref<File | null>(null);
|
||||
const freightRefNo = ref('');
|
||||
const panelRef = ref<HTMLElement | null>(null);
|
||||
let previouslyFocused: HTMLElement | null = null;
|
||||
|
||||
const FOCUSABLE_SELECTOR = [
|
||||
'a[href]',
|
||||
'button:not([disabled])',
|
||||
'textarea:not([disabled])',
|
||||
'input:not([disabled])',
|
||||
'select:not([disabled])',
|
||||
'[tabindex]:not([tabindex="-1"])',
|
||||
].join(',');
|
||||
|
||||
/**
|
||||
* 收集弹窗内可聚焦控件,供 Tab 陷阱使用。
|
||||
*/
|
||||
function focusableNodes(): HTMLElement[] {
|
||||
if (!panelRef.value) return [];
|
||||
return Array.from(panelRef.value.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR))
|
||||
.filter((node) => !node.hasAttribute('disabled') && node.getAttribute('aria-hidden') !== 'true');
|
||||
}
|
||||
|
||||
/**
|
||||
* 关闭对话框并清空本地表单。
|
||||
@@ -39,6 +60,71 @@ function close() {
|
||||
emit('update:open', false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Escape 关闭;Tab / Shift+Tab 在弹窗内循环。
|
||||
*/
|
||||
function onKeydown(event: KeyboardEvent) {
|
||||
if (!props.open) return;
|
||||
if (event.key === 'Escape') {
|
||||
if (busy.value) return;
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
close();
|
||||
return;
|
||||
}
|
||||
if (event.key !== 'Tab') return;
|
||||
const nodes = focusableNodes();
|
||||
const first = nodes[0];
|
||||
const last = nodes[nodes.length - 1];
|
||||
if (!first || !last) {
|
||||
event.preventDefault();
|
||||
return;
|
||||
}
|
||||
const active = document.activeElement as HTMLElement | null;
|
||||
const inside = Boolean(active && panelRef.value?.contains(active));
|
||||
if (event.shiftKey) {
|
||||
if (!inside || active === first) {
|
||||
event.preventDefault();
|
||||
last.focus();
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (!inside || active === last) {
|
||||
event.preventDefault();
|
||||
first.focus();
|
||||
}
|
||||
}
|
||||
|
||||
watch(
|
||||
() => props.open,
|
||||
async (isOpen, wasOpen) => {
|
||||
if (typeof document === 'undefined') return;
|
||||
if (isOpen && !wasOpen) {
|
||||
previouslyFocused = document.activeElement instanceof HTMLElement
|
||||
? document.activeElement
|
||||
: null;
|
||||
document.addEventListener('keydown', onKeydown, true);
|
||||
await nextTick();
|
||||
(focusableNodes()[0] || panelRef.value)?.focus();
|
||||
return;
|
||||
}
|
||||
if (!isOpen && wasOpen) {
|
||||
document.removeEventListener('keydown', onKeydown, true);
|
||||
const restoreTarget = previouslyFocused;
|
||||
previouslyFocused = null;
|
||||
await nextTick();
|
||||
restoreTarget?.focus?.();
|
||||
}
|
||||
},
|
||||
{ immediate: true },
|
||||
);
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
if (typeof document !== 'undefined') {
|
||||
document.removeEventListener('keydown', onKeydown, true);
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* 选择证据文件(截图或 PDF)。
|
||||
*/
|
||||
@@ -50,6 +136,7 @@ function onFileChange(event: Event) {
|
||||
|
||||
/**
|
||||
* 上传证据资产并登记人工上传完成。
|
||||
* 核心逻辑:证据文件与回执号均必填,与后端 record_manual_upload 契约一致。
|
||||
*/
|
||||
async function submit() {
|
||||
if (props.disabled || busy.value) return;
|
||||
@@ -57,14 +144,19 @@ async function submit() {
|
||||
error.value = t('workspace.shippingNotice.manualUpload.evidenceRequired');
|
||||
return;
|
||||
}
|
||||
const receipt = freightRefNo.value.trim();
|
||||
if (!receipt) {
|
||||
error.value = t('workspace.shippingNotice.manualUpload.freightRefRequired');
|
||||
return;
|
||||
}
|
||||
busy.value = true;
|
||||
error.value = '';
|
||||
try {
|
||||
const asset = await uploadFileAsset(evidenceFile.value);
|
||||
await markWorkspaceShippingManualUploaded(props.taskNo, {
|
||||
evidence_asset_no: asset.asset_no,
|
||||
freight_ref_no: receipt,
|
||||
...(props.artifactId ? { artifact_id: props.artifactId } : {}),
|
||||
...(freightRefNo.value.trim() ? { freight_ref_no: freightRefNo.value.trim() } : {}),
|
||||
});
|
||||
emit('success');
|
||||
close();
|
||||
@@ -82,8 +174,19 @@ async function submit() {
|
||||
class="fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-4"
|
||||
@click.self="close"
|
||||
>
|
||||
<div class="w-full max-w-md rounded-2xl border border-default bg-surface p-5 shadow-xl">
|
||||
<h3 class="text-base font-semibold text-primary">
|
||||
<div
|
||||
ref="panelRef"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
:aria-labelledby="'manual-upload-evidence-title'"
|
||||
tabindex="-1"
|
||||
class="w-full max-w-md rounded-2xl border border-default bg-surface p-5 shadow-xl outline-none"
|
||||
data-testid="manual-upload-evidence-dialog"
|
||||
>
|
||||
<h3
|
||||
id="manual-upload-evidence-title"
|
||||
class="text-base font-semibold text-primary"
|
||||
>
|
||||
{{ $t('workspace.shippingNotice.manualUpload.title') }}
|
||||
</h3>
|
||||
<p class="mt-1 text-sm text-muted">
|
||||
@@ -102,7 +205,7 @@ async function submit() {
|
||||
</label>
|
||||
|
||||
<label class="mt-3 block text-xs font-medium text-muted">
|
||||
{{ $t('workspace.shippingNotice.manualUpload.freightRefOptional') }}
|
||||
{{ $t('workspace.shippingNotice.manualUpload.freightRefLabel') }}
|
||||
<input
|
||||
v-model="freightRefNo"
|
||||
type="text"
|
||||
@@ -111,7 +214,7 @@ async function submit() {
|
||||
>
|
||||
</label>
|
||||
|
||||
<p v-if="error" class="mt-3 text-sm text-rose-600">{{ error }}</p>
|
||||
<p v-if="error" class="mt-3 text-sm text-rose-600" role="alert">{{ error }}</p>
|
||||
|
||||
<div class="mt-5 flex justify-end gap-2">
|
||||
<button
|
||||
@@ -125,7 +228,7 @@ async function submit() {
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-xl bg-brand-600 px-3 py-1.5 text-sm font-medium text-white hover:bg-brand-700 disabled:opacity-50"
|
||||
:disabled="busy || disabled || !evidenceFile"
|
||||
:disabled="busy || disabled || !evidenceFile || !freightRefNo.trim()"
|
||||
@click="submit"
|
||||
>
|
||||
{{ busy ? $t('workspace.shippingNotice.manualUpload.submitting') : $t('workspace.shippingNotice.manualUpload.submit') }}
|
||||
|
||||
@@ -2,10 +2,11 @@
|
||||
* features/workspace/shipping-task-center/ShippingTaskCenterPage.vue
|
||||
* 用途:发货「我的待办」壳——Pending|Processing|Done + 识别 Run 续办表 + 右侧任务工作台或复核深链。
|
||||
* 依赖:shipping-tasks.api(my-todos)、shipping.api 详情、ShippingTaskWorkbench、ShippingRunProgressTable、useShippingTodoBadge。
|
||||
* 逻辑:review_case 项用 review_run_no 打开人工复核;task 项打开任务处理工作台;识别页承接取消/重试/回会话。
|
||||
* 逻辑:review_case 项用 review_run_no 打开人工复核;task 项打开任务处理工作台;
|
||||
* 仅对进行中 Workflow/Task 自动刷新(前台 2s / 后台 8s)。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref, watch } from 'vue';
|
||||
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue';
|
||||
import { useRoute, useRouter } from 'vue-router';
|
||||
import { ExternalLink, RefreshCw } from 'lucide-vue-next';
|
||||
import {
|
||||
@@ -24,6 +25,39 @@ import { useShippingTodoBadge } from '../composables/useShippingTodoBadge';
|
||||
import ShippingTaskWorkbench from './ShippingTaskWorkbench.vue';
|
||||
import ShippingRunProgressTable from './ShippingRunProgressTable.vue';
|
||||
|
||||
/** 进行中 Workflow/Task 前台轮询间隔。 */
|
||||
const FOREGROUND_POLL_MS = 2000;
|
||||
/** 页面隐藏时后台轮询间隔。 */
|
||||
const BACKGROUND_POLL_MS = 8000;
|
||||
|
||||
/** 仍视为进行中、需要自动刷新的任务 process_status。 */
|
||||
const IN_PROGRESS_PROCESS = new Set([
|
||||
'parsing',
|
||||
'parsed',
|
||||
'matching',
|
||||
'matched',
|
||||
'waiting_upload',
|
||||
'uploading',
|
||||
'upload_failed',
|
||||
'exporting',
|
||||
'needs_human',
|
||||
'pending_void',
|
||||
]);
|
||||
|
||||
/** WorkflowItem 仍开放处理的生命周期(含待人工上传登记)。 */
|
||||
const IN_PROGRESS_WORKFLOW_ITEM = new Set([
|
||||
'queued',
|
||||
'layout_parsing',
|
||||
'extracting',
|
||||
'building_order',
|
||||
'inventory_matching',
|
||||
'generating_excel',
|
||||
'pending_review',
|
||||
'manual_upload_pending',
|
||||
'reparse_failed',
|
||||
'failed',
|
||||
]);
|
||||
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
const { refreshShippingTodoBadge } = useShippingTodoBadge();
|
||||
@@ -54,6 +88,8 @@ const bucketCounts = ref<ShippingMyTodosCount>({
|
||||
total_pending_badge: 0,
|
||||
});
|
||||
const chatAgentId = ref<number | null>(null);
|
||||
let pollTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
let pollInFlight = false;
|
||||
|
||||
const totalPages = computed(() => Math.max(1, Math.ceil(totalTasks.value / pageSize)));
|
||||
const canHandle = computed(() => detail.value?.can_handle !== false);
|
||||
@@ -89,6 +125,73 @@ function todoDisplayNo(item: ShippingTaskSummary): string {
|
||||
return String(item.task_no || item.todo_ref || '—');
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断详情是否仍处于进行中(含绑定 WorkflowItem)。
|
||||
*/
|
||||
function isDetailInProgress(task: ShippingTaskDetail | null): boolean {
|
||||
if (!task) return false;
|
||||
const process = String(task.process_status || '').trim();
|
||||
if (IN_PROGRESS_PROCESS.has(process)) return true;
|
||||
const itemStatus = String(task.workflow_item?.lifecycle_status || '').trim();
|
||||
return IN_PROGRESS_WORKFLOW_ITEM.has(itemStatus);
|
||||
}
|
||||
|
||||
/**
|
||||
* 是否应继续自动轮询:仅 processing 桶、进行中详情,或 runs 面。
|
||||
*/
|
||||
const shouldAutoRefresh = computed(() => {
|
||||
if (surface.value === 'runs') return true;
|
||||
if (bucket.value === 'processing') return true;
|
||||
if (isDetailInProgress(detail.value)) return true;
|
||||
return tasks.value.some((item) => {
|
||||
const status = String(item.process_status || '').trim();
|
||||
return IN_PROGRESS_PROCESS.has(status) || item.item_kind === 'review_case';
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* 按页面可见性选择轮询间隔。
|
||||
*/
|
||||
function resolvePollMs(): number {
|
||||
if (typeof document !== 'undefined' && document.visibilityState === 'hidden') {
|
||||
return BACKGROUND_POLL_MS;
|
||||
}
|
||||
return FOREGROUND_POLL_MS;
|
||||
}
|
||||
|
||||
/**
|
||||
* 停止自动轮询。
|
||||
*/
|
||||
function stopAutoRefresh() {
|
||||
if (pollTimer != null) {
|
||||
clearTimeout(pollTimer);
|
||||
pollTimer = null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 调度下一次自动刷新(仅进行中 Workflow/Task)。
|
||||
*/
|
||||
function scheduleAutoRefresh() {
|
||||
stopAutoRefresh();
|
||||
if (!shouldAutoRefresh.value) return;
|
||||
pollTimer = setTimeout(() => {
|
||||
void (async () => {
|
||||
if (pollInFlight || !shouldAutoRefresh.value) {
|
||||
scheduleAutoRefresh();
|
||||
return;
|
||||
}
|
||||
pollInFlight = true;
|
||||
try {
|
||||
await refreshAll({ silent: true });
|
||||
} finally {
|
||||
pollInFlight = false;
|
||||
scheduleAutoRefresh();
|
||||
}
|
||||
})();
|
||||
}, resolvePollMs());
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析货代 Chat Agent,供复核/会话深链。
|
||||
*/
|
||||
@@ -194,9 +297,15 @@ async function loadDetail(taskNo: string) {
|
||||
|
||||
/**
|
||||
* 列表与详情联动刷新。
|
||||
* @param options.silent - 轮询时不强制切换 loading 闪烁(详情仍更新)
|
||||
*/
|
||||
async function refreshAll() {
|
||||
await Promise.all([loadTodos(), loadCounts()]);
|
||||
async function refreshAll(options?: { silent?: boolean }) {
|
||||
const silent = Boolean(options?.silent);
|
||||
if (!silent) {
|
||||
await Promise.all([loadTodos(), loadCounts()]);
|
||||
} else {
|
||||
await Promise.all([loadTodos(), loadCounts()]);
|
||||
}
|
||||
if (isDirectTaskRoute.value && preferredTaskNo.value) {
|
||||
await loadDetail(preferredTaskNo.value);
|
||||
return;
|
||||
@@ -286,20 +395,35 @@ watch(selectedItem, (item) => {
|
||||
}
|
||||
});
|
||||
|
||||
watch(shouldAutoRefresh, () => {
|
||||
scheduleAutoRefresh();
|
||||
});
|
||||
|
||||
function onVisibilityChange() {
|
||||
scheduleAutoRefresh();
|
||||
}
|
||||
|
||||
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;
|
||||
await loadDetail(preferredTaskNo.value);
|
||||
} else {
|
||||
const hit = tasks.value.find((item) => String(item.task_no || '').toUpperCase() === preferredTaskNo.value);
|
||||
if (!hit) {
|
||||
selectedRef.value = preferredTaskNo.value;
|
||||
await loadDetail(preferredTaskNo.value);
|
||||
}
|
||||
}
|
||||
}
|
||||
document.addEventListener('visibilitychange', onVisibilityChange);
|
||||
scheduleAutoRefresh();
|
||||
});
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
stopAutoRefresh();
|
||||
document.removeEventListener('visibilitychange', onVisibilityChange);
|
||||
});
|
||||
</script>
|
||||
|
||||
@@ -313,7 +437,7 @@ onMounted(async () => {
|
||||
<button
|
||||
type="button"
|
||||
class="inline-flex items-center gap-1.5 rounded-xl border border-default px-3 py-1.5 text-sm font-medium text-secondary hover:bg-surface-soft"
|
||||
@click="refreshAll"
|
||||
@click="refreshAll()"
|
||||
>
|
||||
<RefreshCw class="h-3.5 w-3.5" />
|
||||
{{ $t('workspace.shippingNotice.refresh') }}
|
||||
@@ -359,7 +483,7 @@ onMounted(async () => {
|
||||
{{ $t('workspace.shippingNotice.openChat') }}
|
||||
</button>
|
||||
</div>
|
||||
<ShippingTaskWorkbench :detail="detail" :can-handle="canHandle" @refreshed="refreshAll" />
|
||||
<ShippingTaskWorkbench :detail="detail" :can-handle="canHandle" @refreshed="() => refreshAll()" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -534,7 +658,7 @@ onMounted(async () => {
|
||||
<ShippingTaskWorkbench
|
||||
:detail="detail"
|
||||
:can-handle="canHandle"
|
||||
@refreshed="refreshAll"
|
||||
@refreshed="() => refreshAll()"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,18 +1,23 @@
|
||||
/**
|
||||
* features/workspace/shipping-task-center/ShippingTaskWorkbench.vue
|
||||
* 用途:发货任务处理主区——当前待办栏、订单概览、时间线;履约写操作入口。
|
||||
* 依赖:TaskTodoPanel、TaskProgressTimeline、ShippingTaskParsedResultCard、ShippingWorkflowStepper。
|
||||
* 逻辑:由 ShippingTaskCenterPage 选中任务后挂载;只消费后端 ui_state,不发明进度百分比。
|
||||
* 用途:发货任务处理主区——当前待办栏、统一节点、最后活动/终止原因、STP 事实、订单概览、时间线。
|
||||
* 依赖:TaskTodoPanel、StpProgressFactsPanel、TaskProgressTimeline、ShippingTaskParsedResultCard、ShippingWorkflowStepper。
|
||||
* 逻辑:由 ShippingTaskCenterPage 选中任务后挂载;只消费后端 ui_state / workflow_item,不发明进度百分比。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import ShippingWorkflowStepper from '@/features/chat/components/ShippingWorkflowStepper.vue';
|
||||
import ShippingMatchResultCard from '@/features/chat/components/messages/ShippingMatchResultCard.vue';
|
||||
import ShippingTaskParsedResultCard from '@/features/chat/components/ShippingTaskParsedResultCard.vue';
|
||||
import { resolveShippingWorkflowSteps } from '@/features/chat/shipping';
|
||||
import type { ShippingTaskDetail } from '@/features/chat/types/shipping.api.types';
|
||||
import { formatLocalDateTime } from '@/shared/utils/dateTime';
|
||||
import TaskTodoPanel from './TaskTodoPanel.vue';
|
||||
import StpProgressFactsPanel from './StpProgressFactsPanel.vue';
|
||||
import TaskProgressTimeline from './TaskProgressTimeline.vue';
|
||||
import { downloadWorkspaceShippingExcelFile } from '@/features/workspace/api/shipping-tasks.api';
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
|
||||
const props = defineProps<{
|
||||
detail: ShippingTaskDetail;
|
||||
@@ -23,6 +28,9 @@ const emit = defineEmits<{
|
||||
refreshed: [];
|
||||
}>();
|
||||
|
||||
const { t } = useI18n();
|
||||
const msg = useMessage();
|
||||
|
||||
const workflowSteps = computed(() => resolveShippingWorkflowSteps(props.detail));
|
||||
const shortageLines = computed(() => props.detail.shortage?.lines || []);
|
||||
const hasMatchCard = computed(() =>
|
||||
@@ -30,6 +38,26 @@ const hasMatchCard = computed(() =>
|
||||
|| shortageLines.value.length > 0,
|
||||
);
|
||||
const events = computed(() => props.detail.events || []);
|
||||
const workflowItem = computed(() => props.detail.workflow_item || null);
|
||||
const workflowEvents = computed(() => workflowItem.value?.events || []);
|
||||
const stpFacts = computed(() => props.detail.ui_state?.summary?.stp_facts || null);
|
||||
const lastActivityAt = computed(() => workflowItem.value?.last_activity_at || props.detail.updated_at || null);
|
||||
const terminateReason = computed(() => workflowItem.value?.closed_reason || null);
|
||||
const hasExcelArtifact = computed(() =>
|
||||
Array.isArray(props.detail.export_artifacts) && props.detail.export_artifacts.length > 0,
|
||||
);
|
||||
|
||||
/**
|
||||
* 下载已生成的发货 Excel。
|
||||
*/
|
||||
async function downloadExcel() {
|
||||
try {
|
||||
await downloadWorkspaceShippingExcelFile(props.detail.task_no);
|
||||
emit('refreshed');
|
||||
} catch (e: unknown) {
|
||||
msg.warning(e instanceof Error ? e.message : t('workspace.shippingNotice.actions.failed'));
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -45,8 +73,35 @@ const events = computed(() => props.detail.events || []);
|
||||
{{ $t('workspace.shippingNotice.todo.workflow') }}
|
||||
</div>
|
||||
<ShippingWorkflowStepper :steps="workflowSteps" />
|
||||
<dl class="mt-3 grid gap-2 text-xs sm:grid-cols-2">
|
||||
<div>
|
||||
<dt class="text-muted">{{ $t('workspace.shippingNotice.todo.lastActivity') }}</dt>
|
||||
<dd class="text-secondary">{{ lastActivityAt ? formatLocalDateTime(lastActivityAt) : '—' }}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt class="text-muted">{{ $t('workspace.shippingNotice.todo.terminateReason') }}</dt>
|
||||
<dd class="text-secondary">{{ terminateReason || '—' }}</dd>
|
||||
</div>
|
||||
<div v-if="workflowItem" class="sm:col-span-2">
|
||||
<dt class="text-muted">{{ $t('workspace.shippingNotice.todo.workflowItem') }}</dt>
|
||||
<dd class="font-mono text-secondary">
|
||||
{{ workflowItem.item_no }} · {{ workflowItem.lifecycle_status }} · {{ workflowItem.current_stage }}
|
||||
</dd>
|
||||
</div>
|
||||
</dl>
|
||||
<div v-if="hasExcelArtifact" class="mt-3">
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-xl border border-default px-3 py-1.5 text-sm font-medium text-secondary hover:bg-surface-soft"
|
||||
@click="downloadExcel"
|
||||
>
|
||||
{{ $t('workspace.shippingNotice.todo.downloadExcel') }}
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<StpProgressFactsPanel :facts="stpFacts" />
|
||||
|
||||
<section class="rounded-2xl border border-default/80 bg-surface px-4 py-3">
|
||||
<h3 class="mb-3 text-sm font-semibold text-secondary">
|
||||
{{ $t('workspace.shippingNotice.todo.orderOverview') }}
|
||||
@@ -97,6 +152,6 @@ const events = computed(() => props.detail.events || []);
|
||||
:action-busy="false"
|
||||
/>
|
||||
|
||||
<TaskProgressTimeline :events="events" />
|
||||
<TaskProgressTimeline :events="events" :workflow-events="workflowEvents" />
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,126 @@
|
||||
/**
|
||||
* features/workspace/shipping-task-center/StpProgressFactsPanel.vue
|
||||
* 用途:展示后端 ui_state.summary.stp_facts,含逐行 Reservation/料号/实际库存源/文件证据。
|
||||
* 依赖:ShippingTaskUiState.summary.stp_facts、vue-i18n。
|
||||
* 逻辑:由 ShippingTaskWorkbench 在待办栏下方挂载;无 stp_facts 时不渲染;不发明进度。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import type { ShippingStpFacts } from '@/features/chat/types/shipping.api.types';
|
||||
|
||||
const props = defineProps<{
|
||||
facts: ShippingStpFacts | null | undefined;
|
||||
}>();
|
||||
|
||||
const { t, te } = useI18n();
|
||||
|
||||
const visible = computed(() => Boolean(props.facts));
|
||||
const resolutionEntries = computed(() => {
|
||||
const counts = props.facts?.resolution_counts || {};
|
||||
return Object.entries(counts).map(([disposition, count]) => ({ disposition, count }));
|
||||
});
|
||||
const lineRows = computed(() => props.facts?.line_resolutions || []);
|
||||
|
||||
/**
|
||||
* 行级 disposition 文案;未知码回退原文。
|
||||
*/
|
||||
function dispositionLabel(disposition: string): string {
|
||||
const key = `workspace.shippingNotice.stpFacts.disposition.${disposition}`;
|
||||
return te(key) ? t(key) : disposition;
|
||||
}
|
||||
|
||||
/**
|
||||
* 行证据摘要:文件号 + 行引用键。
|
||||
*/
|
||||
function evidenceText(row: NonNullable<ShippingStpFacts['line_resolutions']>[number]): string {
|
||||
const fileNo = String(row?.inventory_file_no || '').trim();
|
||||
const ref = row?.inventory_row_ref;
|
||||
const refParts = [
|
||||
ref?.reservation_id,
|
||||
ref?.part_number,
|
||||
ref?.source_code,
|
||||
].filter(Boolean).map(String);
|
||||
if (fileNo && refParts.length) return `${fileNo} · ${refParts.join('/')}`;
|
||||
if (fileNo) return fileNo;
|
||||
if (refParts.length) return refParts.join('/');
|
||||
return '—';
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section
|
||||
v-if="visible && facts"
|
||||
class="rounded-2xl border border-default/80 bg-surface px-4 py-3 text-sm"
|
||||
data-testid="stp-progress-facts-panel"
|
||||
>
|
||||
<h3 class="mb-2 text-sm font-semibold text-secondary">
|
||||
{{ $t('workspace.shippingNotice.stpFacts.title') }}
|
||||
</h3>
|
||||
<dl class="grid gap-2 text-xs sm:grid-cols-2">
|
||||
<div>
|
||||
<dt class="text-muted">{{ $t('workspace.shippingNotice.stpFacts.inventorySourceStatus') }}</dt>
|
||||
<dd class="font-medium text-secondary">{{ facts.inventory_source_status || '—' }}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt class="text-muted">{{ $t('workspace.shippingNotice.stpFacts.inventorySourceCode') }}</dt>
|
||||
<dd class="font-medium text-secondary">{{ facts.inventory_source_code || '—' }}</dd>
|
||||
</div>
|
||||
<div class="sm:col-span-2">
|
||||
<dt class="text-muted">{{ $t('workspace.shippingNotice.stpFacts.frozenCandidates') }}</dt>
|
||||
<dd class="font-medium text-secondary">
|
||||
{{ (facts.frozen_candidate_codes || []).join(', ') || '—' }}
|
||||
</dd>
|
||||
</div>
|
||||
<div v-if="facts.multi_source_excel_block" class="sm:col-span-2 rounded-lg bg-amber-50 px-3 py-2 text-amber-900">
|
||||
{{ $t('workspace.shippingNotice.stpFacts.multiSourceBlock') }}
|
||||
<span v-if="(facts.resolved_ok_source_codes || []).length">
|
||||
({{ (facts.resolved_ok_source_codes || []).join(', ') }})
|
||||
</span>
|
||||
</div>
|
||||
<div v-if="resolutionEntries.length" class="sm:col-span-2">
|
||||
<dt class="mb-1 text-muted">{{ $t('workspace.shippingNotice.stpFacts.resolutionCounts') }}</dt>
|
||||
<dd class="flex flex-wrap gap-2">
|
||||
<span
|
||||
v-for="item in resolutionEntries"
|
||||
:key="item.disposition"
|
||||
class="rounded-full border border-default/70 px-2 py-0.5 text-secondary"
|
||||
>
|
||||
{{ dispositionLabel(item.disposition) }}
|
||||
× {{ item.count }}
|
||||
</span>
|
||||
</dd>
|
||||
</div>
|
||||
</dl>
|
||||
|
||||
<div v-if="lineRows.length" class="mt-3 overflow-x-auto">
|
||||
<div class="mb-1 text-xs text-muted">{{ $t('workspace.shippingNotice.stpFacts.lineTableTitle') }}</div>
|
||||
<table class="min-w-full border-collapse text-xs">
|
||||
<thead>
|
||||
<tr class="border-b border-default/70 text-left text-muted">
|
||||
<th class="py-1 pr-2 font-medium">{{ $t('workspace.shippingNotice.stpFacts.colLine') }}</th>
|
||||
<th class="py-1 pr-2 font-medium">{{ $t('workspace.shippingNotice.stpFacts.colReservation') }}</th>
|
||||
<th class="py-1 pr-2 font-medium">{{ $t('workspace.shippingNotice.stpFacts.colPart') }}</th>
|
||||
<th class="py-1 pr-2 font-medium">{{ $t('workspace.shippingNotice.stpFacts.colDisposition') }}</th>
|
||||
<th class="py-1 pr-2 font-medium">{{ $t('workspace.shippingNotice.stpFacts.colSource') }}</th>
|
||||
<th class="py-1 font-medium">{{ $t('workspace.shippingNotice.stpFacts.colEvidence') }}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr
|
||||
v-for="(row, index) in lineRows"
|
||||
:key="`${row.line_key || row.line_index}-${index}`"
|
||||
class="border-b border-default/50 align-top"
|
||||
>
|
||||
<td class="py-1.5 pr-2 font-mono">{{ (row.line_index ?? index) + 1 }}</td>
|
||||
<td class="py-1.5 pr-2 font-mono">{{ row.effective_reservation_id || '—' }}</td>
|
||||
<td class="py-1.5 pr-2 font-mono">{{ row.part_number || '—' }}</td>
|
||||
<td class="py-1.5 pr-2">{{ dispositionLabel(String(row.disposition || 'unknown')) }}</td>
|
||||
<td class="py-1.5 pr-2 font-mono">{{ row.resolved_inventory_source_code || '—' }}</td>
|
||||
<td class="py-1.5 font-mono text-muted">{{ evidenceText(row) }}</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
@@ -0,0 +1,60 @@
|
||||
/**
|
||||
* features/workspace/shipping-task-center/TaskProgressTimeline.spec.ts
|
||||
* 用途:锁定任务中心时间线同时消费 Task Event 与 Workflow Event。
|
||||
* 依赖:Vitest、@vue/test-utils、TaskProgressTimeline。
|
||||
* 逻辑:合并排序后两类事件均可见;Workflow 操作人展示 type/id。
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { mount } from '@vue/test-utils';
|
||||
import { createI18n } from 'vue-i18n';
|
||||
import TaskProgressTimeline from './TaskProgressTimeline.vue';
|
||||
|
||||
const messages = {
|
||||
'zh-CN': {
|
||||
workspace: {
|
||||
shippingNotice: {
|
||||
events: '事件时间线',
|
||||
operator: '操作者 {id}',
|
||||
eventTypes: { system: '系统', task_created: '任务已创建' },
|
||||
workflowEvents: { stage_changed: '阶段变更', upload_manual_confirmed: '人工上传已登记' },
|
||||
timeline: {
|
||||
empty: '暂无事件记录',
|
||||
detail: '查看详情',
|
||||
sourceTask: '任务事件',
|
||||
sourceWorkflow: 'Workflow 事件',
|
||||
workflowEvent: 'Workflow 事件',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
describe('TaskProgressTimeline', () => {
|
||||
it('merges task and workflow events and shows workflow actor type/id', () => {
|
||||
const i18n = createI18n({ legacy: false, locale: 'zh-CN', messages });
|
||||
const wrapper = mount(TaskProgressTimeline, {
|
||||
props: {
|
||||
events: [
|
||||
{ event_type: 'task_created', created_at: '2026-07-31T01:00:00Z', actor_id: 1 },
|
||||
],
|
||||
workflowEvents: [
|
||||
{
|
||||
seq_no: 1,
|
||||
event_code: 'upload_manual_confirmed',
|
||||
actor_type: 'user',
|
||||
actor_id: '42',
|
||||
occurred_at: '2026-07-31T01:01:00Z',
|
||||
},
|
||||
],
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
// 关键断言:时间线同时展示 Task 与 Workflow 事件来源标签,且 Workflow 显示操作人。
|
||||
expect(wrapper.text()).toContain('任务事件');
|
||||
expect(wrapper.text()).toContain('Workflow 事件');
|
||||
expect(wrapper.text()).toContain('任务已创建');
|
||||
expect(wrapper.text()).toContain('人工上传已登记');
|
||||
expect(wrapper.text()).toContain('操作者 1');
|
||||
expect(wrapper.text()).toContain('操作者 user/42');
|
||||
});
|
||||
});
|
||||
@@ -1,16 +1,93 @@
|
||||
/**
|
||||
* features/workspace/shipping-task-center/TaskProgressTimeline.vue
|
||||
* 用途:展示任务事件时间线(只读),不发明进度百分比。
|
||||
* 依赖:ShippingTaskEvent、dateTime 工具。
|
||||
* 逻辑:由 ShippingTaskWorkbench 传入 detail.events。
|
||||
* 用途:展示任务事件 + Workflow Event 统一时间线(只读),不发明进度百分比。
|
||||
* 依赖:ShippingTaskEvent、ShippingWorkflowEvent、dateTime、vue-i18n。
|
||||
* 逻辑:由 ShippingTaskWorkbench 传入 task events 与 workflow events;按时间合并排序;
|
||||
* Workflow 事件操作人展示为 actor_type/actor_id。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { formatLocalDateTime } from '@/shared/utils/dateTime';
|
||||
import type { ShippingTaskEvent } from '@/features/chat/types/shipping.api.types';
|
||||
import type { ShippingTaskEvent, ShippingWorkflowEvent } from '@/features/chat/types/shipping.api.types';
|
||||
|
||||
defineProps<{
|
||||
const props = defineProps<{
|
||||
events: ShippingTaskEvent[];
|
||||
workflowEvents?: ShippingWorkflowEvent[];
|
||||
}>();
|
||||
|
||||
const { t, te } = useI18n();
|
||||
|
||||
type TimelineRow = {
|
||||
key: string;
|
||||
label: string;
|
||||
createdAt?: string | null;
|
||||
actor?: string | null;
|
||||
detail?: Record<string, unknown> | null;
|
||||
source: 'task' | 'workflow';
|
||||
};
|
||||
|
||||
/**
|
||||
* 将任务事件类型映射为可读文案;契约外码原样展示。
|
||||
*/
|
||||
function taskEventLabel(eventType: string | null | undefined): string {
|
||||
const code = String(eventType || '').trim();
|
||||
if (!code) return t('workspace.shippingNotice.eventTypes.system');
|
||||
const key = `workspace.shippingNotice.eventTypes.${code}`;
|
||||
return te(key) ? t(key) : code;
|
||||
}
|
||||
|
||||
/**
|
||||
* 将 Workflow Event 码映射为可读文案。
|
||||
*/
|
||||
function workflowEventLabel(event: ShippingWorkflowEvent): string {
|
||||
const code = String(event.event_code || event.message_code || event.stage_code || '').trim();
|
||||
if (!code) return t('workspace.shippingNotice.timeline.workflowEvent');
|
||||
const key = `workspace.shippingNotice.workflowEvents.${code}`;
|
||||
return te(key) ? t(key) : code;
|
||||
}
|
||||
|
||||
/**
|
||||
* 格式化操作人展示:优先 type/id,便于审计追溯。
|
||||
* @param actorType - 角色(user/system/admin…)
|
||||
* @param actorId - 操作者 ID 或系统标识
|
||||
*/
|
||||
function formatActorLabel(actorType?: string | null, actorId?: string | number | null): string | null {
|
||||
const type = String(actorType || '').trim();
|
||||
const id = actorId == null ? '' : String(actorId).trim();
|
||||
if (type && id) return `${type}/${id}`;
|
||||
if (id) return id;
|
||||
if (type) return type;
|
||||
return null;
|
||||
}
|
||||
|
||||
const rows = computed<TimelineRow[]>(() => {
|
||||
const taskRows: TimelineRow[] = (props.events || []).map((event, index) => ({
|
||||
key: `task-${event.event_type}-${index}`,
|
||||
label: taskEventLabel(event.event_type),
|
||||
createdAt: event.created_at,
|
||||
actor: formatActorLabel(null, event.actor_id),
|
||||
detail: event.detail_json || null,
|
||||
source: 'task',
|
||||
}));
|
||||
const workflowRows: TimelineRow[] = (props.workflowEvents || []).map((event, index) => ({
|
||||
key: `wf-${event.seq_no}-${index}`,
|
||||
label: workflowEventLabel(event),
|
||||
createdAt: event.occurred_at,
|
||||
actor: formatActorLabel(event.actor_type, event.actor_id),
|
||||
detail: {
|
||||
...(event.payload || {}),
|
||||
...(event.reason ? { reason: event.reason } : {}),
|
||||
...(event.stage_code ? { stage_code: event.stage_code } : {}),
|
||||
},
|
||||
source: 'workflow',
|
||||
}));
|
||||
return [...taskRows, ...workflowRows].sort((a, b) => {
|
||||
const ta = a.createdAt ? new Date(a.createdAt).getTime() : 0;
|
||||
const tb = b.createdAt ? new Date(b.createdAt).getTime() : 0;
|
||||
return ta - tb;
|
||||
});
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -18,21 +95,34 @@ defineProps<{
|
||||
<h3 class="mb-2 text-sm font-semibold text-secondary">
|
||||
{{ $t('workspace.shippingNotice.events') }}
|
||||
</h3>
|
||||
<div v-if="!events.length" class="py-4 text-center text-xs text-muted">
|
||||
<div v-if="!rows.length" class="py-4 text-center text-xs text-muted">
|
||||
{{ $t('workspace.shippingNotice.timeline.empty') }}
|
||||
</div>
|
||||
<div
|
||||
v-for="(event, index) in events"
|
||||
:key="`${event.event_type}-${index}`"
|
||||
v-for="row in rows"
|
||||
:key="row.key"
|
||||
class="border-t border-default/70 py-2 first:border-t-0 first:pt-0"
|
||||
>
|
||||
<div class="flex flex-wrap gap-x-3 gap-y-1 text-xs">
|
||||
<span class="font-medium text-secondary">{{ event.event_type }}</span>
|
||||
<span class="text-muted">{{ formatLocalDateTime(event.created_at) }}</span>
|
||||
<span v-if="event.actor_id" class="text-muted">{{ $t('workspace.shippingNotice.operator', { id: event.actor_id }) }}</span>
|
||||
<span class="font-medium text-secondary">{{ row.label }}</span>
|
||||
<span
|
||||
class="rounded px-1.5 py-0.5 text-[10px]"
|
||||
:class="row.source === 'workflow' ? 'bg-indigo-50 text-indigo-700' : 'bg-slate-100 text-slate-600'"
|
||||
>
|
||||
{{ row.source === 'workflow'
|
||||
? $t('workspace.shippingNotice.timeline.sourceWorkflow')
|
||||
: $t('workspace.shippingNotice.timeline.sourceTask') }}
|
||||
</span>
|
||||
<span class="text-muted">{{ formatLocalDateTime(row.createdAt) }}</span>
|
||||
<span v-if="row.actor" class="text-muted">{{ $t('workspace.shippingNotice.operator', { id: row.actor }) }}</span>
|
||||
</div>
|
||||
<pre v-if="event.detail_json && Object.keys(event.detail_json).length" class="mt-1 whitespace-pre-wrap break-words text-xs text-muted">{{ JSON.stringify(event.detail_json, null, 2) }}</pre>
|
||||
<pre v-if="event.before_json || event.after_json" class="mt-1 whitespace-pre-wrap break-words text-xs text-muted">{{ JSON.stringify({ before: event.before_json, after: event.after_json }, null, 2) }}</pre>
|
||||
<details
|
||||
v-if="row.detail && Object.keys(row.detail).length"
|
||||
class="mt-1 text-xs text-muted"
|
||||
>
|
||||
<summary class="cursor-pointer select-none">{{ $t('workspace.shippingNotice.timeline.detail') }}</summary>
|
||||
<pre class="mt-1 whitespace-pre-wrap break-words">{{ JSON.stringify(row.detail, null, 2) }}</pre>
|
||||
</details>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
@@ -1,131 +1,91 @@
|
||||
/**
|
||||
|
||||
* features/workspace/shipping-task-center/TaskTodoPanel.vue
|
||||
|
||||
* 用途:仅渲染后端 ui_state.action_buttons / summary.allowed_actions 对应的当前待办动作。
|
||||
|
||||
* 依赖:shipping.api 履约写接口、shipping-tasks.api 下载/人工上传、各确认对话框。
|
||||
|
||||
* 逻辑:禁止按 process_status 二次推导按钮;管理员 can_handle=false 时只读。
|
||||
|
||||
* 依赖:shipping.api 履约写接口、shipping-tasks.api 下载/人工上传、ManualUploadEvidenceDialog、各确认对话框。
|
||||
* 逻辑:禁止按 process_status 二次推导按钮;管理员 can_handle=false 时只读;
|
||||
* wait_manual_upload 允许下载 Excel + 登记人工上传凭据(禁 RPA);
|
||||
* 多源阻断时对话框候选强制取 stp_facts.recovery_source_codes,禁止展示冻结全集。
|
||||
*/
|
||||
|
||||
<script setup lang="ts">
|
||||
|
||||
import { computed, ref } from 'vue';
|
||||
|
||||
import { useI18n } from 'vue-i18n';
|
||||
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
|
||||
import DeleteConfirmDialog from '@/shared/components/DeleteConfirmDialog.vue';
|
||||
|
||||
import ShippingCustomerConfirmDialog from '@/features/chat/components/ShippingCustomerConfirmDialog.vue';
|
||||
|
||||
import type {
|
||||
|
||||
ShippingChatAction,
|
||||
|
||||
ShippingCustomerOption,
|
||||
|
||||
ShippingInventorySourceCandidate,
|
||||
|
||||
ShippingTaskDetail,
|
||||
|
||||
} from '@/features/chat/types/shipping.api.types';
|
||||
|
||||
import {
|
||||
|
||||
confirmWorkspaceShippingCustomer,
|
||||
|
||||
confirmWorkspaceShippingInventorySource,
|
||||
|
||||
freezeWorkspaceShippingOrder,
|
||||
|
||||
generateWorkspaceShippingExcel,
|
||||
|
||||
listWorkspaceShippingCustomerOptions,
|
||||
|
||||
matchWorkspaceShippingInventory,
|
||||
|
||||
retryWorkspaceShippingUpload,
|
||||
|
||||
submitWorkspaceShippingDecision,
|
||||
|
||||
} from '@/features/chat/api/shipping.api';
|
||||
|
||||
import { downloadWorkspaceShippingExcelFile } from '@/features/workspace/api/shipping-tasks.api';
|
||||
|
||||
import { refreshShippingTodoBadge } from '@/features/workspace/composables/useShippingTodoBadge';
|
||||
|
||||
import InventorySourceSelectDialog from './InventorySourceSelectDialog.vue';
|
||||
|
||||
import ManualUploadEvidenceDialog from './ManualUploadEvidenceDialog.vue';
|
||||
|
||||
|
||||
|
||||
const props = defineProps<{
|
||||
|
||||
detail: ShippingTaskDetail;
|
||||
|
||||
canHandle: boolean;
|
||||
|
||||
}>();
|
||||
|
||||
|
||||
|
||||
const emit = defineEmits<{
|
||||
|
||||
refreshed: [];
|
||||
|
||||
}>();
|
||||
|
||||
|
||||
|
||||
const { t } = useI18n();
|
||||
|
||||
const msg = useMessage();
|
||||
|
||||
const busyId = ref<string | null>(null);
|
||||
|
||||
const manualUploadOpen = ref(false);
|
||||
|
||||
|
||||
|
||||
const customerDialogOpen = ref(false);
|
||||
|
||||
const customerOptions = ref<ShippingCustomerOption[]>([]);
|
||||
|
||||
const customerLoading = ref(false);
|
||||
|
||||
|
||||
|
||||
const freezeDialogOpen = ref(false);
|
||||
|
||||
const pendingFreezeVersion = ref<number | null>(null);
|
||||
|
||||
|
||||
|
||||
const inventorySourceDialogOpen = ref(false);
|
||||
|
||||
const inventorySourceCandidates = ref<ShippingInventorySourceCandidate[]>([]);
|
||||
|
||||
const inventorySourceInitialCode = ref('');
|
||||
|
||||
|
||||
|
||||
const summary = computed(() => props.detail.ui_state?.summary || {});
|
||||
|
||||
const actionButtons = computed(() => props.detail.ui_state?.action_buttons || []);
|
||||
|
||||
const checkpointKind = computed(() => String(props.detail.ui_state?.checkpoint_kind || ''));
|
||||
const checkpoint = computed(() => String(props.detail.ui_state?.checkpoint || ''));
|
||||
|
||||
/**
|
||||
* 是否展示「待人工上传登记」提示。
|
||||
* 核心逻辑:wait_manual_upload,或 export_ready/export_generated 且已有导出文件名/工件。
|
||||
*/
|
||||
const showWaitingManualUploadNote = computed(() => {
|
||||
if (checkpointKind.value === 'wait_manual_upload') return true;
|
||||
if (checkpoint.value === 'export_ready' || checkpoint.value === 'export_generated') {
|
||||
return Boolean(
|
||||
props.detail.export_file_name
|
||||
|| (Array.isArray(props.detail.export_artifacts) && props.detail.export_artifacts.length > 0),
|
||||
);
|
||||
}
|
||||
return false;
|
||||
});
|
||||
|
||||
/** 当前导出工件 id,供人工上传登记对话框绑定。 */
|
||||
const currentExportArtifactId = computed(() => {
|
||||
const artifacts = props.detail.export_artifacts;
|
||||
if (!Array.isArray(artifacts) || !artifacts.length) return null;
|
||||
const id = Number(artifacts[0]?.id);
|
||||
return Number.isFinite(id) ? id : null;
|
||||
});
|
||||
/** auto_continue 仅保留刷新;正常 STP 由后台自动推进。 */
|
||||
const AUTO_CONTINUE_ACTIONS = new Set(['refresh']);
|
||||
|
||||
/** wait_manual_upload 仅允许下载/导出/人工上传确认。 */
|
||||
const WAIT_MANUAL_UPLOAD_ACTIONS = new Set(['download_excel', 'export', 'mark_manual_uploaded', 'refresh']);
|
||||
|
||||
/** must_human 保留例外处理动作,禁止 Chat 侧履约写路径。 */
|
||||
const MUST_HUMAN_ACTIONS = new Set([
|
||||
'confirm',
|
||||
@@ -142,7 +102,6 @@ const MUST_HUMAN_ACTIONS = new Set([
|
||||
'match_inventory',
|
||||
'refresh',
|
||||
]);
|
||||
|
||||
/**
|
||||
* 按 STP checkpoint_kind 过滤工作台动作,避免 auto_continue 误点写操作。
|
||||
*/
|
||||
@@ -153,601 +112,291 @@ function isActionAllowedForCheckpoint(actionId: string, kind: string): boolean {
|
||||
if (kind === 'must_human') return MUST_HUMAN_ACTIONS.has(actionId);
|
||||
return true;
|
||||
}
|
||||
|
||||
const allowedIds = computed(() => {
|
||||
|
||||
const fromSummary = summary.value.allowed_actions;
|
||||
|
||||
if (Array.isArray(fromSummary) && fromSummary.length) return new Set(fromSummary.map(String));
|
||||
|
||||
return new Set(actionButtons.value.map((item) => item.id));
|
||||
|
||||
});
|
||||
|
||||
|
||||
|
||||
const visibleActions = computed(() =>
|
||||
|
||||
actionButtons.value.filter((action) => {
|
||||
const id = String(action.id || '');
|
||||
return allowedIds.value.has(id) && isActionAllowedForCheckpoint(id, checkpointKind.value);
|
||||
}),
|
||||
|
||||
);
|
||||
|
||||
|
||||
|
||||
/**
|
||||
|
||||
* 动作成功后刷新详情并更新导航徽标。
|
||||
|
||||
*/
|
||||
|
||||
async function afterSuccess() {
|
||||
|
||||
await refreshShippingTodoBadge(true);
|
||||
|
||||
emit('refreshed');
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
|
||||
* 从任务上下文解析唯一库存源编码;多候选或无候选时返回空字符串。
|
||||
|
||||
*/
|
||||
|
||||
function resolveSingleInventorySourceCode(action: ShippingChatAction): string {
|
||||
|
||||
const fromAction = String(action.source_code || '').trim().toUpperCase();
|
||||
|
||||
if (fromAction) return fromAction;
|
||||
|
||||
const resolution = props.detail.inventory_source_resolution;
|
||||
|
||||
const candidates = resolution && typeof resolution === 'object'
|
||||
|
||||
? (resolution as { candidates?: unknown }).candidates
|
||||
|
||||
: null;
|
||||
|
||||
if (Array.isArray(candidates) && candidates.length === 1) {
|
||||
|
||||
const only = candidates[0];
|
||||
|
||||
if (only && typeof only === 'object') {
|
||||
|
||||
return String((only as { source_code?: unknown }).source_code || '').trim().toUpperCase();
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
return '';
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
|
||||
* 打开库存源选择对话框;若已能唯一解析则直接提交。
|
||||
|
||||
*/
|
||||
|
||||
async function runConfirmInventorySource(action: ShippingChatAction) {
|
||||
|
||||
const directCode = resolveSingleInventorySourceCode(action);
|
||||
|
||||
if (directCode) {
|
||||
|
||||
busyId.value = 'confirm_inventory_source';
|
||||
|
||||
try {
|
||||
|
||||
await confirmWorkspaceShippingInventorySource(props.detail.task_no, directCode);
|
||||
|
||||
await afterSuccess();
|
||||
|
||||
} catch (e: unknown) {
|
||||
|
||||
msg.warning(e instanceof Error ? e.message : t('workspace.shippingNotice.actions.failed'));
|
||||
|
||||
} finally {
|
||||
|
||||
busyId.value = null;
|
||||
|
||||
}
|
||||
|
||||
return;
|
||||
|
||||
}
|
||||
|
||||
const resolution = props.detail.inventory_source_resolution;
|
||||
|
||||
const raw = resolution && typeof resolution === 'object'
|
||||
|
||||
? (resolution as { candidates?: unknown }).candidates
|
||||
|
||||
: null;
|
||||
|
||||
inventorySourceCandidates.value = Array.isArray(raw)
|
||||
|
||||
? raw.filter((item): item is ShippingInventorySourceCandidate =>
|
||||
|
||||
Boolean(item && typeof item === 'object' && (item as ShippingInventorySourceCandidate).source_code))
|
||||
|
||||
: [];
|
||||
|
||||
inventorySourceInitialCode.value = String(action.source_code || '').trim().toUpperCase();
|
||||
|
||||
inventorySourceDialogOpen.value = true;
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
|
||||
* 对话框确认库存源后提交后端。
|
||||
|
||||
*/
|
||||
|
||||
async function onInventorySourceConfirm(sourceCode: string) {
|
||||
|
||||
if (!sourceCode.trim()) {
|
||||
|
||||
msg.warning(t('workspace.shippingNotice.actions.inventorySourcePrompt'));
|
||||
|
||||
return;
|
||||
|
||||
}
|
||||
|
||||
busyId.value = 'confirm_inventory_source';
|
||||
|
||||
try {
|
||||
|
||||
await confirmWorkspaceShippingInventorySource(props.detail.task_no, sourceCode.trim().toUpperCase());
|
||||
|
||||
await afterSuccess();
|
||||
|
||||
} catch (e: unknown) {
|
||||
|
||||
msg.warning(e instanceof Error ? e.message : t('workspace.shippingNotice.actions.failed'));
|
||||
|
||||
} finally {
|
||||
|
||||
busyId.value = null;
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
|
||||
* 打开客户确认对话框并加载启用标准客户。
|
||||
|
||||
*/
|
||||
|
||||
async function openCustomerDialog() {
|
||||
|
||||
customerDialogOpen.value = true;
|
||||
|
||||
customerLoading.value = true;
|
||||
|
||||
try {
|
||||
|
||||
customerOptions.value = await listWorkspaceShippingCustomerOptions();
|
||||
|
||||
} catch (e: unknown) {
|
||||
|
||||
customerOptions.value = [];
|
||||
|
||||
msg.warning(e instanceof Error ? e.message : t('workspace.shippingNotice.actions.customerNotFound'));
|
||||
|
||||
} finally {
|
||||
|
||||
customerLoading.value = false;
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
|
||||
* 按关键词刷新客户选项。
|
||||
|
||||
*/
|
||||
|
||||
async function searchCustomers(query: string) {
|
||||
|
||||
customerLoading.value = true;
|
||||
|
||||
try {
|
||||
|
||||
customerOptions.value = await listWorkspaceShippingCustomerOptions(query.trim());
|
||||
|
||||
if (!customerOptions.value.length) {
|
||||
|
||||
msg.warning(t('workspace.shippingNotice.actions.customerNotFound'));
|
||||
|
||||
}
|
||||
|
||||
} catch (e: unknown) {
|
||||
|
||||
msg.warning(e instanceof Error ? e.message : t('workspace.shippingNotice.actions.customerNotFound'));
|
||||
|
||||
} finally {
|
||||
|
||||
customerLoading.value = false;
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
|
||||
* 确认客户后刷新任务详情。
|
||||
|
||||
*/
|
||||
|
||||
async function onCustomerConfirm(customerId: number) {
|
||||
|
||||
busyId.value = 'confirm_customer';
|
||||
|
||||
try {
|
||||
|
||||
await confirmWorkspaceShippingCustomer(props.detail.task_no, customerId);
|
||||
|
||||
customerDialogOpen.value = false;
|
||||
|
||||
await afterSuccess();
|
||||
|
||||
} catch (e: unknown) {
|
||||
|
||||
msg.warning(e instanceof Error ? e.message : t('workspace.shippingNotice.actions.failed'));
|
||||
|
||||
} finally {
|
||||
|
||||
busyId.value = null;
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
|
||||
* 校验版本并打开冻结确认对话框。
|
||||
|
||||
*/
|
||||
|
||||
function openFreezeDialog() {
|
||||
|
||||
const version = Number(props.detail.order_data_version);
|
||||
|
||||
if (!Number.isInteger(version) || version < 1) {
|
||||
|
||||
msg.warning(t('workspace.shippingNotice.actions.freezeFailed'));
|
||||
|
||||
return;
|
||||
|
||||
}
|
||||
|
||||
pendingFreezeVersion.value = version;
|
||||
|
||||
freezeDialogOpen.value = true;
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
|
||||
* 确认冻结后提交后端。
|
||||
|
||||
*/
|
||||
|
||||
async function onFreezeConfirm() {
|
||||
|
||||
const version = pendingFreezeVersion.value;
|
||||
|
||||
if (version == null) return;
|
||||
|
||||
busyId.value = 'freeze_order';
|
||||
|
||||
try {
|
||||
|
||||
await freezeWorkspaceShippingOrder(props.detail.task_no, version);
|
||||
|
||||
await afterSuccess();
|
||||
|
||||
} catch (e: unknown) {
|
||||
|
||||
msg.warning(e instanceof Error ? e.message : t('workspace.shippingNotice.actions.failed'));
|
||||
|
||||
} finally {
|
||||
|
||||
busyId.value = null;
|
||||
|
||||
pendingFreezeVersion.value = null;
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
|
||||
* 执行后端允许的动作;人工上传/客户/库存源/冻结走对话框,其余走对应工作台 API。
|
||||
|
||||
*/
|
||||
|
||||
async function runAction(action: ShippingChatAction) {
|
||||
|
||||
if (!props.canHandle || busyId.value) return;
|
||||
|
||||
const id = String(action.id || '');
|
||||
|
||||
|
||||
|
||||
if (id === 'mark_manual_uploaded') {
|
||||
|
||||
manualUploadOpen.value = true;
|
||||
|
||||
return;
|
||||
|
||||
}
|
||||
|
||||
if (id === 'refresh') {
|
||||
|
||||
emit('refreshed');
|
||||
|
||||
return;
|
||||
|
||||
}
|
||||
|
||||
if (id === 'confirm_customer') {
|
||||
|
||||
await openCustomerDialog();
|
||||
|
||||
return;
|
||||
|
||||
}
|
||||
|
||||
if (id === 'confirm_inventory_source') {
|
||||
|
||||
await runConfirmInventorySource(action);
|
||||
|
||||
return;
|
||||
|
||||
}
|
||||
|
||||
if (id === 'freeze_order') {
|
||||
|
||||
openFreezeDialog();
|
||||
|
||||
return;
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
busyId.value = id;
|
||||
|
||||
try {
|
||||
|
||||
if (id === 'download_excel' || id === 'export') {
|
||||
|
||||
await downloadWorkspaceShippingExcelFile(props.detail.task_no);
|
||||
|
||||
await afterSuccess();
|
||||
|
||||
return;
|
||||
|
||||
}
|
||||
|
||||
if (id === 'generate_excel') {
|
||||
|
||||
await generateWorkspaceShippingExcel(props.detail.task_no);
|
||||
|
||||
await afterSuccess();
|
||||
|
||||
return;
|
||||
|
||||
}
|
||||
|
||||
if (id === 'match_inventory' || id === 'rematch') {
|
||||
|
||||
await matchWorkspaceShippingInventory(props.detail.task_no);
|
||||
|
||||
await afterSuccess();
|
||||
|
||||
return;
|
||||
|
||||
}
|
||||
|
||||
if (id === 'retry_upload') {
|
||||
|
||||
await retryWorkspaceShippingUpload(props.detail.task_no);
|
||||
|
||||
await afterSuccess();
|
||||
|
||||
return;
|
||||
|
||||
}
|
||||
|
||||
await submitWorkspaceShippingDecision(props.detail.task_no, id);
|
||||
|
||||
await afterSuccess();
|
||||
|
||||
} catch (e: unknown) {
|
||||
|
||||
msg.warning(e instanceof Error ? e.message : t('workspace.shippingNotice.actions.failed'));
|
||||
|
||||
} finally {
|
||||
|
||||
busyId.value = null;
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
</script>
|
||||
|
||||
|
||||
|
||||
<template>
|
||||
|
||||
<section class="rounded-2xl border border-brand-200/80 bg-brand-50/40 px-4 py-3">
|
||||
|
||||
<div class="mb-1 text-xs font-semibold uppercase tracking-wide text-brand-700">
|
||||
|
||||
{{ $t('workspace.shippingNotice.todo.currentTodo') }}
|
||||
|
||||
</div>
|
||||
|
||||
<h3 class="text-sm font-semibold text-primary">
|
||||
|
||||
{{ summary.current_todo || summary.title || $t('workspace.shippingNotice.todo.noActionTitle') }}
|
||||
|
||||
</h3>
|
||||
|
||||
<p class="mt-1 text-sm text-secondary">
|
||||
|
||||
{{ summary.message || $t('workspace.shippingNotice.todo.noActionMessage') }}
|
||||
|
||||
</p>
|
||||
|
||||
<p v-if="summary.pause_reason" class="mt-1 text-xs text-amber-700">
|
||||
|
||||
{{ summary.pause_reason }}
|
||||
|
||||
</p>
|
||||
|
||||
|
||||
|
||||
<div v-if="!canHandle" class="mt-3 text-xs text-muted">
|
||||
|
||||
{{ $t('workspace.shippingNotice.todo.adminViewOnly') }}
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
<div v-else-if="visibleActions.length" class="mt-3 flex flex-wrap gap-2">
|
||||
|
||||
<button
|
||||
|
||||
v-for="action in visibleActions"
|
||||
|
||||
:key="action.id"
|
||||
|
||||
type="button"
|
||||
|
||||
class="rounded-xl px-3 py-1.5 text-sm font-medium transition-colors disabled:opacity-50"
|
||||
|
||||
:class="action.variant === 'danger'
|
||||
|
||||
? 'bg-rose-600 text-white hover:bg-rose-700'
|
||||
|
||||
: action.variant === 'secondary'
|
||||
|
||||
? 'border border-default bg-surface text-secondary hover:bg-surface-soft'
|
||||
|
||||
: 'bg-brand-600 text-white hover:bg-brand-700'"
|
||||
|
||||
:disabled="busyId === action.id"
|
||||
|
||||
@click="runAction(action)"
|
||||
|
||||
>
|
||||
|
||||
{{ action.label }}
|
||||
|
||||
</button>
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
<p
|
||||
v-if="showWaitingManualUploadNote"
|
||||
class="mt-3 rounded-xl border border-amber-200 bg-amber-50 px-3 py-2 text-xs text-amber-800"
|
||||
data-testid="manual-upload-end-note"
|
||||
>
|
||||
{{ $t('workspace.shippingNotice.todo.waitingManualUploadNote') }}
|
||||
</p>
|
||||
<ManualUploadEvidenceDialog
|
||||
|
||||
v-model:open="manualUploadOpen"
|
||||
|
||||
:task-no="detail.task_no"
|
||||
|
||||
:artifact-id="detail.export_artifacts?.[0]?.id"
|
||||
|
||||
:artifact-id="currentExportArtifactId"
|
||||
:disabled="!canHandle"
|
||||
|
||||
@success="afterSuccess"
|
||||
|
||||
/>
|
||||
|
||||
|
||||
|
||||
<ShippingCustomerConfirmDialog
|
||||
|
||||
:open="customerDialogOpen"
|
||||
|
||||
:options="customerOptions"
|
||||
|
||||
:loading="customerLoading"
|
||||
|
||||
@close="customerDialogOpen = false"
|
||||
|
||||
@search="searchCustomers"
|
||||
|
||||
@confirm="onCustomerConfirm"
|
||||
|
||||
/>
|
||||
|
||||
|
||||
|
||||
<InventorySourceSelectDialog
|
||||
|
||||
v-model:open="inventorySourceDialogOpen"
|
||||
|
||||
:candidates="inventorySourceCandidates"
|
||||
|
||||
:initial-code="inventorySourceInitialCode"
|
||||
|
||||
@confirm="onInventorySourceConfirm"
|
||||
|
||||
/>
|
||||
|
||||
|
||||
|
||||
<DeleteConfirmDialog
|
||||
|
||||
v-model="freezeDialogOpen"
|
||||
|
||||
confirm-tone="primary"
|
||||
|
||||
:title="$t('workspace.shippingNotice.actions.freezeOrder')"
|
||||
|
||||
:message="$t('workspace.shippingNotice.actions.freezeConfirm')"
|
||||
|
||||
:confirm-text="$t('workspace.shippingNotice.actions.freezeOrder')"
|
||||
|
||||
:confirm-loading="busyId === 'freeze_order'"
|
||||
|
||||
@confirm="onFreezeConfirm"
|
||||
|
||||
/>
|
||||
|
||||
</section>
|
||||
|
||||
</template>
|
||||
|
||||
Reference in new issue
Block a user