feat(shipping-process-gates): 落地全门禁中断恢复并消除双真相

纳入 Execution/Gate/Attempt 模型与迁移、Worker/API/前端恢复卡片与 Admin 诊断,
Gate 阻断时清零旧 action_buttons,异常摘要统一脱敏,并为运维筛选与 Attempt Diff 补齐入口。

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
hugoandCursor committed 2026-08-01 13:08:32 +08:00
1 parent b352c281d5
commit 323928626b
92 files changed
+11930 -458

No files matched your search

@@ -2,7 +2,8 @@
* features/admin/components/AdminNav.vue
* 管理后台左侧导航,在模块原始顺序中渲染货代手风琴、企微和报表二级菜单。
* 依赖:admin-nav.store、modules 常量、vue-router。
* 逻辑:报表/企微子菜单默认折叠;当前路由落在对应模块时自动展开以便看到激活项。
* 逻辑:报表/企微子菜单默认折叠;当前路由落在对应模块时自动展开;
* lg 起固定宽度侧栏,小屏横向滚动导航以免挤占主内容。
*/
<script setup lang="ts">
import { computed, watch } from 'vue';
@@ -140,10 +141,10 @@ watch(
<template>
<aside
class="surface-panel rounded-2xl shadow-sm h-fit md:sticky md:top-24 overflow-hidden shrink-0 z-10 transition-all duration-300"
:class="navStore.sidebarCollapsed ? 'w-0 md:w-20' : 'w-full md:w-64'"
class="surface-panel rounded-2xl shadow-sm h-fit w-full lg:sticky lg:top-24 overflow-hidden shrink-0 z-10 transition-all duration-300"
:class="navStore.sidebarCollapsed ? 'max-h-14 lg:max-h-none lg:w-20' : 'lg:w-64'"
>
<nav class="flex md:flex-col p-3 gap-1 overflow-x-auto md:overflow-visible no-scrollbar">
<nav class="flex lg:flex-col p-3 gap-1 overflow-x-auto lg:overflow-visible no-scrollbar">
<template v-for="item in visibleModules" :key="item.id">
<div v-if="item.id === 'shipping_inventory'" class="flex flex-col flex-shrink-0">
<button
@@ -155,7 +156,7 @@ watch(
>
<div class="flex items-center gap-3">
<Warehouse class="w-5 h-5 flex-shrink-0" :class="isShippingManagementActive ? 'text-brand-600' : 'text-muted'" />
<span :class="navStore.sidebarCollapsed ? 'md:hidden' : ''">{{ t(item.labelKey) }}</span>
<span :class="navStore.sidebarCollapsed ? 'lg:hidden' : ''">{{ t(item.labelKey) }}</span>
</div>
</button>
<div
@@ -198,7 +199,7 @@ watch(
>
<div class="flex items-center gap-3">
<Link2 class="w-5 h-5 flex-shrink-0" :class="isWecomActive ? 'text-brand-600' : 'text-muted'" />
<span :class="navStore.sidebarCollapsed ? 'md:hidden' : ''">{{ t(item.labelKey) }}</span>
<span :class="navStore.sidebarCollapsed ? 'lg:hidden' : ''">{{ t(item.labelKey) }}</span>
</div>
</button>
<div
@@ -231,7 +232,7 @@ watch(
class="w-5 h-5 transition-transform group-hover:scale-110 flex-shrink-0"
:class="isModuleActive(item.id) ? 'text-brand-600' : 'text-muted group-hover:text-secondary'"
/>
<span :class="navStore.sidebarCollapsed ? 'md:hidden' : ''">{{ t(item.labelKey) }}</span>
<span :class="navStore.sidebarCollapsed ? 'lg:hidden' : ''">{{ t(item.labelKey) }}</span>
<span
v-if="navStore.badgeForModule(item.id) && !navStore.sidebarCollapsed"
class="ml-auto bg-red-500 text-white text-[10px] font-bold px-2 py-0.5 rounded-full shadow-sm"
@@ -254,7 +255,7 @@ watch(
>
<div class="flex items-center gap-3">
<BarChart2 class="w-5 h-5 flex-shrink-0" :class="isReportsActive ? 'text-brand-600' : 'text-muted'" />
<span :class="navStore.sidebarCollapsed ? 'md:hidden' : ''">{{ t('admin.nav.reports') }}</span>
<span :class="navStore.sidebarCollapsed ? 'lg:hidden' : ''">{{ t('admin.nav.reports') }}</span>
</div>
</button>
<div
@@ -22,6 +22,7 @@ export interface ShippingConfigSubModuleMeta {
| 'AdminShippingIdentityRules'
| 'AdminShippingOrderExtractionRuns'
| 'AdminShippingAudit'
| 'AdminShippingProcessGates'
| 'AdminShippingOrderDocumentProfiles';
path:
| 'shipping-notice'
@@ -30,6 +31,7 @@ export interface ShippingConfigSubModuleMeta {
| 'shipping-identity-rules'
| 'shipping-order-extraction-runs'
| 'shipping-audit'
| 'shipping-process-gates'
| 'shipping-order-document-profiles';
labelKey: string;
groupKey: 'admin.nav.shippingOrderRecognition' | 'admin.nav.shippingInventoryManagement' | 'admin.nav.shippingRunAudit';
@@ -72,6 +74,7 @@ export const SHIPPING_CONFIG_SUB_MODULE_METAS: ShippingConfigSubModuleMeta[] = [
{ id: 'routing_rules', routeName: 'AdminShippingInventory', path: 'shipping-notice', labelKey: 'admin.shippingInventory.rules', groupKey: 'admin.nav.shippingInventoryManagement', query: { section: 'rules' } },
{ id: 'shipping_templates', routeName: 'AdminShippingInventory', path: 'shipping-notice', labelKey: 'admin.shippingInventory.excelTemplates', groupKey: 'admin.nav.shippingInventoryManagement', query: { section: 'templates' } },
{ id: 'shipping_audit', routeName: 'AdminShippingAudit', path: 'shipping-audit', labelKey: 'admin.nav.shippingAudit', groupKey: 'admin.nav.shippingRunAudit' },
{ id: 'process_gates', routeName: 'AdminShippingProcessGates', path: 'shipping-process-gates', labelKey: 'admin.nav.shippingProcessGates', groupKey: 'admin.nav.shippingRunAudit' },
{ id: 'inventory_snapshots', routeName: 'AdminShippingInventory', path: 'shipping-notice', labelKey: 'admin.shippingInventory.snapshots', groupKey: 'admin.nav.shippingRunAudit', query: { section: 'snapshots' } },
{ id: 'export_records', routeName: 'AdminShippingInventory', path: 'shipping-notice', labelKey: 'admin.shippingInventory.exports', groupKey: 'admin.nav.shippingRunAudit', query: { section: 'exports' } },
];
@@ -0,0 +1,794 @@
<!--
features/admin/modules/shipping-process-gates/ShippingProcessGateDiagnosticsPage.vue
用途:管理员 Process Gate Execution 诊断——列表、Gate 轨道与 Attempt 明细。
依赖:process-gates.api、Vue Router、Vue I18n(admin + workspace.processGate 动作文案)。
逻辑:只读诊断;多维度筛选(status/gate/reason/party/q/时间);小屏卡片化列表,lg+ 横向表格(nowrap + 滚动提示);
状态/动作展示业务标签并附技术码;Gate 诊断结构化卡片(findings/blocking/effective_result);
Attempt 展示 snapshot_diff 摘要并可跳转 AdminShippingAudit。
-->
<script setup lang="ts">
import { computed, onMounted, ref } from 'vue';
import { useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n';
import {
getAdminProcessExecution,
listAdminProcessExecutions,
listAdminProcessGateAttempts,
type AdminProcessExecutionDetail,
type AdminProcessExecutionListFilters,
type AdminProcessExecutionSummary,
type AdminProcessGateAttemptsPayload,
} from '@/features/shipping-process-gates/api/process-gates.api';
const { t, te } = useI18n();
const router = useRouter();
const loading = ref(false);
const detailLoading = ref(false);
const attemptsLoading = ref(false);
const error = ref('');
const page = ref(1);
const pageSize = 25;
const total = ref(0);
const filters = ref<AdminProcessExecutionListFilters>({
status: '',
gate_code: '',
blocking_reason_code: '',
responsible_party: '',
q: '',
updated_from: '',
updated_to: '',
});
const rows = ref<AdminProcessExecutionSummary[]>([]);
const detail = ref<AdminProcessExecutionDetail | null>(null);
const selectedGateCode = ref('');
const attemptsPayload = ref<AdminProcessGateAttemptsPayload | null>(null);
const EXECUTION_STATUS_OPTIONS = [
'active',
'blocked',
'waiting_external',
'completed',
'failed',
'cancelled',
] as const;
type GateFinding = {
severity?: string;
field_code?: string;
field?: string;
responsible_party?: string;
party?: string;
reason_code?: string;
reason?: string;
code?: string;
finding_code?: string;
message?: string;
details?: Record<string, unknown>;
};
type SnapshotKeyDiff = {
added?: string[];
removed?: string[];
changed?: string[];
};
type SnapshotDiffPayload = {
previous_attempt_no?: number;
input?: SnapshotKeyDiff;
output?: SnapshotKeyDiff;
input_hash_changed?: boolean;
output_hash_changed?: boolean;
};
const EMPTY_FILTERS: AdminProcessExecutionListFilters = {
status: '',
gate_code: '',
blocking_reason_code: '',
responsible_party: '',
q: '',
updated_from: '',
updated_to: '',
};
const formatTime = (value?: string | null) => (value ? new Date(value).toLocaleString() : '—');
/**
* 将 datetime-local 值规范为 ISO 字符串供 API 查询。
*/
function normalizeDateTimeFilter(value?: string): string {
const raw = String(value || '').trim();
if (!raw) return '';
const date = new Date(raw);
if (Number.isNaN(date.getTime())) return raw;
return date.toISOString();
}
/**
* Execution / Gate 状态业务标签;无翻译时回落原始码。
*/
function statusLabel(code?: string | null): string {
const key = String(code || '').trim();
if (!key) return '—';
const i18nKey = `admin.shippingProcessGates.statusLabels.${key}`;
return te(i18nKey) ? t(i18nKey) : key;
}
/**
* 主动作业务标签(复用 workspace 动作文案)+ 技术码,便于运维对照。
*/
function actionLabel(code?: string | null): string {
const key = String(code || '').trim();
if (!key) return '—';
const i18nKey = `workspace.shippingNotice.processGate.actionCodes.${key}`;
const label = te(i18nKey) ? t(i18nKey) : key;
return label === key ? key : `${label} (${key})`;
}
/**
* 组装当前列表筛选 payload,剔除空值并规范化时间。
*/
function buildListFilters(): AdminProcessExecutionListFilters {
const payload: AdminProcessExecutionListFilters = {};
(Object.entries(filters.value) as Array<[keyof AdminProcessExecutionListFilters, string | undefined]>).forEach(
([key, value]) => {
const text = String(value || '').trim();
if (!text) return;
if (key === 'updated_from' || key === 'updated_to') {
payload[key] = normalizeDateTimeFilter(text);
return;
}
payload[key] = text;
},
);
return payload;
}
/** 兼容后端 items / attempts 双字段。 */
const attemptRows = computed(() => {
const payload = attemptsPayload.value;
if (!payload) return [];
const list = payload.items || payload.attempts || [];
return Array.isArray(list) ? list : [];
});
/** 详情中的完整 Gate 列表(含 findings)。 */
const diagnosticGates = computed(() => {
const gates = detail.value?.gates;
return Array.isArray(gates) ? gates : [];
});
const selectedGateDetail = computed(() => {
if (!selectedGateCode.value) return null;
return diagnosticGates.value.find((gate) => String(gate.gate_code) === selectedGateCode.value) || null;
});
const selectedGateFindings = computed(() => normalizeFindings(selectedGateDetail.value?.findings));
const selectedBlockingReasonRows = computed(() => blockingReasonRows(selectedGateDetail.value?.blocking_reason));
const selectedEffectiveResultSummary = computed(() => effectiveResultSummary(selectedGateDetail.value?.effective_result));
const selectedEffectiveResultRemainder = computed(() => (
effectiveResultRemainder(selectedGateDetail.value?.effective_result, selectedEffectiveResultSummary.value)
));
/**
* 将任意 JSON 安全格式化为可展示文本。
*/
function formatJson(value: unknown): string {
if (value == null) return '—';
try {
return JSON.stringify(value, null, 2);
} catch {
return String(value);
}
}
/**
* 将单元格值转为短文本。
*/
function formatCellValue(value: unknown): string {
if (value == null) return '—';
if (typeof value === 'string') return value;
if (typeof value === 'number' || typeof value === 'boolean') return String(value);
try {
return JSON.stringify(value);
} catch {
return String(value);
}
}
/**
* 规范化 Gate findings 数组。
*/
function normalizeFindings(raw: unknown): GateFinding[] {
if (!Array.isArray(raw)) return [];
return raw.filter((item): item is GateFinding => Boolean(item) && typeof item === 'object');
}
/**
* 提取 Finding 展示字段。
*/
function findingField(finding: GateFinding): string {
return String(finding.field_code || finding.field || '').trim() || '—';
}
function findingParty(finding: GateFinding): string {
return String(finding.responsible_party || finding.party || '').trim() || '—';
}
function findingReason(finding: GateFinding): string {
return String(finding.reason_code || finding.reason || finding.code || finding.finding_code || '').trim() || '—';
}
function findingMessage(finding: GateFinding): string {
if (finding.message) return String(finding.message);
const details = finding.details;
if (details && typeof details === 'object' && details.message != null) {
return String(details.message);
}
return '—';
}
/**
* 将 blocking_reason 对象转为 key-value 行。
*/
function blockingReasonRows(raw: unknown): Array<{ key: string; value: string }> {
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return [];
return Object.entries(raw as Record<string, unknown>).map(([key, value]) => ({
key,
value: formatCellValue(value),
}));
}
/**
* 从 effective_result 提取摘要 chips(优先常见键 + findings 计数)。
*/
function effectiveResultSummary(raw: unknown): Array<{ key: string; value: string }> {
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return [];
const obj = raw as Record<string, unknown>;
const chips: Array<{ key: string; value: string }> = [];
const priorityKeys = ['passed', 'status', 'case', 'outcome', 'summary'];
for (const key of priorityKeys) {
if (Object.prototype.hasOwnProperty.call(obj, key) && obj[key] != null) {
chips.push({ key, value: formatCellValue(obj[key]) });
}
}
if (Array.isArray(obj.findings)) {
chips.push({ key: 'findings', value: String(obj.findings.length) });
}
return chips;
}
/**
* 返回 effective_result 中未出现在摘要 chips 内的剩余 JSON。
*/
function effectiveResultRemainder(
raw: unknown,
summary: Array<{ key: string; value: string }>,
): Record<string, unknown> | null {
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;
const obj = { ...(raw as Record<string, unknown>) };
const consumed = new Set(summary.map((item) => item.key));
for (const key of consumed) {
delete obj[key];
}
return Object.keys(obj).length ? obj : null;
}
/**
* 格式化 Attempt snapshot_diff 单段(input/output)摘要。
*/
function formatSnapshotDiffSection(scope: 'input' | 'output', diff: SnapshotDiffPayload | null | undefined): string | null {
const section = diff?.[scope];
if (!section) return null;
const added = section.added?.length ?? 0;
const removed = section.removed?.length ?? 0;
const changed = section.changed?.length ?? 0;
if (!added && !removed && !changed) return null;
const scopeLabel = scope === 'input' ? 'input' : 'output';
return t('admin.shippingProcessGates.attemptDiff', {
scope: scopeLabel,
added,
removed,
changed,
});
}
/**
* 合并 Attempt snapshot_diff 的 input/output 摘要行。
*/
function formatAttemptDiffSummary(raw: unknown): string[] {
if (!raw || typeof raw !== 'object') return [];
const diff = raw as SnapshotDiffPayload;
const lines: string[] = [];
const inputLine = formatSnapshotDiffSection('input', diff);
const outputLine = formatSnapshotDiffSection('output', diff);
if (inputLine) lines.push(inputLine);
if (outputLine) lines.push(outputLine);
return lines;
}
/**
* 跳转 Admin 审计中心,预填 Execution 与 process_gate_ 事件前缀。
*/
function openAuditForExecution(executionNo: string) {
void router.push({
name: 'AdminShippingAudit',
query: {
q: executionNo,
event_type: 'process_gate_',
},
});
}
/**
* 加载 Execution 列表。
*/
async function load() {
loading.value = true;
error.value = '';
try {
const response = await listAdminProcessExecutions(page.value, pageSize, buildListFilters());
rows.value = response.items;
total.value = response.total;
} catch {
error.value = t('admin.shippingProcessGates.loadFailed');
} finally {
loading.value = false;
}
}
/**
* 应用筛选并重置到第一页。
*/
function applyFilters() {
page.value = 1;
void load();
}
/**
* 清空筛选并刷新列表。
*/
function resetFilters() {
filters.value = { ...EMPTY_FILTERS };
page.value = 1;
void load();
}
/**
* 打开 Execution 诊断详情。
*/
async function openDetail(executionNo: string) {
detailLoading.value = true;
selectedGateCode.value = '';
attemptsPayload.value = null;
try {
detail.value = await getAdminProcessExecution(executionNo);
const current = detail.value.current_gate?.gate_code
|| detail.value.current_blocking_gate?.gate_code;
if (current) await loadAttempts(String(current));
} catch {
error.value = t('admin.shippingProcessGates.detailFailed');
detail.value = null;
} finally {
detailLoading.value = false;
}
}
/**
* 加载指定 Gate 的 Attempt 列表。
*/
async function loadAttempts(gateCode: string) {
if (!detail.value?.execution_no) return;
selectedGateCode.value = gateCode;
attemptsLoading.value = true;
try {
attemptsPayload.value = await listAdminProcessGateAttempts(detail.value.execution_no, gateCode);
} catch {
attemptsPayload.value = null;
error.value = t('admin.shippingProcessGates.attemptsFailed');
} finally {
attemptsLoading.value = false;
}
}
/**
* 关闭详情面板。
*/
function closeDetail() {
detail.value = null;
selectedGateCode.value = '';
attemptsPayload.value = null;
}
onMounted(() => {
void load();
});
</script>
<template>
<div class="space-y-6 p-4 sm:p-6">
<header>
<h1 class="text-xl font-bold">{{ t('admin.shippingProcessGates.title') }}</h1>
<p class="mt-1 max-w-3xl text-sm text-muted">{{ t('admin.shippingProcessGates.subtitle') }}</p>
</header>
<section class="rounded-xl border border-default bg-surface p-4">
<div class="grid gap-3 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
<label class="text-sm">
<span class="mb-1 block text-xs text-muted">{{ t('admin.shippingProcessGates.status') }}</span>
<select v-model="filters.status" class="w-full rounded border border-default px-2 py-1.5 text-sm">
<option value="">{{ t('admin.shippingProcessGates.allStatuses') }}</option>
<option v-for="code in EXECUTION_STATUS_OPTIONS" :key="code" :value="code">
{{ statusLabel(code) }}
</option>
</select>
</label>
<label class="text-sm">
<span class="mb-1 block text-xs text-muted">{{ t('admin.shippingProcessGates.filterGate') }}</span>
<input
v-model="filters.gate_code"
type="text"
class="w-full rounded border border-default px-2 py-1.5 text-sm font-mono"
:placeholder="t('admin.shippingProcessGates.gateCode')"
/>
</label>
<label class="text-sm">
<span class="mb-1 block text-xs text-muted">{{ t('admin.shippingProcessGates.filterReason') }}</span>
<input
v-model="filters.blocking_reason_code"
type="text"
class="w-full rounded border border-default px-2 py-1.5 text-sm font-mono"
:placeholder="t('admin.shippingProcessGates.blockingReasonCode')"
/>
</label>
<label class="text-sm">
<span class="mb-1 block text-xs text-muted">{{ t('admin.shippingProcessGates.filterParty') }}</span>
<input
v-model="filters.responsible_party"
type="text"
class="w-full rounded border border-default px-2 py-1.5 text-sm"
:placeholder="t('admin.shippingProcessGates.responsibleParty')"
/>
</label>
<label class="text-sm sm:col-span-2 lg:col-span-1">
<span class="mb-1 block text-xs text-muted">{{ t('admin.shippingProcessGates.filterSearch') }}</span>
<input
v-model="filters.q"
type="search"
class="w-full rounded border border-default px-2 py-1.5 text-sm"
:placeholder="t('admin.shippingProcessGates.executionNo')"
/>
</label>
<label class="text-sm">
<span class="mb-1 block text-xs text-muted">{{ t('admin.shippingProcessGates.filterFrom') }}</span>
<input v-model="filters.updated_from" type="datetime-local" class="w-full rounded border border-default px-2 py-1.5 text-sm" />
</label>
<label class="text-sm">
<span class="mb-1 block text-xs text-muted">{{ t('admin.shippingProcessGates.filterTo') }}</span>
<input v-model="filters.updated_to" type="datetime-local" class="w-full rounded border border-default px-2 py-1.5 text-sm" />
</label>
</div>
<div class="mt-3 flex flex-wrap items-center gap-2">
<button type="button" class="rounded border border-default px-3 py-1.5 text-sm" @click="applyFilters">
{{ t('admin.shippingProcessGates.applyFilters') }}
</button>
<button type="button" class="rounded border border-default px-3 py-1.5 text-sm" @click="resetFilters">
{{ t('admin.shippingProcessGates.resetFilters') }}
</button>
<button type="button" class="rounded border border-default px-3 py-1.5 text-sm" @click="load">
{{ t('admin.shippingProcessGates.refresh') }}
</button>
<span class="text-xs text-muted">{{ t('admin.shippingProcessGates.total', { count: total }) }}</span>
</div>
</section>
<p v-if="error" class="text-sm text-rose-600">{{ error }}</p>
<!-- 小屏:卡片列表,避免列标题逐字换行 -->
<div class="space-y-3 lg:hidden" data-testid="shipping-process-gate-cards">
<p v-if="loading" class="rounded-xl border border-default px-4 py-8 text-center text-sm text-muted">
{{ t('admin.shippingProcessGates.loading') }}
</p>
<p v-else-if="!rows.length" class="rounded-xl border border-default px-4 py-8 text-center text-sm text-muted">
{{ t('admin.shippingProcessGates.empty') }}
</p>
<article
v-for="row in rows"
:key="row.execution_no"
class="rounded-xl border border-default bg-surface px-4 py-3 text-sm"
>
<div class="font-mono text-xs break-all">{{ row.execution_no }}</div>
<dl class="mt-2 grid grid-cols-1 gap-1.5 sm:grid-cols-2">
<div>
<dt class="text-xs text-muted">{{ t('admin.shippingProcessGates.status') }}</dt>
<dd>
<span>{{ statusLabel(row.status) }}</span>
<span class="ml-1 font-mono text-[11px] text-muted">{{ row.status }}</span>
</dd>
</div>
<div>
<dt class="text-xs text-muted">{{ t('admin.shippingProcessGates.currentGate') }}</dt>
<dd class="font-mono text-xs break-all">{{ row.current_gate_code || '—' }}</dd>
</div>
<div class="sm:col-span-2">
<dt class="text-xs text-muted">{{ t('admin.shippingProcessGates.nextAction') }}</dt>
<dd class="text-xs">{{ actionLabel(row.primary_next_action_code) }}</dd>
</div>
<div>
<dt class="text-xs text-muted">{{ t('admin.shippingProcessGates.updatedAt') }}</dt>
<dd class="text-xs">{{ formatTime(row.updated_at) }}</dd>
</div>
</dl>
<button
type="button"
class="mt-3 text-sm text-brand-600 hover:underline"
@click="openDetail(row.execution_no)"
>
{{ t('admin.shippingProcessGates.viewDetail') }}
</button>
</article>
</div>
<!-- lg+:横向表格;表头 nowrap + 外层滚动 -->
<div class="hidden lg:block">
<p class="mb-2 text-xs text-muted">{{ t('admin.shippingProcessGates.scrollHint') }}</p>
<div class="overflow-x-auto rounded-xl border border-default">
<table class="min-w-[720px] w-full text-sm">
<thead class="bg-surface-soft text-left text-xs uppercase text-muted">
<tr>
<th class="whitespace-nowrap px-4 py-3">{{ t('admin.shippingProcessGates.executionNo') }}</th>
<th class="whitespace-nowrap px-4 py-3">{{ t('admin.shippingProcessGates.status') }}</th>
<th class="whitespace-nowrap px-4 py-3">{{ t('admin.shippingProcessGates.currentGate') }}</th>
<th class="whitespace-nowrap px-4 py-3">{{ t('admin.shippingProcessGates.nextAction') }}</th>
<th class="whitespace-nowrap px-4 py-3">{{ t('admin.shippingProcessGates.updatedAt') }}</th>
<th class="whitespace-nowrap px-4 py-3">{{ t('admin.shippingProcessGates.actions') }}</th>
</tr>
</thead>
<tbody>
<tr v-if="loading">
<td colspan="6" class="px-4 py-8 text-center text-muted">{{ t('admin.shippingProcessGates.loading') }}</td>
</tr>
<tr v-else-if="!rows.length">
<td colspan="6" class="px-4 py-8 text-center text-muted">{{ t('admin.shippingProcessGates.empty') }}</td>
</tr>
<tr v-for="row in rows" :key="row.execution_no" class="border-t border-default">
<td class="whitespace-nowrap px-4 py-3 font-mono text-xs">{{ row.execution_no }}</td>
<td class="px-4 py-3">
<div>{{ statusLabel(row.status) }}</div>
<div class="font-mono text-[11px] text-muted">{{ row.status }}</div>
</td>
<td class="whitespace-nowrap px-4 py-3 font-mono text-xs">{{ row.current_gate_code || '—' }}</td>
<td class="px-4 py-3 text-xs">{{ actionLabel(row.primary_next_action_code) }}</td>
<td class="whitespace-nowrap px-4 py-3">{{ formatTime(row.updated_at) }}</td>
<td class="whitespace-nowrap px-4 py-3">
<button type="button" class="text-brand-600 hover:underline" @click="openDetail(row.execution_no)">
{{ t('admin.shippingProcessGates.viewDetail') }}
</button>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="flex items-center gap-2 text-sm">
<button type="button" class="rounded border border-default px-3 py-1.5 disabled:opacity-50" :disabled="page <= 1 || loading" @click="page -= 1; load()">
{{ t('admin.shippingProcessGates.previous') }}
</button>
<span>{{ page }}</span>
<button type="button" class="rounded border border-default px-3 py-1.5 disabled:opacity-50" :disabled="page * pageSize >= total || loading" @click="page += 1; load()">
{{ t('admin.shippingProcessGates.next') }}
</button>
</div>
<aside
v-if="detail"
class="rounded-xl border border-default bg-surface p-4"
data-testid="shipping-process-gate-detail"
>
<div class="mb-4 flex items-center justify-between gap-2">
<h2 class="text-lg font-semibold">{{ t('admin.shippingProcessGates.detailTitle') }}</h2>
<button type="button" class="text-sm text-muted hover:text-primary" @click="closeDetail">{{ t('admin.close') }}</button>
</div>
<p v-if="detailLoading" class="text-sm text-muted">{{ t('admin.shippingProcessGates.loading') }}</p>
<template v-else>
<dl class="grid gap-2 text-sm sm:grid-cols-2">
<div><dt class="text-muted">{{ t('admin.shippingProcessGates.executionNo') }}</dt><dd class="font-mono text-xs break-all">{{ detail.execution_no }}</dd></div>
<div>
<dt class="text-muted">{{ t('admin.shippingProcessGates.status') }}</dt>
<dd>
{{ statusLabel(detail.status) }}
<span class="ml-1 font-mono text-[11px] text-muted">{{ detail.status }}</span>
</dd>
</div>
<div><dt class="text-muted">{{ t('admin.shippingProcessGates.taskNo') }}</dt><dd class="font-mono text-xs">{{ detail.task_no || '—' }}</dd></div>
<div><dt class="text-muted">{{ t('admin.shippingProcessGates.caseNo') }}</dt><dd class="font-mono text-xs">{{ detail.review_case_no || detail.case_no || '—' }}</dd></div>
</dl>
<h3 class="mt-6 text-sm font-semibold">{{ t('admin.shippingProcessGates.gates') }}</h3>
<div class="mt-2 space-y-2 lg:hidden">
<article
v-for="gate in diagnosticGates"
:key="String(gate.gate_code)"
class="rounded-lg border border-default px-3 py-2 text-xs"
:class="{ 'bg-amber-50/60 dark:bg-amber-950/20': selectedGateCode === gate.gate_code }"
>
<div class="font-semibold">#{{ gate.sequence_no }} · {{ gate.gate_code }}</div>
<div class="mt-1">{{ statusLabel(String(gate.status)) }} <span class="font-mono text-muted">{{ gate.status }}</span></div>
<div class="mt-1 font-mono text-muted">{{ gate.blocking_reason_code || '—' }}</div>
<button type="button" class="mt-2 text-brand-600 hover:underline" @click="loadAttempts(String(gate.gate_code))">
{{ t('admin.shippingProcessGates.viewAttempts') }}
</button>
</article>
</div>
<div class="mt-2 hidden overflow-x-auto rounded-lg border border-default lg:block">
<table class="min-w-[640px] w-full text-xs">
<thead class="bg-surface-soft text-left text-muted">
<tr>
<th class="whitespace-nowrap px-3 py-2">#</th>
<th class="whitespace-nowrap px-3 py-2">{{ t('admin.shippingProcessGates.gateCode') }}</th>
<th class="whitespace-nowrap px-3 py-2">{{ t('admin.shippingProcessGates.gateStatus') }}</th>
<th class="whitespace-nowrap px-3 py-2">{{ t('admin.shippingProcessGates.blockingReason') }}</th>
<th class="whitespace-nowrap px-3 py-2">{{ t('admin.shippingProcessGates.actions') }}</th>
</tr>
</thead>
<tbody>
<tr
v-for="gate in diagnosticGates"
:key="String(gate.gate_code)"
class="border-t border-default"
:class="{ 'bg-amber-50/60 dark:bg-amber-950/20': selectedGateCode === gate.gate_code }"
>
<td class="whitespace-nowrap px-3 py-2">{{ gate.sequence_no }}</td>
<td class="whitespace-nowrap px-3 py-2 font-mono">{{ gate.gate_code }}</td>
<td class="px-3 py-2">
<div>{{ statusLabel(String(gate.status)) }}</div>
<div class="font-mono text-[11px] text-muted">{{ gate.status }}</div>
</td>
<td class="whitespace-nowrap px-3 py-2 font-mono">{{ gate.blocking_reason_code || '—' }}</td>
<td class="whitespace-nowrap px-3 py-2">
<button type="button" class="text-brand-600 hover:underline" @click="loadAttempts(String(gate.gate_code))">
{{ t('admin.shippingProcessGates.viewAttempts') }}
</button>
</td>
</tr>
</tbody>
</table>
</div>
<section v-if="selectedGateDetail" class="mt-4 rounded-lg border border-default px-3 py-3 text-xs">
<h4 class="font-semibold">{{ t('admin.shippingProcessGates.gateDiagnostics') }}</h4>
<p class="mt-1 text-muted">
{{ t('admin.shippingProcessGates.nextAction') }}:
<span>{{ actionLabel(String(selectedGateDetail.next_action_code || '')) }}</span>
</p>
<div class="mt-3">
<div class="font-medium text-muted">{{ t('admin.shippingProcessGates.findingsStructured') }}</div>
<p v-if="!selectedGateFindings.length" class="mt-1 text-muted">{{ t('admin.shippingProcessGates.noFindings') }}</p>
<div v-else class="mt-2 space-y-2">
<article
v-for="(finding, index) in selectedGateFindings"
:key="`${finding.finding_code || finding.reason_code || index}`"
class="rounded border border-default bg-surface-soft px-3 py-2"
>
<div class="flex flex-wrap items-center gap-2">
<span
class="rounded px-1.5 py-0.5 font-mono text-[11px]"
:class="finding.severity === 'blocking'
? 'bg-rose-100 text-rose-800 dark:bg-rose-950 dark:text-rose-200'
: 'bg-slate-100 text-slate-700 dark:bg-slate-900 dark:text-slate-200'"
>
{{ t('admin.shippingProcessGates.severity') }}: {{ finding.severity || '—' }}
</span>
</div>
<dl class="mt-2 grid gap-1 sm:grid-cols-2">
<div>
<dt class="text-muted">{{ t('admin.shippingProcessGates.field') }}</dt>
<dd class="font-mono">{{ findingField(finding) }}</dd>
</div>
<div>
<dt class="text-muted">{{ t('admin.shippingProcessGates.party') }}</dt>
<dd>{{ findingParty(finding) }}</dd>
</div>
<div>
<dt class="text-muted">{{ t('admin.shippingProcessGates.reason') }}</dt>
<dd class="font-mono">{{ findingReason(finding) }}</dd>
</div>
<div class="sm:col-span-2">
<dt class="text-muted">{{ t('admin.shippingProcessGates.message') }}</dt>
<dd class="break-words">{{ findingMessage(finding) }}</dd>
</div>
</dl>
</article>
</div>
</div>
<div class="mt-3">
<div class="font-medium text-muted">{{ t('admin.shippingProcessGates.blockingReasonDetail') }}</div>
<p v-if="!selectedBlockingReasonRows.length" class="mt-1 text-muted">—</p>
<dl v-else class="mt-2 divide-y divide-default rounded border border-default">
<div
v-for="row in selectedBlockingReasonRows"
:key="row.key"
class="grid gap-1 px-3 py-2 sm:grid-cols-[minmax(8rem,30%)_1fr]"
>
<dt class="font-mono text-muted">{{ row.key }}</dt>
<dd class="break-words">{{ row.value }}</dd>
</div>
</dl>
</div>
<div class="mt-3">
<div class="font-medium text-muted">{{ t('admin.shippingProcessGates.effectiveResult') }}</div>
<p v-if="!selectedEffectiveResultSummary.length && !selectedEffectiveResultRemainder" class="mt-1 text-muted">—</p>
<div v-else class="mt-2 space-y-2">
<div v-if="selectedEffectiveResultSummary.length" class="flex flex-wrap gap-2">
<span
v-for="chip in selectedEffectiveResultSummary"
:key="chip.key"
class="rounded-full border border-default bg-surface-soft px-2 py-0.5 font-mono text-[11px]"
>
{{ chip.key }}: {{ chip.value }}
</span>
</div>
<details v-if="selectedEffectiveResultRemainder">
<summary class="cursor-pointer text-brand-600">
{{ Object.keys(selectedEffectiveResultRemainder).join(', ') }}
</summary>
<pre class="mt-2 max-h-48 overflow-auto rounded bg-surface-soft p-2">{{ formatJson(selectedEffectiveResultRemainder) }}</pre>
</details>
</div>
</div>
</section>
<div class="mt-6 flex flex-wrap items-center justify-between gap-2">
<h3 class="text-sm font-semibold">
{{ t('admin.shippingProcessGates.attempts') }}
<span v-if="selectedGateCode" class="font-mono text-xs text-muted">({{ selectedGateCode }})</span>
</h3>
<button
type="button"
class="text-xs text-brand-600 hover:underline"
@click="openAuditForExecution(detail.execution_no)"
>
{{ t('admin.shippingProcessGates.openAudit') }}
</button>
</div>
<p class="text-xs text-muted">{{ t('admin.shippingProcessGates.auditLink') }}</p>
<p v-if="attemptsLoading" class="mt-2 text-sm text-muted">{{ t('admin.shippingProcessGates.loading') }}</p>
<div v-else-if="attemptRows.length" class="mt-2 space-y-2">
<article
v-for="attempt in attemptRows"
:key="String(attempt.id || attempt.attempt_no)"
class="rounded-lg border border-default px-3 py-2 text-xs"
>
<div class="font-mono">#{{ attempt.attempt_no }} · {{ statusLabel(String(attempt.status)) }} <span class="text-muted">({{ attempt.status }})</span></div>
<div v-if="attempt.error_code" class="mt-1 text-rose-700">{{ attempt.error_code }}: {{ attempt.error_summary }}</div>
<div class="mt-1 text-muted">{{ formatTime(attempt.started_at as string) }} → {{ formatTime(attempt.finished_at as string) }}</div>
<div class="mt-1 text-muted">
hash:
in={{ attempt.input_snapshot_hash || '—' }}
/ out={{ attempt.output_snapshot_hash || '—' }}
</div>
<ul v-if="formatAttemptDiffSummary(attempt.snapshot_diff).length" class="mt-2 space-y-0.5 text-muted">
<li v-for="(line, lineIndex) in formatAttemptDiffSummary(attempt.snapshot_diff)" :key="lineIndex">
{{ line }}
</li>
</ul>
<details v-if="attempt.input_snapshot || attempt.output_snapshot" class="mt-2">
<summary class="cursor-pointer text-brand-600">{{ t('admin.shippingProcessGates.viewSnapshots') }}</summary>
<div class="mt-2 grid gap-2 md:grid-cols-2">
<pre class="max-h-48 overflow-auto rounded bg-surface-soft p-2">{{ formatJson(attempt.input_snapshot) }}</pre>
<pre class="max-h-48 overflow-auto rounded bg-surface-soft p-2">{{ formatJson(attempt.output_snapshot) }}</pre>
</div>
</details>
</article>
</div>
<p v-else class="mt-2 text-sm text-muted">{{ t('admin.shippingProcessGates.noAttempts') }}</p>
</template>
</aside>
</div>
</template>
@@ -17,6 +17,7 @@ const shippingRoutes = adminRoutes[0].children?.filter((route) =>
|| route.name === 'AdminShippingIdentityRules'
|| route.name === 'AdminShippingOrderExtractionRuns'
|| route.name === 'AdminShippingAudit'
|| route.name === 'AdminShippingProcessGates'
|| route.name === 'AdminShippingOrderDocumentProfiles',
) ?? [];
@@ -46,10 +47,11 @@ describe('shipping configuration navigation contract', () => {
{ id: 'routing_rules', routeName: 'AdminShippingInventory', path: 'shipping-notice', labelKey: 'admin.shippingInventory.rules', groupKey: 'admin.nav.shippingInventoryManagement', query: { section: 'rules' } },
{ id: 'shipping_templates', routeName: 'AdminShippingInventory', path: 'shipping-notice', labelKey: 'admin.shippingInventory.excelTemplates', groupKey: 'admin.nav.shippingInventoryManagement', query: { section: 'templates' } },
{ id: 'shipping_audit', routeName: 'AdminShippingAudit', path: 'shipping-audit', labelKey: 'admin.nav.shippingAudit', groupKey: 'admin.nav.shippingRunAudit' },
{ id: 'process_gates', routeName: 'AdminShippingProcessGates', path: 'shipping-process-gates', labelKey: 'admin.nav.shippingProcessGates', groupKey: 'admin.nav.shippingRunAudit' },
{ id: 'inventory_snapshots', routeName: 'AdminShippingInventory', path: 'shipping-notice', labelKey: 'admin.shippingInventory.snapshots', groupKey: 'admin.nav.shippingRunAudit', query: { section: 'snapshots' } },
{ id: 'export_records', routeName: 'AdminShippingInventory', path: 'shipping-notice', labelKey: 'admin.shippingInventory.exports', groupKey: 'admin.nav.shippingRunAudit', query: { section: 'exports' } },
]);
expect(shippingRoutes).toHaveLength(7);
expect(shippingRoutes).toHaveLength(8);
expect(shippingRoutes.some((route) => route.name === 'AdminShippingReviewSupervision')).toBe(false);
});
@@ -72,6 +74,7 @@ describe('shipping configuration navigation contract', () => {
expect.objectContaining({ requiresAdmin: true, adminModule: 'shipping_inventory', adminSubModule: 'identity_rules' }),
expect.objectContaining({ requiresAdmin: true, adminModule: 'shipping_inventory', adminSubModule: 'order_extraction_runs' }),
expect.objectContaining({ requiresAdmin: true, adminModule: 'shipping_inventory', adminSubModule: 'shipping_audit' }),
expect.objectContaining({ requiresAdmin: true, adminModule: 'shipping_inventory', adminSubModule: 'process_gates' }),
expect.objectContaining({ requiresAdmin: true, adminModule: 'shipping_inventory', adminSubModule: 'order_document_profiles' }),
]);
});
@@ -28,6 +28,7 @@ export type ShippingConfigSubModuleId =
| 'identity_rules'
| 'order_extraction_runs'
| 'shipping_audit'
| 'process_gates'
| 'inventory_fields'
| 'connections'
| 'inventory_sites'
@@ -2,7 +2,8 @@
* features/admin/views/AdminLayout.vue
* 管理后台壳层:顶栏 + 左侧导航 + 子路由出口。
* 依赖:AdminNav、vue-router、admin-nav.store。
* 逻辑:AdminNav 统一承担模块和二级目录导航,内容区保持全宽展示当前页面。
* 逻辑:AdminNav 统一承担模块和二级目录导航;lg 起侧栏与内容并排,
* 小于 lg(含 768px)上下堆叠,避免运维诊断页主区被侧栏挤窄。
*/
<script setup lang="ts">
import { onMounted } from 'vue';
@@ -27,7 +28,7 @@ onMounted(() => {
<div class="page-shell min-h-screen font-sans flex flex-col">
<header class="app-header px-6">
<div class="flex items-center gap-4">
<button type="button" class="btn-icon-ds md:block hidden" @click="navStore.toggleSidebar()">
<button type="button" class="btn-icon-ds lg:block hidden" @click="navStore.toggleSidebar()">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect width="18" height="18" x="3" y="3" rx="2"/><path d="M9 3v18"/></svg>
</button>
<button type="button" class="btn-icon-ds" @click="router.push('/workspace')">
@@ -43,7 +44,8 @@ onMounted(() => {
<AppHeaderTools />
</header>
<main class="flex-1 w-full mx-auto px-4 md:px-8 py-6 md:py-8 flex flex-col md:flex-row gap-8 items-start">
<!-- lg 起才并排侧栏;768px 平板保持上下堆叠,避免诊断等运维页主内容被挤窄 -->
<main class="flex-1 w-full mx-auto px-4 md:px-8 py-6 md:py-8 flex flex-col lg:flex-row gap-6 lg:gap-8 items-start">
<AdminNav />
<section class="flex-1 min-w-0 w-full space-y-8">
<router-view />
@@ -1,26 +1,39 @@
<!--
features/chat/components/shipping-review/ReviewBuildEligibilityPanel.vue
用途:展示建单前资格摘要(can_build、阻断原因、行级 Reservation 与库存候选)。
依赖:vue-i18n、ShippingOrderReviewBuildEligibility 类型。
逻辑:ShippingOrderReviewView 传入 draft.build_eligibility;只读展示,不发起写请求。
用途:展示建单前资格摘要(can_build、阻断原因、行级 Reservation 与库存候选)及 Gate 恢复卡片。
依赖:vue-i18n、ProcessGateRecoveryCard、ShippingOrderReviewBuildEligibility 类型。
逻辑:ShippingOrderReviewView 传入 draft.build_eligibility 与 case.process_gate;只读展示资格,Gate 动作可导航/POST。
-->
<script setup lang="ts">
import { computed } from 'vue';
import { useI18n } from 'vue-i18n';
import type { ShippingOrderReviewBuildEligibility } from '@/features/chat/types/shipping.api.types';
import ProcessGateRecoveryCard from '@/features/shipping-process-gates/components/ProcessGateRecoveryCard.vue';
import type {
ShippingOrderReviewBuildEligibility,
ShippingProcessGateUserSummary,
} from '@/features/chat/types/shipping.api.types';
import type { ProcessGateNavigationContext } from '@/features/shipping-process-gates/composables/processGateNavigation';
const props = defineProps<{
eligibility: ShippingOrderReviewBuildEligibility | null;
processGate?: ShippingProcessGateUserSummary | null;
canHandleGate?: boolean;
navigationContext?: ProcessGateNavigationContext;
}>();
const emit = defineEmits<{
gateRefreshed: [];
}>();
const { t, te } = useI18n();
const canHandle = computed(() => props.canHandleGate !== false);
/**
* 解析建单资格状态文案。
*/
function statusLabel(status: string): string {
const key = `chat.shippingOrderReview.buildEligibility.status.${status}`;
return te(key) ? t(key) : status;
return te(key) ? t(key) : t('chat.shippingOrderReview.buildEligibility.status.unknown');
}
/**
@@ -30,7 +43,7 @@ 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');
}
/**
@@ -40,7 +53,7 @@ function routingStatusLabel(status?: string | null): string {
const normalized = String(status || '').trim();
if (!normalized) return '—';
const key = `chat.shippingOrderReview.buildEligibility.routingStatus.${normalized}`;
return te(key) ? t(key) : normalized;
return te(key) ? t(key) : t('chat.shippingOrderReview.buildEligibility.routingStatus.unknown');
}
/** 未满足建单资格的明细行。 */
@@ -60,6 +73,15 @@ const blockingSummary = computed(() => {
</script>
<template>
<div class="space-y-4">
<ProcessGateRecoveryCard
v-if="processGate?.current_blocking_gate"
:summary="processGate"
:can-handle="canHandle"
:navigation-context="navigationContext"
@refreshed="emit('gateRefreshed')"
@refresh-needed="emit('gateRefreshed')"
/>
<section
v-if="eligibility"
class="rounded-xl border border-slate-200 bg-white p-4 shadow-sm dark:border-slate-800 dark:bg-slate-900"
@@ -164,4 +186,5 @@ const blockingSummary = computed(() => {
</article>
</div>
</section>
</div>
</template>
@@ -5,6 +5,7 @@
* orderExtractionProgressDisplay、Workflow 计数投影、vue-router、vue-i18n。
* 逻辑:有 Workflow 投影时优先展示统一 counts;否则回退 handling_items / primary_notice;
* 「查看处理详情」挂载详情抽屉;抽屉内证据/复核入口携带 focus+document_id 打开复核页;
* 用户界面只展示业务原因,内部错误码仅保留在管理员审计中;
* 文档与时间线加载失败支持独立就地重试;右侧 ShippingWorkflowTimeline 承接逐 PDF 明细。
*/
<script setup lang="ts">
@@ -19,8 +20,10 @@ import type {
import type {
ShippingOrderExtractionDocumentResult,
ShippingOrderExtractionProgressEvent,
ShippingProcessGateUserSummary,
ShippingWorkflowItemCounts,
} from '../../types/shipping.api.types';
import ProcessGateRecoveryCard from '@/features/shipping-process-gates/components/ProcessGateRecoveryCard.vue';
import {
listWorkspaceShippingOrderExtractionDocuments,
listWorkspaceShippingOrderExtractionProgressEvents,
@@ -60,6 +63,22 @@ const confirmCancelOpen = ref(false);
const cancelReason = ref('');
const injectedWorkflow = inject(SHIPPING_WORKFLOW_KEY, null);
/**
* 从 Workflow Items 中取首个阻断 Gate 摘要,供 Run 级卡片展示。
*/
const runLevelProcessGate = computed((): ShippingProcessGateUserSummary | null => {
const items = injectedWorkflow?.items.value || [];
for (const item of items) {
if (item.process_gate?.current_blocking_gate) return item.process_gate;
}
return null;
});
const gateNavigationContext = computed(() => ({
agentId: String(route.params.agentId || ''),
conversationId: String(route.query.conversation_id || ''),
}));
const detailsOpen = ref(false);
const detailsLoading = ref(false);
const detailsLoadFailed = ref(false);
@@ -249,18 +268,7 @@ function handlingTitle(item: ShippingOrderExtractionHandlingItemState): string {
}
/**
* 解析原因码是否已有本地化文案。
* @param code - 原因码
*/
function hasReasonLabel(code: string): boolean {
const normalized = String(code || '').trim();
if (!normalized) return false;
return te(`chat.shippingOrderExtractionReason.${normalized}`)
|| te(`chat.shippingOrderExtractionHandling.reason.${normalized}`);
}
/**
* 解析原因码文案;未知码回退通用提示(原始码放入技术详情)。
* 解析原因码文案;未知或内部技术码统一回退为可执行的业务提示。
* @param code - 原因码
*/
function reasonLabel(code: string): string {
@@ -272,16 +280,6 @@ function reasonLabel(code: string): string {
return te(freezeKey) ? t(freezeKey) : t('chat.shippingOrderExtractionReasonUnknown');
}
/**
* 收集事项中无本地化文案的原因码,供可展开技术详情展示。
* @param item - 处理事项
*/
function unknownReasonCodes(item: ShippingOrderExtractionHandlingItemState): string[] {
return (item.reasonCodes || [])
.map((code) => String(code || '').trim())
.filter((code) => code && !hasReasonLabel(code));
}
/**
* 打开订单复核工作台(Chat order-review 模式)。
* @param options.documentId - 可选,定位到具体 PDF
@@ -536,6 +534,16 @@ function openCancelConfirm() {
<span v-if="workflowLastActivityLabel" class="ml-1">· {{ workflowLastActivityLabel }}</span>
</div>
<ProcessGateRecoveryCard
v-if="runLevelProcessGate?.current_blocking_gate"
class="mt-2"
:summary="runLevelProcessGate"
:can-handle="true"
:navigation-context="gateNavigationContext"
@refreshed="emit('refresh')"
@refresh-needed="emit('refresh')"
/>
<div
v-if="handlingItems.length"
class="mt-2 space-y-1.5"
@@ -569,18 +577,6 @@ function openCancelConfirm() {
<div v-if="item.reasonCodes.length" class="mt-1 opacity-80">
{{ t('chat.shippingOrderExtractionHandling.reasonPrefix') }}
{{ item.reasonCodes.slice(0, 4).map(reasonLabel).join(';') }}
<details
v-if="unknownReasonCodes(item).length"
class="mt-1"
data-testid="shipping-order-extraction-reason-tech"
>
<summary class="cursor-pointer opacity-90">
{{ t('chat.shippingOrderExtractionReasonTechDetails') }}
</summary>
<code class="mt-1 block break-all text-[11px]">
{{ unknownReasonCodes(item).join(', ') }}
</code>
</details>
</div>
<div
v-if="affectedRows(item).length"
@@ -4,14 +4,17 @@
* 依赖:vue-i18n、useMessage、useShippingNoticeWorkflow(inject 或自建)、DetailDrawer、ReasonDialog。
* 逻辑:多批次时展示切换器;Items 以文件名为主标题;
* 分组进行中/待处理/待复核/待人工上传登记/失败/已完成(登记前不得进已完成);
* 「仅看待处理」过滤;查看进度 / 取消 / 重试重识别;取消与重识别用应用内原因弹窗。
* 「仅看待处理」过滤;待复核项提供直接进入复核工作台;查看进度 / 取消 / 重试重识别;
* 取消与重识别用应用内原因弹窗。侧栏在桌面端可收窄,在窄屏自动占满宽度。
*/
<script setup lang="ts">
import { computed, inject, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { 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 ProcessGateRecoveryCard from '@/features/shipping-process-gates/components/ProcessGateRecoveryCard.vue';
import {
getWorkspaceShippingWorkflowItem,
} from '@/features/chat/api/shipping.api';
@@ -39,6 +42,13 @@ const props = defineProps<{
const { t, te, locale } = useI18n();
const msg = useMessage();
const route = useRoute();
const router = useRouter();
const gateNavigationContext = computed(() => ({
agentId: String(route.params.agentId || ''),
conversationId: String(props.conversationId || route.query.conversation_id || ''),
}));
const injected = inject(SHIPPING_WORKFLOW_KEY, null);
/** 父级已 provide/传入时本地 composable 以空 conversationId 待机,避免双轮询。 */
@@ -72,6 +82,31 @@ const items = computed((): ShippingWorkflowItem[] => ctl.value.items.value);
const loading = computed(() => ctl.value.loading.value);
const error = computed(() => ctl.value.error.value);
/**
* 打开当前 PDF 对应的人工复核工作台。
* 核心逻辑:复核入口必须复用当前 WorkflowItem 的 Run/Case/文档上下文,
* 避免用户从侧栏进入后还要重新寻找待处理文件。
*/
async function openReview(item: ShippingWorkflowItem) {
const runNo = String(item.current_run_no || '').trim();
if (!runNo) return;
const query: Record<string, string> = {
mode: 'order-review',
run_no: runNo,
focus: 'draft',
document_id: String(item.current_document_id || ''),
};
const caseNo = String(item.current_case_no || '').trim();
if (caseNo) query.case_no = caseNo;
const conversationId = String(props.conversationId || route.query.conversation_id || '').trim();
if (conversationId) query.conversation_id = conversationId;
await router.push({
name: 'Chat',
params: { agentId: String(route.params.agentId || '') },
query,
});
}
const counts = computed(() => workflow.value?.counts || {
total: items.value.length,
processing: 0,
@@ -202,7 +237,7 @@ const groupOrder: ItemGroupKey[] = [
*/
function statusLabel(status: string): string {
const key = `chat.shippingWorkflow.itemStatus.${status}`;
return te(key) ? t(key) : status;
return te(key) ? t(key) : t('chat.shippingWorkflow.itemStatus.unknown');
}
/**
@@ -286,6 +321,36 @@ function openReparseDialog(item: ShippingWorkflowItem) {
reasonDialogOpen.value = true;
}
/**
* 将重新识别失败转换为可执行提示,而不是直接展示内部配置错误。
* @param error - API 层 BusinessError 或未知异常
* @returns 面向业务人员的分层错误提示
*/
function reparseErrorMessage(error: unknown): { title: string; message: string } {
if (!(error instanceof BusinessError)) {
return { title: t('chat.shippingWorkflow.reparseError.title'), message: t('chat.shippingWorkflow.reparseError.generic') };
}
const details = error.details || {};
const code = String(error.code || '').toUpperCase();
const requestId = error.requestId ? `\n${t('chat.shippingWorkflow.reparseError.requestId', { id: error.requestId })}` : '';
if (code.includes('SCHEMA_VERSION_INVALID') || code.includes('SNAPSHOT_OBSOLETE') || code.includes('CANDIDATE_SOURCE_CHANGED')) {
return {
title: t('chat.shippingWorkflow.reparseError.title'),
message: `${t('chat.shippingWorkflow.reparseError.schemaUnavailable')}\n${t('chat.shippingWorkflow.reparseError.fallback')}\n${t('chat.shippingWorkflow.reparseError.contactAdmin')}${requestId}`,
};
}
if (code.includes('REPARSE_PENDING')) {
return { title: t('chat.shippingWorkflow.reparseError.title'), message: t('chat.shippingWorkflow.reparseError.pending') };
}
const fallback = details.fallback_available === true
? `\n${t('chat.shippingWorkflow.reparseError.fallback')}`
: '';
return {
title: t('chat.shippingWorkflow.reparseError.title'),
message: `${error.message || t('chat.shippingWorkflow.reparseError.generic')}${fallback}${requestId}`,
};
}
/**
* 原因弹窗确认:按 action 取消或重识别。
*/
@@ -316,8 +381,7 @@ async function onReasonConfirm(payload: { reason: string; comment?: string }) {
// 失败时关闭原因确认框,避免与错误提示双遮罩。
reasonDialogOpen.value = false;
reasonDialogItem.value = null;
const message = err instanceof BusinessError ? err.message : t('errors.generic');
msg.error(message);
msg.error(reparseErrorMessage(err));
} finally {
actionBusyItemNo.value = null;
}
@@ -333,7 +397,8 @@ watch(
<template>
<aside
class="flex w-72 shrink-0 flex-col border-l border-default bg-surface shadow-[-8px_0_24px_rgba(15,23,42,0.04)]"
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'"
data-testid="shipping-workflow-timeline"
>
<div class="flex w-full items-center gap-1 border-b border-default px-2 py-2">
@@ -342,7 +407,7 @@ watch(
class="flex min-w-0 flex-1 items-center justify-between gap-2 rounded-md px-1 py-1 text-left hover:bg-surface-muted/60"
@click="collapsed = !collapsed"
>
<div class="min-w-0">
<div v-if="!collapsed" class="min-w-0">
<div class="text-sm font-semibold text-primary">
{{ t('chat.shippingWorkflow.title') }}
</div>
@@ -528,7 +593,26 @@ watch(
<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"
@@ -4,6 +4,7 @@
* 依赖:无(纯类型模块)。
* 逻辑:shipping.api.ts 与 Chat/工作台组件统一引用本文件 DTO 类型。
* 阶段 0 冻结用户可见阶段、健康提示、取消元数据与审计 DTO;写路径与 UI 在后续阶段启用。
* 门禁恢复 Phase 1:ShippingProcessGate* 联合类型与 Python process_gate_contract 对齐。
*/
export type InventorySourceStatus =
| 'unresolved'
@@ -218,6 +219,138 @@ export interface ShippingProcessFieldGate {
issues?: ShippingParseIssue[];
}
/**
* 全门禁中断恢复 — 业务门禁编码(与 process_gate_contract.PROCESS_GATE_CODES 对齐)。
* Phase 1 仅冻结类型;统一 Execution API 在后续阶段接线。
*/
export type ShippingProcessGateCode =
| 'document_materialization'
| 'layout_parsing'
| 'document_profile_routing'
| 'order_field_extraction'
| 'field_completeness'
| 'reservation_validation'
| 'customer_resolution'
| 'duplicate_detection'
| 'field_conflict_resolution'
| 'inventory_source_routing'
| 'order_freeze_readiness'
| 'task_creation'
| 'inventory_preparation'
| 'inventory_field_mapping'
| 'inventory_matching'
| 'inventory_sufficiency'
| 'excel_readiness'
| 'artifact_generation'
| 'manual_upload_handoff';
/** 门禁实例状态(与 PROCESS_GATE_STATUSES 对齐)。 */
export type ShippingProcessGateStatus =
| 'pending'
| 'queued'
| 'running'
| 'passed'
| 'blocked_retryable'
| 'blocked_manual'
| 'waiting_external'
| 'failed_terminal'
| 'invalidated'
| 'skipped';
/**
* 服务端下发的主要恢复动作码(与 PROCESS_GATE_ACTION_CODES 对齐)。
* 客户端禁止本地发明或提交起始阶段 / 目标状态 / Worker 名。
*/
export type ShippingProcessGateActionCode =
| 'rematerialize_document'
| 'retry_layout_parsing'
| 'reroute_document_profile'
| 'open_profile_review'
| 'retry_order_extraction'
| 'open_order_review'
| 'edit_order_fields'
| 'revalidate_reservation'
| 'edit_reservation'
| 'retry_customer_resolution'
| 'confirm_customer'
| 'retry_duplicate_detection'
| 'adjudicate_duplicate'
| 'resolve_field_conflicts'
| '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'
| 'regenerate_excel_artifact'
| 'regenerate_manual_upload_todo';
/** 门禁责任方(与 PROCESS_GATE_RESPONSIBLE_PARTIES 对齐)。 */
export type ShippingProcessGateResponsibleParty =
| 'system'
| 'worker'
| 'owner'
| 'admin'
| 'external';
/** Gate 用户安全投影(与 serialize_process_gate include_diagnostics=false 对齐)。 */
export interface ShippingProcessGateProjection {
gate_code: ShippingProcessGateCode | string;
sequence_no: number;
label?: string | null;
status: ShippingProcessGateStatus | string;
evaluation_version: number;
blocking_reason_code?: string | null;
blocking_reason?: Record<string, unknown> | null;
findings?: Array<Record<string, unknown>>;
next_action_code?: ShippingProcessGateActionCode | string | null;
passed_at?: string | null;
latest_attempt?: {
attempt_no?: number;
status?: string;
} | null;
}
/** Execution 用户 Gate 摘要(ui_state.process_gate / GET execution 对齐)。 */
export interface ShippingProcessGateUserSummary {
execution_no: string;
status: string;
current_blocking_gate?: ShippingProcessGateProjection | null;
blocking_reason_code?: string | null;
blocking_message?: string | null;
next_action_code?: ShippingProcessGateActionCode | string | null;
responsible_party?: ShippingProcessGateResponsibleParty | string | null;
diagnostic_hint?: string | null;
case_no?: string | null;
review_case_no?: string | null;
review_run_no?: string | null;
task_no?: string | null;
navigation?: {
target?: 'order_review' | 'task_workspace' | string;
focus?: string | null;
run_no?: string | null;
case_no?: string | null;
task_no?: string | null;
} | null;
gates_track?: Array<{
gate_code: ShippingProcessGateCode | string;
label?: string | null;
status: string;
sequence_no: number;
}>;
current_findings?: Array<Record<string, unknown>>;
}
export interface ShippingFieldEvidenceItem {
field?: string;
line_index?: number;
@@ -468,8 +601,12 @@ export interface ShippingTaskUiState {
allowed_actions?: string[] | null;
/** STP 履约事实;仅后端投影,前端禁止二次推导 */
stp_facts?: ShippingStpFacts | null;
/** 统一 Gate 用户摘要(优先于 legacy action_buttons) */
process_gate?: ShippingProcessGateUserSummary | null;
};
action_buttons: ShippingChatAction[];
/** 顶层 Gate 摘要;与 summary.process_gate 同源 */
process_gate?: ShippingProcessGateUserSummary | null;
updated_at?: string | null;
}
@@ -1061,6 +1198,33 @@ export interface ShippingOrderReviewRun {
items: ShippingOrderReviewCaseSummary[];
}
/** 库存路由规则版本摘要(行级投影 / 规则建议内复用)。 */
export interface ShippingOrderReviewInventoryRuleVersion {
rule_id?: number;
rule_code?: string;
version?: number;
}
/** 库存路由命中规则摘要。 */
export interface ShippingOrderReviewInventoryMatchedRule {
rule_id?: number;
rule_code?: string;
version?: number;
priority?: number;
action_type?: string;
scope?: string;
}
/** 规则引擎产出的库存源建议;人工覆盖后仍可对照。 */
export interface ShippingOrderReviewInventoryRuleSuggestion {
source_codes?: string[];
raw_source_codes?: string[];
unavailable_source_codes?: string[];
routing_status?: string;
rule_versions?: ShippingOrderReviewInventoryRuleVersion[];
matched_rule_ids?: number[];
}
/** 建单前资格行级投影;与后端 validation.line_projections 对齐。 */
export interface ShippingOrderReviewBuildEligibilityLineProjection {
line_key?: string | null;
@@ -1068,6 +1232,22 @@ export interface ShippingOrderReviewBuildEligibilityLineProjection {
effective_reservation_id?: string | null;
inventory_source_hint?: string | null;
candidate_inventory_source_codes?: string[];
/** 规则原始命中源(含不可用) */
raw_rule_source_codes?: string[];
/** 规则建议可用源 */
rule_suggestion_source_codes?: string[];
/** 规则命中但当前不可用的源 */
unavailable_source_codes?: string[];
/** 不可用源 → 原因文案 */
unavailable_reasons?: Record<string, string>;
matched_rule_ids?: number[];
matched_rules?: ShippingOrderReviewInventoryMatchedRule[];
rule_versions?: ShippingOrderReviewInventoryRuleVersion[];
rule_suggestion?: ShippingOrderReviewInventoryRuleSuggestion;
/** 人工结果与最新规则建议不一致,待采纳/保留 */
suggestion_pending?: boolean;
/** 与 rule_suggestion_source_codes 同义兼容字段 */
rule_source_codes?: string[];
routing_status?: string;
can_build?: boolean;
block_reason?: string | null;
@@ -1093,6 +1273,20 @@ export interface ShippingOrderReviewInventoryCandidatesWrite {
reason: string;
}
/** 整单或行级重新匹配库存路由写请求。 */
export interface ShippingOrderReviewInventoryRoutingRerouteWrite {
expected_draft_version: number;
idempotency_key?: string;
line_key?: string;
}
/** 采纳规则建议 / 保留人工路由写请求。 */
export interface ShippingOrderReviewInventoryRoutingDecisionWrite {
expected_draft_version: number;
idempotency_key?: string;
reason?: string;
}
export interface ShippingOrderReviewCase {
case_no: string;
run_no: string;
@@ -1114,6 +1308,7 @@ export interface ShippingOrderReviewCase {
} | null;
available_actions: string[];
llm_suggestions?: ShippingOrderReviewLlmSuggestion[];
process_gate?: ShippingProcessGateUserSummary | null;
}
export interface ShippingOrderReviewConfirmResponse {
@@ -1360,6 +1555,9 @@ export interface ShippingWorkflowItem {
reparse_kind?: 'case_version' | 'failed_run_retry' | string | null;
/** 详情接口 include_events=true 时附带。 */
events?: ShippingWorkflowEvent[];
/** 当前 WorkflowItem 版本关联 Execution 的用户 Gate 摘要。 */
process_gate?: ShippingProcessGateUserSummary | null;
gate_user_hint?: string | null;
}
/** Workflow 批次投影;与 serialize_workflow 对齐。 */
@@ -5,10 +5,12 @@
ReviewLineNoOverrideDialog、ReviewBuildEligibilityPanel、ReviewInventoryCandidatesPanel、
ReviewWorkflowProgressPanel、ReviewLlmSuggestionPanel。
逻辑:左 PDF 预览 + 中部订单编辑 + 右侧独立建单资格/库存候选门禁区(sticky);
build_eligibility 驱动建单门禁与零候选时已启用库存源选择;破坏性操作二次确认;
build_eligibility 驱动建单门禁、路由恢复(reroute / adopt / keep)与零候选时已启用库存源选择;
破坏性操作二次确认;
底部操作窄屏纵向堆叠(异常操作在上、保存/确认建单在下且确认最后);
初始加载失败提供就地重试(再次调用 load);
确认后挂载自动进度面板并轮询 Workflow Item;内部项次 line_no 编辑须经覆盖原因弹窗;
确认后挂载自动进度面板;重识别按 WorkflowItem 真实阶段展示并在新版就绪后自动切换;
内部项次 line_no 编辑须经覆盖原因弹窗;
AI 建议请求/裁决走 useShippingOrderReview.requestSuggestion / decideSuggestion。
-->
<script setup lang="ts">
@@ -53,7 +55,7 @@ const {
draftConflictDiffLines,
buildEligibility,
canConfirmBuild,
manualInventoryLines,
routingRecoveryLines,
isViewingHistoricalVersion,
isReadOnly,
loading,
@@ -80,6 +82,9 @@ const {
deleteLine,
validate,
setLineInventoryCandidates,
rerouteInventoryRouting,
adoptInventoryRoutingSuggestion,
keepManualInventoryRouting,
confirm,
createManualDraft,
markNonOrder,
@@ -92,6 +97,10 @@ const {
editable,
showWorkflowProgress,
workflowProgressPolling,
reparseProgressActive,
reparseProgressPolling,
reparseProgressRefreshFailed,
reparseProgressStage,
} = useShippingOrderReview();
const msg = useMessage();
@@ -100,6 +109,11 @@ const agentId = computed(() => String(route.params.agentId || ''));
const conversationId = computed(() => String(page.conversationId || route.query.conversation_id || ''));
const itemNoFromQuery = computed(() => String(route.query.item_no || ''));
const reviewFocus = computed(() => String(route.query.focus || '').trim());
/** Gate 恢复卡片导航上下文(复核台深链)。 */
const reviewGateNavigationContext = computed(() => ({
agentId: agentId.value,
conversationId: conversationId.value,
}));
const focusedEvidenceRef = ref<{ fieldId: string; lineIndex?: number } | null>(null);
watch(
@@ -291,8 +305,24 @@ const caseStatusLabel = (status: string) => {
};
const statusBannerText = computed(() => {
if (!statusMessage.value) return '';
return t(`chat.shippingOrderReview.statusBanner.${statusMessage.value}`);
const key = `chat.shippingOrderReview.statusBanner.${statusMessage.value}`;
return te(key) ? t(key) : t('chat.shippingOrderReview.statusBanner.unknown');
});
/** 将服务端复核问题码转换为业务说明;未知代码不得直接展示给用户。 */
const reviewIssueLabel = (code?: string) => {
const normalized = String(code || '').trim();
const key = `chat.shippingOrderReview.issueCodes.${normalized}`;
return normalized && te(key) ? t(key) : t('chat.shippingOrderReview.issueCodes.unknown');
};
/** 重识别阶段顺序;仅展示后端状态,不推算虚假百分比。 */
const reparseProgressStages = ['submitted', 'layout_parsing', 'extracting', 'draft_ready'] as const;
const reparseProgressIndex = computed(() => (
reparseProgressStage.value === 'failed'
? reparseProgressStages.indexOf('extracting')
: reparseProgressStages.indexOf(reparseProgressStage.value)
));
const workItemVersionLabel = computed(() => {
const versionNo = workItem.value?.current_version_no;
if (!versionNo) return '';
@@ -359,6 +389,27 @@ const submitInventoryCandidates = async (payload: { lineKey: string; sourceCodes
await reportSave(() => setLineInventoryCandidates(payload.lineKey, payload.sourceCodes, payload.reason));
};
/**
* 重新匹配库存路由(行级或整单);进度复用 saving。
*/
const onInventoryRoutingReroute = async (lineKey?: string) => {
await reportSave(() => rerouteInventoryRouting(lineKey));
};
/**
* 采纳待决规则建议。
*/
const onInventoryRoutingAdopt = async (payload: { lineKey: string; reason?: string }) => {
await reportSave(() => adoptInventoryRoutingSuggestion(payload.lineKey, payload.reason));
};
/**
* 保留当前人工库存路由结果。
*/
const onInventoryRoutingKeep = async (payload: { lineKey: string; reason?: string }) => {
await reportSave(() => keepManualInventoryRouting(payload.lineKey, payload.reason));
};
/** 打开指定类型的二次确认弹窗。 */
const openActionDialog = (action: ReviewConfirmAction) => {
pendingAction.value = action;
@@ -556,7 +607,10 @@ const selectVersionFromHistory = async (caseNo: string) => {
*/
const jumpToCurrentVersion = async () => {
const target = await openCurrentVersion();
if (!target) return;
if (!target) {
msg.warning(t('chat.shippingOrderReview.currentVersionUnavailable'));
return;
}
await router.replace({
query: {
...route.query,
@@ -776,6 +830,64 @@ watch(
/>
</div>
<section
v-if="reparseProgressActive"
class="mx-4 mt-3 rounded-xl border border-sky-200 bg-white p-4 shadow-sm dark:border-sky-900 dark:bg-slate-900"
data-testid="review-reparse-progress"
>
<div class="flex flex-wrap items-start justify-between gap-2">
<div>
<h2 class="text-sm font-semibold">{{ t('chat.shippingOrderReview.reparseProgress.title') }}</h2>
<p class="mt-0.5 text-xs text-slate-500 dark:text-slate-400">
{{ t('chat.shippingOrderReview.reparseProgress.subtitle') }}
</p>
</div>
<span v-if="reparseProgressPolling" class="text-xs text-sky-700 dark:text-sky-300">
{{ t('chat.shippingOrderReview.reparseProgress.polling') }}
</span>
</div>
<ol class="mt-3 grid gap-2 sm:grid-cols-4">
<li
v-for="(stage, index) in reparseProgressStages"
:key="stage"
class="rounded-lg border px-3 py-2 text-xs"
:class="index < reparseProgressIndex
? 'border-emerald-200 bg-emerald-50 text-emerald-900 dark:border-emerald-900 dark:bg-emerald-950/40 dark:text-emerald-100'
: index === reparseProgressIndex
? 'border-sky-300 bg-sky-50 text-sky-950 dark:border-sky-800 dark:bg-sky-950/40 dark:text-sky-100'
: 'border-slate-200 bg-slate-50 text-slate-500 dark:border-slate-800 dark:bg-slate-950/40 dark:text-slate-400'"
:data-testid="`review-reparse-stage-${stage}`"
>
<span class="font-semibold">{{ index + 1 }}.</span>
{{ t(`chat.shippingOrderReview.reparseProgress.stages.${stage}`) }}
</li>
</ol>
<p
v-if="reparseProgressRefreshFailed"
class="mt-3 text-xs text-amber-700 dark:text-amber-300"
data-testid="review-reparse-refresh-failed"
>
{{ t('chat.shippingOrderReview.reparseProgress.refreshFailed') }}
</p>
<p
v-if="reparseProgressStage === 'failed'"
class="mt-3 flex flex-wrap items-center justify-between gap-2 rounded-lg border border-rose-200 bg-rose-50 px-3 py-2 text-xs text-rose-800 dark:border-rose-900 dark:bg-rose-950/40 dark:text-rose-200"
data-testid="review-reparse-failed"
>
<span>{{ t('chat.shippingOrderReview.reparseProgress.failed') }}</span>
<button
v-if="activeCase?.available_actions.includes('reparse')"
type="button"
class="rounded border border-rose-300 px-2.5 py-1 font-medium hover:bg-rose-100 disabled:opacity-50 dark:border-rose-800 dark:hover:bg-rose-900/50"
:disabled="saving"
data-testid="review-reparse-retry"
@click="openActionDialog('reparse')"
>
{{ t('chat.shippingOrderReview.reparseProgress.retry') }}
</button>
</p>
</section>
<div v-if="loading" class="p-8 text-sm text-slate-600 dark:text-slate-300">{{ t('chat.shippingOrderReview.loading') }}</div>
<div
v-else-if="loadFailed"
@@ -863,7 +975,9 @@ watch(
<div v-if="activeCase?.draft?.issues?.length" class="rounded-lg border border-amber-300 bg-amber-50 p-3 text-xs text-amber-950 dark:border-amber-800 dark:bg-amber-950/30 dark:text-amber-100">
<div class="font-semibold">{{ t('chat.shippingOrderReview.issues') }}</div>
<div v-for="issue in activeCase.draft.issues" :key="`${issue.code}-${issue.severity}`" class="mt-1">{{ issue.code }}</div>
<div v-for="issue in activeCase.draft.issues" :key="`${issue.code}-${issue.severity}`" class="mt-1">
{{ reviewIssueLabel(issue.code) }}
</div>
</div>
<ReviewLlmSuggestionPanel
@@ -1054,13 +1168,22 @@ watch(
data-testid="review-build-gate-rail"
:aria-label="t('chat.shippingOrderReview.buildGateRail')"
>
<ReviewBuildEligibilityPanel :eligibility="buildEligibility" />
<ReviewBuildEligibilityPanel
:eligibility="buildEligibility"
:process-gate="activeCase?.process_gate"
:can-handle-gate="editable"
:navigation-context="reviewGateNavigationContext"
@gate-refreshed="reloadLatestDraft"
/>
<ReviewInventoryCandidatesPanel
:lines="manualInventoryLines"
:lines="routingRecoveryLines"
:enabled-source-codes="buildEligibility?.enabled_inventory_source_codes || []"
:editable="editable"
:saving="saving"
@submit="submitInventoryCandidates"
@reroute="onInventoryRoutingReroute"
@adopt="onInventoryRoutingAdopt"
@keep="onInventoryRoutingKeep"
/>
</aside>
</div>
@@ -0,0 +1,163 @@
/**
* features/shipping-process-gates/api/process-gates.api.ts
* 用途:封装 Workspace / Admin 全门禁恢复 HTTP API。
* 依赖:@/shared/api/client requestJson、process-gate.types。
* 逻辑:由 useShippingProcessGateRecovery 与 ProcessGateRecoveryCard 调用;
* 动作码仅使用服务端下发的 next_action_code / primary_next_action_code。
*/
import { requestJson } from '@/shared/api/client';
import type {
ShippingProcessGateActionRequest,
ShippingProcessGateActionResponse,
ShippingProcessGateAuditEventsPage,
ShippingProcessGateUserSummary,
} from '../types/process-gate.types';
const WORKSPACE_BASE = '/api/workspace/shipping-notice/process-executions';
const ADMIN_BASE = '/api/admin/shipping-notice/process-executions';
export interface AdminProcessExecutionSummary {
execution_no: string;
status: string;
current_gate_code?: string | null;
primary_next_action_code?: string | null;
responsible_party?: string | null;
blocking_reason_code?: string | null;
task_no?: string | null;
workflow_item_id?: number | null;
workflow_item_version_id?: number | null;
review_case_id?: number | null;
task_id?: number | null;
lock_version?: number;
updated_at?: string | null;
}
export interface AdminProcessExecutionListFilters {
status?: string;
gate_code?: string;
blocking_reason_code?: string;
responsible_party?: string;
q?: string;
updated_from?: string;
updated_to?: string;
}
export interface AdminProcessExecutionListPage {
items: AdminProcessExecutionSummary[];
total: number;
page: number;
page_size: number;
}
export interface AdminProcessExecutionDetail extends ShippingProcessGateUserSummary {
current_gate?: Record<string, unknown> | null;
current_blocking_gate?: ShippingProcessGateUserSummary['current_blocking_gate'];
gates?: Array<Record<string, unknown>>;
lock_version?: number;
workflow_item_id?: number;
workflow_item_version_id?: number;
review_case_id?: number | null;
task_id?: number | null;
}
export interface AdminProcessGateAttemptsPayload {
gate: Record<string, unknown>;
/** 后端契约主字段 */
items?: Array<Record<string, unknown>>;
/** 与 items 同义的前端兼容别名 */
attempts?: Array<Record<string, unknown>>;
}
/**
* 读取 Execution 工作台投影。
* @param executionNo - Execution 编号
*/
export async function getWorkspaceProcessExecution(
executionNo: string,
): Promise<ShippingProcessGateUserSummary> {
return requestJson<ShippingProcessGateUserSummary>(`${WORKSPACE_BASE}/${encodeURIComponent(executionNo)}`);
}
/**
* 提交门禁恢复动作。
* @param executionNo - Execution 编号
* @param gateCode - 目标 gate_code
* @param body - 契约内动作请求体
*/
export async function postWorkspaceProcessGateAction(
executionNo: string,
gateCode: string,
body: ShippingProcessGateActionRequest,
): Promise<ShippingProcessGateActionResponse> {
return requestJson<ShippingProcessGateActionResponse>(
`${WORKSPACE_BASE}/${encodeURIComponent(executionNo)}/gates/${encodeURIComponent(gateCode)}/actions`,
{
method: 'POST',
body: JSON.stringify(body),
},
);
}
/**
* 分页读取 Admin Execution 摘要列表(支持 Gate/原因/责任方/时间/关键字筛选)。
*/
export async function listAdminProcessExecutions(
page = 1,
pageSize = 25,
filters: AdminProcessExecutionListFilters | string = {},
): Promise<AdminProcessExecutionListPage> {
const normalized: AdminProcessExecutionListFilters =
typeof filters === 'string' ? { status: filters } : (filters || {});
const params = new URLSearchParams({
page: String(page),
page_size: String(pageSize),
});
(Object.entries(normalized) as Array<[keyof AdminProcessExecutionListFilters, string | undefined]>).forEach(
([key, value]) => {
const text = String(value || '').trim();
if (text) params.set(key, text);
},
);
return requestJson<AdminProcessExecutionListPage>(`${ADMIN_BASE}?${params.toString()}`);
}
/**
* 读取 Admin Execution 完整诊断投影。
*/
export async function getAdminProcessExecution(
executionNo: string,
): Promise<AdminProcessExecutionDetail> {
return requestJson<AdminProcessExecutionDetail>(`${ADMIN_BASE}/${encodeURIComponent(executionNo)}`);
}
/**
* 读取指定 Gate 的全部 Attempt 摘要。
*/
export async function listAdminProcessGateAttempts(
executionNo: string,
gateCode: string,
): Promise<AdminProcessGateAttemptsPayload> {
return requestJson<AdminProcessGateAttemptsPayload>(
`${ADMIN_BASE}/${encodeURIComponent(executionNo)}/gates/${encodeURIComponent(gateCode)}/attempts`,
);
}
/**
* 分页读取 Execution 关联 PROCESS_GATE 审计事件。
* @param executionNo - Execution 编号
* @param page - 页码
* @param pageSize - 每页条数
*/
export async function listWorkspaceProcessGateAuditEvents(
executionNo: string,
page = 1,
pageSize = 50,
): Promise<ShippingProcessGateAuditEventsPage> {
const params = new URLSearchParams({
page: String(page),
page_size: String(pageSize),
});
return requestJson<ShippingProcessGateAuditEventsPage>(
`${WORKSPACE_BASE}/${encodeURIComponent(executionNo)}/audit-events?${params.toString()}`,
);
}
@@ -0,0 +1,53 @@
/**
* features/shipping-process-gates/components/ProcessGateRecoveryCard.spec.ts
* 用途:验证待处理事项卡片不展示未知内部编号和技术诊断文本。
* 依赖:Vitest、Vue Test Utils、vue-i18n。
* 逻辑:构造未知环节、动作及技术自由文本,断言全部回退为业务文案。
*/
import { mount } from '@vue/test-utils';
import { createI18n } from 'vue-i18n';
import { describe, expect, it } from 'vitest';
import workspaceZhCn from '@/locales/zh-CN/workspace.json';
import ProcessGateRecoveryCard from './ProcessGateRecoveryCard.vue';
import type { ShippingProcessGateUserSummary } from '../types/process-gate.types';
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',
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',
};
const wrapper = mount(ProcessGateRecoveryCard, {
props: { summary, canHandle: true },
global: { plugins: [i18n] },
});
const text = wrapper.text();
expect(text).toContain('当前处理环节');
expect(text).toContain('当前步骤');
expect(text).toContain('继续处理');
expect(text).toContain('当前步骤需要人工处理');
for (const technicalText of [
'auto_build_gate_quality_gate_passed', 'quality_gate_internal', 'internal_reason_code',
'internal_retry_action', 'HTTP 500', 'node_id', 'traceback', 'worker.py',
]) {
expect(text).not.toContain(technicalText);
}
});
});
@@ -0,0 +1,138 @@
/**
* features/shipping-process-gates/components/ProcessGateRecoveryCard.vue
* 用途:任务工作台展示当前待处理环节与服务端下发的主要处理按钮。
* 依赖:useShippingProcessGateRecovery、processGateNavigation、ShippingProcessGateUserSummary。
* 逻辑:导航类动作 router.push;POST 类动作调 Workspace API;409 触发 refreshed;
* canHandle=false 时只读;禁止展示内部编号、原因码和技术诊断文本。
*/
<script setup lang="ts">
import { computed } from 'vue';
import { useI18n } from 'vue-i18n';
import { useShippingProcessGateRecovery } from '../composables/useShippingProcessGateRecovery';
import type { ProcessGateNavigationContext } from '../composables/processGateNavigation';
import type { ShippingProcessGateUserSummary } from '../types/process-gate.types';
const props = defineProps<{
summary: ShippingProcessGateUserSummary | null | undefined;
canHandle: boolean;
navigationContext?: ProcessGateNavigationContext;
}>();
const emit = defineEmits<{
refreshed: [];
refreshNeeded: [];
navigate: [];
}>();
const { t, te } = useI18n();
const { busy, submitPrimaryAction } = useShippingProcessGateRecovery();
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));
/** 仅允许自然语言业务说明进入界面,内部标识、路径和异常信息统一隐藏。 */
function safeBusinessText(value: unknown): string {
const text = String(value || '').trim();
if (!text) return '';
const technicalPatterns = [
/\b(?:workflow|schema|gate|node|traceback|exception|stack|sql|http|api|json)\b/i,
/\b[a-z][a-z0-9]*_[a-z0-9_]+\b/i,
/(?:^|\s)(?:[A-Z]:\\|\/[^\s]+\/[^\s]+)/,
/(?:status|error|reason|code)\s*[:=]/i,
/^(?:\{|\[)|(?:\}|\])$/,
];
return technicalPatterns.some((pattern) => pattern.test(text)) ? '' : text;
}
const gateLabel = computed(() =>
safeBusinessText(blockingGate.value?.label)
|| t('workspace.shippingNotice.processGate.unknownStep'),
);
const actionLabel = computed(() => {
const code = nextActionCode.value;
if (!code) return '';
const key = `workspace.shippingNotice.processGate.actionCodes.${code}`;
return te(key) ? t(key) : t('workspace.shippingNotice.processGate.continueAction');
});
/**
* 用户可见阻断说明:优先 blocking_message,其次 i18n 原因码,禁止展示原始 code。
*/
const blockingReasonLabel = computed(() => {
const message = safeBusinessText(props.summary?.blocking_message);
if (message) return message;
const code = String(
props.summary?.blocking_reason_code
|| blockingGate.value?.blocking_reason_code
|| '',
).trim();
if (!code) return '';
const key = `workspace.shippingNotice.processGate.reasons.${code}`;
return te(key) ? t(key) : t('workspace.shippingNotice.processGate.genericBlocking');
});
const diagnosticHint = computed(() => safeBusinessText(props.summary?.diagnostic_hint));
/**
* 触发恢复动作:导航 / 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 === 'navigated') {
emit('navigate');
return;
}
if (result.outcome === 'submitted') {
emit('refreshed');
return;
}
if (result.outcome === 'refresh_needed') {
emit('refreshNeeded');
emit('refreshed');
}
}
</script>
<template>
<section
v-if="summary && blockingGate"
class="rounded-2xl border border-amber-200/80 bg-amber-50/60 px-4 py-3 dark:border-amber-900/50 dark:bg-amber-950/20"
>
<div class="mb-2 text-xs font-semibold uppercase tracking-wide text-amber-800 dark:text-amber-200">
{{ $t('workspace.shippingNotice.processGate.title') }}
</div>
<dl class="grid gap-2 text-sm">
<div>
<dt class="text-muted">{{ $t('workspace.shippingNotice.processGate.currentGate') }}</dt>
<dd class="font-medium text-secondary">{{ gateLabel }}</dd>
</div>
<div v-if="blockingReasonLabel">
<dt class="text-muted">{{ $t('workspace.shippingNotice.processGate.blockingMessage') }}</dt>
<dd class="text-secondary">{{ blockingReasonLabel }}</dd>
</div>
<div v-if="diagnosticHint">
<dt class="text-muted">{{ $t('workspace.shippingNotice.processGate.diagnosticHint') }}</dt>
<dd class="text-secondary">{{ diagnosticHint }}</dd>
</div>
</dl>
<div v-if="hasRecoveryAction" class="mt-3 flex flex-wrap items-center 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"
:disabled="!canHandle || busy"
@click="runPrimaryAction"
>
{{ busy ? $t('workspace.shippingNotice.processGate.submitting') : actionLabel }}
</button>
<span v-if="!canHandle" class="text-xs text-muted">
{{ $t('workspace.shippingNotice.todo.adminViewOnlyShort') }}
</span>
</div>
</section>
</template>
@@ -0,0 +1,78 @@
/**
* features/shipping-process-gates/composables/processGateNavigation.ts
* 用途:将服务端下发的门禁恢复动作映射为 Vue Router 深链(复核台 / 任务工作台)。
* 依赖:process-gate.types、vue-router RouteLocationRaw。
* 逻辑:与 process_gate_projection.navigation 对齐;禁止本地发明 action_code。
*/
import type { RouteLocationRaw } from 'vue-router';
import type { ShippingProcessGateUserSummary } from '../types/process-gate.types';
/** 点击后仅导航、不 POST 的人工入口动作(regenerate_manual_upload_todo 除外)。 */
export const PROCESS_GATE_NAVIGATION_ACTIONS = new Set<string>([
'open_order_review',
'open_inventory_source_review',
'open_profile_review',
'edit_order_fields',
'edit_reservation',
'confirm_customer',
'adjudicate_duplicate',
'resolve_field_conflicts',
'open_inventory_match_review',
'open_shortage_review',
'upload_inventory_file',
'confirm_inventory_field_mapping',
]);
export interface ProcessGateNavigationContext {
agentId?: string;
conversationId?: string;
preserveQuery?: Record<string, string>;
}
/**
* 判断动作码是否属于前端导航类恢复动作。
*/
export function isProcessGateNavigationAction(actionCode: string): boolean {
return PROCESS_GATE_NAVIGATION_ACTIONS.has(String(actionCode || '').trim());
}
/**
* 根据 Gate 摘要与动作码构建 router 目标。
* 核心逻辑:优先 summary.navigation;缺省时回退 review_run_no / case_no / task_no。
* @returns 可 push 的路由;缺关键编号时 null
*/
export function buildProcessGateNavigationRoute(
summary: ShippingProcessGateUserSummary,
actionCode: string,
context: ProcessGateNavigationContext = {},
): RouteLocationRaw | null {
const code = String(actionCode || '').trim();
if (!isProcessGateNavigationAction(code)) return null;
const nav = summary.navigation;
const runNo = String(nav?.run_no || summary.review_run_no || '').trim();
const caseNo = String(nav?.case_no || summary.review_case_no || summary.case_no || '').trim();
const taskNo = String(nav?.task_no || summary.task_no || '').trim();
const focus = String(nav?.focus || 'draft').trim();
if (nav?.target === 'task_workspace' || code === 'upload_inventory_file') {
if (!taskNo) return null;
return { name: 'workspace-shipping-tasks', params: { taskNo } };
}
if (!runNo) return null;
const query: Record<string, string> = {
...(context.preserveQuery || {}),
mode: 'order-review',
run_no: runNo,
};
if (caseNo) query.case = caseNo;
if (focus) query.focus = focus;
if (context.conversationId) query.conversation_id = context.conversationId;
if (!context.agentId) return null;
return {
name: 'Chat',
params: { agentId: context.agentId },
query,
};
}
@@ -0,0 +1,132 @@
/**
* features/shipping-process-gates/composables/useShippingProcessGateRecovery.ts
* 用途:任务工作台门禁恢复动作编排(导航、幂等键、版本锁、409 刷新)。
* 依赖:process-gates.api、processGateNavigation、process-gate.types、useMessage。
* 逻辑:ProcessGateRecoveryCard 调用 submitPrimaryAction;禁止本地发明 action_code。
*/
import { ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { useRouter } from 'vue-router';
import { BusinessError, resolveLocalizedErrorMessage } from '@/shared/api/client';
import { useMessage } from '@/shared/composables/useMessage';
import { postWorkspaceProcessGateAction } from '../api/process-gates.api';
import type {
ShippingProcessGateActionCode,
ShippingProcessGateUserSummary,
} from '../types/process-gate.types';
import {
buildProcessGateNavigationRoute,
isProcessGateNavigationAction,
type ProcessGateNavigationContext,
} from './processGateNavigation';
export type ProcessGateActionOutcome =
| 'submitted'
| 'navigated'
| 'refresh_needed'
| 'failed'
| 'noop';
export interface ProcessGateActionResult {
outcome: ProcessGateActionOutcome;
}
function newIdempotencyKey(): string {
if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {
return crypto.randomUUID();
}
return `pg-${Date.now()}-${Math.random().toString(16).slice(2)}`;
}
/**
* 编排单次门禁恢复:导航类动作直接 router.push;其余 POST 到 Workspace API。
* @returns busy 状态与 submitPrimaryAction 方法
*/
export function useShippingProcessGateRecovery() {
const { t } = useI18n();
const msg = useMessage();
const router = useRouter();
const busy = ref(false);
/**
* 提交或导航当前阻断 Gate 的主要恢复动作。
* 核心逻辑:evaluation_version 来自 current_blocking_gate;409 返回 refresh_needed。
*/
async function submitPrimaryAction(
summary: ShippingProcessGateUserSummary,
options?: {
payload?: Record<string, unknown>;
navigationContext?: ProcessGateNavigationContext;
},
): Promise<ProcessGateActionResult> {
const gate = summary.current_blocking_gate;
const actionCode = (summary.next_action_code || gate?.next_action_code || '') as ShippingProcessGateActionCode | '';
if (!summary.execution_no || !gate?.gate_code || !actionCode) {
msg.warning(t('workspace.shippingNotice.processGate.noAction'));
return { outcome: 'noop' };
}
if (isProcessGateNavigationAction(actionCode)) {
const route = buildProcessGateNavigationRoute(
summary,
actionCode,
options?.navigationContext || {},
);
if (!route) {
msg.warning(t('workspace.shippingNotice.processGate.navigationMissing'));
return { outcome: 'failed' };
}
busy.value = true;
try {
await router.push(route);
return { outcome: 'navigated' };
} catch {
msg.warning(t('workspace.shippingNotice.actions.failed'));
return { outcome: 'failed' };
} finally {
busy.value = false;
}
}
const expectedVersion = Number(gate.evaluation_version);
if (!Number.isFinite(expectedVersion) || expectedVersion < 1) {
msg.warning(t('workspace.shippingNotice.processGate.versionMissing'));
return { outcome: 'failed' };
}
busy.value = true;
try {
await postWorkspaceProcessGateAction(summary.execution_no, String(gate.gate_code), {
action_code: actionCode,
expected_gate_version: expectedVersion,
idempotency_key: newIdempotencyKey(),
payload: options?.payload,
});
msg.success(t('workspace.shippingNotice.processGate.actionSubmitted'));
return { outcome: 'submitted' };
} catch (error: unknown) {
const isVersionMismatch = error instanceof BusinessError && (
error.code === 'SHIPPING.PROCESS_GATE_VERSION_MISMATCH'
|| error.status === 409
);
if (isVersionMismatch) {
msg.warning(resolveLocalizedErrorMessage(
'SHIPPING.PROCESS_GATE_VERSION_MISMATCH',
error instanceof BusinessError ? error.message : undefined,
));
return { outcome: 'refresh_needed' };
}
const message = error instanceof BusinessError
? resolveLocalizedErrorMessage(error.code, error.message)
: (error instanceof Error ? error.message : t('workspace.shippingNotice.actions.failed'));
msg.warning(message);
return { outcome: 'failed' };
} finally {
busy.value = false;
}
}
return {
busy,
submitPrimaryAction,
};
}
@@ -0,0 +1,52 @@
/**
* 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 专用响应在此扩展。
*/
import type {
ShippingProcessGateActionCode,
ShippingProcessGateCode,
ShippingProcessGateProjection,
ShippingProcessGateStatus,
ShippingProcessGateUserSummary,
} from '@/features/chat/types/shipping.api.types';
export type {
ShippingProcessGateActionCode,
ShippingProcessGateCode,
ShippingProcessGateProjection,
ShippingProcessGateStatus,
ShippingProcessGateUserSummary,
};
export interface ShippingProcessGateActionRequest {
action_code: ShippingProcessGateActionCode | string;
expected_gate_version: number;
idempotency_key: string;
payload?: Record<string, unknown>;
}
export interface ShippingProcessGateActionResponse {
execution_no: string;
gate_code: ShippingProcessGateCode | string;
action_code: ShippingProcessGateActionCode | string;
dispatch: 'sync' | 'async_job' | 'idempotent_replay' | string;
attempt: {
id: number;
attempt_no: number;
status: string;
idempotency_key: string;
};
gate_status?: string;
gate_evaluation_version?: number;
next_action_code?: ShippingProcessGateActionCode | string | null;
job_id?: number;
}
export interface ShippingProcessGateAuditEventsPage {
items: Array<Record<string, unknown>>;
total: number;
page: number;
page_size: number;
}
@@ -28,7 +28,7 @@ const emit = defineEmits<{
refreshed: [];
}>();
const { t } = useI18n();
const { t, te } = useI18n();
const msg = useMessage();
const workflowSteps = computed(() => resolveShippingWorkflowSteps(props.detail));
@@ -42,11 +42,32 @@ const workflowItem = computed(() => props.detail.workflow_item || null);
const workflowEvents = computed(() => workflowItem.value?.events || []);
const stpFacts = computed(() => props.detail.ui_state?.summary?.stp_facts || null);
const lastActivityAt = computed(() => workflowItem.value?.last_activity_at || props.detail.updated_at || null);
const terminateReason = computed(() => workflowItem.value?.closed_reason || null);
const terminateReason = computed(() => {
const code = String(workflowItem.value?.closed_reason || '').trim();
if (!code) return null;
const key = `workspace.shippingNotice.workflowReasons.${code}`;
return te(key) ? t(key) : t('workspace.shippingNotice.timeline.updated');
});
const hasExcelArtifact = computed(() =>
Array.isArray(props.detail.export_artifacts) && props.detail.export_artifacts.length > 0,
);
/** 将内部状态映射为业务文案,未知值不回显原始状态码。 */
function workflowStatusLabel(value: unknown): string {
const code = String(value || '').trim();
if (!code) return t('workspace.shippingNotice.status.unknown');
const key = `workspace.shippingNotice.workflowStatus.${code}`;
return te(key) ? t(key) : t('workspace.shippingNotice.status.unknown');
}
const taskStatusLabel = computed(() => workflowStatusLabel(props.detail.process_status));
const taskMatchStatusLabel = computed(() => {
const code = String(props.detail.match_status || '').trim();
if (!code) return t('workspace.shippingNotice.matchStatus.unknown');
const key = `workspace.shippingNotice.matchStatus.${code}`;
return te(key) ? t(key) : t('workspace.shippingNotice.matchStatus.unknown');
});
/**
* 下载已生成的发货 Excel。
*/
@@ -84,8 +105,8 @@ async function downloadExcel() {
</div>
<div v-if="workflowItem" class="sm:col-span-2">
<dt class="text-muted">{{ $t('workspace.shippingNotice.todo.workflowItem') }}</dt>
<dd class="font-mono text-secondary">
{{ workflowItem.item_no }} · {{ workflowItem.lifecycle_status }} · {{ workflowItem.current_stage }}
<dd class="text-secondary">
{{ workflowStatusLabel(workflowItem.lifecycle_status) }} · {{ workflowStatusLabel(workflowItem.current_stage) }}
</dd>
</div>
</dl>
@@ -109,11 +130,11 @@ async function downloadExcel() {
<dl class="grid gap-3 text-sm sm:grid-cols-2">
<div>
<dt class="text-muted">{{ $t('workspace.shippingNotice.fields.status') }}</dt>
<dd>{{ detail.process_status || '—' }}</dd>
<dd>{{ taskStatusLabel }}</dd>
</div>
<div>
<dt class="text-muted">{{ $t('workspace.shippingNotice.fields.match') }}</dt>
<dd>{{ detail.match_status || '—' }}</dd>
<dd>{{ taskMatchStatusLabel }}</dd>
</div>
<div>
<dt class="text-muted">{{ $t('workspace.shippingNotice.fields.shipTo') }}</dt>
@@ -2,7 +2,7 @@
* features/workspace/shipping-task-center/TaskProgressTimeline.spec.ts
* 用途:锁定任务中心时间线同时消费 Task Event 与 Workflow Event。
* 依赖:Vitest、@vue/test-utils、TaskProgressTimeline。
* 逻辑:合并排序后两类事件均可见;Workflow 操作人展示 type/id。
* 逻辑:合并排序后两类事件均可见;未知内部码、操作人 ID 与 JSON 详情不展示。
*/
import { describe, expect, it } from 'vitest';
import { mount } from '@vue/test-utils';
@@ -21,8 +21,10 @@ const messages = {
empty: '暂无事件记录',
detail: '查看详情',
sourceTask: '任务事件',
sourceWorkflow: 'Workflow 事件',
workflowEvent: 'Workflow 事件',
sourceWorkflow: '文件处理记录',
workflowEvent: '文件处理记录',
updated: '处理状态已更新',
actors: { user: '业务人员', system: '系统' },
},
},
},
@@ -51,10 +53,40 @@ describe('TaskProgressTimeline', () => {
});
// 关键断言:时间线同时展示 Task 与 Workflow 事件来源标签,且 Workflow 显示操作人。
expect(wrapper.text()).toContain('任务事件');
expect(wrapper.text()).toContain('Workflow 事件');
expect(wrapper.text()).toContain('文件处理记录');
expect(wrapper.text()).toContain('任务已创建');
expect(wrapper.text()).toContain('人工上传已登记');
expect(wrapper.text()).toContain('操作者 1');
expect(wrapper.text()).toContain('操作者 user/42');
expect(wrapper.text()).toContain('操作者 业务人员');
expect(wrapper.text()).not.toContain('user/42');
expect(wrapper.text()).not.toContain('操作者 1');
});
it('does not expose unknown event codes or raw detail JSON', () => {
const i18n = createI18n({ legacy: false, locale: 'zh-CN', messages });
const wrapper = mount(TaskProgressTimeline, {
props: {
events: [{
event_type: 'internal_task_event',
actor_id: 99,
detail_json: { node_id: 'node-1', error: 'HTTP 500' },
}],
workflowEvents: [{
seq_no: 2,
event_code: 'internal_workflow_event',
actor_type: 'worker',
actor_id: 'worker-7',
payload: { gate_code: 'quality_gate_internal' },
}],
},
global: { plugins: [i18n] },
});
const text = wrapper.text();
expect(text).toContain('处理状态已更新');
for (const technicalText of [
'internal_task_event', 'internal_workflow_event', 'node_id', 'HTTP 500',
'gate_code', 'quality_gate_internal', 'worker-7',
]) {
expect(text).not.toContain(technicalText);
}
});
});
@@ -3,7 +3,7 @@
* 用途:展示任务事件 + Workflow Event 统一时间线(只读),不发明进度百分比。
* 依赖:ShippingTaskEvent、ShippingWorkflowEvent、dateTime、vue-i18n。
* 逻辑:由 ShippingTaskWorkbench 传入 task events 与 workflow events;按时间合并排序;
* Workflow 事件操作人展示为 actor_type/actor_id。
* 未知事件与操作者内部标识统一使用通用业务文案。
*/
<script setup lang="ts">
import { computed } from 'vue';
@@ -23,18 +23,17 @@ type TimelineRow = {
label: string;
createdAt?: string | null;
actor?: string | null;
detail?: Record<string, unknown> | null;
source: 'task' | 'workflow';
};
/**
* 将任务事件类型映射为可读文案;契约外码原样展示。
* 将任务事件类型映射为可读文案;契约外码使用通用说明。
*/
function taskEventLabel(eventType: string | null | undefined): string {
const code = String(eventType || '').trim();
if (!code) return t('workspace.shippingNotice.eventTypes.system');
const key = `workspace.shippingNotice.eventTypes.${code}`;
return te(key) ? t(key) : code;
return te(key) ? t(key) : t('workspace.shippingNotice.timeline.updated');
}
/**
@@ -44,20 +43,20 @@ function workflowEventLabel(event: ShippingWorkflowEvent): string {
const code = String(event.event_code || event.message_code || event.stage_code || '').trim();
if (!code) return t('workspace.shippingNotice.timeline.workflowEvent');
const key = `workspace.shippingNotice.workflowEvents.${code}`;
return te(key) ? t(key) : code;
return te(key) ? t(key) : t('workspace.shippingNotice.timeline.updated');
}
/**
* 格式化操作人展示:优先 type/id,便于审计追溯。
* 格式化操作人展示:普通工作台只显示业务角色,不展示内部 ID。
* @param actorType - 角色(user/system/admin…)
* @param actorId - 操作者 ID 或系统标识
*/
function formatActorLabel(actorType?: string | null, actorId?: string | number | null): string | null {
const type = String(actorType || '').trim();
const id = actorId == null ? '' : String(actorId).trim();
if (type && id) return `${type}/${id}`;
if (id) return id;
if (type) return type;
const roleKey = `workspace.shippingNotice.timeline.actors.${type}`;
if (type && te(roleKey)) return t(roleKey);
if (type || id) return t('workspace.shippingNotice.timeline.actors.user');
return null;
}
@@ -67,7 +66,6 @@ const rows = computed<TimelineRow[]>(() => {
label: taskEventLabel(event.event_type),
createdAt: event.created_at,
actor: formatActorLabel(null, event.actor_id),
detail: event.detail_json || null,
source: 'task',
}));
const workflowRows: TimelineRow[] = (props.workflowEvents || []).map((event, index) => ({
@@ -75,11 +73,6 @@ const rows = computed<TimelineRow[]>(() => {
label: workflowEventLabel(event),
createdAt: event.occurred_at,
actor: formatActorLabel(event.actor_type, event.actor_id),
detail: {
...(event.payload || {}),
...(event.reason ? { reason: event.reason } : {}),
...(event.stage_code ? { stage_code: event.stage_code } : {}),
},
source: 'workflow',
}));
return [...taskRows, ...workflowRows].sort((a, b) => {
@@ -116,13 +109,6 @@ const rows = computed<TimelineRow[]>(() => {
<span class="text-muted">{{ formatLocalDateTime(row.createdAt) }}</span>
<span v-if="row.actor" class="text-muted">{{ $t('workspace.shippingNotice.operator', { id: row.actor }) }}</span>
</div>
<details
v-if="row.detail && Object.keys(row.detail).length"
class="mt-1 text-xs text-muted"
>
<summary class="cursor-pointer select-none">{{ $t('workspace.shippingNotice.timeline.detail') }}</summary>
<pre class="mt-1 whitespace-pre-wrap break-words">{{ JSON.stringify(row.detail, null, 2) }}</pre>
</details>
</div>
</section>
</template>
@@ -1,10 +1,10 @@
/**
* features/workspace/shipping-task-center/TaskTodoPanel.vue
* 用途:仅渲染后端 ui_state.action_buttons / summary.allowed_actions 对应的当前待办动作。
* 依赖:shipping.api 履约写接口、shipping-tasks.api 下载/人工上传、ManualUploadEvidenceDialog、各确认对话框。
* 逻辑:禁止按 process_status 二次推导按钮;管理员 can_handle=false 时只读;
* wait_manual_upload 允许下载 Excel + 登记人工上传凭据(禁 RPA);
* 多源阻断时对话框候选强制取 stp_facts.recovery_source_codes,禁止展示冻结全集。
* 用途:渲染统一 Gate 恢复卡片与 STP 履约待办动作(ui_state.action_buttons)。
* 依赖: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 + 人工上传凭据。
*/
<script setup lang="ts">
import { computed, ref } from 'vue';
@@ -32,6 +32,8 @@ import { downloadWorkspaceShippingExcelFile } from '@/features/workspace/api/shi
import { refreshShippingTodoBadge } from '@/features/workspace/composables/useShippingTodoBadge';
import InventorySourceSelectDialog from './InventorySourceSelectDialog.vue';
import ManualUploadEvidenceDialog from './ManualUploadEvidenceDialog.vue';
import ProcessGateRecoveryCard from '@/features/shipping-process-gates/components/ProcessGateRecoveryCard.vue';
import type { ShippingProcessGateUserSummary } from '@/features/chat/types/shipping.api.types';
const props = defineProps<{
detail: ShippingTaskDetail;
@@ -56,9 +58,34 @@ const inventorySourceCandidates = ref<ShippingInventorySourceCandidate[]>([]);
const inventorySourceInitialCode = ref('');
const summary = computed(() => props.detail.ui_state?.summary || {});
const processGateSummary = computed((): ShippingProcessGateUserSummary | null =>
props.detail.ui_state?.process_gate
|| (summary.value.process_gate as ShippingProcessGateUserSummary | null | undefined)
|| null,
);
const actionButtons = computed(() => props.detail.ui_state?.action_buttons || []);
const checkpointKind = computed(() => String(props.detail.ui_state?.checkpoint_kind || ''));
const checkpoint = computed(() => String(props.detail.ui_state?.checkpoint || ''));
/** 统一 Gate 投影中的主要恢复动作;用于去重旧 action_buttons。 */
const processGateNextAction = computed(() =>
String(
processGateSummary.value?.next_action_code
|| processGateSummary.value?.current_blocking_gate?.next_action_code
|| '',
).trim(),
);
/** 有 Gate 阻断时优先展示统一投影文案。 */
const displayTodoTitle = computed(() =>
processGateSummary.value?.current_blocking_gate?.label
|| summary.value.current_todo
|| summary.value.title
|| t('workspace.shippingNotice.todo.noActionTitle'),
);
const displayTodoMessage = computed(() =>
processGateSummary.value?.blocking_message
|| summary.value.message
|| t('workspace.shippingNotice.todo.noActionMessage'),
);
/**
* 是否展示「待人工上传登记」提示。
@@ -117,12 +144,22 @@ const allowedIds = computed(() => {
if (Array.isArray(fromSummary) && fromSummary.length) return new Set(fromSummary.map(String));
return new Set(actionButtons.value.map((item) => item.id));
});
const visibleActions = computed(() =>
actionButtons.value.filter((action) => {
const hasBlockingGate = computed(() => Boolean(processGateSummary.value?.current_blocking_gate));
const visibleActions = computed(() => {
// [STEP] Gate 阻断时后端已清零 action_buttons;前端再兜底隐藏,避免双真相。
if (hasBlockingGate.value) return [];
return actionButtons.value.filter((action) => {
const id = String(action.id || '');
return allowedIds.value.has(id) && isActionAllowedForCheckpoint(id, checkpointKind.value);
}),
);
if (!allowedIds.value.has(id) || !isActionAllowedForCheckpoint(id, checkpointKind.value)) {
return false;
}
if (processGateNextAction.value && id === processGateNextAction.value) {
return false;
}
return true;
});
});
/**
* 动作成功后刷新详情并更新导航徽标。
*/
@@ -327,15 +364,29 @@ async function runAction(action: ShippingChatAction) {
}
</script>
<template>
<section class="rounded-2xl border border-brand-200/80 bg-brand-50/40 px-4 py-3">
<div class="space-y-3">
<ProcessGateRecoveryCard
:summary="processGateSummary"
:can-handle="canHandle"
:navigation-context="{
agentId: detail.owner_agent_id != null ? String(detail.owner_agent_id) : undefined,
conversationId: detail.conversation_id || undefined,
}"
@refreshed="afterSuccess"
@refresh-needed="afterSuccess"
/>
<section
v-if="!hasBlockingGate"
class="rounded-2xl border border-brand-200/80 bg-brand-50/40 px-4 py-3"
>
<div class="mb-1 text-xs font-semibold uppercase tracking-wide text-brand-700">
{{ $t('workspace.shippingNotice.todo.currentTodo') }}
</div>
<h3 class="text-sm font-semibold text-primary">
{{ summary.current_todo || summary.title || $t('workspace.shippingNotice.todo.noActionTitle') }}
{{ displayTodoTitle }}
</h3>
<p class="mt-1 text-sm text-secondary">
{{ summary.message || $t('workspace.shippingNotice.todo.noActionMessage') }}
{{ displayTodoMessage }}
</p>
<p v-if="summary.pause_reason" class="mt-1 text-xs text-amber-700">
{{ summary.pause_reason }}
@@ -398,5 +449,6 @@ async function runAction(action: ShippingChatAction) {
@confirm="onFreezeConfirm"
/>
</section>
</div>
</template>