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

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

No files matched your search

@@ -7,13 +7,14 @@
* 依赖:ChatSidebar、ChatMessageList、ChatInputBar、ShippingWorkflowTimeline、chat.context。
* 逻辑:本文件只做页面结构编排;货代 Chat 仅上传/进度通知,履约写操作不在本页;
* 右侧「本次处理」由 conversationId 驱动 Workflow projection,extractionRunNo 仅作进度装饰。
* 右侧「本次处理」由 conversationId 驱动 Workflow projection,extractionRunNo 仅作进度装饰;
* 订单复核工作台异步分包,避免普通对话首屏拉取 PDF.js。
*/
<script setup lang="ts">
import { computed, provide, ref, watch } from 'vue';
import { computed, defineAsyncComponent, provide, ref, watch } from 'vue';
import { useRoute } from 'vue-router';
@@ -39,8 +40,6 @@ import LedgerConfigPanel from '@/features/maintenance/components/LedgerConfigPan
import MaintenanceRecordManagerPanel from '@/features/maintenance/components/MaintenanceRecordManagerPanel.vue';
import ShippingOrderReviewView from '@/features/chat/views/ShippingOrderReviewView.vue';
import { useChatPageContext } from '@/features/chat/composables/chat.context';
import { matchesTrainingAgent } from '@/features/chat/training/trainingWorkspace.utils';
@@ -66,7 +65,10 @@ import {
} from '@/features/maintenance/utils/maintenance-panel-layout.utils';
/** 复核工作台按需分包:仅 order-review 模式加载,避免 Chat 首屏带上 PDF.js。 */
const ShippingOrderReviewView = defineAsyncComponent(
() => import('@/features/chat/views/ShippingOrderReviewView.vue'),
);
type MaintenanceRecordPanelCommand = {
@@ -0,0 +1,124 @@
<!--
features/chat/components/shipping-review/ReviewBuildEligibilityDetailsDrawer.vue
用途:完整建单检查项抽屉(逐行投影、阻断原因)。
依赖:vue-i18n、ShippingOrderReviewBuildEligibility。
逻辑:仅在用户主动展开时挂载;关闭不写服务端审计(敏感访问审计由阶段 5 统一补齐)。
-->
<script setup lang="ts">
import { computed } from 'vue';
import { useI18n } from 'vue-i18n';
import type { ShippingOrderReviewBuildEligibility } from '@/features/chat/types/shipping.api.types';
const props = defineProps<{
open: boolean;
eligibility: ShippingOrderReviewBuildEligibility | null;
}>();
const emit = defineEmits<{
close: [];
'focus-line': [lineIndex: number];
}>();
const { t, te } = useI18n();
/**
* 解析行级阻断原因文案。
*/
function blockReasonLabel(reason?: string | null): string {
const normalized = String(reason || '').trim();
if (!normalized) return '—';
const key = `chat.shippingOrderReview.buildEligibility.blockReasons.${normalized}`;
return te(key) ? t(key) : t('chat.shippingOrderReview.buildEligibility.blockReasons.unknown');
}
/**
* 解析路由状态文案。
*/
function routingStatusLabel(status?: string | null): string {
const normalized = String(status || '').trim();
if (!normalized) return '—';
const key = `chat.shippingOrderReview.buildEligibility.routingStatus.${normalized}`;
return te(key) ? t(key) : t('chat.shippingOrderReview.buildEligibility.routingStatus.unknown');
}
/** 异常行置顶,已通过行排后。 */
const orderedLines = computed(() => {
const lines = [...(props.eligibility?.line_projections || [])];
return lines.sort((a, b) => {
const aBlocked = a.can_build === false ? 0 : 1;
const bBlocked = b.can_build === false ? 0 : 1;
if (aBlocked !== bBlocked) return aBlocked - bBlocked;
return (a.line_index ?? 0) - (b.line_index ?? 0);
});
});
</script>
<template>
<div
v-if="open && eligibility"
class="fixed inset-0 z-40 flex justify-end bg-slate-900/30"
data-testid="review-eligibility-details-drawer"
@click.self="emit('close')"
>
<aside class="flex h-full w-full max-w-md flex-col bg-white shadow-xl dark:bg-slate-900">
<header class="flex items-center justify-between gap-2 border-b border-slate-200 px-4 py-3 dark:border-slate-800">
<h2 class="text-sm font-semibold">{{ t('chat.shippingOrderReview.workbench.fullChecksTitle') }}</h2>
<button
type="button"
class="rounded border border-slate-300 px-2 py-1 text-xs hover:bg-slate-50 dark:border-slate-600 dark:hover:bg-slate-800"
data-testid="review-eligibility-details-close"
@click="emit('close')"
>
{{ t('chat.shippingOrderReview.workbench.closePdf') }}
</button>
</header>
<div class="min-h-0 flex-1 space-y-2 overflow-y-auto p-4">
<article
v-for="line in orderedLines"
:key="String(line.line_key || line.line_index)"
class="rounded-lg border border-slate-200 p-3 text-xs dark:border-slate-700"
:data-testid="`review-eligibility-detail-line-${line.line_key || line.line_index}`"
>
<div class="flex flex-wrap items-center justify-between gap-2">
<button
type="button"
class="font-medium text-sky-700 hover:underline dark:text-sky-300"
@click="emit('focus-line', Number(line.line_index ?? 0))"
>
{{ t('chat.shippingOrderReview.line', { index: (line.line_index ?? 0) + 1 }) }}
</button>
<span
class="rounded-full px-2 py-0.5 text-[11px]"
:class="line.can_build
? 'bg-emerald-100 text-emerald-800 dark:bg-emerald-950 dark:text-emerald-100'
: 'bg-rose-100 text-rose-800 dark:bg-rose-950 dark:text-rose-100'"
>
{{
line.can_build
? t('chat.shippingOrderReview.buildEligibility.lineCanBuild')
: t('chat.shippingOrderReview.buildEligibility.lineBlocked')
}}
</span>
</div>
<dl class="mt-2 grid gap-1">
<div>
<dt class="inline text-slate-500">{{ t('chat.shippingOrderReview.buildEligibility.routingStatusLabel') }}:</dt>
<dd class="inline">{{ routingStatusLabel(line.routing_status) }}</dd>
</div>
<div v-if="line.block_reason">
<dt class="inline text-slate-500">{{ t('chat.shippingOrderReview.buildEligibility.blockReason') }}:</dt>
<dd class="inline">{{ blockReasonLabel(line.block_reason) }}</dd>
</div>
<div v-if="line.candidate_inventory_source_codes?.length">
<dt class="inline text-slate-500">{{ t('chat.shippingOrderReview.buildEligibility.candidates') }}:</dt>
<dd class="inline font-mono">{{ line.candidate_inventory_source_codes.join(', ') }}</dd>
</div>
</dl>
</article>
<p v-if="!orderedLines.length" class="text-xs text-slate-500">
{{ t('chat.shippingOrderReview.workbench.noLineChecks') }}
</p>
</div>
</aside>
</div>
</template>
@@ -1,8 +1,9 @@
<!--
features/chat/components/shipping-review/ReviewBuildEligibilityPanel.vue
用途:展示建单前资格摘要(can_build、阻断原因、行级 Reservation 与库存候选)及 Gate 恢复卡片。
用途:完整建单资格面板(含逐行投影);布局重构后标准侧栏改用 Summary + DetailsDrawer。
依赖:vue-i18n、ProcessGateRecoveryCard、ShippingOrderReviewBuildEligibility 类型。
逻辑:ShippingOrderReviewView 传入 draft.build_eligibility 与 case.process_gate;只读展示资格,Gate 动作可导航/POST。
逻辑:仍可供需要完整展开的入口复用;标准复核主路径不再默认挂载本组件;
confirm_customer 向上转发,由对话页打开客户选择弹窗。
-->
<script setup lang="ts">
import { computed } from 'vue';
@@ -23,6 +24,7 @@ const props = defineProps<{
const emit = defineEmits<{
gateRefreshed: [];
confirmCustomer: [taskNo: string];
}>();
const { t, te } = useI18n();
@@ -81,6 +83,7 @@ const blockingSummary = computed(() => {
:navigation-context="navigationContext"
@refreshed="emit('gateRefreshed')"
@refresh-needed="emit('gateRefreshed')"
@confirm-customer="(taskNo) => emit('confirmCustomer', taskNo)"
/>
<section
v-if="eligibility"
@@ -0,0 +1,69 @@
/**
* features/chat/components/shipping-review/ReviewBuildEligibilitySummary.spec.ts
* 用途:锁定建单资格摘要卡默认只展示阻断摘要、完整检查按需展开契约。
* 依赖:vitest、@vue/test-utils、vue-i18n。
* 逻辑:验证 badge、首要阻断与 open-details emit;不渲染逐行投影列表。
*/
import { describe, expect, it } from 'vitest';
import { mount } from '@vue/test-utils';
import { createI18n } from 'vue-i18n';
import ReviewBuildEligibilitySummary from './ReviewBuildEligibilitySummary.vue';
import type { ShippingOrderReviewBuildEligibility } from '@/features/chat/types/shipping.api.types';
/**
* 挂载摘要卡。
*/
function mountSummary(eligibility: ShippingOrderReviewBuildEligibility) {
const i18n = createI18n({
legacy: false,
locale: 'zh-CN',
messages: {
'zh-CN': {
chat: {
shippingOrderReview: {
issueCodes: { unknown: '未知问题' },
buildEligibility: {
title: '订单检查',
canBuildYes: '可建单',
canBuildNo: '待处理',
blockReasons: { require_manual_review: '需人工确认', unknown: '未知阻断' },
},
workbench: {
primaryBlock: '首要阻断原因',
blockCount: '阻断项 {count} 项',
viewFullChecks: '查看完整检查',
},
},
},
},
},
});
return mount(ReviewBuildEligibilitySummary, {
props: { eligibility },
global: { plugins: [i18n] },
});
}
describe('ReviewBuildEligibilitySummary', () => {
it('shows primary block and emits open-details without listing all lines', async () => {
const wrapper = mountSummary({
can_build: false,
status: 'blocked',
issues: [{
code: 'require_manual_review',
severity: 'blocking',
explainability: { message: '第 2 行库存来源待确认' },
}],
line_projections: [
{ line_key: 'L1', line_index: 0, can_build: true },
{ line_key: 'L2', line_index: 1, can_build: false, block_reason: 'require_manual_review' },
],
});
expect(wrapper.find('[data-testid="review-build-eligibility-summary"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="review-build-eligibility-badge"]').text()).toContain('待处理');
expect(wrapper.find('[data-testid="review-eligibility-primary-block"]').text()).toContain('第 2 行库存来源待确认');
expect(wrapper.text()).not.toContain('L1');
await wrapper.find('[data-testid="review-open-eligibility-details"]').trigger('click');
expect(wrapper.emitted('open-details')).toBeTruthy();
});
});
@@ -0,0 +1,146 @@
<!--
features/chat/components/shipping-review/ReviewBuildEligibilitySummary.vue
用途:复核摘要侧栏的建单资格压缩卡(可建单状态、门禁清单、首要阻断)。
依赖:vue-i18n、ShippingOrderReviewBuildEligibility。
逻辑:展示客户确认等关键门禁勾选;「查看完整检查」emit open-details;完整逐行结果不常驻。
-->
<script setup lang="ts">
import { computed } from 'vue';
import { useI18n } from 'vue-i18n';
import type { ShippingOrderReviewBuildEligibility } from '@/features/chat/types/shipping.api.types';
const props = defineProps<{
eligibility: ShippingOrderReviewBuildEligibility | null;
}>();
const emit = defineEmits<{
'open-details': [];
}>();
const { t, te } = useI18n();
/** 用户可见的关键建单前门禁(与后端 qualification gates 对齐)。 */
const CHECKLIST_GATES = [
'customer_confirmed',
'required_fields_complete',
'evidence_complete',
'duplicate_resolved',
'field_conflicts_resolved',
] as const;
/** 阻断 issue 数量(优先 blocking severity)。 */
const blockingIssueCount = computed(() => {
const issues = props.eligibility?.issues || [];
const blocking = issues.filter((item) => String(item.severity || '') === 'blocking');
return blocking.length || issues.length;
});
/** 首要阻断文案。 */
const primaryBlockMessage = computed(() => {
const issues = props.eligibility?.issues || [];
const primary = issues.find((item) => String(item.severity || '') === 'blocking') || issues[0];
if (!primary) {
const blockedLines = (props.eligibility?.line_projections || []).filter((line) => line.can_build === false);
if (!blockedLines.length) return '';
const reason = String(blockedLines[0]?.block_reason || '').trim();
const key = `chat.shippingOrderReview.buildEligibility.blockReasons.${reason}`;
return reason && te(key) ? t(key) : t('chat.shippingOrderReview.buildEligibility.blockReasons.unknown');
}
const message = String(primary.explainability?.message || primary.message || '').trim();
if (message) return message;
const code = String(primary.code || '').trim();
const key = `chat.shippingOrderReview.issueCodes.${code}`;
return code && te(key) ? t(key) : t('chat.shippingOrderReview.issueCodes.unknown');
});
/** 不可建单的行数。 */
const blockedLineCount = computed(() =>
(props.eligibility?.line_projections || []).filter((line) => line.can_build === false).length,
);
/**
* 门禁勾选列表:优先 gates 映射;客户未确认时强制展示失败项。
*/
const gateChecklist = computed(() => {
const gates = props.eligibility?.gates || {};
const failed = new Set((props.eligibility?.failed_gates || []).map(String));
const issues = props.eligibility?.issues || [];
const customerIssue = issues.some((item) => String(item.code || '').startsWith('customer_'));
return CHECKLIST_GATES.map((gate) => {
const known = Object.prototype.hasOwnProperty.call(gates, gate);
let passed = known ? Boolean(gates[gate]) : !failed.has(gate);
if (gate === 'customer_confirmed' && customerIssue) passed = false;
const labelKey = `chat.shippingOrderReview.buildEligibility.gates.${gate}`;
return {
gate,
passed,
label: te(labelKey) ? t(labelKey) : gate,
};
}).filter((item) => Object.keys(gates).length === 0 || Object.prototype.hasOwnProperty.call(gates, item.gate) || item.gate === 'customer_confirmed');
});
</script>
<template>
<section
v-if="eligibility"
class="rounded-xl border border-slate-200 bg-white p-3 shadow-sm dark:border-slate-800 dark:bg-slate-900"
data-testid="review-build-eligibility-summary"
>
<header class="flex flex-wrap items-center justify-between gap-2">
<h2 class="text-sm font-semibold">{{ t('chat.shippingOrderReview.buildEligibility.title') }}</h2>
<span
class="rounded-full px-2.5 py-1 text-xs font-medium"
:class="eligibility.can_build
? 'bg-emerald-100 text-emerald-800 dark:bg-emerald-950 dark:text-emerald-100'
: 'bg-amber-100 text-amber-900 dark:bg-amber-950 dark:text-amber-100'"
data-testid="review-build-eligibility-badge"
>
{{
eligibility.can_build
? t('chat.shippingOrderReview.buildEligibility.canBuildYes')
: t('chat.shippingOrderReview.buildEligibility.canBuildNo')
}}
</span>
</header>
<ul
v-if="gateChecklist.length"
class="mt-2 space-y-1 text-xs"
data-testid="review-eligibility-gate-checklist"
>
<li
v-for="item in gateChecklist"
:key="item.gate"
class="flex items-center gap-2"
>
<span :class="item.passed ? 'text-emerald-600' : 'text-rose-600'">{{ item.passed ? '✓' : '×' }}</span>
<span :class="item.passed ? 'text-secondary' : 'font-medium text-rose-700 dark:text-rose-300'">
{{ item.label }}
</span>
</li>
</ul>
<div
v-if="!eligibility.can_build && primaryBlockMessage"
class="mt-2 rounded-lg border border-amber-200 bg-amber-50 px-2.5 py-2 text-xs text-amber-950 dark:border-amber-900 dark:bg-amber-950/30 dark:text-amber-100"
data-testid="review-eligibility-primary-block"
>
<div class="font-semibold">{{ t('chat.shippingOrderReview.workbench.primaryBlock') }}</div>
<p class="mt-0.5">{{ primaryBlockMessage }}</p>
<p v-if="blockingIssueCount || blockedLineCount" class="mt-1 text-[11px] opacity-80">
{{ t('chat.shippingOrderReview.workbench.blockCount', {
count: Math.max(blockingIssueCount, blockedLineCount),
}) }}
</p>
</div>
<button
type="button"
class="mt-2 w-full rounded border border-slate-300 px-2 py-1.5 text-xs hover:bg-slate-50 dark:border-slate-600 dark:hover:bg-slate-800"
data-testid="review-open-eligibility-details"
@click="emit('open-details')"
>
{{ t('chat.shippingOrderReview.workbench.viewFullChecks') }}
</button>
</section>
</template>
@@ -0,0 +1,200 @@
<!--
features/chat/components/shipping-review/ReviewCustomerResolutionPanel.vue
用途:复核工作台固定「建单前客户确认」区域(与重新识别 PDF 分层)。
依赖:vue-i18n、ShippingCustomerConfirmDialog、shipping.api 客户确认/重识别接口。
逻辑:始终展示客户识别状态;选择标准客户 / 重新识别客户;成功后 emit refreshed 刷新建单资格。
-->
<script setup lang="ts">
import { computed, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { BusinessError, resolveLocalizedErrorMessage } from '@/shared/api/client';
import { useMessage } from '@/shared/composables/useMessage';
import ShippingCustomerConfirmDialog from '@/features/chat/components/ShippingCustomerConfirmDialog.vue';
import {
confirmWorkspaceShippingOrderReviewCustomer,
listWorkspaceShippingCustomerOptions,
retryWorkspaceShippingOrderReviewCustomerResolution,
} from '@/features/chat/api/shipping.api';
import type {
ShippingCustomerOption,
ShippingOrderReviewCustomerResolution,
} from '@/features/chat/types/shipping.api.types';
const props = defineProps<{
caseNo: string;
resolution: ShippingOrderReviewCustomerResolution | null | undefined;
editable: boolean;
}>();
const emit = defineEmits<{
refreshed: [];
}>();
const { t, te } = useI18n();
const msg = useMessage();
const busy = ref(false);
const dialogOpen = ref(false);
const options = ref<ShippingCustomerOption[]>([]);
const loadingOptions = ref(false);
const resolved = computed(() => Boolean(props.resolution?.resolved));
const statusLabel = computed(() => {
const status = String(props.resolution?.status || '').trim();
if (!status) {
return resolved.value
? t('chat.shippingOrderReview.customerResolution.status.confirmed')
: t('chat.shippingOrderReview.customerResolution.status.unmatched');
}
const key = `chat.shippingOrderReview.customerResolution.status.${status}`;
return te(key) ? t(key) : status;
});
const displayName = computed(() => {
const name = String(props.resolution?.standard_name || '').trim();
const code = String(props.resolution?.short_code || '').trim();
if (name && code) return `${name} (${code})`;
return name || code || String(props.resolution?.raw_name || '').trim() || '—';
});
/**
* 打开标准客户选择弹窗并加载选项。
*/
async function openSelectDialog() {
if (!props.editable || busy.value) return;
dialogOpen.value = true;
loadingOptions.value = true;
try {
options.value = await listWorkspaceShippingCustomerOptions();
} catch (error: unknown) {
options.value = [];
msg.warning(error instanceof Error ? error.message : t('chat.shippingCustomer.loadFailed'));
} finally {
loadingOptions.value = false;
}
}
/**
* 按关键词搜索标准客户。
*/
async function searchCustomers(query: string) {
loadingOptions.value = true;
try {
options.value = await listWorkspaceShippingCustomerOptions(query.trim());
} catch (error: unknown) {
msg.warning(error instanceof Error ? error.message : t('chat.shippingCustomer.loadFailed'));
} finally {
loadingOptions.value = false;
}
}
/**
* 确认标准客户并通知父级刷新 Case / 建单资格。
*/
async function onConfirm(customerId: number) {
if (!props.caseNo || busy.value) return;
busy.value = true;
try {
await confirmWorkspaceShippingOrderReviewCustomer(props.caseNo, {
customer_id: customerId,
reason: t('chat.shippingOrderReview.customerResolution.confirmReason'),
});
dialogOpen.value = false;
msg.success(t('chat.shippingOrderReview.customerResolution.confirmed'));
emit('refreshed');
} catch (error: unknown) {
const message = error instanceof BusinessError
? resolveLocalizedErrorMessage(error.code, error.message)
: (error instanceof Error ? error.message : t('chat.shippingCustomer.confirmFailed'));
msg.warning(message);
} finally {
busy.value = false;
}
}
/**
* 重新识别客户(不触发 PDF 重识别)。
*/
async function onRetry() {
if (!props.caseNo || !props.editable || busy.value) return;
busy.value = true;
try {
await retryWorkspaceShippingOrderReviewCustomerResolution(props.caseNo);
msg.success(t('chat.shippingOrderReview.customerResolution.retryDone'));
emit('refreshed');
} catch (error: unknown) {
const message = error instanceof BusinessError
? resolveLocalizedErrorMessage(error.code, error.message)
: (error instanceof Error ? error.message : t('chat.shippingOrderReview.customerResolution.retryFailed'));
msg.warning(message);
} finally {
busy.value = false;
}
}
</script>
<template>
<section
class="rounded-xl border border-slate-200 bg-white p-3 shadow-sm dark:border-slate-800 dark:bg-slate-900"
data-testid="review-customer-resolution-panel"
>
<header class="flex flex-wrap items-start justify-between gap-2">
<div>
<h2 class="text-sm font-semibold">{{ t('chat.shippingOrderReview.customerResolution.title') }}</h2>
<p class="mt-0.5 text-xs text-muted">{{ t('chat.shippingOrderReview.customerResolution.subtitle') }}</p>
</div>
<span
class="rounded-full px-2.5 py-1 text-xs font-medium"
:class="resolved
? 'bg-emerald-100 text-emerald-800 dark:bg-emerald-950 dark:text-emerald-100'
: 'bg-amber-100 text-amber-900 dark:bg-amber-950 dark:text-amber-100'"
data-testid="review-customer-resolution-badge"
>
{{ statusLabel }}
</span>
</header>
<dl class="mt-2 space-y-1 text-xs text-secondary">
<div class="flex flex-wrap gap-x-2">
<dt class="text-muted">{{ t('chat.shippingOrderReview.customerResolution.recognizedAs') }}</dt>
<dd class="font-medium text-primary">{{ displayName }}</dd>
</div>
<div v-if="resolution?.raw_name && resolution.raw_name !== displayName" class="flex flex-wrap gap-x-2">
<dt class="text-muted">{{ t('chat.shippingOrderReview.customerResolution.rawName') }}</dt>
<dd>{{ resolution.raw_name }}</dd>
</div>
</dl>
<div v-if="editable" class="mt-3 flex flex-wrap gap-2">
<button
type="button"
class="rounded-xl bg-primary px-3 py-1.5 text-sm font-medium text-on-primary disabled:opacity-60"
data-testid="review-select-customer"
:disabled="busy"
@click="openSelectDialog"
>
{{ t('chat.shippingOrderReview.customerResolution.selectCustomer') }}
</button>
<button
type="button"
class="rounded-xl border border-default bg-surface px-3 py-1.5 text-sm text-secondary hover:bg-surface-soft disabled:opacity-60"
data-testid="review-retry-customer"
:disabled="busy"
@click="onRetry"
>
{{ busy ? t('chat.shippingOrderReview.customerResolution.retrying') : t('chat.shippingOrderReview.customerResolution.retryCustomer') }}
</button>
</div>
<p class="mt-2 text-[11px] text-muted">
{{ t('chat.shippingOrderReview.customerResolution.pdfReparseHint') }}
</p>
<ShippingCustomerConfirmDialog
:open="dialogOpen"
:options="options"
:loading="loadingOptions || busy"
@close="dialogOpen = false"
@search="searchCustomers"
@confirm="onConfirm"
/>
</section>
</template>
@@ -0,0 +1,253 @@
/**
* features/chat/components/shipping-review/ReviewDocumentEvidenceDrawer.spec.ts
* 用途:锁定 PDF 证据浮窗/侧栏的打开、导航、展开/固定、resize 句柄与无 bbox 引文展示契约。
* 依赖:vitest、@vue/test-utils、vue-i18n。
* 逻辑:验证上一/下一证据、关闭/展开/固定 emit、「更多」内退出后保留、八向 resize,以及无 bbox 时展示引文。
*/
import { afterEach, describe, expect, it, vi } from 'vitest';
import { flushPromises, mount } from '@vue/test-utils';
import { createI18n } from 'vue-i18n';
import ReviewDocumentEvidenceDrawer from './ReviewDocumentEvidenceDrawer.vue';
import type { ShippingOrderReviewEvidence } from '@/features/chat/types/shipping.api.types';
vi.mock('./ReviewDocumentPreview.vue', () => ({
default: {
name: 'ReviewDocumentPreview',
template: '<div data-testid="mock-pdf-preview" />',
},
}));
const evidenceList: ShippingOrderReviewEvidence[] = [
{
evidence_id: 'ev-1',
field_id: 'fld-po',
page_no: 1,
quote: 'PO-A',
bbox: { x0: 0.1, y0: 0.1, x1: 0.2, y1: 0.2 },
source: 'document_cell',
highlight_quality: 'candidate',
highlight_source: 'pdf_coordinate',
highlight_bbox: { x0: 0.1, y0: 0.1, x1: 0.2, y1: 0.2 },
coordinate_status: 'candidate',
coordinate_issue_codes: [],
evidence_ref: null,
token_ids: [],
value_match_status: 'matched',
},
{
evidence_id: 'ev-2',
field_id: 'fld-qty',
line_index: 0,
page_no: 2,
quote: '10 EA',
bbox: null,
source: 'document_cell',
highlight_quality: 'unavailable',
highlight_source: 'machine_extraction',
highlight_bbox: null,
coordinate_status: 'unavailable',
coordinate_issue_codes: ['coordinate_missing'],
evidence_ref: null,
token_ids: [],
value_match_status: 'matched',
},
];
/**
* 挂载证据抽屉。
*/
function mountDrawer(overrides: Record<string, unknown> = {}) {
const i18n = createI18n({
legacy: false,
locale: 'zh-CN',
messages: {
'zh-CN': {
chat: {
shippingOrderReview: {
previewTitle: 'PDF',
previewLoading: '加载',
previewUnavailable: '不可用',
emptyValue: '空',
evidenceAt: '第 {page} 页',
evidenceNoHighlight: '无坐标高亮',
evidenceInvalidHighlight: '坐标无效',
locateUnavailableHint: '无可靠坐标',
restoreMachine: '恢复机器值',
llmSuggestion: { request: '请求 AI' },
workbench: {
pinPdf: '退出后保留',
unpinPdf: '退出后关闭',
closePdf: '关闭',
pinPdfHint: '退出后保留',
unpinPdfHint: '退出后关闭',
expandPdf: '展开',
collapsePdf: '收起',
expandPdfHint: '放大',
collapsePdfHint: '收起',
dockPdf: '固定为侧栏',
undockPdf: '取消固定',
dockPdfHint: '双栏',
undockPdfHint: '浮窗',
movePdfLeft: '移至左侧',
movePdfRight: '移至右侧',
movePdfSideHint: '换侧',
moreActions: '更多',
},
highlightQuality: {
verified: '已验证',
candidate: '候选',
unavailable: '无坐标',
invalid: '坐标无效',
},
highlightSource: {
pdf_coordinate: 'PDF 原生坐标',
machine_extraction: '机器抽取',
},
coordinateIssues: {
coordinate_missing: '未获得可靠字段级坐标',
},
evidenceDrawer: {
title: '证据核对',
pageUnknown: '未知页',
prevEvidence: '上一证据',
nextEvidence: '下一证据',
field: '字段:{field}',
currentValue: '当前值',
machineValue: '机器值',
source: '来源',
highlightQuality: '高亮质量',
highlightSource: '坐标来源',
layoutPath: '版面路径',
detailsToggle: '证据详情',
},
},
},
},
},
});
return mount(ReviewDocumentEvidenceDrawer, {
props: {
open: true,
pinned: false,
expanded: false,
docked: false,
floatSide: 'right',
src: 'blob:mock',
evidence: evidenceList[0],
evidenceList,
fieldLabel: '客户 PO',
draftValue: 'PO-A',
machineValue: 'PO-A',
valueSourceLabel: '系统识别',
showAiActions: true,
...overrides,
},
global: { plugins: [i18n] },
attachTo: document.body,
});
}
afterEach(() => {
document.body.innerHTML = '';
localStorage.clear();
});
describe('ReviewDocumentEvidenceDrawer', () => {
it('renders floating panel when open and emits close/expand/dock; pin lives in more menu', async () => {
const wrapper = mountDrawer();
const root = wrapper.find('[data-testid="review-document-evidence-drawer"]');
expect(root.exists()).toBe(true);
expect(root.attributes('data-presentation')).toBe('floating');
expect(root.attributes('role')).toBe('dialog');
expect(root.attributes('aria-modal')).toBe('true');
expect(root.classes()).toContain('fixed');
expect(root.attributes('data-width')).toBeTruthy();
expect(root.attributes('data-height')).toBeTruthy();
expect(wrapper.find('[data-testid="review-evidence-ordinal"]').text()).toContain('1/2');
await wrapper.find('[data-testid="review-evidence-close"]').trigger('click');
expect(wrapper.emitted('close')).toBeTruthy();
await wrapper.find('[data-testid="review-evidence-toggle-expand"]').trigger('click');
expect(wrapper.emitted('toggle-expand')).toBeTruthy();
await wrapper.find('[data-testid="review-evidence-toggle-dock"]').trigger('click');
expect(wrapper.emitted('toggle-dock')).toBeTruthy();
// 关键断言:低频操作收入「更多」,打开后再点「退出后保留」。
expect(wrapper.find('[data-testid="review-evidence-toggle-pin"]').exists()).toBe(false);
await wrapper.find('[data-testid="review-evidence-more"]').trigger('click');
expect(wrapper.find('[data-testid="review-evidence-more-menu"]').exists()).toBe(true);
await wrapper.find('[data-testid="review-evidence-toggle-pin"]').trigger('click');
expect(wrapper.emitted('toggle-pin')).toBeTruthy();
});
it('exposes eight resize handles on floating panel only', () => {
const floating = mountDrawer({ docked: false });
for (const dir of ['n', 's', 'e', 'w', 'ne', 'nw', 'se', 'sw']) {
expect(floating.find(`[data-testid="review-evidence-resize-${dir}"]`).exists()).toBe(true);
}
floating.unmount();
const docked = mountDrawer({ docked: true });
expect(docked.find('[data-testid="review-evidence-resize-se"]').exists()).toBe(false);
});
it('persists float geometry to localStorage after resize end', async () => {
const wrapper = mountDrawer();
const handleEl = wrapper.find('[data-testid="review-evidence-resize-se"]').element;
handleEl.dispatchEvent(new PointerEvent('pointerdown', {
bubbles: true,
clientX: 100,
clientY: 100,
}));
window.dispatchEvent(new PointerEvent('pointermove', { clientX: 180, clientY: 160 }));
window.dispatchEvent(new PointerEvent('pointerup'));
await flushPromises();
const raw = localStorage.getItem('hxops.shippingReview.evidenceFloat.v1');
// 关键断言:拖拽结束写入尺寸位置,供下次打开复用。
expect(raw).toBeTruthy();
const parsed = JSON.parse(String(raw)) as { width: number; height: number };
expect(parsed.width).toBeGreaterThanOrEqual(360);
expect(parsed.height).toBeGreaterThanOrEqual(320);
});
it('closes floating panel on Escape', async () => {
const wrapper = mountDrawer({ open: true, docked: false });
await flushPromises();
document.dispatchEvent(new KeyboardEvent('keydown', {
key: 'Escape',
bubbles: true,
cancelable: true,
}));
// 关键断言:浮动态 Esc 关闭,便于键盘退出。
expect(wrapper.emitted('close')).toBeTruthy();
});
it('uses complementary semantics when docked as sidebar', () => {
const wrapper = mountDrawer({ docked: true });
const root = wrapper.find('[data-testid="review-document-evidence-drawer"]');
expect(root.attributes('data-presentation')).toBe('docked');
expect(root.attributes('role')).toBe('complementary');
expect(root.attributes('aria-modal')).toBeUndefined();
expect(root.classes()).toContain('relative');
expect(root.classes()).not.toContain('fixed');
});
it('enables next evidence and disables prev on first item', async () => {
const wrapper = mountDrawer();
expect((wrapper.find('[data-testid="review-evidence-prev"]').element as HTMLButtonElement).disabled).toBe(true);
expect((wrapper.find('[data-testid="review-evidence-next"]').element as HTMLButtonElement).disabled).toBe(false);
await wrapper.find('[data-testid="review-evidence-next"]').trigger('click');
expect(wrapper.emitted('next-evidence')).toBeTruthy();
});
it('shows quote when evidence has no bbox', () => {
const wrapper = mountDrawer({ evidence: evidenceList[1] });
expect(wrapper.find('[data-testid="review-evidence-no-bbox"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="review-evidence-no-bbox"]').text()).toContain('10 EA');
});
it('does not render when closed', () => {
const wrapper = mountDrawer({ open: false });
expect(wrapper.find('[data-testid="review-document-evidence-drawer"]').exists()).toBe(false);
});
});
@@ -0,0 +1,826 @@
<!--
features/chat/components/shipping-review/ReviewDocumentEvidenceDrawer.vue
用途:复核工作台 PDF 证据面板(默认浮动、可拖拽/resize、可固定为侧栏)。
依赖:ReviewDocumentPreview、ShippingOrderReviewEvidence、vue-i18n、field-highlight 契约。
逻辑:浮动用 left/top/width/height;四边四角 resize;localStorage 记忆尺寸位置;
dialog 语义(Esc/焦点陷阱);打开避让焦点字段;低频操作收入「更多」菜单。
-->
<script setup lang="ts">
import { computed, nextTick, onBeforeUnmount, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import ReviewDocumentPreview from './ReviewDocumentPreview.vue';
import type { ShippingOrderReviewEvidence } from '@/features/chat/types/shipping.api.types';
const FOCUSABLE_SELECTOR = [
'a[href]',
'button:not([disabled])',
'textarea:not([disabled])',
'input:not([disabled])',
'select:not([disabled])',
'[tabindex]:not([tabindex="-1"])',
].join(',');
const STORAGE_KEY = 'hxops.shippingReview.evidenceFloat.v1';
const MIN_WIDTH = 360;
const MIN_HEIGHT = 320;
const VIEW_MARGIN = 16;
const FOOTER_CLEARANCE = 72;
type ResizeDir = 'n' | 's' | 'e' | 'w' | 'ne' | 'nw' | 'se' | 'sw';
interface FloatGeom {
left: number;
top: number;
width: number;
height: number;
}
const RESIZE_DIRS: ResizeDir[] = ['n', 's', 'e', 'w', 'ne', 'nw', 'se', 'sw'];
const props = defineProps<{
open: boolean;
pinned: boolean;
expanded: boolean;
docked: boolean;
floatSide: 'right' | 'left';
src: string;
evidence: ShippingOrderReviewEvidence | null;
evidenceList: ShippingOrderReviewEvidence[];
fieldLabel?: string;
draftValue?: string | null;
machineValue?: string | null;
valueSourceLabel?: string;
showAiActions?: boolean;
/** Case 切换时重置证据焦点相关态;不清除用户记住的浮窗几何。 */
resetKey?: string | null;
}>();
const emit = defineEmits<{
close: [];
'toggle-pin': [];
'toggle-expand': [];
'toggle-dock': [];
'toggle-side': [];
'prev-evidence': [];
'next-evidence': [];
'request-ai': [];
'restore-machine': [];
}>();
const { t } = useI18n();
const panelRef = ref<HTMLElement | null>(null);
const closeButtonRef = ref<HTMLButtonElement | null>(null);
const moreOpen = ref(false);
const detailsOpen = ref(false);
const geom = ref<FloatGeom>(defaultGeom('right', false));
const dragging = ref(false);
const resizing = ref(false);
let dragOrigin: { x: number; y: number; left: number; top: number } | null = null;
let resizeOrigin: {
dir: ResizeDir;
x: number;
y: number;
left: number;
top: number;
width: number;
height: number;
} | null = null;
let previouslyFocused: HTMLElement | null = null;
let autoSideAdjustedForOpen = false;
/**
* 视口允许的最大浮窗宽高(70% / 85%)。
*/
function maxSize() {
if (typeof window === 'undefined') return { width: 720, height: 680 };
return {
width: Math.max(MIN_WIDTH, Math.floor(window.innerWidth * 0.7)),
height: Math.max(MIN_HEIGHT, Math.floor(window.innerHeight * 0.85)),
};
}
/**
* 生成默认浮窗几何(右下或左下,避开底栏)。
*/
function defaultGeom(side: 'left' | 'right', expanded: boolean): FloatGeom {
const max = maxSize();
const width = Math.min(expanded ? 720 : 440, max.width);
const height = Math.min(expanded ? 680 : 520, max.height);
if (typeof window === 'undefined') {
return { left: 16, top: 16, width, height };
}
const left = side === 'left'
? VIEW_MARGIN
: Math.max(VIEW_MARGIN, window.innerWidth - width - VIEW_MARGIN);
const top = Math.max(
VIEW_MARGIN,
window.innerHeight - height - FOOTER_CLEARANCE,
);
return { left, top, width, height };
}
/**
* 钳制几何到视口与最小/最大尺寸。
*/
function clampGeom(next: FloatGeom): FloatGeom {
const max = maxSize();
const width = Math.min(max.width, Math.max(MIN_WIDTH, Math.round(next.width)));
const height = Math.min(max.height, Math.max(MIN_HEIGHT, Math.round(next.height)));
if (typeof window === 'undefined') {
return { left: next.left, top: next.top, width, height };
}
const maxLeft = Math.max(VIEW_MARGIN, window.innerWidth - width - VIEW_MARGIN);
const maxTop = Math.max(VIEW_MARGIN, window.innerHeight - height - VIEW_MARGIN);
return {
width,
height,
left: Math.min(maxLeft, Math.max(VIEW_MARGIN, Math.round(next.left))),
top: Math.min(maxTop, Math.max(VIEW_MARGIN, Math.round(next.top))),
};
}
/**
* 从 localStorage 恢复浮窗几何。
*/
function loadStoredGeom(): FloatGeom | null {
if (typeof localStorage === 'undefined') return null;
try {
const raw = localStorage.getItem(STORAGE_KEY);
if (!raw) return null;
const parsed = JSON.parse(raw) as Partial<FloatGeom>;
if (
typeof parsed.left !== 'number'
|| typeof parsed.top !== 'number'
|| typeof parsed.width !== 'number'
|| typeof parsed.height !== 'number'
) {
return null;
}
return clampGeom({
left: parsed.left,
top: parsed.top,
width: parsed.width,
height: parsed.height,
});
} catch {
return null;
}
}
/**
* 持久化浮窗几何(跨 Case 复用尺寸位置,不复用证据焦点)。
*/
function persistGeom(next: FloatGeom) {
if (typeof localStorage === 'undefined') return;
try {
localStorage.setItem(STORAGE_KEY, JSON.stringify(next));
} catch {
/* ignore quota */
}
}
/**
* 应用几何并可选持久化。
*/
function applyGeom(next: FloatGeom, persist = true) {
const clamped = clampGeom(next);
geom.value = clamped;
if (persist) persistGeom(clamped);
}
/**
* 当前证据在列表中的序号(1-based);无匹配时为 0。
*/
const evidenceOrdinal = computed(() => {
const id = String(props.evidence?.evidence_id || '');
if (!id) return 0;
const idx = props.evidenceList.findIndex((item) => item.evidence_id === id);
return idx >= 0 ? idx + 1 : 0;
});
const canPrev = computed(() => evidenceOrdinal.value > 1);
const canNext = computed(() => {
const total = props.evidenceList.length;
return evidenceOrdinal.value > 0 && evidenceOrdinal.value < total;
});
const pageLabel = computed(() => {
const page = props.evidence?.page_no;
if (page == null) return t('chat.shippingOrderReview.evidenceDrawer.pageUnknown');
return t('chat.shippingOrderReview.evidenceAt', { page });
});
const hasDrawableHighlight = computed(() => {
const quality = String(props.evidence?.highlight_quality || '');
return (quality === 'verified' || quality === 'candidate')
&& Boolean(props.evidence?.highlight_bbox || props.evidence?.bbox);
});
const highlightQualityLabel = computed(() => {
const quality = String(props.evidence?.highlight_quality || 'unavailable');
return t(`chat.shippingOrderReview.highlightQuality.${quality}`, quality);
});
const highlightSourceLabel = computed(() => {
const source = String(props.evidence?.highlight_source || props.evidence?.source || 'unknown');
return t(`chat.shippingOrderReview.highlightSource.${source}`, source);
});
const coordinateIssueLabels = computed(() => {
const codes = props.evidence?.coordinate_issue_codes || [];
return codes.map((code) => t(`chat.shippingOrderReview.coordinateIssues.${code}`, code));
});
/**
* 面板根节点 class:浮动 fixed;固定侧栏走文档流。
*/
const panelClass = computed(() => {
if (props.docked) {
return [
'relative flex min-h-[320px] min-w-0 flex-col overflow-hidden rounded-xl border border-slate-200',
'bg-white shadow-sm xl:min-h-[520px] dark:border-slate-800 dark:bg-slate-900',
].join(' ');
}
return [
'fixed z-30 flex flex-col overflow-hidden rounded-xl border border-slate-200',
'bg-white shadow-2xl dark:border-slate-700 dark:bg-slate-900',
].join(' ');
});
/**
* 浮动几何 style;侧栏不使用。
*/
const panelStyle = computed(() => {
if (props.docked) return undefined;
return {
left: `${geom.value.left}px`,
top: `${geom.value.top}px`,
width: `${geom.value.width}px`,
height: `${geom.value.height}px`,
};
});
const resizeCursor: Record<ResizeDir, string> = {
n: 'ns-resize',
s: 'ns-resize',
e: 'ew-resize',
w: 'ew-resize',
ne: 'nesw-resize',
sw: 'nesw-resize',
nw: 'nwse-resize',
se: 'nwse-resize',
};
/**
* resize handle 定位 style(边 6px / 角 10px)。
*/
function resizeHandleStyle(dir: ResizeDir): Record<string, string> {
const edge = '6px';
const corner = '10px';
const styles: Record<ResizeDir, Record<string, string>> = {
n: { top: '0', left: corner, right: corner, height: edge },
s: { bottom: '0', left: corner, right: corner, height: edge },
e: { top: corner, right: '0', bottom: corner, width: edge },
w: { top: corner, left: '0', bottom: corner, width: edge },
ne: { top: '0', right: '0', width: corner, height: corner },
nw: { top: '0', left: '0', width: corner, height: corner },
se: { bottom: '0', right: '0', width: corner, height: corner },
sw: { bottom: '0', left: '0', width: corner, height: corner },
};
return styles[dir];
}
/** 收集面板内可聚焦控件。 */
const focusableNodes = (): HTMLElement[] => {
if (!panelRef.value) return [];
return Array.from(panelRef.value.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR))
.filter((node) => !node.hasAttribute('disabled') && node.getAttribute('aria-hidden') !== 'true');
};
const onKeydown = (event: KeyboardEvent) => {
if (!props.open || props.docked) return;
if (event.key === 'Escape') {
if (moreOpen.value) {
event.preventDefault();
moreOpen.value = false;
return;
}
event.preventDefault();
event.stopPropagation();
emit('close');
return;
}
if (event.key !== 'Tab') return;
const nodes = focusableNodes();
const first = nodes[0];
const last = nodes[nodes.length - 1];
if (!first || !last) {
event.preventDefault();
return;
}
const active = document.activeElement as HTMLElement | null;
const inside = Boolean(active && panelRef.value?.contains(active));
if (event.shiftKey) {
if (!inside || active === first) {
event.preventDefault();
last.focus();
}
return;
}
if (!inside || active === last) {
event.preventDefault();
first.focus();
}
};
const rectsOverlap = (a: DOMRect, b: DOMRect) => !(
a.right < b.left || a.left > b.right || a.bottom < b.top || a.top > b.bottom
);
/**
* 打开浮窗后若遮挡打开前焦点字段,则移到另一侧一次。
*/
const maybeAvoidFocusedField = async () => {
if (props.docked || autoSideAdjustedForOpen || typeof document === 'undefined') return;
await nextTick();
const panel = panelRef.value;
if (!panel) return;
const target = previouslyFocused
&& previouslyFocused.isConnected
&& !panel.contains(previouslyFocused)
? previouslyFocused
: null;
if (!target) return;
if (!target.matches('input, textarea, select, [contenteditable="true"]')) return;
if (!rectsOverlap(panel.getBoundingClientRect(), target.getBoundingClientRect())) return;
autoSideAdjustedForOpen = true;
const width = geom.value.width;
const left = props.floatSide === 'right'
? VIEW_MARGIN
: Math.max(VIEW_MARGIN, window.innerWidth - width - VIEW_MARGIN);
applyGeom({ ...geom.value, left });
emit('toggle-side');
};
/**
* 标题栏拖动移动浮窗。
*/
const onDragStart = (event: PointerEvent) => {
if (props.docked || resizing.value) return;
const target = event.target as HTMLElement | null;
if (target?.closest('button, details, summary, a, input')) return;
dragging.value = true;
dragOrigin = {
x: event.clientX,
y: event.clientY,
left: geom.value.left,
top: geom.value.top,
};
window.addEventListener('pointermove', onDragMove);
window.addEventListener('pointerup', onDragEnd);
};
const onDragMove = (event: PointerEvent) => {
if (!dragging.value || !dragOrigin) return;
applyGeom({
...geom.value,
left: dragOrigin.left + (event.clientX - dragOrigin.x),
top: dragOrigin.top + (event.clientY - dragOrigin.y),
}, false);
};
const onDragEnd = () => {
dragging.value = false;
dragOrigin = null;
window.removeEventListener('pointermove', onDragMove);
window.removeEventListener('pointerup', onDragEnd);
applyGeom(geom.value, true);
};
/**
* 八向 resize 开始。
*/
const onResizeStart = (dir: ResizeDir, event: PointerEvent) => {
if (props.docked) return;
event.preventDefault();
event.stopPropagation();
resizing.value = true;
resizeOrigin = {
dir,
x: event.clientX,
y: event.clientY,
left: geom.value.left,
top: geom.value.top,
width: geom.value.width,
height: geom.value.height,
};
window.addEventListener('pointermove', onResizeMove);
window.addEventListener('pointerup', onResizeEnd);
};
const onResizeMove = (event: PointerEvent) => {
if (!resizing.value || !resizeOrigin) return;
const dx = event.clientX - resizeOrigin.x;
const dy = event.clientY - resizeOrigin.y;
const next: FloatGeom = {
left: resizeOrigin.left,
top: resizeOrigin.top,
width: resizeOrigin.width,
height: resizeOrigin.height,
};
const dir = resizeOrigin.dir;
if (dir.includes('e')) next.width = resizeOrigin.width + dx;
if (dir.includes('w')) {
next.width = resizeOrigin.width - dx;
next.left = resizeOrigin.left + dx;
}
if (dir.includes('s')) next.height = resizeOrigin.height + dy;
if (dir.includes('n')) {
next.height = resizeOrigin.height - dy;
next.top = resizeOrigin.top + dy;
}
// 宽度触底时锁住 left,避免西向拖拽抖动。
if (dir.includes('w') && next.width <= MIN_WIDTH) {
next.width = MIN_WIDTH;
next.left = resizeOrigin.left + (resizeOrigin.width - MIN_WIDTH);
}
if (dir.includes('n') && next.height <= MIN_HEIGHT) {
next.height = MIN_HEIGHT;
next.top = resizeOrigin.top + (resizeOrigin.height - MIN_HEIGHT);
}
applyGeom(next, false);
};
const onResizeEnd = () => {
resizing.value = false;
resizeOrigin = null;
window.removeEventListener('pointermove', onResizeMove);
window.removeEventListener('pointerup', onResizeEnd);
applyGeom(geom.value, true);
};
/**
* 初始化或按展开态重置默认尺寸(保留可恢复的存储几何优先)。
*/
function ensureFloatGeom(forceDefault = false) {
if (forceDefault) {
applyGeom(defaultGeom(props.floatSide, props.expanded));
return;
}
const stored = loadStoredGeom();
if (stored) {
applyGeom(stored, false);
return;
}
applyGeom(defaultGeom(props.floatSide, props.expanded), false);
}
watch(
() => props.expanded,
(expanded, was) => {
if (props.docked || was === undefined) return;
const max = maxSize();
if (expanded) {
applyGeom({
...geom.value,
width: Math.min(720, max.width),
height: Math.min(680, max.height),
});
return;
}
applyGeom({
...geom.value,
width: Math.min(440, max.width),
height: Math.min(520, max.height),
});
},
);
watch(
() => props.floatSide,
(side, prev) => {
if (props.docked || prev === undefined || side === prev) return;
const width = geom.value.width;
const left = side === 'left'
? VIEW_MARGIN
: Math.max(VIEW_MARGIN, (typeof window !== 'undefined' ? window.innerWidth : 1200) - width - VIEW_MARGIN);
applyGeom({ ...geom.value, left });
},
);
watch(
() => [props.open, props.docked] as const,
([open, docked], previous) => {
if (typeof document === 'undefined') return;
const wasOpen = Boolean(previous?.[0]);
const floatingOpen = Boolean(open && !docked);
if (floatingOpen && !wasOpen) {
autoSideAdjustedForOpen = false;
moreOpen.value = false;
ensureFloatGeom(false);
previouslyFocused = document.activeElement instanceof HTMLElement
? document.activeElement
: null;
document.addEventListener('keydown', onKeydown, true);
void nextTick(() => {
try {
(closeButtonRef.value || focusableNodes()[0])?.focus?.();
} catch {
/* ignore */
}
void maybeAvoidFocusedField();
});
return;
}
if (floatingOpen && wasOpen) {
void maybeAvoidFocusedField();
return;
}
if ((!open || docked) && wasOpen) {
document.removeEventListener('keydown', onKeydown, true);
const restoreTarget = previouslyFocused;
previouslyFocused = null;
autoSideAdjustedForOpen = false;
moreOpen.value = false;
if (!open) {
void nextTick(() => {
try {
restoreTarget?.focus?.();
} catch {
/* ignore */
}
});
}
}
},
{ immediate: true },
);
onBeforeUnmount(() => {
window.removeEventListener('pointermove', onDragMove);
window.removeEventListener('pointerup', onDragEnd);
window.removeEventListener('pointermove', onResizeMove);
window.removeEventListener('pointerup', onResizeEnd);
if (typeof document !== 'undefined') {
document.removeEventListener('keydown', onKeydown, true);
}
});
</script>
<template>
<aside
v-if="open"
ref="panelRef"
:class="panelClass"
:style="panelStyle"
:role="docked ? 'complementary' : 'dialog'"
:aria-modal="docked ? undefined : 'true'"
aria-labelledby="review-evidence-drawer-title"
tabindex="-1"
data-testid="review-document-evidence-drawer"
:data-pinned="pinned ? 'true' : 'false'"
:data-expanded="expanded ? 'true' : 'false'"
:data-docked="docked ? 'true' : 'false'"
:data-float-side="floatSide"
:data-presentation="docked ? 'docked' : 'floating'"
:data-width="Math.round(geom.width)"
:data-height="Math.round(geom.height)"
>
<div
class="flex shrink-0 flex-col gap-1.5 border-b border-slate-200 px-3 py-2 dark:border-slate-800"
:class="docked ? '' : 'cursor-grab active:cursor-grabbing select-none'"
data-testid="review-evidence-drag-handle"
@pointerdown="onDragStart"
>
<div class="flex items-start justify-between gap-2">
<div class="min-w-0">
<div
id="review-evidence-drawer-title"
class="text-xs font-semibold text-slate-700 dark:text-slate-200"
>
{{ t('chat.shippingOrderReview.evidenceDrawer.title') }}
</div>
<p class="truncate text-[11px] text-slate-500">{{ pageLabel }}</p>
</div>
<button
ref="closeButtonRef"
type="button"
class="rounded border border-slate-300 px-2 py-1 text-xs hover:bg-slate-50 dark:border-slate-600 dark:hover:bg-slate-800"
data-testid="review-evidence-close"
@click="emit('close')"
>
{{ t('chat.shippingOrderReview.workbench.closePdf') }}
</button>
</div>
<div class="flex flex-wrap items-center gap-1.5">
<div class="flex items-center gap-1" data-testid="review-evidence-nav-group">
<button
type="button"
class="rounded border border-slate-300 px-2 py-1 text-xs hover:bg-slate-50 dark:border-slate-600 dark:hover:bg-slate-800"
data-testid="review-evidence-prev"
:disabled="!canPrev"
@click="emit('prev-evidence')"
>
{{ t('chat.shippingOrderReview.evidenceDrawer.prevEvidence') }}
</button>
<span class="text-[11px] text-slate-500" data-testid="review-evidence-ordinal">
{{ evidenceOrdinal }}/{{ evidenceList.length || 0 }}
</span>
<button
type="button"
class="rounded border border-slate-300 px-2 py-1 text-xs hover:bg-slate-50 dark:border-slate-600 dark:hover:bg-slate-800"
data-testid="review-evidence-next"
:disabled="!canNext"
@click="emit('next-evidence')"
>
{{ t('chat.shippingOrderReview.evidenceDrawer.nextEvidence') }}
</button>
</div>
<div class="ml-auto flex items-center gap-1" data-testid="review-evidence-window-group">
<button
v-if="!docked"
type="button"
class="rounded border border-slate-300 px-2 py-1 text-xs hover:bg-slate-50 dark:border-slate-600 dark:hover:bg-slate-800"
data-testid="review-evidence-toggle-expand"
:title="expanded
? t('chat.shippingOrderReview.workbench.collapsePdfHint')
: t('chat.shippingOrderReview.workbench.expandPdfHint')"
@click="emit('toggle-expand')"
>
{{ expanded
? t('chat.shippingOrderReview.workbench.collapsePdf')
: t('chat.shippingOrderReview.workbench.expandPdf') }}
</button>
<button
type="button"
class="rounded border border-slate-300 px-2 py-1 text-xs hover:bg-slate-50 dark:border-slate-600 dark:hover:bg-slate-800"
data-testid="review-evidence-toggle-dock"
:title="docked
? t('chat.shippingOrderReview.workbench.undockPdfHint')
: t('chat.shippingOrderReview.workbench.dockPdfHint')"
@click="emit('toggle-dock')"
>
{{ docked
? t('chat.shippingOrderReview.workbench.undockPdf')
: t('chat.shippingOrderReview.workbench.dockPdf') }}
</button>
<div class="relative">
<button
type="button"
class="rounded border border-slate-300 px-2 py-1 text-xs hover:bg-slate-50 dark:border-slate-600 dark:hover:bg-slate-800"
data-testid="review-evidence-more"
:aria-expanded="moreOpen ? 'true' : 'false'"
@click="moreOpen = !moreOpen"
>
{{ t('chat.shippingOrderReview.workbench.moreActions') }}
</button>
<div
v-if="moreOpen"
class="absolute right-0 z-40 mt-1 min-w-[10rem] rounded-md border border-slate-200 bg-white py-1 text-xs shadow-lg dark:border-slate-700 dark:bg-slate-900"
data-testid="review-evidence-more-menu"
>
<button
v-if="!docked"
type="button"
class="block w-full px-3 py-1.5 text-left hover:bg-slate-50 dark:hover:bg-slate-800"
data-testid="review-evidence-toggle-side"
@click="emit('toggle-side'); moreOpen = false"
>
{{ floatSide === 'right'
? t('chat.shippingOrderReview.workbench.movePdfLeft')
: t('chat.shippingOrderReview.workbench.movePdfRight') }}
</button>
<button
type="button"
class="block w-full px-3 py-1.5 text-left hover:bg-slate-50 dark:hover:bg-slate-800"
data-testid="review-evidence-toggle-pin"
@click="emit('toggle-pin'); moreOpen = false"
>
{{ pinned
? t('chat.shippingOrderReview.workbench.unpinPdf')
: t('chat.shippingOrderReview.workbench.pinPdf') }}
</button>
<button
v-if="showAiActions"
type="button"
class="block w-full px-3 py-1.5 text-left hover:bg-slate-50 dark:hover:bg-slate-800"
data-testid="review-evidence-request-ai"
@click="emit('request-ai'); moreOpen = false"
>
{{ t('chat.shippingOrderReview.llmSuggestion.request') }}
</button>
<button
v-if="showAiActions"
type="button"
class="block w-full px-3 py-1.5 text-left hover:bg-slate-50 dark:hover:bg-slate-800"
data-testid="review-evidence-restore-machine"
@click="emit('restore-machine'); moreOpen = false"
>
{{ t('chat.shippingOrderReview.restoreMachine') }}
</button>
</div>
</div>
</div>
</div>
</div>
<div class="grid min-h-0 flex-1 grid-rows-[minmax(0,1fr)_auto]">
<ReviewDocumentPreview
v-if="src"
class="min-h-0"
:src="src"
:evidence="evidence"
:drawer-mode="true"
:title="t('chat.shippingOrderReview.previewTitle')"
:loading-text="t('chat.shippingOrderReview.previewLoading')"
:unavailable-text="t('chat.shippingOrderReview.previewUnavailable')"
/>
<div
v-else
class="flex min-h-[140px] items-center justify-center p-4 text-sm text-slate-500"
>
{{ t('chat.shippingOrderReview.previewUnavailable') }}
</div>
<details
class="shrink-0 border-t border-slate-200 text-xs dark:border-slate-800"
data-testid="review-evidence-details"
:open="detailsOpen"
@toggle="detailsOpen = ($event.target as HTMLDetailsElement).open"
>
<summary class="cursor-pointer px-3 py-2 font-medium text-slate-700 hover:bg-slate-50 dark:text-slate-200 dark:hover:bg-slate-800/60">
{{ t('chat.shippingOrderReview.evidenceDrawer.detailsToggle') }}
<span v-if="fieldLabel" class="ml-1 font-normal text-slate-500">· {{ fieldLabel }}</span>
</summary>
<div class="space-y-2 px-3 pb-2">
<div v-if="fieldLabel" class="font-medium text-slate-700 dark:text-slate-200">
{{ t('chat.shippingOrderReview.evidenceDrawer.field', { field: fieldLabel }) }}
</div>
<dl class="grid gap-1 text-slate-600 dark:text-slate-300">
<div class="flex gap-2">
<dt class="shrink-0 text-slate-500">{{ t('chat.shippingOrderReview.evidenceDrawer.currentValue') }}</dt>
<dd class="min-w-0 break-words">{{ draftValue || t('chat.shippingOrderReview.emptyValue') }}</dd>
</div>
<div class="flex gap-2">
<dt class="shrink-0 text-slate-500">{{ t('chat.shippingOrderReview.evidenceDrawer.machineValue') }}</dt>
<dd class="min-w-0 break-words">{{ machineValue || t('chat.shippingOrderReview.emptyValue') }}</dd>
</div>
<div class="flex gap-2">
<dt class="shrink-0 text-slate-500">{{ t('chat.shippingOrderReview.evidenceDrawer.highlightQuality') }}</dt>
<dd data-testid="review-evidence-highlight-quality">{{ highlightQualityLabel }}</dd>
</div>
<div class="flex gap-2">
<dt class="shrink-0 text-slate-500">{{ t('chat.shippingOrderReview.evidenceDrawer.highlightSource') }}</dt>
<dd data-testid="review-evidence-highlight-source">{{ highlightSourceLabel }}</dd>
</div>
<div v-if="valueSourceLabel" class="flex gap-2">
<dt class="shrink-0 text-slate-500">{{ t('chat.shippingOrderReview.evidenceDrawer.source') }}</dt>
<dd>{{ valueSourceLabel }}</dd>
</div>
<div v-if="evidence?.table_id || evidence?.cell_id" class="flex gap-2">
<dt class="shrink-0 text-slate-500">{{ t('chat.shippingOrderReview.evidenceDrawer.layoutPath') }}</dt>
<dd class="min-w-0 break-all font-mono text-[11px]">
{{ [evidence?.table_id, evidence?.cell_id].filter(Boolean).join(' / ') }}
</dd>
</div>
</dl>
<p
v-if="!hasDrawableHighlight"
class="rounded bg-amber-50 px-2 py-1 text-[11px] text-amber-900 dark:bg-amber-950/40 dark:text-amber-100"
data-testid="review-evidence-no-bbox"
>
<span v-if="!evidence">
{{ t('chat.shippingOrderReview.locateUnavailableHint') }}
</span>
<span v-else-if="evidence.highlight_quality === 'invalid'">
{{ t('chat.shippingOrderReview.evidenceInvalidHighlight') }}
</span>
<span v-else>
{{ t('chat.shippingOrderReview.evidenceNoHighlight') }}
</span>
<span v-if="coordinateIssueLabels.length" class="mt-1 block">
{{ coordinateIssueLabels.join(';') }}
</span>
<span v-if="evidence?.quote" class="mt-1 block font-mono">{{ evidence.quote }}</span>
</p>
</div>
</details>
</div>
<template v-if="!docked">
<span
v-for="dir in RESIZE_DIRS"
:key="dir"
class="absolute z-50 touch-none"
:data-testid="`review-evidence-resize-${dir}`"
:data-resize-dir="dir"
:style="{ cursor: resizeCursor[dir], ...resizeHandleStyle(dir) }"
@pointerdown="onResizeStart(dir, $event)"
/>
</template>
</aside>
</template>
@@ -0,0 +1,72 @@
<!--
features/chat/components/shipping-review/ReviewDocumentNavigation.vue
用途:复核工作台顶部横向 PDF 文件导航(紧凑标签样式)。
依赖:vue-i18n、lucide-vue-next。
逻辑:ShippingOrderReviewView 传入 Run 内 Case 摘要;emit select 切换当前 PDF Case。
-->
<script setup lang="ts">
import { TriangleAlert } from 'lucide-vue-next';
import { useI18n } from 'vue-i18n';
export type ReviewDocumentNavItem = {
case_no: string;
file_name?: string | null;
status: string;
issue_count?: number;
};
const props = defineProps<{
items: ReviewDocumentNavItem[];
activeCaseNo?: string | null;
/** 导航区域无障碍标签(避免与原生 aria-label 属性在 vue-tsc 中冲突) */
navAriaLabel: string;
}>();
const emit = defineEmits<{
select: [caseNo: string];
}>();
const { t, te } = useI18n();
/**
* 将 Case 状态码映射为本地化文案,供导航标签展示。
* @param status - Case 状态码
* @returns 本地化文案;未知状态回落 unknown
*/
function caseStatusLabel(status: string): string {
const key = `chat.shippingOrderReview.caseStatuses.${status}`;
return te(key) ? t(key) : t('chat.shippingOrderReview.caseStatuses.unknown');
}
</script>
<template>
<nav
class="rounded-xl border border-slate-200 bg-white p-2 shadow-sm dark:border-slate-800 dark:bg-slate-900"
:aria-label="navAriaLabel"
data-testid="review-document-navigation"
>
<div class="flex gap-1.5 overflow-x-auto">
<button
v-for="item in items"
:key="item.case_no"
type="button"
class="inline-flex max-w-[220px] shrink-0 items-center gap-1.5 rounded-lg border px-2.5 py-1.5 text-left text-xs transition-colors"
:class="activeCaseNo === item.case_no
? 'border-sky-500 bg-sky-50 text-sky-950 dark:border-sky-700 dark:bg-sky-950/40 dark:text-sky-100'
: 'border-slate-200 text-slate-700 hover:bg-slate-50 dark:border-slate-700 dark:text-slate-300 dark:hover:bg-slate-800'"
:data-testid="`review-doc-nav-${item.case_no}`"
@click="emit('select', item.case_no)"
>
<TriangleAlert
v-if="item.issue_count"
class="h-3.5 w-3.5 shrink-0 text-amber-500"
aria-hidden="true"
/>
<span class="truncate font-medium">{{ item.file_name || t('chat.shippingOrderReview.unnamedDocument') }}</span>
<span class="shrink-0 text-[10px] text-slate-500 dark:text-slate-400">
{{ caseStatusLabel(item.status) }}
</span>
</button>
</div>
</nav>
</template>
@@ -1,38 +1,123 @@
<!--
用途:渲染受控 PDF Blob,并仅为服务端验证的 bbox 绘制证据高亮。
依赖:pdfjs-dist、Review Evidence DTO。
逻辑:预览失败独立显示,不影响同页草稿编辑;缺少可靠 bbox 时只保留页码定位。
features/chat/components/shipping-review/ReviewDocumentPreview.vue
用途:渲染受控 PDF Blob,并按 highlight_quality 绘制证据高亮(阶段 4+评审修复)。
依赖:pdfjs-dist(渲染时动态加载)、pdfHighlightCoords、Review Evidence DTO。
逻辑:预览失败独立显示,不影响同页草稿编辑;仅 verified/candidate 绘制;
verified=黄实线,candidate=橙虚线并显示画布内候选提示;unavailable/invalid 不画框;
Ctrl/Cmd+滚轮缩放;适合宽度/页面/100%;溢出时可拖拽平移;高亮自动滚入视口。
-->
<script setup lang="ts">
import { computed, nextTick, ref, watch } from 'vue';
import * as pdfjs from 'pdfjs-dist';
import workerUrl from 'pdfjs-dist/build/pdf.worker.min.mjs?url';
import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import type { ShippingOrderReviewEvidence } from '../../types/shipping.api.types';
import { normalizedTopLeftBBoxToViewportRect } from './pdfHighlightCoords';
pdfjs.GlobalWorkerOptions.workerSrc = workerUrl;
/** 有合法 bbox 时四种质量都绘制;颜色只提示可信度,不隐藏取值位置。 */
const DRAWABLE_QUALITIES = new Set(['verified', 'candidate', 'unavailable', 'invalid']);
const props = defineProps<{
type PdfJsModule = typeof import('pdfjs-dist');
let pdfjsLoader: Promise<PdfJsModule> | null = null;
/**
* 动态加载 pdfjs 与 worker;同页复用单例 Promise。
*/
async function loadPdfJs(): Promise<PdfJsModule> {
if (!pdfjsLoader) {
pdfjsLoader = (async () => {
const [pdfjs, workerMod] = await Promise.all([
import('pdfjs-dist'),
import('pdfjs-dist/build/pdf.worker.min.mjs?url'),
]);
pdfjs.GlobalWorkerOptions.workerSrc = workerMod.default;
return pdfjs;
})();
}
return pdfjsLoader;
}
const props = withDefaults(defineProps<{
src: string;
evidence?: ShippingOrderReviewEvidence | null;
title: string;
loadingText: string;
unavailableText: string;
/** 证据抽屉内使用更紧凑高度与页码指示。 */
drawerMode?: boolean;
}>(), {
drawerMode: false,
});
const emit = defineEmits<{
'page-change': [pageNo: number];
}>();
const { t } = useI18n();
const canvas = ref<HTMLCanvasElement | null>(null);
const scrollHost = ref<HTMLElement | null>(null);
const loading = ref(false);
const failed = ref(false);
const scale = ref(1.5);
const scale = ref(1.25);
const pageCount = ref(0);
const currentPage = ref(1);
/** 用户手动翻页时覆盖证据页码;证据身份变化时清除。 */
const manualPageOverride = ref<number | null>(null);
const pageJumpInput = ref('');
const zoomLabel = computed(() => `${Math.round(scale.value * 100)}%`);
/** 最近一次渲染的未缩放页宽高,供适合宽度/页面计算。 */
const basePageSize = ref<{ width: number; height: number } | null>(null);
/** 将当前页渲染到 canvas;高亮以 PDF viewport 为基准,绝不猜测不可靠坐标。 */
const highlightQuality = computed(() => String(props.evidence?.highlight_quality || ''));
const showCandidateBanner = computed(() => highlightQuality.value === 'candidate');
const showVerifiedLegend = computed(() => highlightQuality.value === 'verified');
const panning = ref(false);
const canPan = ref(false);
let panOrigin: { x: number; y: number; left: number; top: number } | null = null;
/**
* 根据滚动容器是否出现溢出刷新可拖拽平移状态。
*/
const refreshCanPan = () => {
const host = scrollHost.value;
if (!host || loading.value || failed.value) {
canPan.value = false;
return;
}
canPan.value = host.scrollWidth > host.clientWidth + 2
|| host.scrollHeight > host.clientHeight + 2;
};
/**
* 将高亮矩形滚入滚动容器中心(带边距)。
*/
const scrollHighlightIntoView = (rect: { x: number; y: number; width: number; height: number }) => {
const host = scrollHost.value;
if (!host) return;
const pad = 24;
const targetLeft = Math.max(0, rect.x + rect.width / 2 - host.clientWidth / 2);
const targetTop = Math.max(0, rect.y + rect.height / 2 - host.clientHeight / 2 + pad);
host.scrollTo({ left: targetLeft, top: targetTop, behavior: 'smooth' });
};
/**
* 将当前页渲染到 canvas;高亮以 PDF viewport 矩阵为基准,绝不猜测不可靠坐标。
*/
const render = async () => {
if (!props.src) return;
loading.value = true;
failed.value = false;
try {
const pdfjs = await loadPdfJs();
const document = await pdfjs.getDocument(props.src).promise;
const pageNo = Math.min(Math.max(props.evidence?.page_no || 1, 1), document.numPages);
const page = await document.getPage(pageNo);
pageCount.value = document.numPages;
const evidencePage = props.evidence?.page_no;
const preferred = manualPageOverride.value ?? evidencePage ?? currentPage.value ?? 1;
const targetPage = Math.min(Math.max(preferred, 1), document.numPages);
currentPage.value = targetPage;
const page = await document.getPage(targetPage);
const baseViewport = page.getViewport({ scale: 1 });
basePageSize.value = { width: baseViewport.width, height: baseViewport.height };
const viewport = page.getViewport({ scale: scale.value });
await nextTick();
if (!canvas.value) return;
@@ -41,46 +126,358 @@ const render = async () => {
const context = canvas.value.getContext('2d');
if (!context) return;
await page.render({ canvas: canvas.value, canvasContext: context, viewport }).promise;
const bbox = props.evidence?.bbox;
if (bbox) {
context.save();
context.fillStyle = 'rgba(250, 204, 21, 0.35)';
context.strokeStyle = 'rgba(202, 138, 4, 0.95)';
context.lineWidth = 2;
const x = bbox.x0 * viewport.width;
const y = bbox.y0 * viewport.height;
const width = (bbox.x1 - bbox.x0) * viewport.width;
const height = (bbox.y1 - bbox.y0) * viewport.height;
context.fillRect(x, y, width, height);
context.strokeRect(x, y, width, height);
context.restore();
}
const highlightRect = drawEvidenceHighlight(context, page, viewport, props.evidence);
emit('page-change', targetPage);
await nextTick();
refreshCanPan();
if (highlightRect) scrollHighlightIntoView(highlightRect);
} catch {
failed.value = true;
} finally {
loading.value = false;
await nextTick();
refreshCanPan();
}
};
const zoomIn = () => { scale.value = Math.min(scale.value + 0.25, 3); };
const zoomOut = () => { scale.value = Math.max(scale.value - 0.25, 0.75); };
const fitWidth = () => { scale.value = 1.75; };
/**
* 按后端确认的 highlight_quality 绘制 bbox;非法/缺失质量不绘制。
* @param context - canvas 2d 上下文
* @param page - PDF.js page(含 view / rotate)
* @param viewport - 当前缩放与旋转后的 viewport
* @param evidence - 当前证据 DTO
*/
function drawEvidenceHighlight(
context: CanvasRenderingContext2D,
page: { view: number[]; rotate?: number },
viewport: { width: number; height: number; convertToViewportRectangle: (rect: number[]) => number[] },
evidence: ShippingOrderReviewEvidence | null | undefined,
): { x: number; y: number; width: number; height: number } | null {
const quality = String(evidence?.highlight_quality || '');
const bbox = evidence?.highlight_bbox || evidence?.bbox;
if (!bbox || !DRAWABLE_QUALITIES.has(quality)) return null;
const rect = normalizedTopLeftBBoxToViewportRect(bbox, page, viewport);
if (!rect) return null;
context.save();
if (quality === 'candidate') {
context.fillStyle = 'rgba(249, 115, 22, 0.22)';
context.strokeStyle = 'rgba(194, 65, 12, 0.95)';
context.setLineDash([6, 4]);
} else if (quality === 'verified') {
context.fillStyle = 'rgba(250, 204, 21, 0.35)';
context.strokeStyle = 'rgba(202, 138, 4, 0.95)';
context.setLineDash([]);
} else {
context.fillStyle = 'rgba(244, 63, 94, 0.18)';
context.strokeStyle = 'rgba(225, 29, 72, 0.95)';
context.setLineDash([3, 3]);
}
context.lineWidth = 2;
context.fillRect(rect.x, rect.y, rect.width, rect.height);
context.strokeRect(rect.x, rect.y, rect.width, rect.height);
context.restore();
return rect;
}
watch(() => [props.src, props.evidence?.evidence_id, scale.value], () => { void render(); }, { immediate: true });
/**
* 内容溢出时按下拖拽平移滚动位置。
*/
const onPanStart = (event: PointerEvent) => {
if (event.button !== 0 || loading.value || failed.value) return;
const host = scrollHost.value;
if (!host) return;
refreshCanPan();
if (!canPan.value) return;
const target = event.target as HTMLElement | null;
if (!target?.closest('canvas')) return;
panning.value = true;
panOrigin = {
x: event.clientX,
y: event.clientY,
left: host.scrollLeft,
top: host.scrollTop,
};
host.setPointerCapture?.(event.pointerId);
window.addEventListener('pointermove', onPanMove);
window.addEventListener('pointerup', onPanEnd);
};
const onPanMove = (event: PointerEvent) => {
if (!panning.value || !panOrigin) return;
const host = scrollHost.value;
if (!host) return;
host.scrollLeft = panOrigin.left - (event.clientX - panOrigin.x);
host.scrollTop = panOrigin.top - (event.clientY - panOrigin.y);
};
const onPanEnd = (event?: PointerEvent) => {
const host = scrollHost.value;
if (host && event?.pointerId != null) {
try {
host.releasePointerCapture?.(event.pointerId);
} catch {
/* ignore */
}
}
panning.value = false;
panOrigin = null;
window.removeEventListener('pointermove', onPanMove);
window.removeEventListener('pointerup', onPanEnd);
};
/** 放大预览。 */
const zoomIn = () => { scale.value = Math.min(scale.value + 0.25, 3); };
/** 缩小预览。 */
const zoomOut = () => { scale.value = Math.max(scale.value - 0.25, 0.5); };
/** 重置为 100%。 */
const zoomActual = () => { scale.value = 1; };
/**
* 按滚动容器宽度适配(留边距)。
*/
const fitWidth = () => {
const host = scrollHost.value;
const base = basePageSize.value;
if (!host || !base?.width) {
scale.value = 1.25;
return;
}
const available = Math.max(120, host.clientWidth - 32);
scale.value = Math.min(3, Math.max(0.5, available / base.width));
};
/**
* 按滚动容器宽高适配整页。
*/
const fitPage = () => {
const host = scrollHost.value;
const base = basePageSize.value;
if (!host || !base?.width || !base.height) {
scale.value = 1;
return;
}
const availW = Math.max(120, host.clientWidth - 32);
const availH = Math.max(120, host.clientHeight - 32);
scale.value = Math.min(3, Math.max(0.5, Math.min(availW / base.width, availH / base.height)));
};
/**
* Ctrl/Cmd+滚轮缩放;Shift+滚轮横向滚动;普通滚轮纵向滚动。
* 使用非 passive 监听以便 preventDefault。
*/
const onPreviewWheel = (event: WheelEvent) => {
const host = scrollHost.value;
if (!host) return;
if (event.ctrlKey || event.metaKey) {
event.preventDefault();
const delta = event.deltaY > 0 ? -0.1 : 0.1;
scale.value = Math.min(3, Math.max(0.5, Number((scale.value + delta).toFixed(2))));
return;
}
if (event.shiftKey && Math.abs(event.deltaY) > Math.abs(event.deltaX)) {
event.preventDefault();
host.scrollLeft += event.deltaY;
}
};
/** 当前已绑定 wheel 的宿主,避免 ref 切换时解绑错节点。 */
let wheelHost: HTMLElement | null = null;
/**
* 绑定滚轮(passive:false),保证 Ctrl 缩放可拦截浏览器默认缩放。
*/
const bindWheel = () => {
const host = scrollHost.value;
if (!host || wheelHost === host) return;
if (wheelHost) {
wheelHost.removeEventListener('wheel', onPreviewWheel);
wheelHost = null;
}
host.addEventListener('wheel', onPreviewWheel, { passive: false });
wheelHost = host;
};
/** 解除滚轮绑定。 */
const unbindWheel = () => {
if (!wheelHost) return;
wheelHost.removeEventListener('wheel', onPreviewWheel);
wheelHost = null;
};
onMounted(() => {
void nextTick(() => bindWheel());
});
onBeforeUnmount(() => {
unbindWheel();
onPanEnd();
});
watch(scrollHost, () => {
void nextTick(() => bindWheel());
});
/**
* 跳转到输入页码。
*/
const jumpToPage = () => {
const page = Number.parseInt(String(pageJumpInput.value || ''), 10);
if (!Number.isFinite(page) || page < 1 || page > pageCount.value) return;
manualPageOverride.value = page;
pageJumpInput.value = '';
void render();
};
/**
* 手动翻到上一页。
*/
const prevPage = () => {
if (currentPage.value <= 1) return;
manualPageOverride.value = currentPage.value - 1;
void render();
};
/**
* 手动翻到下一页。
*/
const nextPage = () => {
if (currentPage.value >= pageCount.value) return;
manualPageOverride.value = currentPage.value + 1;
void render();
};
watch(
() => [props.src, props.evidence?.evidence_id] as const,
() => {
manualPageOverride.value = null;
},
);
watch(
() => [
props.src,
props.evidence?.evidence_id,
props.evidence?.page_no,
props.evidence?.highlight_quality,
props.evidence?.highlight_bbox,
scale.value,
manualPageOverride.value,
] as const,
() => { void render(); },
{ immediate: true },
);
</script>
<template>
<div class="relative flex min-h-[180px] flex-1 flex-col overflow-hidden bg-slate-100 xl:min-h-[360px] dark:bg-slate-950">
<div class="flex shrink-0 items-center justify-end gap-1 border-b border-slate-200 bg-white/95 px-2 py-1.5 text-xs dark:border-slate-800 dark:bg-slate-900/95">
<button type="button" class="rounded border px-2 py-1 hover:bg-slate-50 dark:border-slate-700 dark:hover:bg-slate-800" @click="zoomOut">−</button>
<button type="button" class="min-w-12 rounded border px-2 py-1 hover:bg-slate-50 dark:border-slate-700 dark:hover:bg-slate-800" @click="fitWidth">{{ zoomLabel }}</button>
<button type="button" class="rounded border px-2 py-1 hover:bg-slate-50 dark:border-slate-700 dark:hover:bg-slate-800" @click="zoomIn">+</button>
<div
class="relative flex flex-1 flex-col overflow-hidden bg-slate-100 dark:bg-slate-950"
:class="drawerMode ? 'min-h-[200px]' : 'min-h-[180px] xl:min-h-[360px]'"
:data-drawer-mode="drawerMode ? 'true' : 'false'"
>
<div class="flex shrink-0 items-center justify-between gap-1 border-b border-slate-200 bg-white/95 px-2 py-1.5 text-xs dark:border-slate-800 dark:bg-slate-900/95">
<div class="flex items-center gap-1">
<button
type="button"
class="rounded border px-2 py-1 hover:bg-slate-50 disabled:opacity-40 dark:border-slate-700 dark:hover:bg-slate-800"
data-testid="review-pdf-prev-page"
:disabled="currentPage <= 1"
@click="prevPage"
>‹</button>
<span class="min-w-16 text-center text-slate-600 dark:text-slate-300" data-testid="review-pdf-page-label">
{{ currentPage }} / {{ pageCount || '—' }}
</span>
<button
type="button"
class="rounded border px-2 py-1 hover:bg-slate-50 disabled:opacity-40 dark:border-slate-700 dark:hover:bg-slate-800"
data-testid="review-pdf-next-page"
:disabled="!pageCount || currentPage >= pageCount"
@click="nextPage"
>›</button>
<form class="ml-1 flex items-center gap-1" @submit.prevent="jumpToPage">
<input
v-model="pageJumpInput"
type="number"
min="1"
:max="pageCount || undefined"
class="w-12 rounded border border-slate-300 px-1 py-0.5 text-center dark:border-slate-700 dark:bg-slate-950"
data-testid="review-pdf-page-jump"
:aria-label="t('chat.shippingOrderReview.previewZoom.jumpPage')"
>
<button
type="submit"
class="rounded border px-1.5 py-0.5 hover:bg-slate-50 dark:border-slate-700 dark:hover:bg-slate-800"
data-testid="review-pdf-page-jump-go"
>{{ t('chat.shippingOrderReview.previewZoom.go') }}</button>
</form>
</div>
<div class="flex flex-wrap items-center gap-1">
<button
type="button"
class="rounded border px-1.5 py-1 hover:bg-slate-50 dark:border-slate-700 dark:hover:bg-slate-800"
data-testid="review-pdf-zoom-fit-width"
:title="t('chat.shippingOrderReview.previewZoom.fitWidth')"
@click="fitWidth"
>{{ t('chat.shippingOrderReview.previewZoom.fitWidthShort') }}</button>
<button
type="button"
class="rounded border px-1.5 py-1 hover:bg-slate-50 dark:border-slate-700 dark:hover:bg-slate-800"
data-testid="review-pdf-zoom-fit-page"
:title="t('chat.shippingOrderReview.previewZoom.fitPage')"
@click="fitPage"
>{{ t('chat.shippingOrderReview.previewZoom.fitPageShort') }}</button>
<button
type="button"
class="rounded border px-1.5 py-1 hover:bg-slate-50 dark:border-slate-700 dark:hover:bg-slate-800"
data-testid="review-pdf-zoom-actual"
:title="t('chat.shippingOrderReview.previewZoom.actual')"
@click="zoomActual"
>100%</button>
<button type="button" class="rounded border px-2 py-1 hover:bg-slate-50 dark:border-slate-700 dark:hover:bg-slate-800" data-testid="review-pdf-zoom-out" @click="zoomOut">−</button>
<span class="min-w-12 text-center text-slate-600 dark:text-slate-300" data-testid="review-pdf-zoom-label">{{ zoomLabel }}</span>
<button type="button" class="rounded border px-2 py-1 hover:bg-slate-50 dark:border-slate-700 dark:hover:bg-slate-800" data-testid="review-pdf-zoom-in" @click="zoomIn">+</button>
</div>
</div>
<div class="relative flex min-h-0 flex-1 items-start justify-center overflow-auto p-4">
<!-- Keep the canvas mounted while PDF.js is loading; otherwise nextTick cannot obtain a render target. -->
<canvas ref="canvas" :aria-label="title" class="bg-white shadow" :class="{ invisible: loading || failed }" />
<span v-if="loading" class="absolute text-sm text-slate-500">{{ loadingText }}</span>
<span v-else-if="failed" class="absolute text-sm text-rose-600">{{ unavailableText }}</span>
<div
v-if="showCandidateBanner || showVerifiedLegend"
class="flex shrink-0 flex-wrap items-center gap-2 border-b border-slate-200 bg-white/90 px-2 py-1 text-[11px] dark:border-slate-800 dark:bg-slate-900/90"
data-testid="review-pdf-highlight-legend"
>
<span
v-if="showVerifiedLegend"
class="inline-flex items-center gap-1 text-amber-800 dark:text-amber-100"
>
<span class="inline-block h-2.5 w-4 border-2 border-amber-500 bg-amber-300/50" />
{{ t('chat.shippingOrderReview.highlightLegend.verified') }}
</span>
<span
v-if="showCandidateBanner"
class="inline-flex items-center gap-1 font-medium text-orange-800 dark:text-orange-100"
data-testid="review-pdf-candidate-tip"
>
<span class="inline-block h-2.5 w-4 border-2 border-dashed border-orange-600 bg-orange-300/40" />
{{ t('chat.shippingOrderReview.highlightLegend.candidate') }}
</span>
</div>
<div
ref="scrollHost"
class="relative flex min-h-0 flex-1 items-start justify-center overflow-auto p-4"
data-testid="review-pdf-scroll-host"
:data-can-pan="canPan ? 'true' : 'false'"
:data-panning="panning ? 'true' : 'false'"
:class="canPan ? (panning ? 'cursor-grabbing' : 'cursor-grab') : ''"
@pointerdown="onPanStart"
>
<!-- Keep the canvas mounted while PDF.js is loading; otherwise nextTick cannot obtain a render target. -->
<canvas ref="canvas" :aria-label="title" class="bg-white shadow select-none" :class="{ invisible: loading || failed }" />
<span v-if="loading" class="absolute text-sm text-slate-500">{{ loadingText }}</span>
<span v-else-if="failed" class="absolute text-sm text-rose-600">{{ unavailableText }}</span>
<div
v-else-if="showCandidateBanner && !loading && !failed"
class="pointer-events-none absolute left-4 top-4 max-w-[min(100%,18rem)] rounded border border-dashed border-orange-600 bg-orange-50/95 px-2 py-1 text-[11px] font-medium text-orange-900 shadow-sm dark:border-orange-500 dark:bg-orange-950/90 dark:text-orange-100"
data-testid="review-pdf-candidate-canvas-tip"
>
{{ t('chat.shippingOrderReview.highlightLegend.candidate') }}
</div>
</div>
</div>
</template>
@@ -0,0 +1,229 @@
<!--
features/chat/components/shipping-review/ReviewDuplicatePanel.vue
用途:复核工作台建单前重复订单对比与裁决区。
依赖:vue-i18n、shipping.api 重复裁决/刷新、useMessage。
逻辑:needs_adjudication 时展示匹配任务与动作;裁决成功后 emit refreshed。
-->
<script setup lang="ts">
import { computed, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { BusinessError, resolveLocalizedErrorMessage } from '@/shared/api/client';
import { useMessage } from '@/shared/composables/useMessage';
import {
refreshWorkspaceShippingOrderReviewDuplicate,
resolveWorkspaceShippingOrderReviewDuplicate,
} from '@/features/chat/api/shipping.api';
import type {
ShippingDuplicateAction,
ShippingOrderReviewDuplicate,
} from '@/features/chat/types/shipping.api.types';
const props = defineProps<{
caseNo: string;
duplicate: ShippingOrderReviewDuplicate | null | undefined;
editable: boolean;
canForceCreate: boolean;
}>();
const emit = defineEmits<{
refreshed: [];
}>();
const { t, te } = useI18n();
const msg = useMessage();
const busy = ref(false);
const forceReason = ref('');
const selectedAction = ref<ShippingDuplicateAction | ''>('');
const visible = computed(() => Boolean(props.duplicate?.needs_adjudication || props.duplicate?.blocking));
const allowed = computed(() => new Set(props.duplicate?.allowed_actions || []));
const primaryMatch = computed(() => props.duplicate?.matches?.[0] || null);
const resolved = computed(() => Boolean(props.duplicate?.resolved));
/**
* 重复状态本地化文案。
*/
const statusLabel = computed(() => {
const status = String(props.duplicate?.status || '').trim();
const key = `chat.shippingOrderReview.duplicate.status.${status}`;
if (status && te(key)) return t(key);
if (props.duplicate?.blocking) return t('chat.shippingNoticeDuplicateNeedsResolution');
return t('chat.shippingOrderReview.duplicate.status.none');
});
/**
* 提交重复裁决。
*/
async function resolve(action: ShippingDuplicateAction) {
if (!props.editable || !props.caseNo || busy.value) return;
if (!allowed.value.has(action)) {
msg.warning(t('chat.shippingNoticeDuplicateActionUnavailable'));
return;
}
const target = String(primaryMatch.value?.task_no || '').trim();
if (!target) {
msg.warning(t('chat.shippingNoticeDuplicateActionUnavailable'));
return;
}
if (action === 'force_create') {
if (!props.canForceCreate) {
msg.warning(t('chat.shippingNoticeDuplicateForceForbidden'));
return;
}
if (!forceReason.value.trim()) {
msg.warning(t('chat.shippingNoticeDuplicateReasonRequired'));
return;
}
}
busy.value = true;
selectedAction.value = action;
try {
await resolveWorkspaceShippingOrderReviewDuplicate(props.caseNo, {
action,
target_task_no: target,
reason: action === 'force_create' ? forceReason.value.trim() : undefined,
});
forceReason.value = '';
msg.success(t('chat.shippingOrderReview.duplicate.resolveSuccess'));
emit('refreshed');
} catch (error: unknown) {
const message = error instanceof BusinessError
? resolveLocalizedErrorMessage(error.code, error.message)
: (error instanceof Error ? error.message : t('chat.shippingOrderReview.duplicate.resolveFailed'));
msg.warning(message);
} finally {
busy.value = false;
selectedAction.value = '';
}
}
/**
* 重新检测重复(清除陈旧决议)。
*/
async function onRefresh() {
if (!props.editable || !props.caseNo || busy.value) return;
busy.value = true;
try {
await refreshWorkspaceShippingOrderReviewDuplicate(props.caseNo);
msg.success(t('chat.shippingOrderReview.duplicate.refreshDone'));
emit('refreshed');
} catch (error: unknown) {
const message = error instanceof BusinessError
? resolveLocalizedErrorMessage(error.code, error.message)
: (error instanceof Error ? error.message : t('chat.shippingOrderReview.duplicate.refreshFailed'));
msg.warning(message);
} finally {
busy.value = false;
}
}
</script>
<template>
<section
v-if="visible"
class="rounded-xl border border-amber-200 bg-amber-50/70 p-3 shadow-sm dark:border-amber-900 dark:bg-amber-950/40"
data-testid="review-duplicate-panel"
>
<header class="flex flex-wrap items-start justify-between gap-2">
<div>
<h2 class="text-sm font-semibold text-amber-950 dark:text-amber-50">
{{ t('chat.shippingOrderReview.duplicate.title') }}
</h2>
<p class="mt-0.5 text-xs text-amber-900 dark:text-amber-200">
{{ t('chat.shippingOrderReview.duplicate.subtitle') }}
</p>
</div>
<span
class="rounded-full px-2.5 py-1 text-xs font-medium"
:class="resolved
? 'bg-emerald-100 text-emerald-800 dark:bg-emerald-950 dark:text-emerald-100'
: 'bg-amber-100 text-amber-900 dark:bg-amber-950 dark:text-amber-100'"
data-testid="review-duplicate-badge"
>
{{ resolved ? t('chat.shippingOrderReview.duplicate.resolvedBadge') : statusLabel }}
</span>
</header>
<div
v-if="primaryMatch"
class="mt-2 rounded-lg border border-amber-200 bg-white/90 px-2.5 py-2 text-xs text-secondary dark:border-amber-900 dark:bg-slate-900"
data-testid="review-duplicate-match"
>
<div class="font-medium text-primary">
{{ t('chat.shippingNoticeDuplicateMatchTask', { taskNo: primaryMatch.task_no }) }}
</div>
<div class="mt-0.5 text-muted">
{{ t('chat.shippingNoticeDuplicateMatchStatus', { status: primaryMatch.process_status }) }}
</div>
<div v-if="primaryMatch.matched_fields?.length" class="mt-0.5 text-muted">
{{ t('chat.shippingNoticeDuplicateMatchFields', { fields: primaryMatch.matched_fields.join(', ') }) }}
</div>
</div>
<p v-if="duplicate?.resolution?.action" class="mt-2 text-xs text-secondary">
{{ t('chat.shippingOrderReview.duplicate.resolutionLabel', { action: duplicate.resolution.action }) }}
<span v-if="duplicate.resolution.target_task_no" class="font-mono">
→ {{ duplicate.resolution.target_task_no }}
</span>
</p>
<div v-if="editable && duplicate?.needs_adjudication" class="mt-3 space-y-2">
<div class="flex flex-wrap gap-2">
<button
v-if="allowed.has('open_existing')"
type="button"
class="rounded-xl border border-default bg-surface px-3 py-1.5 text-sm text-secondary hover:bg-surface-soft disabled:opacity-60"
data-testid="review-duplicate-open-existing"
:disabled="busy"
@click="resolve('open_existing')"
>
{{ t('chat.shippingNoticeDuplicateOpenExisting') }}
</button>
<button
v-if="allowed.has('create_revision')"
type="button"
class="rounded-xl border border-amber-300 bg-amber-100 px-3 py-1.5 text-sm font-medium text-amber-950 hover:bg-amber-200 disabled:opacity-60 dark:border-amber-800 dark:bg-amber-950 dark:text-amber-100"
data-testid="review-duplicate-create-revision"
:disabled="busy"
@click="resolve('create_revision')"
>
{{ t('chat.shippingNoticeDuplicateCreateRevision') }}
</button>
</div>
<div v-if="allowed.has('force_create') && canForceCreate" class="space-y-1.5">
<input
v-model="forceReason"
type="text"
class="w-full rounded border border-default bg-surface px-2 py-1.5 text-xs"
data-testid="review-duplicate-force-reason"
:placeholder="t('chat.shippingNoticeDuplicateReasonPlaceholder')"
:disabled="busy"
>
<button
type="button"
class="rounded-xl bg-rose-600 px-3 py-1.5 text-sm font-medium text-white hover:bg-rose-700 disabled:opacity-60"
data-testid="review-duplicate-force-create"
:disabled="busy || !forceReason.trim()"
@click="resolve('force_create')"
>
{{ selectedAction === 'force_create' && busy
? t('chat.shippingOrderReview.duplicate.resolving')
: t('chat.shippingNoticeDuplicateForceCreate') }}
</button>
</div>
</div>
<div v-if="editable" class="mt-3">
<button
type="button"
class="text-[11px] text-secondary underline-offset-2 hover:underline disabled:opacity-60"
data-testid="review-duplicate-refresh"
:disabled="busy"
@click="onRefresh"
>
{{ busy ? t('chat.shippingOrderReview.duplicate.refreshing') : t('chat.shippingOrderReview.duplicate.refresh') }}
</button>
</div>
</section>
</template>
@@ -0,0 +1,225 @@
<!--
features/chat/components/shipping-review/ReviewFieldConflictPanel.vue
用途:复核工作台建单前字段冲突集中裁决区(采用候选值 / 手工值)。
依赖:vue-i18n、shipping.api.resolveWorkspaceShippingOrderReviewFieldConflict、useMessage。
逻辑:展示 Case.field_conflicts;裁决成功后 emit refreshed;可 emit focus-conflict 定位证据。
-->
<script setup lang="ts">
import { computed, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { BusinessError, resolveLocalizedErrorMessage } from '@/shared/api/client';
import { useMessage } from '@/shared/composables/useMessage';
import { resolveWorkspaceShippingOrderReviewFieldConflict } from '@/features/chat/api/shipping.api';
import type { ShippingOrderReviewFieldConflict } from '@/features/chat/types/shipping.api.types';
const props = defineProps<{
caseNo: string;
draftVersion: number | null | undefined;
conflicts: ShippingOrderReviewFieldConflict[] | null | undefined;
editable: boolean;
}>();
const emit = defineEmits<{
refreshed: [];
'focus-conflict': [payload: { fieldCode: string; lineIndex: number | null; lineKey: string | null }];
}>();
const { t, te } = useI18n();
const msg = useMessage();
const resolvingKey = ref<string | null>(null);
const customOpenKey = ref<string | null>(null);
const customValue = ref('');
const openConflicts = computed(() => props.conflicts || []);
/**
* 字段编码本地化标签(无文案时回退 field_code)。
*/
function fieldLabel(fieldCode: string): string {
const key = `chat.shippingOrderReview.fieldConflict.fields.${fieldCode}`;
return te(key) ? t(key) : fieldCode;
}
/**
* 冲突原因本地化。
*/
function reasonLabel(reason: string): string {
const key = `chat.shippingOrderReview.fieldConflict.reasons.${reason}`;
return te(key) ? t(key) : reason;
}
/**
* 定位冲突字段到草稿/证据区。
*/
function onFocus(conflict: ShippingOrderReviewFieldConflict) {
emit('focus-conflict', {
fieldCode: conflict.field_code,
lineIndex: conflict.line_index ?? null,
lineKey: conflict.line_key ?? null,
});
}
/**
* 采用某一候选值。
*/
async function adoptOption(conflict: ShippingOrderReviewFieldConflict, optionIndex: number) {
if (!props.editable || !props.caseNo || props.draftVersion == null || resolvingKey.value) return;
resolvingKey.value = conflict.conflict_key;
try {
await resolveWorkspaceShippingOrderReviewFieldConflict(props.caseNo, conflict.conflict_key, {
resolution: 'adopt_option',
option_index: optionIndex,
expected_draft_version: props.draftVersion,
reason: t('chat.shippingOrderReview.fieldConflict.resolveReason'),
});
msg.success(t('chat.shippingOrderReview.fieldConflict.resolveSuccess'));
emit('refreshed');
} catch (error: unknown) {
const message = error instanceof BusinessError
? resolveLocalizedErrorMessage(error.code, error.message)
: (error instanceof Error ? error.message : t('chat.shippingOrderReview.fieldConflict.resolveFailed'));
msg.warning(message);
} finally {
resolvingKey.value = null;
}
}
/**
* 展开/收起手工值输入。
*/
function toggleCustom(conflictKey: string) {
if (customOpenKey.value === conflictKey) {
customOpenKey.value = null;
customValue.value = '';
return;
}
customOpenKey.value = conflictKey;
customValue.value = '';
}
/**
* 提交手工值裁决。
*/
async function submitCustom(conflict: ShippingOrderReviewFieldConflict) {
const value = customValue.value.trim();
if (!value || !props.editable || props.draftVersion == null || resolvingKey.value) return;
resolvingKey.value = conflict.conflict_key;
try {
await resolveWorkspaceShippingOrderReviewFieldConflict(props.caseNo, conflict.conflict_key, {
resolution: 'custom',
custom_value: value,
expected_draft_version: props.draftVersion,
reason: t('chat.shippingOrderReview.fieldConflict.resolveReason'),
});
customOpenKey.value = null;
customValue.value = '';
msg.success(t('chat.shippingOrderReview.fieldConflict.resolveSuccess'));
emit('refreshed');
} catch (error: unknown) {
const message = error instanceof BusinessError
? resolveLocalizedErrorMessage(error.code, error.message)
: (error instanceof Error ? error.message : t('chat.shippingOrderReview.fieldConflict.resolveFailed'));
msg.warning(message);
} finally {
resolvingKey.value = null;
}
}
</script>
<template>
<section
v-if="openConflicts.length"
class="rounded-xl border border-rose-200 bg-rose-50/70 p-3 shadow-sm dark:border-rose-900 dark:bg-rose-950/40"
data-testid="review-field-conflict-panel"
>
<header class="flex flex-wrap items-start justify-between gap-2">
<div>
<h2 class="text-sm font-semibold text-rose-950 dark:text-rose-50">
{{ t('chat.shippingOrderReview.fieldConflict.title', { count: openConflicts.length }) }}
</h2>
<p class="mt-0.5 text-xs text-rose-800 dark:text-rose-200">
{{ t('chat.shippingOrderReview.fieldConflict.subtitle') }}
</p>
</div>
</header>
<ul class="mt-3 space-y-2">
<li
v-for="conflict in openConflicts"
:key="conflict.conflict_key"
class="rounded-lg border border-rose-200 bg-white/95 px-2.5 py-2 dark:border-rose-900 dark:bg-slate-900"
:data-testid="`review-field-conflict-${conflict.conflict_key}`"
>
<div class="flex flex-wrap items-center justify-between gap-2">
<div class="text-xs font-medium text-rose-950 dark:text-rose-50">
<span v-if="conflict.line_index != null">#{{ conflict.line_index + 1 }} · </span>
<span class="font-mono">{{ fieldLabel(conflict.field_code) }}</span>
</div>
<button
type="button"
class="text-[11px] text-primary underline-offset-2 hover:underline"
data-testid="review-field-conflict-focus"
@click="onFocus(conflict)"
>
{{ t('chat.shippingOrderReview.fieldConflict.focusEvidence') }}
</button>
</div>
<p class="mt-1 text-[11px] text-muted">{{ reasonLabel(conflict.reason) }}</p>
<div class="mt-2 grid gap-1 text-[11px] text-secondary sm:grid-cols-2">
<div
v-for="(option, idx) in conflict.options"
:key="`${conflict.conflict_key}-${idx}`"
class="rounded border border-default bg-surface-soft px-2 py-1.5"
>
<div class="text-muted">
{{ t('chat.shippingOrderReview.fieldConflict.optionLabel', { index: idx + 1 }) }}
<span v-if="option.sources?.length" class="ml-1">({{ option.sources.join(', ') }})</span>
</div>
<div class="mt-0.5 font-mono text-primary">{{ option.display_value || option.value_key || '—' }}</div>
<button
v-if="editable"
type="button"
class="mt-1.5 rounded border border-rose-300 bg-rose-100 px-2 py-0.5 text-[11px] font-medium text-rose-900 hover:bg-rose-200 disabled:opacity-50 dark:border-rose-800 dark:bg-rose-950 dark:text-rose-100"
:disabled="resolvingKey != null"
:data-testid="`review-field-conflict-adopt-${idx}`"
@click="adoptOption(conflict, idx)"
>
{{ t('chat.shippingOrderReview.fieldConflict.adoptOption') }}
</button>
</div>
</div>
<div v-if="editable" class="mt-2">
<button
type="button"
class="text-[11px] text-secondary underline-offset-2 hover:underline"
:disabled="resolvingKey != null"
data-testid="review-field-conflict-custom-toggle"
@click="toggleCustom(conflict.conflict_key)"
>
{{ t('chat.shippingOrderReview.fieldConflict.customValue') }}
</button>
<div v-if="customOpenKey === conflict.conflict_key" class="mt-1.5 flex flex-wrap gap-2">
<input
v-model="customValue"
type="text"
class="min-w-[10rem] flex-1 rounded border border-default bg-surface px-2 py-1 text-xs"
data-testid="review-field-conflict-custom-input"
:placeholder="t('chat.shippingOrderReview.fieldConflict.customPlaceholder')"
>
<button
type="button"
class="rounded bg-primary px-2.5 py-1 text-xs font-medium text-on-primary disabled:opacity-50"
:disabled="!customValue.trim() || resolvingKey != null"
data-testid="review-field-conflict-custom-submit"
@click="submitCustom(conflict)"
>
{{ t('chat.shippingOrderReview.fieldConflict.submitCustom') }}
</button>
</div>
</div>
</li>
</ul>
</section>
</template>
@@ -0,0 +1,117 @@
/**
* features/chat/components/shipping-review/ReviewInventoryCandidatesPanel.spec.ts
* 用途:验证库存路由面板在服务端刷新后重置本地表单,并展示规则码/源编码以满足可追溯。
* 依赖:Vitest、Vue Test Utils、vue-i18n、chat 文案。
* 逻辑:构造带技术编码的行投影;断言显示名+编码与命中规则;两列标签卡可扫描;
* 变更候选后本地勾选被重置。
*/
import { flushPromises, mount } from '@vue/test-utils';
import { createI18n } from 'vue-i18n';
import { describe, expect, it } from 'vitest';
import chatZhCn from '@/locales/zh-CN/chat.json';
import ReviewInventoryCandidatesPanel from './ReviewInventoryCandidatesPanel.vue';
import type { ShippingOrderReviewBuildEligibilityLineProjection } from '@/features/chat/types/shipping.api.types';
const i18n = createI18n({
legacy: false,
locale: 'zh-CN',
messages: { 'zh-CN': { chat: chatZhCn } },
});
function line(
overrides: Partial<ShippingOrderReviewBuildEligibilityLineProjection> = {},
): ShippingOrderReviewBuildEligibilityLineProjection {
return {
line_key: 'L1',
line_index: 0,
candidate_inventory_source_codes: ['DSV360_AWSDU'],
raw_rule_source_codes: ['DSV360_AWSSG'],
unavailable_source_codes: ['DSV360_AWSSG'],
unavailable_reasons: { DSV360_AWSSG: 'source_disabled' },
rule_suggestion_source_codes: ['DSV360_AWSDU'],
matched_rules: [{ rule_code: 'ROUTE_HINT_AWSSG', version: 1 }],
rule_versions: [{ rule_code: 'INVENTORY_RULE_18', version: 18 }],
manual_reason: 'initial reason',
...overrides,
};
}
describe('ReviewInventoryCandidatesPanel', () => {
it('shows source labels with codes and matched rule codes for traceability', () => {
const wrapper = mount(ReviewInventoryCandidatesPanel, {
props: {
lines: [line()],
sourceLabels: {
DSV360_AWSDU: '杜塞尔多夫仓',
DSV360_AWSSG: '新加坡仓',
},
editable: true,
},
global: { plugins: [i18n] },
});
const text = wrapper.text();
// 显示名与稳定编码同时可见,满足复核线框「命中规则 / 库存源」可追溯。
// 显示名与稳定编码必须同时可见,避免仅见名称无法对审计。
expect(text).toContain('杜塞尔多夫仓');
expect(text).toContain('新加坡仓');
expect(text).toContain('DSV360_AWSDU');
expect(text).toContain('DSV360_AWSSG');
expect(text).toContain('ROUTE_HINT_AWSSG');
expect(text).toContain('命中规则');
expect(text).toContain('库存源未启用');
expect(wrapper.find('[data-testid="review-inventory-unavailable-sources"]').text()).toContain('DSV360_AWSSG');
expect(
wrapper.find('[data-testid="review-inventory-unavailable-sources"] [data-source-code="DSV360_AWSSG"]').exists(),
).toBe(true);
// 不可用候选用标签卡而非行内长串,便于多源扫描。
expect(wrapper.find('[data-testid="review-inventory-unavailable-sources"] .grid').exists()).toBe(true);
});
it('always shows monospace source_code on inventory hint even when a business name exists', () => {
const wrapper = mount(ReviewInventoryCandidatesPanel, {
props: {
lines: [line({ inventory_source_hint: 'DSV360_AWSSG' })],
sourceLabels: { DSV360_AWSSG: '新加坡仓' },
editable: false,
},
global: { plugins: [i18n] },
});
const hintCode = wrapper.get('[data-testid="review-inventory-hint-source-code"]');
expect(hintCode.text()).toBe('DSV360_AWSSG');
expect(hintCode.attributes('data-source-code')).toBe('DSV360_AWSSG');
expect(wrapper.text()).toContain('新加坡仓');
});
it('resets local form when server candidates change for the same line_key', async () => {
const wrapper = mount(ReviewInventoryCandidatesPanel, {
props: {
lines: [line({ candidate_inventory_source_codes: ['DSV360_AWSDU'], manual_reason: 'old' })],
sourceLabels: { DSV360_AWSDU: '杜塞尔多夫仓', DSV360_AWSBI: '伯明翰仓' },
editable: true,
},
global: { plugins: [i18n] },
});
const textarea = wrapper.get('textarea');
await textarea.setValue('user typed reason');
expect((textarea.element as HTMLTextAreaElement).value).toBe('user typed reason');
await wrapper.setProps({
lines: [line({
candidate_inventory_source_codes: ['DSV360_AWSBI'],
manual_reason: 'server refreshed',
raw_rule_source_codes: ['DSV360_AWSBI'],
unavailable_source_codes: [],
rule_suggestion_source_codes: ['DSV360_AWSBI'],
matched_rules: [{ rule_code: 'ROUTE_HINT_AWSBI', version: 2 }],
})],
});
await flushPromises();
const refreshed = wrapper.get('textarea');
expect((refreshed.element as HTMLTextAreaElement).value).toBe('server refreshed');
expect(wrapper.text()).toContain('伯明翰仓');
expect(wrapper.text()).toContain('DSV360_AWSBI');
expect(wrapper.text()).toContain('ROUTE_HINT_AWSBI');
});
});
@@ -1,11 +1,13 @@
<!--
features/chat/components/shipping-review/ReviewInventoryCandidatesPanel.vue
用途:为库存路由未决的明细行提供多选候选源与强制原因的人工提交表单。
用途:库存路由恢复面板——展示规则建议/不可用源,支持 reroute、采纳建议、保留人工与多选提交。
依赖:vue-i18n、ShippingOrderReviewBuildEligibilityLineProjection 类型。
逻辑:规则候选优先;零候选时回退到已启用库存源列表;emit submit 由 composable 写 API。
逻辑:接收 recovery / suggestion_pending 行;规则候选优先,零候选回退已启用源;
服务端行指纹变化时重置本地表单;业务名与等宽 source_code 始终可见;
原始/不可用/建议候选用两列标签卡降低密度;emit 由 composable 写 API。
-->
<script setup lang="ts">
import { reactive } from 'vue';
import { reactive, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import type { ShippingOrderReviewBuildEligibilityLineProjection } from '@/features/chat/types/shipping.api.types';
@@ -13,12 +15,17 @@ const props = defineProps<{
lines: ShippingOrderReviewBuildEligibilityLineProjection[];
/** 已启用库存源;规则零候选时作为可选列表 */
enabledSourceCodes?: string[];
/** 库存源编码 → 业务显示名;提交仍使用编码 */
sourceLabels?: Record<string, string>;
editable?: boolean;
saving?: boolean;
}>();
const emit = defineEmits<{
(e: 'submit', payload: { lineKey: string; sourceCodes: string[]; reason: string }): void;
(e: 'reroute', lineKey?: string): void;
(e: 'adopt', payload: { lineKey: string; reason?: string }): void;
(e: 'keep', payload: { lineKey: string; reason?: string }): void;
}>();
const { t, te } = useI18n();
@@ -39,6 +46,48 @@ function selectableCodes(line: ShippingOrderReviewBuildEligibilityLineProjection
.filter(Boolean);
}
/**
* 规则建议可用源编码。
*/
function ruleSuggestionCodes(line: ShippingOrderReviewBuildEligibilityLineProjection): string[] {
return line.rule_suggestion?.source_codes
|| line.rule_suggestion_source_codes
|| line.rule_source_codes
|| [];
}
/**
* 服务端行投影指纹;变化时用于重置本地表单,避免提交过期候选/原因。
*/
function lineServerFingerprint(line: ShippingOrderReviewBuildEligibilityLineProjection): string {
return JSON.stringify({
line_key: String(line.line_key || line.line_index || ''),
candidates: (line.candidate_inventory_source_codes || []).map(String),
reason: String(line.manual_reason || ''),
suggestion_pending: Boolean(line.suggestion_pending),
rule: ruleSuggestionCodes(line).map(String),
unavailable: (line.unavailable_source_codes || []).map(String),
raw: (line.raw_rule_source_codes || []).map(String),
block_reason: String(line.block_reason || ''),
});
}
/**
* 清空本地表单缓存(下次 getForm 按服务端投影重新初始化)。
*/
function resetFormState() {
for (const key of Object.keys(formState)) {
delete formState[key];
}
}
watch(
() => (props.lines || []).map(lineServerFingerprint).join('\n'),
() => {
resetFormState();
},
);
/**
* 获取或初始化某行的表单状态。
*/
@@ -71,7 +120,44 @@ function blockReasonLabel(reason?: string | null): string {
const normalized = String(reason || '').trim();
if (!normalized) return '';
const key = `chat.shippingOrderReview.buildEligibility.blockReasons.${normalized}`;
return te(key) ? t(key) : normalized;
return te(key) ? t(key) : t('chat.shippingOrderReview.buildEligibility.blockReasons.unknown');
}
/**
* 库存源业务显示名(不含编码);编码由 sourceCodeLabel 单独展示,避免仅见名称无法对审计。
*/
function sourceBusinessName(code: string): string {
const normalized = String(code || '').trim().toUpperCase();
if (!normalized) return t('chat.shippingOrderReview.inventoryRouting.sourceUnnamed');
const label = String(props.sourceLabels?.[normalized] || props.sourceLabels?.[code] || '').trim();
if (label && label.toUpperCase() !== normalized) return label;
return t('chat.shippingOrderReview.inventoryRouting.sourceUnnamed');
}
/**
* 稳定源编码(始终可见,等宽)。
*/
function sourceCodeLabel(code: string): string {
return String(code || '').trim().toUpperCase();
}
/**
* 命中规则编码列表(rule_code 优先)。
*/
function matchedRuleCodes(line: ShippingOrderReviewBuildEligibilityLineProjection): string[] {
const fromRules = (line.matched_rules || [])
.map((item) => String(item.rule_code || '').trim())
.filter(Boolean);
if (fromRules.length) return [...new Set(fromRules)];
return (line.matched_rule_ids || []).map((id) => String(id));
}
/** 展示规则命中但被运行时配置过滤的具体原因。 */
function unavailableReasonLabel(line: ShippingOrderReviewBuildEligibilityLineProjection, code: string): string {
const reason = String(line.unavailable_reasons?.[code] || '').trim();
if (!reason) return t('chat.shippingOrderReview.inventoryRouting.unavailableReasonUnknown');
const key = `chat.shippingOrderReview.inventoryRouting.unavailableReasons.${reason}`;
return te(key) ? t(key) : t('chat.shippingOrderReview.inventoryRouting.unavailableReasonUnknown');
}
/**
@@ -87,6 +173,34 @@ function submitLine(line: ShippingOrderReviewBuildEligibilityLineProjection) {
reason: form.reason.trim(),
});
}
/**
* 触发行级重新匹配路由。
*/
function rerouteLine(line: ShippingOrderReviewBuildEligibilityLineProjection) {
const lineKey = String(line.line_key || '').trim();
emit('reroute', lineKey || undefined);
}
/**
* 采纳待决规则建议。
*/
function adoptLine(line: ShippingOrderReviewBuildEligibilityLineProjection) {
const lineKey = String(line.line_key || '').trim();
if (!lineKey) return;
const reason = getForm(line).reason.trim();
emit('adopt', { lineKey, ...(reason ? { reason } : {}) });
}
/**
* 保留当前人工路由结果。
*/
function keepLine(line: ShippingOrderReviewBuildEligibilityLineProjection) {
const lineKey = String(line.line_key || '').trim();
if (!lineKey) return;
const reason = getForm(line).reason.trim();
emit('keep', { lineKey, ...(reason ? { reason } : {}) });
}
</script>
<template>
@@ -100,6 +214,9 @@ function submitLine(line: ShippingOrderReviewBuildEligibilityLineProjection) {
<p class="mt-0.5 text-xs text-slate-600 dark:text-slate-400">
{{ t('chat.shippingOrderReview.inventoryCandidates.subtitle') }}
</p>
<p class="mt-1 text-xs text-slate-500 dark:text-slate-400">
{{ t('chat.shippingOrderReview.inventoryRouting.rerouteHint') }}
</p>
</header>
<article
@@ -111,7 +228,7 @@ function submitLine(line: ShippingOrderReviewBuildEligibilityLineProjection) {
<div class="flex flex-wrap items-center justify-between gap-2 text-sm">
<span class="font-medium">
{{ t('chat.shippingOrderReview.line', { index: (line.line_index ?? 0) + 1 }) }}
<span v-if="line.effective_reservation_id" class="ml-1 font-mono text-xs text-slate-500">
<span v-if="line.effective_reservation_id" class="ml-1 text-xs text-slate-500">
{{ line.effective_reservation_id }}
</span>
</span>
@@ -120,6 +237,90 @@ function submitLine(line: ShippingOrderReviewBuildEligibilityLineProjection) {
</span>
</div>
<p
v-if="line.inventory_source_hint"
class="mt-2 text-xs text-slate-600 dark:text-slate-300"
data-testid="review-inventory-routing-hint"
>
{{ t('chat.shippingOrderReview.inventoryRouting.hint') }}:
<span>{{ sourceBusinessName(String(line.inventory_source_hint)) }}</span>
<span
class="ml-1 font-mono text-[11px]"
data-testid="review-inventory-hint-source-code"
:data-source-code="sourceCodeLabel(String(line.inventory_source_hint))"
>{{ sourceCodeLabel(String(line.inventory_source_hint)) }}</span>
</p>
<div class="mt-2 space-y-2 text-xs text-slate-600 dark:text-slate-300">
<div v-if="matchedRuleCodes(line).length" data-testid="review-inventory-matched-rules">
<div class="font-medium">{{ t('chat.shippingOrderReview.inventoryRouting.matchedRules') }}</div>
<div class="mt-1 flex flex-wrap gap-1.5">
<span
v-for="ruleCode in matchedRuleCodes(line)"
:key="`rule-${ruleCode}`"
class="rounded border border-slate-200 bg-slate-50 px-1.5 py-0.5 font-mono text-[11px] dark:border-slate-600 dark:bg-slate-800"
>{{ ruleCode }}</span>
</div>
</div>
<div v-if="(line.raw_rule_source_codes || []).length" data-testid="review-inventory-raw-sources">
<div class="font-medium">{{ t('chat.shippingOrderReview.inventoryRouting.rawCandidates') }}</div>
<div class="mt-1 grid gap-1.5 sm:grid-cols-2">
<div
v-for="code in line.raw_rule_source_codes"
:key="`raw-${code}`"
class="rounded-md border border-slate-200 bg-white px-2 py-1.5 dark:border-slate-600 dark:bg-slate-950"
>
<div class="truncate font-medium text-slate-700 dark:text-slate-200">{{ sourceBusinessName(String(code)) }}</div>
<div
class="mt-0.5 font-mono text-[11px] text-slate-500"
:data-source-code="sourceCodeLabel(String(code))"
>{{ sourceCodeLabel(String(code)) }}</div>
</div>
</div>
</div>
<div v-if="(line.unavailable_source_codes || []).length" data-testid="review-inventory-unavailable-sources">
<div class="font-medium">{{ t('chat.shippingOrderReview.inventoryRouting.unavailableCandidates') }}</div>
<div class="mt-1 grid gap-1.5 sm:grid-cols-2">
<div
v-for="code in line.unavailable_source_codes"
:key="code"
class="rounded-md border border-rose-200 bg-rose-50/70 px-2 py-1.5 dark:border-rose-900 dark:bg-rose-950/30"
>
<div class="truncate font-medium text-rose-900 dark:text-rose-100">{{ sourceBusinessName(code) }}</div>
<div
class="mt-0.5 font-mono text-[11px] text-rose-700 dark:text-rose-300"
:data-source-code="sourceCodeLabel(code)"
>{{ sourceCodeLabel(code) }}</div>
<div class="mt-0.5 text-[11px] text-rose-700 dark:text-rose-300">{{ unavailableReasonLabel(line, code) }}</div>
</div>
</div>
</div>
<div v-if="ruleSuggestionCodes(line).length" data-testid="review-inventory-rule-suggestions">
<div class="font-medium">{{ t('chat.shippingOrderReview.inventoryRouting.ruleSuggestion') }}</div>
<div class="mt-1 grid gap-1.5 sm:grid-cols-2">
<div
v-for="code in ruleSuggestionCodes(line)"
:key="`suggest-${code}`"
class="rounded-md border border-sky-200 bg-sky-50/70 px-2 py-1.5 dark:border-sky-900 dark:bg-sky-950/30"
>
<div class="truncate font-medium text-sky-900 dark:text-sky-100">{{ sourceBusinessName(code) }}</div>
<div
class="mt-0.5 font-mono text-[11px] text-sky-700 dark:text-sky-300"
:data-source-code="sourceCodeLabel(code)"
>{{ sourceCodeLabel(code) }}</div>
</div>
</div>
</div>
</div>
<p
v-if="line.suggestion_pending"
class="mt-2 rounded border border-amber-200 bg-amber-50 px-2 py-1 text-xs text-amber-900 dark:border-amber-900 dark:bg-amber-950/40 dark:text-amber-100"
data-testid="review-inventory-suggestion-pending"
>
{{ t('chat.shippingOrderReview.inventoryRouting.suggestionPending') }}
</p>
<div v-if="selectableCodes(line).length" class="mt-3">
<div class="text-xs font-medium text-slate-600 dark:text-slate-300">
{{
@@ -140,7 +341,8 @@ function submitLine(line: ShippingOrderReviewBuildEligibilityLineProjection) {
:disabled="!editable || saving"
@change="toggleCode(line, code)"
>
<span class="font-mono">{{ code }}</span>
<span>{{ sourceBusinessName(code) }}</span>
<span class="font-mono text-[11px] text-slate-500">{{ sourceCodeLabel(code) }}</span>
</label>
</div>
</div>
@@ -160,7 +362,36 @@ function submitLine(line: ShippingOrderReviewBuildEligibilityLineProjection) {
/>
</label>
<div class="mt-3 flex justify-end">
<div class="mt-3 flex flex-wrap items-center justify-end gap-2">
<button
type="button"
class="rounded border border-slate-300 bg-white px-3 py-1.5 text-xs text-slate-700 disabled:opacity-50 dark:border-slate-600 dark:bg-slate-950 dark:text-slate-200"
data-testid="review-inventory-routing-reroute"
:disabled="!editable || saving"
@click="rerouteLine(line)"
>
{{ t('chat.shippingOrderReview.inventoryRouting.reroute') }}
</button>
<template v-if="line.suggestion_pending">
<button
type="button"
class="rounded border border-amber-300 bg-amber-50 px-3 py-1.5 text-xs text-amber-900 disabled:opacity-50 dark:border-amber-800 dark:bg-amber-950/50 dark:text-amber-100"
data-testid="review-inventory-routing-adopt"
:disabled="!editable || saving"
@click="adoptLine(line)"
>
{{ t('chat.shippingOrderReview.inventoryRouting.adoptSuggestion') }}
</button>
<button
type="button"
class="rounded border border-slate-300 bg-white px-3 py-1.5 text-xs text-slate-700 disabled:opacity-50 dark:border-slate-600 dark:bg-slate-950 dark:text-slate-200"
data-testid="review-inventory-routing-keep"
:disabled="!editable || saving"
@click="keepLine(line)"
>
{{ t('chat.shippingOrderReview.inventoryRouting.keepManual') }}
</button>
</template>
<button
type="button"
class="rounded bg-sky-600 px-3 py-1.5 text-xs text-white disabled:opacity-50"
@@ -0,0 +1,76 @@
<!--
features/chat/components/shipping-review/ReviewInventoryIssueList.vue
用途:标准复核侧栏中的异常库存行摘要列表(只显示需处理行)。
依赖:vue-i18n、ShippingOrderReviewBuildEligibilityLineProjection。
逻辑:行列表由后端 recovery/suggestion 投影提供,前端不自行发明异常规则;
点击行可定位明细或进入库存处理模式。
-->
<script setup lang="ts">
import { useI18n } from 'vue-i18n';
import type { ShippingOrderReviewBuildEligibilityLineProjection } from '@/features/chat/types/shipping.api.types';
defineProps<{
lines: ShippingOrderReviewBuildEligibilityLineProjection[];
}>();
const emit = defineEmits<{
'enter-inventory': [];
'focus-line': [lineIndex: number];
}>();
const { t, te } = useI18n();
/**
* 解析阻断原因展示文案。
*/
function blockReasonLabel(reason?: string | null): string {
const normalized = String(reason || '').trim();
if (!normalized) return t('chat.shippingOrderReview.buildEligibility.blockReasons.unknown');
const key = `chat.shippingOrderReview.buildEligibility.blockReasons.${normalized}`;
return te(key) ? t(key) : t('chat.shippingOrderReview.buildEligibility.blockReasons.unknown');
}
</script>
<template>
<section
v-if="lines.length"
class="rounded-xl border border-slate-200 bg-white p-3 shadow-sm dark:border-slate-800 dark:bg-slate-900"
data-testid="review-inventory-issue-list"
>
<header class="mb-2 flex items-center justify-between gap-2">
<h2 class="text-sm font-semibold">{{ t('chat.shippingOrderReview.workbench.inventoryIssues') }}</h2>
<button
type="button"
class="rounded border border-amber-300 px-2 py-1 text-xs text-amber-900 hover:bg-amber-50 dark:border-amber-800 dark:text-amber-100 dark:hover:bg-amber-950/40"
data-testid="review-inventory-issues-enter"
@click="emit('enter-inventory')"
>
{{ t('chat.shippingOrderReview.workbench.enterInventory') }}
</button>
</header>
<ul class="space-y-1.5">
<li
v-for="line in lines"
:key="String(line.line_key || line.line_index)"
class="rounded-lg border border-amber-200 bg-amber-50/70 px-2.5 py-2 text-xs dark:border-amber-900 dark:bg-amber-950/30"
:data-testid="`review-inventory-issue-${line.line_key || line.line_index}`"
>
<button
type="button"
class="w-full text-left"
@click="emit('focus-line', Number(line.line_index ?? 0))"
>
<div class="font-medium text-amber-950 dark:text-amber-100">
{{ t('chat.shippingOrderReview.line', { index: (line.line_index ?? 0) + 1 }) }}
<span v-if="line.effective_reservation_id" class="ml-1 font-mono text-[11px] opacity-80">
{{ line.effective_reservation_id }}
</span>
</div>
<p class="mt-0.5 text-amber-900/90 dark:text-amber-100/90">
{{ blockReasonLabel(line.block_reason) }}
</p>
</button>
</li>
</ul>
</section>
</template>
@@ -19,7 +19,7 @@ const props = defineProps<{
suggestion?: ShippingOrderReviewLlmSuggestion | null;
evidence?: ShippingOrderReviewEvidence | null;
draftValue?: unknown;
/** Schema 字段展示名;缺省回退 field_id。 */
/** 订单字段展示名;缺省时使用通用业务名称。 */
fieldLabel?: string;
}>();
@@ -39,13 +39,13 @@ const previousFocus = ref<HTMLElement | null>(null);
const rejectOnly = computed(() => String(props.suggestion?.status || '') === 'validation_failed');
const displayFieldLabel = computed(() =>
String(props.fieldLabel || props.suggestion?.field_id || '').trim(),
String(props.fieldLabel || t('chat.shippingOrderReview.unknownField')).trim(),
);
const evidenceLevelText = computed(() => {
const code = String(props.suggestion?.evidence_level || 'L1_field').trim() || 'L1_field';
const key = `chat.shippingOrderReview.llmSuggestion.evidenceLevel.${code}`;
return te(key) ? t(key) : t('chat.shippingOrderReview.llmSuggestion.scope', { level: code });
return te(key) ? t(key) : t('chat.shippingOrderReview.llmSuggestion.evidenceLevel.unknown');
});
const canSubmit = computed(() => {
@@ -0,0 +1,78 @@
<!--
features/chat/components/shipping-review/ReviewLlmSuggestionDrawer.vue
用途:字段级 AI 建议按需抽屉外壳;内容复用 ReviewLlmSuggestionPanel。
依赖:vue-i18n、ReviewLlmSuggestionPanel。
逻辑:无聚焦字段时父级不打开;AI 只能建议,裁决仍走既有保存/审计流程。
-->
<script setup lang="ts">
import { useI18n } from 'vue-i18n';
import ReviewLlmSuggestionPanel from './ReviewLlmSuggestionPanel.vue';
import type {
ShippingOrderReviewCase,
ShippingOrderReviewEvidence,
ShippingOrderReviewLlmAdjudicationPayload,
ShippingOrderReviewLlmSuggestion,
} from '@/features/chat/types/shipping.api.types';
defineProps<{
open: boolean;
activeCase?: ShippingOrderReviewCase | null;
evidence?: ShippingOrderReviewEvidence[] | null;
editable?: boolean;
saving?: boolean;
suggestions?: ShippingOrderReviewLlmSuggestion[];
suggestionLoading?: boolean;
focusedFieldId?: string | null;
focusedLineKey?: string | null;
draftValue?: unknown;
}>();
const emit = defineEmits<{
close: [];
'request-suggestion': [];
adjudicate: [payload: {
suggestion: ShippingOrderReviewLlmSuggestion;
body: ShippingOrderReviewLlmAdjudicationPayload;
}];
}>();
const { t } = useI18n();
</script>
<template>
<div
v-if="open"
class="fixed inset-0 z-40 flex justify-end bg-slate-900/30"
data-testid="review-llm-suggestion-drawer"
@click.self="emit('close')"
>
<aside class="flex h-full w-full max-w-lg flex-col bg-white shadow-xl dark:bg-slate-900">
<header class="flex items-center justify-between gap-2 border-b border-slate-200 px-4 py-3 dark:border-slate-800">
<h2 class="text-sm font-semibold">{{ t('chat.shippingOrderReview.llmSuggestion.panelTitle') }}</h2>
<button
type="button"
class="rounded border border-slate-300 px-2 py-1 text-xs hover:bg-slate-50 dark:border-slate-600 dark:hover:bg-slate-800"
data-testid="review-llm-drawer-close"
@click="emit('close')"
>
{{ t('chat.shippingOrderReview.workbench.closePdf') }}
</button>
</header>
<div class="min-h-0 flex-1 overflow-y-auto p-4">
<ReviewLlmSuggestionPanel
:active-case="activeCase"
:evidence="evidence"
:editable="editable"
:saving="saving"
:suggestions="suggestions"
:suggestion-loading="suggestionLoading"
:focused-field-id="focusedFieldId"
:focused-line-key="focusedLineKey"
:draft-value="draftValue"
@request-suggestion="emit('request-suggestion')"
@adjudicate="emit('adjudicate', $event)"
/>
</div>
</aside>
</div>
</template>
@@ -17,6 +17,7 @@ const messages = {
en: {
chat: {
shippingOrderReview: {
unknownField: 'Order field',
llmSuggestion: {
panelTitle: 'AI suggestion',
panelHint: 'Minimal evidence only',
@@ -39,7 +40,8 @@ const messages = {
modifiedValue: 'Modified',
noteOptional: 'Note',
reasonRequired: 'Reason required',
status: { idle: 'Idle', pending: 'Pending', validated: 'Validated' },
evidenceLevel: { L1_field: 'Current field content', unknown: 'Relevant document content' },
status: { idle: 'Idle', pending: 'Pending', validated: 'Validated', unknown: 'Status pending confirmation' },
decisions: { accept: 'Accept', modify: 'Modify', reject: 'Reject' },
},
},
@@ -87,7 +89,21 @@ function mountPanel(overrides?: {
return mount(ReviewLlmSuggestionPanel, {
props: {
activeCase,
evidence: [{ evidence_id: 'e1', field_id: 'fld-po', quote: 'PO-NEW', page_no: 1, source: 'layout' }],
evidence: [{
evidence_id: 'e1',
field_id: 'fld-po',
quote: 'PO-NEW',
page_no: 1,
source: 'layout',
highlight_quality: 'unavailable',
highlight_source: 'machine_extraction',
highlight_bbox: null,
coordinate_status: 'unavailable',
coordinate_issue_codes: ['coordinate_missing'],
evidence_ref: null,
token_ids: [],
value_match_status: 'matched',
}],
editable: overrides?.editable ?? true,
saving: false,
suggestions: overrides?.suggestions ?? [suggestion],
@@ -159,4 +175,24 @@ describe('ReviewLlmSuggestionPanel', () => {
expect(document.body.textContent).toContain('Failed');
wrapper.unmount();
});
it('does not expose unknown field id or evidence level', async () => {
const unknown: ShippingOrderReviewLlmSuggestion = {
suggestion_no: 'RSG-UNKNOWN',
field_id: 'internal-field-id',
scope: 'header',
evidence_level: 'internal_evidence_level',
status: 'validated',
suggested_value: 'PO-NEW',
validation_issues: [],
};
const wrapper = mountPanel({ suggestions: [unknown], focusedFieldId: 'internal-field-id' });
expect(wrapper.text()).toContain('Order field');
expect(wrapper.text()).not.toContain('internal-field-id');
await wrapper.get('ul button').trigger('click');
await flushPromises();
expect(document.body.textContent).toContain('Relevant document content');
expect(wrapper.text()).not.toContain('internal_evidence_level');
wrapper.unmount();
});
});
@@ -1,9 +1,9 @@
<!--
features/chat/components/shipping-review/ReviewLlmSuggestionPanel.vue
用途:复核工作台内嵌 AI 建议入口、列表与裁决触发(非顶级导航)。
用途:AI 建议列表与裁决内容(布局重构后作为抽屉内容组件,非常驻主区大卡片)。
依赖:vue-i18n、ReviewLlmSuggestionDialog、ShippingOrderReview* 类型。
逻辑:请求/裁决由父级 composable 执行;仅 validated 可接受;validation_failed 单独列表仅可拒绝;
证据按 field_id + line_key/line_index 绑定;打开弹窗时按建议字段解析当前草稿值。
逻辑:由 ReviewLlmSuggestionDrawer 挂载;请求须用户主动触发;仅 validated 可接受;
validation_failed 仅可拒绝;证据按 field_id + line_key/line_index 绑定。
-->
<script setup lang="ts">
import { computed, ref } from 'vue';
@@ -56,7 +56,7 @@ const statusLabel = computed(() => {
const latest = (props.suggestions || [])[0];
const code = String(latest?.status || latest?.decision || 'idle');
const key = `chat.shippingOrderReview.llmSuggestion.status.${code}`;
return te(key) ? t(key) : code;
return te(key) ? t(key) : t('chat.shippingOrderReview.llmSuggestion.status.unknown');
});
const canRequest = computed(() =>
@@ -130,7 +130,7 @@ function openSuggestion(item: ShippingOrderReviewLlmSuggestion) {
}
/**
* 将建议字段解析为 Schema 展示名;缺失时回退 field_id。
* 将建议字段解析为订单字段名称;缺失时使用通用名称,避免显示内部字段 ID。
*/
function suggestionFieldLabel(item: ShippingOrderReviewLlmSuggestion): string {
const fieldId = String(item.field_id || '').trim();
@@ -140,7 +140,7 @@ function suggestionFieldLabel(item: ShippingOrderReviewLlmSuggestion): string {
if (name && item.line_key) {
return `${name} · ${item.line_key}`;
}
return name || fieldId || '—';
return name || t('chat.shippingOrderReview.unknownField');
}
/**
@@ -149,7 +149,7 @@ function suggestionFieldLabel(item: ShippingOrderReviewLlmSuggestion): string {
function evidenceLevelLabel(level?: string | null): string {
const code = String(level || 'L1_field').trim() || 'L1_field';
const key = `chat.shippingOrderReview.llmSuggestion.evidenceLevel.${code}`;
return te(key) ? t(key) : t('chat.shippingOrderReview.llmSuggestion.scope', { level: code });
return te(key) ? t(key) : t('chat.shippingOrderReview.llmSuggestion.evidenceLevel.unknown');
}
/**
@@ -0,0 +1,124 @@
<!--
features/chat/components/shipping-review/ReviewProfileMatchPanel.vue
用途:复核工作台文档模板匹配只读区(选中模板 / 候选分 / 回退原因)。
依赖:vue-i18n、ShippingOrderReviewProfileMatch。
逻辑:A3 只展示;换模板/重抽取仍走 Process Gate 或重新识别 PDF。
-->
<script setup lang="ts">
import { computed } from 'vue';
import { useI18n } from 'vue-i18n';
import type { ShippingOrderReviewProfileMatch } from '@/features/chat/types/shipping.api.types';
const props = defineProps<{
profileMatch: ShippingOrderReviewProfileMatch | null | undefined;
}>();
const { t, te } = useI18n();
const visible = computed(() => Boolean(props.profileMatch?.available));
const needsReview = computed(() => Boolean(props.profileMatch?.needs_review));
/**
* 匹配状态本地化。
*/
const statusLabel = computed(() => {
const status = String(props.profileMatch?.status || '').trim();
const key = `chat.shippingOrderReview.profileMatch.status.${status}`;
return status && te(key) ? t(key) : (status || '—');
});
/**
* 选中模板展示名。
*/
const selectedLabel = computed(() => {
const selected = props.profileMatch?.selected_profile;
if (!selected?.profile_code) {
return t('chat.shippingOrderReview.profileMatch.noSelected');
}
const name = String(selected.display_name || selected.profile_code).trim();
const version = selected.version != null ? ` v${selected.version}` : '';
return `${name}${version}`;
});
/**
* 回退原因本地化列表。
*/
const fallbackLabels = computed(() =>
(props.profileMatch?.fallback_reason_codes || []).map((code) => {
const key = `chat.shippingOrderReview.profileMatch.reasons.${code}`;
return te(key) ? t(key) : code;
}),
);
</script>
<template>
<section
v-if="visible"
class="rounded-xl border border-slate-200 bg-white p-3 shadow-sm dark:border-slate-800 dark:bg-slate-900"
data-testid="review-profile-match-panel"
>
<header class="flex flex-wrap items-start justify-between gap-2">
<div>
<h2 class="text-sm font-semibold">{{ t('chat.shippingOrderReview.profileMatch.title') }}</h2>
<p class="mt-0.5 text-xs text-muted">{{ t('chat.shippingOrderReview.profileMatch.subtitle') }}</p>
</div>
<span
class="rounded-full px-2.5 py-1 text-xs font-medium"
:class="needsReview
? 'bg-amber-100 text-amber-900 dark:bg-amber-950 dark:text-amber-100'
: 'bg-emerald-100 text-emerald-800 dark:bg-emerald-950 dark:text-emerald-100'"
data-testid="review-profile-match-badge"
>
{{ statusLabel }}
</span>
</header>
<dl class="mt-2 space-y-1 text-xs text-secondary">
<div class="flex flex-wrap gap-x-2">
<dt class="text-muted">{{ t('chat.shippingOrderReview.profileMatch.selected') }}</dt>
<dd class="font-medium text-primary" data-testid="review-profile-match-selected">{{ selectedLabel }}</dd>
</div>
<div v-if="profileMatch?.route_type" class="flex flex-wrap gap-x-2">
<dt class="text-muted">{{ t('chat.shippingOrderReview.profileMatch.routeType') }}</dt>
<dd class="font-mono">{{ profileMatch.route_type }}</dd>
</div>
<div v-if="profileMatch?.execution_mode" class="flex flex-wrap gap-x-2">
<dt class="text-muted">{{ t('chat.shippingOrderReview.profileMatch.executionMode') }}</dt>
<dd class="font-mono">{{ profileMatch.execution_mode }}</dd>
</div>
</dl>
<ul
v-if="(profileMatch?.candidates || []).length"
class="mt-2 space-y-1.5"
data-testid="review-profile-match-candidates"
>
<li
v-for="(item, idx) in profileMatch?.candidates || []"
:key="`${item.profile_code}-${item.version}-${idx}`"
class="rounded-lg border border-default bg-surface-soft px-2.5 py-1.5 text-[11px] text-secondary"
>
<div class="flex flex-wrap items-center justify-between gap-2">
<span class="font-medium text-primary">
{{ item.display_name || item.profile_code }}
<span v-if="item.version != null" class="text-muted">v{{ item.version }}</span>
</span>
<span v-if="item.score != null" class="font-mono text-muted">
{{ t('chat.shippingOrderReview.profileMatch.score', { score: Number(item.score).toFixed(2) }) }}
</span>
</div>
<p v-if="item.reason_codes?.length" class="mt-0.5 text-muted">
{{ item.reason_codes.join(', ') }}
</p>
</li>
</ul>
<ul v-if="fallbackLabels.length" class="mt-2 list-disc space-y-0.5 pl-4 text-[11px] text-amber-900 dark:text-amber-100">
<li v-for="label in fallbackLabels" :key="label">{{ label }}</li>
</ul>
<p class="mt-2 text-[11px] text-muted">
{{ t('chat.shippingOrderReview.profileMatch.reselectHint') }}
</p>
</section>
</template>
@@ -0,0 +1,58 @@
<!--
features/chat/components/shipping-review/ReviewVersionHistoryDrawer.vue
用途:版本历史按需抽屉;内容复用 ReviewVersionHistoryPanel(只读)。
依赖:vue-i18n、ReviewVersionHistoryPanel。
逻辑:默认不占主内容高度;由顶栏「版本历史」打开。
-->
<script setup lang="ts">
import { useI18n } from 'vue-i18n';
import ReviewVersionHistoryPanel from './ReviewVersionHistoryPanel.vue';
import type { ShippingWorkflowItemVersion } from '@/features/chat/types/shipping.api.types';
defineProps<{
open: boolean;
itemNo?: string | null;
versions: ShippingWorkflowItemVersion[];
loading?: boolean;
activeCaseNo?: string | null;
}>();
const emit = defineEmits<{
close: [];
select: [caseNo: string];
}>();
const { t } = useI18n();
</script>
<template>
<div
v-if="open"
class="fixed inset-0 z-40 flex justify-end bg-slate-900/30"
data-testid="review-version-history-drawer"
@click.self="emit('close')"
>
<aside class="flex h-full w-full max-w-md flex-col bg-white shadow-xl dark:bg-slate-900">
<header class="flex items-center justify-between gap-2 border-b border-slate-200 px-4 py-3 dark:border-slate-800">
<h2 class="text-sm font-semibold">{{ t('chat.shippingOrderReview.versionHistory.title') }}</h2>
<button
type="button"
class="rounded border border-slate-300 px-2 py-1 text-xs hover:bg-slate-50 dark:border-slate-600 dark:hover:bg-slate-800"
data-testid="review-version-history-close"
@click="emit('close')"
>
{{ t('chat.shippingOrderReview.workbench.closePdf') }}
</button>
</header>
<div class="min-h-0 flex-1 overflow-y-auto p-4">
<ReviewVersionHistoryPanel
:item-no="itemNo"
:versions="versions"
:loading="loading"
:active-case-no="activeCaseNo"
@select="(caseNo) => emit('select', caseNo)"
/>
</div>
</aside>
</div>
</template>
@@ -28,7 +28,7 @@ function resultLabel(status?: string | null): string {
const normalized = String(status || '').trim();
if (!normalized) return '—';
const key = `chat.shippingOrderReview.caseStatuses.${normalized}`;
return te(key) ? t(key) : normalized;
return te(key) ? t(key) : t('chat.shippingOrderReview.caseStatuses.unknown');
}
/**
@@ -0,0 +1,109 @@
<!--
features/chat/components/shipping-review/ReviewWorkbenchFooter.vue
用途:订单复核工作台底部固定操作栏。
依赖:vue-i18n、lucide-vue-next。
逻辑:ShippingOrderReviewView 传入 available_actions 与门禁状态;sticky bottom 保证在主滚动区内常驻可见。
-->
<script setup lang="ts">
import { RefreshCw, Save } from 'lucide-vue-next';
import { useI18n } from 'vue-i18n';
const props = defineProps<{
availableActions: string[];
canConfirmBuild: boolean;
saving: boolean;
isReadOnly: boolean;
hasDraft: boolean;
}>();
const emit = defineEmits<{
'mark-non-order': [];
'mark-quality-issue': [];
reparse: [];
'upload-replacement': [event: Event];
validate: [];
confirm: [];
}>();
const { t } = useI18n();
/**
* 判断某 action 是否在当前 Case 可用。
*/
function hasAction(action: string): boolean {
return props.availableActions.includes(action);
}
</script>
<template>
<footer
v-if="hasDraft && !isReadOnly"
class="sticky bottom-0 z-20 flex shrink-0 flex-col gap-3 border-t border-slate-200 bg-white/95 p-3 shadow-[0_-4px_12px_rgba(15,23,42,0.06)] backdrop-blur sm:flex-row sm:items-center sm:justify-between dark:border-slate-800 dark:bg-slate-900/95"
data-testid="review-footer-actions"
>
<div class="order-1 flex flex-wrap items-center gap-2 sm:order-1">
<button
v-if="hasAction('mark_non_order')"
type="button"
:disabled="saving"
class="rounded border border-rose-200 px-3 py-2 text-sm text-rose-700 hover:bg-rose-50 disabled:opacity-50 dark:border-rose-900 dark:text-rose-300 dark:hover:bg-rose-950/40"
@click="emit('mark-non-order')"
>
{{ t('chat.shippingOrderReview.markNonOrder') }}
</button>
<button
v-if="hasAction('mark_quality_issue')"
type="button"
:disabled="saving"
class="rounded border border-amber-200 px-3 py-2 text-sm text-amber-800 hover:bg-amber-50 disabled:opacity-50 dark:border-amber-900 dark:text-amber-200 dark:hover:bg-amber-950/40"
@click="emit('mark-quality-issue')"
>
{{ t('chat.shippingOrderReview.markQualityIssue') }}
</button>
<button
v-if="hasAction('reparse')"
type="button"
:disabled="saving"
class="inline-flex items-center gap-1 rounded border border-slate-300 px-3 py-2 text-sm text-slate-600 hover:bg-slate-50 disabled:opacity-50 dark:border-slate-700 dark:text-slate-300 dark:hover:bg-slate-800"
@click="emit('reparse')"
>
<RefreshCw class="h-4 w-4" />{{ t('chat.shippingOrderReview.reparse') }}
</button>
<label
v-if="hasAction('mark_quality_issue')"
class="cursor-pointer rounded border border-slate-300 px-3 py-2 text-sm text-slate-600 hover:bg-slate-50 dark:border-slate-700 dark:text-slate-300 dark:hover:bg-slate-800"
>
<input
class="sr-only"
type="file"
accept="application/pdf,.pdf"
:disabled="saving"
@change="emit('upload-replacement', $event)"
>
{{ t('chat.shippingOrderReview.uploadReplacement') }}
</label>
</div>
<div class="order-2 flex flex-wrap items-center justify-end gap-2 sm:order-2">
<button
v-if="hasAction('validate')"
type="button"
:disabled="saving"
class="inline-flex items-center gap-1 rounded bg-sky-600 px-3 py-2 text-sm text-white disabled:opacity-50"
@click="emit('validate')"
>
<Save class="h-4 w-4" />{{ t('chat.shippingOrderReview.saveNow') }}
</button>
<button
v-if="hasAction('confirm')"
type="button"
:disabled="saving || !canConfirmBuild"
class="rounded bg-emerald-600 px-3 py-2 text-sm font-medium text-white disabled:opacity-50"
data-testid="review-confirm-create"
:title="!canConfirmBuild ? t('chat.shippingOrderReview.buildEligibility.confirmBlocked') : undefined"
@click="emit('confirm')"
>
{{ t('chat.shippingOrderReview.confirmCreate') }}
</button>
</div>
</footer>
</template>
@@ -0,0 +1,91 @@
<!--
features/chat/components/shipping-review/ReviewWorkbenchHeader.vue
用途:订单复核工作台顶栏,展示标题上下文与保存状态。
依赖:vue-i18n、lucide-vue-next。
逻辑:ShippingOrderReviewView 传入 run/workItem 上下文;emit back 与 open-version-history;不含对话上下文切换。
-->
<script setup lang="ts">
import { computed } from 'vue';
import { ArrowLeft } from 'lucide-vue-next';
import { useI18n } from 'vue-i18n';
const props = defineProps<{
runNo: string;
itemNo?: string | null;
versionLabel?: string;
saving: boolean;
saveFailed: boolean;
draftConflict: boolean;
isReadOnly: boolean;
showVersionHistory?: boolean;
}>();
const emit = defineEmits<{
back: [];
'open-version-history': [];
}>();
const { t } = useI18n();
/**
* 副标题:优先工作项编号与版本,否则识别批次号。
*/
const subtitle = computed(() => {
if (props.itemNo) {
return t('chat.shippingOrderReview.workItemHeader', {
itemNo: props.itemNo,
version: props.versionLabel || '',
});
}
return t('chat.shippingOrderReview.run', { runNo: props.runNo });
});
</script>
<template>
<header class="flex shrink-0 items-center gap-3 border-b border-slate-200 bg-white px-4 py-3 dark:border-slate-800 dark:bg-slate-900">
<button
type="button"
class="rounded-md p-1 hover:bg-slate-100 dark:hover:bg-slate-800"
:aria-label="t('chat.shippingOrderReview.backToSession')"
@click="emit('back')"
>
<ArrowLeft class="h-5 w-5" />
</button>
<div class="min-w-0 flex-1">
<h1 class="text-base font-semibold">{{ t('chat.shippingOrderReview.title') }}</h1>
<p class="truncate text-xs text-slate-500 dark:text-slate-400">{{ subtitle }}</p>
</div>
<button
v-if="showVersionHistory"
type="button"
class="rounded border border-slate-200 px-2.5 py-1.5 text-xs hover:bg-slate-50 dark:border-slate-700 dark:hover:bg-slate-800"
data-testid="review-open-version-history"
@click="emit('open-version-history')"
>
{{ t('chat.shippingOrderReview.workbench.openVersionHistory') }}
</button>
<span
class="shrink-0 rounded-full px-2.5 py-1 text-xs"
:class="draftConflict
? 'bg-amber-100 text-amber-900 dark:bg-amber-950 dark:text-amber-100'
: 'bg-sky-100 text-sky-800 dark:bg-sky-950 dark:text-sky-100'"
data-testid="review-save-status"
>
{{
saving
? t('chat.shippingOrderReview.saving')
: draftConflict
? t('chat.shippingOrderReview.versionConflict.badge')
: saveFailed
? t('chat.shippingOrderReview.saveFailed')
: t('chat.shippingOrderReview.saved')
}}
</span>
<span
v-if="isReadOnly"
class="shrink-0 rounded-full bg-slate-100 px-2 py-0.5 text-xs text-slate-600 dark:bg-slate-800 dark:text-slate-300"
>
{{ t('chat.shippingOrderReview.readOnly') }}
</span>
</header>
</template>
@@ -0,0 +1,68 @@
<!--
features/chat/components/shipping-review/ReviewWorkbenchModeToggle.vue
用途:复核工作台模式切换条,展示当前模式并提供返回标准/进入库存处理入口。
依赖:vue-i18n、ReviewWorkbenchMode 类型。
逻辑:ShippingOrderReviewView 绑定 workbenchMode;evidence/inventory 模式可返回 standard。
-->
<script setup lang="ts">
import { computed } from 'vue';
import { useI18n } from 'vue-i18n';
import type { ReviewWorkbenchMode } from '@/features/chat/types/shipping.api.types';
const props = defineProps<{
mode: ReviewWorkbenchMode;
canEnterInventory: boolean;
}>();
const emit = defineEmits<{
'update:mode': [mode: ReviewWorkbenchMode];
'set-mode': [mode: ReviewWorkbenchMode];
}>();
const { t } = useI18n();
/**
* 当前模式本地化标签。
*/
const modeLabel = computed(() => t(`chat.shippingOrderReview.workbench.mode.${props.mode}`));
/**
* 向父级发出模式变更(兼容 v-model 与 set-mode)。
*/
function setMode(next: ReviewWorkbenchMode) {
emit('update:mode', next);
emit('set-mode', next);
}
</script>
<template>
<div
class="flex flex-wrap items-center justify-between gap-2 rounded-lg border border-slate-200 bg-white px-3 py-2 text-xs dark:border-slate-800 dark:bg-slate-900"
data-testid="review-workbench-mode"
:data-workbench-mode="mode"
>
<span class="font-medium text-slate-600 dark:text-slate-300">
{{ modeLabel }}
</span>
<div class="flex flex-wrap items-center gap-2">
<button
v-if="canEnterInventory && mode === 'standard'"
type="button"
class="rounded border border-amber-300 px-2 py-1 text-amber-800 hover:bg-amber-50 dark:border-amber-800 dark:text-amber-200 dark:hover:bg-amber-950/40"
data-testid="review-enter-inventory-mode"
@click="setMode('inventory')"
>
{{ t('chat.shippingOrderReview.workbench.enterInventory') }}
</button>
<button
v-if="mode === 'evidence' || mode === 'inventory'"
type="button"
class="rounded border border-slate-300 px-2 py-1 text-slate-700 hover:bg-slate-50 dark:border-slate-600 dark:text-slate-300 dark:hover:bg-slate-800"
data-testid="review-return-standard-mode"
@click="setMode('standard')"
>
{{ t('chat.shippingOrderReview.workbench.returnStandard') }}
</button>
</div>
</div>
</template>
@@ -0,0 +1,95 @@
/**
* features/chat/components/shipping-review/pdfHighlightCoords.spec.ts
* 用途:锁定归一化高亮框 → PDF.js viewport 像素转换(含旋转)。
* 依赖:vitest、pdfHighlightCoords。
* 逻辑:用简易仿射矩阵模拟 0°/90° 旋转,断言不直接宽高相乘。
*/
import { describe, expect, it } from 'vitest';
import { normalizedTopLeftBBoxToViewportRect } from './pdfHighlightCoords';
/**
* 构造仿 PDF.js viewport:可选 90° 旋转(宽高交换 + 坐标变换)。
*/
function makeViewport(scale: number, rotation: 0 | 90) {
const pageWidth = 200;
const pageHeight = 100;
if (rotation === 0) {
return {
width: pageWidth * scale,
height: pageHeight * scale,
convertToViewportRectangle: (rect: number[]) => {
const [x0, y0, x1, y1] = rect;
// PDF 左下 → canvas 左上
return [
x0 * scale,
(pageHeight - y1) * scale,
x1 * scale,
(pageHeight - y0) * scale,
];
},
};
}
// 90° 顺时针:viewport 宽=原高,高=原宽
return {
width: pageHeight * scale,
height: pageWidth * scale,
convertToViewportRectangle: (rect: number[]) => {
const [x0, y0, x1, y1] = rect;
const map = (x: number, y: number) => [y * scale, (pageWidth - x) * scale] as const;
const a = map(x0, y0);
const b = map(x1, y1);
return [a[0], a[1], b[0], b[1]];
},
};
}
describe('normalizedTopLeftBBoxToViewportRect', () => {
it('maps unrotated top-left normalized bbox via viewport transform', () => {
const page = { view: [0, 0, 200, 100], rotate: 0 };
const viewport = makeViewport(2, 0);
const rect = normalizedTopLeftBBoxToViewportRect(
{ x0: 0.1, y0: 0.2, x1: 0.3, y1: 0.4 },
page,
viewport,
);
// 关键断言:结果等于经 PDF 左下转换后的像素框,而非错误的直接相乘错位
expect(rect).toEqual({
x: 40,
y: 40,
width: 80,
height: 40,
});
});
it('handles 90-degree page rotation without simple width/height multiply', () => {
const page = { view: [0, 0, 200, 100], rotate: 90 };
const viewport = makeViewport(1, 90);
const naive = {
x: 0.1 * viewport.width,
y: 0.2 * viewport.height,
width: 0.2 * viewport.width,
height: 0.2 * viewport.height,
};
const rect = normalizedTopLeftBBoxToViewportRect(
{ x0: 0.1, y0: 0.2, x1: 0.3, y1: 0.4 },
page,
viewport,
);
expect(rect).not.toBeNull();
// 关键断言:旋转后不得等于 naive 宽高相乘结果
expect(rect).not.toEqual(naive);
expect(rect!.width).toBeGreaterThan(0);
expect(rect!.height).toBeGreaterThan(0);
});
it('returns null for inverted or out-of-range bbox', () => {
const page = { view: [0, 0, 200, 100] };
const viewport = makeViewport(1, 0);
expect(
normalizedTopLeftBBoxToViewportRect({ x0: 0.4, y0: 0.1, x1: 0.2, y1: 0.3 }, page, viewport),
).toBeNull();
expect(
normalizedTopLeftBBoxToViewportRect({ x0: -0.1, y0: 0.1, x1: 0.2, y1: 0.3 }, page, viewport),
).toBeNull();
});
});
@@ -0,0 +1,80 @@
/**
* features/chat/components/shipping-review/pdfHighlightCoords.ts
* 用途:将后端归一化(左上原点、0..1)高亮框转换为 PDF.js viewport 像素矩形。
* 依赖:pdfjs-dist PageViewport / PDFPageProxy 形态(duck-typed,便于单测)。
* 逻辑:ReviewDocumentPreview 绘制前调用;先还原 PDF 用户空间(左下原点),再经
* convertToViewportRectangle 处理旋转与缩放,避免直接宽高相乘错位。
*/
export type NormalizedBBox = {
x0: number;
y0: number;
x1: number;
y1: number;
};
export type ViewportRect = {
x: number;
y: number;
width: number;
height: number;
};
/** pdf.js page.view / getViewport 的最小接口,避免测试依赖完整 PdfJsModule。 */
export type PdfPageLike = {
view: number[];
rotate?: number;
};
export type PdfViewportLike = {
width: number;
height: number;
convertToViewportRectangle: (rect: number[]) => number[];
};
/**
* 把左上原点归一化 bbox 转为 canvas 像素矩形(含页面旋转)。
* 核心逻辑:归一化 → PDF 用户空间(左下)→ viewport.convertToViewportRectangle → min/max 规整。
* @param bbox - 后端 highlight_bbox(相对未旋转页宽高的 0..1)
* @param page - PDF.js page(读取 media box)
* @param viewport - 已按 scale/rotation 创建的 viewport
* @returns 可直接 strokeRect 的像素矩形;非法输入返回 null
*/
export function normalizedTopLeftBBoxToViewportRect(
bbox: NormalizedBBox | null | undefined,
page: PdfPageLike,
viewport: PdfViewportLike,
): ViewportRect | null {
if (!bbox) return null;
const { x0, y0, x1, y1 } = bbox;
if (![x0, y0, x1, y1].every((n) => Number.isFinite(n))) return null;
if (x1 <= x0 || y1 <= y0) return null;
if (x0 < 0 || y0 < 0 || x1 > 1.0001 || y1 > 1.0001) return null;
const view = Array.isArray(page.view) ? page.view : [0, 0, 0, 0];
const pageWidth = Number(view[2]) - Number(view[0]);
const pageHeight = Number(view[3]) - Number(view[1]);
if (!(pageWidth > 0) || !(pageHeight > 0)) return null;
// [STEP 1] 左上归一化 → PDF 用户空间绝对坐标(左下原点)
const pdfX0 = Number(view[0]) + x0 * pageWidth;
const pdfX1 = Number(view[0]) + x1 * pageWidth;
const pdfY0 = Number(view[1]) + (1 - y1) * pageHeight;
const pdfY1 = Number(view[1]) + (1 - y0) * pageHeight;
// [STEP 2] 经 viewport 矩阵(含 rotate)映射到 canvas;旋转后可能颠倒,取 min/max
const mapped = viewport.convertToViewportRectangle([pdfX0, pdfY0, pdfX1, pdfY1]);
if (!Array.isArray(mapped) || mapped.length < 4) return null;
const a = Number(mapped[0]);
const b = Number(mapped[1]);
const c = Number(mapped[2]);
const d = Number(mapped[3]);
if (![a, b, c, d].every((n) => Number.isFinite(n))) return null;
const left = Math.min(a, c);
const top = Math.min(b, d);
const width = Math.abs(c - a);
const height = Math.abs(d - b);
if (!(width > 0) || !(height > 0)) return null;
return { x: left, y: top, width, height };
}
@@ -4,7 +4,7 @@
* 用途:渲染单个 PDF 的订单抽取结果摘要,供详情抽屉按文档逐项展示。
* 依赖:订单抽取文档 DTO、vue-i18n。
* 逻辑:默认只展示状态/PO/行数/阻断原因;审计与补充信息收入详情折叠;
* 「查看证据」与「人工复核」分别携带 focus+documentId;未知原因码回退通用文案并展开技术码。
* 「查看证据」与「人工复核」分别携带 focus+documentId;内部错误码只转为业务提示。
*/
import { computed } from 'vue';
import { useI18n } from 'vue-i18n';
@@ -46,7 +46,10 @@ const statusTone = computed(() => {
}
});
const statusLabel = computed(() => t(`chat.shippingOrderExtractionDocumentStatus.${props.document.status}`));
const statusLabel = computed(() => {
const key = `chat.shippingOrderExtractionDocumentStatus.${props.document.status}`;
return te(key) ? t(key) : t('chat.shippingOrderExtractionDocumentStatus.unknown');
});
const statusActivityLabel = computed(() => {
const key = `chat.shippingOrderExtractionActivity.${props.document.activity_event_code || props.document.status}`;
return te(key) ? t(key) : statusLabel.value;
@@ -74,13 +77,6 @@ const reasonLabel = computed(() => {
}
return t('chat.shippingOrderExtractionReasonUnknown');
});
const reasonTechnicalCode = computed(() => {
const code = String(props.document.reason_code || '').trim();
if (!code) return '';
const key = `chat.shippingOrderExtractionReason.${code}`;
if (te(key) || code.startsWith('SHIPPING_NOTICE.')) return '';
return code;
});
const emailSupplementLabel = computed(() => {
const status = props.document.email_supplement?.status || 'none';
const key = `chat.shippingOrderExtractionEmailSupplement.${status}`;
@@ -90,7 +86,7 @@ const emailSupplementRelations = computed(() => (
(props.document.email_supplement?.relation_codes || [])
.map((code) => {
const key = `chat.shippingOrderExtractionEmailSupplementRelation.${code}`;
return te(key) ? t(key) : code;
return te(key) ? t(key) : t('chat.shippingOrderExtractionEmailSupplementRelation.unknown');
})
));
const reservationStatusLabel = computed(() => {
@@ -110,13 +106,13 @@ const routeTypeLabel = computed(() => {
const code = String(props.document.route_type || '').trim();
if (!code) return '';
const key = `chat.shippingOrderExtractionRouteType.${code}`;
return te(key) ? t(key) : code;
return te(key) ? t(key) : t('chat.shippingOrderExtractionRouteType.unknown');
});
const freezeSourceLabel = computed(() => {
const code = String(props.document.freeze_source || '').trim();
if (!code) return '';
const key = `chat.shippingOrderExtractionFreezeSource.${code}`;
return te(key) ? t(key) : code;
return te(key) ? t(key) : t('chat.shippingOrderExtractionFreezeSource.unknown');
});
const budgetCostLabel = computed(() => {
if (!props.document.budget_cost) return '';
@@ -129,7 +125,7 @@ const budgetCostLabel = computed(() => {
const reviewDetails = computed(() => props.document.review_details || []);
const reviewFieldLabel = (fieldCode: string | null | undefined): string => {
const key = `chat.shippingOrderExtractionReviewField.${fieldCode || ''}`;
return fieldCode && te(key) ? t(key) : (fieldCode || t('chat.shippingOrderExtractionReviewField.unknown'));
return fieldCode && te(key) ? t(key) : t('chat.shippingOrderExtractionReviewField.unknown');
};
const canEnterManualReview = computed(() => (
@@ -190,10 +186,6 @@ const hasAuditDetails = computed(() => Boolean(
<!-- 异常信息 -->
<div v-if="reasonLabel" class="mt-2 text-xs font-medium opacity-90">
{{ reasonLabel }}
<details v-if="reasonTechnicalCode" class="mt-1 font-normal opacity-80">
<summary class="cursor-pointer">{{ t('chat.shippingOrderExtractionReasonTechDetails') }}</summary>
<code class="mt-1 block break-all text-[11px]">{{ reasonTechnicalCode }}</code>
</details>
</div>
<ul v-if="reviewDetails.length" class="mt-2 space-y-1 text-xs font-medium opacity-90">
<li v-for="detail in reviewDetails" :key="`${detail.line_number}-${detail.field_code || 'general'}`">
@@ -4,15 +4,17 @@
* 依赖:订单抽取 Run 状态卡 DTO、shipping.api 文档/进度接口、ShippingOrderExtractionDetailsDrawer、
* orderExtractionProgressDisplay、Workflow 计数投影、vue-router、vue-i18n。
* 逻辑:有 Workflow 投影时优先展示统一 counts;否则回退 handling_items / primary_notice;
* Run 失败优先展示 errorExplainability.message(含 request_id 提示),禁止只展示技术错误码;
* 「查看处理详情」挂载详情抽屉;抽屉内证据/复核入口携带 focus+document_id 打开复核页;
* 用户界面只展示业务原因,内部错误码仅保留在管理员审计中;
* 文档与时间线加载失败支持独立就地重试;右侧 ShippingWorkflowTimeline 承接逐 PDF 明细。
* 文档与时间线加载失败支持独立就地重试;右侧 ShippingWorkflowTimeline 承接逐 PDF 明细;
* Gate confirm_customer 经 ChatPage 打开客户选择弹窗。
*/
<script setup lang="ts">
import { computed, inject, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { useRoute, useRouter } from 'vue-router';
import { CircleCheck, CircleX, LoaderCircle, TriangleAlert } from 'lucide-vue-next';
import { CHAT_PAGE_KEY } from '@/features/chat/composables/chat.context';
import type {
ShippingOrderExtractionHandlingItemState,
ShippingOrderExtractionState,
@@ -59,10 +61,18 @@ const emit = defineEmits<{
const { t, te } = useI18n();
const route = useRoute();
const router = useRouter();
const chatPage = inject(CHAT_PAGE_KEY, null);
const confirmCancelOpen = ref(false);
const cancelReason = ref('');
const injectedWorkflow = inject(SHIPPING_WORKFLOW_KEY, null);
/**
* Gate 恢复卡「确认客户」:打开对话叠层客户选择弹窗。
*/
async function onGateConfirmCustomer(taskNo: string) {
await chatPage?.openShippingCustomerDialog?.(taskNo);
}
/**
* 从 Workflow Items 中取首个阻断 Gate 摘要,供 Run 级卡片展示。
*/
@@ -219,8 +229,11 @@ const compactLine = computed(() => {
case 'review_required':
return t('chat.shippingSessionSummary.processNoticeNeedsAction');
case 'failed':
case 'cancelled':
case 'cancelled': {
const explained = String(props.state.errorExplainability?.message || '').trim();
if (explained) return explained;
return t('chat.shippingSessionSummary.processNoticeFailed');
}
default: {
if (props.state.status === 'queued' || props.state.status === 'processing') {
const parts: string[] = [];
@@ -399,23 +412,29 @@ async function enterReviewFromDetails(payload?: { focus?: 'evidence' | 'draft';
}
/**
* 打开任务工作台,定位自动冻结受阻等任务号。
* 在对话侧聚焦 Task(双工作台主路径);Task 工作台仅作备用深链。
*/
async function openTaskWorkbench(taskNo: string) {
async function focusTaskInChat(taskNo: string) {
const normalized = String(taskNo || '').trim();
if (!normalized) return;
await router.push({
name: 'workspace-shipping-tasks',
params: { taskNo: normalized },
const conversationId = String(route.query.conversation_id || '').trim();
await router.replace({
name: 'Chat',
params: { agentId: String(route.params.agentId || '') },
query: {
...route.query,
conversation_id: conversationId || undefined,
focus_task_no: normalized,
},
});
}
/**
* 按受影响对象引用跳转到任务或复核入口。
* 按受影响对象引用跳转到对话聚焦或复核入口。
*/
async function openAffectedRef(target: ShippingHandlingRefTarget) {
if (target.kind === 'task') {
await openTaskWorkbench(target.taskNo);
if (target.kind === 'chat_focus_task') {
await focusTaskInChat(target.taskNo);
return;
}
if (target.kind === 'review') {
@@ -498,6 +517,13 @@ function openCancelConfirm() {
<div class="min-w-0 flex-1">
<div class="text-sm font-medium">{{ compactLine }}</div>
<p
v-if="state.errorExplainability?.request_id"
class="mt-1 text-[11px] opacity-80"
data-testid="shipping-order-extraction-error-request-id"
>
{{ t('chat.shippingOrderExtractionErrorRequestId', { id: state.errorExplainability.request_id }) }}
</p>
<div
v-if="displaySummary.totalDocuments > 0"
@@ -542,6 +568,7 @@ function openCancelConfirm() {
:navigation-context="gateNavigationContext"
@refreshed="emit('refresh')"
@refresh-needed="emit('refresh')"
@confirm-customer="(taskNo) => void onGateConfirmCustomer(taskNo)"
/>
<div
@@ -5,7 +5,7 @@
* 依赖:订单抽取状态卡、文档结果项、订单抽取 progress-events DTO、vue-i18n。
* 逻辑:聊天摘要卡只显示概览;需要查看逐文档结果和每轮事件原因时由本抽屉承接;
* 以模态对话框语义呈现(初始焦点、Tab 陷阱、Escape/关闭后焦点恢复);
* 文档与时间线加载失败分别提供就地重试。
* 文档与时间线加载失败分别提供就地重试;内部错误码不向普通用户展示。
*/
import { nextTick, onBeforeUnmount, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
@@ -284,9 +284,7 @@ onBeforeUnmount(() => {
}) }}
</div>
<div v-if="state.unitSummary?.technicalFailureReasonCodes?.length" class="mt-1">
{{ t('chat.shippingOrderExtractionTechnicalFailureCodes', {
codes: state.unitSummary.technicalFailureReasonCodes.join(', '),
}) }}
{{ t('chat.shippingOrderExtractionTechnicalFailureUserHint') }}
</div>
</div>
<div
@@ -133,4 +133,30 @@ describe('ShippingWorkflowItemDetailDrawer', () => {
expect(wrapper.emitted('close')).toBeTruthy();
wrapper.unmount();
});
it('does not expose unknown workflow status or event codes', () => {
const wrapper = mount(ShippingWorkflowItemDetailDrawer, {
props: {
open: true,
item: buildItem({
lifecycle_status: 'internal_future_status',
current_stage: 'internal_future_status',
events: [{
seq_no: 1,
event_code: 'internal_future_event',
actor_type: 'system',
occurred_at: '2026-07-30T10:00:00Z',
}],
}),
},
global: { plugins: [i18n] },
attachTo: document.body,
});
const text = drawerRoot()?.textContent || '';
expect(text).toContain('状态待确认');
expect(text).toContain('处理状态已更新');
expect(text).not.toContain('internal_future_status');
expect(text).not.toContain('internal_future_event');
wrapper.unmount();
});
});
@@ -1,8 +1,10 @@
/**
* features/chat/components/shipping/ShippingWorkflowItemDetailDrawer.vue
* 用途:单个 WorkflowItem(PDF)详情抽屉——文件名、阶段、事件时间线、取消/重识别入口。
* 依赖:vue-i18n、ShippingWorkflowItem / Event 类型、lucide-vue-next。
* 逻辑:由 ShippingWorkflowTimeline 打开;展示 filename / current_stage / events;
* 用途:单个 WorkflowItem(PDF)详情抽屉——文件名、阶段、Process Gate 恢复、事件时间线。
* 依赖:vue-i18n、ProcessGateRecoveryCard、ShippingWorkflowItem / Event 类型、lucide-vue-next。
* 逻辑:由 ShippingWorkflowTimeline 打开;状态优先 display_lifecycle_status;
* 有阻断 Gate 时内嵌 RecoveryCard(对话内完成重试/接管,不绕过后端状态机);
* confirm_customer 向上转发由 Timeline 打开客户弹窗;
* 取消与重识别以后端 available_actions 为准,仅 emit 由父级收集原因;
* 禁止发明百分比与 ETA。以模态对话框语义呈现:初始焦点、Tab 陷阱、Escape/关闭后焦点恢复。
*/
@@ -10,6 +12,7 @@
import { computed, nextTick, onBeforeUnmount, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { X } from 'lucide-vue-next';
import ProcessGateRecoveryCard from '@/features/shipping-process-gates/components/ProcessGateRecoveryCard.vue';
import type { ShippingWorkflowEvent, ShippingWorkflowItem } from '@/features/chat/types/shipping.api.types';
const props = defineProps<{
@@ -24,6 +27,8 @@ const emit = defineEmits<{
close: [];
cancel: [item: ShippingWorkflowItem];
reparse: [item: ShippingWorkflowItem];
refreshed: [];
confirmCustomer: [taskNo: string];
}>();
const { t, te, locale } = useI18n();
@@ -83,7 +88,7 @@ function statusLabel(status?: string | null): string {
const normalized = String(status || '').trim();
if (!normalized) return '';
const key = `chat.shippingWorkflow.itemStatus.${normalized}`;
return te(key) ? t(key) : normalized;
return te(key) ? t(key) : t('chat.shippingWorkflow.itemStatus.unknown');
}
/**
@@ -93,7 +98,7 @@ function eventLabel(event: ShippingWorkflowEvent): string {
const code = String(event.message_code || event.event_code || '').trim();
if (!code) return '—';
const key = `chat.shippingWorkflow.event.${code}`;
return te(key) ? t(key) : code;
return te(key) ? t(key) : t('chat.shippingWorkflow.event.unknown');
}
/**
@@ -241,7 +246,9 @@ onBeforeUnmount(() => {
</div>
<div class="flex justify-between gap-2">
<dt class="text-secondary">{{ t('chat.shippingWorkflow.detail.status') }}</dt>
<dd class="font-medium text-primary">{{ statusLabel(item.lifecycle_status) }}</dd>
<dd class="font-medium text-primary">{{
statusLabel(item.display_lifecycle_status || item.lifecycle_status)
}}</dd>
</div>
<div class="flex justify-between gap-2">
<dt class="text-secondary">{{ t('chat.shippingWorkflow.detail.stage') }}</dt>
@@ -269,6 +276,17 @@ onBeforeUnmount(() => {
</div>
</dl>
<ProcessGateRecoveryCard
v-if="item.process_gate?.current_blocking_gate"
class="mt-4"
:summary="item.process_gate"
:can-handle="true"
data-testid="shipping-workflow-item-drawer-process-gate"
@refreshed="emit('refreshed')"
@refresh-needed="emit('refreshed')"
@confirm-customer="(taskNo) => emit('confirmCustomer', taskNo)"
/>
<section class="mt-4">
<h3 class="text-xs font-semibold text-secondary">
{{ t('chat.shippingWorkflow.detail.eventsTitle') }}
@@ -2,7 +2,7 @@
* features/chat/components/shipping/ShippingWorkflowTimeline.spec.ts
* 用途:验证右侧 Workflow 时间线分组、文件名、批次切换、过滤与取消/重识别弹窗。
* 依赖:Vitest、Vue Test Utils、vue-i18n、shipping.api mock。
* 逻辑:断言 layout_parsing 可见;文件名优先;仅看待处理过滤;原因弹窗提交 cancelItem。
* 逻辑:先展开侧栏并打开详情抽屉;断言 layout_parsing 可见;文件名优先;过滤与 cancel。
*/
import { mount, flushPromises } from '@vue/test-utils';
import { describe, expect, it, vi, beforeEach } from 'vitest';
@@ -13,6 +13,12 @@ import ShippingWorkflowTimeline from './ShippingWorkflowTimeline.vue';
import type { ShippingWorkflow, ShippingWorkflowItem } from '../../types/shipping.api.types';
import type { UseShippingNoticeWorkflowReturn } from '../../shipping/useShippingNoticeWorkflow';
const routerPush = vi.fn(async () => undefined);
vi.mock('vue-router', () => ({
useRoute: () => ({ params: { agentId: 'agent-1' }, query: {} }),
useRouter: () => ({ push: routerPush }),
}));
vi.mock('@/features/chat/api/shipping.api', () => ({
getWorkspaceShippingWorkflowItem: vi.fn(async (itemNo: string) => ({
item_no: itemNo,
@@ -105,9 +111,36 @@ function buildController(
};
}
/**
* 展开窄侧栏并打开详情抽屉(完整列表仅在抽屉内)。
*/
async function openDetailsDrawer(wrapper: ReturnType<typeof mount>) {
const toggleCollapse = wrapper.find('[data-testid="shipping-workflow-timeline"] button');
if (toggleCollapse.exists()) {
await toggleCollapse.trigger('click');
await flushPromises();
}
const openDetails = wrapper.find('[data-testid="shipping-workflow-toggle-details"]');
expect(openDetails.exists()).toBe(true);
await openDetails.trigger('click');
await flushPromises();
expect(wrapper.find('[data-testid="shipping-workflow-details-drawer"]').exists()).toBe(true);
}
const mountOptions = {
global: {
plugins: [i18n],
stubs: {
// 抽屉/原因框经 Teleport;单测就地渲染便于查询。
teleport: true,
},
},
};
describe('ShippingWorkflowTimeline', () => {
beforeEach(() => {
document.body.innerHTML = '';
routerPush.mockClear();
});
it('shows layout_parsing items with filename before review case exists', async () => {
@@ -122,9 +155,11 @@ describe('ShippingWorkflowTimeline', () => {
]);
const wrapper = mount(ShippingWorkflowTimeline, {
props: { conversationId: 'conv-1', controller },
global: { plugins: [i18n] },
...mountOptions,
});
await flushPromises();
await openDetailsDrawer(wrapper);
await wrapper.find('[data-testid="shipping-workflow-pending-only-filter"]').setValue(false);
expect(wrapper.find('[data-testid="shipping-workflow-item-SWI-LAYOUT"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="shipping-workflow-item-SWI-LAYOUT"]').text()).toContain('layout.pdf');
expect(wrapper.text()).toContain('尚无复核单');
@@ -139,29 +174,56 @@ describe('ShippingWorkflowTimeline', () => {
]);
const wrapper = mount(ShippingWorkflowTimeline, {
props: { conversationId: 'conv-1', controller },
global: { plugins: [i18n] },
...mountOptions,
});
await flushPromises();
await openDetailsDrawer(wrapper);
await wrapper.find('[data-testid="shipping-workflow-pending-only-filter"]').setValue(true);
expect(wrapper.find('[data-testid="shipping-workflow-item-SWI-B"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="shipping-workflow-item-SWI-A"]').exists()).toBe(false);
});
it('opens the review workspace directly for pending review items', async () => {
const controller = buildController([
buildItem({
item_no: 'SWI-REVIEW-OPEN',
lifecycle_status: 'pending_review',
current_run_no: 'RUN-REVIEW-1',
current_case_no: 'CASE-REVIEW-1',
current_document_id: 42,
}),
]);
const wrapper = mount(ShippingWorkflowTimeline, {
props: { conversationId: 'conv-1', controller },
...mountOptions,
});
await flushPromises();
await openDetailsDrawer(wrapper);
await wrapper.find('[data-testid="shipping-workflow-action-open-review"]').trigger('click');
expect(routerPush).toHaveBeenCalledWith(expect.objectContaining({
name: 'Chat',
params: { agentId: 'agent-1' },
query: expect.objectContaining({
mode: 'order-review',
run_no: 'RUN-REVIEW-1',
case_no: 'CASE-REVIEW-1',
document_id: '42',
focus: 'draft',
}),
}));
});
it('cancels an item via in-app reason dialog', async () => {
const controller = buildController([
buildItem({ item_no: 'SWI-CANCEL', lifecycle_status: 'extracting', lock_version: 3 }),
]);
const wrapper = mount(ShippingWorkflowTimeline, {
props: { conversationId: 'conv-1', controller },
global: {
plugins: [i18n],
stubs: {
// 让 Teleport 就地渲染,便于 setValue / trigger
teleport: true,
},
},
...mountOptions,
});
await flushPromises();
await openDetailsDrawer(wrapper);
await wrapper.find('[data-testid="shipping-workflow-pending-only-filter"]').setValue(false);
await wrapper.find('[data-testid="shipping-workflow-action-cancel"]').trigger('click');
await flushPromises();
const reasonInput = wrapper.find('[data-testid="shipping-workflow-reason-input"]');
@@ -201,9 +263,10 @@ describe('ShippingWorkflowTimeline', () => {
const controller = buildController(itemsA, { workflows });
const wrapper = mount(ShippingWorkflowTimeline, {
props: { conversationId: 'conv-1', controller },
global: { plugins: [i18n] },
...mountOptions,
});
await flushPromises();
await openDetailsDrawer(wrapper);
expect(wrapper.find('[data-testid="shipping-workflow-batch-switcher"]').exists()).toBe(true);
await wrapper.find('[data-testid="shipping-workflow-batch-SNWF-B"]').trigger('click');
expect(controller.selectWorkflow).toHaveBeenCalledWith('SNWF-B');
@@ -221,9 +284,10 @@ describe('ShippingWorkflowTimeline', () => {
]);
const wrapper = mount(ShippingWorkflowTimeline, {
props: { conversationId: 'conv-1', controller },
global: { plugins: [i18n] },
...mountOptions,
});
await flushPromises();
await openDetailsDrawer(wrapper);
expect(wrapper.find('[data-testid="shipping-workflow-action-reparse"]').exists()).toBe(true);
expect(wrapper.text()).toContain('重试失败识别');
});
@@ -240,9 +304,27 @@ describe('ShippingWorkflowTimeline', () => {
]);
const wrapper = mount(ShippingWorkflowTimeline, {
props: { conversationId: 'conv-1', controller },
global: { plugins: [i18n] },
...mountOptions,
});
await flushPromises();
await openDetailsDrawer(wrapper);
expect(wrapper.find('[data-testid="shipping-workflow-action-reparse"]').exists()).toBe(false);
});
it('keeps sidebar width when opening details dialog overlay', async () => {
const controller = buildController([buildItem()]);
const wrapper = mount(ShippingWorkflowTimeline, {
props: { conversationId: 'conv-1', controller },
...mountOptions,
});
await flushPromises();
await openDetailsDrawer(wrapper);
const aside = wrapper.find('[data-testid="shipping-workflow-timeline"]');
// 关键断言:弹层打开后侧栏仍固定窄宽,对话区不被列表撑开。
expect(aside.classes().join(' ')).toContain('md:w-60');
const overlay = wrapper.find('[data-testid="shipping-workflow-details-drawer"]');
expect(overlay.exists()).toBe(true);
expect(overlay.classes().join(' ')).toContain('fixed');
expect(overlay.find('[role="dialog"]').exists()).toBe(true);
});
});
@@ -1,11 +1,11 @@
/**
* features/chat/components/shipping/ShippingWorkflowTimeline.vue
* 用途:聊天页右侧「本次处理」面板——以会话 Workflow / Items 为列表事实源。
* 依赖:vue-i18n、useMessage、useShippingNoticeWorkflow(inject 或自建)、DetailDrawer、ReasonDialog。
* 逻辑:多批次时展示切换器;Items 以文件名为主标题;
* 分组进行中/待处理/待复核/待人工上传登记/失败/已完成(登记前不得进已完成);
* 「仅看待处理」过滤;待复核项提供直接进入复核工作台;查看进度 / 取消 / 重试重识别;
* 取消与重识别用应用内原因弹窗。侧栏在桌面端可收窄,在窄屏自动占满宽度。
* 用途:聊天页右侧「本次处理中」面板——会话处理对象投影 + Workflow Items 列表。
* 依赖:vue-i18n、useMessage、useShippingNoticeWorkflow、conversationProcessingProjection、
* DetailDrawer、ReasonDialog、ProcessGateRecoveryCard。
* 逻辑:默认轻量摘要(当前对象 / Gate 恢复 / 错误);批次/统计/完整文件列表经 Teleport
* 打开居中弹层(不改侧栏宽度、不压缩对话 flex);窄侧栏固定 md:w-60;
* focus_task_no 聚焦;Task 留在对话侧;confirm_customer 打开对话客户弹窗。
*/
<script setup lang="ts">
import { computed, inject, ref, watch } from 'vue';
@@ -14,14 +14,20 @@ import { useRoute, useRouter } from 'vue-router';
import { ChevronDown, ChevronRight, RefreshCw } from 'lucide-vue-next';
import { BusinessError } from '@/shared/api/client';
import { useMessage } from '@/shared/composables/useMessage';
import { CHAT_PAGE_KEY } from '@/features/chat/composables/chat.context';
import ProcessGateRecoveryCard from '@/features/shipping-process-gates/components/ProcessGateRecoveryCard.vue';
import {
getWorkspaceShippingWorkflowItem,
} from '@/features/chat/api/shipping.api';
import type {
ConversationProcessingObject,
ShippingWorkflow,
ShippingWorkflowItem,
} from '@/features/chat/types/shipping.api.types';
import {
projectConversationProcessingObjects,
resolveItemDisplayStatus,
} from '@/features/chat/shipping/conversationProcessingProjection';
import {
SHIPPING_WORKFLOW_KEY,
useShippingNoticeWorkflow,
@@ -44,12 +50,20 @@ const { t, te, locale } = useI18n();
const msg = useMessage();
const route = useRoute();
const router = useRouter();
const chatPage = inject(CHAT_PAGE_KEY, null);
const gateNavigationContext = computed(() => ({
agentId: String(route.params.agentId || ''),
conversationId: String(props.conversationId || route.query.conversation_id || ''),
}));
/**
* Gate「确认客户」:打开对话叠层客户选择弹窗(非跳转复核)。
*/
async function onGateConfirmCustomer(taskNo: string) {
await chatPage?.openShippingCustomerDialog?.(taskNo);
}
const injected = inject(SHIPPING_WORKFLOW_KEY, null);
/** 父级已 provide/传入时本地 composable 以空 conversationId 待机,避免双轮询。 */
const localController = useShippingNoticeWorkflow({
@@ -64,8 +78,13 @@ const ctl = computed((): UseShippingNoticeWorkflowReturn => (
props.controller || injected || localController
));
const collapsed = ref(false);
const pendingOnlyFilter = ref(false);
/** 默认收起侧栏,避免持续压缩对话区;用户可一键展开轻量摘要。 */
const collapsed = ref(true);
/** 默认折叠批次/统计/文件列表,保持「本次处理中」轻量(完整列表进抽屉)。 */
const showExtendedDetails = ref(false);
/** 复核返回对话时展示的聚焦提示(由 focus_notice 触发一次)。 */
const focusTaskBanner = ref<string | null>(null);
const pendingOnlyFilter = ref(true);
const actionBusyItemNo = ref<string | null>(null);
const detailOpen = ref(false);
const detailLoading = ref(false);
@@ -100,6 +119,8 @@ async function openReview(item: ShippingWorkflowItem) {
if (caseNo) query.case_no = caseNo;
const conversationId = String(props.conversationId || route.query.conversation_id || '').trim();
if (conversationId) query.conversation_id = conversationId;
const taskNo = String(item.current_task_no || route.query.focus_task_no || '').trim();
if (taskNo) query.focus_task_no = taskNo;
await router.push({
name: 'Chat',
params: { agentId: String(route.params.agentId || '') },
@@ -107,6 +128,67 @@ async function openReview(item: ShippingWorkflowItem) {
});
}
/**
* 在对话侧聚焦 Task(不跳转 Task 工作台)。
*/
async function focusTaskInChat(taskNo: string) {
const normalized = String(taskNo || '').trim();
if (!normalized) return;
const conversationId = String(props.conversationId || route.query.conversation_id || '').trim();
await router.replace({
name: 'Chat',
params: { agentId: String(route.params.agentId || '') },
query: {
...route.query,
conversation_id: conversationId || undefined,
focus_task_no: normalized,
},
});
await ctl.value.refresh?.();
}
/**
* 「本次处理中」对象行:Run / Candidate / Task / Process Gate。
*/
const processingObjects = computed((): ConversationProcessingObject[] => (
projectConversationProcessingObjects(items.value, {
focusTaskNo: String(route.query.focus_task_no || ''),
focusRunNo: String(route.query.focus_run_no || route.query.run_no || ''),
focusCandidateNo: String(route.query.focus_candidate_no || route.query.candidate || ''),
})
));
/**
* 点击聚合对象行:Task 聚焦对话,Candidate/Run 打开复核,Gate 展开详情。
*/
async function onProcessingObjectClick(row: ConversationProcessingObject) {
if (row.kind === 'task' && row.task_no) {
await focusTaskInChat(row.task_no);
return;
}
if ((row.kind === 'candidate' || row.kind === 'run') && row.run_no) {
const match = items.value.find((item) => (
String(item.current_run_no || '') === String(row.run_no)
|| String(item.current_case_no || '') === String(row.case_no || '')
));
if (match) {
await openReview(match);
return;
}
}
// Process Gate:对话内展开详情(含 RecoveryCard),不跳转备用深链。
if (row.kind === 'process_gate' || row.workflow_item_no) {
const match = items.value.find((item) => (
item.item_no === row.workflow_item_no
|| (row.task_no && String(item.current_task_no || '').toUpperCase() === String(row.task_no).toUpperCase())
));
if (match) {
if (row.task_no) await focusTaskInChat(row.task_no);
await openDetail(match);
}
}
}
const counts = computed(() => workflow.value?.counts || {
total: items.value.length,
processing: 0,
@@ -138,6 +220,7 @@ const FAILED_STATUSES = new Set(['failed', 'reparse_failed']);
/** 真正完成/取消;待人工登记不是完成。 */
const COMPLETED_STATUSES = new Set(['closed', 'cancelled']);
const WAITING_MANUAL_UPLOAD_STATUSES = new Set(['manual_upload_pending']);
const UPLOAD_RPA_RUNNING_STATUSES = new Set(['upload_rpa_pending', 'upload_rpa_running']);
const PENDING_REVIEW_STATUSES = new Set(['pending_review']);
const ACTIONABLE_FILTER_STATUSES = new Set([
'pending_review',
@@ -145,16 +228,39 @@ const ACTIONABLE_FILTER_STATUSES = new Set([
'reparse_failed',
'queued',
'manual_upload_pending',
'upload_rpa_pending',
'upload_rpa_running',
'upload_rpa_failed',
]);
/**
* 将 Item 归入展示分组。
* 将 Item 归入展示分组;优先 is_waiting_manual_upload / display(禁止单靠 lifecycle 推断人工待办)。
*/
function resolveGroup(item: ShippingWorkflowItem): ItemGroupKey {
const display = resolveItemDisplayStatus(item);
if (PENDING_REVIEW_STATUSES.has(display)) return 'pending_review';
if (FAILED_STATUSES.has(display) || display === 'upload_rpa_failed') return 'failed';
if (UPLOAD_RPA_RUNNING_STATUSES.has(display)) return 'processing';
if (item.is_waiting_manual_upload === true || item.upload_phase === 'manual_pending') {
return 'waiting_manual_upload';
}
if (WAITING_MANUAL_UPLOAD_STATUSES.has(display) && item.is_waiting_manual_upload !== false) {
return 'waiting_manual_upload';
}
const status = String(item.lifecycle_status || '').trim();
if (PENDING_REVIEW_STATUSES.has(status)) return 'pending_review';
if (FAILED_STATUSES.has(status)) return 'failed';
if (WAITING_MANUAL_UPLOAD_STATUSES.has(status)) return 'waiting_manual_upload';
if (
item.is_waiting_manual_upload !== false
&& WAITING_MANUAL_UPLOAD_STATUSES.has(status)
&& !UPLOAD_RPA_RUNNING_STATUSES.has(display)
&& display !== 'upload_rpa_failed'
&& item.upload_phase !== 'rpa_pending'
&& item.upload_phase !== 'rpa_running'
&& item.upload_phase !== 'rpa_failed'
) {
return 'waiting_manual_upload';
}
if (COMPLETED_STATUSES.has(status)) return 'completed';
if (QUEUED_STATUSES.has(status)) return 'queued';
if (PROCESSING_STATUSES.has(status)) return 'processing';
@@ -203,9 +309,13 @@ function itemTitle(item: ShippingWorkflowItem): string {
const filteredItems = computed(() => {
if (!pendingOnlyFilter.value) return items.value;
return items.value.filter((item) =>
ACTIONABLE_FILTER_STATUSES.has(String(item.lifecycle_status || '').trim()),
);
return items.value.filter((item) => {
const display = resolveItemDisplayStatus(item);
return (
ACTIONABLE_FILTER_STATUSES.has(display)
|| ACTIONABLE_FILTER_STATUSES.has(String(item.lifecycle_status || '').trim())
);
});
});
const grouped = computed(() => {
@@ -393,12 +503,39 @@ watch(
/* 面板内展示 network_recoverable,不弹 toast */
},
);
/**
* 复核返回对话:展开侧栏并短暂提示已聚焦 Task,避免误以为未打开进度。
*/
watch(
() => [route.query.focus_task_no, route.query.focus_notice] as const,
async ([taskNo, notice]) => {
const normalized = String(taskNo || '').trim();
if (!normalized) {
focusTaskBanner.value = null;
return;
}
if (String(notice || '') !== '1' && !focusTaskBanner.value) {
// 无 focus_notice 时仍展开侧栏以便看到高亮对象。
collapsed.value = false;
return;
}
collapsed.value = false;
focusTaskBanner.value = normalized;
if (String(notice || '') === '1') {
const nextQuery = { ...route.query };
delete nextQuery.focus_notice;
await router.replace({ query: nextQuery });
}
},
{ immediate: true },
);
</script>
<template>
<aside
class="flex shrink-0 flex-col border-l border-default bg-surface shadow-[-8px_0_24px_rgba(15,23,42,0.04)] transition-[width] duration-200"
:class="collapsed ? 'w-14 md:w-14' : 'w-full md:w-72'"
class="flex w-full shrink-0 flex-col border-l border-default bg-surface shadow-[-8px_0_24px_rgba(15,23,42,0.04)] transition-[width] duration-200 md:w-60"
:class="collapsed ? '!w-14' : ''"
data-testid="shipping-workflow-timeline"
>
<div class="flex w-full items-center gap-1 border-b border-default px-2 py-2">
@@ -412,7 +549,10 @@ watch(
{{ t('chat.shippingWorkflow.title') }}
</div>
<div class="mt-0.5 text-xs text-secondary">
{{ t('chat.shippingWorkflow.pdfCount', { count: counts.total }) }}
{{ t('chat.shippingWorkflow.compactSummary', {
active: processingObjects.length,
total: counts.total,
}) }}
</div>
</div>
<ChevronDown v-if="!collapsed" class="h-4 w-4 shrink-0 text-muted" />
@@ -432,95 +572,50 @@ watch(
<div v-if="!collapsed" class="min-h-0 flex-1 overflow-auto p-3">
<div
v-if="showBatchSwitcher"
class="mb-3 space-y-1.5"
data-testid="shipping-workflow-batch-switcher"
v-if="focusTaskBanner"
class="mb-3 rounded-md border border-brand-200 bg-brand-50 px-2.5 py-2 text-[11px] text-brand-900 dark:border-brand-800 dark:bg-brand-950/40 dark:text-brand-100"
data-testid="shipping-focus-task-banner"
>
<div class="text-[11px] font-semibold uppercase tracking-wide text-secondary">
{{ t('chat.shippingWorkflow.batchSwitcherTitle') }}
</div>
<button
v-for="batch in workflows"
:key="batch.workflow_no"
type="button"
class="w-full rounded-lg border px-2.5 py-2 text-left transition"
:class="batch.workflow_no === selectedWorkflowNo
? 'border-brand-500 bg-brand-50/80 dark:border-brand-400 dark:bg-brand-950/30'
: 'border-default bg-surface-soft/80 hover:bg-surface-muted/50'"
:data-testid="`shipping-workflow-batch-${batch.workflow_no}`"
@click="onSelectWorkflow(batch.workflow_no)"
>
<div class="truncate text-xs font-semibold text-primary">
{{ batch.workflow_no }}
</div>
<div class="mt-0.5 text-[11px] text-secondary">
{{ statusLabel(batch.current_stage) || batch.current_stage }}
· {{ t('chat.shippingWorkflow.batchCounts', {
processing: batch.counts.processing,
pending: batch.counts.pending_review,
waiting: batch.counts.waiting_manual_upload || 0,
failed: batch.counts.failed,
completed: batch.counts.completed,
}) }}
</div>
<div v-if="batch.last_activity_at" class="mt-0.5 text-[11px] text-muted">
{{ formatBatchTime(batch.last_activity_at) }}
</div>
</button>
{{ t('chat.shippingWorkflow.focusTaskBanner', { taskNo: focusTaskBanner }) }}
</div>
<label class="mb-3 flex cursor-pointer items-center gap-2 text-[11px] text-secondary">
<input
v-model="pendingOnlyFilter"
type="checkbox"
class="rounded border-default"
data-testid="shipping-workflow-pending-only-filter"
/>
{{ t('chat.shippingWorkflow.pendingOnlyFilter') }}
</label>
<div class="mb-3 flex flex-wrap gap-1.5 text-[11px]">
<span class="rounded-md bg-sky-50 px-2 py-0.5 text-sky-700 dark:bg-sky-950/40 dark:text-sky-200">
{{ t('chat.shippingWorkflow.counts.processing', { count: counts.processing }) }}
</span>
<span
v-if="counts.pending_review > 0"
class="rounded-md bg-amber-50 px-2 py-0.5 text-amber-700 dark:bg-amber-950/40 dark:text-amber-200"
>
{{ t('chat.shippingWorkflow.counts.pendingReview', { count: counts.pending_review }) }}
</span>
<span
v-if="(counts.waiting_manual_upload || 0) > 0"
class="rounded-md bg-amber-50 px-2 py-0.5 text-amber-800 dark:bg-amber-950/40 dark:text-amber-100"
>
{{ t('chat.shippingWorkflow.counts.waitingManualUpload', {
count: counts.waiting_manual_upload || 0,
}) }}
</span>
<span class="rounded-md bg-emerald-50 px-2 py-0.5 text-emerald-700 dark:bg-emerald-950/40 dark:text-emerald-200">
{{ t('chat.shippingWorkflow.counts.completed', { count: counts.completed }) }}
</span>
<span
v-if="counts.failed > 0"
class="rounded-md bg-rose-50 px-2 py-0.5 text-rose-700 dark:bg-rose-950/40 dark:text-rose-200"
>
{{ t('chat.shippingWorkflow.counts.failed', { count: counts.failed }) }}
</span>
</div>
<button
type="button"
class="mb-3 flex w-full items-center justify-between rounded-md border border-default px-2 py-1.5 text-[11px] text-secondary hover:bg-surface-muted/50"
data-testid="shipping-workflow-toggle-details"
@click="showExtendedDetails = true"
>
<span>{{ t('chat.shippingWorkflow.showDetails') }}</span>
<ChevronRight class="h-3.5 w-3.5" />
</button>
<div
v-if="workflow?.current_stage || workflow?.last_activity_at"
class="mb-3 text-[11px] text-secondary"
data-testid="shipping-workflow-stage-summary"
v-if="processingObjects.length"
class="mb-3 space-y-1.5 rounded-lg border border-default bg-surface-soft/60 p-2"
data-testid="shipping-processing-objects"
>
<span v-if="workflow?.current_stage">
{{ t('chat.shippingWorkflow.currentStage', {
stage: statusLabel(workflow.current_stage) || workflow.current_stage,
}) }}
</span>
<span v-if="workflow?.last_activity_at" class="ml-1">
· {{ formatUpdatedLabel(workflow.last_activity_at) }}
</span>
<div class="text-[11px] font-semibold text-secondary">
{{ t('chat.shippingWorkflow.processingObjectsTitle', { count: processingObjects.length }) }}
</div>
<button
v-for="row in processingObjects"
:key="row.object_key"
type="button"
class="flex w-full items-center justify-between gap-2 rounded-md px-2 py-1.5 text-left text-xs transition"
:class="row.focused
? 'bg-brand-50 text-brand-800 dark:bg-brand-950/40 dark:text-brand-100'
: 'hover:bg-surface-muted/70 text-primary'"
:data-testid="`shipping-processing-object-${row.kind}`"
@click="onProcessingObjectClick(row)"
>
<span class="min-w-0 truncate">
<span class="font-semibold">{{ row.label }}</span>
<span class="ml-1 text-muted">{{ t(`chat.shippingWorkflow.objectKind.${row.kind}`) }}</span>
</span>
<span class="shrink-0 text-[11px] text-secondary">
{{ row.status_label || row.node_status || '' }}
</span>
</button>
</div>
<div
@@ -537,117 +632,280 @@ watch(
{{ error }}
</div>
<div v-if="!filteredItems.length" class="text-xs text-muted">
{{ loading ? t('chat.shippingWorkflow.loading') : t('chat.shippingWorkflow.empty') }}
<div
v-if="!processingObjects.length"
class="text-xs text-muted"
>
{{ loading ? t('chat.shippingWorkflow.loading') : t('chat.shippingWorkflow.emptyCompact') }}
</div>
<template v-for="groupKey in groupOrder" :key="groupKey">
<section
v-if="grouped[groupKey].length"
class="mb-3"
:data-testid="`shipping-workflow-group-${groupKey}`"
>
<h3 class="mb-1.5 text-[11px] font-semibold uppercase tracking-wide text-secondary">
{{ t(`chat.shippingWorkflow.groups.${groupKey}`) }}
</h3>
<ul class="space-y-2">
<li
v-for="item in grouped[groupKey]"
:key="item.item_no"
class="rounded-lg border border-default bg-surface-soft/80 px-2.5 py-2"
:data-testid="`shipping-workflow-item-${item.item_no}`"
>
<div class="flex items-start justify-between gap-2">
<div class="min-w-0">
<div
class="truncate text-xs font-semibold text-primary"
:title="itemTitle(item)"
data-testid="shipping-workflow-item-filename"
>
{{ itemTitle(item) }}
</div>
<div class="mt-0.5 text-[11px] text-muted">
{{ t('chat.shippingWorkflow.versionLabel', { version: item.current_version_no }) }}
· {{ statusLabel(String(item.current_stage || item.lifecycle_status || '')) }}
<span v-if="!item.current_case_no" class="ml-1 text-secondary">
· {{ t('chat.shippingWorkflow.noReviewCaseYet') }}
</span>
</div>
</div>
<span
class="shrink-0 rounded-full px-1.5 py-0.5 text-[10px] font-medium"
:class="{
'bg-amber-100 text-amber-800 dark:bg-amber-900/50 dark:text-amber-100':
groupKey === 'pending_review'
|| groupKey === 'failed'
|| groupKey === 'waiting_manual_upload',
'bg-sky-100 text-sky-800 dark:bg-sky-900/50 dark:text-sky-100':
groupKey === 'processing' || groupKey === 'queued',
'bg-emerald-100 text-emerald-800 dark:bg-emerald-900/50 dark:text-emerald-100':
groupKey === 'completed',
}"
>
{{ statusLabel(String(item.lifecycle_status || '')) }}
</span>
</div>
<div v-if="item.last_activity_at || item.updated_at" class="mt-0.5 text-[11px] text-muted">
{{ formatUpdatedLabel(item.last_activity_at || item.updated_at) }}
</div>
<ProcessGateRecoveryCard
v-if="item.process_gate?.current_blocking_gate"
class="mt-2"
:summary="item.process_gate"
:can-handle="true"
:navigation-context="gateNavigationContext"
@refreshed="() => void ctl.refresh()"
@refresh-needed="() => void ctl.refresh()"
/>
<div class="mt-2 flex flex-wrap gap-2">
<button
v-if="groupKey === 'pending_review' && item.current_run_no"
type="button"
class="inline-flex items-center gap-1 rounded-md bg-brand-600 px-2.5 py-1 text-[11px] font-semibold text-white shadow-sm hover:bg-brand-700 disabled:opacity-50"
:disabled="actionBusyItemNo === item.item_no"
data-testid="shipping-workflow-action-open-review"
@click="openReview(item)"
>
{{ t('chat.shippingWorkflow.actions.openReview') }}
</button>
<button
type="button"
class="inline-flex items-center gap-1 text-[11px] font-medium text-brand-700 hover:underline"
data-testid="shipping-workflow-action-view"
@click="openDetail(item)"
>
{{ t('chat.shippingWorkflow.actions.viewProgress') }}
</button>
<button
v-if="canReparse(item)"
type="button"
class="inline-flex items-center gap-1 text-[11px] font-medium text-amber-800 hover:underline disabled:opacity-50 dark:text-amber-200"
:disabled="actionBusyItemNo === item.item_no"
data-testid="shipping-workflow-action-reparse"
@click="openReparseDialog(item)"
>
{{ reparseActionLabel(item) }}
</button>
<button
v-if="canCancel(item)"
type="button"
class="inline-flex items-center gap-1 text-[11px] font-medium text-rose-700 hover:underline disabled:opacity-50"
:disabled="actionBusyItemNo === item.item_no"
data-testid="shipping-workflow-action-cancel"
@click="openCancelDialog(item)"
>
{{ t('chat.shippingWorkflow.actions.cancelFile') }}
</button>
</div>
</li>
</ul>
</section>
</template>
<!-- 轻量侧栏仅保留阻断 Gate;完整历史列表进抽屉,避免挤压对话区。 -->
<div
class="space-y-2"
data-testid="shipping-workflow-compact-gates"
>
<ProcessGateRecoveryCard
v-for="item in items.filter((row) => row.process_gate?.current_blocking_gate)"
:key="`gate-${item.item_no}`"
:summary="item.process_gate"
:can-handle="true"
:navigation-context="gateNavigationContext"
@refreshed="() => void ctl.refresh()"
@refresh-needed="() => void ctl.refresh()"
@confirm-customer="(taskNo) => void onGateConfirmCustomer(taskNo)"
/>
</div>
</div>
<!-- 完整详情:body 级遮罩弹层,禁止在侧栏内展开以免压缩对话区。 -->
<Teleport to="body">
<div
v-if="showExtendedDetails"
class="fixed inset-0 z-50 flex items-center justify-center p-3 sm:p-6"
data-testid="shipping-workflow-details-drawer"
>
<button
type="button"
class="absolute inset-0 bg-slate-900/45"
:aria-label="t('chat.shippingWorkflow.hideDetails')"
data-testid="shipping-workflow-details-backdrop"
@click="showExtendedDetails = false"
/>
<section
class="relative z-10 flex max-h-[min(88vh,52rem)] w-full max-w-2xl flex-col overflow-hidden rounded-xl border border-default bg-surface shadow-2xl"
role="dialog"
aria-modal="true"
:aria-label="t('chat.shippingWorkflow.detailsDrawerTitle')"
>
<div class="flex items-center justify-between gap-2 border-b border-default px-4 py-3">
<div class="min-w-0">
<div class="text-sm font-semibold text-primary">
{{ t('chat.shippingWorkflow.detailsDrawerTitle') }}
</div>
<div class="mt-0.5 text-[11px] text-secondary">
{{ t('chat.shippingWorkflow.detailsDrawerHint') }}
· {{ t('chat.shippingWorkflow.compactSummary', {
active: processingObjects.length,
total: counts.total,
}) }}
</div>
</div>
<button
type="button"
class="rounded-md px-2.5 py-1 text-[11px] font-medium text-secondary hover:bg-surface-muted"
data-testid="shipping-workflow-details-close"
@click="showExtendedDetails = false"
>
{{ t('chat.shippingWorkflow.hideDetails') }}
</button>
</div>
<div class="min-h-0 flex-1 overflow-auto p-4">
<div
v-if="showBatchSwitcher"
class="mb-3 space-y-1.5"
data-testid="shipping-workflow-batch-switcher"
>
<div class="text-[11px] font-semibold uppercase tracking-wide text-secondary">
{{ t('chat.shippingWorkflow.batchSwitcherTitle') }}
</div>
<button
v-for="batch in workflows"
:key="batch.workflow_no"
type="button"
class="w-full rounded-lg border px-2.5 py-2 text-left transition"
:class="batch.workflow_no === selectedWorkflowNo
? 'border-brand-500 bg-brand-50/80 dark:border-brand-400 dark:bg-brand-950/30'
: 'border-default bg-surface-soft/80 hover:bg-surface-muted/50'"
:data-testid="`shipping-workflow-batch-${batch.workflow_no}`"
@click="onSelectWorkflow(batch.workflow_no)"
>
<div class="truncate text-xs font-semibold text-primary">
{{ batch.workflow_no }}
</div>
<div class="mt-0.5 text-[11px] text-secondary">
{{ statusLabel(batch.current_stage) || batch.current_stage }}
· {{ t('chat.shippingWorkflow.batchCounts', {
processing: batch.counts.processing,
pending: batch.counts.pending_review,
waiting: batch.counts.waiting_manual_upload || 0,
failed: batch.counts.failed,
completed: batch.counts.completed,
}) }}
</div>
<div v-if="batch.last_activity_at" class="mt-0.5 text-[11px] text-muted">
{{ formatBatchTime(batch.last_activity_at) }}
</div>
</button>
</div>
<label class="mb-3 flex cursor-pointer items-center gap-2 text-[11px] text-secondary">
<input
v-model="pendingOnlyFilter"
type="checkbox"
class="rounded border-default"
data-testid="shipping-workflow-pending-only-filter"
/>
{{ t('chat.shippingWorkflow.pendingOnlyFilter') }}
</label>
<div
class="mb-3 flex flex-wrap gap-1.5 text-[11px]"
data-testid="shipping-workflow-counts"
>
<span class="rounded-md bg-sky-50 px-2 py-0.5 text-sky-700 dark:bg-sky-950/40 dark:text-sky-200">
{{ t('chat.shippingWorkflow.counts.processing', { count: counts.processing }) }}
</span>
<span
v-if="counts.pending_review > 0"
class="rounded-md bg-amber-50 px-2 py-0.5 text-amber-700 dark:bg-amber-950/40 dark:text-amber-200"
>
{{ t('chat.shippingWorkflow.counts.pendingReview', { count: counts.pending_review }) }}
</span>
<span
v-if="(counts.waiting_manual_upload || 0) > 0"
class="rounded-md bg-amber-50 px-2 py-0.5 text-amber-800 dark:bg-amber-950/40 dark:text-amber-100"
>
{{ t('chat.shippingWorkflow.counts.waitingManualUpload', {
count: counts.waiting_manual_upload || 0,
}) }}
</span>
<span class="rounded-md bg-emerald-50 px-2 py-0.5 text-emerald-700 dark:bg-emerald-950/40 dark:text-emerald-200">
{{ t('chat.shippingWorkflow.counts.completed', { count: counts.completed }) }}
</span>
<span
v-if="counts.failed > 0"
class="rounded-md bg-rose-50 px-2 py-0.5 text-rose-700 dark:bg-rose-950/40 dark:text-rose-200"
>
{{ t('chat.shippingWorkflow.counts.failed', { count: counts.failed }) }}
</span>
</div>
<div
v-if="workflow?.current_stage || workflow?.last_activity_at"
class="mb-3 text-[11px] text-secondary"
data-testid="shipping-workflow-stage-summary"
>
<span v-if="workflow?.current_stage">
{{ t('chat.shippingWorkflow.currentStage', {
stage: statusLabel(workflow.current_stage) || workflow.current_stage,
}) }}
</span>
<span v-if="workflow?.last_activity_at" class="ml-1">
· {{ formatUpdatedLabel(workflow.last_activity_at) }}
</span>
</div>
<template v-for="groupKey in groupOrder" :key="groupKey">
<section
v-if="grouped[groupKey].length"
class="mb-3"
:data-testid="`shipping-workflow-group-${groupKey}`"
>
<h3 class="mb-1.5 text-[11px] font-semibold uppercase tracking-wide text-secondary">
{{ t(`chat.shippingWorkflow.groups.${groupKey}`) }}
</h3>
<ul class="space-y-2">
<li
v-for="item in grouped[groupKey]"
:key="item.item_no"
class="rounded-lg border border-default bg-surface-soft/80 px-2.5 py-2"
:data-testid="`shipping-workflow-item-${item.item_no}`"
>
<div class="flex items-start justify-between gap-2">
<div class="min-w-0">
<div
class="truncate text-xs font-semibold text-primary"
:title="itemTitle(item)"
data-testid="shipping-workflow-item-filename"
>
{{ itemTitle(item) }}
</div>
<div class="mt-0.5 text-[11px] text-muted">
{{ t('chat.shippingWorkflow.versionLabel', { version: item.current_version_no }) }}
· {{ statusLabel(resolveItemDisplayStatus(item)) }}
<span v-if="!item.current_case_no" class="ml-1 text-secondary">
· {{ t('chat.shippingWorkflow.noReviewCaseYet') }}
</span>
</div>
</div>
<span
class="shrink-0 rounded-full px-1.5 py-0.5 text-[10px] font-medium"
:class="{
'bg-amber-100 text-amber-800 dark:bg-amber-900/50 dark:text-amber-100':
groupKey === 'pending_review'
|| groupKey === 'failed'
|| groupKey === 'waiting_manual_upload',
'bg-sky-100 text-sky-800 dark:bg-sky-900/50 dark:text-sky-100':
groupKey === 'processing' || groupKey === 'queued',
'bg-emerald-100 text-emerald-800 dark:bg-emerald-900/50 dark:text-emerald-100':
groupKey === 'completed',
}"
>
{{ statusLabel(resolveItemDisplayStatus(item)) }}
</span>
</div>
<div v-if="item.last_activity_at || item.updated_at" class="mt-0.5 text-[11px] text-muted">
{{ formatUpdatedLabel(item.last_activity_at || item.updated_at) }}
</div>
<ProcessGateRecoveryCard
v-if="item.process_gate?.current_blocking_gate"
class="mt-2"
:summary="item.process_gate"
:can-handle="true"
:navigation-context="gateNavigationContext"
@refreshed="() => void ctl.refresh()"
@refresh-needed="() => void ctl.refresh()"
@confirm-customer="(taskNo) => void onGateConfirmCustomer(taskNo)"
/>
<div class="mt-2 flex flex-wrap gap-2">
<button
v-if="groupKey === 'pending_review' && item.current_run_no"
type="button"
class="inline-flex items-center gap-1 rounded-md bg-brand-600 px-2.5 py-1 text-[11px] font-semibold text-white shadow-sm hover:bg-brand-700 disabled:opacity-50"
:disabled="actionBusyItemNo === item.item_no"
data-testid="shipping-workflow-action-open-review"
@click="openReview(item)"
>
{{ t('chat.shippingWorkflow.actions.openReview') }}
</button>
<button
type="button"
class="inline-flex items-center gap-1 text-[11px] font-medium text-brand-700 hover:underline"
data-testid="shipping-workflow-action-view"
@click="openDetail(item)"
>
{{ t('chat.shippingWorkflow.actions.viewProgress') }}
</button>
<button
v-if="canReparse(item)"
type="button"
class="inline-flex items-center gap-1 text-[11px] font-medium text-amber-800 hover:underline disabled:opacity-50 dark:text-amber-200"
:disabled="actionBusyItemNo === item.item_no"
data-testid="shipping-workflow-action-reparse"
@click="openReparseDialog(item)"
>
{{ reparseActionLabel(item) }}
</button>
<button
v-if="canCancel(item)"
type="button"
class="inline-flex items-center gap-1 text-[11px] font-medium text-rose-700 hover:underline disabled:opacity-50"
:disabled="actionBusyItemNo === item.item_no"
data-testid="shipping-workflow-action-cancel"
@click="openCancelDialog(item)"
>
{{ t('chat.shippingWorkflow.actions.cancelFile') }}
</button>
</div>
</li>
</ul>
</section>
</template>
</div>
</section>
</div>
</Teleport>
<ShippingWorkflowItemDetailDrawer
:open="detailOpen"
:item="detailItem"
@@ -657,6 +915,8 @@ watch(
@close="detailOpen = false; detailItem = null"
@cancel="openCancelDialog"
@reparse="openReparseDialog"
@refreshed="() => void ctl.refresh()"
@confirm-customer="(taskNo) => void onGateConfirmCustomer(taskNo)"
/>
<ShippingWorkflowReasonDialog