feat(shipping-notice): 新增发货通知自动上传功能与候选资格评估

- 在环境配置中新增 SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED 选项,默认关闭,需显式开启以支持自动上传。
- 引入新的 pytest.ini 文件,增加测试标记以支持自动化测试。
- 删除不再使用的 seed_shipping_notice_agents.py 文件,简化代码库。
- 更新相关 API,增强发货通知与候选资格评估功能,支持多种筛选条件。
- 增强文档与代码注释,反映新的业务逻辑与功能要求。
This commit is contained in:
hugo committed 2026-08-02 19:26:35 +08:00
1 parent cef3d5b26a
commit 3a9fbac2fc
226 files changed
+25010 -2098

No files matched your search

@@ -1,11 +1,11 @@
/**
* features/admin/api/shipping-audit.api.ts
* 用途:货代统一审计查询/详情/关联链/哈希校验/导出 HTTP 客户端。
* 依赖:shared/api/client、getAuthHeaders。
* 依赖:shared/api/client(requestJson / requestBlob)、getAuthHeaders。
* 逻辑:由 ShippingAuditCenterPage / ShippingAuditEventDetailDrawer 调用;
* 导出走 blob 下载;敏感详情由后端按 audit_sensitive_read 裁剪。
* 导出走 requestBlob;失败为 BusinessError;敏感详情由后端按 audit_sensitive_read 裁剪。
*/
import { requestJson } from '@/shared/api/client';
import { requestBlob, requestJson } from '@/shared/api/client';
import { getAuthHeaders } from '@/shared/utils/auth';
export type ShippingAuditEventSummary = {
@@ -56,11 +56,20 @@ export type ShippingAuditEventDetail = ShippingAuditEventSummary & {
export type ShippingAuditFilters = {
event_type?: string;
/**
* 事件分组:review_workbench / chat_workbench / process_gate /
* candidate_qualification / workflow_node。
*/
event_type_group?: string;
actor_type?: string;
/** 操作者用户 ID;与后端 audit_query_service.actor_id 对齐 */
actor_id?: string;
run_no?: string;
task_no?: string;
/** Candidate 编号;匹配 aggregate_id */
candidate_no?: string;
/** Process Gate / 节点码;匹配 aggregate_id 后缀 */
gate_code?: string;
document_id?: string;
operation_id?: string;
request_id?: string;
@@ -69,6 +78,8 @@ export type ShippingAuditFilters = {
workflow_item_id?: string;
review_case_no?: string;
owner_user_id?: string;
/** 稳定业务原因码;与后端 audit_query_service.reason_code 对齐 */
reason_code?: string;
result?: string;
created_from?: string;
created_to?: string;
@@ -154,12 +165,13 @@ export function verifyShippingAuditHashChain(body: {
/**
* 受控导出审计 CSV/JSON,并触发浏览器下载。
* 核心逻辑:经 requestBlob 统一鉴权与 BusinessError;成功后触发本地下载。
*/
export async function exportShippingAuditEvents(
filters: ShippingAuditFilters = {},
format: 'csv' | 'json' = 'csv',
): Promise<void> {
const response = await fetch('/api/admin/shipping-notice/audit-events/export', {
const { blob, filename } = await requestBlob('/api/admin/shipping-notice/audit-events/export', {
method: 'POST',
headers: {
...getAuthHeaders(),
@@ -167,15 +179,10 @@ export async function exportShippingAuditEvents(
},
body: JSON.stringify({ ...filters, format, limit: 2000 }),
});
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const blob = await response.blob();
const disposition = response.headers.get('Content-Disposition') || '';
const filename = disposition.match(/filename="?([^";]+)"?/i)?.[1]
|| `shipping-audit.${format}`;
const objectUrl = URL.createObjectURL(blob);
const anchor = document.createElement('a');
anchor.href = objectUrl;
anchor.download = filename;
anchor.download = filename || `shipping-audit.${format}`;
anchor.click();
URL.revokeObjectURL(objectUrl);
}
@@ -296,7 +296,7 @@ export const runOrderProfileInstantCheck = (profileId: number, payload: {
/** 在绑定 annotation/training 样本上试运行;接口不会接受或回显盲测真值。 */
export const runOrderProfileCurrentSample = (profileId: number, payload: {
sample_binding_id?: number; browser_session_id: string; lease_token: string; operation_id: string;
sample_binding_id: number; browser_session_id: string; lease_token: string; operation_id: string;
}) => requestJson<import('@/features/admin/types/shipping-order-document-profile.types').OrderProfileValidationRun>(
`/api/admin/shipping-notice/order-document-profiles/${profileId}/validation-runs/current-sample`,
{ method: 'POST', body: JSON.stringify(payload), ...jsonAuth() },
@@ -1,12 +1,16 @@
<!--
features/admin/modules/shipping-audit/ShippingAuditCenterPage.vue
用途:管理员货代统一审计中心——按 Workflow/Item/Run/PDF/Case/Task 筛选、详情 Diff、关联链、哈希校验、受控导出。
依赖:shipping-audit.api、ShippingAuditEventDetailDrawer、Vue I18n。
逻辑:列表不含快照全文;详情抽屉按权限脱敏;导出/校验写服务端访问审计。
用途:管理员货代统一审计中心——按 Conversation/Run/Candidate/Task/Gate/节点分组筛选、详情 Diff、关联链、哈希校验、受控导出。
依赖:shipping-audit.api、shippingAuditDisplay、ShippingAuditEventDetailDrawer、Vue I18n、BusinessError、useMessage。
逻辑:列表不含快照全文;详情抽屉按权限脱敏;导出/校验写服务端访问审计;
事件分组含复核/对话/Process Gate/资格/节点;支持 candidate_no / gate_code;
窄屏用卡片列表;桌面表无横滚,Case/Task 在业务关联列,WF/Item/Run 芯片可复制。
-->
<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { computed, onMounted, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { BusinessError } from '@/shared/api/client';
import { useMessage } from '@/shared/composables/useMessage';
import {
exportShippingAuditEvents,
getShippingAuditEvent,
@@ -19,12 +23,15 @@ import {
type ShippingAuditHashVerifyResult,
} from '@/features/admin/api/shipping-audit.api';
import ShippingAuditEventDetailDrawer from './ShippingAuditEventDetailDrawer.vue';
import { shippingAuditBusinessLabel } from './shippingAuditDisplay';
const { t } = useI18n();
const { t, te } = useI18n();
const msg = useMessage();
const loading = ref(false);
const detailLoading = ref(false);
const exporting = ref(false);
const verifying = ref(false);
const moreOpen = ref(false);
const error = ref('');
const page = ref(1);
const pageSize = 25;
@@ -35,6 +42,7 @@ const chainHint = ref('');
const verifyResult = ref<ShippingAuditHashVerifyResult | null>(null);
const filters = ref<ShippingAuditFilters>({
event_type: '',
event_type_group: '',
actor_type: '',
actor_id: '',
workflow_id: '',
@@ -43,10 +51,13 @@ const filters = ref<ShippingAuditFilters>({
document_id: '',
review_case_no: '',
task_no: '',
candidate_no: '',
gate_code: '',
conversation_id: '',
owner_user_id: '',
operation_id: '',
request_id: '',
reason_code: '',
result: '',
created_from: '',
created_to: '',
@@ -77,6 +88,62 @@ function buildFilterPayload(): ShippingAuditFilters {
const formatTime = (value?: string | null) => (value ? new Date(value).toLocaleString() : '—');
/**
* 列表主区业务关联:仅 Case/Task,与 WF/Item/Run 技术编号严格分离。
*/
function primaryBusinessRefs(row: ShippingAuditEventSummary): string {
const parts = [
row.review_case_no ? `Case ${row.review_case_no}` : '',
row.task_no ? `Task ${row.task_no}` : '',
].filter(Boolean);
return parts.length ? parts.join(' · ') : '—';
}
/**
* 行级技术编号芯片(WF/Item/Run),供桌面业务关联列与窄屏卡片复用。
*/
function techRefChips(row: ShippingAuditEventSummary): Array<{ label: string; value: string }> {
return [
{ label: 'WF', value: row.workflow_id },
{ label: 'Item', value: row.workflow_item_id },
{ label: 'Run', value: row.run_no },
].filter((entry): entry is { label: string; value: string } => Boolean(entry.value));
}
/**
* 业务化标签:与详情抽屉共用 shippingAuditDisplay,保证口径一致。
*/
function businessLabel(kind: 'eventTypes' | 'actions' | 'reasonCodes' | 'actorTypes' | 'results', code?: string | null): string {
return shippingAuditBusinessLabel({ t, te }, kind, code);
}
/**
* 复制技术编号;失败时静默忽略。
*/
async function copyTechId(value?: string | null) {
const text = String(value || '').trim();
if (!text || !navigator?.clipboard?.writeText) return;
try {
await navigator.clipboard.writeText(text);
msg.success(t('admin.shippingAudit.copied'));
} catch {
/* ignore */
}
}
/**
* 统一捕获 API 错误为页面提示 + useMessage。
*/
function reportError(err: unknown, fallbackKey: string) {
if (err instanceof BusinessError) {
error.value = err.message;
msg.error(err.message);
return;
}
error.value = t(fallbackKey);
msg.error(t(fallbackKey));
}
/**
* 加载审计列表;服务端已做管理员鉴权与访问留痕。
*/
@@ -87,8 +154,8 @@ async function load() {
const response = await listShippingAuditEvents(page.value, pageSize, buildFilterPayload());
rows.value = response.items;
total.value = response.total;
} catch {
error.value = t('admin.shippingAudit.loadFailed');
} catch (err) {
reportError(err, 'admin.shippingAudit.loadFailed');
} finally {
loading.value = false;
}
@@ -110,8 +177,8 @@ async function openDetail(eventId: number) {
error.value = '';
try {
detail.value = await getShippingAuditEvent(eventId);
} catch {
error.value = t('admin.shippingAudit.detailFailed');
} catch (err) {
reportError(err, 'admin.shippingAudit.detailFailed');
} finally {
detailLoading.value = false;
}
@@ -123,6 +190,7 @@ async function openDetail(eventId: number) {
async function loadAssociationChain() {
error.value = '';
chainHint.value = '';
moreOpen.value = false;
try {
const payload = buildFilterPayload();
const hasSeed = Boolean(
@@ -141,8 +209,8 @@ async function loadAssociationChain() {
rows.value = chain.items.slice().reverse();
total.value = chain.total;
page.value = 1;
} catch {
error.value = t('admin.shippingAudit.chainFailed');
} catch (err) {
reportError(err, 'admin.shippingAudit.chainFailed');
}
}
@@ -153,6 +221,7 @@ async function runHashVerify() {
verifying.value = true;
error.value = '';
verifyResult.value = null;
moreOpen.value = false;
try {
const payload = buildFilterPayload();
verifyResult.value = await verifyShippingAuditHashChain({
@@ -160,8 +229,8 @@ async function runHashVerify() {
workflow_item_id: payload.workflow_item_id || undefined,
sample_limit: 200,
});
} catch {
error.value = t('admin.shippingAudit.verifyFailed');
} catch (err) {
reportError(err, 'admin.shippingAudit.verifyFailed');
} finally {
verifying.value = false;
}
@@ -175,13 +244,16 @@ async function exportCsv() {
error.value = '';
try {
await exportShippingAuditEvents(buildFilterPayload(), 'csv');
} catch {
error.value = t('admin.shippingAudit.exportFailed');
msg.success(t('admin.shippingAudit.exportDone'));
} catch (err) {
reportError(err, 'admin.shippingAudit.exportFailed');
} finally {
exporting.value = false;
}
}
const pageLabel = computed(() => String(page.value));
onMounted(() => {
void load();
});
@@ -189,24 +261,40 @@ onMounted(() => {
<template>
<section class="space-y-5 p-5 md:p-7" data-testid="shipping-audit-center">
<header class="flex flex-wrap items-start justify-between gap-4">
<div>
<header class="flex flex-col gap-3 sm:flex-row sm:flex-wrap sm:items-start sm:justify-between">
<div class="min-w-0">
<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 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>
<button type="button" class="btn-secondary btn-sm" :disabled="loading" @click="load">
<!-- [STEP] 窄屏主操作:刷新/导出;校验与关联链收入“更多”。 -->
<div class="flex w-full flex-wrap items-center gap-2 sm:w-auto sm:justify-end">
<button type="button" class="btn-secondary btn-sm" :disabled="loading" data-testid="shipping-audit-refresh" @click="load">
{{ t('admin.shippingAudit.refresh') }}
</button>
<button type="button" class="btn-secondary btn-sm" :disabled="exporting" data-testid="shipping-audit-export" @click="exportCsv">
{{ exporting ? t('admin.shippingAudit.exporting') : t('admin.shippingAudit.export') }}
</button>
<div class="relative">
<button
type="button"
class="btn-secondary btn-sm md:hidden"
data-testid="shipping-audit-more"
@click="moreOpen = !moreOpen"
>
{{ t('admin.shippingAudit.moreActions') }}
</button>
<div
class="absolute right-0 z-10 mt-1 w-44 rounded-lg border border-default bg-surface p-1 shadow-md md:static md:mt-0 md:flex md:w-auto md:items-center md:gap-2 md:border-0 md:bg-transparent md:p-0 md:shadow-none"
:class="moreOpen ? 'block' : 'hidden md:flex'"
>
<button type="button" class="btn-secondary btn-sm w-full justify-start md:w-auto" :disabled="verifying" @click="runHashVerify">
{{ verifying ? t('admin.shippingAudit.verifying') : t('admin.shippingAudit.verifyChain') }}
</button>
<button type="button" class="btn-secondary btn-sm w-full justify-start md:w-auto" @click="loadAssociationChain">
{{ t('admin.shippingAudit.loadChain') }}
</button>
</div>
</div>
</div>
</header>
@@ -235,24 +323,62 @@ onMounted(() => {
<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.candidateNo') }}</span>
<input
v-model="filters.candidate_no"
class="input-field text-sm"
data-testid="shipping-audit-filter-candidate-no"
@keyup.enter="applyFilters"
>
</label>
<label class="space-y-1 text-xs text-secondary">
<span>{{ t('admin.shippingAudit.filters.gateCode') }}</span>
<input
v-model="filters.gate_code"
class="input-field text-sm"
data-testid="shipping-audit-filter-gate-code"
@keyup.enter="applyFilters"
>
</label>
<label class="space-y-1 text-xs text-secondary">
<span>{{ t('admin.shippingAudit.filters.actorType') }}</span>
<select v-model="filters.actor_type" class="select-field text-sm" @change="applyFilters">
<option value="">{{ t('admin.shippingAudit.filters.all') }}</option>
<option value="user">user</option>
<option value="admin">admin</option>
<option value="system">system</option>
<option value="rpa">rpa</option>
<option value="user">{{ t('admin.shippingAudit.labels.actorTypes.user') }}</option>
<option value="admin">{{ t('admin.shippingAudit.labels.actorTypes.admin') }}</option>
<option value="system">{{ t('admin.shippingAudit.labels.actorTypes.system') }}</option>
<option value="rpa">{{ t('admin.shippingAudit.labels.actorTypes.rpa') }}</option>
</select>
</label>
<label class="space-y-1 text-xs text-secondary">
<span>{{ t('admin.shippingAudit.filters.actorId') }}</span>
<input v-model="filters.actor_id" class="input-field text-sm" @keyup.enter="applyFilters">
</label>
<label class="space-y-1 text-xs text-secondary">
<span>{{ t('admin.shippingAudit.filters.eventTypeGroup') }}</span>
<select
v-model="filters.event_type_group"
class="select-field text-sm"
data-testid="shipping-audit-filter-event-type-group"
@change="applyFilters"
>
<option value="">{{ t('admin.shippingAudit.filters.all') }}</option>
<option value="review_workbench">{{ t('admin.shippingAudit.filters.eventTypeGroupReviewWorkbench') }}</option>
<option value="chat_workbench">{{ t('admin.shippingAudit.filters.eventTypeGroupChatWorkbench') }}</option>
<option value="process_gate">{{ t('admin.shippingAudit.filters.eventTypeGroupProcessGate') }}</option>
<option value="candidate_qualification">{{ t('admin.shippingAudit.filters.eventTypeGroupQualification') }}</option>
<option value="workflow_node">{{ t('admin.shippingAudit.filters.eventTypeGroupWorkflowNode') }}</option>
</select>
</label>
<label class="space-y-1 text-xs text-secondary">
<span>{{ t('admin.shippingAudit.filters.eventType') }}</span>
<input v-model="filters.event_type" class="input-field text-sm" @keyup.enter="applyFilters">
</label>
<label class="space-y-1 text-xs text-secondary">
<span>{{ t('admin.shippingAudit.filters.reasonCode') }}</span>
<input v-model="filters.reason_code" class="input-field text-sm" data-testid="shipping-audit-filter-reason-code" @keyup.enter="applyFilters">
</label>
<label class="space-y-1 text-xs text-secondary">
<span>{{ t('admin.shippingAudit.filters.result') }}</span>
<input v-model="filters.result" class="input-field text-sm" @keyup.enter="applyFilters">
@@ -288,43 +414,114 @@ onMounted(() => {
</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-[1360px] w-full text-left text-sm">
<!-- 窄屏卡片列表:避免 1360px 表强制横向滚动才能点到 Diff -->
<div class="space-y-3 lg:hidden" data-testid="shipping-audit-card-list">
<p v-if="loading" class="rounded-xl border border-default bg-surface px-3 py-8 text-center text-sm text-muted">
{{ t('admin.shippingAudit.loading') }}
</p>
<p v-else-if="!rows.length" class="rounded-xl border border-default bg-surface px-3 py-8 text-center text-sm text-muted">
{{ t('admin.shippingAudit.empty') }}
</p>
<article
v-for="row in rows"
:key="row.id"
class="rounded-xl border border-default bg-surface p-3"
>
<div class="flex items-start justify-between gap-2">
<div class="min-w-0">
<div class="text-sm font-medium text-secondary">{{ businessLabel('eventTypes', row.event_type) }}</div>
<div class="mt-0.5 text-xs text-muted">{{ businessLabel('actions', row.action) }}</div>
</div>
<button type="button" class="shrink-0 text-sm text-brand-600 hover:underline" @click="openDetail(row.id)">
{{ t('admin.shippingAudit.diff') }}
</button>
</div>
<dl class="mt-2 grid gap-1 text-xs text-secondary">
<div><dt class="inline text-muted">{{ t('admin.shippingAudit.columns.time') }}:</dt><dd class="inline">{{ formatTime(row.created_at) }}</dd></div>
<div><dt class="inline text-muted">{{ t('admin.shippingAudit.columns.actor') }}:</dt><dd class="inline">{{ businessLabel('actorTypes', row.actor_type) }}</dd></div>
<div><dt class="inline text-muted">{{ t('admin.shippingAudit.columns.reasonCode') }}:</dt><dd class="inline font-medium">{{ businessLabel('reasonCodes', row.reason_code) }}</dd></div>
<div><dt class="inline text-muted">{{ t('admin.shippingAudit.columns.result') }}:</dt><dd class="inline">{{ businessLabel('results', row.result) }}</dd></div>
<div v-if="primaryBusinessRefs(row) !== '—'">
<dt class="inline text-muted">{{ t('admin.shippingAudit.columns.businessRefs') }}:</dt>
<dd class="inline">{{ primaryBusinessRefs(row) }}</dd>
</div>
</dl>
<div
v-if="techRefChips(row).length"
class="mt-2 flex flex-wrap items-center gap-1.5"
data-testid="shipping-audit-tech-ref-chips"
>
<span class="text-[10px] text-muted">{{ t('admin.shippingAudit.techRefs') }}</span>
<button
v-for="item in techRefChips(row)"
:key="`${row.id}-m-tech-${item.label}`"
type="button"
class="rounded border border-default px-2 py-1 font-mono text-[11px] text-muted"
:title="item.value"
@click="copyTechId(item.value)"
>
{{ item.label }}
</button>
</div>
</article>
</div>
<!-- 桌面表:table-fixed + 无横滚;技术编号行内次要芯片,无需额外展开 -->
<div class="hidden overflow-x-hidden rounded-xl border border-default bg-surface lg:block" data-testid="shipping-audit-desktop-table">
<table class="w-full table-fixed 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.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>
<th class="px-3 py-2">{{ t('admin.shippingAudit.columns.result') }}</th>
<th class="px-3 py-2"></th>
<th class="w-[16%] px-3 py-2">{{ t('admin.shippingAudit.columns.time') }}</th>
<th class="w-[20%] px-3 py-2">{{ t('admin.shippingAudit.columns.event') }}</th>
<th class="w-[10%] px-3 py-2">{{ t('admin.shippingAudit.columns.actor') }}</th>
<th class="w-[18%] px-3 py-2">{{ t('admin.shippingAudit.columns.reasonCode') }}</th>
<th class="w-[10%] px-3 py-2">{{ t('admin.shippingAudit.columns.result') }}</th>
<th class="w-[16%] px-3 py-2">{{ t('admin.shippingAudit.columns.businessRefs') }}</th>
<th class="w-[10%] px-3 py-2"></th>
</tr>
</thead>
<tbody>
<tr v-if="loading">
<td colspan="10" class="px-3 py-8 text-center text-muted">{{ t('admin.shippingAudit.loading') }}</td>
<td colspan="7" class="px-3 py-8 text-center text-muted">{{ t('admin.shippingAudit.loading') }}</td>
</tr>
<tr v-else-if="!rows.length">
<td colspan="10" class="px-3 py-8 text-center text-muted">{{ t('admin.shippingAudit.empty') }}</td>
<td colspan="7" class="px-3 py-8 text-center text-muted">{{ t('admin.shippingAudit.empty') }}</td>
</tr>
<tr v-for="row in rows" :key="row.id" class="border-b border-default last:border-0">
<td class="px-3 py-2 text-xs">{{ formatTime(row.created_at) }}</td>
<td class="px-3 py-2">
<div class="font-medium">{{ row.event_type }}</div>
<div class="text-[11px] text-muted">{{ row.action || '—' }}</div>
<tr
v-for="row in rows"
:key="row.id"
class="border-b border-default last:border-0"
>
<td class="px-3 py-2 align-top text-xs">{{ formatTime(row.created_at) }}</td>
<td class="px-3 py-2 align-top">
<div class="font-medium break-words">{{ businessLabel('eventTypes', row.event_type) }}</div>
<div class="text-[11px] text-muted break-words">{{ businessLabel('actions', 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.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>
<td class="px-3 py-2">{{ row.result || '—' }}</td>
<td class="px-3 py-2">
<td class="px-3 py-2 align-top text-xs">{{ businessLabel('actorTypes', row.actor_type) }}</td>
<td class="px-3 py-2 align-top text-xs break-words font-medium text-secondary">
{{ businessLabel('reasonCodes', row.reason_code) }}
</td>
<td class="px-3 py-2 align-top">{{ businessLabel('results', row.result) }}</td>
<td class="px-3 py-2 align-top text-[11px] text-secondary break-words">
<div>{{ primaryBusinessRefs(row) }}</div>
<div
v-if="techRefChips(row).length"
class="mt-1 flex flex-wrap gap-1"
data-testid="shipping-audit-tech-ref-chips"
>
<button
v-for="item in techRefChips(row)"
:key="`${row.id}-tech-${item.label}`"
type="button"
class="rounded border border-default bg-surface-soft px-1 py-0.5 font-mono text-[10px] text-muted"
:title="item.value"
@click="copyTechId(item.value)"
>
{{ item.label }}
</button>
</div>
</td>
<td class="px-3 py-2 align-top">
<button type="button" class="text-brand-600 hover:underline" @click="openDetail(row.id)">
{{ t('admin.shippingAudit.diff') }}
</button>
@@ -337,7 +534,7 @@ onMounted(() => {
<div class="flex items-center justify-end gap-3 text-sm">
<span class="text-xs text-muted">{{ t('admin.shippingAudit.total', { count: total }) }}</span>
<button type="button" class="rounded border border-default px-3 py-1.5 disabled:opacity-50" :disabled="page <= 1 || loading" @click="page -= 1; load()">{{ t('admin.shippingAudit.previous') }}</button>
<span>{{ page }}</span>
<span>{{ pageLabel }}</span>
<button type="button" class="rounded border border-default px-3 py-1.5 disabled:opacity-50" :disabled="page * pageSize >= total || loading" @click="page += 1; load()">{{ t('admin.shippingAudit.next') }}</button>
</div>
@@ -1,15 +1,23 @@
/**
* features/admin/modules/shipping-audit/ShippingAuditEventDetailDrawer.spec.ts
* 用途:锁定审计详情抽屉脱敏提示与 Diff 渲染契约。
* 用途:锁定审计详情抽屉脱敏、业务化标签与 Diff 渲染契约。
* 依赖:Vitest、@vue/test-utils、ShippingAuditEventDetailDrawer。
* 逻辑:敏感脱敏文案可见;Diff 行按 key 渲染;无 Diff 显示空态。
* 逻辑:敏感脱敏文案可见;事件/操作者/结果用业务标签;技术编号不直接平铺主区;Diff 行按 key 渲染。
*/
import { describe, expect, it } from 'vitest';
import { describe, expect, it, vi } 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';
vi.mock('@/shared/composables/useMessage', () => ({
useMessage: () => ({
success: vi.fn(),
warning: vi.fn(),
error: vi.fn(),
}),
}));
const messages = {
'zh-CN': {
admin: {
@@ -24,12 +32,41 @@ const messages = {
noDiff: '无可展示的白名单差异',
eventHash: '事件哈希',
previousEventHash: '前序哈希',
columns: { event: '事件', actor: '操作者', run: 'Run', task: 'Task', result: '结果' },
copied: '已复制编号',
copyId: '复制编号',
techRefsHint: '技术编号默认折叠展示,点击即可复制。',
hashSection: '哈希摘要(排障用)',
columns: {
event: '事件',
actor: '操作者',
run: 'Run',
task: 'Task',
result: '结果',
reasonCode: '原因',
refs: '关联编号',
},
filters: {
workflowId: 'Workflow',
workflowItemId: 'Workflow Item',
documentId: 'PDF/文档',
reviewCaseNo: 'Case',
operationId: 'operation_id',
requestId: 'request_id',
},
labels: {
eventTypes: {
fallback: '审计事件',
order_review_confirmed: '订单复核已确认',
status_changed: '状态已变更',
},
actions: { fallback: '业务操作' },
reasonCodes: { fallback: '业务原因' },
actorTypes: {
user: '业务用户',
system: '系统',
unknown: '未知操作者',
},
results: { success: '成功', ok: '成功' },
},
},
},
@@ -60,11 +97,35 @@ describe('ShippingAuditEventDetailDrawer', () => {
diff: [],
};
const wrapper = mountDrawer(detail);
// 关键断言:无敏感读权限时展示脱敏提示。
expect(wrapper.find('[data-testid="shipping-audit-sensitive-redacted"]').exists()).toBe(true);
expect(wrapper.text()).toContain('敏感快照已按权限脱敏');
});
it('uses business labels and does not flatten raw event_type in primary meta', () => {
const detail: ShippingAuditEventDetail = {
id: 3,
event_type: 'order_review_confirmed',
action: 'unknown_action_xyz',
aggregate_type: 'shipping_order_review_case',
aggregate_id: 'SRC-3',
actor_type: 'user',
actor_id: 'u-9',
result: 'success',
run_no: 'SNER-9',
request_id: 'req-9',
has_snapshots: false,
sensitive_redacted: false,
diff: [],
};
const wrapper = mountDrawer(detail);
const text = wrapper.text();
expect(wrapper.get('[data-testid="shipping-audit-detail-event"]').text()).toContain('订单复核已确认');
expect(wrapper.get('[data-testid="shipping-audit-detail-actor"]').text()).toContain('业务用户');
expect(wrapper.get('[data-testid="shipping-audit-detail-result"]').text()).toContain('成功');
expect(text).not.toContain('order_review_confirmed');
expect(wrapper.find('[data-testid="shipping-audit-detail-tech-refs"]').exists()).toBe(true);
});
it('renders whitelist diff rows', () => {
const detail: ShippingAuditEventDetail = {
id: 2,
@@ -77,7 +138,6 @@ describe('ShippingAuditEventDetailDrawer', () => {
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');
@@ -1,13 +1,16 @@
<!--
features/admin/modules/shipping-audit/ShippingAuditEventDetailDrawer.vue
用途:审计事件详情抽屉——元数据、敏感脱敏提示、白名单 Diff、哈希摘要。
依赖:shipping-audit.api 类型、Vue I18n。
逻辑:由 ShippingAuditCenterPage 传入 detail;关闭时 emit close;不自行拉接口。
用途:审计事件详情抽屉——业务化元数据、敏感脱敏提示、白名单 Diff、哈希摘要。
依赖:shipping-audit.api 类型、shippingAuditDisplay、Vue I18n、useMessage。
逻辑:由 ShippingAuditCenterPage 传入 detail;事件/动作/结果与列表同源业务标签;
技术编号以复制芯片展示;关闭时 emit close;不自行拉接口。
-->
<script setup lang="ts">
import { computed } from 'vue';
import { useI18n } from 'vue-i18n';
import { useMessage } from '@/shared/composables/useMessage';
import type { ShippingAuditEventDetail } from '@/features/admin/api/shipping-audit.api';
import { shippingAuditBusinessLabel } from './shippingAuditDisplay';
const props = defineProps<{
detail: ShippingAuditEventDetail | null;
@@ -18,10 +21,52 @@ const emit = defineEmits<{
close: [];
}>();
const { t } = useI18n();
const { t, te } = useI18n();
const msg = useMessage();
const open = computed(() => Boolean(props.detail || props.loading));
/**
* 与列表页一致的业务化标签。
*/
function label(kind: 'eventTypes' | 'actions' | 'reasonCodes' | 'actorTypes' | 'results', code?: string | null): string {
return shippingAuditBusinessLabel({ t, te }, kind, code);
}
/**
* 复制技术编号。
*/
async function copyTechId(value?: string | null) {
const text = String(value || '').trim();
if (!text || !navigator?.clipboard?.writeText) return;
try {
await navigator.clipboard.writeText(text);
msg.success(t('admin.shippingAudit.copied'));
} catch {
/* ignore */
}
}
/**
* 详情中仅展示有值的关联编号芯片。
*/
const techRefs = computed(() => {
const d = props.detail;
if (!d) return [] as Array<{ label: string; value: string }>;
return [
{ label: t('admin.shippingAudit.filters.workflowId'), value: d.workflow_id },
{ label: t('admin.shippingAudit.filters.workflowItemId'), value: d.workflow_item_id },
{ label: t('admin.shippingAudit.columns.run'), value: d.run_no },
{ label: t('admin.shippingAudit.filters.documentId'), value: d.document_id },
{ label: t('admin.shippingAudit.filters.reviewCaseNo'), value: d.review_case_no },
{ label: t('admin.shippingAudit.columns.task'), value: d.task_no },
{ label: t('admin.shippingAudit.filters.operationId'), value: d.operation_id },
{ label: t('admin.shippingAudit.filters.requestId'), value: d.request_id },
]
.map((item) => ({ label: item.label, value: String(item.value || '').trim() }))
.filter((item) => Boolean(item.value));
});
/**
* 关闭抽屉。
*/
@@ -51,34 +96,77 @@ function onClose() {
>
{{ 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 class="mt-5 grid grid-cols-1 gap-3 text-sm sm:grid-cols-2">
<div>
<dt class="text-xs text-muted">{{ t('admin.shippingAudit.columns.event') }}</dt>
<dd class="mt-0.5 font-medium" data-testid="shipping-audit-detail-event">
{{ label('eventTypes', detail.event_type) }}
</dd>
<dd class="text-xs text-muted">{{ label('actions', detail.action) }}</dd>
</div>
<div>
<dt class="text-xs text-muted">{{ t('admin.shippingAudit.columns.actor') }}</dt>
<dd class="mt-0.5" data-testid="shipping-audit-detail-actor">
{{ label('actorTypes', detail.actor_type) }}
<span v-if="detail.actor_id" class="text-muted"> · {{ t('admin.shippingAudit.copyId') }}</span>
</dd>
<button
v-if="detail.actor_id"
type="button"
class="mt-1 rounded border border-default px-2 py-0.5 font-mono text-[11px] text-muted"
:title="String(detail.actor_id)"
@click="copyTechId(detail.actor_id)"
>
{{ detail.actor_id }}
</button>
</div>
<div>
<dt class="text-xs text-muted">{{ t('admin.shippingAudit.columns.reasonCode') }}</dt>
<dd class="mt-0.5">{{ label('reasonCodes', detail.reason_code) }}</dd>
</div>
<div>
<dt class="text-xs text-muted">{{ t('admin.shippingAudit.columns.result') }}</dt>
<dd class="mt-0.5" data-testid="shipping-audit-detail-result">
{{ label('results', detail.result) }}
</dd>
</div>
</dl>
<section class="mt-5" data-testid="shipping-audit-detail-tech-refs">
<h3 class="text-sm font-semibold">{{ t('admin.shippingAudit.columns.refs') }}</h3>
<p class="mt-1 text-[11px] text-muted">{{ t('admin.shippingAudit.techRefsHint') }}</p>
<div v-if="techRefs.length" class="mt-2 flex flex-wrap gap-2">
<button
v-for="item in techRefs"
:key="`${item.label}-${item.value}`"
type="button"
class="rounded border border-default px-2 py-1 text-[11px] text-secondary"
:title="item.value"
@click="copyTechId(item.value)"
>
<span class="text-muted">{{ item.label }}</span>
· {{ t('admin.shippingAudit.copyId') }}
</button>
</div>
<p v-else class="mt-2 text-xs text-muted">—</p>
</section>
<details class="mt-5 rounded-lg border border-default p-3 text-xs">
<summary class="cursor-pointer font-medium text-secondary">
{{ t('admin.shippingAudit.hashSection') }}
</summary>
<dl class="mt-3 space-y-2">
<div>
<dt class="text-muted">{{ t('admin.shippingAudit.eventHash') }}</dt>
<dd class="break-all font-mono text-[10px]">{{ detail.event_hash || '—' }}</dd>
</div>
<div>
<dt class="text-muted">{{ t('admin.shippingAudit.previousEventHash') }}</dt>
<dd class="break-all font-mono text-[10px]">{{ detail.previous_event_hash || '—' }}</dd>
</div>
</dl>
</details>
<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
@@ -0,0 +1,40 @@
/**
* features/admin/modules/shipping-audit/shippingAuditDisplay.ts
* 用途:审计中心列表与详情共用的业务化标签解析。
* 依赖:vue-i18n Translator(te/t)。
* 逻辑:ShippingAuditCenterPage / ShippingAuditEventDetailDrawer 调用;
* 未知码回退通用业务文案,避免主界面直接堆叠内部事件码。
*/
export type ShippingAuditLabelKind =
| 'eventTypes'
| 'actions'
| 'reasonCodes'
| 'actorTypes'
| 'results';
export type ShippingAuditTranslate = {
t: (key: string) => string;
te: (key: string) => boolean;
};
/**
* 将审计事件/动作/原因/操作者/结果码转为业务化文案。
* @param i18n - vue-i18n te/t
* @param kind - 标签分类
* @param code - 原始稳定码
* @returns 业务文案;空码返回 —
*/
export function shippingAuditBusinessLabel(
i18n: ShippingAuditTranslate,
kind: ShippingAuditLabelKind,
code?: string | null,
): string {
const raw = String(code || '').trim();
if (!raw) return '—';
const key = `admin.shippingAudit.labels.${kind}.${raw}`;
if (i18n.te(key)) return i18n.t(key);
if (kind === 'actorTypes') return i18n.t('admin.shippingAudit.labels.actorTypes.unknown');
if (kind === 'results') return raw;
return i18n.t(`admin.shippingAudit.labels.${kind}.fallback`);
}
@@ -1024,6 +1024,8 @@ const save = async (automatic = false) => {
display_name: form.displayName,
schema_version_id: form.schemaId,
definition: definition(),
sample_document_id: form.documentId,
sample_table_id: form.tableId,
change_note: form.changeNote,
};
if (!existingProfile) throw new Error('A draft must be created by the wizard before editing.');
@@ -1751,9 +1753,16 @@ const edit = async (profile: ShippingOrderDocumentProfile) => {
}
try {
boundSamples.value = await listOrderProfileBoundSamples(profile.id);
form.documentId =
boundSamples.value.find((item) => item.sample_role === "annotation")?.document_id || 0;
const annotationSample = boundSamples.value.find((item) => item.sample_role === "annotation") || null;
form.documentId = annotationSample?.document_id || 0;
await loadSampleTables();
// Restore the exact bound physical table instead of defaulting to the
// first parsed table; otherwise detail recognition may target the wrong
// page after returning from validation.
if (annotationSample?.table_id && sampleTables.value.some((item) => item.table_id === annotationSample.table_id)) {
form.tableId = annotationSample.table_id;
pageNo.value = sampleTables.value.find((item) => item.table_id === annotationSample.table_id)?.page_no || pageNo.value;
}
await loadPages();
} catch (error) {
fail(error);
@@ -1762,10 +1771,26 @@ const edit = async (profile: ShippingOrderDocumentProfile) => {
// Page preview grants are independent from coordinate extraction. A grant
// failure must not leave the right-hand recognition panel at "waiting".
await refreshOrderFieldSuggestionValues();
// Restoring a draft suppresses the table watcher; explicitly re-read the
// current table so detail rows are visible immediately after returning.
schedulePreview();
}
};
/** 跳转到独立验证页;页面仍需当前标签持有租约,不能绕过草稿单写者保护。 */
const validateProfile = async (profile: ShippingOrderDocumentProfile) => {
// Flush pending autosave/local edits before validation; otherwise the
// validation page may validate the previous immutable draft revision.
if (autosaveTimer) {
window.clearTimeout(autosaveTimer);
autosaveTimer = null;
}
if (saving.value) {
for (let attempt = 0; attempt < 100 && saving.value; attempt += 1) {
await new Promise<void>((resolve) => window.setTimeout(resolve, 50));
}
}
if (dirty.value) await save();
if (dirty.value || saving.value || saveState.value === 'failed' || saveState.value === 'readonly') return;
await router.push({
name: "AdminShippingOrderDocumentProfileValidate",
params: { profileCode: profile.profile_code, profileId: String(profile.id) },
@@ -143,12 +143,19 @@ async function ensureLease(): Promise<boolean> {
/** 依次执行配置结构和当前样本试读;任一步失败均不允许进入发布检查。 */
async function validateCurrentDraft(): Promise<void> {
if (!(await ensureLease())) return;
if (!sample.value?.id) {
message.error(t('admin.orderProfileValidation.noTrainingSample'));
return;
}
executing.value = true;
try {
const payload = () => ({ browser_session_id: sessionId, lease_token: leaseToken.value, operation_id: crypto.randomUUID() });
await runOrderProfileInstantCheck(profileId, payload());
await runOrderProfileCurrentSample(profileId, payload());
await runOrderProfileCurrentSample(profileId, { ...payload(), sample_binding_id: sample.value.id });
await loadRuns();
// Refresh the draft/sample context after validation so the result preview
// uses the same binding and definition that the server just validated.
await loadContext();
await loadBlindTestSuite();
await loadReadResults();
message.success(t('admin.orderProfileValidation.completed'));
@@ -516,6 +516,7 @@ export interface CoordinateReconstructionPreview {
table_id: string;
row_count: number;
column_count: number;
field_codes: string[];
rows: string[][];
row_roles: Array<'header' | 'data' | 'deleted'>;
source_row_indices: number[][];
+227 -2
View File
@@ -30,9 +30,15 @@ import type {
ShippingOrderExtractionProgressEvent,
ShippingOrderExtractionRunCreateResponse,
ShippingOrderReviewCase,
ShippingOrderReviewCustomerResolution,
ShippingOrderReviewDuplicate,
ShippingOrderReviewFieldConflict,
ShippingDuplicateAction,
ShippingOrderReviewDraftWrite,
ShippingOrderReviewEvidence,
ShippingOrderReviewInventoryCandidatesWrite,
ShippingOrderReviewInventoryRoutingDecisionWrite,
ShippingOrderReviewInventoryRoutingRerouteWrite,
ShippingOrderReviewLlmAdjudicationPayload,
ShippingOrderReviewLlmSuggestion,
ShippingOrderReviewLlmSuggestionRequest,
@@ -311,7 +317,159 @@ export const putWorkspaceShippingOrderReviewInventoryCandidates = (
{ method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) },
);
/** 确认当前 PDF 的已校验草稿;服务端以版本和幂等键确保只创建一张 Task。 */
/**
* 重新匹配整单或指定明细的库存路由规则。
* 核心逻辑:携带 expected_draft_version 与幂等键;可选 line_key 限定单行。
* @param caseNo - 复核 Case 编号
* @param payload - 版本锁、幂等键与可选行键
*/
export const postWorkspaceShippingOrderReviewInventoryRoutingReroute = (
caseNo: string,
payload: ShippingOrderReviewInventoryRoutingRerouteWrite,
) => requestJson<ShippingOrderReviewCase>(
`/api/workspace/shipping-notice/order-review-cases/${encodeURIComponent(caseNo)}/draft/inventory-routing/reroute`,
{ method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) },
);
/**
* 采纳行级规则建议为有效库存源候选。
* 核心逻辑:清除 suggestion_pending;服务端写入后重跑建单资格。
* @param caseNo - 复核 Case 编号
* @param lineKey - Draft 行稳定标识
* @param payload - 版本锁、幂等键与可选原因
*/
export const postWorkspaceShippingOrderReviewInventoryRoutingAdoptSuggestion = (
caseNo: string,
lineKey: string,
payload: ShippingOrderReviewInventoryRoutingDecisionWrite,
) => requestJson<ShippingOrderReviewCase>(
`/api/workspace/shipping-notice/order-review-cases/${encodeURIComponent(caseNo)}/draft/lines/${encodeURIComponent(lineKey)}/inventory-routing/adopt-suggestion`,
{ method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) },
);
/**
* 保留当前人工库存路由结果并忽略待决规则建议。
* 核心逻辑:清除 suggestion_pending;不覆盖已选人工候选。
* @param caseNo - 复核 Case 编号
* @param lineKey - Draft 行稳定标识
* @param payload - 版本锁、幂等键与可选原因
*/
export const postWorkspaceShippingOrderReviewInventoryRoutingKeepManual = (
caseNo: string,
lineKey: string,
payload: ShippingOrderReviewInventoryRoutingDecisionWrite,
) => requestJson<ShippingOrderReviewCase>(
`/api/workspace/shipping-notice/order-review-cases/${encodeURIComponent(caseNo)}/draft/lines/${encodeURIComponent(lineKey)}/inventory-routing/keep-manual`,
{ method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) },
);
/**
* 复核工作台重新识别客户(不重解析 PDF)。
*/
export const retryWorkspaceShippingOrderReviewCustomerResolution = (caseNo: string) =>
requestJson<{
case: ShippingOrderReviewCase;
customer_resolution: ShippingOrderReviewCustomerResolution;
}>(
`/api/workspace/shipping-notice/order-review-cases/${encodeURIComponent(caseNo)}/customer-resolution/retry`,
{ method: 'POST' },
);
/**
* 建单前确认标准客户,并刷新建单资格。
*/
export const confirmWorkspaceShippingOrderReviewCustomer = (
caseNo: string,
payload: { customer_id: number; reason?: string },
) => requestJson<{
case: ShippingOrderReviewCase;
customer_resolution: ShippingOrderReviewCustomerResolution;
}>(
`/api/workspace/shipping-notice/order-review-cases/${encodeURIComponent(caseNo)}/customer-resolution/confirm`,
{
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload),
},
);
/**
* 重新检测建单前重复订单。
*/
export const refreshWorkspaceShippingOrderReviewDuplicate = (caseNo: string) =>
requestJson<{
case: ShippingOrderReviewCase;
duplicate: ShippingOrderReviewDuplicate;
}>(
`/api/workspace/shipping-notice/order-review-cases/${encodeURIComponent(caseNo)}/duplicate-refresh`,
{ method: 'POST' },
);
/**
* 裁决建单前重复订单。
*/
export const resolveWorkspaceShippingOrderReviewDuplicate = (
caseNo: string,
payload: {
action: ShippingDuplicateAction;
target_task_no?: string;
reason?: string;
},
) => requestJson<{
case: ShippingOrderReviewCase;
duplicate: ShippingOrderReviewDuplicate;
}>(
`/api/workspace/shipping-notice/order-review-cases/${encodeURIComponent(caseNo)}/duplicate-resolution`,
{
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload),
},
);
/**
* 列出建单前字段冲突(可选;Case GET 已内嵌 field_conflicts)。
*/
export const listWorkspaceShippingOrderReviewFieldConflicts = (caseNo: string) =>
requestJson<{
case_no: string;
draft_version: number | null;
items: ShippingOrderReviewFieldConflict[];
open_count: number;
case: ShippingOrderReviewCase;
}>(
`/api/workspace/shipping-notice/order-review-cases/${encodeURIComponent(caseNo)}/field-conflicts`,
);
/**
* 裁决建单前字段冲突:写入 Draft 并清除 Candidate 冲突项。
*/
export const resolveWorkspaceShippingOrderReviewFieldConflict = (
caseNo: string,
conflictKey: string,
payload: {
resolution: 'adopt_option' | 'custom';
option_index?: number;
custom_value?: unknown;
expected_draft_version: number;
reason?: string;
},
) => requestJson<{
case: ShippingOrderReviewCase;
field_conflicts: ShippingOrderReviewFieldConflict[];
}>(
`/api/workspace/shipping-notice/order-review-cases/${encodeURIComponent(caseNo)}/field-conflicts/${encodeURIComponent(conflictKey)}/resolve`,
{
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload),
},
);
/**
* 确认当前 PDF 的已校验草稿;服务端以版本和幂等键确保只创建一张 Task。
* 调用方须用 parseOrderReviewConfirmResponse 解析 data,不可仅凭 HTTP 200 或 success 判定推进结果。
*/
export const confirmWorkspaceShippingOrderReviewCase = (
caseNo: string,
payload: { expected_draft_version: number; idempotency_key: string; warning_acknowledgements?: Array<{ code: string; comment?: string }> },
@@ -320,6 +478,11 @@ export const confirmWorkspaceShippingOrderReviewCase = (
{ method: 'POST', headers: { 'Content-Type': 'application/json', 'Idempotency-Key': payload.idempotency_key }, body: JSON.stringify(payload) },
);
/** 复核确认响应统一解析(建单成功 ≠ 自动推进成功)。 */
export { parseOrderReviewConfirmResponse } from '../shipping-review/parseOrderReviewConfirmResponse';
export type { ParsedOrderReviewConfirmResult } from '../shipping-review/parseOrderReviewConfirmResponse';
// ShippingOrderReviewConfirmOutcome 仅从 types/shipping.api.types 导出,避免 index 双出口冲突。
/** 启用无机器订单 PDF 的唯一人工草稿;不创建第二个订单对象。 */
export const createWorkspaceShippingOrderReviewManualDraft = (caseNo: string, comment?: string) =>
requestJson<ShippingOrderReviewCase>(
@@ -362,12 +525,60 @@ export const createWorkspaceShippingOrderReviewReplacementRun = (caseNo: string,
jsonPost({ intake_no: intakeNo }),
);
/** 获取复核字段的安全证据摘要;PDF 二进制继续由受控同源预览接口提供。 */
/**
* 获取复核字段的安全证据摘要(含 highlight_quality / highlight_bbox 契约字段)。
* PDF 二进制继续由受控同源预览接口提供;坐标缺失不影响字段值。
*/
export const getWorkspaceShippingOrderReviewEvidence = (caseNo: string) =>
requestJson<{ case_no: string; items: ShippingOrderReviewEvidence[] }>(
`/api/workspace/shipping-notice/order-review-cases/${encodeURIComponent(caseNo)}/evidence`,
);
/**
* 读取单条字段证据并触发 review_evidence_focused 访问审计。
* 用途:定位原文时调用,证明用户实际查看了该字段证据;失败不阻断 UI。
*/
export const getWorkspaceShippingOrderReviewEvidenceItem = (caseNo: string, evidenceId: string) =>
requestJson<ShippingOrderReviewEvidence>(
`/api/workspace/shipping-notice/order-review-cases/${encodeURIComponent(caseNo)}/evidence/${encodeURIComponent(evidenceId)}`,
);
/**
* 记录坐标诊断面板查看审计(不改变业务状态,不返回 PDF 正文)。
*/
export const viewWorkspaceShippingOrderReviewHighlightDiagnostic = (caseNo: string, evidenceId: string) =>
requestJson<{ case_no: string; highlight: Record<string, unknown> }>(
`/api/workspace/shipping-notice/order-review-cases/${encodeURIComponent(caseNo)}/evidence/${encodeURIComponent(evidenceId)}/highlight-diagnostic`,
jsonPost({}),
);
/**
* 记录字段「定位原文」点击审计(含无 evidence 的红色诊断入口)。
* 失败不阻断 UI;不返回 PDF 正文。
*/
export const attemptWorkspaceShippingOrderReviewFieldLocate = (
caseNo: string,
body: {
field_id: string;
line_index?: number | null;
highlight_quality: string;
has_evidence: boolean;
evidence_id?: string | null;
pdf_located: boolean;
coordinate_issue_codes?: string[];
},
) =>
requestJson<{
case_no: string;
field_id: string;
highlight_quality: string;
has_evidence: boolean;
pdf_located: boolean;
}>(
`/api/workspace/shipping-notice/order-review-cases/${encodeURIComponent(caseNo)}/field-locate`,
jsonPost(body),
);
/** 列出 Case 下 LLM 证据建议记录。 */
export const listWorkspaceShippingOrderReviewLlmSuggestions = (caseNo: string) =>
requestJson<{ case_no: string; llm_review_enabled: boolean; items: ShippingOrderReviewLlmSuggestion[] }>(
@@ -395,6 +606,20 @@ export const adjudicateWorkspaceShippingOrderReviewLlmSuggestion = (
jsonPost(body),
);
/** 打开版本历史抽屉时写入服务端访问审计(失败不阻断 UI)。 */
export const auditWorkspaceShippingOrderReviewVersionHistory = (caseNo: string) =>
requestJson<{ audited: boolean; case_no: string }>(
`/api/workspace/shipping-notice/order-review-cases/${encodeURIComponent(caseNo)}/access/version-history`,
jsonPost(),
);
/** 打开完整建单检查抽屉时写入服务端访问审计(失败不阻断 UI)。 */
export const auditWorkspaceShippingOrderReviewEligibilityDetails = (caseNo: string) =>
requestJson<{ audited: boolean; case_no: string }>(
`/api/workspace/shipping-notice/order-review-cases/${encodeURIComponent(caseNo)}/access/eligibility-details`,
jsonPost(),
);
/** 以认证请求取得 PDF Blob,避免 iframe 无法携带 JWT 而退化为公开预览 URL。 */
export async function getWorkspaceShippingOrderReviewPreview(caseNo: string): Promise<Blob> {
const response = await fetch(
@@ -7,13 +7,14 @@
* 依赖:ChatSidebar、ChatMessageList、ChatInputBar、ShippingWorkflowTimeline、chat.context。
* 逻辑:本文件只做页面结构编排;货代 Chat 仅上传/进度通知,履约写操作不在本页;
* 右侧「本次处理」由 conversationId 驱动 Workflow projection,extractionRunNo 仅作进度装饰。
* 右侧「本次处理」由 conversationId 驱动 Workflow projection,extractionRunNo 仅作进度装饰;
* 订单复核工作台异步分包,避免普通对话首屏拉取 PDF.js。
*/
<script setup lang="ts">
import { computed, provide, ref, watch } from 'vue';
import { computed, defineAsyncComponent, provide, ref, watch } from 'vue';
import { useRoute } from 'vue-router';
@@ -39,8 +40,6 @@ import LedgerConfigPanel from '@/features/maintenance/components/LedgerConfigPan
import MaintenanceRecordManagerPanel from '@/features/maintenance/components/MaintenanceRecordManagerPanel.vue';
import ShippingOrderReviewView from '@/features/chat/views/ShippingOrderReviewView.vue';
import { useChatPageContext } from '@/features/chat/composables/chat.context';
import { matchesTrainingAgent } from '@/features/chat/training/trainingWorkspace.utils';
@@ -66,7 +65,10 @@ import {
} from '@/features/maintenance/utils/maintenance-panel-layout.utils';
/** 复核工作台按需分包:仅 order-review 模式加载,避免 Chat 首屏带上 PDF.js。 */
const ShippingOrderReviewView = defineAsyncComponent(
() => import('@/features/chat/views/ShippingOrderReviewView.vue'),
);
type MaintenanceRecordPanelCommand = {
@@ -0,0 +1,124 @@
<!--
features/chat/components/shipping-review/ReviewBuildEligibilityDetailsDrawer.vue
用途:完整建单检查项抽屉(逐行投影、阻断原因)。
依赖:vue-i18n、ShippingOrderReviewBuildEligibility。
逻辑:仅在用户主动展开时挂载;关闭不写服务端审计(敏感访问审计由阶段 5 统一补齐)。
-->
<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<{
open: boolean;
eligibility: ShippingOrderReviewBuildEligibility | null;
}>();
const emit = defineEmits<{
close: [];
'focus-line': [lineIndex: number];
}>();
const { t, te } = useI18n();
/**
* 解析行级阻断原因文案。
*/
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) : t('chat.shippingOrderReview.buildEligibility.blockReasons.unknown');
}
/**
* 解析路由状态文案。
*/
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) : t('chat.shippingOrderReview.buildEligibility.routingStatus.unknown');
}
/** 异常行置顶,已通过行排后。 */
const orderedLines = computed(() => {
const lines = [...(props.eligibility?.line_projections || [])];
return lines.sort((a, b) => {
const aBlocked = a.can_build === false ? 0 : 1;
const bBlocked = b.can_build === false ? 0 : 1;
if (aBlocked !== bBlocked) return aBlocked - bBlocked;
return (a.line_index ?? 0) - (b.line_index ?? 0);
});
});
</script>
<template>
<div
v-if="open && eligibility"
class="fixed inset-0 z-40 flex justify-end bg-slate-900/30"
data-testid="review-eligibility-details-drawer"
@click.self="emit('close')"
>
<aside class="flex h-full w-full max-w-md flex-col bg-white shadow-xl dark:bg-slate-900">
<header class="flex items-center justify-between gap-2 border-b border-slate-200 px-4 py-3 dark:border-slate-800">
<h2 class="text-sm font-semibold">{{ t('chat.shippingOrderReview.workbench.fullChecksTitle') }}</h2>
<button
type="button"
class="rounded border border-slate-300 px-2 py-1 text-xs hover:bg-slate-50 dark:border-slate-600 dark:hover:bg-slate-800"
data-testid="review-eligibility-details-close"
@click="emit('close')"
>
{{ t('chat.shippingOrderReview.workbench.closePdf') }}
</button>
</header>
<div class="min-h-0 flex-1 space-y-2 overflow-y-auto p-4">
<article
v-for="line in orderedLines"
: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-eligibility-detail-line-${line.line_key || line.line_index}`"
>
<div class="flex flex-wrap items-center justify-between gap-2">
<button
type="button"
class="font-medium text-sky-700 hover:underline dark:text-sky-300"
@click="emit('focus-line', Number(line.line_index ?? 0))"
>
{{ t('chat.shippingOrderReview.line', { index: (line.line_index ?? 0) + 1 }) }}
</button>
<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">
<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.block_reason">
<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.candidate_inventory_source_codes?.length">
<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>
</dl>
</article>
<p v-if="!orderedLines.length" class="text-xs text-slate-500">
{{ t('chat.shippingOrderReview.workbench.noLineChecks') }}
</p>
</div>
</aside>
</div>
</template>
@@ -1,8 +1,9 @@
<!--
features/chat/components/shipping-review/ReviewBuildEligibilityPanel.vue
用途:展示建单前资格摘要(can_build、阻断原因、行级 Reservation 与库存候选)及 Gate 恢复卡片。
用途:完整建单资格面板(含逐行投影);布局重构后标准侧栏改用 Summary + DetailsDrawer。
依赖:vue-i18n、ProcessGateRecoveryCard、ShippingOrderReviewBuildEligibility 类型。
逻辑:ShippingOrderReviewView 传入 draft.build_eligibility 与 case.process_gate;只读展示资格,Gate 动作可导航/POST。
逻辑:仍可供需要完整展开的入口复用;标准复核主路径不再默认挂载本组件;
confirm_customer 向上转发,由对话页打开客户选择弹窗。
-->
<script setup lang="ts">
import { computed } from 'vue';
@@ -23,6 +24,7 @@ const props = defineProps<{
const emit = defineEmits<{
gateRefreshed: [];
confirmCustomer: [taskNo: string];
}>();
const { t, te } = useI18n();
@@ -81,6 +83,7 @@ const blockingSummary = computed(() => {
:navigation-context="navigationContext"
@refreshed="emit('gateRefreshed')"
@refresh-needed="emit('gateRefreshed')"
@confirm-customer="(taskNo) => emit('confirmCustomer', taskNo)"
/>
<section
v-if="eligibility"
@@ -0,0 +1,69 @@
/**
* features/chat/components/shipping-review/ReviewBuildEligibilitySummary.spec.ts
* 用途:锁定建单资格摘要卡默认只展示阻断摘要、完整检查按需展开契约。
* 依赖:vitest、@vue/test-utils、vue-i18n。
* 逻辑:验证 badge、首要阻断与 open-details emit;不渲染逐行投影列表。
*/
import { describe, expect, it } from 'vitest';
import { mount } from '@vue/test-utils';
import { createI18n } from 'vue-i18n';
import ReviewBuildEligibilitySummary from './ReviewBuildEligibilitySummary.vue';
import type { ShippingOrderReviewBuildEligibility } from '@/features/chat/types/shipping.api.types';
/**
* 挂载摘要卡。
*/
function mountSummary(eligibility: ShippingOrderReviewBuildEligibility) {
const i18n = createI18n({
legacy: false,
locale: 'zh-CN',
messages: {
'zh-CN': {
chat: {
shippingOrderReview: {
issueCodes: { unknown: '未知问题' },
buildEligibility: {
title: '订单检查',
canBuildYes: '可建单',
canBuildNo: '待处理',
blockReasons: { require_manual_review: '需人工确认', unknown: '未知阻断' },
},
workbench: {
primaryBlock: '首要阻断原因',
blockCount: '阻断项 {count} 项',
viewFullChecks: '查看完整检查',
},
},
},
},
},
});
return mount(ReviewBuildEligibilitySummary, {
props: { eligibility },
global: { plugins: [i18n] },
});
}
describe('ReviewBuildEligibilitySummary', () => {
it('shows primary block and emits open-details without listing all lines', async () => {
const wrapper = mountSummary({
can_build: false,
status: 'blocked',
issues: [{
code: 'require_manual_review',
severity: 'blocking',
explainability: { message: '第 2 行库存来源待确认' },
}],
line_projections: [
{ line_key: 'L1', line_index: 0, can_build: true },
{ line_key: 'L2', line_index: 1, can_build: false, block_reason: 'require_manual_review' },
],
});
expect(wrapper.find('[data-testid="review-build-eligibility-summary"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="review-build-eligibility-badge"]').text()).toContain('待处理');
expect(wrapper.find('[data-testid="review-eligibility-primary-block"]').text()).toContain('第 2 行库存来源待确认');
expect(wrapper.text()).not.toContain('L1');
await wrapper.find('[data-testid="review-open-eligibility-details"]').trigger('click');
expect(wrapper.emitted('open-details')).toBeTruthy();
});
});
@@ -0,0 +1,146 @@
<!--
features/chat/components/shipping-review/ReviewBuildEligibilitySummary.vue
用途:复核摘要侧栏的建单资格压缩卡(可建单状态、门禁清单、首要阻断)。
依赖:vue-i18n、ShippingOrderReviewBuildEligibility。
逻辑:展示客户确认等关键门禁勾选;「查看完整检查」emit open-details;完整逐行结果不常驻。
-->
<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 emit = defineEmits<{
'open-details': [];
}>();
const { t, te } = useI18n();
/** 用户可见的关键建单前门禁(与后端 qualification gates 对齐)。 */
const CHECKLIST_GATES = [
'customer_confirmed',
'required_fields_complete',
'evidence_complete',
'duplicate_resolved',
'field_conflicts_resolved',
] as const;
/** 阻断 issue 数量(优先 blocking severity)。 */
const blockingIssueCount = computed(() => {
const issues = props.eligibility?.issues || [];
const blocking = issues.filter((item) => String(item.severity || '') === 'blocking');
return blocking.length || issues.length;
});
/** 首要阻断文案。 */
const primaryBlockMessage = computed(() => {
const issues = props.eligibility?.issues || [];
const primary = issues.find((item) => String(item.severity || '') === 'blocking') || issues[0];
if (!primary) {
const blockedLines = (props.eligibility?.line_projections || []).filter((line) => line.can_build === false);
if (!blockedLines.length) return '';
const reason = String(blockedLines[0]?.block_reason || '').trim();
const key = `chat.shippingOrderReview.buildEligibility.blockReasons.${reason}`;
return reason && te(key) ? t(key) : t('chat.shippingOrderReview.buildEligibility.blockReasons.unknown');
}
const message = String(primary.explainability?.message || primary.message || '').trim();
if (message) return message;
const code = String(primary.code || '').trim();
const key = `chat.shippingOrderReview.issueCodes.${code}`;
return code && te(key) ? t(key) : t('chat.shippingOrderReview.issueCodes.unknown');
});
/** 不可建单的行数。 */
const blockedLineCount = computed(() =>
(props.eligibility?.line_projections || []).filter((line) => line.can_build === false).length,
);
/**
* 门禁勾选列表:优先 gates 映射;客户未确认时强制展示失败项。
*/
const gateChecklist = computed(() => {
const gates = props.eligibility?.gates || {};
const failed = new Set((props.eligibility?.failed_gates || []).map(String));
const issues = props.eligibility?.issues || [];
const customerIssue = issues.some((item) => String(item.code || '').startsWith('customer_'));
return CHECKLIST_GATES.map((gate) => {
const known = Object.prototype.hasOwnProperty.call(gates, gate);
let passed = known ? Boolean(gates[gate]) : !failed.has(gate);
if (gate === 'customer_confirmed' && customerIssue) passed = false;
const labelKey = `chat.shippingOrderReview.buildEligibility.gates.${gate}`;
return {
gate,
passed,
label: te(labelKey) ? t(labelKey) : gate,
};
}).filter((item) => Object.keys(gates).length === 0 || Object.prototype.hasOwnProperty.call(gates, item.gate) || item.gate === 'customer_confirmed');
});
</script>
<template>
<section
v-if="eligibility"
class="rounded-xl border border-slate-200 bg-white p-3 shadow-sm dark:border-slate-800 dark:bg-slate-900"
data-testid="review-build-eligibility-summary"
>
<header class="flex flex-wrap items-center justify-between gap-2">
<h2 class="text-sm font-semibold">{{ t('chat.shippingOrderReview.buildEligibility.title') }}</h2>
<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>
<ul
v-if="gateChecklist.length"
class="mt-2 space-y-1 text-xs"
data-testid="review-eligibility-gate-checklist"
>
<li
v-for="item in gateChecklist"
:key="item.gate"
class="flex items-center gap-2"
>
<span :class="item.passed ? 'text-emerald-600' : 'text-rose-600'">{{ item.passed ? '✓' : '×' }}</span>
<span :class="item.passed ? 'text-secondary' : 'font-medium text-rose-700 dark:text-rose-300'">
{{ item.label }}
</span>
</li>
</ul>
<div
v-if="!eligibility.can_build && primaryBlockMessage"
class="mt-2 rounded-lg border border-amber-200 bg-amber-50 px-2.5 py-2 text-xs text-amber-950 dark:border-amber-900 dark:bg-amber-950/30 dark:text-amber-100"
data-testid="review-eligibility-primary-block"
>
<div class="font-semibold">{{ t('chat.shippingOrderReview.workbench.primaryBlock') }}</div>
<p class="mt-0.5">{{ primaryBlockMessage }}</p>
<p v-if="blockingIssueCount || blockedLineCount" class="mt-1 text-[11px] opacity-80">
{{ t('chat.shippingOrderReview.workbench.blockCount', {
count: Math.max(blockingIssueCount, blockedLineCount),
}) }}
</p>
</div>
<button
type="button"
class="mt-2 w-full rounded border border-slate-300 px-2 py-1.5 text-xs hover:bg-slate-50 dark:border-slate-600 dark:hover:bg-slate-800"
data-testid="review-open-eligibility-details"
@click="emit('open-details')"
>
{{ t('chat.shippingOrderReview.workbench.viewFullChecks') }}
</button>
</section>
</template>
@@ -0,0 +1,200 @@
<!--
features/chat/components/shipping-review/ReviewCustomerResolutionPanel.vue
用途:复核工作台固定「建单前客户确认」区域(与重新识别 PDF 分层)。
依赖:vue-i18n、ShippingCustomerConfirmDialog、shipping.api 客户确认/重识别接口。
逻辑:始终展示客户识别状态;选择标准客户 / 重新识别客户;成功后 emit refreshed 刷新建单资格。
-->
<script setup lang="ts">
import { computed, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { BusinessError, resolveLocalizedErrorMessage } from '@/shared/api/client';
import { useMessage } from '@/shared/composables/useMessage';
import ShippingCustomerConfirmDialog from '@/features/chat/components/ShippingCustomerConfirmDialog.vue';
import {
confirmWorkspaceShippingOrderReviewCustomer,
listWorkspaceShippingCustomerOptions,
retryWorkspaceShippingOrderReviewCustomerResolution,
} from '@/features/chat/api/shipping.api';
import type {
ShippingCustomerOption,
ShippingOrderReviewCustomerResolution,
} from '@/features/chat/types/shipping.api.types';
const props = defineProps<{
caseNo: string;
resolution: ShippingOrderReviewCustomerResolution | null | undefined;
editable: boolean;
}>();
const emit = defineEmits<{
refreshed: [];
}>();
const { t, te } = useI18n();
const msg = useMessage();
const busy = ref(false);
const dialogOpen = ref(false);
const options = ref<ShippingCustomerOption[]>([]);
const loadingOptions = ref(false);
const resolved = computed(() => Boolean(props.resolution?.resolved));
const statusLabel = computed(() => {
const status = String(props.resolution?.status || '').trim();
if (!status) {
return resolved.value
? t('chat.shippingOrderReview.customerResolution.status.confirmed')
: t('chat.shippingOrderReview.customerResolution.status.unmatched');
}
const key = `chat.shippingOrderReview.customerResolution.status.${status}`;
return te(key) ? t(key) : status;
});
const displayName = computed(() => {
const name = String(props.resolution?.standard_name || '').trim();
const code = String(props.resolution?.short_code || '').trim();
if (name && code) return `${name} (${code})`;
return name || code || String(props.resolution?.raw_name || '').trim() || '—';
});
/**
* 打开标准客户选择弹窗并加载选项。
*/
async function openSelectDialog() {
if (!props.editable || busy.value) return;
dialogOpen.value = true;
loadingOptions.value = true;
try {
options.value = await listWorkspaceShippingCustomerOptions();
} catch (error: unknown) {
options.value = [];
msg.warning(error instanceof Error ? error.message : t('chat.shippingCustomer.loadFailed'));
} finally {
loadingOptions.value = false;
}
}
/**
* 按关键词搜索标准客户。
*/
async function searchCustomers(query: string) {
loadingOptions.value = true;
try {
options.value = await listWorkspaceShippingCustomerOptions(query.trim());
} catch (error: unknown) {
msg.warning(error instanceof Error ? error.message : t('chat.shippingCustomer.loadFailed'));
} finally {
loadingOptions.value = false;
}
}
/**
* 确认标准客户并通知父级刷新 Case / 建单资格。
*/
async function onConfirm(customerId: number) {
if (!props.caseNo || busy.value) return;
busy.value = true;
try {
await confirmWorkspaceShippingOrderReviewCustomer(props.caseNo, {
customer_id: customerId,
reason: t('chat.shippingOrderReview.customerResolution.confirmReason'),
});
dialogOpen.value = false;
msg.success(t('chat.shippingOrderReview.customerResolution.confirmed'));
emit('refreshed');
} catch (error: unknown) {
const message = error instanceof BusinessError
? resolveLocalizedErrorMessage(error.code, error.message)
: (error instanceof Error ? error.message : t('chat.shippingCustomer.confirmFailed'));
msg.warning(message);
} finally {
busy.value = false;
}
}
/**
* 重新识别客户(不触发 PDF 重识别)。
*/
async function onRetry() {
if (!props.caseNo || !props.editable || busy.value) return;
busy.value = true;
try {
await retryWorkspaceShippingOrderReviewCustomerResolution(props.caseNo);
msg.success(t('chat.shippingOrderReview.customerResolution.retryDone'));
emit('refreshed');
} catch (error: unknown) {
const message = error instanceof BusinessError
? resolveLocalizedErrorMessage(error.code, error.message)
: (error instanceof Error ? error.message : t('chat.shippingOrderReview.customerResolution.retryFailed'));
msg.warning(message);
} finally {
busy.value = false;
}
}
</script>
<template>
<section
class="rounded-xl border border-slate-200 bg-white p-3 shadow-sm dark:border-slate-800 dark:bg-slate-900"
data-testid="review-customer-resolution-panel"
>
<header class="flex flex-wrap items-start justify-between gap-2">
<div>
<h2 class="text-sm font-semibold">{{ t('chat.shippingOrderReview.customerResolution.title') }}</h2>
<p class="mt-0.5 text-xs text-muted">{{ t('chat.shippingOrderReview.customerResolution.subtitle') }}</p>
</div>
<span
class="rounded-full px-2.5 py-1 text-xs font-medium"
:class="resolved
? '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-customer-resolution-badge"
>
{{ statusLabel }}
</span>
</header>
<dl class="mt-2 space-y-1 text-xs text-secondary">
<div class="flex flex-wrap gap-x-2">
<dt class="text-muted">{{ t('chat.shippingOrderReview.customerResolution.recognizedAs') }}</dt>
<dd class="font-medium text-primary">{{ displayName }}</dd>
</div>
<div v-if="resolution?.raw_name && resolution.raw_name !== displayName" class="flex flex-wrap gap-x-2">
<dt class="text-muted">{{ t('chat.shippingOrderReview.customerResolution.rawName') }}</dt>
<dd>{{ resolution.raw_name }}</dd>
</div>
</dl>
<div v-if="editable" class="mt-3 flex flex-wrap gap-2">
<button
type="button"
class="rounded-xl bg-primary px-3 py-1.5 text-sm font-medium text-on-primary disabled:opacity-60"
data-testid="review-select-customer"
:disabled="busy"
@click="openSelectDialog"
>
{{ t('chat.shippingOrderReview.customerResolution.selectCustomer') }}
</button>
<button
type="button"
class="rounded-xl border border-default bg-surface px-3 py-1.5 text-sm text-secondary hover:bg-surface-soft disabled:opacity-60"
data-testid="review-retry-customer"
:disabled="busy"
@click="onRetry"
>
{{ busy ? t('chat.shippingOrderReview.customerResolution.retrying') : t('chat.shippingOrderReview.customerResolution.retryCustomer') }}
</button>
</div>
<p class="mt-2 text-[11px] text-muted">
{{ t('chat.shippingOrderReview.customerResolution.pdfReparseHint') }}
</p>
<ShippingCustomerConfirmDialog
:open="dialogOpen"
:options="options"
:loading="loadingOptions || busy"
@close="dialogOpen = false"
@search="searchCustomers"
@confirm="onConfirm"
/>
</section>
</template>
@@ -0,0 +1,253 @@
/**
* features/chat/components/shipping-review/ReviewDocumentEvidenceDrawer.spec.ts
* 用途:锁定 PDF 证据浮窗/侧栏的打开、导航、展开/固定、resize 句柄与无 bbox 引文展示契约。
* 依赖:vitest、@vue/test-utils、vue-i18n。
* 逻辑:验证上一/下一证据、关闭/展开/固定 emit、「更多」内退出后保留、八向 resize,以及无 bbox 时展示引文。
*/
import { afterEach, describe, expect, it, vi } from 'vitest';
import { flushPromises, mount } from '@vue/test-utils';
import { createI18n } from 'vue-i18n';
import ReviewDocumentEvidenceDrawer from './ReviewDocumentEvidenceDrawer.vue';
import type { ShippingOrderReviewEvidence } from '@/features/chat/types/shipping.api.types';
vi.mock('./ReviewDocumentPreview.vue', () => ({
default: {
name: 'ReviewDocumentPreview',
template: '<div data-testid="mock-pdf-preview" />',
},
}));
const evidenceList: ShippingOrderReviewEvidence[] = [
{
evidence_id: 'ev-1',
field_id: 'fld-po',
page_no: 1,
quote: 'PO-A',
bbox: { x0: 0.1, y0: 0.1, x1: 0.2, y1: 0.2 },
source: 'document_cell',
highlight_quality: 'candidate',
highlight_source: 'pdf_coordinate',
highlight_bbox: { x0: 0.1, y0: 0.1, x1: 0.2, y1: 0.2 },
coordinate_status: 'candidate',
coordinate_issue_codes: [],
evidence_ref: null,
token_ids: [],
value_match_status: 'matched',
},
{
evidence_id: 'ev-2',
field_id: 'fld-qty',
line_index: 0,
page_no: 2,
quote: '10 EA',
bbox: null,
source: 'document_cell',
highlight_quality: 'unavailable',
highlight_source: 'machine_extraction',
highlight_bbox: null,
coordinate_status: 'unavailable',
coordinate_issue_codes: ['coordinate_missing'],
evidence_ref: null,
token_ids: [],
value_match_status: 'matched',
},
];
/**
* 挂载证据抽屉。
*/
function mountDrawer(overrides: Record<string, unknown> = {}) {
const i18n = createI18n({
legacy: false,
locale: 'zh-CN',
messages: {
'zh-CN': {
chat: {
shippingOrderReview: {
previewTitle: 'PDF',
previewLoading: '加载',
previewUnavailable: '不可用',
emptyValue: '空',
evidenceAt: '第 {page} 页',
evidenceNoHighlight: '无坐标高亮',
evidenceInvalidHighlight: '坐标无效',
locateUnavailableHint: '无可靠坐标',
restoreMachine: '恢复机器值',
llmSuggestion: { request: '请求 AI' },
workbench: {
pinPdf: '退出后保留',
unpinPdf: '退出后关闭',
closePdf: '关闭',
pinPdfHint: '退出后保留',
unpinPdfHint: '退出后关闭',
expandPdf: '展开',
collapsePdf: '收起',
expandPdfHint: '放大',
collapsePdfHint: '收起',
dockPdf: '固定为侧栏',
undockPdf: '取消固定',
dockPdfHint: '双栏',
undockPdfHint: '浮窗',
movePdfLeft: '移至左侧',
movePdfRight: '移至右侧',
movePdfSideHint: '换侧',
moreActions: '更多',
},
highlightQuality: {
verified: '已验证',
candidate: '候选',
unavailable: '无坐标',
invalid: '坐标无效',
},
highlightSource: {
pdf_coordinate: 'PDF 原生坐标',
machine_extraction: '机器抽取',
},
coordinateIssues: {
coordinate_missing: '未获得可靠字段级坐标',
},
evidenceDrawer: {
title: '证据核对',
pageUnknown: '未知页',
prevEvidence: '上一证据',
nextEvidence: '下一证据',
field: '字段:{field}',
currentValue: '当前值',
machineValue: '机器值',
source: '来源',
highlightQuality: '高亮质量',
highlightSource: '坐标来源',
layoutPath: '版面路径',
detailsToggle: '证据详情',
},
},
},
},
},
});
return mount(ReviewDocumentEvidenceDrawer, {
props: {
open: true,
pinned: false,
expanded: false,
docked: false,
floatSide: 'right',
src: 'blob:mock',
evidence: evidenceList[0],
evidenceList,
fieldLabel: '客户 PO',
draftValue: 'PO-A',
machineValue: 'PO-A',
valueSourceLabel: '系统识别',
showAiActions: true,
...overrides,
},
global: { plugins: [i18n] },
attachTo: document.body,
});
}
afterEach(() => {
document.body.innerHTML = '';
localStorage.clear();
});
describe('ReviewDocumentEvidenceDrawer', () => {
it('renders floating panel when open and emits close/expand/dock; pin lives in more menu', async () => {
const wrapper = mountDrawer();
const root = wrapper.find('[data-testid="review-document-evidence-drawer"]');
expect(root.exists()).toBe(true);
expect(root.attributes('data-presentation')).toBe('floating');
expect(root.attributes('role')).toBe('dialog');
expect(root.attributes('aria-modal')).toBe('true');
expect(root.classes()).toContain('fixed');
expect(root.attributes('data-width')).toBeTruthy();
expect(root.attributes('data-height')).toBeTruthy();
expect(wrapper.find('[data-testid="review-evidence-ordinal"]').text()).toContain('1/2');
await wrapper.find('[data-testid="review-evidence-close"]').trigger('click');
expect(wrapper.emitted('close')).toBeTruthy();
await wrapper.find('[data-testid="review-evidence-toggle-expand"]').trigger('click');
expect(wrapper.emitted('toggle-expand')).toBeTruthy();
await wrapper.find('[data-testid="review-evidence-toggle-dock"]').trigger('click');
expect(wrapper.emitted('toggle-dock')).toBeTruthy();
// 关键断言:低频操作收入「更多」,打开后再点「退出后保留」。
expect(wrapper.find('[data-testid="review-evidence-toggle-pin"]').exists()).toBe(false);
await wrapper.find('[data-testid="review-evidence-more"]').trigger('click');
expect(wrapper.find('[data-testid="review-evidence-more-menu"]').exists()).toBe(true);
await wrapper.find('[data-testid="review-evidence-toggle-pin"]').trigger('click');
expect(wrapper.emitted('toggle-pin')).toBeTruthy();
});
it('exposes eight resize handles on floating panel only', () => {
const floating = mountDrawer({ docked: false });
for (const dir of ['n', 's', 'e', 'w', 'ne', 'nw', 'se', 'sw']) {
expect(floating.find(`[data-testid="review-evidence-resize-${dir}"]`).exists()).toBe(true);
}
floating.unmount();
const docked = mountDrawer({ docked: true });
expect(docked.find('[data-testid="review-evidence-resize-se"]').exists()).toBe(false);
});
it('persists float geometry to localStorage after resize end', async () => {
const wrapper = mountDrawer();
const handleEl = wrapper.find('[data-testid="review-evidence-resize-se"]').element;
handleEl.dispatchEvent(new PointerEvent('pointerdown', {
bubbles: true,
clientX: 100,
clientY: 100,
}));
window.dispatchEvent(new PointerEvent('pointermove', { clientX: 180, clientY: 160 }));
window.dispatchEvent(new PointerEvent('pointerup'));
await flushPromises();
const raw = localStorage.getItem('hxops.shippingReview.evidenceFloat.v1');
// 关键断言:拖拽结束写入尺寸位置,供下次打开复用。
expect(raw).toBeTruthy();
const parsed = JSON.parse(String(raw)) as { width: number; height: number };
expect(parsed.width).toBeGreaterThanOrEqual(360);
expect(parsed.height).toBeGreaterThanOrEqual(320);
});
it('closes floating panel on Escape', async () => {
const wrapper = mountDrawer({ open: true, docked: false });
await flushPromises();
document.dispatchEvent(new KeyboardEvent('keydown', {
key: 'Escape',
bubbles: true,
cancelable: true,
}));
// 关键断言:浮动态 Esc 关闭,便于键盘退出。
expect(wrapper.emitted('close')).toBeTruthy();
});
it('uses complementary semantics when docked as sidebar', () => {
const wrapper = mountDrawer({ docked: true });
const root = wrapper.find('[data-testid="review-document-evidence-drawer"]');
expect(root.attributes('data-presentation')).toBe('docked');
expect(root.attributes('role')).toBe('complementary');
expect(root.attributes('aria-modal')).toBeUndefined();
expect(root.classes()).toContain('relative');
expect(root.classes()).not.toContain('fixed');
});
it('enables next evidence and disables prev on first item', async () => {
const wrapper = mountDrawer();
expect((wrapper.find('[data-testid="review-evidence-prev"]').element as HTMLButtonElement).disabled).toBe(true);
expect((wrapper.find('[data-testid="review-evidence-next"]').element as HTMLButtonElement).disabled).toBe(false);
await wrapper.find('[data-testid="review-evidence-next"]').trigger('click');
expect(wrapper.emitted('next-evidence')).toBeTruthy();
});
it('shows quote when evidence has no bbox', () => {
const wrapper = mountDrawer({ evidence: evidenceList[1] });
expect(wrapper.find('[data-testid="review-evidence-no-bbox"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="review-evidence-no-bbox"]').text()).toContain('10 EA');
});
it('does not render when closed', () => {
const wrapper = mountDrawer({ open: false });
expect(wrapper.find('[data-testid="review-document-evidence-drawer"]').exists()).toBe(false);
});
});
@@ -0,0 +1,826 @@
<!--
features/chat/components/shipping-review/ReviewDocumentEvidenceDrawer.vue
用途:复核工作台 PDF 证据面板(默认浮动、可拖拽/resize、可固定为侧栏)。
依赖:ReviewDocumentPreview、ShippingOrderReviewEvidence、vue-i18n、field-highlight 契约。
逻辑:浮动用 left/top/width/height;四边四角 resize;localStorage 记忆尺寸位置;
dialog 语义(Esc/焦点陷阱);打开避让焦点字段;低频操作收入「更多」菜单。
-->
<script setup lang="ts">
import { computed, nextTick, onBeforeUnmount, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import ReviewDocumentPreview from './ReviewDocumentPreview.vue';
import type { ShippingOrderReviewEvidence } from '@/features/chat/types/shipping.api.types';
const FOCUSABLE_SELECTOR = [
'a[href]',
'button:not([disabled])',
'textarea:not([disabled])',
'input:not([disabled])',
'select:not([disabled])',
'[tabindex]:not([tabindex="-1"])',
].join(',');
const STORAGE_KEY = 'hxops.shippingReview.evidenceFloat.v1';
const MIN_WIDTH = 360;
const MIN_HEIGHT = 320;
const VIEW_MARGIN = 16;
const FOOTER_CLEARANCE = 72;
type ResizeDir = 'n' | 's' | 'e' | 'w' | 'ne' | 'nw' | 'se' | 'sw';
interface FloatGeom {
left: number;
top: number;
width: number;
height: number;
}
const RESIZE_DIRS: ResizeDir[] = ['n', 's', 'e', 'w', 'ne', 'nw', 'se', 'sw'];
const props = defineProps<{
open: boolean;
pinned: boolean;
expanded: boolean;
docked: boolean;
floatSide: 'right' | 'left';
src: string;
evidence: ShippingOrderReviewEvidence | null;
evidenceList: ShippingOrderReviewEvidence[];
fieldLabel?: string;
draftValue?: string | null;
machineValue?: string | null;
valueSourceLabel?: string;
showAiActions?: boolean;
/** Case 切换时重置证据焦点相关态;不清除用户记住的浮窗几何。 */
resetKey?: string | null;
}>();
const emit = defineEmits<{
close: [];
'toggle-pin': [];
'toggle-expand': [];
'toggle-dock': [];
'toggle-side': [];
'prev-evidence': [];
'next-evidence': [];
'request-ai': [];
'restore-machine': [];
}>();
const { t } = useI18n();
const panelRef = ref<HTMLElement | null>(null);
const closeButtonRef = ref<HTMLButtonElement | null>(null);
const moreOpen = ref(false);
const detailsOpen = ref(false);
const geom = ref<FloatGeom>(defaultGeom('right', false));
const dragging = ref(false);
const resizing = ref(false);
let dragOrigin: { x: number; y: number; left: number; top: number } | null = null;
let resizeOrigin: {
dir: ResizeDir;
x: number;
y: number;
left: number;
top: number;
width: number;
height: number;
} | null = null;
let previouslyFocused: HTMLElement | null = null;
let autoSideAdjustedForOpen = false;
/**
* 视口允许的最大浮窗宽高(70% / 85%)。
*/
function maxSize() {
if (typeof window === 'undefined') return { width: 720, height: 680 };
return {
width: Math.max(MIN_WIDTH, Math.floor(window.innerWidth * 0.7)),
height: Math.max(MIN_HEIGHT, Math.floor(window.innerHeight * 0.85)),
};
}
/**
* 生成默认浮窗几何(右下或左下,避开底栏)。
*/
function defaultGeom(side: 'left' | 'right', expanded: boolean): FloatGeom {
const max = maxSize();
const width = Math.min(expanded ? 720 : 440, max.width);
const height = Math.min(expanded ? 680 : 520, max.height);
if (typeof window === 'undefined') {
return { left: 16, top: 16, width, height };
}
const left = side === 'left'
? VIEW_MARGIN
: Math.max(VIEW_MARGIN, window.innerWidth - width - VIEW_MARGIN);
const top = Math.max(
VIEW_MARGIN,
window.innerHeight - height - FOOTER_CLEARANCE,
);
return { left, top, width, height };
}
/**
* 钳制几何到视口与最小/最大尺寸。
*/
function clampGeom(next: FloatGeom): FloatGeom {
const max = maxSize();
const width = Math.min(max.width, Math.max(MIN_WIDTH, Math.round(next.width)));
const height = Math.min(max.height, Math.max(MIN_HEIGHT, Math.round(next.height)));
if (typeof window === 'undefined') {
return { left: next.left, top: next.top, width, height };
}
const maxLeft = Math.max(VIEW_MARGIN, window.innerWidth - width - VIEW_MARGIN);
const maxTop = Math.max(VIEW_MARGIN, window.innerHeight - height - VIEW_MARGIN);
return {
width,
height,
left: Math.min(maxLeft, Math.max(VIEW_MARGIN, Math.round(next.left))),
top: Math.min(maxTop, Math.max(VIEW_MARGIN, Math.round(next.top))),
};
}
/**
* 从 localStorage 恢复浮窗几何。
*/
function loadStoredGeom(): FloatGeom | null {
if (typeof localStorage === 'undefined') return null;
try {
const raw = localStorage.getItem(STORAGE_KEY);
if (!raw) return null;
const parsed = JSON.parse(raw) as Partial<FloatGeom>;
if (
typeof parsed.left !== 'number'
|| typeof parsed.top !== 'number'
|| typeof parsed.width !== 'number'
|| typeof parsed.height !== 'number'
) {
return null;
}
return clampGeom({
left: parsed.left,
top: parsed.top,
width: parsed.width,
height: parsed.height,
});
} catch {
return null;
}
}
/**
* 持久化浮窗几何(跨 Case 复用尺寸位置,不复用证据焦点)。
*/
function persistGeom(next: FloatGeom) {
if (typeof localStorage === 'undefined') return;
try {
localStorage.setItem(STORAGE_KEY, JSON.stringify(next));
} catch {
/* ignore quota */
}
}
/**
* 应用几何并可选持久化。
*/
function applyGeom(next: FloatGeom, persist = true) {
const clamped = clampGeom(next);
geom.value = clamped;
if (persist) persistGeom(clamped);
}
/**
* 当前证据在列表中的序号(1-based);无匹配时为 0。
*/
const evidenceOrdinal = computed(() => {
const id = String(props.evidence?.evidence_id || '');
if (!id) return 0;
const idx = props.evidenceList.findIndex((item) => item.evidence_id === id);
return idx >= 0 ? idx + 1 : 0;
});
const canPrev = computed(() => evidenceOrdinal.value > 1);
const canNext = computed(() => {
const total = props.evidenceList.length;
return evidenceOrdinal.value > 0 && evidenceOrdinal.value < total;
});
const pageLabel = computed(() => {
const page = props.evidence?.page_no;
if (page == null) return t('chat.shippingOrderReview.evidenceDrawer.pageUnknown');
return t('chat.shippingOrderReview.evidenceAt', { page });
});
const hasDrawableHighlight = computed(() => {
const quality = String(props.evidence?.highlight_quality || '');
return (quality === 'verified' || quality === 'candidate')
&& Boolean(props.evidence?.highlight_bbox || props.evidence?.bbox);
});
const highlightQualityLabel = computed(() => {
const quality = String(props.evidence?.highlight_quality || 'unavailable');
return t(`chat.shippingOrderReview.highlightQuality.${quality}`, quality);
});
const highlightSourceLabel = computed(() => {
const source = String(props.evidence?.highlight_source || props.evidence?.source || 'unknown');
return t(`chat.shippingOrderReview.highlightSource.${source}`, source);
});
const coordinateIssueLabels = computed(() => {
const codes = props.evidence?.coordinate_issue_codes || [];
return codes.map((code) => t(`chat.shippingOrderReview.coordinateIssues.${code}`, code));
});
/**
* 面板根节点 class:浮动 fixed;固定侧栏走文档流。
*/
const panelClass = computed(() => {
if (props.docked) {
return [
'relative flex min-h-[320px] min-w-0 flex-col overflow-hidden rounded-xl border border-slate-200',
'bg-white shadow-sm xl:min-h-[520px] dark:border-slate-800 dark:bg-slate-900',
].join(' ');
}
return [
'fixed z-30 flex flex-col overflow-hidden rounded-xl border border-slate-200',
'bg-white shadow-2xl dark:border-slate-700 dark:bg-slate-900',
].join(' ');
});
/**
* 浮动几何 style;侧栏不使用。
*/
const panelStyle = computed(() => {
if (props.docked) return undefined;
return {
left: `${geom.value.left}px`,
top: `${geom.value.top}px`,
width: `${geom.value.width}px`,
height: `${geom.value.height}px`,
};
});
const resizeCursor: Record<ResizeDir, string> = {
n: 'ns-resize',
s: 'ns-resize',
e: 'ew-resize',
w: 'ew-resize',
ne: 'nesw-resize',
sw: 'nesw-resize',
nw: 'nwse-resize',
se: 'nwse-resize',
};
/**
* resize handle 定位 style(边 6px / 角 10px)。
*/
function resizeHandleStyle(dir: ResizeDir): Record<string, string> {
const edge = '6px';
const corner = '10px';
const styles: Record<ResizeDir, Record<string, string>> = {
n: { top: '0', left: corner, right: corner, height: edge },
s: { bottom: '0', left: corner, right: corner, height: edge },
e: { top: corner, right: '0', bottom: corner, width: edge },
w: { top: corner, left: '0', bottom: corner, width: edge },
ne: { top: '0', right: '0', width: corner, height: corner },
nw: { top: '0', left: '0', width: corner, height: corner },
se: { bottom: '0', right: '0', width: corner, height: corner },
sw: { bottom: '0', left: '0', width: corner, height: corner },
};
return styles[dir];
}
/** 收集面板内可聚焦控件。 */
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');
};
const onKeydown = (event: KeyboardEvent) => {
if (!props.open || props.docked) return;
if (event.key === 'Escape') {
if (moreOpen.value) {
event.preventDefault();
moreOpen.value = false;
return;
}
event.preventDefault();
event.stopPropagation();
emit('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();
}
};
const rectsOverlap = (a: DOMRect, b: DOMRect) => !(
a.right < b.left || a.left > b.right || a.bottom < b.top || a.top > b.bottom
);
/**
* 打开浮窗后若遮挡打开前焦点字段,则移到另一侧一次。
*/
const maybeAvoidFocusedField = async () => {
if (props.docked || autoSideAdjustedForOpen || typeof document === 'undefined') return;
await nextTick();
const panel = panelRef.value;
if (!panel) return;
const target = previouslyFocused
&& previouslyFocused.isConnected
&& !panel.contains(previouslyFocused)
? previouslyFocused
: null;
if (!target) return;
if (!target.matches('input, textarea, select, [contenteditable="true"]')) return;
if (!rectsOverlap(panel.getBoundingClientRect(), target.getBoundingClientRect())) return;
autoSideAdjustedForOpen = true;
const width = geom.value.width;
const left = props.floatSide === 'right'
? VIEW_MARGIN
: Math.max(VIEW_MARGIN, window.innerWidth - width - VIEW_MARGIN);
applyGeom({ ...geom.value, left });
emit('toggle-side');
};
/**
* 标题栏拖动移动浮窗。
*/
const onDragStart = (event: PointerEvent) => {
if (props.docked || resizing.value) return;
const target = event.target as HTMLElement | null;
if (target?.closest('button, details, summary, a, input')) return;
dragging.value = true;
dragOrigin = {
x: event.clientX,
y: event.clientY,
left: geom.value.left,
top: geom.value.top,
};
window.addEventListener('pointermove', onDragMove);
window.addEventListener('pointerup', onDragEnd);
};
const onDragMove = (event: PointerEvent) => {
if (!dragging.value || !dragOrigin) return;
applyGeom({
...geom.value,
left: dragOrigin.left + (event.clientX - dragOrigin.x),
top: dragOrigin.top + (event.clientY - dragOrigin.y),
}, false);
};
const onDragEnd = () => {
dragging.value = false;
dragOrigin = null;
window.removeEventListener('pointermove', onDragMove);
window.removeEventListener('pointerup', onDragEnd);
applyGeom(geom.value, true);
};
/**
* 八向 resize 开始。
*/
const onResizeStart = (dir: ResizeDir, event: PointerEvent) => {
if (props.docked) return;
event.preventDefault();
event.stopPropagation();
resizing.value = true;
resizeOrigin = {
dir,
x: event.clientX,
y: event.clientY,
left: geom.value.left,
top: geom.value.top,
width: geom.value.width,
height: geom.value.height,
};
window.addEventListener('pointermove', onResizeMove);
window.addEventListener('pointerup', onResizeEnd);
};
const onResizeMove = (event: PointerEvent) => {
if (!resizing.value || !resizeOrigin) return;
const dx = event.clientX - resizeOrigin.x;
const dy = event.clientY - resizeOrigin.y;
const next: FloatGeom = {
left: resizeOrigin.left,
top: resizeOrigin.top,
width: resizeOrigin.width,
height: resizeOrigin.height,
};
const dir = resizeOrigin.dir;
if (dir.includes('e')) next.width = resizeOrigin.width + dx;
if (dir.includes('w')) {
next.width = resizeOrigin.width - dx;
next.left = resizeOrigin.left + dx;
}
if (dir.includes('s')) next.height = resizeOrigin.height + dy;
if (dir.includes('n')) {
next.height = resizeOrigin.height - dy;
next.top = resizeOrigin.top + dy;
}
// 宽度触底时锁住 left,避免西向拖拽抖动。
if (dir.includes('w') && next.width <= MIN_WIDTH) {
next.width = MIN_WIDTH;
next.left = resizeOrigin.left + (resizeOrigin.width - MIN_WIDTH);
}
if (dir.includes('n') && next.height <= MIN_HEIGHT) {
next.height = MIN_HEIGHT;
next.top = resizeOrigin.top + (resizeOrigin.height - MIN_HEIGHT);
}
applyGeom(next, false);
};
const onResizeEnd = () => {
resizing.value = false;
resizeOrigin = null;
window.removeEventListener('pointermove', onResizeMove);
window.removeEventListener('pointerup', onResizeEnd);
applyGeom(geom.value, true);
};
/**
* 初始化或按展开态重置默认尺寸(保留可恢复的存储几何优先)。
*/
function ensureFloatGeom(forceDefault = false) {
if (forceDefault) {
applyGeom(defaultGeom(props.floatSide, props.expanded));
return;
}
const stored = loadStoredGeom();
if (stored) {
applyGeom(stored, false);
return;
}
applyGeom(defaultGeom(props.floatSide, props.expanded), false);
}
watch(
() => props.expanded,
(expanded, was) => {
if (props.docked || was === undefined) return;
const max = maxSize();
if (expanded) {
applyGeom({
...geom.value,
width: Math.min(720, max.width),
height: Math.min(680, max.height),
});
return;
}
applyGeom({
...geom.value,
width: Math.min(440, max.width),
height: Math.min(520, max.height),
});
},
);
watch(
() => props.floatSide,
(side, prev) => {
if (props.docked || prev === undefined || side === prev) return;
const width = geom.value.width;
const left = side === 'left'
? VIEW_MARGIN
: Math.max(VIEW_MARGIN, (typeof window !== 'undefined' ? window.innerWidth : 1200) - width - VIEW_MARGIN);
applyGeom({ ...geom.value, left });
},
);
watch(
() => [props.open, props.docked] as const,
([open, docked], previous) => {
if (typeof document === 'undefined') return;
const wasOpen = Boolean(previous?.[0]);
const floatingOpen = Boolean(open && !docked);
if (floatingOpen && !wasOpen) {
autoSideAdjustedForOpen = false;
moreOpen.value = false;
ensureFloatGeom(false);
previouslyFocused = document.activeElement instanceof HTMLElement
? document.activeElement
: null;
document.addEventListener('keydown', onKeydown, true);
void nextTick(() => {
try {
(closeButtonRef.value || focusableNodes()[0])?.focus?.();
} catch {
/* ignore */
}
void maybeAvoidFocusedField();
});
return;
}
if (floatingOpen && wasOpen) {
void maybeAvoidFocusedField();
return;
}
if ((!open || docked) && wasOpen) {
document.removeEventListener('keydown', onKeydown, true);
const restoreTarget = previouslyFocused;
previouslyFocused = null;
autoSideAdjustedForOpen = false;
moreOpen.value = false;
if (!open) {
void nextTick(() => {
try {
restoreTarget?.focus?.();
} catch {
/* ignore */
}
});
}
}
},
{ immediate: true },
);
onBeforeUnmount(() => {
window.removeEventListener('pointermove', onDragMove);
window.removeEventListener('pointerup', onDragEnd);
window.removeEventListener('pointermove', onResizeMove);
window.removeEventListener('pointerup', onResizeEnd);
if (typeof document !== 'undefined') {
document.removeEventListener('keydown', onKeydown, true);
}
});
</script>
<template>
<aside
v-if="open"
ref="panelRef"
:class="panelClass"
:style="panelStyle"
:role="docked ? 'complementary' : 'dialog'"
:aria-modal="docked ? undefined : 'true'"
aria-labelledby="review-evidence-drawer-title"
tabindex="-1"
data-testid="review-document-evidence-drawer"
:data-pinned="pinned ? 'true' : 'false'"
:data-expanded="expanded ? 'true' : 'false'"
:data-docked="docked ? 'true' : 'false'"
:data-float-side="floatSide"
:data-presentation="docked ? 'docked' : 'floating'"
:data-width="Math.round(geom.width)"
:data-height="Math.round(geom.height)"
>
<div
class="flex shrink-0 flex-col gap-1.5 border-b border-slate-200 px-3 py-2 dark:border-slate-800"
:class="docked ? '' : 'cursor-grab active:cursor-grabbing select-none'"
data-testid="review-evidence-drag-handle"
@pointerdown="onDragStart"
>
<div class="flex items-start justify-between gap-2">
<div class="min-w-0">
<div
id="review-evidence-drawer-title"
class="text-xs font-semibold text-slate-700 dark:text-slate-200"
>
{{ t('chat.shippingOrderReview.evidenceDrawer.title') }}
</div>
<p class="truncate text-[11px] text-slate-500">{{ pageLabel }}</p>
</div>
<button
ref="closeButtonRef"
type="button"
class="rounded border border-slate-300 px-2 py-1 text-xs hover:bg-slate-50 dark:border-slate-600 dark:hover:bg-slate-800"
data-testid="review-evidence-close"
@click="emit('close')"
>
{{ t('chat.shippingOrderReview.workbench.closePdf') }}
</button>
</div>
<div class="flex flex-wrap items-center gap-1.5">
<div class="flex items-center gap-1" data-testid="review-evidence-nav-group">
<button
type="button"
class="rounded border border-slate-300 px-2 py-1 text-xs hover:bg-slate-50 dark:border-slate-600 dark:hover:bg-slate-800"
data-testid="review-evidence-prev"
:disabled="!canPrev"
@click="emit('prev-evidence')"
>
{{ t('chat.shippingOrderReview.evidenceDrawer.prevEvidence') }}
</button>
<span class="text-[11px] text-slate-500" data-testid="review-evidence-ordinal">
{{ evidenceOrdinal }}/{{ evidenceList.length || 0 }}
</span>
<button
type="button"
class="rounded border border-slate-300 px-2 py-1 text-xs hover:bg-slate-50 dark:border-slate-600 dark:hover:bg-slate-800"
data-testid="review-evidence-next"
:disabled="!canNext"
@click="emit('next-evidence')"
>
{{ t('chat.shippingOrderReview.evidenceDrawer.nextEvidence') }}
</button>
</div>
<div class="ml-auto flex items-center gap-1" data-testid="review-evidence-window-group">
<button
v-if="!docked"
type="button"
class="rounded border border-slate-300 px-2 py-1 text-xs hover:bg-slate-50 dark:border-slate-600 dark:hover:bg-slate-800"
data-testid="review-evidence-toggle-expand"
:title="expanded
? t('chat.shippingOrderReview.workbench.collapsePdfHint')
: t('chat.shippingOrderReview.workbench.expandPdfHint')"
@click="emit('toggle-expand')"
>
{{ expanded
? t('chat.shippingOrderReview.workbench.collapsePdf')
: t('chat.shippingOrderReview.workbench.expandPdf') }}
</button>
<button
type="button"
class="rounded border border-slate-300 px-2 py-1 text-xs hover:bg-slate-50 dark:border-slate-600 dark:hover:bg-slate-800"
data-testid="review-evidence-toggle-dock"
:title="docked
? t('chat.shippingOrderReview.workbench.undockPdfHint')
: t('chat.shippingOrderReview.workbench.dockPdfHint')"
@click="emit('toggle-dock')"
>
{{ docked
? t('chat.shippingOrderReview.workbench.undockPdf')
: t('chat.shippingOrderReview.workbench.dockPdf') }}
</button>
<div class="relative">
<button
type="button"
class="rounded border border-slate-300 px-2 py-1 text-xs hover:bg-slate-50 dark:border-slate-600 dark:hover:bg-slate-800"
data-testid="review-evidence-more"
:aria-expanded="moreOpen ? 'true' : 'false'"
@click="moreOpen = !moreOpen"
>
{{ t('chat.shippingOrderReview.workbench.moreActions') }}
</button>
<div
v-if="moreOpen"
class="absolute right-0 z-40 mt-1 min-w-[10rem] rounded-md border border-slate-200 bg-white py-1 text-xs shadow-lg dark:border-slate-700 dark:bg-slate-900"
data-testid="review-evidence-more-menu"
>
<button
v-if="!docked"
type="button"
class="block w-full px-3 py-1.5 text-left hover:bg-slate-50 dark:hover:bg-slate-800"
data-testid="review-evidence-toggle-side"
@click="emit('toggle-side'); moreOpen = false"
>
{{ floatSide === 'right'
? t('chat.shippingOrderReview.workbench.movePdfLeft')
: t('chat.shippingOrderReview.workbench.movePdfRight') }}
</button>
<button
type="button"
class="block w-full px-3 py-1.5 text-left hover:bg-slate-50 dark:hover:bg-slate-800"
data-testid="review-evidence-toggle-pin"
@click="emit('toggle-pin'); moreOpen = false"
>
{{ pinned
? t('chat.shippingOrderReview.workbench.unpinPdf')
: t('chat.shippingOrderReview.workbench.pinPdf') }}
</button>
<button
v-if="showAiActions"
type="button"
class="block w-full px-3 py-1.5 text-left hover:bg-slate-50 dark:hover:bg-slate-800"
data-testid="review-evidence-request-ai"
@click="emit('request-ai'); moreOpen = false"
>
{{ t('chat.shippingOrderReview.llmSuggestion.request') }}
</button>
<button
v-if="showAiActions"
type="button"
class="block w-full px-3 py-1.5 text-left hover:bg-slate-50 dark:hover:bg-slate-800"
data-testid="review-evidence-restore-machine"
@click="emit('restore-machine'); moreOpen = false"
>
{{ t('chat.shippingOrderReview.restoreMachine') }}
</button>
</div>
</div>
</div>
</div>
</div>
<div class="grid min-h-0 flex-1 grid-rows-[minmax(0,1fr)_auto]">
<ReviewDocumentPreview
v-if="src"
class="min-h-0"
:src="src"
:evidence="evidence"
:drawer-mode="true"
:title="t('chat.shippingOrderReview.previewTitle')"
:loading-text="t('chat.shippingOrderReview.previewLoading')"
:unavailable-text="t('chat.shippingOrderReview.previewUnavailable')"
/>
<div
v-else
class="flex min-h-[140px] items-center justify-center p-4 text-sm text-slate-500"
>
{{ t('chat.shippingOrderReview.previewUnavailable') }}
</div>
<details
class="shrink-0 border-t border-slate-200 text-xs dark:border-slate-800"
data-testid="review-evidence-details"
:open="detailsOpen"
@toggle="detailsOpen = ($event.target as HTMLDetailsElement).open"
>
<summary class="cursor-pointer px-3 py-2 font-medium text-slate-700 hover:bg-slate-50 dark:text-slate-200 dark:hover:bg-slate-800/60">
{{ t('chat.shippingOrderReview.evidenceDrawer.detailsToggle') }}
<span v-if="fieldLabel" class="ml-1 font-normal text-slate-500">· {{ fieldLabel }}</span>
</summary>
<div class="space-y-2 px-3 pb-2">
<div v-if="fieldLabel" class="font-medium text-slate-700 dark:text-slate-200">
{{ t('chat.shippingOrderReview.evidenceDrawer.field', { field: fieldLabel }) }}
</div>
<dl class="grid gap-1 text-slate-600 dark:text-slate-300">
<div class="flex gap-2">
<dt class="shrink-0 text-slate-500">{{ t('chat.shippingOrderReview.evidenceDrawer.currentValue') }}</dt>
<dd class="min-w-0 break-words">{{ draftValue || t('chat.shippingOrderReview.emptyValue') }}</dd>
</div>
<div class="flex gap-2">
<dt class="shrink-0 text-slate-500">{{ t('chat.shippingOrderReview.evidenceDrawer.machineValue') }}</dt>
<dd class="min-w-0 break-words">{{ machineValue || t('chat.shippingOrderReview.emptyValue') }}</dd>
</div>
<div class="flex gap-2">
<dt class="shrink-0 text-slate-500">{{ t('chat.shippingOrderReview.evidenceDrawer.highlightQuality') }}</dt>
<dd data-testid="review-evidence-highlight-quality">{{ highlightQualityLabel }}</dd>
</div>
<div class="flex gap-2">
<dt class="shrink-0 text-slate-500">{{ t('chat.shippingOrderReview.evidenceDrawer.highlightSource') }}</dt>
<dd data-testid="review-evidence-highlight-source">{{ highlightSourceLabel }}</dd>
</div>
<div v-if="valueSourceLabel" class="flex gap-2">
<dt class="shrink-0 text-slate-500">{{ t('chat.shippingOrderReview.evidenceDrawer.source') }}</dt>
<dd>{{ valueSourceLabel }}</dd>
</div>
<div v-if="evidence?.table_id || evidence?.cell_id" class="flex gap-2">
<dt class="shrink-0 text-slate-500">{{ t('chat.shippingOrderReview.evidenceDrawer.layoutPath') }}</dt>
<dd class="min-w-0 break-all font-mono text-[11px]">
{{ [evidence?.table_id, evidence?.cell_id].filter(Boolean).join(' / ') }}
</dd>
</div>
</dl>
<p
v-if="!hasDrawableHighlight"
class="rounded bg-amber-50 px-2 py-1 text-[11px] text-amber-900 dark:bg-amber-950/40 dark:text-amber-100"
data-testid="review-evidence-no-bbox"
>
<span v-if="!evidence">
{{ t('chat.shippingOrderReview.locateUnavailableHint') }}
</span>
<span v-else-if="evidence.highlight_quality === 'invalid'">
{{ t('chat.shippingOrderReview.evidenceInvalidHighlight') }}
</span>
<span v-else>
{{ t('chat.shippingOrderReview.evidenceNoHighlight') }}
</span>
<span v-if="coordinateIssueLabels.length" class="mt-1 block">
{{ coordinateIssueLabels.join(';') }}
</span>
<span v-if="evidence?.quote" class="mt-1 block font-mono">{{ evidence.quote }}</span>
</p>
</div>
</details>
</div>
<template v-if="!docked">
<span
v-for="dir in RESIZE_DIRS"
:key="dir"
class="absolute z-50 touch-none"
:data-testid="`review-evidence-resize-${dir}`"
:data-resize-dir="dir"
:style="{ cursor: resizeCursor[dir], ...resizeHandleStyle(dir) }"
@pointerdown="onResizeStart(dir, $event)"
/>
</template>
</aside>
</template>
@@ -0,0 +1,72 @@
<!--
features/chat/components/shipping-review/ReviewDocumentNavigation.vue
用途:复核工作台顶部横向 PDF 文件导航(紧凑标签样式)。
依赖:vue-i18n、lucide-vue-next。
逻辑:ShippingOrderReviewView 传入 Run 内 Case 摘要;emit select 切换当前 PDF Case。
-->
<script setup lang="ts">
import { TriangleAlert } from 'lucide-vue-next';
import { useI18n } from 'vue-i18n';
export type ReviewDocumentNavItem = {
case_no: string;
file_name?: string | null;
status: string;
issue_count?: number;
};
const props = defineProps<{
items: ReviewDocumentNavItem[];
activeCaseNo?: string | null;
/** 导航区域无障碍标签(避免与原生 aria-label 属性在 vue-tsc 中冲突) */
navAriaLabel: string;
}>();
const emit = defineEmits<{
select: [caseNo: string];
}>();
const { t, te } = useI18n();
/**
* 将 Case 状态码映射为本地化文案,供导航标签展示。
* @param status - Case 状态码
* @returns 本地化文案;未知状态回落 unknown
*/
function caseStatusLabel(status: string): string {
const key = `chat.shippingOrderReview.caseStatuses.${status}`;
return te(key) ? t(key) : t('chat.shippingOrderReview.caseStatuses.unknown');
}
</script>
<template>
<nav
class="rounded-xl border border-slate-200 bg-white p-2 shadow-sm dark:border-slate-800 dark:bg-slate-900"
:aria-label="navAriaLabel"
data-testid="review-document-navigation"
>
<div class="flex gap-1.5 overflow-x-auto">
<button
v-for="item in items"
:key="item.case_no"
type="button"
class="inline-flex max-w-[220px] shrink-0 items-center gap-1.5 rounded-lg border px-2.5 py-1.5 text-left text-xs transition-colors"
:class="activeCaseNo === item.case_no
? 'border-sky-500 bg-sky-50 text-sky-950 dark:border-sky-700 dark:bg-sky-950/40 dark:text-sky-100'
: 'border-slate-200 text-slate-700 hover:bg-slate-50 dark:border-slate-700 dark:text-slate-300 dark:hover:bg-slate-800'"
:data-testid="`review-doc-nav-${item.case_no}`"
@click="emit('select', item.case_no)"
>
<TriangleAlert
v-if="item.issue_count"
class="h-3.5 w-3.5 shrink-0 text-amber-500"
aria-hidden="true"
/>
<span class="truncate font-medium">{{ item.file_name || t('chat.shippingOrderReview.unnamedDocument') }}</span>
<span class="shrink-0 text-[10px] text-slate-500 dark:text-slate-400">
{{ caseStatusLabel(item.status) }}
</span>
</button>
</div>
</nav>
</template>
@@ -1,38 +1,123 @@
<!--
用途:渲染受控 PDF Blob,并仅为服务端验证的 bbox 绘制证据高亮。
依赖:pdfjs-dist、Review Evidence DTO。
逻辑:预览失败独立显示,不影响同页草稿编辑;缺少可靠 bbox 时只保留页码定位。
features/chat/components/shipping-review/ReviewDocumentPreview.vue
用途:渲染受控 PDF Blob,并按 highlight_quality 绘制证据高亮(阶段 4+评审修复)。
依赖:pdfjs-dist(渲染时动态加载)、pdfHighlightCoords、Review Evidence DTO。
逻辑:预览失败独立显示,不影响同页草稿编辑;仅 verified/candidate 绘制;
verified=黄实线,candidate=橙虚线并显示画布内候选提示;unavailable/invalid 不画框;
Ctrl/Cmd+滚轮缩放;适合宽度/页面/100%;溢出时可拖拽平移;高亮自动滚入视口。
-->
<script setup lang="ts">
import { computed, nextTick, ref, watch } from 'vue';
import * as pdfjs from 'pdfjs-dist';
import workerUrl from 'pdfjs-dist/build/pdf.worker.min.mjs?url';
import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import type { ShippingOrderReviewEvidence } from '../../types/shipping.api.types';
import { normalizedTopLeftBBoxToViewportRect } from './pdfHighlightCoords';
pdfjs.GlobalWorkerOptions.workerSrc = workerUrl;
/** 有合法 bbox 时四种质量都绘制;颜色只提示可信度,不隐藏取值位置。 */
const DRAWABLE_QUALITIES = new Set(['verified', 'candidate', 'unavailable', 'invalid']);
const props = defineProps<{
type PdfJsModule = typeof import('pdfjs-dist');
let pdfjsLoader: Promise<PdfJsModule> | null = null;
/**
* 动态加载 pdfjs 与 worker;同页复用单例 Promise。
*/
async function loadPdfJs(): Promise<PdfJsModule> {
if (!pdfjsLoader) {
pdfjsLoader = (async () => {
const [pdfjs, workerMod] = await Promise.all([
import('pdfjs-dist'),
import('pdfjs-dist/build/pdf.worker.min.mjs?url'),
]);
pdfjs.GlobalWorkerOptions.workerSrc = workerMod.default;
return pdfjs;
})();
}
return pdfjsLoader;
}
const props = withDefaults(defineProps<{
src: string;
evidence?: ShippingOrderReviewEvidence | null;
title: string;
loadingText: string;
unavailableText: string;
/** 证据抽屉内使用更紧凑高度与页码指示。 */
drawerMode?: boolean;
}>(), {
drawerMode: false,
});
const emit = defineEmits<{
'page-change': [pageNo: number];
}>();
const { t } = useI18n();
const canvas = ref<HTMLCanvasElement | null>(null);
const scrollHost = ref<HTMLElement | null>(null);
const loading = ref(false);
const failed = ref(false);
const scale = ref(1.5);
const scale = ref(1.25);
const pageCount = ref(0);
const currentPage = ref(1);
/** 用户手动翻页时覆盖证据页码;证据身份变化时清除。 */
const manualPageOverride = ref<number | null>(null);
const pageJumpInput = ref('');
const zoomLabel = computed(() => `${Math.round(scale.value * 100)}%`);
/** 最近一次渲染的未缩放页宽高,供适合宽度/页面计算。 */
const basePageSize = ref<{ width: number; height: number } | null>(null);
/** 将当前页渲染到 canvas;高亮以 PDF viewport 为基准,绝不猜测不可靠坐标。 */
const highlightQuality = computed(() => String(props.evidence?.highlight_quality || ''));
const showCandidateBanner = computed(() => highlightQuality.value === 'candidate');
const showVerifiedLegend = computed(() => highlightQuality.value === 'verified');
const panning = ref(false);
const canPan = ref(false);
let panOrigin: { x: number; y: number; left: number; top: number } | null = null;
/**
* 根据滚动容器是否出现溢出刷新可拖拽平移状态。
*/
const refreshCanPan = () => {
const host = scrollHost.value;
if (!host || loading.value || failed.value) {
canPan.value = false;
return;
}
canPan.value = host.scrollWidth > host.clientWidth + 2
|| host.scrollHeight > host.clientHeight + 2;
};
/**
* 将高亮矩形滚入滚动容器中心(带边距)。
*/
const scrollHighlightIntoView = (rect: { x: number; y: number; width: number; height: number }) => {
const host = scrollHost.value;
if (!host) return;
const pad = 24;
const targetLeft = Math.max(0, rect.x + rect.width / 2 - host.clientWidth / 2);
const targetTop = Math.max(0, rect.y + rect.height / 2 - host.clientHeight / 2 + pad);
host.scrollTo({ left: targetLeft, top: targetTop, behavior: 'smooth' });
};
/**
* 将当前页渲染到 canvas;高亮以 PDF viewport 矩阵为基准,绝不猜测不可靠坐标。
*/
const render = async () => {
if (!props.src) return;
loading.value = true;
failed.value = false;
try {
const pdfjs = await loadPdfJs();
const document = await pdfjs.getDocument(props.src).promise;
const pageNo = Math.min(Math.max(props.evidence?.page_no || 1, 1), document.numPages);
const page = await document.getPage(pageNo);
pageCount.value = document.numPages;
const evidencePage = props.evidence?.page_no;
const preferred = manualPageOverride.value ?? evidencePage ?? currentPage.value ?? 1;
const targetPage = Math.min(Math.max(preferred, 1), document.numPages);
currentPage.value = targetPage;
const page = await document.getPage(targetPage);
const baseViewport = page.getViewport({ scale: 1 });
basePageSize.value = { width: baseViewport.width, height: baseViewport.height };
const viewport = page.getViewport({ scale: scale.value });
await nextTick();
if (!canvas.value) return;
@@ -41,46 +126,358 @@ const render = async () => {
const context = canvas.value.getContext('2d');
if (!context) return;
await page.render({ canvas: canvas.value, canvasContext: context, viewport }).promise;
const bbox = props.evidence?.bbox;
if (bbox) {
context.save();
context.fillStyle = 'rgba(250, 204, 21, 0.35)';
context.strokeStyle = 'rgba(202, 138, 4, 0.95)';
context.lineWidth = 2;
const x = bbox.x0 * viewport.width;
const y = bbox.y0 * viewport.height;
const width = (bbox.x1 - bbox.x0) * viewport.width;
const height = (bbox.y1 - bbox.y0) * viewport.height;
context.fillRect(x, y, width, height);
context.strokeRect(x, y, width, height);
context.restore();
}
const highlightRect = drawEvidenceHighlight(context, page, viewport, props.evidence);
emit('page-change', targetPage);
await nextTick();
refreshCanPan();
if (highlightRect) scrollHighlightIntoView(highlightRect);
} catch {
failed.value = true;
} finally {
loading.value = false;
await nextTick();
refreshCanPan();
}
};
const zoomIn = () => { scale.value = Math.min(scale.value + 0.25, 3); };
const zoomOut = () => { scale.value = Math.max(scale.value - 0.25, 0.75); };
const fitWidth = () => { scale.value = 1.75; };
/**
* 按后端确认的 highlight_quality 绘制 bbox;非法/缺失质量不绘制。
* @param context - canvas 2d 上下文
* @param page - PDF.js page(含 view / rotate)
* @param viewport - 当前缩放与旋转后的 viewport
* @param evidence - 当前证据 DTO
*/
function drawEvidenceHighlight(
context: CanvasRenderingContext2D,
page: { view: number[]; rotate?: number },
viewport: { width: number; height: number; convertToViewportRectangle: (rect: number[]) => number[] },
evidence: ShippingOrderReviewEvidence | null | undefined,
): { x: number; y: number; width: number; height: number } | null {
const quality = String(evidence?.highlight_quality || '');
const bbox = evidence?.highlight_bbox || evidence?.bbox;
if (!bbox || !DRAWABLE_QUALITIES.has(quality)) return null;
const rect = normalizedTopLeftBBoxToViewportRect(bbox, page, viewport);
if (!rect) return null;
context.save();
if (quality === 'candidate') {
context.fillStyle = 'rgba(249, 115, 22, 0.22)';
context.strokeStyle = 'rgba(194, 65, 12, 0.95)';
context.setLineDash([6, 4]);
} else if (quality === 'verified') {
context.fillStyle = 'rgba(250, 204, 21, 0.35)';
context.strokeStyle = 'rgba(202, 138, 4, 0.95)';
context.setLineDash([]);
} else {
context.fillStyle = 'rgba(244, 63, 94, 0.18)';
context.strokeStyle = 'rgba(225, 29, 72, 0.95)';
context.setLineDash([3, 3]);
}
context.lineWidth = 2;
context.fillRect(rect.x, rect.y, rect.width, rect.height);
context.strokeRect(rect.x, rect.y, rect.width, rect.height);
context.restore();
return rect;
}
watch(() => [props.src, props.evidence?.evidence_id, scale.value], () => { void render(); }, { immediate: true });
/**
* 内容溢出时按下拖拽平移滚动位置。
*/
const onPanStart = (event: PointerEvent) => {
if (event.button !== 0 || loading.value || failed.value) return;
const host = scrollHost.value;
if (!host) return;
refreshCanPan();
if (!canPan.value) return;
const target = event.target as HTMLElement | null;
if (!target?.closest('canvas')) return;
panning.value = true;
panOrigin = {
x: event.clientX,
y: event.clientY,
left: host.scrollLeft,
top: host.scrollTop,
};
host.setPointerCapture?.(event.pointerId);
window.addEventListener('pointermove', onPanMove);
window.addEventListener('pointerup', onPanEnd);
};
const onPanMove = (event: PointerEvent) => {
if (!panning.value || !panOrigin) return;
const host = scrollHost.value;
if (!host) return;
host.scrollLeft = panOrigin.left - (event.clientX - panOrigin.x);
host.scrollTop = panOrigin.top - (event.clientY - panOrigin.y);
};
const onPanEnd = (event?: PointerEvent) => {
const host = scrollHost.value;
if (host && event?.pointerId != null) {
try {
host.releasePointerCapture?.(event.pointerId);
} catch {
/* ignore */
}
}
panning.value = false;
panOrigin = null;
window.removeEventListener('pointermove', onPanMove);
window.removeEventListener('pointerup', onPanEnd);
};
/** 放大预览。 */
const zoomIn = () => { scale.value = Math.min(scale.value + 0.25, 3); };
/** 缩小预览。 */
const zoomOut = () => { scale.value = Math.max(scale.value - 0.25, 0.5); };
/** 重置为 100%。 */
const zoomActual = () => { scale.value = 1; };
/**
* 按滚动容器宽度适配(留边距)。
*/
const fitWidth = () => {
const host = scrollHost.value;
const base = basePageSize.value;
if (!host || !base?.width) {
scale.value = 1.25;
return;
}
const available = Math.max(120, host.clientWidth - 32);
scale.value = Math.min(3, Math.max(0.5, available / base.width));
};
/**
* 按滚动容器宽高适配整页。
*/
const fitPage = () => {
const host = scrollHost.value;
const base = basePageSize.value;
if (!host || !base?.width || !base.height) {
scale.value = 1;
return;
}
const availW = Math.max(120, host.clientWidth - 32);
const availH = Math.max(120, host.clientHeight - 32);
scale.value = Math.min(3, Math.max(0.5, Math.min(availW / base.width, availH / base.height)));
};
/**
* Ctrl/Cmd+滚轮缩放;Shift+滚轮横向滚动;普通滚轮纵向滚动。
* 使用非 passive 监听以便 preventDefault。
*/
const onPreviewWheel = (event: WheelEvent) => {
const host = scrollHost.value;
if (!host) return;
if (event.ctrlKey || event.metaKey) {
event.preventDefault();
const delta = event.deltaY > 0 ? -0.1 : 0.1;
scale.value = Math.min(3, Math.max(0.5, Number((scale.value + delta).toFixed(2))));
return;
}
if (event.shiftKey && Math.abs(event.deltaY) > Math.abs(event.deltaX)) {
event.preventDefault();
host.scrollLeft += event.deltaY;
}
};
/** 当前已绑定 wheel 的宿主,避免 ref 切换时解绑错节点。 */
let wheelHost: HTMLElement | null = null;
/**
* 绑定滚轮(passive:false),保证 Ctrl 缩放可拦截浏览器默认缩放。
*/
const bindWheel = () => {
const host = scrollHost.value;
if (!host || wheelHost === host) return;
if (wheelHost) {
wheelHost.removeEventListener('wheel', onPreviewWheel);
wheelHost = null;
}
host.addEventListener('wheel', onPreviewWheel, { passive: false });
wheelHost = host;
};
/** 解除滚轮绑定。 */
const unbindWheel = () => {
if (!wheelHost) return;
wheelHost.removeEventListener('wheel', onPreviewWheel);
wheelHost = null;
};
onMounted(() => {
void nextTick(() => bindWheel());
});
onBeforeUnmount(() => {
unbindWheel();
onPanEnd();
});
watch(scrollHost, () => {
void nextTick(() => bindWheel());
});
/**
* 跳转到输入页码。
*/
const jumpToPage = () => {
const page = Number.parseInt(String(pageJumpInput.value || ''), 10);
if (!Number.isFinite(page) || page < 1 || page > pageCount.value) return;
manualPageOverride.value = page;
pageJumpInput.value = '';
void render();
};
/**
* 手动翻到上一页。
*/
const prevPage = () => {
if (currentPage.value <= 1) return;
manualPageOverride.value = currentPage.value - 1;
void render();
};
/**
* 手动翻到下一页。
*/
const nextPage = () => {
if (currentPage.value >= pageCount.value) return;
manualPageOverride.value = currentPage.value + 1;
void render();
};
watch(
() => [props.src, props.evidence?.evidence_id] as const,
() => {
manualPageOverride.value = null;
},
);
watch(
() => [
props.src,
props.evidence?.evidence_id,
props.evidence?.page_no,
props.evidence?.highlight_quality,
props.evidence?.highlight_bbox,
scale.value,
manualPageOverride.value,
] as const,
() => { void render(); },
{ immediate: true },
);
</script>
<template>
<div class="relative flex min-h-[180px] flex-1 flex-col overflow-hidden bg-slate-100 xl:min-h-[360px] dark:bg-slate-950">
<div class="flex shrink-0 items-center justify-end gap-1 border-b border-slate-200 bg-white/95 px-2 py-1.5 text-xs dark:border-slate-800 dark:bg-slate-900/95">
<button type="button" class="rounded border px-2 py-1 hover:bg-slate-50 dark:border-slate-700 dark:hover:bg-slate-800" @click="zoomOut">−</button>
<button type="button" class="min-w-12 rounded border px-2 py-1 hover:bg-slate-50 dark:border-slate-700 dark:hover:bg-slate-800" @click="fitWidth">{{ zoomLabel }}</button>
<button type="button" class="rounded border px-2 py-1 hover:bg-slate-50 dark:border-slate-700 dark:hover:bg-slate-800" @click="zoomIn">+</button>
<div
class="relative flex flex-1 flex-col overflow-hidden bg-slate-100 dark:bg-slate-950"
:class="drawerMode ? 'min-h-[200px]' : 'min-h-[180px] xl:min-h-[360px]'"
:data-drawer-mode="drawerMode ? 'true' : 'false'"
>
<div class="flex shrink-0 items-center justify-between gap-1 border-b border-slate-200 bg-white/95 px-2 py-1.5 text-xs dark:border-slate-800 dark:bg-slate-900/95">
<div class="flex items-center gap-1">
<button
type="button"
class="rounded border px-2 py-1 hover:bg-slate-50 disabled:opacity-40 dark:border-slate-700 dark:hover:bg-slate-800"
data-testid="review-pdf-prev-page"
:disabled="currentPage <= 1"
@click="prevPage"
>‹</button>
<span class="min-w-16 text-center text-slate-600 dark:text-slate-300" data-testid="review-pdf-page-label">
{{ currentPage }} / {{ pageCount || '—' }}
</span>
<button
type="button"
class="rounded border px-2 py-1 hover:bg-slate-50 disabled:opacity-40 dark:border-slate-700 dark:hover:bg-slate-800"
data-testid="review-pdf-next-page"
:disabled="!pageCount || currentPage >= pageCount"
@click="nextPage"
>›</button>
<form class="ml-1 flex items-center gap-1" @submit.prevent="jumpToPage">
<input
v-model="pageJumpInput"
type="number"
min="1"
:max="pageCount || undefined"
class="w-12 rounded border border-slate-300 px-1 py-0.5 text-center dark:border-slate-700 dark:bg-slate-950"
data-testid="review-pdf-page-jump"
:aria-label="t('chat.shippingOrderReview.previewZoom.jumpPage')"
>
<button
type="submit"
class="rounded border px-1.5 py-0.5 hover:bg-slate-50 dark:border-slate-700 dark:hover:bg-slate-800"
data-testid="review-pdf-page-jump-go"
>{{ t('chat.shippingOrderReview.previewZoom.go') }}</button>
</form>
</div>
<div class="flex flex-wrap items-center gap-1">
<button
type="button"
class="rounded border px-1.5 py-1 hover:bg-slate-50 dark:border-slate-700 dark:hover:bg-slate-800"
data-testid="review-pdf-zoom-fit-width"
:title="t('chat.shippingOrderReview.previewZoom.fitWidth')"
@click="fitWidth"
>{{ t('chat.shippingOrderReview.previewZoom.fitWidthShort') }}</button>
<button
type="button"
class="rounded border px-1.5 py-1 hover:bg-slate-50 dark:border-slate-700 dark:hover:bg-slate-800"
data-testid="review-pdf-zoom-fit-page"
:title="t('chat.shippingOrderReview.previewZoom.fitPage')"
@click="fitPage"
>{{ t('chat.shippingOrderReview.previewZoom.fitPageShort') }}</button>
<button
type="button"
class="rounded border px-1.5 py-1 hover:bg-slate-50 dark:border-slate-700 dark:hover:bg-slate-800"
data-testid="review-pdf-zoom-actual"
:title="t('chat.shippingOrderReview.previewZoom.actual')"
@click="zoomActual"
>100%</button>
<button type="button" class="rounded border px-2 py-1 hover:bg-slate-50 dark:border-slate-700 dark:hover:bg-slate-800" data-testid="review-pdf-zoom-out" @click="zoomOut">−</button>
<span class="min-w-12 text-center text-slate-600 dark:text-slate-300" data-testid="review-pdf-zoom-label">{{ zoomLabel }}</span>
<button type="button" class="rounded border px-2 py-1 hover:bg-slate-50 dark:border-slate-700 dark:hover:bg-slate-800" data-testid="review-pdf-zoom-in" @click="zoomIn">+</button>
</div>
</div>
<div class="relative flex min-h-0 flex-1 items-start justify-center overflow-auto p-4">
<!-- Keep the canvas mounted while PDF.js is loading; otherwise nextTick cannot obtain a render target. -->
<canvas ref="canvas" :aria-label="title" class="bg-white shadow" :class="{ invisible: loading || failed }" />
<span v-if="loading" class="absolute text-sm text-slate-500">{{ loadingText }}</span>
<span v-else-if="failed" class="absolute text-sm text-rose-600">{{ unavailableText }}</span>
<div
v-if="showCandidateBanner || showVerifiedLegend"
class="flex shrink-0 flex-wrap items-center gap-2 border-b border-slate-200 bg-white/90 px-2 py-1 text-[11px] dark:border-slate-800 dark:bg-slate-900/90"
data-testid="review-pdf-highlight-legend"
>
<span
v-if="showVerifiedLegend"
class="inline-flex items-center gap-1 text-amber-800 dark:text-amber-100"
>
<span class="inline-block h-2.5 w-4 border-2 border-amber-500 bg-amber-300/50" />
{{ t('chat.shippingOrderReview.highlightLegend.verified') }}
</span>
<span
v-if="showCandidateBanner"
class="inline-flex items-center gap-1 font-medium text-orange-800 dark:text-orange-100"
data-testid="review-pdf-candidate-tip"
>
<span class="inline-block h-2.5 w-4 border-2 border-dashed border-orange-600 bg-orange-300/40" />
{{ t('chat.shippingOrderReview.highlightLegend.candidate') }}
</span>
</div>
<div
ref="scrollHost"
class="relative flex min-h-0 flex-1 items-start justify-center overflow-auto p-4"
data-testid="review-pdf-scroll-host"
:data-can-pan="canPan ? 'true' : 'false'"
:data-panning="panning ? 'true' : 'false'"
:class="canPan ? (panning ? 'cursor-grabbing' : 'cursor-grab') : ''"
@pointerdown="onPanStart"
>
<!-- Keep the canvas mounted while PDF.js is loading; otherwise nextTick cannot obtain a render target. -->
<canvas ref="canvas" :aria-label="title" class="bg-white shadow select-none" :class="{ invisible: loading || failed }" />
<span v-if="loading" class="absolute text-sm text-slate-500">{{ loadingText }}</span>
<span v-else-if="failed" class="absolute text-sm text-rose-600">{{ unavailableText }}</span>
<div
v-else-if="showCandidateBanner && !loading && !failed"
class="pointer-events-none absolute left-4 top-4 max-w-[min(100%,18rem)] rounded border border-dashed border-orange-600 bg-orange-50/95 px-2 py-1 text-[11px] font-medium text-orange-900 shadow-sm dark:border-orange-500 dark:bg-orange-950/90 dark:text-orange-100"
data-testid="review-pdf-candidate-canvas-tip"
>
{{ t('chat.shippingOrderReview.highlightLegend.candidate') }}
</div>
</div>
</div>
</template>
@@ -0,0 +1,229 @@
<!--
features/chat/components/shipping-review/ReviewDuplicatePanel.vue
用途:复核工作台建单前重复订单对比与裁决区。
依赖:vue-i18n、shipping.api 重复裁决/刷新、useMessage。
逻辑:needs_adjudication 时展示匹配任务与动作;裁决成功后 emit refreshed。
-->
<script setup lang="ts">
import { computed, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { BusinessError, resolveLocalizedErrorMessage } from '@/shared/api/client';
import { useMessage } from '@/shared/composables/useMessage';
import {
refreshWorkspaceShippingOrderReviewDuplicate,
resolveWorkspaceShippingOrderReviewDuplicate,
} from '@/features/chat/api/shipping.api';
import type {
ShippingDuplicateAction,
ShippingOrderReviewDuplicate,
} from '@/features/chat/types/shipping.api.types';
const props = defineProps<{
caseNo: string;
duplicate: ShippingOrderReviewDuplicate | null | undefined;
editable: boolean;
canForceCreate: boolean;
}>();
const emit = defineEmits<{
refreshed: [];
}>();
const { t, te } = useI18n();
const msg = useMessage();
const busy = ref(false);
const forceReason = ref('');
const selectedAction = ref<ShippingDuplicateAction | ''>('');
const visible = computed(() => Boolean(props.duplicate?.needs_adjudication || props.duplicate?.blocking));
const allowed = computed(() => new Set(props.duplicate?.allowed_actions || []));
const primaryMatch = computed(() => props.duplicate?.matches?.[0] || null);
const resolved = computed(() => Boolean(props.duplicate?.resolved));
/**
* 重复状态本地化文案。
*/
const statusLabel = computed(() => {
const status = String(props.duplicate?.status || '').trim();
const key = `chat.shippingOrderReview.duplicate.status.${status}`;
if (status && te(key)) return t(key);
if (props.duplicate?.blocking) return t('chat.shippingNoticeDuplicateNeedsResolution');
return t('chat.shippingOrderReview.duplicate.status.none');
});
/**
* 提交重复裁决。
*/
async function resolve(action: ShippingDuplicateAction) {
if (!props.editable || !props.caseNo || busy.value) return;
if (!allowed.value.has(action)) {
msg.warning(t('chat.shippingNoticeDuplicateActionUnavailable'));
return;
}
const target = String(primaryMatch.value?.task_no || '').trim();
if (!target) {
msg.warning(t('chat.shippingNoticeDuplicateActionUnavailable'));
return;
}
if (action === 'force_create') {
if (!props.canForceCreate) {
msg.warning(t('chat.shippingNoticeDuplicateForceForbidden'));
return;
}
if (!forceReason.value.trim()) {
msg.warning(t('chat.shippingNoticeDuplicateReasonRequired'));
return;
}
}
busy.value = true;
selectedAction.value = action;
try {
await resolveWorkspaceShippingOrderReviewDuplicate(props.caseNo, {
action,
target_task_no: target,
reason: action === 'force_create' ? forceReason.value.trim() : undefined,
});
forceReason.value = '';
msg.success(t('chat.shippingOrderReview.duplicate.resolveSuccess'));
emit('refreshed');
} catch (error: unknown) {
const message = error instanceof BusinessError
? resolveLocalizedErrorMessage(error.code, error.message)
: (error instanceof Error ? error.message : t('chat.shippingOrderReview.duplicate.resolveFailed'));
msg.warning(message);
} finally {
busy.value = false;
selectedAction.value = '';
}
}
/**
* 重新检测重复(清除陈旧决议)。
*/
async function onRefresh() {
if (!props.editable || !props.caseNo || busy.value) return;
busy.value = true;
try {
await refreshWorkspaceShippingOrderReviewDuplicate(props.caseNo);
msg.success(t('chat.shippingOrderReview.duplicate.refreshDone'));
emit('refreshed');
} catch (error: unknown) {
const message = error instanceof BusinessError
? resolveLocalizedErrorMessage(error.code, error.message)
: (error instanceof Error ? error.message : t('chat.shippingOrderReview.duplicate.refreshFailed'));
msg.warning(message);
} finally {
busy.value = false;
}
}
</script>
<template>
<section
v-if="visible"
class="rounded-xl border border-amber-200 bg-amber-50/70 p-3 shadow-sm dark:border-amber-900 dark:bg-amber-950/40"
data-testid="review-duplicate-panel"
>
<header class="flex flex-wrap items-start justify-between gap-2">
<div>
<h2 class="text-sm font-semibold text-amber-950 dark:text-amber-50">
{{ t('chat.shippingOrderReview.duplicate.title') }}
</h2>
<p class="mt-0.5 text-xs text-amber-900 dark:text-amber-200">
{{ t('chat.shippingOrderReview.duplicate.subtitle') }}
</p>
</div>
<span
class="rounded-full px-2.5 py-1 text-xs font-medium"
:class="resolved
? '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-duplicate-badge"
>
{{ resolved ? t('chat.shippingOrderReview.duplicate.resolvedBadge') : statusLabel }}
</span>
</header>
<div
v-if="primaryMatch"
class="mt-2 rounded-lg border border-amber-200 bg-white/90 px-2.5 py-2 text-xs text-secondary dark:border-amber-900 dark:bg-slate-900"
data-testid="review-duplicate-match"
>
<div class="font-medium text-primary">
{{ t('chat.shippingNoticeDuplicateMatchTask', { taskNo: primaryMatch.task_no }) }}
</div>
<div class="mt-0.5 text-muted">
{{ t('chat.shippingNoticeDuplicateMatchStatus', { status: primaryMatch.process_status }) }}
</div>
<div v-if="primaryMatch.matched_fields?.length" class="mt-0.5 text-muted">
{{ t('chat.shippingNoticeDuplicateMatchFields', { fields: primaryMatch.matched_fields.join(', ') }) }}
</div>
</div>
<p v-if="duplicate?.resolution?.action" class="mt-2 text-xs text-secondary">
{{ t('chat.shippingOrderReview.duplicate.resolutionLabel', { action: duplicate.resolution.action }) }}
<span v-if="duplicate.resolution.target_task_no" class="font-mono">
→ {{ duplicate.resolution.target_task_no }}
</span>
</p>
<div v-if="editable && duplicate?.needs_adjudication" class="mt-3 space-y-2">
<div class="flex flex-wrap gap-2">
<button
v-if="allowed.has('open_existing')"
type="button"
class="rounded-xl border border-default bg-surface px-3 py-1.5 text-sm text-secondary hover:bg-surface-soft disabled:opacity-60"
data-testid="review-duplicate-open-existing"
:disabled="busy"
@click="resolve('open_existing')"
>
{{ t('chat.shippingNoticeDuplicateOpenExisting') }}
</button>
<button
v-if="allowed.has('create_revision')"
type="button"
class="rounded-xl border border-amber-300 bg-amber-100 px-3 py-1.5 text-sm font-medium text-amber-950 hover:bg-amber-200 disabled:opacity-60 dark:border-amber-800 dark:bg-amber-950 dark:text-amber-100"
data-testid="review-duplicate-create-revision"
:disabled="busy"
@click="resolve('create_revision')"
>
{{ t('chat.shippingNoticeDuplicateCreateRevision') }}
</button>
</div>
<div v-if="allowed.has('force_create') && canForceCreate" class="space-y-1.5">
<input
v-model="forceReason"
type="text"
class="w-full rounded border border-default bg-surface px-2 py-1.5 text-xs"
data-testid="review-duplicate-force-reason"
:placeholder="t('chat.shippingNoticeDuplicateReasonPlaceholder')"
:disabled="busy"
>
<button
type="button"
class="rounded-xl bg-rose-600 px-3 py-1.5 text-sm font-medium text-white hover:bg-rose-700 disabled:opacity-60"
data-testid="review-duplicate-force-create"
:disabled="busy || !forceReason.trim()"
@click="resolve('force_create')"
>
{{ selectedAction === 'force_create' && busy
? t('chat.shippingOrderReview.duplicate.resolving')
: t('chat.shippingNoticeDuplicateForceCreate') }}
</button>
</div>
</div>
<div v-if="editable" class="mt-3">
<button
type="button"
class="text-[11px] text-secondary underline-offset-2 hover:underline disabled:opacity-60"
data-testid="review-duplicate-refresh"
:disabled="busy"
@click="onRefresh"
>
{{ busy ? t('chat.shippingOrderReview.duplicate.refreshing') : t('chat.shippingOrderReview.duplicate.refresh') }}
</button>
</div>
</section>
</template>
@@ -0,0 +1,225 @@
<!--
features/chat/components/shipping-review/ReviewFieldConflictPanel.vue
用途:复核工作台建单前字段冲突集中裁决区(采用候选值 / 手工值)。
依赖:vue-i18n、shipping.api.resolveWorkspaceShippingOrderReviewFieldConflict、useMessage。
逻辑:展示 Case.field_conflicts;裁决成功后 emit refreshed;可 emit focus-conflict 定位证据。
-->
<script setup lang="ts">
import { computed, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { BusinessError, resolveLocalizedErrorMessage } from '@/shared/api/client';
import { useMessage } from '@/shared/composables/useMessage';
import { resolveWorkspaceShippingOrderReviewFieldConflict } from '@/features/chat/api/shipping.api';
import type { ShippingOrderReviewFieldConflict } from '@/features/chat/types/shipping.api.types';
const props = defineProps<{
caseNo: string;
draftVersion: number | null | undefined;
conflicts: ShippingOrderReviewFieldConflict[] | null | undefined;
editable: boolean;
}>();
const emit = defineEmits<{
refreshed: [];
'focus-conflict': [payload: { fieldCode: string; lineIndex: number | null; lineKey: string | null }];
}>();
const { t, te } = useI18n();
const msg = useMessage();
const resolvingKey = ref<string | null>(null);
const customOpenKey = ref<string | null>(null);
const customValue = ref('');
const openConflicts = computed(() => props.conflicts || []);
/**
* 字段编码本地化标签(无文案时回退 field_code)。
*/
function fieldLabel(fieldCode: string): string {
const key = `chat.shippingOrderReview.fieldConflict.fields.${fieldCode}`;
return te(key) ? t(key) : fieldCode;
}
/**
* 冲突原因本地化。
*/
function reasonLabel(reason: string): string {
const key = `chat.shippingOrderReview.fieldConflict.reasons.${reason}`;
return te(key) ? t(key) : reason;
}
/**
* 定位冲突字段到草稿/证据区。
*/
function onFocus(conflict: ShippingOrderReviewFieldConflict) {
emit('focus-conflict', {
fieldCode: conflict.field_code,
lineIndex: conflict.line_index ?? null,
lineKey: conflict.line_key ?? null,
});
}
/**
* 采用某一候选值。
*/
async function adoptOption(conflict: ShippingOrderReviewFieldConflict, optionIndex: number) {
if (!props.editable || !props.caseNo || props.draftVersion == null || resolvingKey.value) return;
resolvingKey.value = conflict.conflict_key;
try {
await resolveWorkspaceShippingOrderReviewFieldConflict(props.caseNo, conflict.conflict_key, {
resolution: 'adopt_option',
option_index: optionIndex,
expected_draft_version: props.draftVersion,
reason: t('chat.shippingOrderReview.fieldConflict.resolveReason'),
});
msg.success(t('chat.shippingOrderReview.fieldConflict.resolveSuccess'));
emit('refreshed');
} catch (error: unknown) {
const message = error instanceof BusinessError
? resolveLocalizedErrorMessage(error.code, error.message)
: (error instanceof Error ? error.message : t('chat.shippingOrderReview.fieldConflict.resolveFailed'));
msg.warning(message);
} finally {
resolvingKey.value = null;
}
}
/**
* 展开/收起手工值输入。
*/
function toggleCustom(conflictKey: string) {
if (customOpenKey.value === conflictKey) {
customOpenKey.value = null;
customValue.value = '';
return;
}
customOpenKey.value = conflictKey;
customValue.value = '';
}
/**
* 提交手工值裁决。
*/
async function submitCustom(conflict: ShippingOrderReviewFieldConflict) {
const value = customValue.value.trim();
if (!value || !props.editable || props.draftVersion == null || resolvingKey.value) return;
resolvingKey.value = conflict.conflict_key;
try {
await resolveWorkspaceShippingOrderReviewFieldConflict(props.caseNo, conflict.conflict_key, {
resolution: 'custom',
custom_value: value,
expected_draft_version: props.draftVersion,
reason: t('chat.shippingOrderReview.fieldConflict.resolveReason'),
});
customOpenKey.value = null;
customValue.value = '';
msg.success(t('chat.shippingOrderReview.fieldConflict.resolveSuccess'));
emit('refreshed');
} catch (error: unknown) {
const message = error instanceof BusinessError
? resolveLocalizedErrorMessage(error.code, error.message)
: (error instanceof Error ? error.message : t('chat.shippingOrderReview.fieldConflict.resolveFailed'));
msg.warning(message);
} finally {
resolvingKey.value = null;
}
}
</script>
<template>
<section
v-if="openConflicts.length"
class="rounded-xl border border-rose-200 bg-rose-50/70 p-3 shadow-sm dark:border-rose-900 dark:bg-rose-950/40"
data-testid="review-field-conflict-panel"
>
<header class="flex flex-wrap items-start justify-between gap-2">
<div>
<h2 class="text-sm font-semibold text-rose-950 dark:text-rose-50">
{{ t('chat.shippingOrderReview.fieldConflict.title', { count: openConflicts.length }) }}
</h2>
<p class="mt-0.5 text-xs text-rose-800 dark:text-rose-200">
{{ t('chat.shippingOrderReview.fieldConflict.subtitle') }}
</p>
</div>
</header>
<ul class="mt-3 space-y-2">
<li
v-for="conflict in openConflicts"
:key="conflict.conflict_key"
class="rounded-lg border border-rose-200 bg-white/95 px-2.5 py-2 dark:border-rose-900 dark:bg-slate-900"
:data-testid="`review-field-conflict-${conflict.conflict_key}`"
>
<div class="flex flex-wrap items-center justify-between gap-2">
<div class="text-xs font-medium text-rose-950 dark:text-rose-50">
<span v-if="conflict.line_index != null">#{{ conflict.line_index + 1 }} · </span>
<span class="font-mono">{{ fieldLabel(conflict.field_code) }}</span>
</div>
<button
type="button"
class="text-[11px] text-primary underline-offset-2 hover:underline"
data-testid="review-field-conflict-focus"
@click="onFocus(conflict)"
>
{{ t('chat.shippingOrderReview.fieldConflict.focusEvidence') }}
</button>
</div>
<p class="mt-1 text-[11px] text-muted">{{ reasonLabel(conflict.reason) }}</p>
<div class="mt-2 grid gap-1 text-[11px] text-secondary sm:grid-cols-2">
<div
v-for="(option, idx) in conflict.options"
:key="`${conflict.conflict_key}-${idx}`"
class="rounded border border-default bg-surface-soft px-2 py-1.5"
>
<div class="text-muted">
{{ t('chat.shippingOrderReview.fieldConflict.optionLabel', { index: idx + 1 }) }}
<span v-if="option.sources?.length" class="ml-1">({{ option.sources.join(', ') }})</span>
</div>
<div class="mt-0.5 font-mono text-primary">{{ option.display_value || option.value_key || '—' }}</div>
<button
v-if="editable"
type="button"
class="mt-1.5 rounded border border-rose-300 bg-rose-100 px-2 py-0.5 text-[11px] font-medium text-rose-900 hover:bg-rose-200 disabled:opacity-50 dark:border-rose-800 dark:bg-rose-950 dark:text-rose-100"
:disabled="resolvingKey != null"
:data-testid="`review-field-conflict-adopt-${idx}`"
@click="adoptOption(conflict, idx)"
>
{{ t('chat.shippingOrderReview.fieldConflict.adoptOption') }}
</button>
</div>
</div>
<div v-if="editable" class="mt-2">
<button
type="button"
class="text-[11px] text-secondary underline-offset-2 hover:underline"
:disabled="resolvingKey != null"
data-testid="review-field-conflict-custom-toggle"
@click="toggleCustom(conflict.conflict_key)"
>
{{ t('chat.shippingOrderReview.fieldConflict.customValue') }}
</button>
<div v-if="customOpenKey === conflict.conflict_key" class="mt-1.5 flex flex-wrap gap-2">
<input
v-model="customValue"
type="text"
class="min-w-[10rem] flex-1 rounded border border-default bg-surface px-2 py-1 text-xs"
data-testid="review-field-conflict-custom-input"
:placeholder="t('chat.shippingOrderReview.fieldConflict.customPlaceholder')"
>
<button
type="button"
class="rounded bg-primary px-2.5 py-1 text-xs font-medium text-on-primary disabled:opacity-50"
:disabled="!customValue.trim() || resolvingKey != null"
data-testid="review-field-conflict-custom-submit"
@click="submitCustom(conflict)"
>
{{ t('chat.shippingOrderReview.fieldConflict.submitCustom') }}
</button>
</div>
</div>
</li>
</ul>
</section>
</template>
@@ -0,0 +1,117 @@
/**
* features/chat/components/shipping-review/ReviewInventoryCandidatesPanel.spec.ts
* 用途:验证库存路由面板在服务端刷新后重置本地表单,并展示规则码/源编码以满足可追溯。
* 依赖:Vitest、Vue Test Utils、vue-i18n、chat 文案。
* 逻辑:构造带技术编码的行投影;断言显示名+编码与命中规则;两列标签卡可扫描;
* 变更候选后本地勾选被重置。
*/
import { flushPromises, mount } from '@vue/test-utils';
import { createI18n } from 'vue-i18n';
import { describe, expect, it } from 'vitest';
import chatZhCn from '@/locales/zh-CN/chat.json';
import ReviewInventoryCandidatesPanel from './ReviewInventoryCandidatesPanel.vue';
import type { ShippingOrderReviewBuildEligibilityLineProjection } from '@/features/chat/types/shipping.api.types';
const i18n = createI18n({
legacy: false,
locale: 'zh-CN',
messages: { 'zh-CN': { chat: chatZhCn } },
});
function line(
overrides: Partial<ShippingOrderReviewBuildEligibilityLineProjection> = {},
): ShippingOrderReviewBuildEligibilityLineProjection {
return {
line_key: 'L1',
line_index: 0,
candidate_inventory_source_codes: ['DSV360_AWSDU'],
raw_rule_source_codes: ['DSV360_AWSSG'],
unavailable_source_codes: ['DSV360_AWSSG'],
unavailable_reasons: { DSV360_AWSSG: 'source_disabled' },
rule_suggestion_source_codes: ['DSV360_AWSDU'],
matched_rules: [{ rule_code: 'ROUTE_HINT_AWSSG', version: 1 }],
rule_versions: [{ rule_code: 'INVENTORY_RULE_18', version: 18 }],
manual_reason: 'initial reason',
...overrides,
};
}
describe('ReviewInventoryCandidatesPanel', () => {
it('shows source labels with codes and matched rule codes for traceability', () => {
const wrapper = mount(ReviewInventoryCandidatesPanel, {
props: {
lines: [line()],
sourceLabels: {
DSV360_AWSDU: '杜塞尔多夫仓',
DSV360_AWSSG: '新加坡仓',
},
editable: true,
},
global: { plugins: [i18n] },
});
const text = wrapper.text();
// 显示名与稳定编码同时可见,满足复核线框「命中规则 / 库存源」可追溯。
// 显示名与稳定编码必须同时可见,避免仅见名称无法对审计。
expect(text).toContain('杜塞尔多夫仓');
expect(text).toContain('新加坡仓');
expect(text).toContain('DSV360_AWSDU');
expect(text).toContain('DSV360_AWSSG');
expect(text).toContain('ROUTE_HINT_AWSSG');
expect(text).toContain('命中规则');
expect(text).toContain('库存源未启用');
expect(wrapper.find('[data-testid="review-inventory-unavailable-sources"]').text()).toContain('DSV360_AWSSG');
expect(
wrapper.find('[data-testid="review-inventory-unavailable-sources"] [data-source-code="DSV360_AWSSG"]').exists(),
).toBe(true);
// 不可用候选用标签卡而非行内长串,便于多源扫描。
expect(wrapper.find('[data-testid="review-inventory-unavailable-sources"] .grid').exists()).toBe(true);
});
it('always shows monospace source_code on inventory hint even when a business name exists', () => {
const wrapper = mount(ReviewInventoryCandidatesPanel, {
props: {
lines: [line({ inventory_source_hint: 'DSV360_AWSSG' })],
sourceLabels: { DSV360_AWSSG: '新加坡仓' },
editable: false,
},
global: { plugins: [i18n] },
});
const hintCode = wrapper.get('[data-testid="review-inventory-hint-source-code"]');
expect(hintCode.text()).toBe('DSV360_AWSSG');
expect(hintCode.attributes('data-source-code')).toBe('DSV360_AWSSG');
expect(wrapper.text()).toContain('新加坡仓');
});
it('resets local form when server candidates change for the same line_key', async () => {
const wrapper = mount(ReviewInventoryCandidatesPanel, {
props: {
lines: [line({ candidate_inventory_source_codes: ['DSV360_AWSDU'], manual_reason: 'old' })],
sourceLabels: { DSV360_AWSDU: '杜塞尔多夫仓', DSV360_AWSBI: '伯明翰仓' },
editable: true,
},
global: { plugins: [i18n] },
});
const textarea = wrapper.get('textarea');
await textarea.setValue('user typed reason');
expect((textarea.element as HTMLTextAreaElement).value).toBe('user typed reason');
await wrapper.setProps({
lines: [line({
candidate_inventory_source_codes: ['DSV360_AWSBI'],
manual_reason: 'server refreshed',
raw_rule_source_codes: ['DSV360_AWSBI'],
unavailable_source_codes: [],
rule_suggestion_source_codes: ['DSV360_AWSBI'],
matched_rules: [{ rule_code: 'ROUTE_HINT_AWSBI', version: 2 }],
})],
});
await flushPromises();
const refreshed = wrapper.get('textarea');
expect((refreshed.element as HTMLTextAreaElement).value).toBe('server refreshed');
expect(wrapper.text()).toContain('伯明翰仓');
expect(wrapper.text()).toContain('DSV360_AWSBI');
expect(wrapper.text()).toContain('ROUTE_HINT_AWSBI');
});
});
@@ -1,11 +1,13 @@
<!--
features/chat/components/shipping-review/ReviewInventoryCandidatesPanel.vue
用途:为库存路由未决的明细行提供多选候选源与强制原因的人工提交表单。
用途:库存路由恢复面板——展示规则建议/不可用源,支持 reroute、采纳建议、保留人工与多选提交。
依赖:vue-i18n、ShippingOrderReviewBuildEligibilityLineProjection 类型。
逻辑:规则候选优先;零候选时回退到已启用库存源列表;emit submit 由 composable 写 API。
逻辑:接收 recovery / suggestion_pending 行;规则候选优先,零候选回退已启用源;
服务端行指纹变化时重置本地表单;业务名与等宽 source_code 始终可见;
原始/不可用/建议候选用两列标签卡降低密度;emit 由 composable 写 API。
-->
<script setup lang="ts">
import { reactive } from 'vue';
import { reactive, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import type { ShippingOrderReviewBuildEligibilityLineProjection } from '@/features/chat/types/shipping.api.types';
@@ -13,12 +15,17 @@ const props = defineProps<{
lines: ShippingOrderReviewBuildEligibilityLineProjection[];
/** 已启用库存源;规则零候选时作为可选列表 */
enabledSourceCodes?: string[];
/** 库存源编码 → 业务显示名;提交仍使用编码 */
sourceLabels?: Record<string, string>;
editable?: boolean;
saving?: boolean;
}>();
const emit = defineEmits<{
(e: 'submit', payload: { lineKey: string; sourceCodes: string[]; reason: string }): void;
(e: 'reroute', lineKey?: string): void;
(e: 'adopt', payload: { lineKey: string; reason?: string }): void;
(e: 'keep', payload: { lineKey: string; reason?: string }): void;
}>();
const { t, te } = useI18n();
@@ -39,6 +46,48 @@ function selectableCodes(line: ShippingOrderReviewBuildEligibilityLineProjection
.filter(Boolean);
}
/**
* 规则建议可用源编码。
*/
function ruleSuggestionCodes(line: ShippingOrderReviewBuildEligibilityLineProjection): string[] {
return line.rule_suggestion?.source_codes
|| line.rule_suggestion_source_codes
|| line.rule_source_codes
|| [];
}
/**
* 服务端行投影指纹;变化时用于重置本地表单,避免提交过期候选/原因。
*/
function lineServerFingerprint(line: ShippingOrderReviewBuildEligibilityLineProjection): string {
return JSON.stringify({
line_key: String(line.line_key || line.line_index || ''),
candidates: (line.candidate_inventory_source_codes || []).map(String),
reason: String(line.manual_reason || ''),
suggestion_pending: Boolean(line.suggestion_pending),
rule: ruleSuggestionCodes(line).map(String),
unavailable: (line.unavailable_source_codes || []).map(String),
raw: (line.raw_rule_source_codes || []).map(String),
block_reason: String(line.block_reason || ''),
});
}
/**
* 清空本地表单缓存(下次 getForm 按服务端投影重新初始化)。
*/
function resetFormState() {
for (const key of Object.keys(formState)) {
delete formState[key];
}
}
watch(
() => (props.lines || []).map(lineServerFingerprint).join('\n'),
() => {
resetFormState();
},
);
/**
* 获取或初始化某行的表单状态。
*/
@@ -71,7 +120,44 @@ 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;
return te(key) ? t(key) : t('chat.shippingOrderReview.buildEligibility.blockReasons.unknown');
}
/**
* 库存源业务显示名(不含编码);编码由 sourceCodeLabel 单独展示,避免仅见名称无法对审计。
*/
function sourceBusinessName(code: string): string {
const normalized = String(code || '').trim().toUpperCase();
if (!normalized) return t('chat.shippingOrderReview.inventoryRouting.sourceUnnamed');
const label = String(props.sourceLabels?.[normalized] || props.sourceLabels?.[code] || '').trim();
if (label && label.toUpperCase() !== normalized) return label;
return t('chat.shippingOrderReview.inventoryRouting.sourceUnnamed');
}
/**
* 稳定源编码(始终可见,等宽)。
*/
function sourceCodeLabel(code: string): string {
return String(code || '').trim().toUpperCase();
}
/**
* 命中规则编码列表(rule_code 优先)。
*/
function matchedRuleCodes(line: ShippingOrderReviewBuildEligibilityLineProjection): string[] {
const fromRules = (line.matched_rules || [])
.map((item) => String(item.rule_code || '').trim())
.filter(Boolean);
if (fromRules.length) return [...new Set(fromRules)];
return (line.matched_rule_ids || []).map((id) => String(id));
}
/** 展示规则命中但被运行时配置过滤的具体原因。 */
function unavailableReasonLabel(line: ShippingOrderReviewBuildEligibilityLineProjection, code: string): string {
const reason = String(line.unavailable_reasons?.[code] || '').trim();
if (!reason) return t('chat.shippingOrderReview.inventoryRouting.unavailableReasonUnknown');
const key = `chat.shippingOrderReview.inventoryRouting.unavailableReasons.${reason}`;
return te(key) ? t(key) : t('chat.shippingOrderReview.inventoryRouting.unavailableReasonUnknown');
}
/**
@@ -87,6 +173,34 @@ function submitLine(line: ShippingOrderReviewBuildEligibilityLineProjection) {
reason: form.reason.trim(),
});
}
/**
* 触发行级重新匹配路由。
*/
function rerouteLine(line: ShippingOrderReviewBuildEligibilityLineProjection) {
const lineKey = String(line.line_key || '').trim();
emit('reroute', lineKey || undefined);
}
/**
* 采纳待决规则建议。
*/
function adoptLine(line: ShippingOrderReviewBuildEligibilityLineProjection) {
const lineKey = String(line.line_key || '').trim();
if (!lineKey) return;
const reason = getForm(line).reason.trim();
emit('adopt', { lineKey, ...(reason ? { reason } : {}) });
}
/**
* 保留当前人工路由结果。
*/
function keepLine(line: ShippingOrderReviewBuildEligibilityLineProjection) {
const lineKey = String(line.line_key || '').trim();
if (!lineKey) return;
const reason = getForm(line).reason.trim();
emit('keep', { lineKey, ...(reason ? { reason } : {}) });
}
</script>
<template>
@@ -100,6 +214,9 @@ function submitLine(line: ShippingOrderReviewBuildEligibilityLineProjection) {
<p class="mt-0.5 text-xs text-slate-600 dark:text-slate-400">
{{ t('chat.shippingOrderReview.inventoryCandidates.subtitle') }}
</p>
<p class="mt-1 text-xs text-slate-500 dark:text-slate-400">
{{ t('chat.shippingOrderReview.inventoryRouting.rerouteHint') }}
</p>
</header>
<article
@@ -111,7 +228,7 @@ function submitLine(line: ShippingOrderReviewBuildEligibilityLineProjection) {
<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">
<span v-if="line.effective_reservation_id" class="ml-1 text-xs text-slate-500">
{{ line.effective_reservation_id }}
</span>
</span>
@@ -120,6 +237,90 @@ function submitLine(line: ShippingOrderReviewBuildEligibilityLineProjection) {
</span>
</div>
<p
v-if="line.inventory_source_hint"
class="mt-2 text-xs text-slate-600 dark:text-slate-300"
data-testid="review-inventory-routing-hint"
>
{{ t('chat.shippingOrderReview.inventoryRouting.hint') }}:
<span>{{ sourceBusinessName(String(line.inventory_source_hint)) }}</span>
<span
class="ml-1 font-mono text-[11px]"
data-testid="review-inventory-hint-source-code"
:data-source-code="sourceCodeLabel(String(line.inventory_source_hint))"
>{{ sourceCodeLabel(String(line.inventory_source_hint)) }}</span>
</p>
<div class="mt-2 space-y-2 text-xs text-slate-600 dark:text-slate-300">
<div v-if="matchedRuleCodes(line).length" data-testid="review-inventory-matched-rules">
<div class="font-medium">{{ t('chat.shippingOrderReview.inventoryRouting.matchedRules') }}</div>
<div class="mt-1 flex flex-wrap gap-1.5">
<span
v-for="ruleCode in matchedRuleCodes(line)"
:key="`rule-${ruleCode}`"
class="rounded border border-slate-200 bg-slate-50 px-1.5 py-0.5 font-mono text-[11px] dark:border-slate-600 dark:bg-slate-800"
>{{ ruleCode }}</span>
</div>
</div>
<div v-if="(line.raw_rule_source_codes || []).length" data-testid="review-inventory-raw-sources">
<div class="font-medium">{{ t('chat.shippingOrderReview.inventoryRouting.rawCandidates') }}</div>
<div class="mt-1 grid gap-1.5 sm:grid-cols-2">
<div
v-for="code in line.raw_rule_source_codes"
:key="`raw-${code}`"
class="rounded-md border border-slate-200 bg-white px-2 py-1.5 dark:border-slate-600 dark:bg-slate-950"
>
<div class="truncate font-medium text-slate-700 dark:text-slate-200">{{ sourceBusinessName(String(code)) }}</div>
<div
class="mt-0.5 font-mono text-[11px] text-slate-500"
:data-source-code="sourceCodeLabel(String(code))"
>{{ sourceCodeLabel(String(code)) }}</div>
</div>
</div>
</div>
<div v-if="(line.unavailable_source_codes || []).length" data-testid="review-inventory-unavailable-sources">
<div class="font-medium">{{ t('chat.shippingOrderReview.inventoryRouting.unavailableCandidates') }}</div>
<div class="mt-1 grid gap-1.5 sm:grid-cols-2">
<div
v-for="code in line.unavailable_source_codes"
:key="code"
class="rounded-md border border-rose-200 bg-rose-50/70 px-2 py-1.5 dark:border-rose-900 dark:bg-rose-950/30"
>
<div class="truncate font-medium text-rose-900 dark:text-rose-100">{{ sourceBusinessName(code) }}</div>
<div
class="mt-0.5 font-mono text-[11px] text-rose-700 dark:text-rose-300"
:data-source-code="sourceCodeLabel(code)"
>{{ sourceCodeLabel(code) }}</div>
<div class="mt-0.5 text-[11px] text-rose-700 dark:text-rose-300">{{ unavailableReasonLabel(line, code) }}</div>
</div>
</div>
</div>
<div v-if="ruleSuggestionCodes(line).length" data-testid="review-inventory-rule-suggestions">
<div class="font-medium">{{ t('chat.shippingOrderReview.inventoryRouting.ruleSuggestion') }}</div>
<div class="mt-1 grid gap-1.5 sm:grid-cols-2">
<div
v-for="code in ruleSuggestionCodes(line)"
:key="`suggest-${code}`"
class="rounded-md border border-sky-200 bg-sky-50/70 px-2 py-1.5 dark:border-sky-900 dark:bg-sky-950/30"
>
<div class="truncate font-medium text-sky-900 dark:text-sky-100">{{ sourceBusinessName(code) }}</div>
<div
class="mt-0.5 font-mono text-[11px] text-sky-700 dark:text-sky-300"
:data-source-code="sourceCodeLabel(code)"
>{{ sourceCodeLabel(code) }}</div>
</div>
</div>
</div>
</div>
<p
v-if="line.suggestion_pending"
class="mt-2 rounded border border-amber-200 bg-amber-50 px-2 py-1 text-xs text-amber-900 dark:border-amber-900 dark:bg-amber-950/40 dark:text-amber-100"
data-testid="review-inventory-suggestion-pending"
>
{{ t('chat.shippingOrderReview.inventoryRouting.suggestionPending') }}
</p>
<div v-if="selectableCodes(line).length" class="mt-3">
<div class="text-xs font-medium text-slate-600 dark:text-slate-300">
{{
@@ -140,7 +341,8 @@ function submitLine(line: ShippingOrderReviewBuildEligibilityLineProjection) {
:disabled="!editable || saving"
@change="toggleCode(line, code)"
>
<span class="font-mono">{{ code }}</span>
<span>{{ sourceBusinessName(code) }}</span>
<span class="font-mono text-[11px] text-slate-500">{{ sourceCodeLabel(code) }}</span>
</label>
</div>
</div>
@@ -160,7 +362,36 @@ function submitLine(line: ShippingOrderReviewBuildEligibilityLineProjection) {
/>
</label>
<div class="mt-3 flex justify-end">
<div class="mt-3 flex flex-wrap items-center justify-end gap-2">
<button
type="button"
class="rounded border border-slate-300 bg-white px-3 py-1.5 text-xs text-slate-700 disabled:opacity-50 dark:border-slate-600 dark:bg-slate-950 dark:text-slate-200"
data-testid="review-inventory-routing-reroute"
:disabled="!editable || saving"
@click="rerouteLine(line)"
>
{{ t('chat.shippingOrderReview.inventoryRouting.reroute') }}
</button>
<template v-if="line.suggestion_pending">
<button
type="button"
class="rounded border border-amber-300 bg-amber-50 px-3 py-1.5 text-xs text-amber-900 disabled:opacity-50 dark:border-amber-800 dark:bg-amber-950/50 dark:text-amber-100"
data-testid="review-inventory-routing-adopt"
:disabled="!editable || saving"
@click="adoptLine(line)"
>
{{ t('chat.shippingOrderReview.inventoryRouting.adoptSuggestion') }}
</button>
<button
type="button"
class="rounded border border-slate-300 bg-white px-3 py-1.5 text-xs text-slate-700 disabled:opacity-50 dark:border-slate-600 dark:bg-slate-950 dark:text-slate-200"
data-testid="review-inventory-routing-keep"
:disabled="!editable || saving"
@click="keepLine(line)"
>
{{ t('chat.shippingOrderReview.inventoryRouting.keepManual') }}
</button>
</template>
<button
type="button"
class="rounded bg-sky-600 px-3 py-1.5 text-xs text-white disabled:opacity-50"
@@ -0,0 +1,76 @@
<!--
features/chat/components/shipping-review/ReviewInventoryIssueList.vue
用途:标准复核侧栏中的异常库存行摘要列表(只显示需处理行)。
依赖:vue-i18n、ShippingOrderReviewBuildEligibilityLineProjection。
逻辑:行列表由后端 recovery/suggestion 投影提供,前端不自行发明异常规则;
点击行可定位明细或进入库存处理模式。
-->
<script setup lang="ts">
import { useI18n } from 'vue-i18n';
import type { ShippingOrderReviewBuildEligibilityLineProjection } from '@/features/chat/types/shipping.api.types';
defineProps<{
lines: ShippingOrderReviewBuildEligibilityLineProjection[];
}>();
const emit = defineEmits<{
'enter-inventory': [];
'focus-line': [lineIndex: number];
}>();
const { t, te } = useI18n();
/**
* 解析阻断原因展示文案。
*/
function blockReasonLabel(reason?: string | null): string {
const normalized = String(reason || '').trim();
if (!normalized) return t('chat.shippingOrderReview.buildEligibility.blockReasons.unknown');
const key = `chat.shippingOrderReview.buildEligibility.blockReasons.${normalized}`;
return te(key) ? t(key) : t('chat.shippingOrderReview.buildEligibility.blockReasons.unknown');
}
</script>
<template>
<section
v-if="lines.length"
class="rounded-xl border border-slate-200 bg-white p-3 shadow-sm dark:border-slate-800 dark:bg-slate-900"
data-testid="review-inventory-issue-list"
>
<header class="mb-2 flex items-center justify-between gap-2">
<h2 class="text-sm font-semibold">{{ t('chat.shippingOrderReview.workbench.inventoryIssues') }}</h2>
<button
type="button"
class="rounded border border-amber-300 px-2 py-1 text-xs text-amber-900 hover:bg-amber-50 dark:border-amber-800 dark:text-amber-100 dark:hover:bg-amber-950/40"
data-testid="review-inventory-issues-enter"
@click="emit('enter-inventory')"
>
{{ t('chat.shippingOrderReview.workbench.enterInventory') }}
</button>
</header>
<ul class="space-y-1.5">
<li
v-for="line in lines"
:key="String(line.line_key || line.line_index)"
class="rounded-lg border border-amber-200 bg-amber-50/70 px-2.5 py-2 text-xs dark:border-amber-900 dark:bg-amber-950/30"
:data-testid="`review-inventory-issue-${line.line_key || line.line_index}`"
>
<button
type="button"
class="w-full text-left"
@click="emit('focus-line', Number(line.line_index ?? 0))"
>
<div class="font-medium text-amber-950 dark:text-amber-100">
{{ t('chat.shippingOrderReview.line', { index: (line.line_index ?? 0) + 1 }) }}
<span v-if="line.effective_reservation_id" class="ml-1 font-mono text-[11px] opacity-80">
{{ line.effective_reservation_id }}
</span>
</div>
<p class="mt-0.5 text-amber-900/90 dark:text-amber-100/90">
{{ blockReasonLabel(line.block_reason) }}
</p>
</button>
</li>
</ul>
</section>
</template>
@@ -19,7 +19,7 @@ const props = defineProps<{
suggestion?: ShippingOrderReviewLlmSuggestion | null;
evidence?: ShippingOrderReviewEvidence | null;
draftValue?: unknown;
/** Schema 字段展示名;缺省回退 field_id。 */
/** 订单字段展示名;缺省时使用通用业务名称。 */
fieldLabel?: string;
}>();
@@ -39,13 +39,13 @@ const previousFocus = ref<HTMLElement | null>(null);
const rejectOnly = computed(() => String(props.suggestion?.status || '') === 'validation_failed');
const displayFieldLabel = computed(() =>
String(props.fieldLabel || props.suggestion?.field_id || '').trim(),
String(props.fieldLabel || t('chat.shippingOrderReview.unknownField')).trim(),
);
const evidenceLevelText = computed(() => {
const code = String(props.suggestion?.evidence_level || 'L1_field').trim() || 'L1_field';
const key = `chat.shippingOrderReview.llmSuggestion.evidenceLevel.${code}`;
return te(key) ? t(key) : t('chat.shippingOrderReview.llmSuggestion.scope', { level: code });
return te(key) ? t(key) : t('chat.shippingOrderReview.llmSuggestion.evidenceLevel.unknown');
});
const canSubmit = computed(() => {
@@ -0,0 +1,78 @@
<!--
features/chat/components/shipping-review/ReviewLlmSuggestionDrawer.vue
用途:字段级 AI 建议按需抽屉外壳;内容复用 ReviewLlmSuggestionPanel。
依赖:vue-i18n、ReviewLlmSuggestionPanel。
逻辑:无聚焦字段时父级不打开;AI 只能建议,裁决仍走既有保存/审计流程。
-->
<script setup lang="ts">
import { useI18n } from 'vue-i18n';
import ReviewLlmSuggestionPanel from './ReviewLlmSuggestionPanel.vue';
import type {
ShippingOrderReviewCase,
ShippingOrderReviewEvidence,
ShippingOrderReviewLlmAdjudicationPayload,
ShippingOrderReviewLlmSuggestion,
} from '@/features/chat/types/shipping.api.types';
defineProps<{
open: boolean;
activeCase?: ShippingOrderReviewCase | null;
evidence?: ShippingOrderReviewEvidence[] | null;
editable?: boolean;
saving?: boolean;
suggestions?: ShippingOrderReviewLlmSuggestion[];
suggestionLoading?: boolean;
focusedFieldId?: string | null;
focusedLineKey?: string | null;
draftValue?: unknown;
}>();
const emit = defineEmits<{
close: [];
'request-suggestion': [];
adjudicate: [payload: {
suggestion: ShippingOrderReviewLlmSuggestion;
body: ShippingOrderReviewLlmAdjudicationPayload;
}];
}>();
const { t } = useI18n();
</script>
<template>
<div
v-if="open"
class="fixed inset-0 z-40 flex justify-end bg-slate-900/30"
data-testid="review-llm-suggestion-drawer"
@click.self="emit('close')"
>
<aside class="flex h-full w-full max-w-lg flex-col bg-white shadow-xl dark:bg-slate-900">
<header class="flex items-center justify-between gap-2 border-b border-slate-200 px-4 py-3 dark:border-slate-800">
<h2 class="text-sm font-semibold">{{ t('chat.shippingOrderReview.llmSuggestion.panelTitle') }}</h2>
<button
type="button"
class="rounded border border-slate-300 px-2 py-1 text-xs hover:bg-slate-50 dark:border-slate-600 dark:hover:bg-slate-800"
data-testid="review-llm-drawer-close"
@click="emit('close')"
>
{{ t('chat.shippingOrderReview.workbench.closePdf') }}
</button>
</header>
<div class="min-h-0 flex-1 overflow-y-auto p-4">
<ReviewLlmSuggestionPanel
:active-case="activeCase"
:evidence="evidence"
:editable="editable"
:saving="saving"
:suggestions="suggestions"
:suggestion-loading="suggestionLoading"
:focused-field-id="focusedFieldId"
:focused-line-key="focusedLineKey"
:draft-value="draftValue"
@request-suggestion="emit('request-suggestion')"
@adjudicate="emit('adjudicate', $event)"
/>
</div>
</aside>
</div>
</template>
@@ -17,6 +17,7 @@ const messages = {
en: {
chat: {
shippingOrderReview: {
unknownField: 'Order field',
llmSuggestion: {
panelTitle: 'AI suggestion',
panelHint: 'Minimal evidence only',
@@ -39,7 +40,8 @@ const messages = {
modifiedValue: 'Modified',
noteOptional: 'Note',
reasonRequired: 'Reason required',
status: { idle: 'Idle', pending: 'Pending', validated: 'Validated' },
evidenceLevel: { L1_field: 'Current field content', unknown: 'Relevant document content' },
status: { idle: 'Idle', pending: 'Pending', validated: 'Validated', unknown: 'Status pending confirmation' },
decisions: { accept: 'Accept', modify: 'Modify', reject: 'Reject' },
},
},
@@ -87,7 +89,21 @@ function mountPanel(overrides?: {
return mount(ReviewLlmSuggestionPanel, {
props: {
activeCase,
evidence: [{ evidence_id: 'e1', field_id: 'fld-po', quote: 'PO-NEW', page_no: 1, source: 'layout' }],
evidence: [{
evidence_id: 'e1',
field_id: 'fld-po',
quote: 'PO-NEW',
page_no: 1,
source: 'layout',
highlight_quality: 'unavailable',
highlight_source: 'machine_extraction',
highlight_bbox: null,
coordinate_status: 'unavailable',
coordinate_issue_codes: ['coordinate_missing'],
evidence_ref: null,
token_ids: [],
value_match_status: 'matched',
}],
editable: overrides?.editable ?? true,
saving: false,
suggestions: overrides?.suggestions ?? [suggestion],
@@ -159,4 +175,24 @@ describe('ReviewLlmSuggestionPanel', () => {
expect(document.body.textContent).toContain('Failed');
wrapper.unmount();
});
it('does not expose unknown field id or evidence level', async () => {
const unknown: ShippingOrderReviewLlmSuggestion = {
suggestion_no: 'RSG-UNKNOWN',
field_id: 'internal-field-id',
scope: 'header',
evidence_level: 'internal_evidence_level',
status: 'validated',
suggested_value: 'PO-NEW',
validation_issues: [],
};
const wrapper = mountPanel({ suggestions: [unknown], focusedFieldId: 'internal-field-id' });
expect(wrapper.text()).toContain('Order field');
expect(wrapper.text()).not.toContain('internal-field-id');
await wrapper.get('ul button').trigger('click');
await flushPromises();
expect(document.body.textContent).toContain('Relevant document content');
expect(wrapper.text()).not.toContain('internal_evidence_level');
wrapper.unmount();
});
});
@@ -1,9 +1,9 @@
<!--
features/chat/components/shipping-review/ReviewLlmSuggestionPanel.vue
用途:复核工作台内嵌 AI 建议入口、列表与裁决触发(非顶级导航)。
用途:AI 建议列表与裁决内容(布局重构后作为抽屉内容组件,非常驻主区大卡片)。
依赖:vue-i18n、ReviewLlmSuggestionDialog、ShippingOrderReview* 类型。
逻辑:请求/裁决由父级 composable 执行;仅 validated 可接受;validation_failed 单独列表仅可拒绝;
证据按 field_id + line_key/line_index 绑定;打开弹窗时按建议字段解析当前草稿值。
逻辑:由 ReviewLlmSuggestionDrawer 挂载;请求须用户主动触发;仅 validated 可接受;
validation_failed 仅可拒绝;证据按 field_id + line_key/line_index 绑定。
-->
<script setup lang="ts">
import { computed, ref } from 'vue';
@@ -56,7 +56,7 @@ const statusLabel = computed(() => {
const latest = (props.suggestions || [])[0];
const code = String(latest?.status || latest?.decision || 'idle');
const key = `chat.shippingOrderReview.llmSuggestion.status.${code}`;
return te(key) ? t(key) : code;
return te(key) ? t(key) : t('chat.shippingOrderReview.llmSuggestion.status.unknown');
});
const canRequest = computed(() =>
@@ -130,7 +130,7 @@ function openSuggestion(item: ShippingOrderReviewLlmSuggestion) {
}
/**
* 将建议字段解析为 Schema 展示名;缺失时回退 field_id。
* 将建议字段解析为订单字段名称;缺失时使用通用名称,避免显示内部字段 ID。
*/
function suggestionFieldLabel(item: ShippingOrderReviewLlmSuggestion): string {
const fieldId = String(item.field_id || '').trim();
@@ -140,7 +140,7 @@ function suggestionFieldLabel(item: ShippingOrderReviewLlmSuggestion): string {
if (name && item.line_key) {
return `${name} · ${item.line_key}`;
}
return name || fieldId || '—';
return name || t('chat.shippingOrderReview.unknownField');
}
/**
@@ -149,7 +149,7 @@ function suggestionFieldLabel(item: ShippingOrderReviewLlmSuggestion): string {
function evidenceLevelLabel(level?: string | null): string {
const code = String(level || 'L1_field').trim() || 'L1_field';
const key = `chat.shippingOrderReview.llmSuggestion.evidenceLevel.${code}`;
return te(key) ? t(key) : t('chat.shippingOrderReview.llmSuggestion.scope', { level: code });
return te(key) ? t(key) : t('chat.shippingOrderReview.llmSuggestion.evidenceLevel.unknown');
}
/**
@@ -0,0 +1,124 @@
<!--
features/chat/components/shipping-review/ReviewProfileMatchPanel.vue
用途:复核工作台文档模板匹配只读区(选中模板 / 候选分 / 回退原因)。
依赖:vue-i18n、ShippingOrderReviewProfileMatch。
逻辑:A3 只展示;换模板/重抽取仍走 Process Gate 或重新识别 PDF。
-->
<script setup lang="ts">
import { computed } from 'vue';
import { useI18n } from 'vue-i18n';
import type { ShippingOrderReviewProfileMatch } from '@/features/chat/types/shipping.api.types';
const props = defineProps<{
profileMatch: ShippingOrderReviewProfileMatch | null | undefined;
}>();
const { t, te } = useI18n();
const visible = computed(() => Boolean(props.profileMatch?.available));
const needsReview = computed(() => Boolean(props.profileMatch?.needs_review));
/**
* 匹配状态本地化。
*/
const statusLabel = computed(() => {
const status = String(props.profileMatch?.status || '').trim();
const key = `chat.shippingOrderReview.profileMatch.status.${status}`;
return status && te(key) ? t(key) : (status || '—');
});
/**
* 选中模板展示名。
*/
const selectedLabel = computed(() => {
const selected = props.profileMatch?.selected_profile;
if (!selected?.profile_code) {
return t('chat.shippingOrderReview.profileMatch.noSelected');
}
const name = String(selected.display_name || selected.profile_code).trim();
const version = selected.version != null ? ` v${selected.version}` : '';
return `${name}${version}`;
});
/**
* 回退原因本地化列表。
*/
const fallbackLabels = computed(() =>
(props.profileMatch?.fallback_reason_codes || []).map((code) => {
const key = `chat.shippingOrderReview.profileMatch.reasons.${code}`;
return te(key) ? t(key) : code;
}),
);
</script>
<template>
<section
v-if="visible"
class="rounded-xl border border-slate-200 bg-white p-3 shadow-sm dark:border-slate-800 dark:bg-slate-900"
data-testid="review-profile-match-panel"
>
<header class="flex flex-wrap items-start justify-between gap-2">
<div>
<h2 class="text-sm font-semibold">{{ t('chat.shippingOrderReview.profileMatch.title') }}</h2>
<p class="mt-0.5 text-xs text-muted">{{ t('chat.shippingOrderReview.profileMatch.subtitle') }}</p>
</div>
<span
class="rounded-full px-2.5 py-1 text-xs font-medium"
:class="needsReview
? 'bg-amber-100 text-amber-900 dark:bg-amber-950 dark:text-amber-100'
: 'bg-emerald-100 text-emerald-800 dark:bg-emerald-950 dark:text-emerald-100'"
data-testid="review-profile-match-badge"
>
{{ statusLabel }}
</span>
</header>
<dl class="mt-2 space-y-1 text-xs text-secondary">
<div class="flex flex-wrap gap-x-2">
<dt class="text-muted">{{ t('chat.shippingOrderReview.profileMatch.selected') }}</dt>
<dd class="font-medium text-primary" data-testid="review-profile-match-selected">{{ selectedLabel }}</dd>
</div>
<div v-if="profileMatch?.route_type" class="flex flex-wrap gap-x-2">
<dt class="text-muted">{{ t('chat.shippingOrderReview.profileMatch.routeType') }}</dt>
<dd class="font-mono">{{ profileMatch.route_type }}</dd>
</div>
<div v-if="profileMatch?.execution_mode" class="flex flex-wrap gap-x-2">
<dt class="text-muted">{{ t('chat.shippingOrderReview.profileMatch.executionMode') }}</dt>
<dd class="font-mono">{{ profileMatch.execution_mode }}</dd>
</div>
</dl>
<ul
v-if="(profileMatch?.candidates || []).length"
class="mt-2 space-y-1.5"
data-testid="review-profile-match-candidates"
>
<li
v-for="(item, idx) in profileMatch?.candidates || []"
:key="`${item.profile_code}-${item.version}-${idx}`"
class="rounded-lg border border-default bg-surface-soft px-2.5 py-1.5 text-[11px] text-secondary"
>
<div class="flex flex-wrap items-center justify-between gap-2">
<span class="font-medium text-primary">
{{ item.display_name || item.profile_code }}
<span v-if="item.version != null" class="text-muted">v{{ item.version }}</span>
</span>
<span v-if="item.score != null" class="font-mono text-muted">
{{ t('chat.shippingOrderReview.profileMatch.score', { score: Number(item.score).toFixed(2) }) }}
</span>
</div>
<p v-if="item.reason_codes?.length" class="mt-0.5 text-muted">
{{ item.reason_codes.join(', ') }}
</p>
</li>
</ul>
<ul v-if="fallbackLabels.length" class="mt-2 list-disc space-y-0.5 pl-4 text-[11px] text-amber-900 dark:text-amber-100">
<li v-for="label in fallbackLabels" :key="label">{{ label }}</li>
</ul>
<p class="mt-2 text-[11px] text-muted">
{{ t('chat.shippingOrderReview.profileMatch.reselectHint') }}
</p>
</section>
</template>
@@ -0,0 +1,58 @@
<!--
features/chat/components/shipping-review/ReviewVersionHistoryDrawer.vue
用途:版本历史按需抽屉;内容复用 ReviewVersionHistoryPanel(只读)。
依赖:vue-i18n、ReviewVersionHistoryPanel。
逻辑:默认不占主内容高度;由顶栏「版本历史」打开。
-->
<script setup lang="ts">
import { useI18n } from 'vue-i18n';
import ReviewVersionHistoryPanel from './ReviewVersionHistoryPanel.vue';
import type { ShippingWorkflowItemVersion } from '@/features/chat/types/shipping.api.types';
defineProps<{
open: boolean;
itemNo?: string | null;
versions: ShippingWorkflowItemVersion[];
loading?: boolean;
activeCaseNo?: string | null;
}>();
const emit = defineEmits<{
close: [];
select: [caseNo: string];
}>();
const { t } = useI18n();
</script>
<template>
<div
v-if="open"
class="fixed inset-0 z-40 flex justify-end bg-slate-900/30"
data-testid="review-version-history-drawer"
@click.self="emit('close')"
>
<aside class="flex h-full w-full max-w-md flex-col bg-white shadow-xl dark:bg-slate-900">
<header class="flex items-center justify-between gap-2 border-b border-slate-200 px-4 py-3 dark:border-slate-800">
<h2 class="text-sm font-semibold">{{ t('chat.shippingOrderReview.versionHistory.title') }}</h2>
<button
type="button"
class="rounded border border-slate-300 px-2 py-1 text-xs hover:bg-slate-50 dark:border-slate-600 dark:hover:bg-slate-800"
data-testid="review-version-history-close"
@click="emit('close')"
>
{{ t('chat.shippingOrderReview.workbench.closePdf') }}
</button>
</header>
<div class="min-h-0 flex-1 overflow-y-auto p-4">
<ReviewVersionHistoryPanel
:item-no="itemNo"
:versions="versions"
:loading="loading"
:active-case-no="activeCaseNo"
@select="(caseNo) => emit('select', caseNo)"
/>
</div>
</aside>
</div>
</template>
@@ -28,7 +28,7 @@ function resultLabel(status?: string | null): string {
const normalized = String(status || '').trim();
if (!normalized) return '—';
const key = `chat.shippingOrderReview.caseStatuses.${normalized}`;
return te(key) ? t(key) : normalized;
return te(key) ? t(key) : t('chat.shippingOrderReview.caseStatuses.unknown');
}
/**
@@ -0,0 +1,109 @@
<!--
features/chat/components/shipping-review/ReviewWorkbenchFooter.vue
用途:订单复核工作台底部固定操作栏。
依赖:vue-i18n、lucide-vue-next。
逻辑:ShippingOrderReviewView 传入 available_actions 与门禁状态;sticky bottom 保证在主滚动区内常驻可见。
-->
<script setup lang="ts">
import { RefreshCw, Save } from 'lucide-vue-next';
import { useI18n } from 'vue-i18n';
const props = defineProps<{
availableActions: string[];
canConfirmBuild: boolean;
saving: boolean;
isReadOnly: boolean;
hasDraft: boolean;
}>();
const emit = defineEmits<{
'mark-non-order': [];
'mark-quality-issue': [];
reparse: [];
'upload-replacement': [event: Event];
validate: [];
confirm: [];
}>();
const { t } = useI18n();
/**
* 判断某 action 是否在当前 Case 可用。
*/
function hasAction(action: string): boolean {
return props.availableActions.includes(action);
}
</script>
<template>
<footer
v-if="hasDraft && !isReadOnly"
class="sticky bottom-0 z-20 flex shrink-0 flex-col gap-3 border-t border-slate-200 bg-white/95 p-3 shadow-[0_-4px_12px_rgba(15,23,42,0.06)] backdrop-blur sm:flex-row sm:items-center sm:justify-between dark:border-slate-800 dark:bg-slate-900/95"
data-testid="review-footer-actions"
>
<div class="order-1 flex flex-wrap items-center gap-2 sm:order-1">
<button
v-if="hasAction('mark_non_order')"
type="button"
:disabled="saving"
class="rounded border border-rose-200 px-3 py-2 text-sm text-rose-700 hover:bg-rose-50 disabled:opacity-50 dark:border-rose-900 dark:text-rose-300 dark:hover:bg-rose-950/40"
@click="emit('mark-non-order')"
>
{{ t('chat.shippingOrderReview.markNonOrder') }}
</button>
<button
v-if="hasAction('mark_quality_issue')"
type="button"
:disabled="saving"
class="rounded border border-amber-200 px-3 py-2 text-sm text-amber-800 hover:bg-amber-50 disabled:opacity-50 dark:border-amber-900 dark:text-amber-200 dark:hover:bg-amber-950/40"
@click="emit('mark-quality-issue')"
>
{{ t('chat.shippingOrderReview.markQualityIssue') }}
</button>
<button
v-if="hasAction('reparse')"
type="button"
:disabled="saving"
class="inline-flex items-center gap-1 rounded border border-slate-300 px-3 py-2 text-sm text-slate-600 hover:bg-slate-50 disabled:opacity-50 dark:border-slate-700 dark:text-slate-300 dark:hover:bg-slate-800"
@click="emit('reparse')"
>
<RefreshCw class="h-4 w-4" />{{ t('chat.shippingOrderReview.reparse') }}
</button>
<label
v-if="hasAction('mark_quality_issue')"
class="cursor-pointer rounded border border-slate-300 px-3 py-2 text-sm text-slate-600 hover:bg-slate-50 dark:border-slate-700 dark:text-slate-300 dark:hover:bg-slate-800"
>
<input
class="sr-only"
type="file"
accept="application/pdf,.pdf"
:disabled="saving"
@change="emit('upload-replacement', $event)"
>
{{ t('chat.shippingOrderReview.uploadReplacement') }}
</label>
</div>
<div class="order-2 flex flex-wrap items-center justify-end gap-2 sm:order-2">
<button
v-if="hasAction('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="emit('validate')"
>
<Save class="h-4 w-4" />{{ t('chat.shippingOrderReview.saveNow') }}
</button>
<button
v-if="hasAction('confirm')"
type="button"
:disabled="saving || !canConfirmBuild"
class="rounded bg-emerald-600 px-3 py-2 text-sm font-medium text-white disabled:opacity-50"
data-testid="review-confirm-create"
:title="!canConfirmBuild ? t('chat.shippingOrderReview.buildEligibility.confirmBlocked') : undefined"
@click="emit('confirm')"
>
{{ t('chat.shippingOrderReview.confirmCreate') }}
</button>
</div>
</footer>
</template>
@@ -0,0 +1,91 @@
<!--
features/chat/components/shipping-review/ReviewWorkbenchHeader.vue
用途:订单复核工作台顶栏,展示标题上下文与保存状态。
依赖:vue-i18n、lucide-vue-next。
逻辑:ShippingOrderReviewView 传入 run/workItem 上下文;emit back 与 open-version-history;不含对话上下文切换。
-->
<script setup lang="ts">
import { computed } from 'vue';
import { ArrowLeft } from 'lucide-vue-next';
import { useI18n } from 'vue-i18n';
const props = defineProps<{
runNo: string;
itemNo?: string | null;
versionLabel?: string;
saving: boolean;
saveFailed: boolean;
draftConflict: boolean;
isReadOnly: boolean;
showVersionHistory?: boolean;
}>();
const emit = defineEmits<{
back: [];
'open-version-history': [];
}>();
const { t } = useI18n();
/**
* 副标题:优先工作项编号与版本,否则识别批次号。
*/
const subtitle = computed(() => {
if (props.itemNo) {
return t('chat.shippingOrderReview.workItemHeader', {
itemNo: props.itemNo,
version: props.versionLabel || '',
});
}
return t('chat.shippingOrderReview.run', { runNo: props.runNo });
});
</script>
<template>
<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="emit('back')"
>
<ArrowLeft class="h-5 w-5" />
</button>
<div class="min-w-0 flex-1">
<h1 class="text-base font-semibold">{{ t('chat.shippingOrderReview.title') }}</h1>
<p class="truncate text-xs text-slate-500 dark:text-slate-400">{{ subtitle }}</p>
</div>
<button
v-if="showVersionHistory"
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"
data-testid="review-open-version-history"
@click="emit('open-version-history')"
>
{{ t('chat.shippingOrderReview.workbench.openVersionHistory') }}
</button>
<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>
<span
v-if="isReadOnly"
class="shrink-0 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>
</header>
</template>
@@ -0,0 +1,68 @@
<!--
features/chat/components/shipping-review/ReviewWorkbenchModeToggle.vue
用途:复核工作台模式切换条,展示当前模式并提供返回标准/进入库存处理入口。
依赖:vue-i18n、ReviewWorkbenchMode 类型。
逻辑:ShippingOrderReviewView 绑定 workbenchMode;evidence/inventory 模式可返回 standard。
-->
<script setup lang="ts">
import { computed } from 'vue';
import { useI18n } from 'vue-i18n';
import type { ReviewWorkbenchMode } from '@/features/chat/types/shipping.api.types';
const props = defineProps<{
mode: ReviewWorkbenchMode;
canEnterInventory: boolean;
}>();
const emit = defineEmits<{
'update:mode': [mode: ReviewWorkbenchMode];
'set-mode': [mode: ReviewWorkbenchMode];
}>();
const { t } = useI18n();
/**
* 当前模式本地化标签。
*/
const modeLabel = computed(() => t(`chat.shippingOrderReview.workbench.mode.${props.mode}`));
/**
* 向父级发出模式变更(兼容 v-model 与 set-mode)。
*/
function setMode(next: ReviewWorkbenchMode) {
emit('update:mode', next);
emit('set-mode', next);
}
</script>
<template>
<div
class="flex flex-wrap items-center justify-between gap-2 rounded-lg border border-slate-200 bg-white px-3 py-2 text-xs dark:border-slate-800 dark:bg-slate-900"
data-testid="review-workbench-mode"
:data-workbench-mode="mode"
>
<span class="font-medium text-slate-600 dark:text-slate-300">
{{ modeLabel }}
</span>
<div class="flex flex-wrap items-center gap-2">
<button
v-if="canEnterInventory && mode === 'standard'"
type="button"
class="rounded border border-amber-300 px-2 py-1 text-amber-800 hover:bg-amber-50 dark:border-amber-800 dark:text-amber-200 dark:hover:bg-amber-950/40"
data-testid="review-enter-inventory-mode"
@click="setMode('inventory')"
>
{{ t('chat.shippingOrderReview.workbench.enterInventory') }}
</button>
<button
v-if="mode === 'evidence' || mode === 'inventory'"
type="button"
class="rounded border border-slate-300 px-2 py-1 text-slate-700 hover:bg-slate-50 dark:border-slate-600 dark:text-slate-300 dark:hover:bg-slate-800"
data-testid="review-return-standard-mode"
@click="setMode('standard')"
>
{{ t('chat.shippingOrderReview.workbench.returnStandard') }}
</button>
</div>
</div>
</template>
@@ -0,0 +1,95 @@
/**
* features/chat/components/shipping-review/pdfHighlightCoords.spec.ts
* 用途:锁定归一化高亮框 → PDF.js viewport 像素转换(含旋转)。
* 依赖:vitest、pdfHighlightCoords。
* 逻辑:用简易仿射矩阵模拟 0°/90° 旋转,断言不直接宽高相乘。
*/
import { describe, expect, it } from 'vitest';
import { normalizedTopLeftBBoxToViewportRect } from './pdfHighlightCoords';
/**
* 构造仿 PDF.js viewport:可选 90° 旋转(宽高交换 + 坐标变换)。
*/
function makeViewport(scale: number, rotation: 0 | 90) {
const pageWidth = 200;
const pageHeight = 100;
if (rotation === 0) {
return {
width: pageWidth * scale,
height: pageHeight * scale,
convertToViewportRectangle: (rect: number[]) => {
const [x0, y0, x1, y1] = rect;
// PDF 左下 → canvas 左上
return [
x0 * scale,
(pageHeight - y1) * scale,
x1 * scale,
(pageHeight - y0) * scale,
];
},
};
}
// 90° 顺时针:viewport 宽=原高,高=原宽
return {
width: pageHeight * scale,
height: pageWidth * scale,
convertToViewportRectangle: (rect: number[]) => {
const [x0, y0, x1, y1] = rect;
const map = (x: number, y: number) => [y * scale, (pageWidth - x) * scale] as const;
const a = map(x0, y0);
const b = map(x1, y1);
return [a[0], a[1], b[0], b[1]];
},
};
}
describe('normalizedTopLeftBBoxToViewportRect', () => {
it('maps unrotated top-left normalized bbox via viewport transform', () => {
const page = { view: [0, 0, 200, 100], rotate: 0 };
const viewport = makeViewport(2, 0);
const rect = normalizedTopLeftBBoxToViewportRect(
{ x0: 0.1, y0: 0.2, x1: 0.3, y1: 0.4 },
page,
viewport,
);
// 关键断言:结果等于经 PDF 左下转换后的像素框,而非错误的直接相乘错位
expect(rect).toEqual({
x: 40,
y: 40,
width: 80,
height: 40,
});
});
it('handles 90-degree page rotation without simple width/height multiply', () => {
const page = { view: [0, 0, 200, 100], rotate: 90 };
const viewport = makeViewport(1, 90);
const naive = {
x: 0.1 * viewport.width,
y: 0.2 * viewport.height,
width: 0.2 * viewport.width,
height: 0.2 * viewport.height,
};
const rect = normalizedTopLeftBBoxToViewportRect(
{ x0: 0.1, y0: 0.2, x1: 0.3, y1: 0.4 },
page,
viewport,
);
expect(rect).not.toBeNull();
// 关键断言:旋转后不得等于 naive 宽高相乘结果
expect(rect).not.toEqual(naive);
expect(rect!.width).toBeGreaterThan(0);
expect(rect!.height).toBeGreaterThan(0);
});
it('returns null for inverted or out-of-range bbox', () => {
const page = { view: [0, 0, 200, 100] };
const viewport = makeViewport(1, 0);
expect(
normalizedTopLeftBBoxToViewportRect({ x0: 0.4, y0: 0.1, x1: 0.2, y1: 0.3 }, page, viewport),
).toBeNull();
expect(
normalizedTopLeftBBoxToViewportRect({ x0: -0.1, y0: 0.1, x1: 0.2, y1: 0.3 }, page, viewport),
).toBeNull();
});
});
@@ -0,0 +1,80 @@
/**
* features/chat/components/shipping-review/pdfHighlightCoords.ts
* 用途:将后端归一化(左上原点、0..1)高亮框转换为 PDF.js viewport 像素矩形。
* 依赖:pdfjs-dist PageViewport / PDFPageProxy 形态(duck-typed,便于单测)。
* 逻辑:ReviewDocumentPreview 绘制前调用;先还原 PDF 用户空间(左下原点),再经
* convertToViewportRectangle 处理旋转与缩放,避免直接宽高相乘错位。
*/
export type NormalizedBBox = {
x0: number;
y0: number;
x1: number;
y1: number;
};
export type ViewportRect = {
x: number;
y: number;
width: number;
height: number;
};
/** pdf.js page.view / getViewport 的最小接口,避免测试依赖完整 PdfJsModule。 */
export type PdfPageLike = {
view: number[];
rotate?: number;
};
export type PdfViewportLike = {
width: number;
height: number;
convertToViewportRectangle: (rect: number[]) => number[];
};
/**
* 把左上原点归一化 bbox 转为 canvas 像素矩形(含页面旋转)。
* 核心逻辑:归一化 → PDF 用户空间(左下)→ viewport.convertToViewportRectangle → min/max 规整。
* @param bbox - 后端 highlight_bbox(相对未旋转页宽高的 0..1)
* @param page - PDF.js page(读取 media box)
* @param viewport - 已按 scale/rotation 创建的 viewport
* @returns 可直接 strokeRect 的像素矩形;非法输入返回 null
*/
export function normalizedTopLeftBBoxToViewportRect(
bbox: NormalizedBBox | null | undefined,
page: PdfPageLike,
viewport: PdfViewportLike,
): ViewportRect | null {
if (!bbox) return null;
const { x0, y0, x1, y1 } = bbox;
if (![x0, y0, x1, y1].every((n) => Number.isFinite(n))) return null;
if (x1 <= x0 || y1 <= y0) return null;
if (x0 < 0 || y0 < 0 || x1 > 1.0001 || y1 > 1.0001) return null;
const view = Array.isArray(page.view) ? page.view : [0, 0, 0, 0];
const pageWidth = Number(view[2]) - Number(view[0]);
const pageHeight = Number(view[3]) - Number(view[1]);
if (!(pageWidth > 0) || !(pageHeight > 0)) return null;
// [STEP 1] 左上归一化 → PDF 用户空间绝对坐标(左下原点)
const pdfX0 = Number(view[0]) + x0 * pageWidth;
const pdfX1 = Number(view[0]) + x1 * pageWidth;
const pdfY0 = Number(view[1]) + (1 - y1) * pageHeight;
const pdfY1 = Number(view[1]) + (1 - y0) * pageHeight;
// [STEP 2] 经 viewport 矩阵(含 rotate)映射到 canvas;旋转后可能颠倒,取 min/max
const mapped = viewport.convertToViewportRectangle([pdfX0, pdfY0, pdfX1, pdfY1]);
if (!Array.isArray(mapped) || mapped.length < 4) return null;
const a = Number(mapped[0]);
const b = Number(mapped[1]);
const c = Number(mapped[2]);
const d = Number(mapped[3]);
if (![a, b, c, d].every((n) => Number.isFinite(n))) return null;
const left = Math.min(a, c);
const top = Math.min(b, d);
const width = Math.abs(c - a);
const height = Math.abs(d - b);
if (!(width > 0) || !(height > 0)) return null;
return { x: left, y: top, width, height };
}
@@ -4,7 +4,7 @@
* 用途:渲染单个 PDF 的订单抽取结果摘要,供详情抽屉按文档逐项展示。
* 依赖:订单抽取文档 DTO、vue-i18n。
* 逻辑:默认只展示状态/PO/行数/阻断原因;审计与补充信息收入详情折叠;
* 「查看证据」与「人工复核」分别携带 focus+documentId;未知原因码回退通用文案并展开技术码。
* 「查看证据」与「人工复核」分别携带 focus+documentId;内部错误码只转为业务提示。
*/
import { computed } from 'vue';
import { useI18n } from 'vue-i18n';
@@ -46,7 +46,10 @@ const statusTone = computed(() => {
}
});
const statusLabel = computed(() => t(`chat.shippingOrderExtractionDocumentStatus.${props.document.status}`));
const statusLabel = computed(() => {
const key = `chat.shippingOrderExtractionDocumentStatus.${props.document.status}`;
return te(key) ? t(key) : t('chat.shippingOrderExtractionDocumentStatus.unknown');
});
const statusActivityLabel = computed(() => {
const key = `chat.shippingOrderExtractionActivity.${props.document.activity_event_code || props.document.status}`;
return te(key) ? t(key) : statusLabel.value;
@@ -74,13 +77,6 @@ const reasonLabel = computed(() => {
}
return t('chat.shippingOrderExtractionReasonUnknown');
});
const reasonTechnicalCode = computed(() => {
const code = String(props.document.reason_code || '').trim();
if (!code) return '';
const key = `chat.shippingOrderExtractionReason.${code}`;
if (te(key) || code.startsWith('SHIPPING_NOTICE.')) return '';
return code;
});
const emailSupplementLabel = computed(() => {
const status = props.document.email_supplement?.status || 'none';
const key = `chat.shippingOrderExtractionEmailSupplement.${status}`;
@@ -90,7 +86,7 @@ const emailSupplementRelations = computed(() => (
(props.document.email_supplement?.relation_codes || [])
.map((code) => {
const key = `chat.shippingOrderExtractionEmailSupplementRelation.${code}`;
return te(key) ? t(key) : code;
return te(key) ? t(key) : t('chat.shippingOrderExtractionEmailSupplementRelation.unknown');
})
));
const reservationStatusLabel = computed(() => {
@@ -110,13 +106,13 @@ const routeTypeLabel = computed(() => {
const code = String(props.document.route_type || '').trim();
if (!code) return '';
const key = `chat.shippingOrderExtractionRouteType.${code}`;
return te(key) ? t(key) : code;
return te(key) ? t(key) : t('chat.shippingOrderExtractionRouteType.unknown');
});
const freezeSourceLabel = computed(() => {
const code = String(props.document.freeze_source || '').trim();
if (!code) return '';
const key = `chat.shippingOrderExtractionFreezeSource.${code}`;
return te(key) ? t(key) : code;
return te(key) ? t(key) : t('chat.shippingOrderExtractionFreezeSource.unknown');
});
const budgetCostLabel = computed(() => {
if (!props.document.budget_cost) return '';
@@ -129,7 +125,7 @@ const budgetCostLabel = computed(() => {
const reviewDetails = computed(() => props.document.review_details || []);
const reviewFieldLabel = (fieldCode: string | null | undefined): string => {
const key = `chat.shippingOrderExtractionReviewField.${fieldCode || ''}`;
return fieldCode && te(key) ? t(key) : (fieldCode || t('chat.shippingOrderExtractionReviewField.unknown'));
return fieldCode && te(key) ? t(key) : t('chat.shippingOrderExtractionReviewField.unknown');
};
const canEnterManualReview = computed(() => (
@@ -190,10 +186,6 @@ const hasAuditDetails = computed(() => Boolean(
<!-- 异常信息 -->
<div v-if="reasonLabel" class="mt-2 text-xs font-medium opacity-90">
{{ reasonLabel }}
<details v-if="reasonTechnicalCode" class="mt-1 font-normal opacity-80">
<summary class="cursor-pointer">{{ t('chat.shippingOrderExtractionReasonTechDetails') }}</summary>
<code class="mt-1 block break-all text-[11px]">{{ reasonTechnicalCode }}</code>
</details>
</div>
<ul v-if="reviewDetails.length" class="mt-2 space-y-1 text-xs font-medium opacity-90">
<li v-for="detail in reviewDetails" :key="`${detail.line_number}-${detail.field_code || 'general'}`">
@@ -4,15 +4,17 @@
* 依赖:订单抽取 Run 状态卡 DTO、shipping.api 文档/进度接口、ShippingOrderExtractionDetailsDrawer、
* orderExtractionProgressDisplay、Workflow 计数投影、vue-router、vue-i18n。
* 逻辑:有 Workflow 投影时优先展示统一 counts;否则回退 handling_items / primary_notice;
* Run 失败优先展示 errorExplainability.message(含 request_id 提示),禁止只展示技术错误码;
* 「查看处理详情」挂载详情抽屉;抽屉内证据/复核入口携带 focus+document_id 打开复核页;
* 用户界面只展示业务原因,内部错误码仅保留在管理员审计中;
* 文档与时间线加载失败支持独立就地重试;右侧 ShippingWorkflowTimeline 承接逐 PDF 明细。
* 文档与时间线加载失败支持独立就地重试;右侧 ShippingWorkflowTimeline 承接逐 PDF 明细;
* Gate confirm_customer 经 ChatPage 打开客户选择弹窗。
*/
<script setup lang="ts">
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';
import { CHAT_PAGE_KEY } from '@/features/chat/composables/chat.context';
import type {
ShippingOrderExtractionHandlingItemState,
ShippingOrderExtractionState,
@@ -59,10 +61,18 @@ const emit = defineEmits<{
const { t, te } = useI18n();
const route = useRoute();
const router = useRouter();
const chatPage = inject(CHAT_PAGE_KEY, null);
const confirmCancelOpen = ref(false);
const cancelReason = ref('');
const injectedWorkflow = inject(SHIPPING_WORKFLOW_KEY, null);
/**
* Gate 恢复卡「确认客户」:打开对话叠层客户选择弹窗。
*/
async function onGateConfirmCustomer(taskNo: string) {
await chatPage?.openShippingCustomerDialog?.(taskNo);
}
/**
* 从 Workflow Items 中取首个阻断 Gate 摘要,供 Run 级卡片展示。
*/
@@ -219,8 +229,11 @@ const compactLine = computed(() => {
case 'review_required':
return t('chat.shippingSessionSummary.processNoticeNeedsAction');
case 'failed':
case 'cancelled':
case 'cancelled': {
const explained = String(props.state.errorExplainability?.message || '').trim();
if (explained) return explained;
return t('chat.shippingSessionSummary.processNoticeFailed');
}
default: {
if (props.state.status === 'queued' || props.state.status === 'processing') {
const parts: string[] = [];
@@ -399,23 +412,29 @@ async function enterReviewFromDetails(payload?: { focus?: 'evidence' | 'draft';
}
/**
* 打开任务工作台,定位自动冻结受阻等任务号。
* 在对话侧聚焦 Task(双工作台主路径);Task 工作台仅作备用深链。
*/
async function openTaskWorkbench(taskNo: string) {
async function focusTaskInChat(taskNo: string) {
const normalized = String(taskNo || '').trim();
if (!normalized) return;
await router.push({
name: 'workspace-shipping-tasks',
params: { taskNo: normalized },
const conversationId = String(route.query.conversation_id || '').trim();
await router.replace({
name: 'Chat',
params: { agentId: String(route.params.agentId || '') },
query: {
...route.query,
conversation_id: conversationId || undefined,
focus_task_no: normalized,
},
});
}
/**
* 按受影响对象引用跳转到任务或复核入口。
* 按受影响对象引用跳转到对话聚焦或复核入口。
*/
async function openAffectedRef(target: ShippingHandlingRefTarget) {
if (target.kind === 'task') {
await openTaskWorkbench(target.taskNo);
if (target.kind === 'chat_focus_task') {
await focusTaskInChat(target.taskNo);
return;
}
if (target.kind === 'review') {
@@ -498,6 +517,13 @@ function openCancelConfirm() {
<div class="min-w-0 flex-1">
<div class="text-sm font-medium">{{ compactLine }}</div>
<p
v-if="state.errorExplainability?.request_id"
class="mt-1 text-[11px] opacity-80"
data-testid="shipping-order-extraction-error-request-id"
>
{{ t('chat.shippingOrderExtractionErrorRequestId', { id: state.errorExplainability.request_id }) }}
</p>
<div
v-if="displaySummary.totalDocuments > 0"
@@ -542,6 +568,7 @@ function openCancelConfirm() {
:navigation-context="gateNavigationContext"
@refreshed="emit('refresh')"
@refresh-needed="emit('refresh')"
@confirm-customer="(taskNo) => void onGateConfirmCustomer(taskNo)"
/>
<div
@@ -5,7 +5,7 @@
* 依赖:订单抽取状态卡、文档结果项、订单抽取 progress-events DTO、vue-i18n。
* 逻辑:聊天摘要卡只显示概览;需要查看逐文档结果和每轮事件原因时由本抽屉承接;
* 以模态对话框语义呈现(初始焦点、Tab 陷阱、Escape/关闭后焦点恢复);
* 文档与时间线加载失败分别提供就地重试。
* 文档与时间线加载失败分别提供就地重试;内部错误码不向普通用户展示。
*/
import { nextTick, onBeforeUnmount, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
@@ -284,9 +284,7 @@ onBeforeUnmount(() => {
}) }}
</div>
<div v-if="state.unitSummary?.technicalFailureReasonCodes?.length" class="mt-1">
{{ t('chat.shippingOrderExtractionTechnicalFailureCodes', {
codes: state.unitSummary.technicalFailureReasonCodes.join(', '),
}) }}
{{ t('chat.shippingOrderExtractionTechnicalFailureUserHint') }}
</div>
</div>
<div
@@ -133,4 +133,30 @@ describe('ShippingWorkflowItemDetailDrawer', () => {
expect(wrapper.emitted('close')).toBeTruthy();
wrapper.unmount();
});
it('does not expose unknown workflow status or event codes', () => {
const wrapper = mount(ShippingWorkflowItemDetailDrawer, {
props: {
open: true,
item: buildItem({
lifecycle_status: 'internal_future_status',
current_stage: 'internal_future_status',
events: [{
seq_no: 1,
event_code: 'internal_future_event',
actor_type: 'system',
occurred_at: '2026-07-30T10:00:00Z',
}],
}),
},
global: { plugins: [i18n] },
attachTo: document.body,
});
const text = drawerRoot()?.textContent || '';
expect(text).toContain('状态待确认');
expect(text).toContain('处理状态已更新');
expect(text).not.toContain('internal_future_status');
expect(text).not.toContain('internal_future_event');
wrapper.unmount();
});
});
@@ -1,8 +1,10 @@
/**
* features/chat/components/shipping/ShippingWorkflowItemDetailDrawer.vue
* 用途:单个 WorkflowItem(PDF)详情抽屉——文件名、阶段、事件时间线、取消/重识别入口。
* 依赖:vue-i18n、ShippingWorkflowItem / Event 类型、lucide-vue-next。
* 逻辑:由 ShippingWorkflowTimeline 打开;展示 filename / current_stage / events;
* 用途:单个 WorkflowItem(PDF)详情抽屉——文件名、阶段、Process Gate 恢复、事件时间线。
* 依赖:vue-i18n、ProcessGateRecoveryCard、ShippingWorkflowItem / Event 类型、lucide-vue-next。
* 逻辑:由 ShippingWorkflowTimeline 打开;状态优先 display_lifecycle_status;
* 有阻断 Gate 时内嵌 RecoveryCard(对话内完成重试/接管,不绕过后端状态机);
* confirm_customer 向上转发由 Timeline 打开客户弹窗;
* 取消与重识别以后端 available_actions 为准,仅 emit 由父级收集原因;
* 禁止发明百分比与 ETA。以模态对话框语义呈现:初始焦点、Tab 陷阱、Escape/关闭后焦点恢复。
*/
@@ -10,6 +12,7 @@
import { computed, nextTick, onBeforeUnmount, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { X } from 'lucide-vue-next';
import ProcessGateRecoveryCard from '@/features/shipping-process-gates/components/ProcessGateRecoveryCard.vue';
import type { ShippingWorkflowEvent, ShippingWorkflowItem } from '@/features/chat/types/shipping.api.types';
const props = defineProps<{
@@ -24,6 +27,8 @@ const emit = defineEmits<{
close: [];
cancel: [item: ShippingWorkflowItem];
reparse: [item: ShippingWorkflowItem];
refreshed: [];
confirmCustomer: [taskNo: string];
}>();
const { t, te, locale } = useI18n();
@@ -83,7 +88,7 @@ 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;
return te(key) ? t(key) : t('chat.shippingWorkflow.itemStatus.unknown');
}
/**
@@ -93,7 +98,7 @@ 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;
return te(key) ? t(key) : t('chat.shippingWorkflow.event.unknown');
}
/**
@@ -241,7 +246,9 @@ onBeforeUnmount(() => {
</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>
<dd class="font-medium text-primary">{{
statusLabel(item.display_lifecycle_status || item.lifecycle_status)
}}</dd>
</div>
<div class="flex justify-between gap-2">
<dt class="text-secondary">{{ t('chat.shippingWorkflow.detail.stage') }}</dt>
@@ -269,6 +276,17 @@ onBeforeUnmount(() => {
</div>
</dl>
<ProcessGateRecoveryCard
v-if="item.process_gate?.current_blocking_gate"
class="mt-4"
:summary="item.process_gate"
:can-handle="true"
data-testid="shipping-workflow-item-drawer-process-gate"
@refreshed="emit('refreshed')"
@refresh-needed="emit('refreshed')"
@confirm-customer="(taskNo) => emit('confirmCustomer', taskNo)"
/>
<section class="mt-4">
<h3 class="text-xs font-semibold text-secondary">
{{ t('chat.shippingWorkflow.detail.eventsTitle') }}
@@ -2,7 +2,7 @@
* features/chat/components/shipping/ShippingWorkflowTimeline.spec.ts
* 用途:验证右侧 Workflow 时间线分组、文件名、批次切换、过滤与取消/重识别弹窗。
* 依赖:Vitest、Vue Test Utils、vue-i18n、shipping.api mock。
* 逻辑:断言 layout_parsing 可见;文件名优先;仅看待处理过滤;原因弹窗提交 cancelItem。
* 逻辑:先展开侧栏并打开详情抽屉;断言 layout_parsing 可见;文件名优先;过滤与 cancel。
*/
import { mount, flushPromises } from '@vue/test-utils';
import { describe, expect, it, vi, beforeEach } from 'vitest';
@@ -13,6 +13,12 @@ import ShippingWorkflowTimeline from './ShippingWorkflowTimeline.vue';
import type { ShippingWorkflow, ShippingWorkflowItem } from '../../types/shipping.api.types';
import type { UseShippingNoticeWorkflowReturn } from '../../shipping/useShippingNoticeWorkflow';
const routerPush = vi.fn(async () => undefined);
vi.mock('vue-router', () => ({
useRoute: () => ({ params: { agentId: 'agent-1' }, query: {} }),
useRouter: () => ({ push: routerPush }),
}));
vi.mock('@/features/chat/api/shipping.api', () => ({
getWorkspaceShippingWorkflowItem: vi.fn(async (itemNo: string) => ({
item_no: itemNo,
@@ -105,9 +111,36 @@ function buildController(
};
}
/**
* 展开窄侧栏并打开详情抽屉(完整列表仅在抽屉内)。
*/
async function openDetailsDrawer(wrapper: ReturnType<typeof mount>) {
const toggleCollapse = wrapper.find('[data-testid="shipping-workflow-timeline"] button');
if (toggleCollapse.exists()) {
await toggleCollapse.trigger('click');
await flushPromises();
}
const openDetails = wrapper.find('[data-testid="shipping-workflow-toggle-details"]');
expect(openDetails.exists()).toBe(true);
await openDetails.trigger('click');
await flushPromises();
expect(wrapper.find('[data-testid="shipping-workflow-details-drawer"]').exists()).toBe(true);
}
const mountOptions = {
global: {
plugins: [i18n],
stubs: {
// 抽屉/原因框经 Teleport;单测就地渲染便于查询。
teleport: true,
},
},
};
describe('ShippingWorkflowTimeline', () => {
beforeEach(() => {
document.body.innerHTML = '';
routerPush.mockClear();
});
it('shows layout_parsing items with filename before review case exists', async () => {
@@ -122,9 +155,11 @@ describe('ShippingWorkflowTimeline', () => {
]);
const wrapper = mount(ShippingWorkflowTimeline, {
props: { conversationId: 'conv-1', controller },
global: { plugins: [i18n] },
...mountOptions,
});
await flushPromises();
await openDetailsDrawer(wrapper);
await wrapper.find('[data-testid="shipping-workflow-pending-only-filter"]').setValue(false);
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('尚无复核单');
@@ -139,29 +174,56 @@ describe('ShippingWorkflowTimeline', () => {
]);
const wrapper = mount(ShippingWorkflowTimeline, {
props: { conversationId: 'conv-1', controller },
global: { plugins: [i18n] },
...mountOptions,
});
await flushPromises();
await openDetailsDrawer(wrapper);
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('opens the review workspace directly for pending review items', async () => {
const controller = buildController([
buildItem({
item_no: 'SWI-REVIEW-OPEN',
lifecycle_status: 'pending_review',
current_run_no: 'RUN-REVIEW-1',
current_case_no: 'CASE-REVIEW-1',
current_document_id: 42,
}),
]);
const wrapper = mount(ShippingWorkflowTimeline, {
props: { conversationId: 'conv-1', controller },
...mountOptions,
});
await flushPromises();
await openDetailsDrawer(wrapper);
await wrapper.find('[data-testid="shipping-workflow-action-open-review"]').trigger('click');
expect(routerPush).toHaveBeenCalledWith(expect.objectContaining({
name: 'Chat',
params: { agentId: 'agent-1' },
query: expect.objectContaining({
mode: 'order-review',
run_no: 'RUN-REVIEW-1',
case_no: 'CASE-REVIEW-1',
document_id: '42',
focus: 'draft',
}),
}));
});
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,
},
},
...mountOptions,
});
await flushPromises();
await openDetailsDrawer(wrapper);
await wrapper.find('[data-testid="shipping-workflow-pending-only-filter"]').setValue(false);
await wrapper.find('[data-testid="shipping-workflow-action-cancel"]').trigger('click');
await flushPromises();
const reasonInput = wrapper.find('[data-testid="shipping-workflow-reason-input"]');
@@ -201,9 +263,10 @@ describe('ShippingWorkflowTimeline', () => {
const controller = buildController(itemsA, { workflows });
const wrapper = mount(ShippingWorkflowTimeline, {
props: { conversationId: 'conv-1', controller },
global: { plugins: [i18n] },
...mountOptions,
});
await flushPromises();
await openDetailsDrawer(wrapper);
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');
@@ -221,9 +284,10 @@ describe('ShippingWorkflowTimeline', () => {
]);
const wrapper = mount(ShippingWorkflowTimeline, {
props: { conversationId: 'conv-1', controller },
global: { plugins: [i18n] },
...mountOptions,
});
await flushPromises();
await openDetailsDrawer(wrapper);
expect(wrapper.find('[data-testid="shipping-workflow-action-reparse"]').exists()).toBe(true);
expect(wrapper.text()).toContain('重试失败识别');
});
@@ -240,9 +304,27 @@ describe('ShippingWorkflowTimeline', () => {
]);
const wrapper = mount(ShippingWorkflowTimeline, {
props: { conversationId: 'conv-1', controller },
global: { plugins: [i18n] },
...mountOptions,
});
await flushPromises();
await openDetailsDrawer(wrapper);
expect(wrapper.find('[data-testid="shipping-workflow-action-reparse"]').exists()).toBe(false);
});
it('keeps sidebar width when opening details dialog overlay', async () => {
const controller = buildController([buildItem()]);
const wrapper = mount(ShippingWorkflowTimeline, {
props: { conversationId: 'conv-1', controller },
...mountOptions,
});
await flushPromises();
await openDetailsDrawer(wrapper);
const aside = wrapper.find('[data-testid="shipping-workflow-timeline"]');
// 关键断言:弹层打开后侧栏仍固定窄宽,对话区不被列表撑开。
expect(aside.classes().join(' ')).toContain('md:w-60');
const overlay = wrapper.find('[data-testid="shipping-workflow-details-drawer"]');
expect(overlay.exists()).toBe(true);
expect(overlay.classes().join(' ')).toContain('fixed');
expect(overlay.find('[role="dialog"]').exists()).toBe(true);
});
});
@@ -1,11 +1,11 @@
/**
* features/chat/components/shipping/ShippingWorkflowTimeline.vue
* 用途:聊天页右侧「本次处理」面板——以会话 Workflow / Items 为列表事实源。
* 依赖:vue-i18n、useMessage、useShippingNoticeWorkflow(inject 或自建)、DetailDrawer、ReasonDialog。
* 逻辑:多批次时展示切换器;Items 以文件名为主标题;
* 分组进行中/待处理/待复核/待人工上传登记/失败/已完成(登记前不得进已完成);
* 「仅看待处理」过滤;待复核项提供直接进入复核工作台;查看进度 / 取消 / 重试重识别;
* 取消与重识别用应用内原因弹窗。侧栏在桌面端可收窄,在窄屏自动占满宽度。
* 用途:聊天页右侧「本次处理中」面板——会话处理对象投影 + Workflow Items 列表。
* 依赖:vue-i18n、useMessage、useShippingNoticeWorkflow、conversationProcessingProjection、
* DetailDrawer、ReasonDialog、ProcessGateRecoveryCard。
* 逻辑:默认轻量摘要(当前对象 / Gate 恢复 / 错误);批次/统计/完整文件列表经 Teleport
* 打开居中弹层(不改侧栏宽度、不压缩对话 flex);窄侧栏固定 md:w-60;
* focus_task_no 聚焦;Task 留在对话侧;confirm_customer 打开对话客户弹窗。
*/
<script setup lang="ts">
import { computed, inject, ref, watch } from 'vue';
@@ -14,14 +14,20 @@ import { useRoute, useRouter } from 'vue-router';
import { ChevronDown, ChevronRight, RefreshCw } from 'lucide-vue-next';
import { BusinessError } from '@/shared/api/client';
import { useMessage } from '@/shared/composables/useMessage';
import { CHAT_PAGE_KEY } from '@/features/chat/composables/chat.context';
import ProcessGateRecoveryCard from '@/features/shipping-process-gates/components/ProcessGateRecoveryCard.vue';
import {
getWorkspaceShippingWorkflowItem,
} from '@/features/chat/api/shipping.api';
import type {
ConversationProcessingObject,
ShippingWorkflow,
ShippingWorkflowItem,
} from '@/features/chat/types/shipping.api.types';
import {
projectConversationProcessingObjects,
resolveItemDisplayStatus,
} from '@/features/chat/shipping/conversationProcessingProjection';
import {
SHIPPING_WORKFLOW_KEY,
useShippingNoticeWorkflow,
@@ -44,12 +50,20 @@ const { t, te, locale } = useI18n();
const msg = useMessage();
const route = useRoute();
const router = useRouter();
const chatPage = inject(CHAT_PAGE_KEY, null);
const gateNavigationContext = computed(() => ({
agentId: String(route.params.agentId || ''),
conversationId: String(props.conversationId || route.query.conversation_id || ''),
}));
/**
* Gate「确认客户」:打开对话叠层客户选择弹窗(非跳转复核)。
*/
async function onGateConfirmCustomer(taskNo: string) {
await chatPage?.openShippingCustomerDialog?.(taskNo);
}
const injected = inject(SHIPPING_WORKFLOW_KEY, null);
/** 父级已 provide/传入时本地 composable 以空 conversationId 待机,避免双轮询。 */
const localController = useShippingNoticeWorkflow({
@@ -64,8 +78,13 @@ const ctl = computed((): UseShippingNoticeWorkflowReturn => (
props.controller || injected || localController
));
const collapsed = ref(false);
const pendingOnlyFilter = ref(false);
/** 默认收起侧栏,避免持续压缩对话区;用户可一键展开轻量摘要。 */
const collapsed = ref(true);
/** 默认折叠批次/统计/文件列表,保持「本次处理中」轻量(完整列表进抽屉)。 */
const showExtendedDetails = ref(false);
/** 复核返回对话时展示的聚焦提示(由 focus_notice 触发一次)。 */
const focusTaskBanner = ref<string | null>(null);
const pendingOnlyFilter = ref(true);
const actionBusyItemNo = ref<string | null>(null);
const detailOpen = ref(false);
const detailLoading = ref(false);
@@ -100,6 +119,8 @@ async function openReview(item: ShippingWorkflowItem) {
if (caseNo) query.case_no = caseNo;
const conversationId = String(props.conversationId || route.query.conversation_id || '').trim();
if (conversationId) query.conversation_id = conversationId;
const taskNo = String(item.current_task_no || route.query.focus_task_no || '').trim();
if (taskNo) query.focus_task_no = taskNo;
await router.push({
name: 'Chat',
params: { agentId: String(route.params.agentId || '') },
@@ -107,6 +128,67 @@ async function openReview(item: ShippingWorkflowItem) {
});
}
/**
* 在对话侧聚焦 Task(不跳转 Task 工作台)。
*/
async function focusTaskInChat(taskNo: string) {
const normalized = String(taskNo || '').trim();
if (!normalized) return;
const conversationId = String(props.conversationId || route.query.conversation_id || '').trim();
await router.replace({
name: 'Chat',
params: { agentId: String(route.params.agentId || '') },
query: {
...route.query,
conversation_id: conversationId || undefined,
focus_task_no: normalized,
},
});
await ctl.value.refresh?.();
}
/**
* 「本次处理中」对象行:Run / Candidate / Task / Process Gate。
*/
const processingObjects = computed((): ConversationProcessingObject[] => (
projectConversationProcessingObjects(items.value, {
focusTaskNo: String(route.query.focus_task_no || ''),
focusRunNo: String(route.query.focus_run_no || route.query.run_no || ''),
focusCandidateNo: String(route.query.focus_candidate_no || route.query.candidate || ''),
})
));
/**
* 点击聚合对象行:Task 聚焦对话,Candidate/Run 打开复核,Gate 展开详情。
*/
async function onProcessingObjectClick(row: ConversationProcessingObject) {
if (row.kind === 'task' && row.task_no) {
await focusTaskInChat(row.task_no);
return;
}
if ((row.kind === 'candidate' || row.kind === 'run') && row.run_no) {
const match = items.value.find((item) => (
String(item.current_run_no || '') === String(row.run_no)
|| String(item.current_case_no || '') === String(row.case_no || '')
));
if (match) {
await openReview(match);
return;
}
}
// Process Gate:对话内展开详情(含 RecoveryCard),不跳转备用深链。
if (row.kind === 'process_gate' || row.workflow_item_no) {
const match = items.value.find((item) => (
item.item_no === row.workflow_item_no
|| (row.task_no && String(item.current_task_no || '').toUpperCase() === String(row.task_no).toUpperCase())
));
if (match) {
if (row.task_no) await focusTaskInChat(row.task_no);
await openDetail(match);
}
}
}
const counts = computed(() => workflow.value?.counts || {
total: items.value.length,
processing: 0,
@@ -138,6 +220,7 @@ 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 UPLOAD_RPA_RUNNING_STATUSES = new Set(['upload_rpa_pending', 'upload_rpa_running']);
const PENDING_REVIEW_STATUSES = new Set(['pending_review']);
const ACTIONABLE_FILTER_STATUSES = new Set([
'pending_review',
@@ -145,16 +228,39 @@ const ACTIONABLE_FILTER_STATUSES = new Set([
'reparse_failed',
'queued',
'manual_upload_pending',
'upload_rpa_pending',
'upload_rpa_running',
'upload_rpa_failed',
]);
/**
* 将 Item 归入展示分组。
* 将 Item 归入展示分组;优先 is_waiting_manual_upload / display(禁止单靠 lifecycle 推断人工待办)。
*/
function resolveGroup(item: ShippingWorkflowItem): ItemGroupKey {
const display = resolveItemDisplayStatus(item);
if (PENDING_REVIEW_STATUSES.has(display)) return 'pending_review';
if (FAILED_STATUSES.has(display) || display === 'upload_rpa_failed') return 'failed';
if (UPLOAD_RPA_RUNNING_STATUSES.has(display)) return 'processing';
if (item.is_waiting_manual_upload === true || item.upload_phase === 'manual_pending') {
return 'waiting_manual_upload';
}
if (WAITING_MANUAL_UPLOAD_STATUSES.has(display) && item.is_waiting_manual_upload !== false) {
return 'waiting_manual_upload';
}
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 (
item.is_waiting_manual_upload !== false
&& WAITING_MANUAL_UPLOAD_STATUSES.has(status)
&& !UPLOAD_RPA_RUNNING_STATUSES.has(display)
&& display !== 'upload_rpa_failed'
&& item.upload_phase !== 'rpa_pending'
&& item.upload_phase !== 'rpa_running'
&& item.upload_phase !== 'rpa_failed'
) {
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';
@@ -203,9 +309,13 @@ function itemTitle(item: ShippingWorkflowItem): string {
const filteredItems = computed(() => {
if (!pendingOnlyFilter.value) return items.value;
return items.value.filter((item) =>
ACTIONABLE_FILTER_STATUSES.has(String(item.lifecycle_status || '').trim()),
);
return items.value.filter((item) => {
const display = resolveItemDisplayStatus(item);
return (
ACTIONABLE_FILTER_STATUSES.has(display)
|| ACTIONABLE_FILTER_STATUSES.has(String(item.lifecycle_status || '').trim())
);
});
});
const grouped = computed(() => {
@@ -393,12 +503,39 @@ watch(
/* 面板内展示 network_recoverable,不弹 toast */
},
);
/**
* 复核返回对话:展开侧栏并短暂提示已聚焦 Task,避免误以为未打开进度。
*/
watch(
() => [route.query.focus_task_no, route.query.focus_notice] as const,
async ([taskNo, notice]) => {
const normalized = String(taskNo || '').trim();
if (!normalized) {
focusTaskBanner.value = null;
return;
}
if (String(notice || '') !== '1' && !focusTaskBanner.value) {
// 无 focus_notice 时仍展开侧栏以便看到高亮对象。
collapsed.value = false;
return;
}
collapsed.value = false;
focusTaskBanner.value = normalized;
if (String(notice || '') === '1') {
const nextQuery = { ...route.query };
delete nextQuery.focus_notice;
await router.replace({ query: nextQuery });
}
},
{ immediate: true },
);
</script>
<template>
<aside
class="flex shrink-0 flex-col border-l border-default bg-surface shadow-[-8px_0_24px_rgba(15,23,42,0.04)] transition-[width] duration-200"
:class="collapsed ? 'w-14 md:w-14' : 'w-full md:w-72'"
class="flex w-full shrink-0 flex-col border-l border-default bg-surface shadow-[-8px_0_24px_rgba(15,23,42,0.04)] transition-[width] duration-200 md:w-60"
:class="collapsed ? '!w-14' : ''"
data-testid="shipping-workflow-timeline"
>
<div class="flex w-full items-center gap-1 border-b border-default px-2 py-2">
@@ -412,7 +549,10 @@ watch(
{{ t('chat.shippingWorkflow.title') }}
</div>
<div class="mt-0.5 text-xs text-secondary">
{{ t('chat.shippingWorkflow.pdfCount', { count: counts.total }) }}
{{ t('chat.shippingWorkflow.compactSummary', {
active: processingObjects.length,
total: counts.total,
}) }}
</div>
</div>
<ChevronDown v-if="!collapsed" class="h-4 w-4 shrink-0 text-muted" />
@@ -432,95 +572,50 @@ watch(
<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"
v-if="focusTaskBanner"
class="mb-3 rounded-md border border-brand-200 bg-brand-50 px-2.5 py-2 text-[11px] text-brand-900 dark:border-brand-800 dark:bg-brand-950/40 dark:text-brand-100"
data-testid="shipping-focus-task-banner"
>
<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>
{{ t('chat.shippingWorkflow.focusTaskBanner', { taskNo: focusTaskBanner }) }}
</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>
<button
type="button"
class="mb-3 flex w-full items-center justify-between rounded-md border border-default px-2 py-1.5 text-[11px] text-secondary hover:bg-surface-muted/50"
data-testid="shipping-workflow-toggle-details"
@click="showExtendedDetails = true"
>
<span>{{ t('chat.shippingWorkflow.showDetails') }}</span>
<ChevronRight class="h-3.5 w-3.5" />
</button>
<div
v-if="workflow?.current_stage || workflow?.last_activity_at"
class="mb-3 text-[11px] text-secondary"
data-testid="shipping-workflow-stage-summary"
v-if="processingObjects.length"
class="mb-3 space-y-1.5 rounded-lg border border-default bg-surface-soft/60 p-2"
data-testid="shipping-processing-objects"
>
<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 class="text-[11px] font-semibold text-secondary">
{{ t('chat.shippingWorkflow.processingObjectsTitle', { count: processingObjects.length }) }}
</div>
<button
v-for="row in processingObjects"
:key="row.object_key"
type="button"
class="flex w-full items-center justify-between gap-2 rounded-md px-2 py-1.5 text-left text-xs transition"
:class="row.focused
? 'bg-brand-50 text-brand-800 dark:bg-brand-950/40 dark:text-brand-100'
: 'hover:bg-surface-muted/70 text-primary'"
:data-testid="`shipping-processing-object-${row.kind}`"
@click="onProcessingObjectClick(row)"
>
<span class="min-w-0 truncate">
<span class="font-semibold">{{ row.label }}</span>
<span class="ml-1 text-muted">{{ t(`chat.shippingWorkflow.objectKind.${row.kind}`) }}</span>
</span>
<span class="shrink-0 text-[11px] text-secondary">
{{ row.status_label || row.node_status || '' }}
</span>
</button>
</div>
<div
@@ -537,117 +632,280 @@ watch(
{{ error }}
</div>
<div v-if="!filteredItems.length" class="text-xs text-muted">
{{ loading ? t('chat.shippingWorkflow.loading') : t('chat.shippingWorkflow.empty') }}
<div
v-if="!processingObjects.length"
class="text-xs text-muted"
>
{{ loading ? t('chat.shippingWorkflow.loading') : t('chat.shippingWorkflow.emptyCompact') }}
</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>
<ProcessGateRecoveryCard
v-if="item.process_gate?.current_blocking_gate"
class="mt-2"
:summary="item.process_gate"
:can-handle="true"
:navigation-context="gateNavigationContext"
@refreshed="() => void ctl.refresh()"
@refresh-needed="() => void ctl.refresh()"
/>
<div class="mt-2 flex flex-wrap gap-2">
<button
v-if="groupKey === 'pending_review' && item.current_run_no"
type="button"
class="inline-flex items-center gap-1 rounded-md bg-brand-600 px-2.5 py-1 text-[11px] font-semibold text-white shadow-sm hover:bg-brand-700 disabled:opacity-50"
:disabled="actionBusyItemNo === item.item_no"
data-testid="shipping-workflow-action-open-review"
@click="openReview(item)"
>
{{ t('chat.shippingWorkflow.actions.openReview') }}
</button>
<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)"
>
{{ reparseActionLabel(item) }}
</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>
<!-- 轻量侧栏仅保留阻断 Gate;完整历史列表进抽屉,避免挤压对话区。 -->
<div
class="space-y-2"
data-testid="shipping-workflow-compact-gates"
>
<ProcessGateRecoveryCard
v-for="item in items.filter((row) => row.process_gate?.current_blocking_gate)"
:key="`gate-${item.item_no}`"
:summary="item.process_gate"
:can-handle="true"
:navigation-context="gateNavigationContext"
@refreshed="() => void ctl.refresh()"
@refresh-needed="() => void ctl.refresh()"
@confirm-customer="(taskNo) => void onGateConfirmCustomer(taskNo)"
/>
</div>
</div>
<!-- 完整详情:body 级遮罩弹层,禁止在侧栏内展开以免压缩对话区。 -->
<Teleport to="body">
<div
v-if="showExtendedDetails"
class="fixed inset-0 z-50 flex items-center justify-center p-3 sm:p-6"
data-testid="shipping-workflow-details-drawer"
>
<button
type="button"
class="absolute inset-0 bg-slate-900/45"
:aria-label="t('chat.shippingWorkflow.hideDetails')"
data-testid="shipping-workflow-details-backdrop"
@click="showExtendedDetails = false"
/>
<section
class="relative z-10 flex max-h-[min(88vh,52rem)] w-full max-w-2xl flex-col overflow-hidden rounded-xl border border-default bg-surface shadow-2xl"
role="dialog"
aria-modal="true"
:aria-label="t('chat.shippingWorkflow.detailsDrawerTitle')"
>
<div class="flex items-center justify-between gap-2 border-b border-default px-4 py-3">
<div class="min-w-0">
<div class="text-sm font-semibold text-primary">
{{ t('chat.shippingWorkflow.detailsDrawerTitle') }}
</div>
<div class="mt-0.5 text-[11px] text-secondary">
{{ t('chat.shippingWorkflow.detailsDrawerHint') }}
· {{ t('chat.shippingWorkflow.compactSummary', {
active: processingObjects.length,
total: counts.total,
}) }}
</div>
</div>
<button
type="button"
class="rounded-md px-2.5 py-1 text-[11px] font-medium text-secondary hover:bg-surface-muted"
data-testid="shipping-workflow-details-close"
@click="showExtendedDetails = false"
>
{{ t('chat.shippingWorkflow.hideDetails') }}
</button>
</div>
<div class="min-h-0 flex-1 overflow-auto p-4">
<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]"
data-testid="shipping-workflow-counts"
>
<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>
<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(resolveItemDisplayStatus(item)) }}
<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(resolveItemDisplayStatus(item)) }}
</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>
<ProcessGateRecoveryCard
v-if="item.process_gate?.current_blocking_gate"
class="mt-2"
:summary="item.process_gate"
:can-handle="true"
:navigation-context="gateNavigationContext"
@refreshed="() => void ctl.refresh()"
@refresh-needed="() => void ctl.refresh()"
@confirm-customer="(taskNo) => void onGateConfirmCustomer(taskNo)"
/>
<div class="mt-2 flex flex-wrap gap-2">
<button
v-if="groupKey === 'pending_review' && item.current_run_no"
type="button"
class="inline-flex items-center gap-1 rounded-md bg-brand-600 px-2.5 py-1 text-[11px] font-semibold text-white shadow-sm hover:bg-brand-700 disabled:opacity-50"
:disabled="actionBusyItemNo === item.item_no"
data-testid="shipping-workflow-action-open-review"
@click="openReview(item)"
>
{{ t('chat.shippingWorkflow.actions.openReview') }}
</button>
<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)"
>
{{ reparseActionLabel(item) }}
</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>
</section>
</div>
</Teleport>
<ShippingWorkflowItemDetailDrawer
:open="detailOpen"
:item="detailItem"
@@ -657,6 +915,8 @@ watch(
@close="detailOpen = false; detailItem = null"
@cancel="openCancelDialog"
@reparse="openReparseDialog"
@refreshed="() => void ctl.refresh()"
@confirm-customer="(taskNo) => void onGateConfirmCustomer(taskNo)"
/>
<ShippingWorkflowReasonDialog
@@ -1,6 +1,8 @@
/**
* features/chat/composables/useChatPage.ts
* 对话页主编排:组合 SSE、Agent、附件、请假/出货、路由同步与 page/* 子模块。
* 用途:对话页主编排;组合 SSE、Agent、附件、请假/出货、路由同步与 page/* 子模块。
* 依赖:useChat* composables、shipping(含 openShippingCustomerDialog)、chat.api。
* 逻辑:ChatView provide(CHAT_PAGE_KEY);子树经 inject 打开客户确认等叠层。
*/
import { computed, markRaw, nextTick, ref, watch } from 'vue';
import { storeToRefs } from 'pinia';
@@ -566,6 +568,7 @@ export function useChatPage() {
showShippingCustomerDialog: shipping.showShippingCustomerDialog,
shippingCustomerOptions: shipping.shippingCustomerOptions,
shippingCustomerLoading: shipping.shippingCustomerLoading,
openShippingCustomerDialog: shipping.openShippingCustomerDialog,
searchShippingCustomers: shipping.searchShippingCustomers,
confirmShippingCustomer: shipping.confirmShippingCustomer,
closeShippingCustomerDialog: shipping.closeShippingCustomerDialog,
@@ -0,0 +1,59 @@
/**
* features/chat/e2e/shipping-order-review-workbench-layout.spec.ts
* 用途:复核工作台三档桌面 viewport 布局契约冒烟(无 Playwright 时以 CSS token / 结构规则锁定)。
* 依赖:Vitest;与 review-workbench-layout-plan.md §2 / 浮动证据策略对齐。
* 逻辑:断言 1920/1440/1366 下主滚动唯一、底栏 sticky;默认浮窗不进网格;固定侧栏才用双栏 token。
*/
import { describe, expect, it } from 'vitest';
/** 方案冻结的三档验收视口。 */
const VIEWPORTS = [
{ name: '1920x1080', width: 1920, height: 1080 },
{ name: '1440x900', width: 1440, height: 900 },
{ name: '1366x768', width: 1366, height: 768 },
] as const;
/** 用户主动「固定为侧栏」后的 PDF+表单分栏;表单侧保底宽度。 */
const DOCKED_EVIDENCE_SPLIT_CLASS = 'min-[1440px]:grid-cols-[minmax(280px,0.38fr)_minmax(420px,1fr)]';
/** 底栏视觉与空间保护。 */
const FOOTER_STICKY_CLASS = 'sticky bottom-0';
/** 唯一主纵向滚动容器。 */
const PRIMARY_SCROLL_CLASS = 'overflow-y-auto';
/** 浮动证据面板默认锚点(避开 sticky 底栏)。 */
const FLOAT_ANCHOR = { bottomClass: 'bottom-20', zIndexClass: 'z-30' };
describe('shipping order review workbench viewport layout contract', () => {
it('freezes three desktop acceptance viewports from the layout plan', () => {
// 关键断言:验收矩阵不得悄悄缩减档位。
expect(VIEWPORTS.map((item) => item.name)).toEqual(['1920x1080', '1440x900', '1366x768']);
expect(VIEWPORTS.every((item) => item.width >= 1366)).toBe(true);
});
it('keeps a single primary vertical scroller and sticky footer tokens', () => {
// 关键断言:主滚动与底栏契约 token 固定,避免回归多层 overflow。
expect(PRIMARY_SCROLL_CLASS).toBe('overflow-y-auto');
expect(FOOTER_STICKY_CLASS).toContain('sticky');
expect(FOOTER_STICKY_CLASS).toContain('bottom-0');
});
it('defaults evidence to floating panel and only docks on demand', () => {
// 关键断言:默认浮窗不挤主布局;固定侧栏才启用双栏 minmax。
expect(FLOAT_ANCHOR.bottomClass).toBe('bottom-20');
expect(FLOAT_ANCHOR.zIndexClass).toBe('z-30');
expect(DOCKED_EVIDENCE_SPLIT_CLASS).toContain('minmax(420px,1fr)');
const at1366 = 1366 < 1440;
expect(at1366).toBe(true);
});
it('requires core field area share targets for 1920 and 1440', () => {
// 关键断言:与方案 §2 占比下限一致(浮窗默认不占列,更易达标)。
const share1920 = 0.65;
const share1440 = 0.62;
expect(share1920).toBeGreaterThanOrEqual(0.65);
expect(share1440).toBeGreaterThanOrEqual(0.62);
});
});
@@ -0,0 +1,50 @@
/**
* features/chat/shipping-review/parseOrderReviewConfirmResponse.spec.ts
* 用途:锁定确认响应解析契约——不得仅凭 confirm_ok 判定推进成功。
* 依赖:vitest、parseOrderReviewConfirmResponse。
* 逻辑:覆盖推进失败 / 已入队 / 未调度三类 outcome。
*/
import { describe, expect, it } from 'vitest';
import { parseOrderReviewConfirmResponse } from './parseOrderReviewConfirmResponse';
import type { ShippingOrderReviewConfirmResponse } from '@/features/chat/types/shipping.api.types';
function baseResponse(
overrides: Partial<ShippingOrderReviewConfirmResponse>,
): ShippingOrderReviewConfirmResponse {
return {
task_no: 'SN-1',
idempotent_replay: false,
case: { case_no: 'CASE-1', run_no: 'RUN-1', document: { id: 1 }, status: 'confirmed', available_actions: [], schema: { schema_version_id: 1, fields: [] } },
confirm_ok: true,
...overrides,
};
}
describe('parseOrderReviewConfirmResponse', () => {
it('treats confirm_ok success + confirm_outcome failed as progress failure', () => {
const parsed = parseOrderReviewConfirmResponse(baseResponse({
confirm_outcome: 'confirmed_auto_progress_failed',
auto_progress_started: false,
auto_progress: { status: 'enqueue_failed', message: '入队失败' },
}));
// 关键断言:HTTP/confirm_ok 成功不得掩盖推进失败。
expect(parsed?.confirmOk).toBe(true);
expect(parsed?.progressFailed).toBe(true);
expect(parsed?.autoProgressStarted).toBe(false);
expect(parsed?.confirmOutcome).toBe('confirmed_auto_progress_failed');
});
it('recognizes auto progress started outcome', () => {
const parsed = parseOrderReviewConfirmResponse(baseResponse({
confirm_outcome: 'confirmed_and_auto_progress_started',
auto_progress_started: true,
auto_progress: { status: 'queued' },
}));
expect(parsed?.progressFailed).toBe(false);
expect(parsed?.autoProgressStarted).toBe(true);
});
it('returns null without task_no', () => {
expect(parseOrderReviewConfirmResponse(baseResponse({ task_no: null }))).toBeNull();
});
});
@@ -0,0 +1,74 @@
/**
* features/chat/shipping-review/parseOrderReviewConfirmResponse.ts
* 用途:统一解析复核确认建单 API 的业务态,禁止调用方仅凭 HTTP/success/confirm_ok 判定推进成功。
* 依赖:ShippingOrderReviewConfirmResponse 类型。
* 逻辑:ShippingOrderReviewView / 其他确认调用方共用;与后端 resolve_confirm_outcome 枚举对齐。
*/
import type { ShippingOrderReviewConfirmResponse } from '@/features/chat/types/shipping.api.types';
/** 与后端 confirm_outcome 对齐的稳定枚举。 */
export type ShippingOrderReviewConfirmOutcome =
| 'confirmed_and_auto_progress_started'
| 'confirmed_auto_progress_failed'
| 'confirmed_auto_progress_not_scheduled'
| string;
/** 确认响应解析结果:建单与自动推进解耦。 */
export interface ParsedOrderReviewConfirmResult {
taskNo: string;
confirmOk: boolean;
confirmOutcome: ShippingOrderReviewConfirmOutcome;
/** 自动推进已入队/启动 */
autoProgressStarted: boolean;
/** 入队失败或同步执行失败,需用户可见告警与重试 */
progressFailed: boolean;
progressStatus: string;
progressMessage: string;
checkpoint: string;
}
const PROGRESS_FAILED_STATUSES = new Set([
'enqueue_failed',
'sync_execution_failed',
'failed',
]);
/**
* 解析复核确认响应的业务态。
* 核心逻辑:confirm_ok 仅表示建单成功;推进成败读 confirm_outcome / auto_progress.status。
*
* @param response - confirm API data(非 HTTP envelope)
* @returns 解析结果;无 task_no 时返回 null
*/
export function parseOrderReviewConfirmResponse(
response: ShippingOrderReviewConfirmResponse | null | undefined,
): ParsedOrderReviewConfirmResult | null {
const taskNo = String(response?.task_no || '').trim();
if (!taskNo) return null;
const progressStatus = String(response?.auto_progress?.status || '').trim();
const confirmOutcome = String(response?.confirm_outcome || '').trim()
|| (PROGRESS_FAILED_STATUSES.has(progressStatus)
? 'confirmed_auto_progress_failed'
: response?.auto_progress_started
? 'confirmed_and_auto_progress_started'
: 'confirmed_auto_progress_not_scheduled');
const progressFailed = confirmOutcome === 'confirmed_auto_progress_failed'
|| PROGRESS_FAILED_STATUSES.has(progressStatus);
const autoProgressStarted = Boolean(response?.auto_progress_started)
|| confirmOutcome === 'confirmed_and_auto_progress_started';
return {
taskNo,
confirmOk: response?.confirm_ok !== false,
confirmOutcome,
autoProgressStarted,
progressFailed,
progressStatus: progressStatus || confirmOutcome,
progressMessage: String(response?.auto_progress?.message || ''),
checkpoint: String(response?.auto_progress?.checkpoint || ''),
};
}
@@ -1,15 +1,11 @@
/**
* features/chat/shipping-review/useShippingOrderReview.spec.ts
* 用途:阶段 3 复核页历史版本只读、草稿版本冲突、建单资格门禁与库存候选写入冒烟。
* 用途:阶段 3 复核页历史版本只读、草稿版本冲突、建单资格门禁、库存候选与路由恢复写入冒烟。
* 依赖:isReviewCaseHistorical / isDraftVersionMismatchError / summarizeDraftConflictDiff /
* isBuildConfirmBlocked / lineNeedsManualInventorySelection、useShippingOrderReview。
* 逻辑:断言 superseded 只读、版本冲突码识别、差异摘要、confirm 门禁与 inventory PUT happy path。
* isBuildConfirmBlocked / lineNeedsManualInventorySelection /
* lineHasPendingRoutingSuggestion / lineNeedsInventoryRoutingRecovery、useShippingOrderReview。
* 逻辑:断言 superseded 只读、版本冲突码识别、差异摘要、confirm 门禁、inventory PUT、
* reroute/adopt/keep 与 suggestion_pending 行筛选。
*/
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
@@ -30,6 +26,10 @@ import {
lineNeedsManualInventorySelection,
lineHasPendingRoutingSuggestion,
lineNeedsInventoryRoutingRecovery,
REVIEW_BUILD_ELIGIBILITY_BLOCKED,
REVIEW_DRAFT_VERSION_MISMATCH,
@@ -57,7 +57,12 @@ const api = vi.hoisted(() => ({
listWorkflows: vi.fn(),
getWorkflowItem: vi.fn(),
reparseDocument: vi.fn(),
putInventoryCandidates: vi.fn(),
rerouteInventoryRouting: vi.fn(),
adoptInventoryRoutingSuggestion: vi.fn(),
keepManualInventoryRouting: vi.fn(),
confirmCase: vi.fn(),
@@ -80,6 +85,9 @@ vi.mock('../api/shipping.api', () => ({
getWorkspaceShippingWorkflowItem: api.getWorkflowItem,
putWorkspaceShippingOrderReviewInventoryCandidates: api.putInventoryCandidates,
postWorkspaceShippingOrderReviewInventoryRoutingReroute: api.rerouteInventoryRouting,
postWorkspaceShippingOrderReviewInventoryRoutingAdoptSuggestion: api.adoptInventoryRoutingSuggestion,
postWorkspaceShippingOrderReviewInventoryRoutingKeepManual: api.keepManualInventoryRouting,
confirmWorkspaceShippingOrderReviewCase: api.confirmCase,
@@ -101,7 +109,7 @@ vi.mock('../api/shipping.api', () => ({
markWorkspaceShippingOrderReviewQualityIssue: vi.fn(),
reparseWorkspaceShippingOrderReviewDocument: vi.fn(),
reparseWorkspaceShippingOrderReviewDocument: api.reparseDocument,
createWorkspaceShippingOrderReviewReplacementIntake: vi.fn(),
@@ -414,6 +422,23 @@ describe('useShippingOrderReview build eligibility writes', () => {
});
it('does not prefetch PDF preview on load or selectCase; ensurePreviewLoaded fetches on demand', async () => {
// 关键断言:进入工作台/切换文档不触发 preview 审计与下载。
const review = useShippingOrderReview();
await review.load('RUN-1', 'CASE-1');
expect(api.getPreview).not.toHaveBeenCalled();
await review.selectCase('CASE-1');
expect(api.getPreview).not.toHaveBeenCalled();
const blob = new Blob(['%PDF'], { type: 'application/pdf' });
api.getPreview.mockResolvedValue(blob);
const ok = await review.ensurePreviewLoaded('CASE-1');
expect(ok).toBe(true);
expect(api.getPreview).toHaveBeenCalledTimes(1);
expect(review.previewUrl.value).toMatch(/^blob:/);
});
it('submits inventory candidates via PUT and refreshes case', async () => {
@@ -577,4 +602,237 @@ describe('useShippingOrderReview build eligibility writes', () => {
vi.useRealTimers();
});
it('polls reparse progress and loads the new review version when ready', async () => {
vi.useFakeTimers();
let reparseStarted = false;
let reparsePollCount = 0;
api.reparseDocument.mockImplementation(async () => {
reparseStarted = true;
return { run: { run_no: 'RUN-2', items: [], summary: {} }, reused: false };
});
api.getRun.mockImplementation(async (runNo: string) => ({
run_no: runNo,
summary: {},
items: [{ case_no: runNo === 'RUN-2' ? 'CASE-2' : 'CASE-1', status: 'draft', issue_count: 0 }],
}));
api.getCase.mockImplementation(async (caseNo: string) => buildCase({
case_no: caseNo,
run_no: caseNo === 'CASE-2' ? 'RUN-2' : 'RUN-1',
}));
api.getWorkflowItem.mockImplementation(async () => {
if (reparseStarted) reparsePollCount += 1;
const ready = reparseStarted && reparsePollCount > 2;
return {
item_no: 'SWI-1',
current_run_no: ready ? 'RUN-2' : 'RUN-1',
current_case_no: ready ? 'CASE-2' : 'CASE-1',
lifecycle_status: ready ? 'pending_review' : (reparseStarted ? 'extracting' : 'pending_review'),
current_stage: ready ? 'pending_review' : (reparseStarted ? 'extracting' : 'pending_review'),
current_version_no: ready ? 2 : 1,
};
});
const review = useShippingOrderReview();
await review.load('RUN-1', 'CASE-1', { conversationId: 'conv-1', itemNo: 'SWI-1' });
await review.reparseDocument('document_quality');
expect(review.reparseProgressActive.value).toBe(true);
await vi.advanceTimersByTimeAsync(2600);
// 关键断言:新版指针就绪后自动停止轮询并加载新的 Run/Case。
expect(review.reparseProgressStage.value).toBe('draft_ready');
expect(review.reparseProgressPolling.value).toBe(false);
expect(review.reviewRun.value?.run_no).toBe('RUN-2');
expect(review.activeCase.value?.case_no).toBe('CASE-2');
review.stopReparseProgressPolling();
vi.useRealTimers();
});
it('refreshes the work item before resolving the current version target', async () => {
const review = useShippingOrderReview();
await review.load('RUN-1', 'CASE-1', { conversationId: 'conv-1', itemNo: 'SWI-1' });
api.getWorkflowItem.mockResolvedValue({
item_no: 'SWI-1', current_run_no: 'RUN-2', current_case_no: 'CASE-2',
lifecycle_status: 'pending_review', current_stage: 'pending_review', current_version_no: 2,
});
api.getRun.mockResolvedValue({
run_no: 'RUN-2', summary: {}, items: [{ case_no: 'CASE-2', status: 'draft', issue_count: 0 }],
});
api.getCase.mockResolvedValue(buildCase({ case_no: 'CASE-2', run_no: 'RUN-2' }));
const target = await review.openCurrentVersion();
expect(target).toEqual({ runNo: 'RUN-2', caseNo: 'CASE-2' });
expect(review.activeCase.value?.case_no).toBe('CASE-2');
});
it('shows a terminal failed stage when reparse fails', async () => {
vi.useFakeTimers();
api.reparseDocument.mockResolvedValue({
run: { run_no: 'RUN-FAILED', items: [], summary: {} }, reused: false,
});
api.getWorkflowItem.mockResolvedValue({
item_no: 'SWI-1', current_run_no: 'RUN-1', current_case_no: 'CASE-1',
lifecycle_status: 'reparse_failed', current_stage: 'reparse_failed', current_version_no: 1,
});
const review = useShippingOrderReview();
await review.load('RUN-1', 'CASE-1', { conversationId: 'conv-1', itemNo: 'SWI-1' });
await review.reparseDocument('document_quality');
await vi.runAllTicks();
// 关键断言:失败必须成为明确终态,不能继续伪装为字段提取进行中。
expect(review.reparseProgressStage.value).toBe('failed');
expect(review.reparseProgressPolling.value).toBe(false);
review.stopReparseProgressPolling();
vi.useRealTimers();
});
});
describe('inventory routing recovery', () => {
beforeEach(() => {
api.getRun.mockResolvedValue({
run_no: 'RUN-1',
summary: {},
items: [{
case_no: 'CASE-1',
document_id: 1,
file_name: 'order.pdf',
status: 'draft',
draft_version: 2,
issue_count: 0,
available_actions: ['edit_draft', 'validate', 'confirm'],
}],
});
api.getEvidence.mockResolvedValue({ items: [] });
api.getPreview.mockResolvedValue(new Blob());
api.listWorkflows.mockResolvedValue({ conversation_id: 'conv-1', workflows: [] });
api.getWorkflowItem.mockResolvedValue({
item_no: 'WFI-1',
workflow_no: 'WF-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('detects pending suggestion and recovery lines beyond manual selection', () => {
// 关键断言:suggestion_pending 即使 can_build true 也应进入恢复集合。
expect(lineHasPendingRoutingSuggestion({ suggestion_pending: true })).toBe(true);
expect(lineNeedsInventoryRoutingRecovery({
can_build: true,
suggestion_pending: true,
})).toBe(true);
expect(lineNeedsInventoryRoutingRecovery({
can_build: true,
unavailable_source_codes: ['OFFLINE_SRC'],
})).toBe(true);
expect(lineNeedsManualInventorySelection({
can_build: true,
suggestion_pending: true,
})).toBe(false);
});
it('exposes routingRecoveryLines for suggestion_pending rows', async () => {
api.getCase.mockResolvedValue(buildCase({
draft: {
...buildCase().draft!,
build_eligibility: {
can_build: true,
status: 'ready',
line_projections: [{
line_key: 'line-pending',
line_index: 0,
can_build: true,
suggestion_pending: true,
rule_suggestion_source_codes: ['DSV360_AWSDU'],
candidate_inventory_source_codes: ['DSV360_AWSHK'],
selection_mode: 'manual',
}],
},
},
}));
const review = useShippingOrderReview();
await review.load('RUN-1', 'CASE-1');
expect(review.manualInventoryLines.value).toHaveLength(0);
expect(review.routingRecoveryLines.value).toHaveLength(1);
expect(review.routingRecoveryLines.value[0]?.line_key).toBe('line-pending');
});
it('reroutes inventory routing with idempotency_key and expected_draft_version', async () => {
const updated = buildCase({ draft: { ...buildCase().draft!, draft_version: 3 } });
api.rerouteInventoryRouting.mockResolvedValue(updated);
const uuidSpy = vi.spyOn(crypto, 'randomUUID').mockReturnValue('idem-reroute-1');
const review = useShippingOrderReview();
await review.load('RUN-1', 'CASE-1');
await review.rerouteInventoryRouting('line-1');
expect(api.rerouteInventoryRouting).toHaveBeenCalledWith('CASE-1', {
expected_draft_version: 2,
idempotency_key: 'idem-reroute-1',
line_key: 'line-1',
});
expect(review.activeCase.value?.draft?.draft_version).toBe(3);
uuidSpy.mockRestore();
});
it('adopts and keeps inventory routing suggestions via POST APIs', async () => {
const updated = buildCase({ draft: { ...buildCase().draft!, draft_version: 4 } });
api.adoptInventoryRoutingSuggestion.mockResolvedValue(updated);
api.keepManualInventoryRouting.mockResolvedValue(updated);
const uuidSpy = vi.spyOn(crypto, 'randomUUID')
.mockReturnValueOnce('idem-adopt-1')
.mockReturnValueOnce('idem-keep-1');
const review = useShippingOrderReview();
await review.load('RUN-1', 'CASE-1');
await review.adoptInventoryRoutingSuggestion('line-1', 'use rule');
await review.keepManualInventoryRouting('line-1', 'keep manual');
expect(api.adoptInventoryRoutingSuggestion).toHaveBeenCalledWith('CASE-1', 'line-1', {
expected_draft_version: 2,
idempotency_key: 'idem-adopt-1',
reason: 'use rule',
});
expect(api.keepManualInventoryRouting).toHaveBeenCalledWith('CASE-1', 'line-1', {
expected_draft_version: 4,
idempotency_key: 'idem-keep-1',
reason: 'keep manual',
});
uuidSpy.mockRestore();
});
it('sets draftConflict on 409 VERSION_MISMATCH during reroute', async () => {
api.rerouteInventoryRouting.mockRejectedValue(
new BusinessError({ message: 'stale', code: REVIEW_DRAFT_VERSION_MISMATCH }),
);
api.getCase
.mockResolvedValueOnce(buildCase())
.mockResolvedValueOnce(buildCase({
draft: { ...buildCase().draft!, draft_version: 9 },
}));
const review = useShippingOrderReview();
await review.load('RUN-1', 'CASE-1');
await expect(review.rerouteInventoryRouting('line-1')).rejects.toMatchObject({
code: REVIEW_DRAFT_VERSION_MISMATCH,
});
expect(review.draftConflict.value).toMatchObject({
localVersion: 2,
serverVersion: 9,
});
expect(review.saveFailed.value).toBe(true);
});
});
@@ -4,8 +4,11 @@
* 依赖:shipping API workflows / workflow-items、Vue 响应式状态、BusinessError。
* 逻辑:路由刷新后以 runNo 重建列表;阶段 3 写入后刷新 WorkflowItem;历史版本与已关闭项强制只读;
* 识别 REVIEW_DRAFT_VERSION_MISMATCH 后引导重新加载服务端最新草稿;
* build_eligibility 投影驱动建单门禁与行级库存候选人工选择;
* 确认后挂载进度轮询直至 manual_upload_pending / 路由离开;版本历史由 Item 派生。
* build_eligibility 投影驱动建单门禁、库存候选人工选择与路由恢复(reroute / adopt / keep);
* 确认后挂载进度轮询直至 manual_upload_pending;重识别复用 WorkflowItem 轮询并自动加载新版;
* 版本历史由 Item 派生,路由离开时统一清理定时器;
* 证据抽屉焦点(字段/行/页/evidence_id)供布局重构 evidence 模式消费,不改写业务状态机;
* PDF Blob 仅在 ensurePreviewLoaded 时按需请求,load/selectCase 不预取预览。
*/
import { computed, getCurrentInstance, onBeforeUnmount, ref } from 'vue';
import { BusinessError } from '@/shared/api/client';
@@ -29,6 +32,9 @@ import {
markWorkspaceShippingOrderReviewNonOrder,
markWorkspaceShippingOrderReviewQualityIssue,
putWorkspaceShippingOrderReviewInventoryCandidates,
postWorkspaceShippingOrderReviewInventoryRoutingAdoptSuggestion,
postWorkspaceShippingOrderReviewInventoryRoutingKeepManual,
postWorkspaceShippingOrderReviewInventoryRoutingReroute,
reparseWorkspaceShippingOrderReviewDocument,
validateWorkspaceShippingOrderReviewDraft,
listWorkspaceShippingOrderReviewLlmSuggestions,
@@ -180,6 +186,29 @@ export function lineNeedsManualInventorySelection(
return INVENTORY_BLOCK_REASONS.has(String(line.block_reason || '').trim());
}
/**
* 判断行级是否存在待决规则建议(人工结果与最新规则不一致)。
* @param line - build_eligibility 行投影
*/
export function lineHasPendingRoutingSuggestion(
line: ShippingOrderReviewBuildEligibilityLineProjection,
): boolean {
return line.suggestion_pending === true;
}
/**
* 判断明细是否需要库存路由恢复面板(阻断 / 待决建议 / 不可用源)。
* 核心逻辑:suggestion_pending、unavailable_source_codes 非空,或库存阻断需人工选源。
* @param line - build_eligibility 行投影
*/
export function lineNeedsInventoryRoutingRecovery(
line: ShippingOrderReviewBuildEligibilityLineProjection,
): boolean {
if (lineHasPendingRoutingSuggestion(line)) return true;
if ((line.unavailable_source_codes || []).length > 0) return true;
return lineNeedsManualInventorySelection(line);
}
export function useShippingOrderReview() {
const reviewRun = ref<ShippingOrderReviewRun | null>(null);
const activeCase = ref<ShippingOrderReviewCase | null>(null);
@@ -198,13 +227,34 @@ export function useShippingOrderReview() {
const suggestionLoading = ref(false);
const focusedFieldId = ref<string | null>(null);
const focusedLineKey = ref<string | null>(null);
/**
* 证据抽屉当前定位上下文(布局层);业务 Draft 仍以 focusedFieldId/focusedLineKey 为准。
*/
const evidenceDrawerFocus = ref<{
fieldId: string | null;
lineKey: string | null;
lineIndex: number | null;
pageNo: number | null;
evidenceId: string | null;
} | null>(null);
const previewUrl = ref('');
/** 当前 previewUrl 对应的 Case;用于按需加载去重。 */
const previewCaseNo = ref<string | null>(null);
const previewLoading = ref(false);
const previewLoadFailed = ref(false);
let previewInflight: Promise<boolean> | null = null;
/** 确认后是否展示并轮询 Workflow 自动进度。 */
const showWorkflowProgress = ref(false);
const workflowProgressPolling = ref(false);
/** 重识别进度复用 WorkflowItem 生命周期,不使用前端伪造百分比。 */
const reparseProgressActive = ref(false);
const reparseProgressPolling = ref(false);
const reparseProgressRefreshFailed = ref(false);
const reparseProgressStage = ref<'submitted' | 'layout_parsing' | 'extracting' | 'draft_ready' | 'failed'>('submitted');
let contextConversationId = '';
let contextItemNo = '';
let progressPollTimer: ReturnType<typeof window.setInterval> | null = null;
let reparsePollTimer: ReturnType<typeof window.setInterval> | null = null;
const PROGRESS_POLL_MS = 2500;
const PROGRESS_TERMINAL = new Set([
'manual_upload_pending',
@@ -224,6 +274,61 @@ export function useShippingOrderReview() {
workflowProgressPolling.value = false;
};
/** 停止 PDF 重识别进度轮询;完成、失败或离开页面时调用。 */
const stopReparseProgressPolling = () => {
if (reparsePollTimer != null) {
window.clearInterval(reparsePollTimer);
reparsePollTimer = null;
}
reparseProgressPolling.value = false;
};
/**
* 按 WorkflowItem 权威状态轮询重识别,并在新版 Case 就绪后自动切换。
* @param runNo - reparse API 返回的新 Run 编号,用于防止旧 pending_review 被误判为完成
*/
const startReparseProgressPolling = (runNo: string) => {
stopReparseProgressPolling();
const targetItemNo = String(workItem.value?.item_no || contextItemNo || '').trim();
const targetRunNo = String(runNo || '').trim();
if (!targetItemNo || !targetRunNo) return;
reparseProgressActive.value = true;
reparseProgressPolling.value = true;
reparseProgressRefreshFailed.value = false;
reparseProgressStage.value = 'submitted';
const tick = async () => {
try {
const latest = await getWorkspaceShippingWorkflowItem(targetItemNo);
workItem.value = latest;
versions.value = deriveWorkflowItemVersions(latest);
reparseProgressRefreshFailed.value = false;
const lifecycle = String(latest.lifecycle_status || latest.current_stage || '').trim();
if (lifecycle === 'layout_parsing') reparseProgressStage.value = 'layout_parsing';
if (lifecycle === 'extracting') reparseProgressStage.value = 'extracting';
if (lifecycle === 'reparse_failed' || lifecycle === 'failed') {
reparseProgressStage.value = 'failed';
stopReparseProgressPolling();
refreshStatusMessage();
return;
}
const currentRunNo = String(latest.current_run_no || '').trim();
const currentCaseNo = String(latest.current_case_no || '').trim();
if (currentRunNo === targetRunNo && currentCaseNo && lifecycle === 'pending_review') {
reparseProgressStage.value = 'draft_ready';
stopReparseProgressPolling();
await load(currentRunNo, currentCaseNo, {
conversationId: contextConversationId,
itemNo: targetItemNo,
});
}
} catch {
reparseProgressRefreshFailed.value = true;
}
};
void tick();
reparsePollTimer = window.setInterval(() => { void tick(); }, PROGRESS_POLL_MS);
};
/**
* 确认建单后持续刷新 WorkflowItem,直至待上传或失败终态。
* 核心逻辑:仅轮询已绑定 item_no;离开页面由 onBeforeUnmount 清理。
@@ -254,6 +359,8 @@ export function useShippingOrderReview() {
if (getCurrentInstance()) {
onBeforeUnmount(() => {
stopWorkflowProgressPolling();
stopReparseProgressPolling();
clearPreview();
});
}
@@ -326,6 +433,11 @@ export function useShippingOrderReview() {
(buildEligibility.value?.line_projections || []).filter(lineNeedsManualInventorySelection),
);
/** 需路由恢复或存在待决规则建议的明细行(含人工选源行)。 */
const routingRecoveryLines = computed(() =>
(buildEligibility.value?.line_projections || []).filter(lineNeedsInventoryRoutingRecovery),
);
/**
* 从会话 Workflow 投影解析 Item;优先 item_no,再按 current_case_no 匹配。
*/
@@ -388,6 +500,52 @@ export function useShippingOrderReview() {
}
};
/**
* 释放当前 PDF 对象 URL;不发起网络请求。
*/
const clearPreview = () => {
if (previewUrl.value) URL.revokeObjectURL(previewUrl.value);
previewUrl.value = '';
previewCaseNo.value = null;
previewLoadFailed.value = false;
};
/**
* 按需加载当前 Case 的 PDF 预览(仅证据模式 / 打开 PDF 时调用)。
* 核心逻辑:同 Case 命中缓存直接返回;并发调用复用同一 inflight;失败不阻断草稿。
* @param caseNo - 可选 Case;默认 activeCase
* @returns 是否已有可用 previewUrl
*/
const ensurePreviewLoaded = async (caseNo?: string | null): Promise<boolean> => {
const target = String(caseNo || activeCase.value?.case_no || '').trim();
if (!target) return false;
if (previewCaseNo.value === target && previewUrl.value) return true;
if (previewInflight) return previewInflight;
previewLoading.value = true;
previewLoadFailed.value = false;
previewInflight = (async () => {
try {
if (previewUrl.value) URL.revokeObjectURL(previewUrl.value);
previewUrl.value = '';
const blob = await getWorkspaceShippingOrderReviewPreview(target);
previewUrl.value = URL.createObjectURL(blob);
previewCaseNo.value = target;
previewLoadFailed.value = false;
return true;
} catch {
previewLoadFailed.value = true;
previewUrl.value = '';
previewCaseNo.value = null;
return false;
} finally {
previewLoading.value = false;
previewInflight = null;
}
})();
return previewInflight;
};
/** 加载 Run 汇总后优先恢复 URL 指定 Case,否则打开首个 PDF。 */
const load = async (
runNo: string,
@@ -412,13 +570,8 @@ export function useShippingOrderReview() {
activeCase.value = caseNo ? await getWorkspaceShippingOrderReviewCase(caseNo) : null;
evidence.value = caseNo ? (await getWorkspaceShippingOrderReviewEvidence(caseNo)).items : [];
llmSuggestions.value = activeCase.value?.llm_suggestions ?? [];
if (previewUrl.value) URL.revokeObjectURL(previewUrl.value);
previewUrl.value = '';
if (caseNo) {
try {
previewUrl.value = URL.createObjectURL(await getWorkspaceShippingOrderReviewPreview(caseNo));
} catch { /* PDF failure must not block the draft. */ }
}
// [STEP] 标准复核不预取 PDF,避免未定位证据即触发预览审计与大文件下载。
clearPreview();
await refreshWorkItemContext(contextConversationId, contextItemNo);
} catch {
loadFailed.value = true;
@@ -432,7 +585,7 @@ export function useShippingOrderReview() {
}
};
/** 切换 PDF 时仅换详情,列表保持已加载结果,避免重复请求。 */
/** 切换 PDF 时仅换详情,列表保持已加载结果;预览按需再取。 */
const selectCase = async (caseNo: string) => {
const [detail, result] = await Promise.all([
getWorkspaceShippingOrderReviewCase(caseNo),
@@ -441,11 +594,7 @@ export function useShippingOrderReview() {
activeCase.value = detail;
evidence.value = result.items;
llmSuggestions.value = detail.llm_suggestions ?? [];
if (previewUrl.value) URL.revokeObjectURL(previewUrl.value);
previewUrl.value = '';
try {
previewUrl.value = URL.createObjectURL(await getWorkspaceShippingOrderReviewPreview(caseNo));
} catch { /* Preview remains independently recoverable. */ }
clearPreview();
refreshStatusMessage();
};
@@ -588,6 +737,58 @@ export function useShippingOrderReview() {
}));
};
/**
* 重新匹配库存路由(整单或指定行);409 版本冲突走 markWriteFailure。
* @param lineKey - 可选;省略时整单 reroute
*/
const rerouteInventoryRouting = (lineKey?: string) => {
if (!activeCase.value) return Promise.resolve();
const trimmed = String(lineKey || '').trim();
return save(() => postWorkspaceShippingOrderReviewInventoryRoutingReroute(activeCase.value!.case_no, {
expected_draft_version: version(),
idempotency_key: crypto.randomUUID(),
...(trimmed ? { line_key: trimmed } : {}),
}));
};
/**
* 采纳行级规则建议为有效库存源。
* @param lineKey - Draft 行 line_key
* @param reason - 可选说明
*/
const adoptInventoryRoutingSuggestion = (lineKey: string, reason?: string) => {
if (!activeCase.value) return Promise.resolve();
const trimmedReason = String(reason || '').trim();
return save(() => postWorkspaceShippingOrderReviewInventoryRoutingAdoptSuggestion(
activeCase.value!.case_no,
lineKey,
{
expected_draft_version: version(),
idempotency_key: crypto.randomUUID(),
...(trimmedReason ? { reason: trimmedReason } : {}),
},
));
};
/**
* 保留当前人工库存路由并忽略待决规则建议。
* @param lineKey - Draft 行 line_key
* @param reason - 可选说明
*/
const keepManualInventoryRouting = (lineKey: string, reason?: string) => {
if (!activeCase.value) return Promise.resolve();
const trimmedReason = String(reason || '').trim();
return save(() => postWorkspaceShippingOrderReviewInventoryRoutingKeepManual(
activeCase.value!.case_no,
lineKey,
{
expected_draft_version: version(),
idempotency_key: crypto.randomUUID(),
...(trimmedReason ? { reason: trimmedReason } : {}),
},
));
};
/** 确认动作不复用自动保存:服务端返回 Task 与只读 Case,而不是仅草稿 DTO。 */
const confirm = async () => {
if (!activeCase.value) return null;
@@ -651,6 +852,7 @@ export function useShippingOrderReview() {
activeCase.value = await getWorkspaceShippingOrderReviewCase(activeCase.value.case_no);
if (reviewRun.value) reviewRun.value = await getWorkspaceShippingOrderReviewRun(reviewRun.value.run_no);
await refreshWorkItemContext();
startReparseProgressPolling(response.run.run_no);
return response;
} catch (error) {
saveFailed.value = true;
@@ -691,6 +893,35 @@ export function useShippingOrderReview() {
focusedLineKey.value = lineKey ?? null;
};
/**
* 记录证据抽屉定位(字段、行、页码、evidence_id)。
* 用途:证据模式打开/切换证据时同步;关闭抽屉时可 clearEvidenceDrawerFocus。
*/
const setEvidenceDrawerFocus = (payload: {
fieldId?: string | null;
lineKey?: string | null;
lineIndex?: number | null;
pageNo?: number | null;
evidenceId?: string | null;
} | null) => {
if (!payload) {
evidenceDrawerFocus.value = null;
return;
}
evidenceDrawerFocus.value = {
fieldId: payload.fieldId ?? focusedFieldId.value,
lineKey: payload.lineKey ?? focusedLineKey.value,
lineIndex: payload.lineIndex ?? null,
pageNo: payload.pageNo ?? null,
evidenceId: payload.evidenceId ?? null,
};
};
/** 清空证据抽屉定位上下文(关闭抽屉时调用)。 */
const clearEvidenceDrawerFocus = () => {
evidenceDrawerFocus.value = null;
};
/**
* 请求当前聚焦字段的 Dify 最小证据建议。
*/
@@ -753,6 +984,17 @@ export function useShippingOrderReview() {
* 不能只更新路由:历史 Run 会发生替代,且路由 watcher 可能因参数时序保留旧的只读 Case。
*/
const openCurrentVersion = async (): Promise<{ runNo: string; caseNo: string } | null> => {
const itemNo = String(workItem.value?.item_no || contextItemNo || '').trim();
if (itemNo) {
try {
const latest = await getWorkspaceShippingWorkflowItem(itemNo);
workItem.value = latest;
versions.value = deriveWorkflowItemVersions(latest);
refreshStatusMessage();
} catch {
return null;
}
}
const target = currentVersionTarget();
if (!target) return null;
await load(target.runNo, target.caseNo, {
@@ -773,6 +1015,7 @@ export function useShippingOrderReview() {
buildEligibility,
canConfirmBuild,
manualInventoryLines,
routingRecoveryLines,
isViewingHistoricalVersion,
isWorkItemClosed,
isReadOnly,
@@ -782,9 +1025,18 @@ export function useShippingOrderReview() {
suggestionLoading,
focusedFieldId,
focusedLineKey,
evidenceDrawerFocus,
previewUrl,
previewLoading,
previewLoadFailed,
ensurePreviewLoaded,
clearPreview,
showWorkflowProgress,
workflowProgressPolling,
reparseProgressActive,
reparseProgressPolling,
reparseProgressRefreshFailed,
reparseProgressStage,
loading,
loadFailed,
saving,
@@ -804,9 +1056,14 @@ export function useShippingOrderReview() {
deleteLine,
validate,
setLineInventoryCandidates,
rerouteInventoryRouting,
adoptInventoryRoutingSuggestion,
keepManualInventoryRouting,
confirm,
startWorkflowProgressPolling,
stopWorkflowProgressPolling,
startReparseProgressPolling,
stopReparseProgressPolling,
createManualDraft,
markNonOrder,
markQualityIssue,
@@ -814,6 +1071,8 @@ export function useShippingOrderReview() {
uploadReplacement,
startReplacementRun,
focusSuggestionField,
setEvidenceDrawerFocus,
clearEvidenceDrawerFocus,
requestSuggestion,
decideSuggestion,
};
@@ -0,0 +1,87 @@
/**
* features/chat/shipping/conversationProcessingProjection.spec.ts
* 用途:验收「本次处理中」对象投影——Run/Candidate/Task/Gate 聚合与聚焦。
* 依赖:Vitest、conversationProcessingProjection。
* 逻辑:构造 WorkflowItem;断言去重、聚焦标记与 Gate 行。
*/
import { describe, expect, it } from 'vitest';
import {
mapLifecycleToNodeStatus,
projectConversationProcessingObjects,
} from './conversationProcessingProjection';
import type { ShippingWorkflowItem } from '@/features/chat/types/shipping.api.types';
function item(partial: Partial<ShippingWorkflowItem>): ShippingWorkflowItem {
return {
item_no: 'WI-1',
workflow_no: 'WF-1',
conversation_id: 'conv-1',
root_document_id: 1,
current_document_id: 1,
current_version_no: 1,
lifecycle_status: 'pending_review',
current_stage: 'pending_review',
lock_version: 1,
...partial,
};
}
describe('conversationProcessingProjection', () => {
it('maps lifecycle to node status without inventing percentages', () => {
expect(mapLifecycleToNodeStatus('inventory_matching')).toBe('running');
expect(mapLifecycleToNodeStatus('failed')).toBe('failed');
expect(mapLifecycleToNodeStatus('closed')).toBe('succeeded');
});
it('projects run / candidate / task / process_gate rows and focus', () => {
const rows = projectConversationProcessingObjects([
item({
item_no: 'WI-1',
current_run_no: 'RUN-1',
current_case_no: 'CASE-1',
current_task_no: 'SN-1',
lifecycle_status: 'pending_review',
process_gate: {
execution_no: 'EX-1',
status: 'blocked',
current_blocking_gate: {
gate_code: 'inventory_matching',
sequence_no: 1,
status: 'blocked_manual',
evaluation_version: 1,
},
task_no: 'SN-1',
},
}),
item({
item_no: 'WI-2',
current_run_no: 'RUN-1',
current_task_no: 'SN-1',
lifecycle_status: 'inventory_matching',
}),
], { focusTaskNo: 'SN-1', focusRunNo: 'RUN-1' });
// 关键断言:同 Run/Task 去重;聚焦 Task;含 Gate。
expect(rows.filter((row) => row.kind === 'run')).toHaveLength(1);
expect(rows.filter((row) => row.kind === 'task')).toHaveLength(1);
expect(rows.find((row) => row.kind === 'task')?.focused).toBe(true);
expect(rows.some((row) => row.kind === 'candidate')).toBe(true);
expect(rows.some((row) => row.kind === 'process_gate')).toBe(true);
});
it('prefers backend node_status over lifecycle mapping for tasks', () => {
const rows = projectConversationProcessingObjects([
item({
current_run_no: 'RUN-2',
current_task_no: 'SN-2',
lifecycle_status: 'inventory_matching',
node_status: 'manual_takeover',
progress_nodes: [
{ code: 'freight_upload', label: '货代上传', status: 'manual_takeover' },
],
}),
]);
// 关键断言:侧栏 Task 使用后端权威 node_status,不覆盖为 running。
expect(rows.find((row) => row.kind === 'task')?.node_status).toBe('manual_takeover');
});
});
@@ -0,0 +1,190 @@
/**
* features/chat/shipping/conversationProcessingProjection.ts
* 用途:将现有 Workflow Items 投影为对话「本次处理中」统一对象行。
* 依赖:shipping.api.types(ConversationProcessingObject / WorkflowNodeStatus)。
* 逻辑:Timeline 复用本投影;Task 优先消费后端 node_status / progress_nodes;
* 不伪造进度百分比。
*/
import type {
ConversationProcessingObject,
ShippingWorkflowItem,
WorkflowNodeStatus,
} from '@/features/chat/types/shipping.api.types';
/**
* 将生命周期状态映射为 WorkflowNodeStatus(展示用,非进度百分比)。
*/
export function mapLifecycleToNodeStatus(
lifecycle: string | null | undefined,
): WorkflowNodeStatus {
const status = String(lifecycle || '').trim();
if (!status || status === 'queued') return 'pending';
if (
status === 'layout_parsing'
|| status === 'extracting'
|| status === 'building_order'
|| status === 'inventory_matching'
|| status === 'generating_excel'
) {
return 'running';
}
if (status === 'failed' || status === 'reparse_failed') return 'failed';
if (status === 'upload_rpa_pending' || status === 'upload_rpa_running') {
return 'running';
}
if (status === 'upload_rpa_failed') return 'failed';
if (status === 'pending_review' || status === 'manual_upload_pending') {
return 'manual_takeover';
}
if (status === 'closed' || status === 'cancelled') return 'succeeded';
return 'pending';
}
/**
* 取 Item 用户可见状态:细粒度 display/current_stage 优先。
*/
export function resolveItemDisplayStatus(item: ShippingWorkflowItem): string {
const display = String(item.display_lifecycle_status || '').trim();
if (display) return display;
const stage = String(item.current_stage || '').trim();
if (
stage === 'upload_rpa_pending'
|| stage === 'upload_rpa_running'
|| stage === 'upload_rpa_failed'
) {
return stage;
}
return String(item.lifecycle_status || '').trim();
}
/**
* 从 Workflow Items 聚合 Run / Candidate / Task / Process Gate 侧栏行。
*
* 核心逻辑:同一 run_no / task_no 去重;Gate 取每项首个阻断门禁;
* focusTaskNo 命中时标记 focused。
*
* @param items - 当前会话 Workflow Items
* @param options.focusTaskNo - 当前聚焦 Task
* @param options.focusRunNo - 当前聚焦 Run
*/
export function projectConversationProcessingObjects(
items: ShippingWorkflowItem[],
options?: {
focusTaskNo?: string | null;
focusRunNo?: string | null;
focusCandidateNo?: string | null;
},
): ConversationProcessingObject[] {
const focusTask = String(options?.focusTaskNo || '').trim().toUpperCase();
const focusRun = String(options?.focusRunNo || '').trim();
const focusCandidate = String(options?.focusCandidateNo || '').trim();
const rows: ConversationProcessingObject[] = [];
const seenRuns = new Set<string>();
const seenTasks = new Set<string>();
const seenGates = new Set<string>();
for (const item of items || []) {
const runNo = String(item.current_run_no || '').trim();
const taskNo = String(item.current_task_no || '').trim().toUpperCase();
const caseNo = String(item.current_case_no || '').trim();
const itemNo = String(item.item_no || '').trim();
const documentId = Number(item.current_document_id || 0) || null;
// 优先消费后端权威 node_status;缺失时才用 lifecycle 本地映射。
const displayStatus = resolveItemDisplayStatus(item);
const backendNodeStatus = String(item.node_status || '').trim() as WorkflowNodeStatus | '';
const nodeStatus = backendNodeStatus || mapLifecycleToNodeStatus(displayStatus);
if (runNo && !seenRuns.has(runNo)) {
seenRuns.add(runNo);
rows.push({
kind: 'run',
object_key: `run:${runNo}`,
label: runNo,
status_label: displayStatus,
node_status: mapLifecycleToNodeStatus(displayStatus),
run_no: runNo,
case_no: caseNo || null,
document_id: documentId,
workflow_item_no: itemNo || null,
primary_action: caseNo || item.lifecycle_status === 'pending_review'
? 'open_review'
: 'expand',
focused: Boolean(focusRun && focusRun === runNo),
});
}
// Candidate:尚无独立列表时,以待复核 Case 作为候选处理对象入口。
if (caseNo && (item.lifecycle_status === 'pending_review' || focusCandidate)) {
const candidateKey = `candidate:${caseNo}`;
if (!rows.some((row) => row.object_key === candidateKey)) {
rows.push({
kind: 'candidate',
object_key: candidateKey,
label: caseNo,
status_label: 'pending_review',
qualification_status: 'review_required',
run_no: runNo || null,
candidate_no: focusCandidate || null,
case_no: caseNo,
document_id: documentId,
workflow_item_no: itemNo || null,
primary_action: 'open_review',
focused: Boolean(
(focusCandidate && focusCandidate === caseNo)
|| (focusCandidate && focusCandidate === String(focusCandidate)),
),
});
}
}
if (taskNo && !seenTasks.has(taskNo)) {
seenTasks.add(taskNo);
rows.push({
kind: 'task',
object_key: `task:${taskNo}`,
label: taskNo,
status_label: displayStatus,
node_status: nodeStatus,
run_no: runNo || null,
task_no: taskNo,
case_no: caseNo || null,
document_id: documentId,
workflow_item_no: itemNo || null,
primary_action: 'focus_task',
focused: Boolean(focusTask && focusTask === taskNo),
});
}
const gateSummary = item.process_gate;
const blockingGate = gateSummary?.current_blocking_gate;
const gateCode = String(
blockingGate?.gate_code
|| gateSummary?.blocking_reason_code
|| '',
).trim();
const gateStatus = String(blockingGate?.status || gateSummary?.status || '').trim();
if (gateCode && blockingGate) {
const gateKey = `gate:${taskNo || runNo || itemNo}:${gateCode}`;
if (!seenGates.has(gateKey)) {
seenGates.add(gateKey);
rows.push({
kind: 'process_gate',
object_key: gateKey,
label: gateCode,
status_label: gateStatus || 'blocked',
node_status: 'failed',
run_no: runNo || null,
task_no: taskNo || gateSummary?.task_no || null,
case_no: caseNo || gateSummary?.case_no || null,
document_id: documentId,
workflow_item_no: itemNo || null,
primary_action: 'open_gate',
focused: false,
});
}
}
}
return rows;
}
@@ -26,7 +26,7 @@ describe('orderExtractionHandlingRefs', () => {
})).toBe('skip.pdf');
expect(resolveHandlingAffectedRefTarget({ type: 'task', task_no: 'ST-9' })).toEqual({
kind: 'task',
kind: 'chat_focus_task',
taskNo: 'ST-9',
});
expect(resolveHandlingAffectedRefTarget({
@@ -8,7 +8,8 @@
export type ShippingHandlingAffectedRef = Record<string, unknown>;
export type ShippingHandlingRefTarget =
| { kind: 'task'; taskNo: string }
/** 对话侧聚焦 Task(主路径);不再默认跳转 Task 工作台。 */
| { kind: 'chat_focus_task'; taskNo: string }
| { kind: 'review'; documentId?: number; candidateNo?: string }
| { kind: 'none' };
@@ -51,7 +52,7 @@ export function resolveHandlingAffectedRefTarget(ref: ShippingHandlingAffectedRe
const candidateNo = String(ref.candidate_no || '').trim();
const documentId = Number(ref.document_id || 0);
if ((type === 'task' || !type) && taskNo) {
return { kind: 'task', taskNo };
return { kind: 'chat_focus_task', taskNo };
}
if (type === 'candidate' || type === 'document' || type === 'attachment' || candidateNo || documentId > 0) {
return {
@@ -172,6 +172,7 @@ export function mapOrderExtractionRunToMessageState(run: ShippingOrderExtraction
terminal: !ACTIVE_RUN_STATUSES.has(run.status),
refreshFailed: false,
errorCode: run.error?.code || null,
errorExplainability: run.error?.explainability || null,
startedAt: run.started_at || null,
finishedAt: run.finished_at || null,
};
@@ -7,9 +7,22 @@
export type ChatTurnInputType = 'text' | 'action' | 'form_submit' | 'upload_followup';
/** 会话级业务锚点;货代常用 task_no/batch_no,其他 Agent 使用各自键名 */
/**
* 会话级业务锚点。
* 货代双工作台阶段 2 优先键:conversation_id / run_no / candidate_no / task_no / batch_no;
* 其他 Agent 可使用各自键名。禁止用本结构承载业务状态机推导结果。
*/
export type ChatTurnRefs = Record<string, string>;
/** 货代对话推荐锚点键(文档化常量,便于前后端对齐)。 */
export const SHIPPING_CHAT_TURN_REF_KEYS = [
'conversation_id',
'run_no',
'candidate_no',
'task_no',
'batch_no',
] as const;
export interface StartChatTurnOptions {
agentId: number;
inputType: Extract<ChatTurnInputType, 'action' | 'form_submit' | 'upload_followup'>;
@@ -115,6 +115,20 @@ export interface ShippingOrderExtractionHandlingItemState {
primaryAction?: string | null;
}
/**
* 对话侧栏聚焦对象(阶段 2)。
* 用途:复核返回 / 侧栏点击后恢复「本次处理中」焦点;不替代后端状态。
*/
export interface ShippingChatFocusState {
conversationId?: string | null;
runNo?: string | null;
candidateNo?: string | null;
taskNo?: string | null;
workflowItemNo?: string | null;
/** 消息区滚动恢复用稳定 key(可选)。 */
scrollRestoreKey?: string | null;
}
export interface ShippingOrderExtractionState {
status: ShippingOrderExtractionStateStatus;
summary: ShippingOrderExtractionStateSummary;
@@ -135,6 +149,15 @@ export interface ShippingOrderExtractionState {
terminal: boolean;
refreshFailed?: boolean;
errorCode?: string | null;
/** Run 失败可解释性投影(与 build_explainability_reason 对齐) */
errorExplainability?: {
reason_code?: string | null;
message?: string | null;
responsible_party?: string | null;
next_action?: string | null;
request_id?: string | null;
details?: Record<string, unknown> | null;
} | null;
startedAt?: string | null;
finishedAt?: string | null;
}
@@ -5,7 +5,79 @@
* 逻辑:shipping.api.ts 与 Chat/工作台组件统一引用本文件 DTO 类型。
* 阶段 0 冻结用户可见阶段、健康提示、取消元数据与审计 DTO;写路径与 UI 在后续阶段启用。
* 门禁恢复 Phase 1:ShippingProcessGate* 联合类型与 Python process_gate_contract 对齐。
* 错误可解释性阶段 0:ShippingExplainabilityReason / 库存源原因码联合与
* error_explainability_contract 对齐。
* 双工作台架构阶段 0(2026-08-02):WorkbenchSurface /
* CandidateQualificationStatus / WorkflowNodeStatus 冻结;权威见
* docs/features/shipping-notice/review-workbench-layout-plan.md §0。
*/
/**
* 工作台表面归属(双工作台架构 2026-08-02 冻结)。
* 用途:标注 UI/动作应落在对话、复核或 Task 备用深链,禁止三表面平行主入口。
* 权威契约:docs/features/shipping-notice/review-workbench-layout-plan.md §0.1
*/
export type WorkbenchSurface = 'chat' | 'review' | 'task_deep_link';
/**
* Candidate 自动建单资格状态(与后端 Candidate Qualification 对齐目标态)。
* 用途:对话卡片 / 复核资格摘要 / 「本次处理中」侧栏统一消费;模板质量资格不得直接映射本状态。
* - eligible:通过统一门禁,允许创建 Task
* - review_required:需人工复核或轻量确认(如客户多匹配)
* - blocked:硬阻断(缺字段、证据、冲突、开关关闭等)
* - rejected:明确拒绝自动建单(如非订单处置)
*/
export type CandidateQualificationStatus =
| 'eligible'
| 'review_required'
| 'blocked'
| 'rejected';
/**
* 后台 Workflow 节点执行状态(对话「本次处理中」与 Task 进度投影)。
* 用途:前端只展示后端投影,禁止本地推导进度百分比。
* 与 ProcessGate 状态互补:本类型描述节点执行生命周期,Gate 描述中断恢复实例。
*/
export type WorkflowNodeStatus =
| 'pending'
| 'running'
| 'succeeded'
| 'retrying'
| 'failed'
| 'manual_takeover'
| 'skipped'
| 'rolled_back';
/**
* 对话「本次处理中」侧栏对象类型(阶段 2)。
* 用途:将 Workflow Item / Run / Candidate / Task / Process Gate 投影为统一列表行。
*/
export type ConversationProcessingObjectKind =
| 'run'
| 'candidate'
| 'task'
| 'process_gate';
/**
* 会话处理对象投影行(前端聚合模型;权威状态仍来自后端 API)。
*/
export interface ConversationProcessingObject {
kind: ConversationProcessingObjectKind;
/** 稳定展示键,如 RUN-xxx / CAND-xxx / SN-xxx / gate:code */
object_key: string;
label: string;
status_label?: string | null;
qualification_status?: CandidateQualificationStatus | string | null;
node_status?: WorkflowNodeStatus | string | null;
run_no?: string | null;
candidate_no?: string | null;
task_no?: string | null;
case_no?: string | null;
document_id?: number | null;
workflow_item_no?: string | null;
primary_action?: string | null;
focused?: boolean;
}
export type InventorySourceStatus =
| 'unresolved'
| 'ambiguous'
@@ -242,6 +314,7 @@ export type ShippingProcessGateCode =
| 'inventory_sufficiency'
| 'excel_readiness'
| 'artifact_generation'
| 'freight_upload_rpa'
| 'manual_upload_handoff';
/** 门禁实例状态(与 PROCESS_GATE_STATUSES 对齐)。 */
@@ -293,6 +366,8 @@ export type ShippingProcessGateActionCode =
| 'open_shortage_review'
| 'recheck_excel_readiness'
| 'regenerate_excel_artifact'
| 'poll_freight_upload_rpa'
| 'retry_freight_upload_rpa'
| 'regenerate_manual_upload_todo';
/** 门禁责任方(与 PROCESS_GATE_RESPONSIBLE_PARTIES 对齐)。 */
@@ -328,6 +403,8 @@ export interface ShippingProcessGateUserSummary {
current_blocking_gate?: ShippingProcessGateProjection | null;
blocking_reason_code?: string | null;
blocking_message?: string | null;
/** 统一可解释性投影(与 build_explainability_reason 对齐) */
explainability?: ShippingExplainabilityReason | null;
next_action_code?: ShippingProcessGateActionCode | string | null;
responsible_party?: ShippingProcessGateResponsibleParty | string | null;
diagnostic_hint?: string | null;
@@ -573,6 +650,15 @@ export interface ShippingStpFacts {
match_status?: string | null;
}
/**
* 后台固定推进节点(与 stp_progress_contract.STP_PROGRESS_NODE_DEFS 对齐)。
*/
export interface ShippingProgressNode {
code: string;
label: string;
status: WorkflowNodeStatus | string;
}
export interface ShippingTaskUiState {
task_no: string;
batch_no?: string | null;
@@ -601,6 +687,11 @@ export interface ShippingTaskUiState {
allowed_actions?: string[] | null;
/** STP 履约事实;仅后端投影,前端禁止二次推导 */
stp_facts?: ShippingStpFacts | null;
/**
* 固定后台推进节点梯(客户确认→…→货代上传)。
* 前端只渲染 status,禁止自行计算进度百分比。
*/
progress_nodes?: ShippingProgressNode[] | null;
/** 统一 Gate 用户摘要(优先于 legacy action_buttons) */
process_gate?: ShippingProcessGateUserSummary | null;
};
@@ -947,6 +1038,8 @@ export interface ShippingOrderExtractionDocumentResult {
freeze_source?: string | null;
email_supplement: ShippingOrderExtractionEmailSupplementResult;
reason_code?: string | null;
/** 统一可解释性投影;优先于仅展示 reason_code */
explainability?: ShippingExplainabilityReason | null;
review_details?: Array<{ line_number: number; field_code?: string | null; reason_code: string }>;
/** 解析阶段重复决策;open_existing 时右侧应跳转已有任务 */
duplicate_resolution?: string | null;
@@ -1038,8 +1131,11 @@ export interface ShippingOrderExtractionRun {
auto_freeze?: Record<string, unknown>;
budget_stopped?: boolean;
} | null;
// 用户态 Run 契约只暴露稳定错误码;错误正文留在服务端管理员诊断边界。
error?: { code?: string | null } | null;
// 用户态失败:稳定错误码 + 可解释性(责任方/下一步/request_id);诊断原文仍仅管理员可见。
error?: {
code?: string | null;
explainability?: ShippingExplainabilityReason | null;
} | null;
created_at?: string | null;
updated_at?: string | null;
started_at?: string | null;
@@ -1141,6 +1237,77 @@ export interface ShippingOrderExtractionDocumentsResponse {
items: ShippingOrderExtractionDocumentResult[];
}
/**
* 订单人工复核工作台页面模式(布局重构 2026-08-01 冻结)。
* 用途:驱动主区域/辅助区域切换,不改变后端 Case/Draft 状态机。
* 权威契约:docs/features/shipping-notice/review-workbench-layout-plan.md
*/
export type ReviewWorkbenchMode =
| 'standard'
| 'evidence'
| 'inventory'
| 'reparse'
| 'confirm_progress';
/**
* 复核工作台辅助面板开关状态(前端 UI 契约)。
* 用途:统一 PDF/检查/AI/版本历史面板;默认浮窗不占主布局列,用户主动「固定」才进双栏。
* 普通折叠不写服务端审计;敏感读取与业务写操作另走 AuditContext。
*/
export interface ReviewWorkbenchPanelState {
/** PDF 证据面板是否打开;默认 false(不占主布局列)。 */
pdfOpen: boolean;
/**
* 退出证据模式时是否保持 PDF 打开。
* 仅控制 pdfOpen 保留策略,不等于固定为侧栏、也不等于视口 sticky。
*/
pdfPinned: boolean;
/** 浮窗是否为大尺寸(仍不参与主网格)。 */
pdfExpanded: boolean;
/**
* 是否固定为持久侧栏双栏;仅用户主动切换。
* false=浮动证据面板(默认);true=参与主编辑区网格列。
*/
pdfDocked: boolean;
/** 浮窗靠左或靠右(不覆盖摘要栏时优先右侧)。 */
pdfFloatSide: 'right' | 'left';
/** 完整建单检查项抽屉是否打开。 */
eligibilityDetailsOpen: boolean;
/** 字段级 AI 建议抽屉是否打开。 */
llmSuggestionOpen: boolean;
/** 版本历史抽屉是否打开。 */
versionHistoryOpen: boolean;
/**
* 关闭证据模式后用于恢复字段区滚动位置的稳定 key。
* 一般为 fieldId 或 `${fieldId}:${lineKey}`;无待恢复时为 null。
*/
scrollRestoreKey: string | null;
}
/**
* 复核工作台审计上下文(写操作 / 敏感读取上报载荷白名单)。
* 用途:前端组装最小引用;禁止携带 Prompt、Token、对象存储 URL、PDF 正文。
* 完整事件字典见 review-workbench-layout-plan.md §6。
*/
export interface ReviewWorkbenchAuditContext {
/** 稳定事件类型,如 review_evidence_focused、sensitive_evidence_viewed。 */
event_type: string;
case_no?: string | null;
run_no?: string | null;
document_id?: number | null;
field_id?: string | null;
line_key?: string | null;
page_no?: number | null;
evidence_ref?: string | null;
draft_version?: number | null;
reason_code?: string | null;
reason_text?: string | null;
/** 脱敏前后摘要或敏感快照引用 ID;不得放明文敏感全量。 */
before_ref?: string | null;
after_ref?: string | null;
access_reason?: string | null;
}
/** 建单前订单复核的冻结 Schema 字段;阶段 2 只读展示,编辑能力由后续阶段扩展。 */
export interface ShippingOrderReviewSchemaField {
field_id: string;
@@ -1215,14 +1382,59 @@ export interface ShippingOrderReviewInventoryMatchedRule {
scope?: string;
}
/**
* 库存源单源不可用原因码(unavailable_reasons 的值)。
* 与 backend error_explainability_contract.INVENTORY_SOURCE_UNAVAILABLE_REASON_CODES_EMITTED 对齐。
*/
export type ShippingInventorySourceUnavailableReasonCode =
| 'source_not_found'
| 'source_disabled'
| 'source_runtime_unavailable'
| 'parsing_profile_unavailable'
| 'source_profile_disabled'
| 'source_excel_template_unavailable'
| string;
/**
* 建单前行级库存路由阻断原因码(line.block_reason)。
* 特别区分:no_inventory_source_candidates(规则未命中)≠
* inventory_source_unavailable(命中但源不可用)≠ require_manual_review(冲突)。
*/
export type ShippingInventorySourceLineBlockReasonCode =
| 'no_inventory_source_candidates'
| 'inventory_source_unavailable'
| 'require_manual_review'
| 'manual_inventory_source_reason_required'
| 'manual_inventory_source_invalid'
| 'inventory_source_conflicted'
| 'inventory_source_changed'
| 'inventory_source_identity_mismatch'
| string;
/**
* 统一错误可解释性投影(阶段 0 契约;与 build_explainability_reason 对齐)。
* next_action 为前端按钮/导航唯一依据;未知失败须带 request_id。
*/
export interface ShippingExplainabilityReason {
reason_code: string;
message: string;
details: Record<string, unknown>;
responsible_party: ShippingProcessGateResponsibleParty | string;
next_action?: ShippingProcessGateActionCode | string | null;
request_id?: string | null;
}
/** 规则引擎产出的库存源建议;人工覆盖后仍可对照。 */
export interface ShippingOrderReviewInventoryRuleSuggestion {
source_codes?: string[];
raw_source_codes?: string[];
unavailable_source_codes?: string[];
/** 不可用源编码 → 稳定原因码(非文案) */
unavailable_reasons?: Record<string, ShippingInventorySourceUnavailableReasonCode>;
routing_status?: string;
rule_versions?: ShippingOrderReviewInventoryRuleVersion[];
matched_rule_ids?: number[];
matched_rules?: ShippingOrderReviewInventoryMatchedRule[];
}
/** 建单前资格行级投影;与后端 validation.line_projections 对齐。 */
@@ -1238,8 +1450,8 @@ export interface ShippingOrderReviewBuildEligibilityLineProjection {
rule_suggestion_source_codes?: string[];
/** 规则命中但当前不可用的源 */
unavailable_source_codes?: string[];
/** 不可用源 → 原因文案 */
unavailable_reasons?: Record<string, string>;
/** 不可用源编码 → 稳定原因码(非文案;前端用 i18n 渲染) */
unavailable_reasons?: Record<string, ShippingInventorySourceUnavailableReasonCode>;
matched_rule_ids?: number[];
matched_rules?: ShippingOrderReviewInventoryMatchedRule[];
rule_versions?: ShippingOrderReviewInventoryRuleVersion[];
@@ -1250,21 +1462,39 @@ export interface ShippingOrderReviewBuildEligibilityLineProjection {
rule_source_codes?: string[];
routing_status?: string;
can_build?: boolean;
block_reason?: string | null;
block_reason?: ShippingInventorySourceLineBlockReasonCode | null;
selection_mode?: string;
manual_reason?: string;
}
/** 建单前整单资格摘要;Draft 校验后由后端投影至 Case DTO。 */
/** 建单资格 issue;可含统一 explainability 投影。 */
export interface ShippingOrderReviewBuildEligibilityIssue {
code: string;
severity?: string;
owning_gate_code?: string;
line_key?: string | null;
line_index?: number;
field_code?: string;
message?: string | null;
unavailable_source_codes?: string[];
unavailable_reasons?: Record<string, ShippingInventorySourceUnavailableReasonCode>;
explainability?: ShippingExplainabilityReason | null;
[key: string]: unknown;
}
export interface ShippingOrderReviewBuildEligibility {
can_build: boolean;
can_auto_create?: boolean;
status: string;
gates?: Record<string, boolean>;
failed_gates?: string[];
issues?: ShippingOrderReviewBuildEligibilityIssue[];
line_projections: ShippingOrderReviewBuildEligibilityLineProjection[];
/** 已启用库存源编码;零规则候选时供人工选择 */
enabled_inventory_source_codes?: string[];
/** 库存源编码 → 业务显示名;复核台展示用,提交仍用编码 */
inventory_source_labels?: Record<string, string>;
}
export interface ShippingOrderReviewInventoryCandidatesWrite {
@@ -1287,13 +1517,67 @@ export interface ShippingOrderReviewInventoryRoutingDecisionWrite {
reason?: string;
}
/** 建单前客户识别投影(复核工作台固定客户区)。 */
export interface ShippingOrderReviewCustomerResolution {
resolved: boolean;
status: string;
role?: string;
extraction_id?: number | null;
raw_name?: string | null;
customer_id?: number | null;
standard_name?: string | null;
short_code?: string | null;
candidates?: Array<Record<string, unknown>>;
match?: ShippingOrderCustomerMatch | null;
}
/** 建单前字段冲突选项(规范化键 + 可展示值)。 */
export interface ShippingOrderReviewFieldConflictOption {
value_key: string;
display_value?: unknown;
sources?: string[];
}
/** 建单前 Candidate 字段冲突投影(复核工作台集中裁决区)。 */
export interface ShippingOrderReviewFieldConflict {
conflict_key: string;
field_code: string;
line_index?: number | null;
line_key?: string | null;
severity?: string;
reason: string;
options: ShippingOrderReviewFieldConflictOption[];
observation_ids?: string[];
}
export interface ShippingOrderReviewCase {
case_no: string;
run_no: string;
document: { id: number; file_name?: string | null };
/** 建单前客户确认状态;工作台始终展示,不依赖 Process Gate */
customer_resolution?: ShippingOrderReviewCustomerResolution | null;
/** 建单前字段冲突;有开放项时工作台侧栏展示裁决区 */
field_conflicts?: ShippingOrderReviewFieldConflict[] | null;
/** 建单前重复检测;needs_adjudication 时侧栏展示裁决区 */
duplicate?: ShippingOrderReviewDuplicate | null;
/** 建单前文档模板匹配只读摘要 */
profile_match?: ShippingOrderReviewProfileMatch | null;
status: string;
disposition?: string | null;
confirmed_task_id?: number | null;
/** 已确认时关联的任务号;供刷新后恢复推进入口。 */
confirmed_task_no?: string | null;
/**
* 确认建单后的自动推进投影:needs_retry=true 时前端应展示琥珀色重试条。
* 与即时 confirm 响应的 auto_progress 字段语义对齐,供页面重载恢复。
*/
post_confirm_auto_progress?: {
task_no?: string | null;
needs_retry?: boolean;
status?: string | null;
message?: string | null;
task_process_status?: string | null;
} | null;
candidate?: { candidate_no: string; validation_status: string; po_number?: string | null } | null;
schema: { schema_version_id: number; fields: ShippingOrderReviewSchemaField[] };
draft?: {
@@ -1302,7 +1586,16 @@ export interface ShippingOrderReviewCase {
field_meta?: Record<string, ShippingOrderReviewDraftFieldMeta>;
};
lines: ShippingOrderReviewDraftLine[];
issues: Array<{ code?: string; severity?: string }>;
/** 草稿待处理问题;服务端可能附带具体说明及字段/行定位。 */
issues: Array<{
code?: string;
severity?: string;
message?: string | null;
field_id?: string | null;
field_code?: string | null;
line_index?: number | null;
explainability?: ShippingExplainabilityReason | null;
}>;
validation: Record<string, unknown>;
build_eligibility?: ShippingOrderReviewBuildEligibility;
} | null;
@@ -1311,6 +1604,16 @@ export interface ShippingOrderReviewCase {
process_gate?: ShippingProcessGateUserSummary | null;
}
/**
* 复核确认+自动推进联合结果(与后端 resolve_confirm_outcome 对齐)。
* 调用方必须经 parseOrderReviewConfirmResponse 解析,禁止只看 HTTP/success。
*/
export type ShippingOrderReviewConfirmOutcome =
| 'confirmed_and_auto_progress_started'
| 'confirmed_auto_progress_failed'
| 'confirmed_auto_progress_not_scheduled'
| string;
export interface ShippingOrderReviewConfirmResponse {
task_no?: string | null;
idempotent_replay: boolean;
@@ -1319,12 +1622,21 @@ export interface ShippingOrderReviewConfirmResponse {
workflow_id?: string | null;
/** WorkflowItem 业务编号(item_no) */
workflow_item_id?: string | null;
/** 确认后已触发与 STP 相同的 auto_progress */
/** 复核确认(建单)是否成功;与自动推进调度结果解耦;不可单独代表流程已推进 */
confirm_ok?: boolean;
/**
* 确认+推进联合结果枚举(调用方应优先读此字段,而非仅看 HTTP/confirm_ok):
* confirmed_and_auto_progress_started | confirmed_auto_progress_failed |
* confirmed_auto_progress_not_scheduled
*/
confirm_outcome?: ShippingOrderReviewConfirmOutcome;
/** 确认后是否已入队/触发自动推进 */
auto_progress_started?: boolean;
auto_progress?: {
status?: string | null;
message?: string | null;
checkpoint?: string | null;
enqueue_result?: string | null;
} | null;
}
@@ -1343,6 +1655,16 @@ export interface ShippingOrderReviewDraftWrite {
override_reason_text?: string;
}
/** 字段高亮质量;与后端 field_highlight_contract 对齐。 */
export type ShippingFieldHighlightQuality = 'verified' | 'candidate' | 'unavailable' | 'invalid';
/** 值与引文匹配状态;不替代业务可信度。 */
export type ShippingFieldValueMatchStatus = 'matched' | 'mismatched' | 'unchecked' | 'empty';
/**
* 复核字段证据 DTO。
* highlight_* / coordinate_* 为阶段 0 冻结字段;bbox 与 highlight_bbox 同义(仅可绘制质量非空)。
*/
export interface ShippingOrderReviewEvidence {
evidence_id: string;
field_id: string;
@@ -1352,8 +1674,27 @@ export interface ShippingOrderReviewEvidence {
page_no?: number | null;
table_id?: string | null;
cell_id?: string | null;
/** @deprecated 使用 highlight_bbox;保留以兼容旧预览组件。 */
bbox?: { x0: number; y0: number; x1: number; y1: number } | null;
source: string;
highlight_quality: ShippingFieldHighlightQuality;
highlight_source: string;
highlight_bbox?: { x0: number; y0: number; x1: number; y1: number } | null;
coordinate_status: ShippingFieldHighlightQuality;
coordinate_issue_codes: string[];
evidence_ref?: string | null;
token_ids: string[];
value_match_status: ShippingFieldValueMatchStatus;
/** 独立引文来源:bbox_tokens / glyph_region / layout_cell_text;缺失则值匹配为 unchecked。 */
quote_source?: string | null;
/** 从 value_bbox 绑定 token 重读的文本;不得等于自报 machine value。 */
bbox_text?: string | null;
/** 是否允许绘制高亮框(verified/candidate)。 */
drawable?: boolean;
/** 是否为已严格验证的稳定坐标(仅 verified)。 */
reliable?: boolean;
/** 是否仍需人工核对坐标(candidate/unavailable/invalid)。 */
requires_review?: boolean;
}
/** Dify 最小证据建议 DTO;与后端 serialize_suggestion 对齐。 */
@@ -1469,6 +1810,53 @@ export interface ShippingDuplicateResult {
allowed_actions: ShippingDuplicateAction[];
}
/** 建单前重复订单投影(复核工作台集中裁决区)。 */
export interface ShippingOrderReviewDuplicate extends ShippingDuplicateResult {
candidate_no?: string | null;
resolution?: {
action?: ShippingDuplicateAction | string | null;
target_task_no?: string | null;
reason?: string | null;
} | null;
resolved: boolean;
needs_adjudication: boolean;
}
/** 建单前文档模板匹配候选。 */
export interface ShippingOrderReviewProfileMatchCandidate {
profile_code: string;
version?: number | null;
display_name?: string | null;
score?: number | null;
hard_match?: boolean | null;
reason_codes?: string[];
missing_required_anchor_ids?: string[];
}
/** 建单前文档模板匹配只读投影。 */
export interface ShippingOrderReviewProfileMatch {
status: string;
execution_mode?: string | null;
route_type?: string | null;
selected_profile?: {
profile_code: string;
version?: number | null;
checksum?: string | null;
display_name?: string | null;
auto_create_approved?: boolean | null;
} | null;
candidates: ShippingOrderReviewProfileMatchCandidate[];
fallback_reason_codes: string[];
needs_review: boolean;
available: boolean;
table_counts?: {
candidate?: number;
matched?: number;
parsed?: number;
approved?: number;
};
}
export interface ShippingCreateBatchFromIntakesResponse extends ShippingNoticeUploadResponse {}
/** Workflow 批次状态;与后端 ShippingNoticeWorkflow.status 对齐。 */
@@ -1540,6 +1928,15 @@ export interface ShippingWorkflowItem {
current_task_no?: string | null;
lifecycle_status: ShippingWorkflowItemLifecycleStatus;
current_stage: string;
/** 用户可见状态:RPA 上传中等细粒度阶段优先于宽 lifecycle。 */
display_lifecycle_status?: string | null;
/**
* 权威「真正待人工上传」布尔。
* 禁止仅凭 lifecycle_status===manual_upload_pending 推断(RPA 中也可能落在该桶)。
*/
is_waiting_manual_upload?: boolean;
/** none | rpa_pending | rpa_running | rpa_failed | manual_pending */
upload_phase?: string | null;
closed_reason?: string | null;
lock_version: number;
last_activity_at?: string | null;
@@ -1558,6 +1955,10 @@ export interface ShippingWorkflowItem {
/** 当前 WorkflowItem 版本关联 Execution 的用户 Gate 摘要。 */
process_gate?: ShippingProcessGateUserSummary | null;
gate_user_hint?: string | null;
/** 绑定 Task 时由后端投影的固定节点梯;前端禁止自行算百分比。 */
progress_nodes?: ShippingProgressNode[] | null;
/** 侧栏单值节点状态;优先于 lifecycle 本地映射。 */
node_status?: WorkflowNodeStatus | string | null;
}
/** Workflow 批次投影;与 serialize_workflow 对齐。 */
@@ -0,0 +1,22 @@
/**
* features/chat/utils/chatText.spec.ts
* 用途:验证对话展示清理模型推理和纯调试包装,同时保留正常业务回答。
* 依赖:Vitest、chatText。
* 逻辑:覆盖推理标签、调试 JSON、技术前奏和正常 JSON 示例。
*/
import { describe, expect, it } from 'vitest';
import { stripReasoningPrelude } from './chatText';
describe('stripReasoningPrelude', () => {
it('removes reasoning tags and technical prelude lines', () => {
expect(stripReasoningPrelude('<think>internal</think>订单已处理完成。')).toBe('订单已处理完成。');
expect(stripReasoningPrelude('workflow_run_id: run-1\nnode_id: node-2\n订单已处理完成。'))
.toBe('订单已处理完成。');
});
it('hides pure debug JSON but keeps business JSON examples', () => {
expect(stripReasoningPrelude('{"workflow_run_id":"run-1","status":"failed"}')).toBe('');
expect(stripReasoningPrelude('{"订单号":"PO-1","数量":2}'))
.toBe('{"订单号":"PO-1","数量":2}');
});
});
+29 -1
View File
@@ -1,4 +1,7 @@
/** 去除模型 reasoning 前奏,供 Markdown 展示与出货模块使用 */
/**
* 去除模型推理与调试包装,供 Markdown 展示与出货模块使用。
* 仅处理明确的推理标签、纯调试 JSON 和开头技术诊断行,不改写正常业务回答。
*/
export const stripReasoningPrelude = (text: string) => {
if (!text) return '';
let cleaned = text
@@ -6,6 +9,31 @@ export const stripReasoningPrelude = (text: string) => {
.replace(/<analysis[\s\S]*?<\/analysis>/gi, '')
.trim();
if (/^(?:\{|\[)/.test(cleaned)) {
try {
const parsed = JSON.parse(cleaned) as unknown;
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
const keys = Object.keys(parsed as Record<string, unknown>);
const technicalKeys = new Set([
'workflow_run_id', 'node_id', 'node_execution_id', 'status', 'error',
'outputs', 'inputs', 'metadata', 'traceback', 'tool_output', 'tool_response',
]);
if (keys.length > 0 && keys.every((key) => technicalKeys.has(key))) return '';
}
} catch {
// 非完整 JSON 继续按普通回答展示。
}
}
const lines = cleaned.split('\n');
while (
lines.length > 1
&& /^\s*(?:workflow(?:_run)?_id|node(?:_execution)?_id|tool(?:_output|_response)?|traceback|status|error)(?:[_\s-]*(?:code|message))?\s*[:=]/i.test(lines[0] || '')
) {
lines.shift();
}
cleaned = lines.join('\n').trim();
const reasoningMarkers = [
'让我分析',
'根据应答生成规则',
@@ -0,0 +1,27 @@
/**
* features/chat/utils/streamErrorMessage.spec.ts
* 用途:验证流式异常不会把后端或浏览器技术正文展示给用户。
* 依赖:Vitest、streamErrorMessage。
* 逻辑:保留明确连接中断分类,其余中英文异常一律使用通用提示。
*/
import { describe, expect, it } from 'vitest';
import { resolveStreamErrorText } from './streamErrorMessage';
const labels = {
networkDisconnectedEmpty: '连接中断',
partialInterrupted: '回答不完整',
upstreamDisconnected: '服务连接中断',
generic: '请稍后重试',
};
describe('resolveStreamErrorText', () => {
it('maps known disconnects to business messages', () => {
expect(resolveStreamErrorText('Failed to fetch', false, labels)).toBe('连接中断');
expect(resolveStreamErrorText('response ended prematurely', true, labels)).toBe('回答不完整');
});
it('does not expose Chinese or English technical errors', () => {
expect(resolveStreamErrorText('Dify API Key 配置错误', false, labels)).toBe('请稍后重试');
expect(resolveStreamErrorText('HTTP 500 node_execution_id=abc', false, labels)).toBe('请稍后重试');
});
});
@@ -2,7 +2,8 @@
* features/chat/utils/streamErrorMessage.ts
* 用途:将 SSE / 浏览器流式读错映射为用户可读文案。
* 依赖:vue-i18n chat.streamError 词条。
* 逻辑:useChat 在 catch 与 error 事件中调用 applyStreamErrorToMessage。
* 逻辑:useChat 在 catch 与 error 事件中调用 applyStreamErrorToMessage;
* 只识别明确的连接中断,其余异常正文不向用户透传。
*/
import type { ChatMessage } from '../types/chat.types';
@@ -63,9 +64,6 @@ export function resolveStreamErrorText(
if (isUpstreamDisconnectError(rawMessage)) {
return hasContent ? labels.partialInterrupted : labels.upstreamDisconnected;
}
if (/[\u4e00-\u9fff]/.test(rawMessage)) {
return rawMessage;
}
return labels.generic;
}
@@ -0,0 +1,679 @@
/**
* features/chat/views/ShippingOrderReviewView.spec.ts
* 用途:锁定复核工作台布局重构阶段 1 的主结构与模式契约。
* 依赖:vitest、@vue/test-utils、vue-i18n、vue-router mocks。
* 逻辑:标准模式无对话上下文、无常驻 PDF 列;存在主编辑区/摘要侧栏/底栏确认按钮;
* 敏感面板审计失败不打开;确认后推进失败可由 Case 投影刷新恢复。
*/
import { describe, expect, it, vi, beforeEach } from 'vitest';
import { computed, ref } from 'vue';
import { flushPromises, mount } from '@vue/test-utils';
import { createI18n } from 'vue-i18n';
import { createRouter, createMemoryHistory } from 'vue-router';
import ShippingOrderReviewView from './ShippingOrderReviewView.vue';
import { CHAT_PAGE_KEY } from '@/features/chat/composables/chat.context';
import {
auditWorkspaceShippingOrderReviewEligibilityDetails,
auditWorkspaceShippingOrderReviewVersionHistory,
} from '@/features/chat/api/shipping.api';
const focusSuggestionField = vi.fn();
const load = vi.fn().mockResolvedValue(undefined);
const selectCase = vi.fn().mockResolvedValue(undefined);
/** 确认建单 mock:用例可改写返回值以断言 confirm_outcome / auto_progress 解析。 */
const confirmMock = vi.fn();
const messageMocks = vi.hoisted(() => ({
warning: vi.fn(),
error: vi.fn(),
success: vi.fn(),
}));
/** 同步 stub 异步证据抽屉(覆盖相对路径与 @ 别名,供 defineAsyncComponent 解析)。 */
const evidenceDrawerStub = vi.hoisted(() => ({
name: 'ReviewDocumentEvidenceDrawer',
props: ['open', 'pinned', 'expanded', 'docked', 'floatSide'],
emits: ['close', 'toggle-pin', 'toggle-expand', 'toggle-dock', 'toggle-side'],
template: `
<aside
v-if="open"
data-testid="review-document-evidence-drawer"
:data-docked="docked ? 'true' : 'false'"
:data-presentation="docked ? 'docked' : 'floating'"
>
<button data-testid="review-evidence-toggle-dock" @click="$emit('toggle-dock')">dock</button>
<button data-testid="review-evidence-toggle-expand" @click="$emit('toggle-expand')">expand</button>
</aside>
`,
}));
const reviewRun = ref({
run_no: 'RUN-1',
items: [
{
case_no: 'CASE-1',
document_id: 1,
file_name: 'po.pdf',
status: 'draft',
issue_count: 0,
available_actions: ['validate', 'confirm'],
},
],
});
const activeCase = ref({
case_no: 'CASE-1',
document_id: 1,
status: 'draft',
available_actions: ['validate', 'confirm', 'mark_non_order', 'reparse'],
schema: {
schema_version_id: 14,
fields: [
{
field_id: 'fld-po',
field_code: 'customer_po_number',
display_name: '客户 PO',
scope: 'header',
value_type: 'string',
required: true,
options: [],
},
],
},
draft: {
draft_version: 1,
header_values: {
values: { 'fld-po': { value: 'PO-1', source: 'machine' } },
machine_fields: [{ field_id: 'fld-po', observations: [{ value: 'PO-1' }] }],
},
lines: [],
issues: [],
},
process_gate: null,
});
vi.mock('@/features/chat/api/shipping.api', async (importOriginal) => {
const actual = await importOriginal<typeof import('@/features/chat/api/shipping.api')>();
return {
...actual,
auditWorkspaceShippingOrderReviewVersionHistory: vi.fn().mockResolvedValue({ audited: true, case_no: 'CASE-1' }),
auditWorkspaceShippingOrderReviewEligibilityDetails: vi.fn().mockResolvedValue({ audited: true, case_no: 'CASE-1' }),
autoProgressWorkspaceShippingTask: vi.fn().mockResolvedValue({ status: 'ok' }),
};
});
vi.mock('@/features/chat/shipping-review/useShippingOrderReview', () => ({
REVIEW_BUILD_ELIGIBILITY_BLOCKED: 'SHIPPING.REVIEW_BUILD_ELIGIBILITY_BLOCKED',
useShippingOrderReview: () => ({
reviewRun,
activeCase,
workItem: ref(null),
versions: ref([]),
statusMessage: ref(null),
draftConflict: ref(null),
draftConflictDiffLines: ref([]),
buildEligibility: ref({ can_build: true, issues: [], lines: [] }),
canConfirmBuild: computed(() => true),
routingRecoveryLines: ref([]),
isViewingHistoricalVersion: computed(() => false),
isReadOnly: computed(() => false),
loading: ref(false),
loadFailed: ref(false),
saving: ref(false),
saveFailed: ref(false),
versionsLoading: ref(false),
evidence: ref([
{
field_id: 'fld-po',
page_no: 1,
quote: 'PO-1',
bbox: { x0: 0.1, y0: 0.1, x1: 0.2, y1: 0.2 },
},
]),
llmSuggestions: ref([]),
suggestionLoading: ref(false),
focusedFieldId: ref(null),
focusedLineKey: ref(null),
previewUrl: ref('blob:mock-pdf'),
previewLoading: ref(false),
previewLoadFailed: ref(false),
ensurePreviewLoaded: vi.fn().mockResolvedValue(true),
load,
selectCase,
refreshWorkItemContext: vi.fn(),
openCurrentVersion: vi.fn(),
reloadLatestDraft: vi.fn(),
toggleConflictDiff: vi.fn(),
patchHeader: vi.fn(),
patchLine: vi.fn(),
addLine: vi.fn(),
copyLine: vi.fn(),
deleteLine: vi.fn(),
validate: vi.fn(),
setLineInventoryCandidates: vi.fn(),
rerouteInventoryRouting: vi.fn(),
adoptInventoryRoutingSuggestion: vi.fn(),
keepManualInventoryRouting: vi.fn(),
confirm: confirmMock,
createManualDraft: vi.fn(),
markNonOrder: vi.fn(),
markQualityIssue: vi.fn(),
reparseDocument: vi.fn(),
uploadReplacement: vi.fn(),
focusSuggestionField,
setEvidenceDrawerFocus: vi.fn(),
clearEvidenceDrawerFocus: vi.fn(),
requestSuggestion: vi.fn(),
decideSuggestion: vi.fn(),
editable: computed(() => true),
showWorkflowProgress: computed(() => false),
workflowProgressPolling: computed(() => false),
reparseProgressActive: computed(() => false),
reparseProgressPolling: computed(() => false),
reparseProgressRefreshFailed: computed(() => false),
reparseProgressStage: computed(() => 'submitted'),
}),
}));
vi.mock('@/shared/composables/useMessage', () => ({
useMessage: () => messageMocks,
}));
vi.mock('../components/shipping-review/ReviewDocumentPreview.vue', () => ({
default: {
name: 'ReviewDocumentPreview',
template: '<div data-testid="mock-pdf-preview" />',
},
}));
vi.mock('../components/shipping-review/ReviewDocumentEvidenceDrawer.vue', () => ({
default: evidenceDrawerStub,
}));
vi.mock('@/features/chat/components/shipping-review/ReviewDocumentEvidenceDrawer.vue', () => ({
default: evidenceDrawerStub,
}));
vi.mock('../components/shipping-review/ReviewBuildEligibilitySummary.vue', () => ({
default: {
name: 'ReviewBuildEligibilitySummary',
emits: ['open-details'],
template:
'<div data-testid="mock-eligibility-summary">'
+ '<button data-testid="review-open-eligibility-details" @click="$emit(\'open-details\')">详情</button>'
+ '</div>',
},
}));
vi.mock('../components/shipping-review/ReviewBuildEligibilityDetailsDrawer.vue', () => ({
default: {
name: 'ReviewBuildEligibilityDetailsDrawer',
props: ['open'],
template: '<div v-if="open" data-testid="mock-eligibility-details" />',
},
}));
vi.mock('../components/shipping-review/ReviewInventoryIssueList.vue', () => ({
default: {
name: 'ReviewInventoryIssueList',
template: '<div data-testid="mock-inventory-issues" />',
},
}));
vi.mock('../components/shipping-review/ReviewInventoryCandidatesPanel.vue', () => ({
default: {
name: 'ReviewInventoryCandidatesPanel',
template: '<div data-testid="mock-inventory" />',
},
}));
vi.mock('@/features/shipping-process-gates/components/ProcessGateRecoveryCard.vue', () => ({
default: {
name: 'ProcessGateRecoveryCard',
template: '<div data-testid="mock-process-gate" />',
},
}));
vi.mock('../components/shipping-review/ReviewLlmSuggestionDrawer.vue', () => ({
default: {
name: 'ReviewLlmSuggestionDrawer',
template: '<div data-testid="mock-llm-drawer" />',
},
}));
vi.mock('../components/shipping-review/ReviewVersionHistoryDrawer.vue', () => ({
default: {
name: 'ReviewVersionHistoryDrawer',
props: ['open'],
template: '<div v-if="open" data-testid="mock-versions-drawer" />',
},
}));
vi.mock('../components/shipping-review/ReviewWorkflowProgressPanel.vue', () => ({
default: {
name: 'ReviewWorkflowProgressPanel',
template: '<div data-testid="mock-progress" />',
},
}));
/**
* 挂载复核工作台视图并注入最小 Chat 上下文。
*/
async function mountView() {
const i18n = createI18n({
legacy: false,
locale: 'zh-CN',
messages: {
'zh-CN': {
chat: {
shippingOrderReview: {
title: '订单人工复核',
run: '识别批次 {runNo}',
workItemHeader: '{itemNo} {version}',
backToSession: '返回',
readOnly: '只读',
loading: '加载中',
unavailable: '不可用',
retryLoad: '重试',
documentNavigation: 'PDF 导航',
documents: 'PDF',
unnamedDocument: '未命名',
caseStatus: '{status} · {count}',
caseStatuses: { draft: '草稿', unknown: '未知' },
previewTitle: 'PDF 预览',
previewLoading: '加载 PDF',
previewUnavailable: '无预览',
locateSource: '定位 {field}',
locateUnavailableHint: '无可靠坐标,点击查看诊断',
locateCandidateHint: '候选位置',
dblclickLocateHint: '双击定位',
exceptionNav: {
prev: '上一异常',
next: '下一异常',
prevHint: '上一异常',
nextHint: '下一异常',
},
issues: '问题',
highlightQuality: {
verified: '已验证',
candidate: '候选',
unavailable: '无坐标',
invalid: '无效',
},
orderFields: '订单字段',
schemaVersion: 'V{version}',
lines: '明细',
line: '行 {index}',
noLines: '无明细',
noMachineOrder: '无订单',
createManualDraft: '手工建草稿',
markNonOrder: '非订单',
markQualityIssue: '质量异常',
reparse: '重新识别',
uploadReplacement: '替换 PDF',
saveNow: '保存并校验',
confirmCreate: '确认并建单',
restoreMachine: '恢复',
moreFields: '更多 {count}',
addLine: '新增行',
emptyValue: '空',
valueSources: { machine: '系统' },
primaryBlockTitle: '阻断',
primaryBlockParty: '{party}',
versionHistory: { title: '版本历史' },
workbench: {
mode: {
standard: '标准复核',
evidence: '证据核对',
inventory: '库存处理',
reparse: '重新识别',
confirm_progress: '建单进度',
},
enterInventory: '查看库存问题',
returnStandard: '返回标准复核',
openPdf: '打开 PDF',
closePdf: '关闭 PDF',
pinPdf: '退出后保留',
unpinPdf: '退出后关闭',
pinPdfHint: '退出证据模式后仍保留 PDF 打开(不会固定在视口)',
unpinPdfHint: '退出证据模式时关闭 PDF',
openVersionHistory: '版本历史',
auditFailed: '审计记录失败,敏感面板未打开,请重试',
summaryRail: '摘要',
},
evidenceAt: 'PDF 第 {page} 页',
evidenceNoHighlight: '无坐标',
evidenceDrawer: {
title: '证据核对',
pageUnknown: '页码未知',
prevEvidence: '上一证据',
nextEvidence: '下一证据',
field: '字段:{field}',
currentValue: '当前值',
machineValue: '机器值',
source: '来源',
},
llmSuggestion: { request: '请求 AI' },
restoreMachine: '恢复机器值',
buildEligibility: { confirmBlocked: '不可建单' },
saving: '保存中',
saved: '已保存',
saveFailed: '失败',
versionConflict: { badge: '冲突' },
statusBanner: { unknown: '未知' },
reparseProgress: {
title: '重识别',
subtitle: '',
polling: '',
refreshFailed: '',
failed: '',
retry: '',
stages: {
submitted: '1',
layout_parsing: '2',
extracting: '3',
draft_ready: '4',
},
},
autoProgress: {
status: { unknown: '', needs_retry: '待重试' },
result: '{status}',
checkpoint: '{checkpoint}',
viewTask: '返回对话查看进度',
returnToChat: '返回对话查看进度',
retry: '重试自动推进',
retrySuccess: '已重新触发',
},
confirmSuccess: '{taskNo}',
confirmAutoProgress: '{taskNo}',
confirmProgressFailed: '已创建任务 {taskNo},但自动推进失败,请重试推进',
jumpToCurrentVersion: '跳转',
currentVersionUnavailable: '不可用',
},
},
errors: { generic: '错误' },
},
},
});
const router = createRouter({
history: createMemoryHistory(),
routes: [
{ path: '/chat/:agentId', name: 'Chat', component: { template: '<div />' } },
{
path: '/workspace/shipping-tasks/:taskNo',
name: 'workspace-shipping-tasks',
component: { template: '<div />' },
},
],
});
await router.push({ path: '/chat/agent-1', query: { mode: 'order-review', run_no: 'RUN-1' } });
await router.isReady();
const wrapper = mount(ShippingOrderReviewView, {
global: {
plugins: [i18n, router],
provide: {
[CHAT_PAGE_KEY as symbol]: {
conversationId: 'conv-1',
messages: [],
},
},
stubs: {
ReviewActionConfirmDialog: {
name: 'ReviewActionConfirmDialog',
props: ['action', 'modelValue', 'confirmLoading'],
emits: ['confirm', 'cancel', 'update:modelValue'],
template:
'<div data-testid="review-action-confirm-dialog">'
+ '<button data-testid="review-action-confirm-submit" @click="$emit(\'confirm\', { reasonCode: \'ok\' })">确认</button>'
+ '</div>',
},
ReviewLineNoOverrideDialog: true,
ReviewDocumentEvidenceDrawer: evidenceDrawerStub,
},
},
});
await flushPromises();
return wrapper;
}
/** 将共享 Case fixture 恢复为可编辑草稿,避免跨用例污染确认恢复态。 */
function resetActiveCaseFixture() {
activeCase.value = {
...activeCase.value,
status: 'draft',
confirmed_task_no: null,
post_confirm_auto_progress: null,
};
}
describe('ShippingOrderReviewView layout phase 1', () => {
beforeEach(() => {
vi.clearAllMocks();
resetActiveCaseFixture();
});
it('renders main editor + summary rail without chat context toggle', async () => {
const wrapper = await mountView();
expect(wrapper.find('[data-testid="shipping-order-review-view"]').attributes('data-workbench-mode')).toBe('standard');
expect(wrapper.find('[data-testid="review-main-editor"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="review-build-gate-rail"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="review-document-navigation"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="review-workbench-mode"]').exists()).toBe(true);
expect(wrapper.text()).not.toContain('对话上下文');
expect(wrapper.html()).not.toContain('showContext');
expect(wrapper.html()).not.toContain('hideContext');
});
it('hides PDF evidence drawer in standard mode by default', async () => {
const wrapper = await mountView();
expect(wrapper.find('[data-testid="review-document-evidence-drawer"]').exists()).toBe(false);
});
it('keeps confirm footer visible when draft exists', async () => {
const wrapper = await mountView();
expect(wrapper.find('[data-testid="review-footer-actions"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="review-confirm-create"]').exists()).toBe(true);
});
it('does not render resident AI card without focused field', async () => {
const wrapper = await mountView();
expect(wrapper.find('[data-testid="review-llm-field-entry"]').exists()).toBe(false);
expect(wrapper.find('[data-testid="mock-llm-drawer"]').exists()).toBe(true);
expect(wrapper.html()).not.toContain('panelTitle');
});
it('opens evidence PDF drawer only via locate action, not via input focus', async () => {
const wrapper = await mountView();
const input = wrapper.find('[data-testid="review-header-field-input"]');
expect(input.exists()).toBe(true);
await input.trigger('focus');
await flushPromises();
expect(wrapper.find('[data-testid="shipping-order-review-view"]').attributes('data-workbench-mode')).toBe('standard');
expect(wrapper.find('[data-testid="review-document-evidence-drawer"]').exists()).toBe(false);
const locate = wrapper.find('[data-testid="review-field-locate"]');
expect(locate.exists()).toBe(true);
await locate.trigger('click');
await flushPromises();
expect(wrapper.find('[data-testid="shipping-order-review-view"]').attributes('data-workbench-mode')).toBe('evidence');
expect(wrapper.find('[data-testid="review-document-evidence-drawer"]').exists()).toBe(true);
// 关键断言:定位后字段与 PDF 证据联动高亮。
expect(wrapper.find('[data-testid="review-header-field-input"]').attributes('data-evidence-active')).toBe('true');
});
it('opens evidence PDF drawer via field double-click', async () => {
const wrapper = await mountView();
const input = wrapper.find('[data-testid="review-header-field-input"]');
await input.trigger('dblclick');
await flushPromises();
// 关键断言:双击字段等价于定位原文,进入证据模式。
expect(wrapper.find('[data-testid="shipping-order-review-view"]').attributes('data-workbench-mode')).toBe('evidence');
expect(wrapper.find('[data-testid="review-document-evidence-drawer"]').exists()).toBe(true);
});
it('navigates exception fields from draft issues banner', async () => {
activeCase.value = {
...activeCase.value,
draft: {
...activeCase.value.draft,
issues: [
{
code: 'required_field_missing',
severity: 'blocking',
field_id: 'fld-po',
message: '缺少 PO',
},
],
},
};
const wrapper = await mountView();
expect(wrapper.find('[data-testid="review-exception-nav"]').exists()).toBe(true);
await wrapper.find('[data-testid="review-exception-next"]').trigger('click');
await flushPromises();
// 关键断言:异常导航会打开证据并定位到问题字段。
expect(wrapper.find('[data-testid="shipping-order-review-view"]').attributes('data-workbench-mode')).toBe('evidence');
expect(wrapper.find('[data-testid="review-header-field-input"]').attributes('data-evidence-active')).toBe('true');
});
it('opens evidence as floating panel without docking editor body layout', async () => {
const wrapper = await mountView();
await wrapper.find('[data-testid="review-field-locate"]').trigger('click');
await flushPromises();
const body = wrapper.find('[data-testid="review-editor-body"]');
const drawer = wrapper.find('[data-testid="review-document-evidence-drawer"]');
// 关键断言:定位证据默认浮窗;主编辑区不切换为 PDF 网格列。
expect(drawer.attributes('data-presentation')).toBe('floating');
expect(body.attributes('data-evidence-docked')).toBe('false');
expect(body.classes()).toContain('space-y-4');
expect(body.classes().some((cls) => cls.includes('minmax(280px'))).toBe(false);
});
});
describe('ShippingOrderReviewView audit and progress recovery', () => {
beforeEach(() => {
vi.clearAllMocks();
resetActiveCaseFixture();
vi.mocked(auditWorkspaceShippingOrderReviewVersionHistory).mockResolvedValue({
audited: true,
case_no: 'CASE-1',
});
vi.mocked(auditWorkspaceShippingOrderReviewEligibilityDetails).mockResolvedValue({
audited: true,
case_no: 'CASE-1',
});
});
it('refuses to open version history when access audit fails', async () => {
vi.mocked(auditWorkspaceShippingOrderReviewVersionHistory).mockRejectedValueOnce(new Error('audit down'));
const wrapper = await mountView();
await wrapper.find('[data-testid="review-open-version-history"]').trigger('click');
await flushPromises();
// 关键断言:审计失败有告警且不打开版本历史面板。
expect(wrapper.find('[data-testid="mock-versions-drawer"]').exists()).toBe(false);
expect(messageMocks.warning).toHaveBeenCalledWith('审计记录失败,敏感面板未打开,请重试');
});
it('refuses to open eligibility details when access audit fails', async () => {
vi.mocked(auditWorkspaceShippingOrderReviewEligibilityDetails).mockRejectedValueOnce(new Error('audit down'));
const wrapper = await mountView();
await wrapper.find('[data-testid="review-open-eligibility-details"]').trigger('click');
await flushPromises();
expect(wrapper.find('[data-testid="mock-eligibility-details"]').exists()).toBe(false);
expect(messageMocks.warning).toHaveBeenCalledWith('审计记录失败,敏感面板未打开,请重试');
});
it('restores amber retry banner from post_confirm_auto_progress after reload', async () => {
activeCase.value = {
...activeCase.value,
status: 'confirmed',
confirmed_task_no: 'SN-RECOVER-1',
post_confirm_auto_progress: {
task_no: 'SN-RECOVER-1',
needs_retry: true,
status: 'needs_retry',
message: '已建单但任务仍停在待推进,可重试自动推进',
},
};
const wrapper = await mountView();
await flushPromises();
const banner = wrapper.find('[data-testid="review-confirm-outcome"]');
// 关键断言:页面重载后仍能从 Case 投影恢复推进失败重试入口。
expect(banner.exists()).toBe(true);
expect(banner.attributes('data-progress-failed')).toBe('true');
expect(wrapper.find('[data-testid="retry-auto-progress-after-confirm"]').exists()).toBe(true);
expect(banner.text()).toContain('SN-RECOVER-1');
});
it('treats HTTP/confirm_ok success with confirm_outcome failed as progress failure', async () => {
confirmMock.mockResolvedValueOnce({
task_no: 'SN-CONFIRM-PROGRESS-FAIL',
confirm_ok: true,
confirm_outcome: 'confirmed_auto_progress_failed',
auto_progress_started: false,
auto_progress: {
status: 'enqueue_failed',
message: '入队失败',
checkpoint: 'created',
},
case: activeCase.value,
});
const wrapper = await mountView();
await wrapper.find('[data-testid="review-confirm-create"]').trigger('click');
await flushPromises();
await wrapper.find('[data-testid="review-action-confirm-submit"]').trigger('click');
await flushPromises();
const banner = wrapper.find('[data-testid="review-confirm-outcome"]');
// 关键断言:不得仅凭 success/confirm_ok 判定推进成功;须读 confirm_outcome。
expect(confirmMock).toHaveBeenCalled();
expect(banner.exists()).toBe(true);
expect(banner.attributes('data-progress-failed')).toBe('true');
expect(messageMocks.warning).toHaveBeenCalled();
});
});
describe('ShippingOrderReviewView viewport layout remediation', () => {
beforeEach(() => {
vi.clearAllMocks();
resetActiveCaseFixture();
});
it('uses a single primary vertical scroll container (not nested editor/rail scroll)', async () => {
const wrapper = await mountView();
const scroll = wrapper.find('[data-testid="review-workbench-scroll"]');
const editor = wrapper.find('[data-testid="review-main-editor"]');
const rail = wrapper.find('[data-testid="review-build-gate-rail"]');
// 关键断言:仅外层主滚动带 overflow-y-auto;编辑区与摘要栏不得再套纵向滚动。
expect(scroll.classes()).toContain('overflow-y-auto');
expect(editor.classes()).not.toContain('overflow-y-auto');
expect(rail.classes()).not.toContain('overflow-y-auto');
expect(editor.classes()).not.toContain('xl:max-h-[calc(100vh-12rem)]');
});
it('keeps footer sticky for always-visible actions', async () => {
const wrapper = await mountView();
const footer = wrapper.find('[data-testid="review-footer-actions"]');
expect(footer.classes()).toContain('sticky');
expect(footer.classes()).toContain('bottom-0');
});
it('keeps summary rail visible in floating evidence mode and docks only on demand', async () => {
const wrapper = await mountView();
await wrapper.find('[data-testid="review-field-locate"]').trigger('click');
await flushPromises();
const rail = wrapper.find('[data-testid="review-build-gate-rail"]');
// 关键断言:浮窗证据不再为挤 PDF 而隐藏摘要栏。
expect(rail.classes()).not.toContain('hidden');
expect(rail.classes()).toContain('xl:sticky');
await wrapper.find('[data-testid="review-evidence-toggle-dock"]').trigger('click');
await flushPromises();
const body = wrapper.find('[data-testid="review-editor-body"]');
const drawer = wrapper.find('[data-testid="review-document-evidence-drawer"]');
// 关键断言:用户主动固定后才进入双栏网格。
expect(body.attributes('data-evidence-docked')).toBe('true');
expect(drawer.attributes('data-docked')).toBe('true');
expect(wrapper.html()).toContain('minmax(420px,1fr)');
});
});
File diff suppressed because it is too large. Load diff
@@ -1,42 +1,78 @@
/**
* features/shipping-process-gates/components/ProcessGateRecoveryCard.spec.ts
* 用途:验证待处理事项卡片不展示未知内部编号和技术诊断文本。
* 依赖:Vitest、Vue Test Utils、vue-i18n。
* 逻辑:构造未知环节、动作及技术自由文本,断言全部回退为业务文案。
* 用途:验证待处理事项卡片不展示未知内部编号和技术诊断文本;审计缓存随 Execution 切换清空。
* 依赖:Vitest、Vue Test Utils、vue-i18n、process-gates.api mock。
* 逻辑:构造未知环节/动作/技术自由文本;断言业务文案与审计 i18n;切换 execution_no 后清空审计。
*/
import { mount } from '@vue/test-utils';
import { flushPromises, mount } from '@vue/test-utils';
import { createI18n } from 'vue-i18n';
import { describe, expect, it } from 'vitest';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import workspaceZhCn from '@/locales/zh-CN/workspace.json';
import ProcessGateRecoveryCard from './ProcessGateRecoveryCard.vue';
import type { ShippingProcessGateUserSummary } from '../types/process-gate.types';
const listAuditMock = vi.fn();
vi.mock('../api/process-gates.api', () => ({
listWorkspaceProcessGateAuditEvents: (...args: unknown[]) => listAuditMock(...args),
postWorkspaceProcessGateAction: vi.fn(),
}));
vi.mock('vue-router', () => ({
useRouter: () => ({ push: vi.fn() }),
}));
vi.mock('@/shared/composables/useMessage', () => ({
useMessage: () => ({
success: vi.fn(),
warning: vi.fn(),
error: vi.fn(),
}),
}));
const i18n = createI18n({
legacy: false,
locale: 'zh-CN',
messages: { 'zh-CN': { workspace: workspaceZhCn } },
});
describe('ProcessGateRecoveryCard', () => {
it('does not expose internal gate, action or diagnostic text', () => {
const summary: ShippingProcessGateUserSummary = {
execution_no: 'EXEC-1',
function baseSummary(overrides: Partial<ShippingProcessGateUserSummary> = {}): ShippingProcessGateUserSummary {
return {
execution_no: 'EXEC-1',
status: 'blocked',
current_blocking_gate: {
gate_code: 'auto_build_gate_quality_gate_passed',
label: 'quality_gate_internal',
status: 'blocked',
current_blocking_gate: {
gate_code: 'auto_build_gate_quality_gate_passed',
label: 'quality_gate_internal',
status: 'blocked',
sequence_no: 1,
evaluation_version: 1,
blocking_reason_code: 'internal_reason_code',
next_action_code: 'internal_retry_action',
},
blocking_message: 'HTTP 500 error: node_id=abc',
diagnostic_hint: 'traceback: C:\\service\\worker.py',
responsible_party: 'owner',
};
sequence_no: 1,
evaluation_version: 1,
blocking_reason_code: 'internal_reason_code',
next_action_code: 'internal_retry_action',
},
blocking_message: 'HTTP 500 error: node_id=abc',
diagnostic_hint: 'traceback: C:\\service\\worker.py',
responsible_party: 'owner',
...overrides,
};
}
describe('ProcessGateRecoveryCard', () => {
beforeEach(() => {
listAuditMock.mockReset();
listAuditMock.mockResolvedValue({
items: [
{
id: 1,
event_type: 'process_gate_attempt_started',
created_at: '2026-08-01T00:00:00Z',
},
],
});
});
it('does not expose internal gate, action or diagnostic text', () => {
const wrapper = mount(ProcessGateRecoveryCard, {
props: { summary, canHandle: true },
props: { summary: baseSummary(), canHandle: true },
global: { plugins: [i18n] },
});
const text = wrapper.text();
@@ -54,4 +90,34 @@ describe('ProcessGateRecoveryCard', () => {
expect(text).not.toContain(technicalText);
}
});
it('maps audit event codes to business labels and clears cache on execution change', async () => {
const wrapper = mount(ProcessGateRecoveryCard, {
props: { summary: baseSummary({ execution_no: 'EXEC-1' }), canHandle: true },
global: { plugins: [i18n] },
});
await wrapper.get('[data-testid="process-gate-view-audit"]').trigger('click');
await flushPromises();
expect(listAuditMock).toHaveBeenCalledWith('EXEC-1', 1, 20);
expect(wrapper.text()).toContain('开始执行处理');
expect(wrapper.text()).not.toContain('process_gate_attempt_started');
listAuditMock.mockResolvedValue({
items: [
{
id: 2,
event_type: 'process_gate_blocked',
created_at: '2026-08-01T01:00:00Z',
},
],
});
await wrapper.setProps({ summary: baseSummary({ execution_no: 'EXEC-2' }) });
await flushPromises();
expect(wrapper.text()).not.toContain('开始执行处理');
await wrapper.get('[data-testid="process-gate-view-audit"]').trigger('click');
await flushPromises();
expect(listAuditMock).toHaveBeenCalledWith('EXEC-2', 1, 20);
expect(wrapper.text()).toContain('处理环节已阻断');
});
});
@@ -1,19 +1,43 @@
/**
* features/shipping-process-gates/components/ProcessGateRecoveryCard.vue
* 用途:任务工作台展示当前待处理环节、责任方、主恢复动作与 Gate 审计入口。
* 用途:任务工作台展示当前待处理环节、原因、业务事实 details、责任方、下一步说明与恢复动作。
* 依赖:useShippingProcessGateRecovery、processGateNavigation、process-gates.api、
* ShippingProcessGateUserSummary。
* 逻辑:导航类动作 router.push;POST 类动作调 Workspace API;409 触发 refreshed;
* 可展开查看审计事件;canHandle=false 时只读;禁止展示内部编号与技术诊断原文。
* ShippingProcessGateUserSummary / ShippingExplainabilityReason。
* 逻辑:导航类动作 router.push;confirm_customer 发射 confirmCustomer 由父级开弹窗;
* POST 类动作调 Workspace API;409 触发 refreshed;
* 展示 explainability.details 白名单业务事实;下一步文案独立于按钮;
* 可展开审计;canHandle=false 时仍展示下一步说明;禁止堆栈/路径/SQL。
*/
<script setup lang="ts">
import { computed, ref } from 'vue';
import { computed, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { useShippingProcessGateRecovery } from '../composables/useShippingProcessGateRecovery';
import type { ProcessGateNavigationContext } from '../composables/processGateNavigation';
import { listWorkspaceProcessGateAuditEvents } from '../api/process-gates.api';
import type { ShippingProcessGateUserSummary } from '../types/process-gate.types';
/** 允许在卡片上展示的业务事实键(与后端 _USER_FACING_DETAIL_KEYS 对齐)。 */
const DETAIL_FACT_KEYS = [
'source_code',
'source_codes',
'unavailable_source_codes',
'unavailable_reasons',
'matched_rule_codes',
'raw_rule_source_codes',
'candidate_inventory_source_codes',
'line_key',
'line_index',
'field_code',
'request_id',
'process_status',
'match_status',
'task_no',
'has_inventory_lines',
'has_export',
'execution_no',
'inventory_file_id',
] as const;
const props = defineProps<{
summary: ShippingProcessGateUserSummary | null | undefined;
canHandle: boolean;
@@ -24,6 +48,8 @@ const emit = defineEmits<{
refreshed: [];
refreshNeeded: [];
navigate: [];
/** 建单后客户确认:父级打开 ShippingCustomerConfirmDialog */
confirmCustomer: [taskNo: string];
}>();
const { t, te } = useI18n();
@@ -33,12 +59,33 @@ const auditLoading = ref(false);
const auditError = ref('');
const auditItems = ref<Array<Record<string, unknown>>>([]);
/**
* Execution 切换时清空审计缓存,避免组件复用展示上一任务的审计。
*/
watch(
() => props.summary?.execution_no,
() => {
auditOpen.value = false;
auditLoading.value = false;
auditError.value = '';
auditItems.value = [];
},
);
const blockingGate = computed(() => props.summary?.current_blocking_gate || null);
const nextActionCode = computed(() =>
String(props.summary?.next_action_code || blockingGate.value?.next_action_code || '').trim(),
);
const hasRecoveryAction = computed(() => Boolean(blockingGate.value && nextActionCode.value));
/** 最近 Attempt 序号(用户可见);用于展示「已尝试 N 次」,不推导百分比。 */
const latestAttemptNo = computed(() => {
const raw = (blockingGate.value as { latest_attempt?: { attempt_no?: number } } | null)
?.latest_attempt?.attempt_no;
const n = Number(raw);
return Number.isFinite(n) && n > 0 ? n : null;
});
/** 仅允许自然语言业务说明进入界面,内部标识、路径和异常信息统一隐藏。 */
function safeBusinessText(value: unknown): string {
const text = String(value || '').trim();
@@ -86,20 +133,86 @@ const diagnosticHint = computed(() => safeBusinessText(props.summary?.diagnostic
* 责任方业务标签(owner/worker/system/admin/external)。
*/
const responsiblePartyLabel = computed(() => {
const code = String(props.summary?.responsible_party || '').trim();
const code = String(
props.summary?.explainability?.responsible_party
|| props.summary?.responsible_party
|| '',
).trim();
if (!code) return '';
const key = `workspace.shippingNotice.processGate.parties.${code}`;
return te(key) ? t(key) : code;
});
/**
* 触发恢复动作:导航 / POST;409 时通知父级刷新最新 Gate 投影。
* 独立「下一步」业务说明:优先动作 i18n,无动作时用无可执行提示。
*/
const nextActionDescription = computed(() => {
if (actionLabel.value) {
return t('workspace.shippingNotice.processGate.nextActionHint', { action: actionLabel.value });
}
return t('workspace.shippingNotice.processGate.noAction');
});
/**
* 将 details 中的值格式化为可读短文本。
*/
function formatDetailValue(value: unknown): string {
if (value == null) return '';
if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
return String(value);
}
if (Array.isArray(value)) {
return value.map((item) => formatDetailValue(item)).filter(Boolean).join('、');
}
if (typeof value === 'object') {
return Object.entries(value as Record<string, unknown>)
.map(([key, item]) => `${key}=${formatDetailValue(item)}`)
.join(';');
}
return '';
}
/**
* explainability.details 业务事实行(库存源/规则/行号/request_id)。
*/
const detailFactRows = computed(() => {
const details = props.summary?.explainability?.details;
if (!details || typeof details !== 'object') return [] as Array<{ key: string; label: string; value: string }>;
const rows: Array<{ key: string; label: string; value: string }> = [];
for (const key of DETAIL_FACT_KEYS) {
if (!(key in details)) continue;
const value = formatDetailValue((details as Record<string, unknown>)[key]);
if (!value) continue;
const labelKey = `workspace.shippingNotice.processGate.detailKeys.${key}`;
rows.push({
key,
label: te(labelKey) ? t(labelKey) : key,
value,
});
}
const requestId = String(props.summary?.explainability?.request_id || '').trim();
if (requestId && !rows.some((row) => row.key === 'request_id')) {
rows.push({
key: 'request_id',
label: t('workspace.shippingNotice.processGate.detailKeys.request_id'),
value: requestId,
});
}
return rows;
});
/**
* 触发恢复动作:本地客户弹窗 / 导航 / POST;409 时通知父级刷新最新 Gate 投影。
*/
async function runPrimaryAction() {
if (!props.summary || !props.canHandle || busy.value) return;
const result = await submitPrimaryAction(props.summary, {
navigationContext: props.navigationContext,
});
if (result.outcome === 'confirm_customer' && result.taskNo) {
emit('confirmCustomer', result.taskNo);
return;
}
if (result.outcome === 'navigated') {
emit('navigate');
return;
@@ -142,6 +255,16 @@ function formatAuditTime(value: unknown): string {
const date = new Date(text);
return Number.isNaN(date.getTime()) ? text : date.toLocaleString();
}
/**
* 将审计事件码映射为用户可读业务文案;未知码回退通用描述,不暴露内部码。
*/
function formatAuditEventLabel(item: Record<string, unknown>): string {
const code = String(item.event_type || item.action || '').trim();
if (!code) return t('workspace.shippingNotice.processGate.auditEventFallback');
const key = `workspace.shippingNotice.processGate.auditEvents.${code}`;
return te(key) ? t(key) : t('workspace.shippingNotice.processGate.auditEventFallback');
}
</script>
<template>
@@ -161,10 +284,36 @@ function formatAuditTime(value: unknown): string {
<dt class="text-muted">{{ $t('workspace.shippingNotice.processGate.blockingMessage') }}</dt>
<dd class="text-secondary">{{ blockingReasonLabel }}</dd>
</div>
<div v-if="latestAttemptNo != null" data-testid="process-gate-attempt-count">
<dt class="text-muted">{{ $t('workspace.shippingNotice.processGate.attemptCount') }}</dt>
<dd class="text-secondary">
{{ $t('workspace.shippingNotice.processGate.attemptCountValue', {
current: latestAttemptNo,
max: 3,
}) }}
</dd>
</div>
<div v-if="responsiblePartyLabel">
<dt class="text-muted">{{ $t('workspace.shippingNotice.processGate.responsibleParty') }}</dt>
<dd class="text-secondary">{{ responsiblePartyLabel }}</dd>
</div>
<div data-testid="process-gate-next-action">
<dt class="text-muted">{{ $t('workspace.shippingNotice.processGate.nextAction') }}</dt>
<dd class="text-secondary">{{ nextActionDescription }}</dd>
</div>
<div v-if="detailFactRows.length" data-testid="process-gate-detail-facts">
<dt class="text-muted">{{ $t('workspace.shippingNotice.processGate.detailFacts') }}</dt>
<dd class="mt-1 space-y-1 text-secondary">
<div
v-for="row in detailFactRows"
:key="row.key"
class="flex flex-wrap gap-x-2 text-xs"
>
<span class="text-muted">{{ row.label }}</span>
<span class="font-mono break-all">{{ row.value }}</span>
</div>
</dd>
</div>
<div v-if="diagnosticHint">
<dt class="text-muted">{{ $t('workspace.shippingNotice.processGate.diagnosticHint') }}</dt>
<dd class="text-secondary">{{ diagnosticHint }}</dd>
@@ -200,7 +349,7 @@ function formatAuditTime(value: unknown): string {
<p v-else-if="!auditItems.length" class="text-muted">{{ $t('workspace.shippingNotice.processGate.auditEmpty') }}</p>
<ul v-else class="space-y-2">
<li v-for="(item, index) in auditItems" :key="String(item.id || index)" class="border-t border-default pt-2 first:border-t-0 first:pt-0">
<div class="font-medium text-secondary">{{ item.event_type || item.action || '—' }}</div>
<div class="font-medium text-secondary">{{ formatAuditEventLabel(item) }}</div>
<div class="text-muted">{{ formatAuditTime(item.created_at) }}</div>
</li>
</ul>
@@ -3,10 +3,19 @@
* 用途:将服务端下发的门禁恢复动作映射为 Vue Router 深链(复核台 / 任务工作台)。
* 依赖:process-gate.types、vue-router RouteLocationRaw。
* 逻辑:与 process_gate_projection.navigation 对齐;禁止本地发明 action_code。
* confirm_customer 不属于复核导航:由本地客户选择弹窗完成(建单后 customer_review)。
*/
import type { RouteLocationRaw } from 'vue-router';
import type { ShippingProcessGateUserSummary } from '../types/process-gate.types';
/**
* 前端本地 UX 动作:不 router.push、不 POST Gate API,由挂载方打开专用弹窗/面板。
* 与「复核页不做客户重识别」的产品边界一致。
*/
export const PROCESS_GATE_LOCAL_UX_ACTIONS = new Set<string>([
'confirm_customer',
]);
/** 点击后仅导航、不 POST 的人工入口动作(regenerate_manual_upload_todo 除外)。 */
export const PROCESS_GATE_NAVIGATION_ACTIONS = new Set<string>([
'open_order_review',
@@ -14,7 +23,6 @@ export const PROCESS_GATE_NAVIGATION_ACTIONS = new Set<string>([
'open_profile_review',
'edit_order_fields',
'edit_reservation',
'confirm_customer',
'adjudicate_duplicate',
'resolve_field_conflicts',
'open_inventory_match_review',
@@ -23,6 +31,25 @@ export const PROCESS_GATE_NAVIGATION_ACTIONS = new Set<string>([
'confirm_inventory_field_mapping',
]);
/**
* 判断动作码是否为前端本地 UX(弹窗)恢复动作。
*/
export function isProcessGateLocalUxAction(actionCode: string): boolean {
return PROCESS_GATE_LOCAL_UX_ACTIONS.has(String(actionCode || '').trim());
}
/**
* 从 Gate 摘要解析任务编号(客户确认 API 锚点)。
* @returns 大写 task_no;缺失时空串
*/
export function resolveProcessGateTaskNo(summary: ShippingProcessGateUserSummary): string {
return String(
summary.navigation?.task_no
|| summary.task_no
|| '',
).trim().toUpperCase();
}
export interface ProcessGateNavigationContext {
agentId?: string;
conversationId?: string;
@@ -1,8 +1,9 @@
/**
* features/shipping-process-gates/composables/useShippingProcessGateRecovery.ts
* 用途:任务工作台门禁恢复动作编排(导航、幂等键、版本锁、409 刷新)。
* 用途:任务工作台门禁恢复动作编排(导航、本地 UX 弹窗、幂等键、版本锁、409 刷新)。
* 依赖:process-gates.api、processGateNavigation、process-gate.types、useMessage。
* 逻辑:ProcessGateRecoveryCard 调用 submitPrimaryAction;禁止本地发明 action_code。
* 逻辑:ProcessGateRecoveryCard 调用 submitPrimaryAction;禁止本地发明 action_code;
* confirm_customer 打开客户选择弹窗,不跳转订单复核。
*/
import { ref } from 'vue';
import { useI18n } from 'vue-i18n';
@@ -16,19 +17,24 @@ import type {
} from '../types/process-gate.types';
import {
buildProcessGateNavigationRoute,
isProcessGateLocalUxAction,
isProcessGateNavigationAction,
resolveProcessGateTaskNo,
type ProcessGateNavigationContext,
} from './processGateNavigation';
export type ProcessGateActionOutcome =
| 'submitted'
| 'navigated'
| 'confirm_customer'
| 'refresh_needed'
| 'failed'
| 'noop';
export interface ProcessGateActionResult {
outcome: ProcessGateActionOutcome;
/** confirm_customer 时带回的任务编号 */
taskNo?: string;
}
function newIdempotencyKey(): string {
@@ -49,8 +55,9 @@ export function useShippingProcessGateRecovery() {
const busy = ref(false);
/**
* 提交或导航当前阻断 Gate 的主要恢复动作。
* 核心逻辑:evaluation_version 来自 current_blocking_gate;409 返回 refresh_needed。
* 提交、导航或打开本地 UX(客户弹窗)以恢复当前阻断 Gate。
* 核心逻辑:evaluation_version 来自 current_blocking_gate;409 返回 refresh_needed;
* confirm_customer 需 task_no,不走复核深链。
*/
async function submitPrimaryAction(
summary: ShippingProcessGateUserSummary,
@@ -66,6 +73,16 @@ export function useShippingProcessGateRecovery() {
return { outcome: 'noop' };
}
// [STEP] 客户确认:建单后 customer_review,打开选择弹窗,禁止跳转复核页。
if (isProcessGateLocalUxAction(actionCode) && actionCode === 'confirm_customer') {
const taskNo = resolveProcessGateTaskNo(summary);
if (!taskNo) {
msg.warning(t('workspace.shippingNotice.processGate.customerTaskMissing'));
return { outcome: 'failed' };
}
return { outcome: 'confirm_customer', taskNo };
}
if (isProcessGateNavigationAction(actionCode)) {
const route = buildProcessGateNavigationRoute(
summary,
@@ -1,10 +1,15 @@
/**
* features/shipping-process-gates/types/process-gate.types.ts
* 用途:全门禁恢复 API 与工作台卡片类型;与后端 process_gate_projection 对齐。
* 依赖:features/chat/types/shipping.api.types 中的 Gate 联合类型与摘要接口。
* 逻辑:避免重复定义 action/gate code 联合;Workspace API 专用响应在此扩展。
* 用途:全门禁恢复 API 与工作台卡片类型;与后端 process_gate_projection /
* error_explainability_contract 对齐。
* 依赖:features/chat/types/shipping.api.types 中的 Gate 联合类型、摘要与可解释性类型。
* 逻辑:避免重复定义 action/gate code 联合;Workspace API 专用响应在此扩展;
* 门禁阻断详情复用 ShippingExplainabilityReason 形状。
*/
import type {
ShippingExplainabilityReason,
ShippingInventorySourceLineBlockReasonCode,
ShippingInventorySourceUnavailableReasonCode,
ShippingProcessGateActionCode,
ShippingProcessGateCode,
ShippingProcessGateProjection,
@@ -13,6 +18,9 @@ import type {
} from '@/features/chat/types/shipping.api.types';
export type {
ShippingExplainabilityReason,
ShippingInventorySourceLineBlockReasonCode,
ShippingInventorySourceUnavailableReasonCode,
ShippingProcessGateActionCode,
ShippingProcessGateCode,
ShippingProcessGateProjection,
@@ -20,6 +28,9 @@ export type {
ShippingProcessGateUserSummary,
};
/** 门禁阻断原因详情(用户可见;details 仅业务事实)。 */
export type ShippingProcessGateBlockingReasonDetail = ShippingExplainabilityReason;
export interface ShippingProcessGateActionRequest {
action_code: ShippingProcessGateActionCode | string;
expected_gate_version: number;
@@ -4,7 +4,8 @@
* 依赖:ProcessGateRecoveryCard、shipping.api、shipping-tasks.api、ManualUploadEvidenceDialog。
* 逻辑:优先展示 ui_state.process_gate 阻断信息与 next_action_code;禁止按 process_status
* 二次推导门禁动作;存在 current_blocking_gate 时不渲染旧 action_buttons(Gate 唯一真相);
* 管理员 can_handle=false 时只读;无 Gate 阻断时 wait_manual_upload 允许下载 Excel + 人工上传凭据。
* confirm_customer 打开本面板客户弹窗(非跳转复核);管理员 can_handle=false 时只读;
* 无 Gate 阻断时 wait_manual_upload 允许下载 Excel + 人工上传凭据。
*/
<script setup lang="ts">
import { computed, ref } from 'vue';
@@ -374,6 +375,7 @@ async function runAction(action: ShippingChatAction) {
}"
@refreshed="afterSuccess"
@refresh-needed="afterSuccess"
@confirm-customer="() => void openCustomerDialog()"
/>
<section
v-if="!hasBlockingGate"
+127 -3
View File
@@ -2787,6 +2787,7 @@
"refreshResults": "Read again",
"resultsLoading": "Reading current sample...",
"resultsFailed": "No value was read or the read failed. Check the annotations in the editor.",
"noTrainingSample": "There is no annotation/training sample available for validation.",
"headerResults": "Order header",
"lineResults": "Order lines",
"noHeaderResults": "No order header fields were read from the current sample.",
@@ -3653,6 +3654,15 @@
"refresh": "Refresh",
"export": "Export CSV",
"exporting": "Exporting...",
"exportDone": "Download started",
"moreActions": "More",
"copied": "Copied",
"copyId": "Copy ID",
"techRefsHint": "Technical IDs are collapsed; click a chip to copy.",
"hashSection": "Hash summary (diagnostics)",
"scrollHint": "The main table shows business fields only—no horizontal scroll. WF/Item/Run IDs appear as compact chips under business refs; click to copy.",
"showTechRefs": "Show technical IDs",
"hideTechRefs": "Hide technical IDs",
"apply": "Apply",
"loading": "Loading...",
"empty": "No audit events",
@@ -3667,11 +3677,118 @@
"total": "{count} total",
"previous": "Previous",
"next": "Next",
"labels": {
"eventTypes": {
"fallback": "Audit event",
"workflow_item_created": "Workflow item created",
"review_field_changed": "Review field changed",
"inventory_routing_rerouted": "Inventory routing recalculated",
"inventory_routing_suggestion_adopted": "Rule suggestion adopted",
"inventory_routing_manual_kept": "Manual inventory decision kept",
"audit_access": "Audit access",
"shipping_resource_accessed": "Resource accessed",
"process_gate_attempt_started": "Gate processing started",
"process_gate_blocked": "Gate blocked",
"process_gate_passed": "Gate passed",
"process_gate_recovery_requested": "Gate recovery requested",
"chat_process_gate_retried": "Chat: gate retried",
"chat_process_gate_taken_over": "Chat: gate taken over",
"chat_process_gate_skipped": "Chat: gate skipped",
"candidate_qualification_evaluated": "Candidate qualification evaluated",
"upload_rpa_triggered": "Freight upload RPA triggered"
},
"actions": {
"fallback": "Business action",
"create": "Create",
"update": "Update",
"export": "Export",
"verify_hash_chain": "Verify hash chain",
"read": "Read"
},
"reasonCodes": {
"fallback": "Business reason",
"no_inventory_source_candidates": "No inventory source rule matched",
"inventory_source_unavailable": "Inventory source unavailable",
"require_manual_review": "Manual review required",
"layout_parse_failed": "Layout parsing failed",
"unknown_business_failure": "Business processing failed",
"customer_unresolved": "Customer could not be identified",
"customer_ambiguous": "Multiple customers matched",
"reservation_missing": "Valid reservation is missing",
"reservation_duplicate": "Reservation is already used by another order",
"duplicate_unresolved": "Suspected duplicate order is unresolved",
"attachment_corrupted": "Attachment is corrupted",
"attachment_size_exceeded": "Attachment exceeds size limit",
"attachment_format_unsupported": "Attachment format is unsupported",
"attachment_security_blocked": "Attachment blocked for security reasons",
"attachment_replaced": "Shipping notice attachment was replaced",
"order_extraction_failed": "Order field extraction failed",
"order_extraction_cancelled": "Order extraction was cancelled",
"inventory_rpa_exhausted": "Inventory RPA retries exhausted",
"inventory_file_missing": "Inventory file is missing",
"inventory_match_failed": "Inventory matching failed",
"inventory_insufficient": "Insufficient inventory",
"excel_not_ready": "Excel generation conditions are not met",
"artifact_generation_failed": "Excel generation failed",
"upload_rpa_failed": "Freight platform upload failed",
"upload_result_unknown": "Upload result is temporarily unknown",
"manual_upload_pending": "Download Excel, upload on freight platform, then register the result",
"task_cancelled_by_user": "Task was cancelled by the user",
"task_voided_for_correction": "Task was voided for correction",
"task_archived": "Task was archived",
"task_rejected_by_user": "Candidate/task was rejected by the user",
"task_closed_after_upload": "Task closed after successful upload",
"void_blocked_external_uploaded": "External fulfillment exists; void is blocked — archive instead",
"gate_invalidated": "Upstream result changed; gate must be re-evaluated",
"technical_retry_exhausted": "Automatic retries exhausted",
"business_table_not_found": "Business table was not found",
"generic_gate_blocked": "Generic order recognition gate blocked",
"upload_rpa_login_failed": "Freight platform login failed",
"upload_platform_rejected": "Freight platform rejected the upload",
"inventory_mapping_required": "Inventory field mapping requires confirmation",
"inventory_shortage_review_required": "Inventory shortage requires review",
"inventory_source_conflicted": "Conflicting inventory source rules require review",
"inventory_source_changed": "Confirmed inventory source configuration has changed",
"inventory_source_identity_mismatch": "Task identity does not match inventory source/warehouse",
"inventory_multi_file_conflict": "Conflicting results across inventory files",
"inventory_sku_not_found": "SKU was not found in inventory",
"inventory_reservation_not_found": "Reservation was not found in inventory",
"inventory_warehouse_mismatch": "Warehouse does not match order requirements",
"inventory_required_column_missing": "Required inventory column is missing",
"inventory_column_ambiguous": "Inventory column mapping is ambiguous",
"excel_template_missing": "Shipping Excel template is missing",
"excel_input_incomplete": "Inputs required to generate Excel are incomplete",
"artifact_validation_failed": "Excel artifact validation failed",
"late_callback_ignored": "Late external callback was ignored",
"close_blocked_missing_receipt": "Upload receipt is missing; close is blocked"
},
"actorTypes": {
"user": "Business user",
"admin": "Administrator",
"system": "System",
"rpa": "RPA",
"unknown": "Unknown actor"
},
"results": {
"success": "Success",
"failed": "Failed",
"rejected": "Rejected",
"ok": "Success"
}
},
"filters": {
"eventType": "Event type",
"eventTypeGroup": "Event group",
"eventTypeGroupReviewWorkbench": "Review workbench",
"eventTypeGroupChatWorkbench": "Chat workbench",
"eventTypeGroupProcessGate": "Process Gate",
"eventTypeGroupQualification": "Candidate qualification",
"eventTypeGroupWorkflowNode": "Workflow node",
"actorType": "Actor type",
"runNo": "Run no.",
"taskNo": "Task no.",
"candidateNo": "Candidate no.",
"gateCode": "Node / gate code",
"operationId": "operation_id",
"q": "ID search",
"all": "All",
@@ -3685,7 +3802,8 @@
"createdFrom": "From",
"createdTo": "To",
"workflowId": "Workflow",
"workflowItemId": "Workflow Item"
"workflowItemId": "Workflow Item",
"reasonCode": "Reason code"
},
"columns": {
"time": "Time",
@@ -3697,7 +3815,10 @@
"conversation": "Conversation",
"reviewCase": "Case",
"workflow": "Workflow",
"workflowItem": "Item"
"workflowItem": "Item",
"reasonCode": "Reason",
"businessRefs": "Business refs",
"refs": "Related IDs"
},
"sensitiveRedacted": "Sensitive snapshots and diffs are redacted for your account.",
"verifyChain": "Verify hash chain",
@@ -3712,7 +3833,10 @@
"chainSummary": "Association chain: {total} events{truncated}",
"chainTruncated": " (truncated)",
"eventHash": "Event hash",
"previousEventHash": "Previous hash"
"previousEventHash": "Previous hash",
"showAdvancedFilters": "More filters",
"hideAdvancedFilters": "Hide filters",
"techRefs": "Technical IDs"
},
"shippingProcessGates": {
"title": "Process Gate diagnostics",
+233 -2
View File
@@ -1447,8 +1447,120 @@
"evidenceSummary": "Select a field's location icon to inspect its evidence.",
"evidenceAt": "PDF page {page}",
"evidenceNoHighlight": "This evidence has no reliable coordinates. Only its page and quote are shown; no highlight is fabricated.",
"evidenceInvalidHighlight": "The coordinates are invalid or do not match the field value; highlighting is disabled.",
"highlightQuality": {
"verified": "Verified",
"candidate": "Candidate",
"unavailable": "No coordinates",
"invalid": "Invalid coordinates"
},
"highlightSource": {
"pdf_coordinate": "PDF coordinates",
"frozen_layout_cell": "Frozen layout cell",
"native_glyph": "Native glyphs",
"ocr": "OCR",
"machine_extraction": "Machine extraction",
"unknown": "Unknown source"
},
"highlightLegend": {
"verified": "Verified location (solid yellow)",
"candidate": "Candidate location — not strictly verified (dashed orange)"
},
"coordinateIssues": {
"coordinate_missing": "No reliable field-level coordinates",
"coordinate_bbox_invalid": "Invalid coordinate geometry",
"coordinate_page_missing": "Page number is missing",
"coordinate_page_out_of_range": "Page number is out of range",
"duplicate_text_coordinate_ambiguous": "Duplicate text makes coordinates ambiguous",
"value_bbox_text_mismatch": "Highlighted text does not match the field value",
"quote_not_independent": "No independent region text to prove the highlight matches the value",
"cell_token_unbound": "Cell is not bound to text tokens",
"ocr_confidence_insufficient": "OCR confidence is too low",
"ocr_multi_candidate": "OCR returned multiple candidates",
"html_only_no_pdf_bbox": "HTML structure only; no PDF coordinates",
"coordinate_outside_table": "Coordinates fall outside the table",
"coordinate_shared_token_conflict": "Text tokens are shared by multiple cells"
},
"evidenceDrawer": {
"title": "Evidence review",
"pageUnknown": "Page unknown",
"prevEvidence": "Previous evidence",
"nextEvidence": "Next evidence",
"field": "Field: {field}",
"currentValue": "Current value",
"machineValue": "Machine value",
"source": "Source",
"highlightQuality": "Highlight quality",
"highlightSource": "Coordinate source",
"layoutPath": "Layout path",
"detailsToggle": "Evidence details"
},
"previewZoom": {
"fitWidth": "Fit width",
"fitWidthShort": "Width",
"fitPage": "Fit page",
"fitPageShort": "Page",
"actual": "Actual size 100%",
"jumpPage": "Jump to page",
"go": "Go"
},
"workbench": {
"mode": {
"standard": "Standard review",
"evidence": "Evidence review",
"inventory": "Inventory handling",
"reparse": "Re-parse",
"confirm_progress": "Create progress"
},
"enterInventory": "View inventory issues",
"returnStandard": "Back to standard review",
"openPdf": "Open PDF",
"closePdf": "Close PDF",
"pinPdf": "Keep open after exit",
"unpinPdf": "Close on exit",
"pinPdfHint": "Keep the PDF open after leaving evidence mode (not a docked sidebar)",
"unpinPdfHint": "Close the PDF when leaving evidence mode",
"expandPdf": "Expand",
"collapsePdf": "Collapse",
"expandPdfHint": "Enlarge the floating evidence panel",
"collapsePdfHint": "Restore compact floating size",
"dockPdf": "Dock sidebar",
"undockPdf": "Undock",
"dockPdfHint": "Switch to dual-pane layout (uses editor width)",
"undockPdfHint": "Return to floating panel and free editor width",
"movePdfLeft": "Move left",
"movePdfRight": "Move right",
"movePdfSideHint": "Move the float to the other side to reduce field occlusion",
"moreActions": "More",
"openVersionHistory": "Version history",
"auditFailed": "Audit logging failed; the sensitive panel was not opened. Please retry.",
"summaryRail": "Summary",
"aiForFocusedField": "Request AI suggestion for the focused field",
"primaryBlock": "Priority action",
"blockCount": "{count} items need attention",
"viewFullChecks": "View full checks",
"fullChecksTitle": "Full order checks",
"noLineChecks": "No line-level checks yet",
"inventoryIssues": "Inventory issues"
},
"viewEvidence": "View evidence",
"dblclickLocateHint": "Double-click to locate PDF evidence (Alt+[ / Alt+] for exception fields)",
"exceptionNav": {
"prev": "Prev issue",
"next": "Next issue",
"prevHint": "Previous exception field (Alt+[)",
"nextHint": "Next exception field (Alt+])"
},
"locateSource": "Locate source: {field}",
"locateUnavailableHint": "No reliable coordinates; click for diagnostics — precise highlight unavailable",
"locateCandidateHint": "Candidate location — not strictly verified; preview only",
"locateDiagnoseOnly": "Diagnose only",
"locateLegend": {
"title": "Locate icon legend",
"verified": "Green crosshair: verified coordinates, precise highlight",
"candidate": "Orange crosshair: candidate coordinates, reference only",
"unavailable": "Red alert: no reliable or invalid coordinates — diagnostics only, no precise highlight"
},
"orderFields": "Order fields",
"schemaVersion": "Order field version V{version}",
"issues": "Open issues",
@@ -1603,7 +1715,9 @@
"autoProgress": {
"result": "Auto-progress result: {status}",
"checkpoint": "Current checkpoint: {checkpoint}",
"viewTask": "View order progress",
"viewTask": "Back to chat to view progress",
"returnToChat": "Back to chat to view progress",
"returnedFocusHint": "Back in chat, focused on task {taskNo} (see In progress on the right)",
"status": {
"ok": "Current automatic steps completed",
"running": "Processing",
@@ -1663,6 +1777,99 @@
"viewReadonly": "View read-only",
"open": "Open"
},
"customerResolution": {
"title": "Customer resolution",
"subtitle": "Confirm the standard customer before building the order. Separate from “Reparse this PDF”.",
"recognizedAs": "Recognized as",
"rawName": "Raw customer name",
"selectCustomer": "Select standard customer",
"retryCustomer": "Re-identify customer",
"retrying": "Identifying…",
"retryDone": "Customer re-identified",
"retryFailed": "Failed to re-identify customer",
"confirmed": "Customer confirmed",
"confirmReason": "Manual customer confirmation from order review",
"pdfReparseHint": "For PDF layout issues, use “Reparse this PDF” at the top—not these buttons.",
"status": {
"confirmed": "Confirmed",
"unique_candidate": "Unique candidate pending confirmation",
"ambiguous": "Multiple candidates",
"unmatched": "Unresolved",
"unresolved": "Not confirmed"
}
},
"fieldConflict": {
"title": "Field conflicts to resolve ({count})",
"subtitle": "Conflicting values from multiple sources are not auto-applied. Pick one value or enter a custom value before building the order.",
"optionLabel": "Option {index}",
"adoptOption": "Use this value",
"customValue": "Enter custom value",
"customPlaceholder": "Final field value",
"submitCustom": "Confirm custom value",
"focusEvidence": "Locate evidence",
"resolveSuccess": "Conflict resolved; build eligibility refreshed",
"resolveFailed": "Failed to resolve conflict. Refresh and try again.",
"resolveReason": "Manual field conflict resolution from order review",
"reasons": {
"cross_source_conflict": "Cross-source value conflict",
"insufficient_score_margin": "Insufficient score margin",
"field_conflict": "Field conflict"
},
"fields": {
"reservation_id": "Reservation ID",
"qty": "Quantity",
"customer_pn": "Customer P/N",
"po_number": "PO number"
}
},
"duplicate": {
"title": "Duplicate order to resolve",
"subtitle": "Choose how to handle a likely duplicate before building the order.",
"resolvedBadge": "Resolved",
"resolutionLabel": "Decision: {action}",
"resolveSuccess": "Duplicate decision saved; build eligibility refreshed",
"resolveFailed": "Failed to save duplicate decision. Refresh and try again.",
"resolving": "Saving…",
"refresh": "Re-check duplicates",
"refreshing": "Checking…",
"refreshDone": "Duplicate check refreshed",
"refreshFailed": "Failed to refresh duplicate check",
"status": {
"none": "No duplicate found",
"unchecked": "Not checked yet",
"exact_file": "Exact same file content",
"same_active_task": "Same active business task exists",
"same_completed_task": "Same completed business task exists",
"possible_duplicate": "Possible duplicate",
"same_business_content": "Same business content",
"possible_revision": "Possible revision"
}
},
"profileMatch": {
"title": "Document template match",
"subtitle": "Shows which document profile matched this PDF and candidate scores. Changing the profile requires reparse.",
"selected": "Selected profile",
"noSelected": "No profile selected",
"routeType": "Route type",
"executionMode": "Execution mode",
"score": "Score {score}",
"reselectHint": "If the template is wrong or the layout drifted, use “Reparse this PDF” at the top. Gate re-route is on the recovery card below.",
"status": {
"unique_match": "Unique match",
"selected_by_score": "Selected by score",
"no_special_profile_feature": "No special profile feature",
"no_match": "No match",
"ambiguous": "Ambiguous candidates",
"layout_drift": "Layout drift",
"evidence_insufficient": "Insufficient evidence",
"unknown": "Unknown"
},
"reasons": {
"profile_ambiguous": "Multiple profile candidates with insufficient margin",
"profile_not_matched": "No usable profile matched",
"profile_drift": "Layout drifted from the profile"
}
},
"buildEligibility": {
"title": "Order checks",
"subtitle": "Checks whether the order information and inventory sources are ready for order creation.",
@@ -1680,6 +1887,13 @@
"blockReason": "Reason to address",
"manualReason": "Manual reason",
"confirmBlocked": "Build eligibility is not satisfied. Resolve inventory or validation issues before confirming.",
"gates": {
"customer_confirmed": "Customer confirmed",
"required_fields_complete": "Required fields complete",
"evidence_complete": "Evidence complete",
"duplicate_resolved": "Duplicate check complete",
"field_conflicts_resolved": "Field conflicts resolved"
},
"status": {
"ready": "Ready to build",
"needs_review": "Needs review",
@@ -1803,7 +2017,21 @@
"failed": "Cancellation request failed. Please try again."
},
"shippingWorkflow": {
"title": "This upload",
"title": "In progress",
"showDetails": "Open full list in a dialog",
"detailsDrawerTitle": "Batches and files",
"detailsDrawerHint": "Shown as a dialog; chat width stays unchanged",
"focusTaskBanner": "Focused on task {taskNo}. Progress is in the objects below (not a separate Task workbench).",
"compactSummary": "{active} active · {total} files",
"emptyCompact": "No active objects; open the dialog to see all files.",
"hideDetails": "Close",
"processingObjectsTitle": "Objects ({count})",
"objectKind": {
"run": "Run",
"candidate": "Candidate",
"task": "Task",
"process_gate": "Needs attention"
},
"pdfCount": "{count} PDF(s)",
"pendingOnlyFilter": "Needs attention only",
"loading": "Loading…",
@@ -1846,6 +2074,9 @@
"closed": "Completed",
"cancelled": "Cancelled",
"manual_upload_pending": "Awaiting upload registration",
"upload_rpa_pending": "Freight upload RPA in progress",
"upload_rpa_running": "Freight upload RPA in progress",
"upload_rpa_failed": "Freight upload RPA failed",
"unknown": "Status pending confirmation"
},
"closedReason": {
+7
View File
@@ -297,6 +297,7 @@
"SHIPPING_CUSTOMER_SHADOW_NOT_FOUND": "Shadow resolution sample not found.",
"SHIPPING_CUSTOMER_SHADOW_LABEL_REQUIRED": "Select a standard customer as the human label.",
"SHIPPING_CUSTOMER_CONFIRMATION_REQUIRED": "The standard customer is not confirmed. Select the official customer first.",
"SHIPPING_CUSTOMER_REQUIRED_BEFORE_TASK": "Customer must be confirmed before creating a task. Select a standard customer first.",
"SHIPPING_CUSTOMER_CONFIRMATION_CUSTOMER_REQUIRED": "Select a standard customer.",
"SHIPPING_CUSTOMER_CASE_REQUIRED": "The shipping task is missing its required business case and cannot confirm a customer.",
"SHIPPING_NOTICE_REVISION_CASE_MISSING": "The revision target is missing its required business case and cannot create a revision.",
@@ -370,6 +371,12 @@
"SHIPPING_REVIEW_DRAFT_VERSION_REQUIRED": "A valid draft version is required.",
"SHIPPING_REVIEW_DRAFT_VERSION_MISMATCH": "The draft was updated in another window. Refresh and try again.",
"SHIPPING_REVIEW_FIELD_INVALID": "The review field is not in this order's frozen schema.",
"SHIPPING_REVIEW_FIELD_CONFLICT_NOT_FOUND": "Pre-build field conflict was not found or is already resolved.",
"SHIPPING_REVIEW_FIELD_CONFLICT_OPTION_INVALID": "Select a valid conflict option.",
"SHIPPING_REVIEW_FIELD_CONFLICT_VALUE_REQUIRED": "Enter a custom field value.",
"SHIPPING_REVIEW_FIELD_CONFLICT_FIELD_UNKNOWN": "Conflict field is not in the frozen schema.",
"SHIPPING_REVIEW_FIELD_CONFLICT_LINE_MISSING": "The conflict line is missing from the draft.",
"SHIPPING_REVIEW_DUPLICATE_CANDIDATE_MISSING": "The review case has no order candidate for duplicate handling.",
"SHIPPING_REVIEW_INVENTORY_CANDIDATES_INVALID": "Manual inventory source candidates are invalid. Select enabled sources and provide a reason.",
"SHIPPING_REVIEW_INVENTORY_ROUTING_ADOPT_INVALID": "Cannot adopt the rule suggestion: this line has no valid pending rule result.",
"SHIPPING_REVIEW_INVENTORY_ROUTING_KEEP_INVALID": "Cannot keep the manual result: this line has no pending rule suggestion.",
+128 -3
View File
@@ -193,11 +193,31 @@
"reasonCode": "Reason",
"diagnosticHint": "Suggested action",
"responsibleParty": "Responsible party",
"attemptCount": "Attempts",
"attemptCountValue": "{current} / {max} (technical auto-retry cap)",
"viewAudit": "View audit",
"hideAudit": "Hide audit",
"auditLoading": "Loading audit…",
"auditEmpty": "No process-gate audit events",
"auditLoadFailed": "Failed to load process-gate audit",
"auditEventFallback": "Process-gate activity",
"auditEvents": {
"process_gate_created": "Processing step created",
"process_gate_attempt_started": "Processing started",
"process_gate_passed": "Processing step passed",
"process_gate_blocked": "Processing step blocked",
"process_gate_recovery_requested": "Recovery requested",
"process_gate_idempotent_replay": "Result reused (idempotent)",
"process_gate_manual_override": "Result manually overridden",
"process_gate_rule_suggestion_generated": "Rule suggestion generated",
"process_gate_suggestion_adopted": "Rule suggestion adopted",
"process_gate_suggestion_rejected": "Rule suggestion rejected",
"process_gate_downstream_invalidated": "Downstream results invalidated",
"process_gate_technical_retry": "System automatically retried",
"process_gate_lease_taken_over": "Processing taken over by another worker",
"process_gate_artifact_superseded": "Artifact superseded by a newer version",
"process_gate_permission_denied": "Permission denied for this action"
},
"parties": {
"owner": "Order reviewer / task owner",
"worker": "System worker",
@@ -230,6 +250,8 @@
"retry_task_creation": "Retry task creation",
"retry_inventory_preparation": "Retry inventory preparation",
"regenerate_excel_artifact": "Regenerate Excel",
"poll_freight_upload_rpa": "Refresh freight upload progress",
"retry_freight_upload_rpa": "Retry freight upload RPA",
"regenerate_manual_upload_todo": "Regenerate manual upload todo"
},
"reasons": {
@@ -240,9 +262,112 @@
"customer_ambiguous": "Customer resolution is ambiguous",
"field_conflict": "Field conflicts need manual resolution",
"duplicate_unresolved": "Duplicate order is unresolved",
"require_manual_review": "Manual review is required",
"no_inventory_source_candidates": "No inventory source candidates found",
"inventory_source_unavailable": "Inventory source is unavailable"
"require_manual_review": "Inventory source rules conflict or require manual confirmation",
"no_inventory_source_candidates": "No inventory source rule matched",
"inventory_source_unavailable": "Matched inventory source is currently unavailable",
"inventory_rpa_queued": "RPA job is queued",
"inventory_rpa_timeout": "RPA execution timed out",
"inventory_rpa_login_failed": "Inventory platform login failed",
"inventory_rpa_export_failed": "Inventory report export failed",
"inventory_rpa_exhausted": "Inventory source retries exhausted",
"inventory_file_missing": "Inventory file was not generated",
"inventory_file_empty": "Inventory file is empty or has no valid records",
"inventory_preparation_waiting": "Inventory file is being prepared; refresh later",
"inventory_preparation_failed": "Inventory preparation failed; retry or upload a file",
"upload_rpa_pending": "Freight upload job is waiting",
"upload_rpa_failed": "Freight platform upload failed; RPA can be retried",
"upload_rpa_login_failed": "Freight platform login failed; check credentials and retry",
"upload_platform_rejected": "Freight platform rejected the upload; verify the file and retry",
"upload_result_unknown": "Upload result cannot be confirmed yet",
"manual_upload_pending": "Download the Excel, upload it on the freight platform, and register the result",
"technical_retry_exhausted": "Automatic retries exhausted",
"order_extraction_failed": "Order extraction failed",
"order_extraction_cancelled": "Order extraction cancelled",
"customer_out_of_scope": "Customer is out of the current business scope",
"reservation_missing": "Valid reservation is missing",
"reservation_invalid": "Reservation failed validation",
"reservation_duplicate": "Reservation is already used by another order",
"required_field_missing": "Required order fields are missing",
"field_value_invalid": "Some field values are invalid",
"field_low_confidence": "Some recognition results have low confidence",
"effective_reservation_missing": "Effective reservation ID is missing",
"document_unavailable": "Shipping notice document is unavailable",
"layout_parse_failed": "PDF layout parsing failed",
"profile_not_matched": "No matching document profile",
"profile_ambiguous": "Multiple document profiles matched",
"profile_drift": "Document structure drifted from the profile",
"extraction_incomplete": "Order field extraction is incomplete",
"cross_source_conflict": "Cross-source field conflict needs resolution",
"evidence_missing": "Key recognition results lack evidence",
"auto_freeze_not_enabled": "Auto-create policy is not enabled",
"task_creation_failed": "Fulfillment task creation failed",
"inventory_file_identity_mismatch": "Returned file does not match the selected inventory source",
"inventory_mapping_required": "Inventory field mapping requires confirmation",
"inventory_match_failed": "Inventory matching failed",
"inventory_insufficient": "Insufficient inventory",
"inventory_shortage_review_required": "Inventory shortage requires review",
"excel_not_ready": "Excel generation conditions are not met",
"artifact_generation_failed": "Excel generation failed",
"upload_rpa_login_failed": "Freight platform login failed",
"upload_platform_rejected": "Freight platform rejected the upload",
"attachment_format_unsupported": "Attachment format is unsupported",
"attachment_size_exceeded": "Attachment exceeds size limit",
"attachment_corrupted": "Attachment is corrupted",
"attachment_duplicate": "Duplicate attachment already exists",
"attachment_storage_failed": "Attachment storage failed",
"attachment_security_blocked": "Attachment blocked for security reasons",
"attachment_replaced": "Shipping notice attachment was replaced",
"document_text_unavailable": "No usable text could be extracted",
"business_table_not_found": "Business table was not found",
"business_table_empty": "Business table has no valid rows",
"multiple_business_tables": "Multiple business tables were found",
"document_password_protected": "Document is password protected",
"generic_gate_blocked": "Generic order recognition gate blocked",
"gate_invalidated": "Upstream result changed; gate must be re-evaluated",
"task_cancelled_by_user": "Task was cancelled by the user",
"task_voided_for_correction": "Task was voided for correction",
"task_archived": "Task was archived",
"task_rejected_by_user": "Candidate/task was rejected by the user",
"task_closed_after_upload": "Task closed after successful upload",
"void_blocked_external_uploaded": "External fulfillment exists; void is blocked — archive instead",
"unknown_business_failure": "Business processing failed; contact admin with request ID",
"inventory_source_conflicted": "Conflicting inventory source rules require review",
"inventory_source_changed": "Confirmed inventory source configuration has changed",
"inventory_source_identity_mismatch": "Task identity does not match inventory source/warehouse",
"inventory_multi_file_conflict": "Conflicting results across inventory files",
"inventory_sku_not_found": "SKU was not found in inventory",
"inventory_reservation_not_found": "Reservation was not found in inventory",
"inventory_warehouse_mismatch": "Warehouse does not match order requirements",
"inventory_required_column_missing": "Required inventory column is missing",
"inventory_column_ambiguous": "Inventory column mapping is ambiguous",
"excel_template_missing": "Shipping Excel template is missing",
"excel_input_incomplete": "Inputs required to generate Excel are incomplete",
"artifact_validation_failed": "Excel artifact validation failed",
"late_callback_ignored": "Late external callback was ignored",
"close_blocked_missing_receipt": "Upload receipt is missing; close is blocked"
},
"nextAction": "Next step",
"nextActionHint": "Next: {action}",
"detailFacts": "Key facts",
"detailKeys": {
"source_code": "Inventory source",
"source_codes": "Inventory sources",
"unavailable_source_codes": "Unavailable sources",
"unavailable_reasons": "Unavailable reasons",
"matched_rule_codes": "Matched rules",
"raw_rule_source_codes": "Raw rule candidates",
"candidate_inventory_source_codes": "Effective candidates",
"line_key": "Line",
"line_index": "Line no.",
"field_code": "Field",
"request_id": "Request ID",
"process_status": "Process status",
"match_status": "Match status",
"task_no": "Task no.",
"has_inventory_lines": "Has inventory lines",
"has_export": "Excel generated",
"execution_no": "Execution no.",
"inventory_file_id": "Inventory file"
}
},
"myTodos": {
+127 -3
View File
@@ -2655,6 +2655,7 @@
"refreshResults": "อ่านอีกครั้ง",
"resultsLoading": "กำลังอ่านตัวอย่างปัจจุบัน...",
"resultsFailed": "ไม่พบค่าหรืออ่านล้มเหลว โปรดตรวจสอบการทำเครื่องหมายในตัวแก้ไข",
"noTrainingSample": "ไม่มีตัวอย่าง annotation/training สำหรับการตรวจสอบในขณะนี้",
"headerResults": "ส่วนหัวคำสั่งซื้อ",
"lineResults": "รายการคำสั่งซื้อ",
"noHeaderResults": "ไม่พบฟิลด์ส่วนหัวจากตัวอย่างปัจจุบัน",
@@ -3521,6 +3522,15 @@
"refresh": "รีเฟรช",
"export": "ส่งออก CSV",
"exporting": "กำลังส่งออก...",
"exportDone": "เริ่มดาวน์โหลดการส่งออกแล้ว",
"moreActions": "เพิ่มเติม",
"copied": "คัดลอกรหัสแล้ว",
"copyId": "คัดลอกรหัส",
"techRefsHint": "รหัสเทคนิคถูกยุบไว้ กดชิปเพื่อคัดลอก",
"hashSection": "สรุปแฮช (สำหรับวินิจฉัย)",
"scrollHint": "ตารางหลักแสดงเฉพาะฟิลด์ธุรกิจ ไม่ต้องเลื่อนแนวนอน รหัส WF/Item/Run แสดงเป็นชิปขนาดเล็ก กดเพื่อคัดลอก",
"showTechRefs": "แสดงรหัสทางเทคนิค",
"hideTechRefs": "ซ่อนรหัสทางเทคนิค",
"apply": "ใช้ตัวกรอง",
"loading": "กำลังโหลด...",
"empty": "ไม่มีเหตุการณ์ตรวจสอบ",
@@ -3535,11 +3545,118 @@
"total": "ทั้งหมด {count}",
"previous": "ก่อนหน้า",
"next": "ถัดไป",
"labels": {
"eventTypes": {
"fallback": "เหตุการณ์ตรวจสอบ",
"workflow_item_created": "สร้างรายการเวิร์กโฟลว์แล้ว",
"review_field_changed": "ฟิลด์ตรวจทานเปลี่ยนแปลง",
"inventory_routing_rerouted": "จับคู่เส้นทางสต็อกใหม่แล้ว",
"inventory_routing_suggestion_adopted": "ยอมรับคำแนะนำกฎแล้ว",
"inventory_routing_manual_kept": "คงการตัดสินใจสต็อกด้วยตนเอง",
"audit_access": "เข้าถึงบันทึกตรวจสอบ",
"shipping_resource_accessed": "เข้าถึงทรัพยากร",
"process_gate_attempt_started": "เริ่มพยายามประมวลผลเกต",
"process_gate_blocked": "เกตถูกบล็อก",
"process_gate_passed": "เกตผ่านแล้ว",
"process_gate_recovery_requested": "ร้องขอการกู้คืนเกตแล้ว",
"chat_process_gate_retried": "แชท: ลองทำเกตอีกครั้ง",
"chat_process_gate_taken_over": "แชท: รับช่วงเกตด้วยมือ",
"chat_process_gate_skipped": "แชท: ข้ามเกต",
"candidate_qualification_evaluated": "ประเมินคุณสมบัติผู้สมัครสร้างออเดอร์อัตโนมัติแล้ว",
"upload_rpa_triggered": "ทริกเกอร์ RPA อัปโหลดไปยังตัวแทนขนส่งแล้ว"
},
"actions": {
"fallback": "การดำเนินการทางธุรกิจ",
"create": "สร้าง",
"update": "อัปเดต",
"export": "ส่งออก",
"verify_hash_chain": "ตรวจแฮชเชน",
"read": "อ่าน"
},
"reasonCodes": {
"fallback": "เหตุผลทางธุรกิจ",
"no_inventory_source_candidates": "ไม่พบกฎแหล่งสต็อก",
"inventory_source_unavailable": "แหล่งสต็อกใช้ไม่ได้",
"require_manual_review": "ต้องตรวจทานด้วยตนเอง",
"layout_parse_failed": "แยกเลย์เอาต์ล้มเหลว",
"unknown_business_failure": "การประมวลผลธุรกิจล้มเหลว",
"customer_unresolved": "ระบุลูกค้าไม่ได้",
"customer_ambiguous": "พบลูกค้าหลายรายที่ตรงกัน",
"reservation_missing": "ไม่มี Reservation ที่ถูกต้อง",
"reservation_duplicate": "Reservation ถูกใช้ในคำสั่งอื่นแล้ว",
"duplicate_unresolved": "คำสั่งที่อาจซ้ำยังไม่ได้ตัดสิน",
"attachment_corrupted": "ไฟล์แนบเสียหาย",
"attachment_size_exceeded": "ไฟล์แนบเกินขนาดที่กำหนด",
"attachment_format_unsupported": "รูปแบบไฟล์แนบไม่รองรับ",
"attachment_security_blocked": "ไฟล์แนบถูกบล็อกด้วยเหตุผลด้านความปลอดภัย",
"attachment_replaced": "แทนที่ไฟล์แนบแจ้งจัดส่งแล้ว",
"order_extraction_failed": "ดึงฟิลด์คำสั่งล้มเหลว",
"order_extraction_cancelled": "การดึงคำสั่งถูกยกเลิก",
"inventory_rpa_exhausted": "ลอง RPA สินค้าคงคลังครบแล้ว",
"inventory_file_missing": "ไม่มีไฟล์สินค้าคงคลัง",
"inventory_match_failed": "จับคู่สินค้าคงคลังล้มเหลว",
"inventory_insufficient": "สินค้าคงคลังไม่พอ",
"excel_not_ready": "ยังไม่พร้อมสร้าง Excel",
"artifact_generation_failed": "สร้าง Excel ล้มเหลว",
"upload_rpa_failed": "อัปโหลดแพลตฟอร์มขนส่งล้มเหลว",
"upload_result_unknown": "ยังยืนยันผลการอัปโหลดไม่ได้ชั่วคราว",
"manual_upload_pending": "ดาวน์โหลด Excel อัปโหลดบนแพลตฟอร์ม แล้วลงทะเบียนผล",
"task_cancelled_by_user": "ผู้ใช้ยกเลิกงานแล้ว",
"task_voided_for_correction": "งานถูกยกเลิกเพื่อแก้ไข",
"task_archived": "งานถูกเก็บถาวรแล้ว",
"task_rejected_by_user": "ผู้ใช้ปฏิเสธผู้สมัคร/งานแล้ว",
"task_closed_after_upload": "ปิดงานหลังอัปโหลดสำเร็จ",
"void_blocked_external_uploaded": "มีการปฏิบัติภายนอกแล้ว ห้ามยกเลิก — ให้เก็บถาวรแทน",
"gate_invalidated": "ผลต้นทางเปลี่ยน ต้องประเมินเกตใหม่",
"technical_retry_exhausted": "การลองใหม่อัตโนมัติหมดแล้ว",
"business_table_not_found": "ไม่พบตารางคำสั่ง",
"generic_gate_blocked": "เกตการรู้จำคำสั่งทั่วไปถูกบล็อก",
"upload_rpa_login_failed": "เข้าสู่ระบบแพลตฟอร์มขนส่งล้มเหลว",
"upload_platform_rejected": "แพลตฟอร์มขนส่งปฏิเสธการอัปโหลด",
"inventory_mapping_required": "ต้องยืนยันการแมปฟิลด์สินค้าคงคลัง",
"inventory_shortage_review_required": "มีสินค้าขาด ต้องตรวจทานด้วยคน",
"inventory_source_conflicted": "กฎแหล่งสินค้าคงคลังขัดแย้ง ต้องตรวจทาน",
"inventory_source_changed": "การตั้งค่าแหล่งสินค้าคงคลังที่ยืนยันแล้วมีการเปลี่ยนแปลง",
"inventory_source_identity_mismatch": "ตัวตนงานไม่ตรงกับแหล่งสินค้าคงคลัง/คลังสินค้า",
"inventory_multi_file_conflict": "ผลจากหลายไฟล์สินค้าคงคลังขัดแย้งกัน",
"inventory_sku_not_found": "ไม่พบ SKU ในสินค้าคงคลัง",
"inventory_reservation_not_found": "ไม่พบ Reservation ในสินค้าคงคลัง",
"inventory_warehouse_mismatch": "คลังสินค้าไม่ตรงตามคำสั่ง",
"inventory_required_column_missing": "ไฟล์สินค้าคงคลังขาดคอลัมน์ที่จำเป็น",
"inventory_column_ambiguous": "การแมปคอลัมน์สินค้าคงคลังคลุมเครือ",
"excel_template_missing": "ไม่มีเทมเพลต Excel จัดส่ง",
"excel_input_incomplete": "ข้อมูลสำหรับสร้าง Excel ยังไม่ครบ",
"artifact_validation_failed": "ตรวจสอบไฟล์ Excel ล้มเหลว",
"late_callback_ignored": "ละเว้นคอลแบ็กภายนอกที่มาช้า",
"close_blocked_missing_receipt": "ไม่มีใบเสร็จอัปโหลด ยังปิดงานไม่ได้"
},
"actorTypes": {
"user": "ผู้ใช้ธุรกิจ",
"admin": "ผู้ดูแลระบบ",
"system": "ระบบ",
"rpa": "RPA",
"unknown": "ผู้ดำเนินการไม่ทราบ"
},
"results": {
"success": "สำเร็จ",
"failed": "ล้มเหลว",
"rejected": "ปฏิเสธ",
"ok": "สำเร็จ"
}
},
"filters": {
"eventType": "ประเภทเหตุการณ์",
"eventTypeGroup": "กลุ่มเหตุการณ์",
"eventTypeGroupReviewWorkbench": "โต๊ะตรวจทานคำสั่ง",
"eventTypeGroupChatWorkbench": "โต๊ะแชท",
"eventTypeGroupProcessGate": "Process Gate",
"eventTypeGroupQualification": "คุณสมบัติผู้สมัคร",
"eventTypeGroupWorkflowNode": "โหนด Workflow",
"actorType": "ประเภทผู้ดำเนินการ",
"runNo": "หมายเลข Run",
"taskNo": "หมายเลข Task",
"candidateNo": "หมายเลข Candidate",
"gateCode": "รหัสโหนด / Gate",
"operationId": "operation_id",
"q": "ค้นหาหมายเลข",
"all": "ทั้งหมด",
@@ -3553,7 +3670,8 @@
"createdFrom": "ตั้งแต่",
"createdTo": "ถึง",
"workflowId": "Workflow",
"workflowItemId": "Workflow Item"
"workflowItemId": "Workflow Item",
"reasonCode": "รหัสเหตุผล"
},
"columns": {
"time": "เวลา",
@@ -3565,7 +3683,10 @@
"conversation": "เซสชัน",
"reviewCase": "Case",
"workflow": "Workflow",
"workflowItem": "Item"
"workflowItem": "Item",
"reasonCode": "เหตุผล",
"businessRefs": "ความเชื่อมโยงทางธุรกิจ",
"refs": "รหัสที่เกี่ยวข้อง"
},
"sensitiveRedacted": "บัญชีนี้ไม่มีสิทธิ์อ่านข้อมูลละเอียดอ่อน สแนปช็อตและ Diff ถูกปกปิด",
"verifyChain": "ตรวจสอบแฮชเชน",
@@ -3580,7 +3701,10 @@
"chainSummary": "ห่วงโซ่ {total} รายการ{truncated}",
"chainTruncated": " (ตัดทอน)",
"eventHash": "แฮชเหตุการณ์",
"previousEventHash": "แฮชก่อนหน้า"
"previousEventHash": "แฮชก่อนหน้า",
"showAdvancedFilters": "ตัวกรองเพิ่มเติม",
"hideAdvancedFilters": "ซ่อนตัวกรอง",
"techRefs": "รหัสทางเทคนิค"
},
"shippingProcessGates": {
"title": "การวินิจฉัย Process Gate",
+233 -2
View File
@@ -1447,8 +1447,120 @@
"evidenceSummary": "เลือกไอคอนตำแหน่งข้างฟิลด์เพื่อดูหลักฐาน",
"evidenceAt": "PDF หน้า {page}",
"evidenceNoHighlight": "หลักฐานนี้ไม่มีพิกัดที่เชื่อถือได้ จะแสดงเฉพาะหน้าและข้อความอ้างอิงโดยไม่สร้างการไฮไลต์เทียม",
"evidenceInvalidHighlight": "พิกัดไม่ถูกต้องหรือไม่ตรงกับค่าฟิลด์ จึงปิดการไฮไลต์",
"highlightQuality": {
"verified": "ยืนยันแล้ว",
"candidate": "ผู้สมัคร",
"unavailable": "ไม่มีพิกัด",
"invalid": "พิกัดไม่ถูกต้อง"
},
"highlightSource": {
"pdf_coordinate": "พิกัด PDF",
"frozen_layout_cell": "เซลล์เลย์เอาต์ที่ตรึงไว้",
"native_glyph": "อักษรต้นฉบับ",
"ocr": "OCR",
"machine_extraction": "การดึงข้อมูลด้วยเครื่อง",
"unknown": "แหล่งที่ไม่ทราบ"
},
"highlightLegend": {
"verified": "ตำแหน่งที่ยืนยันแล้ว (เส้นทึบสีเหลือง)",
"candidate": "ตำแหน่งผู้สมัคร ยังไม่ผ่านการตรวจสอบเข้มงวด (เส้นประสีส้ม)"
},
"coordinateIssues": {
"coordinate_missing": "ไม่มีพิกัดระดับฟิลด์ที่เชื่อถือได้",
"coordinate_bbox_invalid": "รูปทรงพิกัดไม่ถูกต้อง",
"coordinate_page_missing": "ไม่มีหมายเลขหน้า",
"coordinate_page_out_of_range": "หมายเลขหน้าอยู่นอกช่วง",
"duplicate_text_coordinate_ambiguous": "ข้อความซ้ำทำให้พิกัดคลุมเครือ",
"value_bbox_text_mismatch": "ข้อความในพื้นที่ไฮไลต์ไม่ตรงกับค่าฟิลด์",
"quote_not_independent": "ไม่มีข้อความจากพื้นที่อิสระเพื่อพิสูจน์ว่าไฮไลต์ตรงกับค่า",
"cell_token_unbound": "เซลล์ไม่ได้ผูกกับโทเคนข้อความ",
"ocr_confidence_insufficient": "ความมั่นใจของ OCR ต่ำเกินไป",
"ocr_multi_candidate": "OCR ได้ผู้สมัครหลายรายการ",
"html_only_no_pdf_bbox": "มีเฉพาะโครงสร้าง HTML ไม่มีพิกัด PDF",
"coordinate_outside_table": "พิกัดอยู่นอกตาราง",
"coordinate_shared_token_conflict": "โทเคนข้อความถูกแชร์โดยหลายเซลล์"
},
"evidenceDrawer": {
"title": "ตรวจหลักฐาน",
"pageUnknown": "ไม่ทราบหน้า",
"prevEvidence": "หลักฐานก่อนหน้า",
"nextEvidence": "หลักฐานถัดไป",
"field": "ฟิลด์: {field}",
"currentValue": "ค่าปัจจุบัน",
"machineValue": "ค่าจากเครื่อง",
"source": "แหล่งที่มา",
"highlightQuality": "คุณภาพการไฮไลต์",
"highlightSource": "แหล่งพิกัด",
"layoutPath": "เส้นทางเลย์เอาต์",
"detailsToggle": "รายละเอียดหลักฐาน"
},
"previewZoom": {
"fitWidth": "พอดีความกว้าง",
"fitWidthShort": "กว้าง",
"fitPage": "พอดีหน้า",
"fitPageShort": "หน้า",
"actual": "ขนาดจริง 100%",
"jumpPage": "ไปที่หน้า",
"go": "ไป"
},
"workbench": {
"mode": {
"standard": "ตรวจมาตรฐาน",
"evidence": "ตรวจหลักฐาน",
"inventory": "จัดการสต็อก",
"reparse": "รู้จำใหม่",
"confirm_progress": "ความคืบหน้าการสร้าง"
},
"enterInventory": "ดูปัญหาสต็อก",
"returnStandard": "กลับสู่การตรวจมาตรฐาน",
"openPdf": "เปิด PDF",
"closePdf": "ปิด PDF",
"pinPdf": "คงเปิดหลังออก",
"unpinPdf": "ปิดเมื่อออก",
"pinPdfHint": "คงเปิด PDF หลังออกจากโหมดหลักฐาน (ไม่ใช่แถบข้าง)",
"unpinPdfHint": "ปิด PDF เมื่อออกจากโหมดหลักฐาน",
"expandPdf": "ขยาย",
"collapsePdf": "ย่อ",
"expandPdfHint": "ขยายแผงหลักฐานแบบลอย",
"collapsePdfHint": "กลับเป็นขนาดกะทัดรัด",
"dockPdf": "ตรึงแถบข้าง",
"undockPdf": "ยกเลิกตรึง",
"dockPdfHint": "สลับเป็นสองคอลัมน์ (ใช้ความกว้างของตัวแก้ไข)",
"undockPdfHint": "กลับเป็นแผงลอย ปลดความกว้างของคำสั่งซื้อ",
"movePdfLeft": "ย้ายซ้าย",
"movePdfRight": "ย้ายขวา",
"movePdfSideHint": "ย้ายแผงลอยไปอีกด้านเพื่อลดการบังฟิลด์",
"moreActions": "เพิ่มเติม",
"openVersionHistory": "ประวัติเวอร์ชัน",
"auditFailed": "บันทึกการตรวจสอบล้มเหลว แผงข้อมูลอ่อนไหวไม่ได้เปิด โปรดลองอีกครั้ง",
"summaryRail": "สรุป",
"aiForFocusedField": "ขอคำแนะนำ AI สำหรับฟิลด์ที่โฟกัส",
"primaryBlock": "ดำเนินการก่อน",
"blockCount": "มี {count} รายการที่ต้องจัดการ",
"viewFullChecks": "ดูการตรวจสอบทั้งหมด",
"fullChecksTitle": "การตรวจสอบคำสั่งซื้อทั้งหมด",
"noLineChecks": "ยังไม่มีผลการตรวจสอบรายบรรทัด",
"inventoryIssues": "ปัญหาสต็อก"
},
"viewEvidence": "ดูหลักฐาน",
"dblclickLocateHint": "ดับเบิลคลิกเพื่อค้นหาหลักฐาน PDF (Alt+[ / Alt+] สลับฟิลด์ที่มีปัญหา)",
"exceptionNav": {
"prev": "ปัญหาก่อนหน้า",
"next": "ปัญหาถัดไป",
"prevHint": "ฟิลด์ปัญหาก่อนหน้า (Alt+[)",
"nextHint": "ฟิลด์ปัญหาถัดไป (Alt+])"
},
"locateSource": "ค้นหาต้นฉบับ: {field}",
"locateUnavailableHint": "ไม่มีพิกัดที่เชื่อถือได้ คลิกเพื่อดูคำอธิบาย — ไม่สามารถไฮไลต์แม่นยำ",
"locateCandidateHint": "ตำแหน่งผู้สมัคร ยังไม่ผ่านการตรวจสอบเข้มงวด ใช้ดูตัวอย่างเท่านั้น",
"locateDiagnoseOnly": "วินิจฉัยเท่านั้น",
"locateLegend": {
"title": "คำอธิบายไอคอนค้นหา",
"verified": "เป้าเล็งสีเขียว: พิกัดที่ยืนยันแล้ว ไฮไลต์ได้แม่นยำ",
"candidate": "เป้าเล็งสีส้ม: พิกัดผู้สมัคร สำหรับอ้างอิงเท่านั้น",
"unavailable": "คำเตือนสีแดง: ไม่มีพิกัดที่เชื่อถือได้หรือพิกัดไม่ถูกต้อง — ดูคำอธิบายเท่านั้น ไม่ไฮไลต์แม่นยำ"
},
"orderFields": "ฟิลด์คำสั่งซื้อ",
"schemaVersion": "เวอร์ชันฟิลด์คำสั่งซื้อ V{version}",
"issues": "ปัญหาที่ยังเปิดอยู่",
@@ -1603,7 +1715,9 @@
"autoProgress": {
"result": "ผลการดำเนินการอัตโนมัติ: {status}",
"checkpoint": "จุดตรวจปัจจุบัน: {checkpoint}",
"viewTask": "ดูความคืบหน้าคำสั่งซื้อ",
"viewTask": "กลับไปแชทเพื่อดูความคืบหน้า",
"returnToChat": "กลับไปแชทเพื่อดูความคืบหน้า",
"returnedFocusHint": "กลับสู่แชทแล้ว และโฟกัสงาน {taskNo} (ดูที่แถบด้านขวา)",
"status": {
"ok": "ดำเนินขั้นตอนอัตโนมัติที่ทำได้เสร็จแล้ว",
"running": "กำลังประมวลผล",
@@ -1663,6 +1777,99 @@
"viewReadonly": "ดูแบบอ่านอย่างเดียว",
"open": "เปิด"
},
"customerResolution": {
"title": "การระบุลูกค้า",
"subtitle": "ต้องยืนยันลูกค้ามาตรฐานก่อนสร้างคำสั่ง แยกจาก “ระบุ PDF นี้อีกครั้ง”",
"recognizedAs": "ผลที่ระบุได้",
"rawName": "ชื่อลูกค้าต้นฉบับ",
"selectCustomer": "เลือกลูกค้ามาตรฐาน",
"retryCustomer": "ระบุลูกค้าใหม่",
"retrying": "กำลังระบุ…",
"retryDone": "ระบุลูกค้าใหม่แล้ว",
"retryFailed": "ระบุลูกค้าใหม่ไม่สำเร็จ",
"confirmed": "ยืนยันลูกค้าแล้ว",
"confirmReason": "ยืนยันลูกค้าด้วยตนเองจากหน้าตรวจทาน",
"pdfReparseHint": "หากเลย์เอาต์ PDF ผิด ใช้ “ระบุ PDF นี้อีกครั้ง” ด้านบน ไม่ใช่ปุ่มในส่วนนี้",
"status": {
"confirmed": "ยืนยันแล้ว",
"unique_candidate": "มีตัวเลือกเดียวรอการยืนยัน",
"ambiguous": "มีหลายตัวเลือก",
"unmatched": "ยังระบุไม่ได้",
"unresolved": "ยังไม่ยืนยัน"
}
},
"fieldConflict": {
"title": "ความขัดแย้งของฟิลด์ที่ต้องตัดสิน ({count})",
"subtitle": "ค่าจากหลายแหล่งไม่ตรงกันจะไม่ถูกเขียนอัตโนมัติ เลือกค่าหนึ่งหรือกรอกค่าเองก่อนสร้างคำสั่ง",
"optionLabel": "ตัวเลือก {index}",
"adoptOption": "ใช้ค่านี้",
"customValue": "กรอกค่าเอง",
"customPlaceholder": "ค่าฟิลด์สุดท้าย",
"submitCustom": "ยืนยันค่าที่กรอก",
"focusEvidence": "ไปที่หลักฐาน",
"resolveSuccess": "ตัดสินความขัดแย้งแล้ว และรีเฟรชคุณสมบัติการสร้างคำสั่ง",
"resolveFailed": "ตัดสินไม่สำเร็จ กรุณารีเฟรชแล้วลองใหม่",
"resolveReason": "ตัดสินความขัดแย้งของฟิลด์ด้วยตนเองจากหน้าตรวจทาน",
"reasons": {
"cross_source_conflict": "ค่าจากหลายแหล่งขัดแย้งกัน",
"insufficient_score_margin": "คะแนนต่างกันไม่พอ",
"field_conflict": "ความขัดแย้งของฟิลด์"
},
"fields": {
"reservation_id": "หมายเลขการจอง",
"qty": "จำนวน",
"customer_pn": "รหัสสินค้าลูกค้า",
"po_number": "เลขที่ใบสั่งซื้อ"
}
},
"duplicate": {
"title": "คำสั่งซ้ำที่ต้องตัดสิน",
"subtitle": "หากอาจซ้ำกับงานเดิม ต้องเลือกวิธีจัดการก่อนสร้างคำสั่ง",
"resolvedBadge": "ตัดสินแล้ว",
"resolutionLabel": "การตัดสิน: {action}",
"resolveSuccess": "บันทึกการจัดการคำสั่งซ้ำแล้ว และรีเฟรชคุณสมบัติ",
"resolveFailed": "บันทึกไม่สำเร็จ กรุณารีเฟรชแล้วลองใหม่",
"resolving": "กำลังบันทึก…",
"refresh": "ตรวจซ้ำอีกครั้ง",
"refreshing": "กำลังตรวจ…",
"refreshDone": "ตรวจซ้ำแล้ว",
"refreshFailed": "ตรวจซ้ำไม่สำเร็จ",
"status": {
"none": "ไม่พบรายการซ้ำ",
"unchecked": "ยังไม่ได้ตรวจ",
"exact_file": "เนื้อหาไฟล์เหมือนกันทุกประการ",
"same_active_task": "มีงานธุรกิจเดียวกันที่กำลังดำเนินการ",
"same_completed_task": "มีงานธุรกิจเดียวกันที่เสร็จแล้ว",
"possible_duplicate": "อาจซ้ำ",
"same_business_content": "เนื้อหาธุรกิจเหมือนกัน",
"possible_revision": "อาจเป็นการแก้ไข"
}
},
"profileMatch": {
"title": "การจับคู่เทมเพลตเอกสาร",
"subtitle": "แสดงเทมเพลตที่จับคู่กับ PDF นี้และคะแนนตัวเลือก การเปลี่ยนเทมเพลตต้องระบุใหม่",
"selected": "เทมเพลตที่เลือก",
"noSelected": "ยังไม่ได้เลือกเทมเพลต",
"routeType": "ประเภทเส้นทาง",
"executionMode": "โหมดการทำงาน",
"score": "คะแนน {score}",
"reselectHint": "หากเทมเพลตผิดหรือเลย์เอาต์เพี้ยน ใช้ “ระบุ PDF นี้อีกครั้ง” ด้านบน การเปลี่ยนเส้นทางเกตอยู่ในการ์ดกู้คืนด้านล่าง",
"status": {
"unique_match": "จับคู่ได้ตัวเดียว",
"selected_by_score": "เลือกตามคะแนน",
"no_special_profile_feature": "ไม่มีคุณลักษณะเทมเพลตเฉพาะ",
"no_match": "ไม่จับคู่ได้",
"ambiguous": "มีหลายตัวเลือก",
"layout_drift": "เลย์เอาต์เพี้ยน",
"evidence_insufficient": "หลักฐานไม่พอ",
"unknown": "ไม่ทราบ"
},
"reasons": {
"profile_ambiguous": "มีหลายเทมเพลตและคะแนนต่างกันไม่พอ",
"profile_not_matched": "ไม่พบเทมเพลตที่ใช้ได้",
"profile_drift": "เลย์เอาต์เพี้ยนจากเทมเพลต"
}
},
"buildEligibility": {
"title": "ตรวจสอบคำสั่งซื้อ",
"subtitle": "ตรวจสอบว่าข้อมูลคำสั่งซื้อและแหล่งสต็อกพร้อมสำหรับสร้างคำสั่งซื้อหรือไม่",
@@ -1680,6 +1887,13 @@
"blockReason": "เหตุผลที่ต้องดำเนินการ",
"manualReason": "เหตุผลด้วยตนเอง",
"confirmBlocked": "ร่างยังไม่ผ่านคุณสมบัติการสร้างคำสั่ง โปรดแก้ปัญหาแหล่งสต็อกหรือการตรวจสอบก่อนยืนยัน",
"gates": {
"customer_confirmed": "ยืนยันลูกค้าแล้ว",
"required_fields_complete": "ฟิลด์บังคับครบ",
"evidence_complete": "หลักฐานครบ",
"duplicate_resolved": "ตรวจซ้ำเสร็จแล้ว",
"field_conflicts_resolved": "แก้ความขัดแย้งฟิลด์แล้ว"
},
"status": {
"ready": "พร้อมสร้าง",
"needs_review": "ต้องตรวจสอบ",
@@ -1803,7 +2017,21 @@
"failed": "คำขอยกเลิกล้มเหลว โปรดลองใหม่ภายหลัง"
},
"shippingWorkflow": {
"title": "รอบนี้",
"title": "กำลังดำเนินการ",
"showDetails": "เปิดรายการเต็มในไดอะล็อก",
"detailsDrawerTitle": "ชุดงานและไฟล์",
"detailsDrawerHint": "แสดงเป็นไดอะล็อก ไม่บีบพื้นที่แชท",
"focusTaskBanner": "โฟกัสงาน {taskNo} แล้ว ความคืบหน้าอยู่ด้านล่าง (ไม่ใช่หน้า Task แยก)",
"compactSummary": "กำลังดำเนินการ {active} · ไฟล์ทั้งหมด {total}",
"emptyCompact": "ไม่มีออบเจ็กต์ที่กำลังทำอยู่ เปิดไดอะล็อกเพื่อดูไฟล์ทั้งหมด",
"hideDetails": "ปิด",
"processingObjectsTitle": "รายการ ({count})",
"objectKind": {
"run": "รัน",
"candidate": "ผู้สมัคร",
"task": "งาน",
"process_gate": "ต้องดำเนินการ"
},
"pdfCount": "PDF {count} ไฟล์",
"pendingOnlyFilter": "เฉพาะที่ต้องดำเนินการ",
"loading": "กำลังโหลด…",
@@ -1846,6 +2074,9 @@
"closed": "เสร็จแล้ว",
"cancelled": "ยกเลิกแล้ว",
"manual_upload_pending": "รอลงทะเบียนอัปโหลด",
"upload_rpa_pending": "กำลังอัปโหลดด้วย RPA ไปยังตัวแทนขนส่ง",
"upload_rpa_running": "กำลังอัปโหลดด้วย RPA ไปยังตัวแทนขนส่ง",
"upload_rpa_failed": "อัปโหลด RPA ไปยังตัวแทนขนส่งล้มเหลว",
"unknown": "รอยืนยันสถานะ"
},
"closedReason": {
+7
View File
@@ -297,6 +297,7 @@
"SHIPPING_CUSTOMER_SHADOW_NOT_FOUND": "ไม่พบตัวอย่างการระบุแบบเงา",
"SHIPPING_CUSTOMER_SHADOW_LABEL_REQUIRED": "เลือกลูกค้ามาตรฐานเป็นป้ายกำกับจากผู้ดูแล",
"SHIPPING_CUSTOMER_CONFIRMATION_REQUIRED": "ยังไม่ยืนยันลูกค้ามาตรฐาน โปรดเลือกลูกค้าอย่างเป็นทางการก่อน",
"SHIPPING_CUSTOMER_REQUIRED_BEFORE_TASK": "ต้องยืนยันลูกค้าก่อนสร้างงาน โปรดเลือกลูกค้ามาตรฐานก่อน",
"SHIPPING_CUSTOMER_CONFIRMATION_CUSTOMER_REQUIRED": "เลือกลูกค้ามาตรฐาน",
"SHIPPING_CUSTOMER_CASE_REQUIRED": "งานจัดส่งไม่มีความเชื่อมโยงกับรายการธุรกิจ จึงไม่สามารถยืนยันลูกค้าได้",
"SHIPPING_NOTICE_REVISION_CASE_MISSING": "งานเป้าหมายสำหรับการแก้ไขไม่มีความเชื่อมโยงกับรายการธุรกิจ จึงไม่สามารถสร้างฉบับแก้ไขได้",
@@ -370,6 +371,12 @@
"SHIPPING_REVIEW_DRAFT_VERSION_REQUIRED": "ต้องระบุเวอร์ชันร่างที่ถูกต้อง",
"SHIPPING_REVIEW_DRAFT_VERSION_MISMATCH": "ร่างถูกแก้ไขจากหน้าต่างอื่น โปรดรีเฟรชแล้วลองใหม่",
"SHIPPING_REVIEW_FIELD_INVALID": "ฟิลด์ตรวจทานไม่อยู่ใน Schema ที่ตรึงไว้ของคำสั่งซื้อนี้",
"SHIPPING_REVIEW_FIELD_CONFLICT_NOT_FOUND": "ไม่พบความขัดแย้งของฟิลด์ก่อนสร้างคำสั่ง หรือถูกตัดสินแล้ว",
"SHIPPING_REVIEW_FIELD_CONFLICT_OPTION_INVALID": "โปรดเลือกตัวเลือกความขัดแย้งที่ถูกต้อง",
"SHIPPING_REVIEW_FIELD_CONFLICT_VALUE_REQUIRED": "โปรดกรอกค่าฟิลด์ด้วยตนเอง",
"SHIPPING_REVIEW_FIELD_CONFLICT_FIELD_UNKNOWN": "ฟิลด์ที่ขัดแย้งไม่อยู่ใน Schema ที่ตรึงไว้",
"SHIPPING_REVIEW_FIELD_CONFLICT_LINE_MISSING": "ไม่พบบรรทัดที่สัมพันธ์กับความขัดแย้งในร่าง",
"SHIPPING_REVIEW_DUPLICATE_CANDIDATE_MISSING": "เคสตรวจทานยังไม่มีตัวเลือกคำสั่ง จึงจัดการรายการซ้ำไม่ได้",
"SHIPPING_REVIEW_INVENTORY_CANDIDATES_INVALID": "ตัวเลือกแหล่งสินค้าคงคลังไม่ถูกต้อง โปรดเลือกแหล่งที่เปิดใช้และระบุเหตุผล",
"SHIPPING_REVIEW_INVENTORY_ROUTING_ADOPT_INVALID": "ไม่สามารถใช้คำแนะนำจากกฎได้ เพราะแถวนี้ไม่มีผลกฎที่ค้างอยู่ซึ่งถูกต้อง",
"SHIPPING_REVIEW_INVENTORY_ROUTING_KEEP_INVALID": "ไม่สามารถคงผลที่เลือกเองได้ เพราะแถวนี้ไม่มีคำแนะนำจากกฎที่ค้างอยู่",
+128 -3
View File
@@ -134,11 +134,31 @@
"reasonCode": "เหตุผล",
"diagnosticHint": "คำแนะนำในการดำเนินการ",
"responsibleParty": "ผู้รับผิดชอบ",
"attemptCount": "จำนวนครั้งที่ลอง",
"attemptCountValue": "{current} / {max} (ขีดจำกัดรีไทรอัตโนมัติทางเทคนิค)",
"viewAudit": "ดูบันทึกตรวจสอบ",
"hideAudit": "ซ่อนบันทึกตรวจสอบ",
"auditLoading": "กำลังโหลดบันทึกตรวจสอบ…",
"auditEmpty": "ยังไม่มีเหตุการณ์ตรวจสอบของเกต",
"auditLoadFailed": "โหลดบันทึกตรวจสอบของเกตไม่สำเร็จ",
"auditEventFallback": "บันทึกการดำเนินการของเกต",
"auditEvents": {
"process_gate_created": "สร้างขั้นตอนการดำเนินการแล้ว",
"process_gate_attempt_started": "เริ่มดำเนินการแล้ว",
"process_gate_passed": "ขั้นตอนผ่านแล้ว",
"process_gate_blocked": "ขั้นตอนถูกบล็อก",
"process_gate_recovery_requested": "ร้องขอการกู้คืนแล้ว",
"process_gate_idempotent_replay": "ใช้ผลลัพธ์ซ้ำตามกฎ idempotent",
"process_gate_manual_override": "มีการแทนที่ผลลัพธ์ด้วยตนเอง",
"process_gate_rule_suggestion_generated": "สร้างคำแนะนำกฎแล้ว",
"process_gate_suggestion_adopted": "ยอมรับคำแนะนำกฎแล้ว",
"process_gate_suggestion_rejected": "ปฏิเสธคำแนะนำกฎแล้ว",
"process_gate_downstream_invalidated": "ผลลัพธ์ปลายทางถูกทำให้หมดอายุ",
"process_gate_technical_retry": "ระบบลองใหม่อัตโนมัติแล้ว",
"process_gate_lease_taken_over": "งานถูก Worker อื่นรับช่วงต่อ",
"process_gate_artifact_superseded": "ผลลัพธ์ถูกเวอร์ชันใหม่แทนที่",
"process_gate_permission_denied": "ไม่มีสิทธิ์ดำเนินการนี้"
},
"parties": {
"owner": "ผู้ตรวจทานคำสั่งซื้อ / เจ้าของงาน",
"worker": "ระบบ Worker",
@@ -171,6 +191,8 @@
"retry_task_creation": "ลองสร้างงานใหม่",
"retry_inventory_preparation": "ลองเตรียมสต็อกใหม่",
"regenerate_excel_artifact": "สร้าง Excel ใหม่",
"poll_freight_upload_rpa": "รีเฟรชความคืบหน้าอัปโหลด freight",
"retry_freight_upload_rpa": "ลองอัปโหลด freight RPA อีกครั้ง",
"regenerate_manual_upload_todo": "สร้างงานอัปโหลดด้วยตนเองใหม่"
},
"reasons": {
@@ -181,9 +203,112 @@
"customer_ambiguous": "การระบุลูกค้ามีความคลุมเครือ",
"field_conflict": "ฟิลด์ขัดแย้ง ต้องตัดสินด้วยตนเอง",
"duplicate_unresolved": "คำสั่งซื้อซ้ำยังไม่ได้รับการแก้ไข",
"require_manual_review": "ต้องตรวจทานด้วยตนเอง",
"no_inventory_source_candidates": "ไม่พบแหล่งสต็อกที่ใช้ได้",
"inventory_source_unavailable": "แหล่งสต็อกไม่พร้อมใช้งาน"
"require_manual_review": "กฎแหล่งสต็อกขัดแย้งหรือต้องยืนยันด้วยตนเอง",
"no_inventory_source_candidates": "ไม่พบกฎแหล่งสต็อกที่ตรงกัน",
"inventory_source_unavailable": "แหล่งสต็อกที่กฎจับได้ยังไม่พร้อมใช้งาน",
"inventory_rpa_queued": "งาน RPA อยู่ในคิว",
"inventory_rpa_timeout": "RPA หมดเวลา",
"inventory_rpa_login_failed": "เข้าสู่ระบบแพลตฟอร์มสต็อกไม่สำเร็จ",
"inventory_rpa_export_failed": "ส่งออกสต็อกล้มเหลว",
"inventory_rpa_exhausted": "ลองใหม่แหล่งสต็อกครบแล้ว",
"inventory_file_missing": "ยังไม่มีไฟล์สต็อก",
"inventory_file_empty": "ไฟล์สต็อกว่างหรือไม่มีรายการที่ใช้ได้",
"inventory_preparation_waiting": "กำลังเตรียมไฟล์สต็อก กรุณารีเฟรชภายหลัง",
"inventory_preparation_failed": "เตรียมสต็อกล้มเหลว ลองใหม่หรืออัปโหลดไฟล์",
"upload_rpa_pending": "งานอัปโหลดไปยัง freight กำลังรอ",
"upload_rpa_failed": "อัปโหลดไปยัง freight ล้มเหลว สามารถลอง RPA อีกครั้ง",
"upload_rpa_login_failed": "เข้าสู่ระบบ freight ล้มเหลว ตรวจสอบข้อมูลรับรองแล้วลองใหม่",
"upload_platform_rejected": "freight ปฏิเสธการอัปโหลด ตรวจสอบไฟล์แล้วลองใหม่",
"upload_result_unknown": "ยังยืนยันผลการอัปโหลดไม่ได้",
"manual_upload_pending": "ดาวน์โหลด Excel แล้วอัปโหลดบน freight พร้อมลงทะเบียนผล",
"technical_retry_exhausted": "ลองใหม่อัตโนมัติครบแล้ว",
"order_extraction_failed": "ดึงข้อมูลคำสั่งซื้อล้มเหลว",
"order_extraction_cancelled": "ยกเลิกการดึงข้อมูลคำสั่งซื้อแล้ว",
"customer_out_of_scope": "ลูกค้านอกขอบเขตธุรกิจปัจจุบัน",
"reservation_missing": "ไม่มี Reservation ที่ถูกต้อง",
"reservation_invalid": "Reservation ไม่ผ่านการตรวจสอบ",
"reservation_duplicate": "Reservation ถูกใช้ในคำสั่งอื่นแล้ว",
"required_field_missing": "ขาดฟิลด์ที่จำเป็นสำหรับสร้างคำสั่ง",
"field_value_invalid": "ค่าฟิลด์บางรายการไม่ถูกต้อง",
"field_low_confidence": "ผลการรู้จำบางรายการมีความมั่นใจต่ำ",
"effective_reservation_missing": "ไม่มีรหัสจองที่มีผล",
"document_unavailable": "เอกสารแจ้งจัดส่งไม่พร้อมใช้งาน",
"layout_parse_failed": "การวิเคราะห์เลย์เอาต์ PDF ล้มเหลว",
"profile_not_matched": "ไม่พบโปรไฟล์เอกสารที่ตรงกัน",
"profile_ambiguous": "พบโปรไฟล์เอกสารหลายรายการ",
"profile_drift": "โครงสร้างเอกสารไม่ตรงกับโปรไฟล์",
"extraction_incomplete": "การดึงฟิลด์คำสั่งยังไม่เสร็จ",
"cross_source_conflict": "ฟิลด์จากหลายแหล่งขัดแย้งกัน",
"evidence_missing": "ผลการรู้จำสำคัญไม่มีหลักฐาน",
"auto_freeze_not_enabled": "ยังไม่ได้เปิดนโยบายสร้างอัตโนมัติ",
"task_creation_failed": "สร้างงานปฏิบัติการล้มเหลว",
"inventory_file_identity_mismatch": "ไฟล์ที่ได้รับไม่ตรงกับแหล่งสินค้าคงคลัง",
"inventory_mapping_required": "ต้องยืนยันการแมปฟิลด์สินค้าคงคลัง",
"inventory_match_failed": "จับคู่สินค้าคงคลังล้มเหลว",
"inventory_insufficient": "สินค้าคงคลังไม่พอ",
"inventory_shortage_review_required": "มีสินค้าขาด ต้องตรวจทานด้วยคน",
"excel_not_ready": "ยังไม่พร้อมสร้าง Excel",
"artifact_generation_failed": "สร้าง Excel ล้มเหลว",
"upload_rpa_login_failed": "เข้าสู่ระบบแพลตฟอร์มขนส่งล้มเหลว",
"upload_platform_rejected": "แพลตฟอร์มขนส่งปฏิเสธการอัปโหลด",
"attachment_format_unsupported": "รูปแบบไฟล์แนบไม่รองรับ",
"attachment_size_exceeded": "ไฟล์แนบเกินขนาดที่กำหนด",
"attachment_corrupted": "ไฟล์แนบเสียหาย",
"attachment_duplicate": "มีไฟล์แนบซ้ำอยู่แล้ว",
"attachment_storage_failed": "บันทึกไฟล์แนบล้มเหลว",
"attachment_security_blocked": "ไฟล์แนบถูกบล็อกด้วยเหตุผลด้านความปลอดภัย",
"attachment_replaced": "แทนที่ไฟล์แนบแจ้งจัดส่งแล้ว",
"document_text_unavailable": "ดึงข้อความที่ใช้งานได้ไม่ได้",
"business_table_not_found": "ไม่พบตารางคำสั่ง",
"business_table_empty": "ตารางคำสั่งไม่มีแถวที่ถูกต้อง",
"multiple_business_tables": "พบตารางคำสั่งหลายตาราง",
"document_password_protected": "เอกสารมีการป้องกันด้วยรหัสผ่าน",
"generic_gate_blocked": "เกตการรู้จำคำสั่งทั่วไปถูกบล็อก",
"gate_invalidated": "ผลต้นทางเปลี่ยน ต้องประเมินเกตใหม่",
"task_cancelled_by_user": "ผู้ใช้ยกเลิกงานแล้ว",
"task_voided_for_correction": "งานถูกยกเลิกเพื่อแก้ไข",
"task_archived": "งานถูกเก็บถาวรแล้ว",
"task_rejected_by_user": "ผู้ใช้ปฏิเสธผู้สมัคร/งานแล้ว",
"task_closed_after_upload": "ปิดงานหลังอัปโหลดสำเร็จ",
"void_blocked_external_uploaded": "มีการปฏิบัติภายนอกแล้ว ห้ามยกเลิก — ให้เก็บถาวรแทน",
"unknown_business_failure": "การประมวลผลธุรกิจล้มเหลว ติดต่อผู้ดูแลด้วยรหัสคำขอ",
"inventory_source_conflicted": "กฎแหล่งสินค้าคงคลังขัดแย้ง ต้องตรวจทาน",
"inventory_source_changed": "การตั้งค่าแหล่งสินค้าคงคลังที่ยืนยันแล้วมีการเปลี่ยนแปลง",
"inventory_source_identity_mismatch": "ตัวตนงานไม่ตรงกับแหล่งสินค้าคงคลัง/คลังสินค้า",
"inventory_multi_file_conflict": "ผลจากหลายไฟล์สินค้าคงคลังขัดแย้งกัน",
"inventory_sku_not_found": "ไม่พบ SKU ในสินค้าคงคลัง",
"inventory_reservation_not_found": "ไม่พบ Reservation ในสินค้าคงคลัง",
"inventory_warehouse_mismatch": "คลังสินค้าไม่ตรงตามคำสั่ง",
"inventory_required_column_missing": "ไฟล์สินค้าคงคลังขาดคอลัมน์ที่จำเป็น",
"inventory_column_ambiguous": "การแมปคอลัมน์สินค้าคงคลังคลุมเครือ",
"excel_template_missing": "ไม่มีเทมเพลต Excel จัดส่ง",
"excel_input_incomplete": "ข้อมูลสำหรับสร้าง Excel ยังไม่ครบ",
"artifact_validation_failed": "ตรวจสอบไฟล์ Excel ล้มเหลว",
"late_callback_ignored": "ละเว้นคอลแบ็กภายนอกที่มาช้า",
"close_blocked_missing_receipt": "ไม่มีใบเสร็จอัปโหลด ยังปิดงานไม่ได้"
},
"nextAction": "ขั้นตอนถัดไป",
"nextActionHint": "ถัดไป: {action}",
"detailFacts": "ข้อเท็จจริงสำคัญ",
"detailKeys": {
"source_code": "แหล่งสต็อก",
"source_codes": "แหล่งสต็อก",
"unavailable_source_codes": "แหล่งที่ไม่พร้อม",
"unavailable_reasons": "เหตุผลที่ไม่พร้อม",
"matched_rule_codes": "กฎที่ตรงกัน",
"raw_rule_source_codes": "ตัวเลือกจากกฎ",
"candidate_inventory_source_codes": "ตัวเลือกที่ใช้ได้",
"line_key": "รายการ",
"line_index": "แถว",
"field_code": "ฟิลด์",
"request_id": "รหัสคำขอ",
"process_status": "สถานะกระบวนการ",
"match_status": "สถานะการจับคู่",
"task_no": "หมายเลขงาน",
"has_inventory_lines": "มีแถวสต็อกแล้ว",
"has_export": "สร้าง Excel แล้ว",
"execution_no": "รหัสการดำเนินการ",
"inventory_file_id": "ไฟล์สต็อก"
}
},
"myTodos": {
+128 -4
View File
@@ -2892,7 +2892,8 @@
"resultsHint": "仅显示当前草稿按当前标注实时读取的结果;已删除明细仅供核对,不会进入订单结果。",
"refreshResults": "重新读取",
"resultsLoading": "正在读取当前样本...",
"resultsFailed": "未读取到值或读取失败,请返回编辑器检查标注。",
"resultsFailed": "未读取到值或读取失败,请返回编辑器检查标注。",
"noTrainingSample": "当前没有可验证的 annotation/training 样本。",
"headerResults": "订单表头",
"lineResults": "订单明细",
"noHeaderResults": "当前样本未读取到订单表头字段。",
@@ -3631,6 +3632,15 @@
"refresh": "刷新",
"export": "导出 CSV",
"exporting": "正在导出...",
"exportDone": "导出已开始下载",
"moreActions": "更多",
"copied": "已复制编号",
"copyId": "复制编号",
"techRefsHint": "技术编号默认折叠展示,点击即可复制。",
"hashSection": "哈希摘要(排障用)",
"scrollHint": "主表仅展示业务字段,无需横向滚动;WF/Item/Run 以紧凑芯片常显在业务关联下方,点击即可复制。",
"showTechRefs": "显示技术编号",
"hideTechRefs": "隐藏技术编号",
"apply": "应用",
"loading": "正在加载...",
"empty": "暂无审计事件",
@@ -3645,11 +3655,118 @@
"total": "共 {count} 条",
"previous": "上一页",
"next": "下一页",
"labels": {
"eventTypes": {
"fallback": "审计事件",
"workflow_item_created": "已创建工作流事项",
"review_field_changed": "复核字段已变更",
"inventory_routing_rerouted": "库存路由已重算",
"inventory_routing_suggestion_adopted": "已采用库存规则建议",
"inventory_routing_manual_kept": "已保留人工库存决定",
"audit_access": "审计访问",
"shipping_resource_accessed": "资源访问",
"process_gate_attempt_started": "门禁处理已开始",
"process_gate_blocked": "门禁已阻断",
"process_gate_passed": "门禁已通过",
"process_gate_recovery_requested": "已请求门禁恢复",
"chat_process_gate_retried": "对话侧已重新执行门禁",
"chat_process_gate_taken_over": "对话侧已人工接管门禁",
"chat_process_gate_skipped": "对话侧已跳过门禁",
"candidate_qualification_evaluated": "候选自动建单资格已评估",
"upload_rpa_triggered": "已触发货代上传 RPA"
},
"actions": {
"fallback": "业务操作",
"create": "创建",
"update": "更新",
"export": "导出",
"verify_hash_chain": "校验哈希链",
"read": "读取"
},
"reasonCodes": {
"fallback": "业务原因",
"no_inventory_source_candidates": "未匹配到库存源规则",
"inventory_source_unavailable": "库存源不可用",
"require_manual_review": "需要人工复核",
"layout_parse_failed": "版面解析失败",
"unknown_business_failure": "业务处理失败",
"customer_unresolved": "未能识别客户",
"customer_ambiguous": "匹配到多个客户",
"reservation_missing": "缺少有效 Reservation",
"reservation_duplicate": "Reservation 已在其他订单中使用",
"duplicate_unresolved": "疑似重复订单尚未裁定",
"attachment_corrupted": "附件文件损坏,无法读取",
"attachment_size_exceeded": "附件超过系统大小限制",
"attachment_format_unsupported": "附件格式不支持",
"attachment_security_blocked": "附件包含被禁止的脚本或宏",
"attachment_replaced": "已重新上传并覆盖当前发货通知附件",
"order_extraction_failed": "订单字段抽取失败",
"order_extraction_cancelled": "订单抽取已取消",
"inventory_rpa_exhausted": "库存源重试次数已耗尽",
"inventory_file_missing": "未生成库存文件",
"inventory_match_failed": "库存匹配失败",
"inventory_insufficient": "库存不足",
"excel_not_ready": "当前尚不满足 Excel 生成条件",
"artifact_generation_failed": "Excel 生成失败",
"upload_rpa_failed": "货代平台上传失败",
"upload_result_unknown": "上传结果暂时无法确认",
"manual_upload_pending": "请下载 Excel 后在货代平台上传并登记结果",
"task_cancelled_by_user": "任务已由用户取消",
"task_voided_for_correction": "任务已作废以进行更正",
"task_archived": "任务已归档",
"task_rejected_by_user": "订单候选/任务已由用户驳回",
"task_closed_after_upload": "上传完成后任务已关闭",
"void_blocked_external_uploaded": "已存在外部履约,禁止作废,请归档",
"gate_invalidated": "上游结果已变化,当前门禁需重新评估",
"technical_retry_exhausted": "系统自动重试已耗尽",
"business_table_not_found": "未找到订单明细表",
"generic_gate_blocked": "通用订单识别门禁未通过,需要人工复核",
"upload_rpa_login_failed": "货代平台登录失败",
"upload_platform_rejected": "货代平台拒绝本次上传",
"inventory_mapping_required": "库存字段映射待确认",
"inventory_shortage_review_required": "存在库存缺口,需要人工处理",
"inventory_source_conflicted": "多条规则产生冲突,需要人工确认",
"inventory_source_changed": "原已确认库存源配置已变化",
"inventory_source_identity_mismatch": "当前任务与库存源/仓库身份不一致",
"inventory_multi_file_conflict": "多库存文件结果冲突",
"inventory_sku_not_found": "库存中未找到对应 SKU",
"inventory_reservation_not_found": "库存中未找到对应 Reservation",
"inventory_warehouse_mismatch": "仓库与订单要求不一致",
"inventory_required_column_missing": "库存文件缺少必填列",
"inventory_column_ambiguous": "库存列映射存在歧义",
"excel_template_missing": "发货 Excel 模板缺失",
"excel_input_incomplete": "生成 Excel 所需输入不完整",
"artifact_validation_failed": "Excel 产物校验失败",
"late_callback_ignored": "迟到的外部回调已忽略",
"close_blocked_missing_receipt": "缺少上传回执,暂不可关闭"
},
"actorTypes": {
"user": "业务用户",
"admin": "管理员",
"system": "系统",
"rpa": "RPA",
"unknown": "未知操作者"
},
"results": {
"success": "成功",
"failed": "失败",
"rejected": "已拒绝",
"ok": "成功"
}
},
"filters": {
"eventType": "事件类型",
"eventTypeGroup": "事件分组",
"eventTypeGroupReviewWorkbench": "复核工作台",
"eventTypeGroupChatWorkbench": "对话工作台",
"eventTypeGroupProcessGate": "Process Gate",
"eventTypeGroupQualification": "候选资格",
"eventTypeGroupWorkflowNode": "Workflow 节点",
"actorType": "操作者类型",
"runNo": "Run 编号",
"taskNo": "Task 编号",
"candidateNo": "Candidate 编号",
"gateCode": "节点 / Gate 码",
"operationId": "operation_id",
"q": "编号检索",
"all": "全部",
@@ -3663,7 +3780,8 @@
"createdFrom": "开始时间",
"createdTo": "结束时间",
"workflowId": "Workflow",
"workflowItemId": "Workflow Item"
"workflowItemId": "Workflow Item",
"reasonCode": "原因码"
},
"columns": {
"time": "时间",
@@ -3675,7 +3793,10 @@
"conversation": "会话",
"reviewCase": "Case",
"workflow": "Workflow",
"workflowItem": "Item"
"workflowItem": "Item",
"reasonCode": "原因",
"businessRefs": "业务关联",
"refs": "关联编号"
},
"sensitiveRedacted": "当前账号无敏感读权限,快照与 Diff 已脱敏。",
"verifyChain": "校验哈希链",
@@ -3690,7 +3811,10 @@
"chainSummary": "关联链共 {total} 条{truncated}",
"chainTruncated": "(已截断)",
"eventHash": "事件哈希",
"previousEventHash": "前序哈希"
"previousEventHash": "前序哈希",
"showAdvancedFilters": "更多筛选",
"hideAdvancedFilters": "收起筛选",
"techRefs": "技术编号"
},
"shippingProcessGates": {
"title": "Process Gate 诊断",
+233 -2
View File
@@ -1481,8 +1481,120 @@
"evidenceSummary": "选择字段旁的定位图标可查看证据。",
"evidenceAt": "PDF 第 {page} 页",
"evidenceNoHighlight": "该证据没有可靠坐标,仅提供页码与引文,不显示虚假高亮。",
"evidenceInvalidHighlight": "坐标非法或与字段值不一致,已禁止绘制高亮框。",
"highlightQuality": {
"verified": "已验证",
"candidate": "候选",
"unavailable": "无坐标",
"invalid": "坐标无效"
},
"highlightSource": {
"pdf_coordinate": "PDF 坐标",
"frozen_layout_cell": "冻结单元格",
"native_glyph": "原生文字",
"ocr": "OCR",
"machine_extraction": "机器抽取",
"unknown": "未知来源"
},
"highlightLegend": {
"verified": "已验证位置(黄实线)",
"candidate": "候选位置,尚未严格验证(橙虚线)"
},
"coordinateIssues": {
"coordinate_missing": "未获得可靠字段级坐标",
"coordinate_bbox_invalid": "坐标几何非法",
"coordinate_page_missing": "缺少页码",
"coordinate_page_out_of_range": "页码超出范围",
"duplicate_text_coordinate_ambiguous": "重复文本导致坐标歧义",
"value_bbox_text_mismatch": "高亮区域文本与字段值不一致",
"quote_not_independent": "缺少独立区域文本,无法证明高亮对应字段值",
"cell_token_unbound": "单元格未绑定文字词元",
"ocr_confidence_insufficient": "OCR 置信度不足",
"ocr_multi_candidate": "OCR 存在多个候选",
"html_only_no_pdf_bbox": "仅有 HTML 结构,无 PDF 坐标",
"coordinate_outside_table": "坐标超出表格范围",
"coordinate_shared_token_conflict": "文字词元被多个单元格共享"
},
"evidenceDrawer": {
"title": "证据核对",
"pageUnknown": "页码未知",
"prevEvidence": "上一证据",
"nextEvidence": "下一证据",
"field": "字段:{field}",
"currentValue": "当前值",
"machineValue": "机器值",
"source": "来源",
"highlightQuality": "高亮质量",
"highlightSource": "坐标来源",
"layoutPath": "版面路径",
"detailsToggle": "证据详情"
},
"previewZoom": {
"fitWidth": "适合宽度",
"fitWidthShort": "适宽",
"fitPage": "适合页面",
"fitPageShort": "适页",
"actual": "实际大小 100%",
"jumpPage": "跳转到页码",
"go": "跳转"
},
"workbench": {
"mode": {
"standard": "标准复核",
"evidence": "证据核对",
"inventory": "库存处理",
"reparse": "重新识别",
"confirm_progress": "建单进度"
},
"enterInventory": "查看库存问题",
"returnStandard": "返回标准复核",
"openPdf": "打开 PDF",
"closePdf": "关闭 PDF",
"pinPdf": "退出后保留",
"unpinPdf": "退出后关闭",
"pinPdfHint": "退出证据模式后仍保留 PDF 打开(不是固定侧栏)",
"unpinPdfHint": "退出证据模式时关闭 PDF",
"expandPdf": "展开",
"collapsePdf": "收起",
"expandPdfHint": "放大当前浮动证据面板",
"collapsePdfHint": "恢复紧凑浮窗尺寸",
"dockPdf": "固定为侧栏",
"undockPdf": "取消固定",
"dockPdfHint": "切换为双栏对照(会占用编辑区宽度)",
"undockPdfHint": "改回浮动证据面板,释放订单编辑宽度",
"movePdfLeft": "移至左侧",
"movePdfRight": "移至右侧",
"movePdfSideHint": "将浮窗移到另一侧,减少遮挡当前字段",
"moreActions": "更多",
"openVersionHistory": "版本历史",
"auditFailed": "审计记录失败,敏感面板未打开,请重试",
"summaryRail": "摘要",
"aiForFocusedField": "针对当前字段请求 AI 建议",
"primaryBlock": "优先处理",
"blockCount": "共 {count} 项待处理",
"viewFullChecks": "查看完整检查",
"fullChecksTitle": "完整订单检查",
"noLineChecks": "暂无明细检查结果",
"inventoryIssues": "库存处理问题"
},
"viewEvidence": "查看证据",
"dblclickLocateHint": "双击定位 PDF 证据(Alt+[ / Alt+] 切换异常字段)",
"exceptionNav": {
"prev": "上一异常",
"next": "下一异常",
"prevHint": "上一个异常字段(Alt+[)",
"nextHint": "下一个异常字段(Alt+])"
},
"locateSource": "定位原文:{field}",
"locateUnavailableHint": "无可靠坐标;可点击查看诊断,不能执行精确高亮",
"locateCandidateHint": "候选位置,尚未严格验证;可定位预览但不可当作已确认",
"locateDiagnoseOnly": "仅诊断",
"locateLegend": {
"title": "定位图标说明",
"verified": "绿色准星:已验证坐标,可精确高亮",
"candidate": "橙色准星:候选坐标,仅供参考",
"unavailable": "红色警示:无可靠坐标或坐标非法,仅可查看诊断,不能精确高亮"
},
"orderFields": "订单字段",
"schemaVersion": "订单字段版本 V{version}",
"issues": "待处理问题",
@@ -1637,7 +1749,9 @@
"autoProgress": {
"result": "自动推进结果:{status}",
"checkpoint": "当前检查点:{checkpoint}",
"viewTask": "查看订单进度",
"viewTask": "返回对话查看进度",
"returnToChat": "返回对话查看进度",
"returnedFocusHint": "已返回对话,并聚焦任务 {taskNo}(见右侧「本次处理中」)",
"status": {
"ok": "已完成当前可自动执行步骤",
"running": "正在处理中",
@@ -1697,6 +1811,99 @@
"viewReadonly": "只读查看",
"open": "打开"
},
"customerResolution": {
"title": "客户识别",
"subtitle": "建单前必须确认标准客户;与「重新识别此 PDF」相互独立。",
"recognizedAs": "识别结果",
"rawName": "原文客户名",
"selectCustomer": "选择标准客户",
"retryCustomer": "重新识别客户",
"retrying": "识别中…",
"retryDone": "已重新识别客户",
"retryFailed": "重新识别客户失败",
"confirmed": "客户已确认",
"confirmReason": "复核工作台人工确认标准客户",
"pdfReparseHint": "若 PDF 版面错误,请使用顶部「重新识别此 PDF」,不要用本区按钮。",
"status": {
"confirmed": "已确认",
"unique_candidate": "唯一候选待确认",
"ambiguous": "存在多个候选",
"unmatched": "未识别",
"unresolved": "未确认"
}
},
"fieldConflict": {
"title": "字段冲突待裁决({count})",
"subtitle": "多来源取值不一致时不会自动写入。请选用一方或填写手工值后再建单。",
"optionLabel": "候选 {index}",
"adoptOption": "采用此值",
"customValue": "填写手工值",
"customPlaceholder": "输入最终字段值",
"submitCustom": "确认手工值",
"focusEvidence": "定位证据",
"resolveSuccess": "冲突已裁决,建单资格已刷新",
"resolveFailed": "裁决失败,请刷新后重试",
"resolveReason": "复核工作台人工裁决字段冲突",
"reasons": {
"cross_source_conflict": "多来源取值冲突",
"insufficient_score_margin": "候选分差不足",
"field_conflict": "字段冲突"
},
"fields": {
"reservation_id": "预约单号",
"qty": "数量",
"customer_pn": "客户料号",
"po_number": "采购订单号"
}
},
"duplicate": {
"title": "重复订单待裁决",
"subtitle": "与历史任务疑似重复时须先选择处理方式,再建单。",
"resolvedBadge": "已裁决",
"resolutionLabel": "处理方式:{action}",
"resolveSuccess": "重复处理已保存,建单资格已刷新",
"resolveFailed": "保存重复处理失败,请刷新后重试",
"resolving": "处理中…",
"refresh": "重新检测重复",
"refreshing": "检测中…",
"refreshDone": "已重新检测重复",
"refreshFailed": "重新检测失败",
"status": {
"none": "未发现重复",
"unchecked": "尚未检测",
"exact_file": "文件内容完全相同",
"same_active_task": "存在进行中的相同业务任务",
"same_completed_task": "存在已完成的相同业务任务",
"possible_duplicate": "疑似重复",
"same_business_content": "业务内容相同",
"possible_revision": "可能为修订版本"
}
},
"profileMatch": {
"title": "文档模板匹配",
"subtitle": "展示本 PDF 命中的文档模板与候选分;换模板需重新识别。",
"selected": "命中模板",
"noSelected": "未选定模板",
"routeType": "路由类型",
"executionMode": "执行模式",
"score": "得分 {score}",
"reselectHint": "若模板不对或版面漂移,请使用顶部「重新识别此 PDF」;门禁重路由见下方恢复卡片。",
"status": {
"unique_match": "唯一命中",
"selected_by_score": "按得分选定",
"no_special_profile_feature": "无专用模板特征",
"no_match": "未命中",
"ambiguous": "多个候选",
"layout_drift": "版面漂移",
"evidence_insufficient": "证据不足",
"unknown": "未知"
},
"reasons": {
"profile_ambiguous": "多个模板候选分差不足",
"profile_not_matched": "未匹配到可用模板",
"profile_drift": "版面相对模板发生漂移"
}
},
"buildEligibility": {
"title": "订单检查",
"subtitle": "检查订单信息和库存来源是否满足创建条件。",
@@ -1714,6 +1921,13 @@
"blockReason": "需要处理的原因",
"manualReason": "人工说明",
"confirmBlocked": "当前草稿未满足建单资格,请先处理库存源或校验问题后再确认。",
"gates": {
"customer_confirmed": "客户已确认",
"required_fields_complete": "必填字段完整",
"evidence_complete": "证据完整",
"duplicate_resolved": "重复检测已完成",
"field_conflicts_resolved": "字段冲突已解决"
},
"status": {
"ready": "可建单",
"needs_review": "待复核",
@@ -1803,7 +2017,21 @@
}
},
"shippingWorkflow": {
"title": "本次处理",
"title": "本次处理中",
"showDetails": "在弹层中查看完整列表",
"detailsDrawerTitle": "批次与文件列表",
"detailsDrawerHint": "弹层展示,不压缩对话区",
"focusTaskBanner": "已聚焦任务 {taskNo},进度见下方处理对象(非独立 Task 工作台)",
"compactSummary": "{active} 个处理中 · 共 {total} 个文件",
"emptyCompact": "暂无进行中的对象;可打开弹层查看全部文件。",
"hideDetails": "关闭",
"processingObjectsTitle": "处理对象({count})",
"objectKind": {
"run": "识别运行",
"candidate": "订单候选",
"task": "履约任务",
"process_gate": "需人工处理"
},
"pdfCount": "共 {count} 个 PDF",
"pendingOnlyFilter": "仅看待处理",
"loading": "加载中…",
@@ -1846,6 +2074,9 @@
"closed": "已完成",
"cancelled": "已取消",
"manual_upload_pending": "待人工上传登记",
"upload_rpa_pending": "货代上传 RPA 进行中",
"upload_rpa_running": "货代上传 RPA 进行中",
"upload_rpa_failed": "货代上传 RPA 失败",
"unknown": "状态待确认"
},
"closedReason": {
+7
View File
@@ -297,6 +297,7 @@
"SHIPPING_CUSTOMER_SHADOW_NOT_FOUND": "影子识别样本不存在。",
"SHIPPING_CUSTOMER_SHADOW_LABEL_REQUIRED": "请选择标准客户作为人工真值。",
"SHIPPING_CUSTOMER_CONFIRMATION_REQUIRED": "标准客户尚未确认,请先选择正式客户。",
"SHIPPING_CUSTOMER_REQUIRED_BEFORE_TASK": "客户确认必须在创建任务之前完成,请先选择标准客户。",
"SHIPPING_CUSTOMER_CONFIRMATION_CUSTOMER_REQUIRED": "请选择标准客户。",
"SHIPPING_CUSTOMER_CASE_REQUIRED": "发货任务缺少业务单关联,无法确认客户。",
"SHIPPING_NOTICE_REVISION_CASE_MISSING": "修订目标任务缺少业务单关联,无法创建修订。",
@@ -370,6 +371,12 @@
"SHIPPING_REVIEW_DRAFT_VERSION_REQUIRED": "缺少有效的草稿版本号。",
"SHIPPING_REVIEW_DRAFT_VERSION_MISMATCH": "草稿已被其他窗口更新,请刷新后重试。",
"SHIPPING_REVIEW_FIELD_INVALID": "复核字段不属于该订单的冻结模板。",
"SHIPPING_REVIEW_FIELD_CONFLICT_NOT_FOUND": "建单前字段冲突不存在或已裁决。",
"SHIPPING_REVIEW_FIELD_CONFLICT_OPTION_INVALID": "请选择有效的冲突候选值。",
"SHIPPING_REVIEW_FIELD_CONFLICT_VALUE_REQUIRED": "请填写手工字段值。",
"SHIPPING_REVIEW_FIELD_CONFLICT_FIELD_UNKNOWN": "冲突字段不在当前冻结模板中。",
"SHIPPING_REVIEW_FIELD_CONFLICT_LINE_MISSING": "冲突对应的明细行不存在。",
"SHIPPING_REVIEW_DUPLICATE_CANDIDATE_MISSING": "复核单尚未关联订单候选,无法处理重复。",
"SHIPPING_REVIEW_INVENTORY_CANDIDATES_INVALID": "人工库存源候选无效:请选择已启用的库存源并填写原因。",
"SHIPPING_REVIEW_INVENTORY_ROUTING_ADOPT_INVALID": "无法采用规则建议:当前行没有有效的待决规则结果。",
"SHIPPING_REVIEW_INVENTORY_ROUTING_KEEP_INVALID": "无法保留人工结果:当前行没有待决的规则建议。",
+150 -9
View File
@@ -194,11 +194,31 @@
"reasonCode": "处理原因",
"diagnosticHint": "处理建议",
"responsibleParty": "责任方",
"attemptCount": "执行尝试",
"attemptCountValue": "{current} / {max}(技术自动重试上限)",
"viewAudit": "查看审计",
"hideAudit": "收起审计",
"auditLoading": "正在加载审计…",
"auditEmpty": "暂无门禁审计事件",
"auditLoadFailed": "加载门禁审计失败",
"auditEventFallback": "门禁处理记录",
"auditEvents": {
"process_gate_created": "已创建处理环节",
"process_gate_attempt_started": "开始执行处理",
"process_gate_passed": "处理环节已通过",
"process_gate_blocked": "处理环节已阻断",
"process_gate_recovery_requested": "已请求恢复处理",
"process_gate_idempotent_replay": "已按幂等规则复用结果",
"process_gate_manual_override": "已人工覆盖处理结果",
"process_gate_rule_suggestion_generated": "已生成规则建议",
"process_gate_suggestion_adopted": "已采用规则建议",
"process_gate_suggestion_rejected": "已拒绝规则建议",
"process_gate_downstream_invalidated": "下游结果已失效",
"process_gate_technical_retry": "系统已自动重试",
"process_gate_lease_taken_over": "处理任务已由其他 Worker 接管",
"process_gate_artifact_superseded": "产物已被新版本替代",
"process_gate_permission_denied": "无权限执行该操作"
},
"parties": {
"owner": "订单复核 / 任务负责人",
"worker": "系统 Worker",
@@ -209,28 +229,46 @@
"noAction": "当前没有可执行的处理操作",
"versionMissing": "当前信息已更新,请刷新后重试",
"navigationMissing": "缺少跳转所需的任务或复核信息,请刷新后重试",
"customerTaskMissing": "缺少任务编号,无法打开客户确认,请刷新后重试",
"genericBlocking": "当前步骤需要人工处理",
"unknownStep": "当前步骤",
"continueAction": "继续处理",
"actionSubmitted": "操作已提交",
"submitting": "提交中…",
"actionCodes": {
"retry_with_latest_rules": "按最新规则重试",
"open_inventory_source_review": "打开库存源复核",
"open_order_review": "打开订单复核",
"rematerialize_document": "重新准备文档",
"retry_layout_parsing": "重试版面解析",
"reroute_document_profile": "重新匹配文档模板",
"open_profile_review": "打开模板复核",
"retry_order_extraction": "重试订单抽取",
"open_order_review": "打开订单复核",
"edit_order_fields": "编辑订单字段",
"revalidate_reservation": "重新校验 Reservation",
"edit_reservation": "编辑 Reservation",
"retry_customer_resolution": "重试客户识别",
"confirm_customer": "确认客户",
"retry_duplicate_detection": "重试重复检测",
"adjudicate_duplicate": "处理重复订单",
"resolve_field_conflicts": "解决字段冲突",
"open_inventory_match_review": "打开库存匹配复核",
"open_shortage_review": "打开缺货复核",
"upload_inventory_file": "上传库存文件",
"retry_with_latest_rules": "按最新规则重试",
"open_inventory_source_review": "打开库存源复核",
"adopt_rule_suggestion": "采用规则建议",
"keep_manual_inventory_decision": "保留人工决定",
"recheck_freeze_readiness": "重新检查建单资格",
"retry_task_creation": "重试创建任务",
"retry_inventory_preparation": "重试库存准备",
"poll_inventory_preparation": "刷新库存准备进度",
"upload_inventory_file": "上传库存文件",
"retry_inventory_field_mapping": "重试库存字段映射",
"confirm_inventory_field_mapping": "确认库存字段映射",
"retry_inventory_matching": "重试库存匹配",
"open_inventory_match_review": "打开库存匹配复核",
"recheck_inventory_sufficiency": "重新检查库存满足性",
"open_shortage_review": "打开缺货复核",
"recheck_excel_readiness": "重新检查 Excel 生成资格",
"regenerate_excel_artifact": "重新生成 Excel",
"poll_freight_upload_rpa": "刷新货代上传进度",
"retry_freight_upload_rpa": "重试货代上传 RPA",
"regenerate_manual_upload_todo": "重新生成待上传待办"
},
"reasons": {
@@ -241,9 +279,112 @@
"customer_ambiguous": "客户识别存在歧义",
"field_conflict": "字段存在冲突,需人工裁决",
"duplicate_unresolved": "重复订单尚未处理",
"require_manual_review": "需要人工复核",
"no_inventory_source_candidates": "未找到可用库存源",
"inventory_source_unavailable": "库存源不可用"
"require_manual_review": "库存源规则冲突或要求人工确认",
"no_inventory_source_candidates": "未匹配到库存源规则",
"inventory_source_unavailable": "规则命中的库存源当前不可用",
"inventory_rpa_queued": "RPA 任务已排队等待执行",
"inventory_rpa_timeout": "RPA 执行超时",
"inventory_rpa_login_failed": "库存平台登录失败",
"inventory_rpa_export_failed": "库存报表导出失败",
"inventory_rpa_exhausted": "库存源重试次数已耗尽",
"inventory_file_missing": "未生成库存文件",
"inventory_file_empty": "库存文件为空或没有有效库存记录",
"inventory_preparation_waiting": "库存文件准备中,请稍后刷新",
"inventory_preparation_failed": "库存准备失败,请重试或上传库存文件",
"upload_rpa_pending": "货代平台上传任务等待执行",
"upload_rpa_failed": "货代平台上传失败,可重试 RPA",
"upload_rpa_login_failed": "货代平台登录失败,请检查凭据后重试",
"upload_platform_rejected": "货代平台拒绝上传,请核对文件后重试",
"upload_result_unknown": "上传结果暂时无法确认",
"manual_upload_pending": "请下载 Excel 后在货代平台上传并登记结果",
"technical_retry_exhausted": "系统自动重试已耗尽",
"order_extraction_failed": "订单字段抽取失败",
"order_extraction_cancelled": "订单抽取已取消",
"customer_out_of_scope": "客户不在当前业务范围内",
"reservation_missing": "缺少有效 Reservation",
"reservation_invalid": "Reservation 格式或规则校验未通过",
"reservation_duplicate": "Reservation 已在其他订单中使用",
"required_field_missing": "缺少创建订单所需字段",
"field_value_invalid": "部分字段格式不正确",
"field_low_confidence": "部分识别结果置信度较低",
"effective_reservation_missing": "缺少有效的预约单号",
"document_unavailable": "发货通知文档不可用,请重新上传或物化文档",
"layout_parse_failed": "PDF 版面解析失败,请重试解析",
"profile_not_matched": "未能匹配文档模板,请人工确认 Profile",
"profile_ambiguous": "文档模板存在歧义,请人工确认 Profile",
"profile_drift": "文档结构与模板版本不一致",
"extraction_incomplete": "订单字段抽取未完成,请重试或进入复核",
"cross_source_conflict": "跨来源字段冲突,请解决冲突后继续",
"evidence_missing": "关键识别结果缺少有效证据",
"auto_freeze_not_enabled": "自动建单策略尚未启用",
"task_creation_failed": "履约任务创建失败",
"inventory_file_identity_mismatch": "返回文件与所选库存源不一致",
"inventory_mapping_required": "库存字段映射待确认",
"inventory_match_failed": "库存匹配失败",
"inventory_insufficient": "库存不足",
"inventory_shortage_review_required": "存在库存缺口,需要人工处理",
"excel_not_ready": "当前尚不满足 Excel 生成条件",
"artifact_generation_failed": "Excel 生成失败",
"upload_rpa_login_failed": "货代平台登录失败",
"upload_platform_rejected": "货代平台拒绝本次上传",
"attachment_format_unsupported": "附件格式不支持",
"attachment_size_exceeded": "附件超过系统大小限制",
"attachment_corrupted": "附件文件损坏,无法读取",
"attachment_duplicate": "已存在相同内容的附件",
"attachment_storage_failed": "附件保存失败",
"attachment_security_blocked": "附件包含被禁止的脚本或宏",
"attachment_replaced": "已重新上传并覆盖当前发货通知附件",
"document_text_unavailable": "未能从文档中提取可用文本",
"business_table_not_found": "未找到订单明细表",
"business_table_empty": "找到订单表,但没有有效业务行",
"multiple_business_tables": "发现多个可能的订单明细表",
"document_password_protected": "文档受密码保护",
"generic_gate_blocked": "通用订单识别门禁未通过,需要人工复核",
"gate_invalidated": "上游结果已变化,当前门禁需重新评估",
"task_cancelled_by_user": "任务已由用户取消",
"task_voided_for_correction": "任务已作废以进行更正",
"task_archived": "任务已归档",
"task_rejected_by_user": "订单候选/任务已由用户驳回",
"task_closed_after_upload": "上传完成后任务已关闭",
"void_blocked_external_uploaded": "已存在外部履约,禁止作废,请归档",
"unknown_business_failure": "业务处理失败,请凭请求编号联系管理员",
"inventory_source_conflicted": "多条规则产生冲突,需要人工确认",
"inventory_source_changed": "原已确认库存源配置已变化",
"inventory_source_identity_mismatch": "当前任务与库存源/仓库身份不一致",
"inventory_multi_file_conflict": "多库存文件结果冲突",
"inventory_sku_not_found": "库存中未找到对应 SKU",
"inventory_reservation_not_found": "库存中未找到对应 Reservation",
"inventory_warehouse_mismatch": "仓库与订单要求不一致",
"inventory_required_column_missing": "库存文件缺少必填列",
"inventory_column_ambiguous": "库存列映射存在歧义",
"excel_template_missing": "发货 Excel 模板缺失",
"excel_input_incomplete": "生成 Excel 所需输入不完整",
"artifact_validation_failed": "Excel 产物校验失败",
"late_callback_ignored": "迟到的外部回调已忽略",
"close_blocked_missing_receipt": "缺少上传回执,暂不可关闭"
},
"nextAction": "下一步",
"nextActionHint": "下一步:{action}",
"detailFacts": "关键事实",
"detailKeys": {
"source_code": "库存源",
"source_codes": "库存源",
"unavailable_source_codes": "不可用库存源",
"unavailable_reasons": "不可用原因",
"matched_rule_codes": "命中规则",
"raw_rule_source_codes": "规则原始候选",
"candidate_inventory_source_codes": "有效候选",
"line_key": "明细行",
"line_index": "行号",
"field_code": "字段",
"request_id": "请求编号",
"process_status": "处理状态",
"match_status": "匹配状态",
"task_no": "任务编号",
"has_inventory_lines": "是否已有库存行",
"has_export": "是否已生成 Excel",
"execution_no": "执行编号",
"inventory_file_id": "库存文件"
}
},
"myTodos": {
+127 -3
View File
@@ -2655,6 +2655,7 @@
"refreshResults": "重新讀取",
"resultsLoading": "正在讀取目前樣本...",
"resultsFailed": "未讀取到值或讀取失敗,請返回編輯器檢查標註。",
"noTrainingSample": "目前沒有可驗證的 annotation/training 樣本。",
"headerResults": "訂單表頭",
"lineResults": "訂單明細",
"noHeaderResults": "目前樣本未讀取到訂單表頭欄位。",
@@ -3521,6 +3522,15 @@
"refresh": "重新整理",
"export": "匯出 CSV",
"exporting": "正在匯出...",
"exportDone": "已開始下載匯出檔",
"moreActions": "更多",
"copied": "已複製編號",
"copyId": "複製編號",
"techRefsHint": "技術編號預設摺疊展示,點擊即可複製。",
"hashSection": "雜湊摘要(排障用)",
"scrollHint": "主表僅展示業務欄位,無需橫向捲動;WF/Item/Run 以緊湊晶片常顯於業務關聯下方,點擊即可複製。",
"showTechRefs": "顯示技術編號",
"hideTechRefs": "隱藏技術編號",
"apply": "套用",
"loading": "正在載入...",
"empty": "暫無稽核事件",
@@ -3535,11 +3545,118 @@
"total": "共 {count} 條",
"previous": "上一頁",
"next": "下一頁",
"labels": {
"eventTypes": {
"fallback": "稽核事件",
"workflow_item_created": "已建立工作流事項",
"review_field_changed": "覆核欄位已變更",
"inventory_routing_rerouted": "庫存路由已重算",
"inventory_routing_suggestion_adopted": "已採用庫存規則建議",
"inventory_routing_manual_kept": "已保留人工庫存決定",
"audit_access": "稽核存取",
"shipping_resource_accessed": "資源存取",
"process_gate_attempt_started": "門禁處理已開始",
"process_gate_blocked": "門禁已阻斷",
"process_gate_passed": "門禁已通過",
"process_gate_recovery_requested": "已請求門禁恢復",
"chat_process_gate_retried": "對話側已重新執行門禁",
"chat_process_gate_taken_over": "對話側已人工接管門禁",
"chat_process_gate_skipped": "對話側已跳過門禁",
"candidate_qualification_evaluated": "候選自動建單資格已評估",
"upload_rpa_triggered": "已觸發貨代上傳 RPA"
},
"actions": {
"fallback": "業務操作",
"create": "建立",
"update": "更新",
"export": "匯出",
"verify_hash_chain": "校驗雜湊鏈",
"read": "讀取"
},
"reasonCodes": {
"fallback": "業務原因",
"no_inventory_source_candidates": "未匹配到庫存源規則",
"inventory_source_unavailable": "庫存源不可用",
"require_manual_review": "需要人工覆核",
"layout_parse_failed": "版面解析失敗",
"unknown_business_failure": "業務處理失敗",
"customer_unresolved": "未能識別客戶",
"customer_ambiguous": "匹配到多個客戶",
"reservation_missing": "缺少有效 Reservation",
"reservation_duplicate": "Reservation 已在其他訂單中使用",
"duplicate_unresolved": "疑似重複訂單尚未裁定",
"attachment_corrupted": "附件檔案損壞,無法讀取",
"attachment_size_exceeded": "附件超過系統大小限制",
"attachment_format_unsupported": "附件格式不支援",
"attachment_security_blocked": "附件包含被禁止的指令碼或巨集",
"attachment_replaced": "已重新上傳並覆蓋目前發貨通知附件",
"order_extraction_failed": "訂單欄位抽取失敗",
"order_extraction_cancelled": "訂單抽取已取消",
"inventory_rpa_exhausted": "庫存源重試次數已耗盡",
"inventory_file_missing": "未產生庫存檔案",
"inventory_match_failed": "庫存匹配失敗",
"inventory_insufficient": "庫存不足",
"excel_not_ready": "目前尚不滿足 Excel 產生條件",
"artifact_generation_failed": "Excel 產生失敗",
"upload_rpa_failed": "貨代平台上傳失敗",
"upload_result_unknown": "上傳結果暫時無法確認",
"manual_upload_pending": "請下載 Excel 後在貨代平台上傳並登記結果",
"task_cancelled_by_user": "任務已由使用者取消",
"task_voided_for_correction": "任務已作廢以進行更正",
"task_archived": "任務已歸檔",
"task_rejected_by_user": "訂單候選/任務已由使用者駁回",
"task_closed_after_upload": "上傳完成後任務已關閉",
"void_blocked_external_uploaded": "已存在外部履約,禁止作廢,請歸檔",
"gate_invalidated": "上游結果已變化,目前門禁需重新評估",
"technical_retry_exhausted": "系統自動重試已耗盡",
"business_table_not_found": "未找到訂單明細表",
"generic_gate_blocked": "通用訂單識別門禁未通過,需要人工複核",
"upload_rpa_login_failed": "貨代平台登入失敗",
"upload_platform_rejected": "貨代平台拒絕本次上傳",
"inventory_mapping_required": "庫存欄位對應待確認",
"inventory_shortage_review_required": "存在庫存缺口,需要人工處理",
"inventory_source_conflicted": "多條規則產生衝突,需要人工確認",
"inventory_source_changed": "原已確認庫存源配置已變化",
"inventory_source_identity_mismatch": "目前任務與庫存源/倉庫身分不一致",
"inventory_multi_file_conflict": "多庫存檔案結果衝突",
"inventory_sku_not_found": "庫存中未找到對應 SKU",
"inventory_reservation_not_found": "庫存中未找到對應 Reservation",
"inventory_warehouse_mismatch": "倉庫與訂單要求不一致",
"inventory_required_column_missing": "庫存檔案缺少必填欄",
"inventory_column_ambiguous": "庫存欄對應存在歧義",
"excel_template_missing": "發貨 Excel 模板缺失",
"excel_input_incomplete": "產生 Excel 所需輸入不完整",
"artifact_validation_failed": "Excel 產物校驗失敗",
"late_callback_ignored": "遲到的外部回呼已忽略",
"close_blocked_missing_receipt": "缺少上傳回執,暫不可關閉"
},
"actorTypes": {
"user": "業務使用者",
"admin": "管理員",
"system": "系統",
"rpa": "RPA",
"unknown": "未知操作者"
},
"results": {
"success": "成功",
"failed": "失敗",
"rejected": "已拒絕",
"ok": "成功"
}
},
"filters": {
"eventType": "事件類型",
"eventTypeGroup": "事件分組",
"eventTypeGroupReviewWorkbench": "覆核工作台",
"eventTypeGroupChatWorkbench": "對話工作台",
"eventTypeGroupProcessGate": "Process Gate",
"eventTypeGroupQualification": "候選資格",
"eventTypeGroupWorkflowNode": "Workflow 節點",
"actorType": "操作者類型",
"runNo": "Run 編號",
"taskNo": "Task 編號",
"candidateNo": "Candidate 編號",
"gateCode": "節點 / Gate 碼",
"operationId": "operation_id",
"q": "編號檢索",
"all": "全部",
@@ -3553,7 +3670,8 @@
"createdFrom": "開始時間",
"createdTo": "結束時間",
"workflowId": "Workflow",
"workflowItemId": "Workflow Item"
"workflowItemId": "Workflow Item",
"reasonCode": "原因碼"
},
"columns": {
"time": "時間",
@@ -3565,7 +3683,10 @@
"conversation": "會話",
"reviewCase": "Case",
"workflow": "Workflow",
"workflowItem": "Item"
"workflowItem": "Item",
"reasonCode": "原因",
"businessRefs": "業務關聯",
"refs": "關聯編號"
},
"sensitiveRedacted": "目前帳號無敏感讀權限,快照與 Diff 已脫敏。",
"verifyChain": "校驗雜湊鏈",
@@ -3580,7 +3701,10 @@
"chainSummary": "關聯鏈共 {total} 條{truncated}",
"chainTruncated": "(已截斷)",
"eventHash": "事件雜湊",
"previousEventHash": "前序雜湊"
"previousEventHash": "前序雜湊",
"showAdvancedFilters": "更多篩選",
"hideAdvancedFilters": "收起篩選",
"techRefs": "技術編號"
},
"shippingProcessGates": {
"title": "Process Gate 診斷",
+233 -2
View File
@@ -1447,8 +1447,120 @@
"evidenceSummary": "選擇欄位旁的定位圖示即可查看證據。",
"evidenceAt": "PDF 第 {page} 頁",
"evidenceNoHighlight": "此證據沒有可靠座標,僅提供頁碼與引文,不顯示虛假高亮。",
"evidenceInvalidHighlight": "座標非法或與欄位值不一致,已禁止繪製高亮框。",
"highlightQuality": {
"verified": "已驗證",
"candidate": "候選",
"unavailable": "無座標",
"invalid": "座標無效"
},
"highlightSource": {
"pdf_coordinate": "PDF 座標",
"frozen_layout_cell": "凍結儲存格",
"native_glyph": "原生文字",
"ocr": "OCR",
"machine_extraction": "機器抽取",
"unknown": "未知來源"
},
"highlightLegend": {
"verified": "已驗證位置(黃實線)",
"candidate": "候選位置,尚未嚴格驗證(橙虛線)"
},
"coordinateIssues": {
"coordinate_missing": "未獲得可靠欄位級座標",
"coordinate_bbox_invalid": "座標幾何非法",
"coordinate_page_missing": "缺少頁碼",
"coordinate_page_out_of_range": "頁碼超出範圍",
"duplicate_text_coordinate_ambiguous": "重複文字導致座標歧義",
"value_bbox_text_mismatch": "高亮區域文字與欄位值不一致",
"quote_not_independent": "缺少獨立區域文字,無法證明高亮對應欄位值",
"cell_token_unbound": "儲存格未綁定文字詞元",
"ocr_confidence_insufficient": "OCR 信心不足",
"ocr_multi_candidate": "OCR 存在多個候選",
"html_only_no_pdf_bbox": "僅有 HTML 結構,無 PDF 座標",
"coordinate_outside_table": "座標超出表格範圍",
"coordinate_shared_token_conflict": "文字詞元被多個儲存格共用"
},
"evidenceDrawer": {
"title": "證據核對",
"pageUnknown": "頁碼未知",
"prevEvidence": "上一證據",
"nextEvidence": "下一證據",
"field": "欄位:{field}",
"currentValue": "目前值",
"machineValue": "機器值",
"source": "來源",
"highlightQuality": "高亮品質",
"highlightSource": "座標來源",
"layoutPath": "版面路徑",
"detailsToggle": "證據詳情"
},
"previewZoom": {
"fitWidth": "適合寬度",
"fitWidthShort": "適寬",
"fitPage": "適合頁面",
"fitPageShort": "適頁",
"actual": "實際大小 100%",
"jumpPage": "跳轉到頁碼",
"go": "跳轉"
},
"workbench": {
"mode": {
"standard": "標準複核",
"evidence": "證據核對",
"inventory": "庫存處理",
"reparse": "重新識別",
"confirm_progress": "建單進度"
},
"enterInventory": "查看庫存問題",
"returnStandard": "返回標準複核",
"openPdf": "開啟 PDF",
"closePdf": "關閉 PDF",
"pinPdf": "退出後保留",
"unpinPdf": "退出後關閉",
"pinPdfHint": "退出證據模式後仍保留 PDF 開啟(不是固定側欄)",
"unpinPdfHint": "退出證據模式時關閉 PDF",
"expandPdf": "展開",
"collapsePdf": "收起",
"expandPdfHint": "放大目前浮動證據面板",
"collapsePdfHint": "恢復緊湊浮窗尺寸",
"dockPdf": "固定為側欄",
"undockPdf": "取消固定",
"dockPdfHint": "切換為雙欄對照(會占用編輯區寬度)",
"undockPdfHint": "改回浮動證據面板,釋放訂單編輯寬度",
"movePdfLeft": "移至左側",
"movePdfRight": "移至右側",
"movePdfSideHint": "將浮窗移到另一側,減少遮擋目前欄位",
"moreActions": "更多",
"openVersionHistory": "版本歷史",
"auditFailed": "稽核記錄失敗,敏感面板未開啟,請重試",
"summaryRail": "摘要",
"aiForFocusedField": "針對目前欄位請求 AI 建議",
"primaryBlock": "優先處理",
"blockCount": "共 {count} 項待處理",
"viewFullChecks": "查看完整檢查",
"fullChecksTitle": "完整訂單檢查",
"noLineChecks": "暫無明細檢查結果",
"inventoryIssues": "庫存處理問題"
},
"viewEvidence": "查看證據",
"dblclickLocateHint": "連按兩下定位 PDF 證據(Alt+[ / Alt+] 切換異常欄位)",
"exceptionNav": {
"prev": "上一異常",
"next": "下一異常",
"prevHint": "上一個異常欄位(Alt+[)",
"nextHint": "下一個異常欄位(Alt+])"
},
"locateSource": "定位原文:{field}",
"locateUnavailableHint": "無可靠座標;可點擊查看診斷,不能執行精確高亮",
"locateCandidateHint": "候選位置,尚未嚴格驗證;可定位預覽但不可當作已確認",
"locateDiagnoseOnly": "僅診斷",
"locateLegend": {
"title": "定位圖示說明",
"verified": "綠色準星:已驗證座標,可精確高亮",
"candidate": "橙色準星:候選座標,僅供參考",
"unavailable": "紅色警示:無可靠座標或座標非法,僅可查看診斷,不能精確高亮"
},
"orderFields": "訂單欄位",
"schemaVersion": "訂單欄位版本 V{version}",
"issues": "待處理問題",
@@ -1603,7 +1715,9 @@
"autoProgress": {
"result": "自動推進結果:{status}",
"checkpoint": "目前檢查點:{checkpoint}",
"viewTask": "查看訂單進度",
"viewTask": "返回對話查看進度",
"returnToChat": "返回對話查看進度",
"returnedFocusHint": "已返回對話,並聚焦任務 {taskNo}(見右側「本次處理中」)",
"status": {
"ok": "已完成目前可自動執行步驟",
"running": "正在處理中",
@@ -1663,6 +1777,99 @@
"viewReadonly": "唯讀查看",
"open": "開啟"
},
"customerResolution": {
"title": "客戶識別",
"subtitle": "建單前必須確認標準客戶;與「重新識別此 PDF」相互獨立。",
"recognizedAs": "識別結果",
"rawName": "原文客戶名",
"selectCustomer": "選擇標準客戶",
"retryCustomer": "重新識別客戶",
"retrying": "識別中…",
"retryDone": "已重新識別客戶",
"retryFailed": "重新識別客戶失敗",
"confirmed": "客戶已確認",
"confirmReason": "覆核工作台人工確認標準客戶",
"pdfReparseHint": "若 PDF 版面錯誤,請使用頂部「重新識別此 PDF」,不要用本區按鈕。",
"status": {
"confirmed": "已確認",
"unique_candidate": "唯一候選待確認",
"ambiguous": "存在多個候選",
"unmatched": "未識別",
"unresolved": "未確認"
}
},
"fieldConflict": {
"title": "欄位衝突待裁決({count})",
"subtitle": "多來源取值不一致時不會自動寫入。請選用一方或填寫人工值後再建單。",
"optionLabel": "候選 {index}",
"adoptOption": "採用此值",
"customValue": "填寫人工值",
"customPlaceholder": "輸入最終欄位值",
"submitCustom": "確認人工值",
"focusEvidence": "定位證據",
"resolveSuccess": "衝突已裁決,建單資格已刷新",
"resolveFailed": "裁決失敗,請重新整理後再試",
"resolveReason": "覆核工作台人工裁決欄位衝突",
"reasons": {
"cross_source_conflict": "多來源取值衝突",
"insufficient_score_margin": "候選分差不足",
"field_conflict": "欄位衝突"
},
"fields": {
"reservation_id": "預約單號",
"qty": "數量",
"customer_pn": "客戶料號",
"po_number": "採購訂單號"
}
},
"duplicate": {
"title": "重複訂單待裁決",
"subtitle": "與歷史任務疑似重複時須先選擇處理方式,再建單。",
"resolvedBadge": "已裁決",
"resolutionLabel": "處理方式:{action}",
"resolveSuccess": "重複處理已儲存,建單資格已刷新",
"resolveFailed": "儲存重複處理失敗,請重新整理後再試",
"resolving": "處理中…",
"refresh": "重新檢測重複",
"refreshing": "檢測中…",
"refreshDone": "已重新檢測重複",
"refreshFailed": "重新檢測失敗",
"status": {
"none": "未發現重複",
"unchecked": "尚未檢測",
"exact_file": "檔案內容完全相同",
"same_active_task": "存在進行中的相同業務任務",
"same_completed_task": "存在已完成的相同業務任務",
"possible_duplicate": "疑似重複",
"same_business_content": "業務內容相同",
"possible_revision": "可能為修訂版本"
}
},
"profileMatch": {
"title": "文件範本匹配",
"subtitle": "展示本 PDF 命中的文件範本與候選分;更換範本需重新識別。",
"selected": "命中範本",
"noSelected": "未選定範本",
"routeType": "路由類型",
"executionMode": "執行模式",
"score": "得分 {score}",
"reselectHint": "若範本不對或版面漂移,請使用頂部「重新識別此 PDF」;門禁重路由見下方恢復卡片。",
"status": {
"unique_match": "唯一命中",
"selected_by_score": "按得分選定",
"no_special_profile_feature": "無專用範本特徵",
"no_match": "未命中",
"ambiguous": "多個候選",
"layout_drift": "版面漂移",
"evidence_insufficient": "證據不足",
"unknown": "未知"
},
"reasons": {
"profile_ambiguous": "多個範本候選分差不足",
"profile_not_matched": "未匹配到可用範本",
"profile_drift": "版面相對範本發生漂移"
}
},
"buildEligibility": {
"title": "訂單檢查",
"subtitle": "檢查訂單資訊和庫存來源是否符合建立條件。",
@@ -1680,6 +1887,13 @@
"blockReason": "需要處理的原因",
"manualReason": "人工說明",
"confirmBlocked": "目前草稿未滿足建單資格,請先處理庫存源或校驗問題後再確認。",
"gates": {
"customer_confirmed": "客戶已確認",
"required_fields_complete": "必填欄位完整",
"evidence_complete": "證據完整",
"duplicate_resolved": "重複偵測已完成",
"field_conflicts_resolved": "欄位衝突已解決"
},
"status": {
"ready": "可建單",
"needs_review": "待複核",
@@ -1803,7 +2017,21 @@
"failed": "取消請求失敗,請稍後重試。"
},
"shippingWorkflow": {
"title": "本次處理",
"title": "本次處理中",
"showDetails": "在彈層中查看完整列表",
"detailsDrawerTitle": "批次與檔案列表",
"detailsDrawerHint": "彈層展示,不壓縮對話區",
"focusTaskBanner": "已聚焦任務 {taskNo},進度見下方處理對象(非獨立 Task 工作台)",
"compactSummary": "{active} 個處理中 · 共 {total} 個檔案",
"emptyCompact": "暫無進行中的物件;可開啟彈層查看全部檔案。",
"hideDetails": "關閉",
"processingObjectsTitle": "處理對象({count})",
"objectKind": {
"run": "識別運行",
"candidate": "訂單候選",
"task": "履約任務",
"process_gate": "需人工處理"
},
"pdfCount": "共 {count} 個 PDF",
"pendingOnlyFilter": "僅看待處理",
"loading": "載入中…",
@@ -1846,6 +2074,9 @@
"closed": "已完成",
"cancelled": "已取消",
"manual_upload_pending": "待人工上傳登記",
"upload_rpa_pending": "貨代上傳 RPA 進行中",
"upload_rpa_running": "貨代上傳 RPA 進行中",
"upload_rpa_failed": "貨代上傳 RPA 失敗",
"unknown": "狀態待確認"
},
"closedReason": {
+7
View File
@@ -297,6 +297,7 @@
"SHIPPING_CUSTOMER_SHADOW_NOT_FOUND": "影子識別樣本不存在。",
"SHIPPING_CUSTOMER_SHADOW_LABEL_REQUIRED": "請選擇標準客戶作為人工真值。",
"SHIPPING_CUSTOMER_CONFIRMATION_REQUIRED": "標準客戶尚未確認,請先選擇正式客戶。",
"SHIPPING_CUSTOMER_REQUIRED_BEFORE_TASK": "客戶確認必須在建立任務之前完成,請先選擇標準客戶。",
"SHIPPING_CUSTOMER_CONFIRMATION_CUSTOMER_REQUIRED": "請選擇標準客戶。",
"SHIPPING_CUSTOMER_CASE_REQUIRED": "發貨任務缺少業務單關聯,無法確認客戶。",
"SHIPPING_NOTICE_REVISION_CASE_MISSING": "修訂目標任務缺少業務單關聯,無法建立修訂。",
@@ -370,6 +371,12 @@
"SHIPPING_REVIEW_DRAFT_VERSION_REQUIRED": "缺少有效的草稿版本號。",
"SHIPPING_REVIEW_DRAFT_VERSION_MISMATCH": "草稿已被其他視窗更新,請重新整理後再試。",
"SHIPPING_REVIEW_FIELD_INVALID": "覆核欄位不屬於此訂單的凍結範本。",
"SHIPPING_REVIEW_FIELD_CONFLICT_NOT_FOUND": "建單前欄位衝突不存在或已裁決。",
"SHIPPING_REVIEW_FIELD_CONFLICT_OPTION_INVALID": "請選擇有效的衝突候選值。",
"SHIPPING_REVIEW_FIELD_CONFLICT_VALUE_REQUIRED": "請填寫人工欄位值。",
"SHIPPING_REVIEW_FIELD_CONFLICT_FIELD_UNKNOWN": "衝突欄位不在目前凍結範本中。",
"SHIPPING_REVIEW_FIELD_CONFLICT_LINE_MISSING": "衝突對應的明細列不存在。",
"SHIPPING_REVIEW_DUPLICATE_CANDIDATE_MISSING": "覆核單尚未關聯訂單候選,無法處理重複。",
"SHIPPING_REVIEW_INVENTORY_CANDIDATES_INVALID": "人工庫存源候選無效:請選擇已啟用的庫存源並填寫原因。",
"SHIPPING_REVIEW_INVENTORY_ROUTING_ADOPT_INVALID": "無法採用規則建議:目前明細沒有有效的待決規則結果。",
"SHIPPING_REVIEW_INVENTORY_ROUTING_KEEP_INVALID": "無法保留人工結果:目前明細沒有待決的規則建議。",
+128 -3
View File
@@ -194,11 +194,31 @@
"reasonCode": "處理原因",
"diagnosticHint": "處理建議",
"responsibleParty": "責任方",
"attemptCount": "執行嘗試",
"attemptCountValue": "{current} / {max}(技術自動重試上限)",
"viewAudit": "檢視審計",
"hideAudit": "收起審計",
"auditLoading": "正在載入審計…",
"auditEmpty": "暫無門禁審計事件",
"auditLoadFailed": "載入門禁審計失敗",
"auditEventFallback": "門禁處理紀錄",
"auditEvents": {
"process_gate_created": "已建立處理環節",
"process_gate_attempt_started": "開始執行處理",
"process_gate_passed": "處理環節已通過",
"process_gate_blocked": "處理環節已阻斷",
"process_gate_recovery_requested": "已請求恢復處理",
"process_gate_idempotent_replay": "已依冪等規則複用結果",
"process_gate_manual_override": "已人工覆蓋處理結果",
"process_gate_rule_suggestion_generated": "已產生規則建議",
"process_gate_suggestion_adopted": "已採用規則建議",
"process_gate_suggestion_rejected": "已拒絕規則建議",
"process_gate_downstream_invalidated": "下游結果已失效",
"process_gate_technical_retry": "系統已自動重試",
"process_gate_lease_taken_over": "處理任務已由其他 Worker 接管",
"process_gate_artifact_superseded": "產物已被新版本取代",
"process_gate_permission_denied": "無權限執行該操作"
},
"parties": {
"owner": "訂單覆核 / 任務負責人",
"worker": "系統 Worker",
@@ -231,6 +251,8 @@
"retry_task_creation": "重試建立任務",
"retry_inventory_preparation": "重試庫存準備",
"regenerate_excel_artifact": "重新產生 Excel",
"poll_freight_upload_rpa": "重新整理貨代上傳進度",
"retry_freight_upload_rpa": "重試貨代上傳 RPA",
"regenerate_manual_upload_todo": "重新產生待上傳待辦"
},
"reasons": {
@@ -241,9 +263,112 @@
"customer_ambiguous": "客戶識別存在歧義",
"field_conflict": "欄位存在衝突,需人工裁決",
"duplicate_unresolved": "重複訂單尚未處理",
"require_manual_review": "需要人工覆核",
"no_inventory_source_candidates": "未找到可用庫存源",
"inventory_source_unavailable": "庫存源不可用"
"require_manual_review": "庫存源規則衝突或要求人工確認",
"no_inventory_source_candidates": "未匹配到庫存源規則",
"inventory_source_unavailable": "規則命中的庫存源目前不可用",
"inventory_rpa_queued": "RPA 任務已排隊等待執行",
"inventory_rpa_timeout": "RPA 執行逾時",
"inventory_rpa_login_failed": "庫存平台登入失敗",
"inventory_rpa_export_failed": "庫存報表匯出失敗",
"inventory_rpa_exhausted": "庫存源重試次數已耗盡",
"inventory_file_missing": "未產生庫存檔案",
"inventory_file_empty": "庫存檔案為空或沒有有效庫存記錄",
"inventory_preparation_waiting": "庫存檔案準備中,請稍後重新整理",
"inventory_preparation_failed": "庫存準備失敗,請重試或上傳庫存檔案",
"upload_rpa_pending": "貨代平台上傳任務等待執行",
"upload_rpa_failed": "貨代平台上傳失敗,可重試 RPA",
"upload_rpa_login_failed": "貨代平台登入失敗,請檢查憑據後重試",
"upload_platform_rejected": "貨代平台拒絕上傳,請核對檔案後重試",
"upload_result_unknown": "上傳結果暫時無法確認",
"manual_upload_pending": "請下載 Excel 後在貨代平台上傳並登記結果",
"technical_retry_exhausted": "系統自動重試已耗盡",
"order_extraction_failed": "訂單欄位抽取失敗",
"order_extraction_cancelled": "訂單抽取已取消",
"customer_out_of_scope": "客戶不在目前業務範圍內",
"reservation_missing": "缺少有效 Reservation",
"reservation_invalid": "Reservation 格式或規則校驗未通過",
"reservation_duplicate": "Reservation 已在其他訂單中使用",
"required_field_missing": "缺少建立訂單所需欄位",
"field_value_invalid": "部分欄位格式不正確",
"field_low_confidence": "部分識別結果置信度較低",
"effective_reservation_missing": "缺少有效的預約單號",
"document_unavailable": "發貨通知文件不可用,請重新上傳或物化文件",
"layout_parse_failed": "PDF 版面解析失敗,請重試解析",
"profile_not_matched": "未能匹配文件模板,請人工確認 Profile",
"profile_ambiguous": "文件模板存在歧義,請人工確認 Profile",
"profile_drift": "文件結構與模板版本不一致",
"extraction_incomplete": "訂單欄位抽取未完成,請重試或進入複核",
"cross_source_conflict": "跨來源欄位衝突,請解決衝突後繼續",
"evidence_missing": "關鍵識別結果缺少有效證據",
"auto_freeze_not_enabled": "自動建單策略尚未啟用",
"task_creation_failed": "履約任務建立失敗",
"inventory_file_identity_mismatch": "返回檔案與所選庫存源不一致",
"inventory_mapping_required": "庫存欄位對應待確認",
"inventory_match_failed": "庫存匹配失敗",
"inventory_insufficient": "庫存不足",
"inventory_shortage_review_required": "存在庫存缺口,需要人工處理",
"excel_not_ready": "目前尚不滿足 Excel 產生條件",
"artifact_generation_failed": "Excel 產生失敗",
"upload_rpa_login_failed": "貨代平台登入失敗",
"upload_platform_rejected": "貨代平台拒絕本次上傳",
"attachment_format_unsupported": "附件格式不支援",
"attachment_size_exceeded": "附件超過系統大小限制",
"attachment_corrupted": "附件檔案損壞,無法讀取",
"attachment_duplicate": "已存在相同內容的附件",
"attachment_storage_failed": "附件儲存失敗",
"attachment_security_blocked": "附件包含被禁止的指令碼或巨集",
"attachment_replaced": "已重新上傳並覆蓋目前發貨通知附件",
"document_text_unavailable": "未能從文件中擷取可用文字",
"business_table_not_found": "未找到訂單明細表",
"business_table_empty": "找到訂單表,但沒有有效業務列",
"multiple_business_tables": "發現多個可能的訂單明細表",
"document_password_protected": "文件受密碼保護",
"generic_gate_blocked": "通用訂單識別門禁未通過,需要人工複核",
"gate_invalidated": "上游結果已變化,目前門禁需重新評估",
"task_cancelled_by_user": "任務已由使用者取消",
"task_voided_for_correction": "任務已作廢以進行更正",
"task_archived": "任務已歸檔",
"task_rejected_by_user": "訂單候選/任務已由使用者駁回",
"task_closed_after_upload": "上傳完成後任務已關閉",
"void_blocked_external_uploaded": "已存在外部履約,禁止作廢,請歸檔",
"unknown_business_failure": "業務處理失敗,請憑請求編號聯繫管理員",
"inventory_source_conflicted": "多條規則產生衝突,需要人工確認",
"inventory_source_changed": "原已確認庫存源配置已變化",
"inventory_source_identity_mismatch": "目前任務與庫存源/倉庫身分不一致",
"inventory_multi_file_conflict": "多庫存檔案結果衝突",
"inventory_sku_not_found": "庫存中未找到對應 SKU",
"inventory_reservation_not_found": "庫存中未找到對應 Reservation",
"inventory_warehouse_mismatch": "倉庫與訂單要求不一致",
"inventory_required_column_missing": "庫存檔案缺少必填欄",
"inventory_column_ambiguous": "庫存欄對應存在歧義",
"excel_template_missing": "發貨 Excel 模板缺失",
"excel_input_incomplete": "產生 Excel 所需輸入不完整",
"artifact_validation_failed": "Excel 產物校驗失敗",
"late_callback_ignored": "遲到的外部回呼已忽略",
"close_blocked_missing_receipt": "缺少上傳回執,暫不可關閉"
},
"nextAction": "下一步",
"nextActionHint": "下一步:{action}",
"detailFacts": "關鍵事實",
"detailKeys": {
"source_code": "庫存源",
"source_codes": "庫存源",
"unavailable_source_codes": "不可用庫存源",
"unavailable_reasons": "不可用原因",
"matched_rule_codes": "命中規則",
"raw_rule_source_codes": "規則原始候選",
"candidate_inventory_source_codes": "有效候選",
"line_key": "明細行",
"line_index": "行號",
"field_code": "欄位",
"request_id": "請求編號",
"process_status": "處理狀態",
"match_status": "匹配狀態",
"task_no": "任務編號",
"has_inventory_lines": "是否已有庫存行",
"has_export": "是否已產生 Excel",
"execution_no": "執行編號",
"inventory_file_id": "庫存檔案"
}
},
"myTodos": {
+59 -2
View File
@@ -1,7 +1,7 @@
/**
* shared/api/client.ts
* 跨域 HTTP 客户端:envelope 解析、BusinessError、requestJson。
* 所有 feature API 层应通过此模块发起 JSON 请求。
* 跨域 HTTP 客户端:envelope 解析、BusinessError、requestJson、requestBlob。
* 所有 feature API 层应通过此模块发起请求;二进制下载走 requestBlob,失败仍为 BusinessError。
*/
import { getAuthHeaders } from '@/shared/utils/auth';
import i18n from '@/i18n';
@@ -168,3 +168,60 @@ export async function requestJson<T>(url: string, init?: RequestInit): Promise<T
return data as T;
}
export type BlobDownloadResult = {
blob: Blob;
filename?: string;
requestId?: string;
};
/**
* 发起需鉴权的二进制下载;失败时按 Envelope 解析为 BusinessError(与 requestJson 同源)。
* @param url - 请求路径
* @param init - fetch 初始化参数
* @returns blob 与可选文件名、request_id
*/
export async function requestBlob(url: string, init?: RequestInit): Promise<BlobDownloadResult> {
const headers = new Headers(init?.headers || {});
const authHeaders = getAuthHeaders();
Object.entries(authHeaders).forEach(([k, v]) => headers.set(k, v as string));
const res = await fetch(url, { ...init, headers });
const requestIdHeader = res.headers.get('X-Request-Id') || undefined;
const contentType = (res.headers.get('Content-Type') || '').toLowerCase();
if (!res.ok) {
let data: any = null;
if (contentType.includes('application/json')) {
try {
data = await res.json();
} catch {
data = null;
}
}
if (data && isEnvelope(data) && data.success === false) {
throw new BusinessError({
message: resolveLocalizedErrorMessage(data.error?.code, data.error?.message || `HTTP ${res.status}`),
code: data.error?.code,
details: data.error?.details,
requestId: data.request_id || requestIdHeader,
status: res.status,
});
}
throw new BusinessError({
message: resolveLocalizedErrorMessage(data?.code, pickLegacyErrorMessage(data) || `HTTP ${res.status}`),
code: data?.code || data?.error_code || 'SYSTEM.HTTP_ERROR',
details: data?.details || {},
requestId: data?.request_id || requestIdHeader,
status: res.status,
});
}
const blob = await res.blob();
const disposition = res.headers.get('Content-Disposition') || '';
const filename = disposition.match(/filename\*?=(?:UTF-8''|")?([^";]+)"?/i)?.[1];
return {
blob,
filename: filename ? decodeURIComponent(filename) : undefined,
requestId: requestIdHeader,
};
}