feat(shipping-notice): 增强发货通知与审计功能,支持敏感数据控制与哈希链校验

- 更新发货通知工具 API,剥离不可信的操作人身份字段,确保审计安全
- 引入审计事件的哈希链校验机制,支持数据完整性验证
- 增强订单抽取与审计功能,支持敏感快照的访问控制
- 更新相关模型与服务,确保新功能的完整性与可追溯性
- 完善文档与代码注释,反映新的业务逻辑与审计要求
This commit is contained in:
hugo committed 2026-07-31 08:59:44 +08:00
1 parent 95cdfe66b0
commit d0fe084999
225 files changed
+25923 -6653

No files matched your search

@@ -1,11 +1,12 @@
/**
* features/chat/components/shipping/ShippingOrderExtractionCard.vue
* 用途:聊天主区批次进度卡——摘要计数、Run 级处理事项、当前文件阶段、健康提醒与动作。
* 依赖:订单抽取 Run 状态卡 DTO、orderExtractionProgressDisplay、vue-router、vue-i18n。
* 逻辑:事实一律来自后端 handling_items / primary_notice;右侧 ShippingSessionSummaryPanel 承接逐 PDF 明细。
* 依赖:订单抽取 Run 状态卡 DTO、orderExtractionProgressDisplay、Workflow 计数投影、vue-router、vue-i18n。
* 逻辑:有 Workflow 投影时优先展示统一 counts;否则回退 handling_items / primary_notice;
* 右侧 ShippingWorkflowTimeline 承接逐 PDF 明细;禁止发明百分比与 ETA。
*/
<script setup lang="ts">
import { computed, ref } from 'vue';
import { computed, inject, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { useRoute, useRouter } from 'vue-router';
import { CircleCheck, CircleX, LoaderCircle, TriangleAlert } from 'lucide-vue-next';
@@ -13,6 +14,7 @@ import type {
ShippingOrderExtractionHandlingItemState,
ShippingOrderExtractionState,
} from '../../types/chat.types';
import type { ShippingWorkflowItemCounts } from '../../types/shipping.api.types';
import {
formatOrderExtractionElapsed,
resolveOrderExtractionUserStageKey,
@@ -22,6 +24,7 @@ import {
type ShippingHandlingAffectedRef,
type ShippingHandlingRefTarget,
} from '../../shipping/orderExtractionHandlingRefs';
import { SHIPPING_WORKFLOW_KEY } from '../../shipping/useShippingNoticeWorkflow';
const props = defineProps<{
state: ShippingOrderExtractionState;
@@ -29,6 +32,8 @@ const props = defineProps<{
retrying?: boolean;
refreshing?: boolean;
cancelling?: boolean;
/** 可选:父级传入的 Workflow 计数;优先于 Run summary。 */
workflowSummary?: ShippingWorkflowItemCounts | null;
}>();
const emit = defineEmits<{
@@ -42,6 +47,49 @@ const route = useRoute();
const router = useRouter();
const confirmCancelOpen = ref(false);
const cancelReason = ref('');
const injectedWorkflow = inject(SHIPPING_WORKFLOW_KEY, null);
/**
* 统一计数:优先 props.workflowSummary,其次 inject 的 Workflow.counts,最后回退 Run summary。
*/
const unifiedCounts = computed(() => {
const fromProp = props.workflowSummary;
if (fromProp && Number(fromProp.total || 0) > 0) return fromProp;
const fromInject = injectedWorkflow?.workflow.value?.counts;
if (fromInject && Number(fromInject.total || 0) > 0) return fromInject;
return null;
});
const displaySummary = computed(() => {
const counts = unifiedCounts.value;
if (!counts) return props.state.summary;
return {
totalDocuments: counts.total,
processingDocuments: counts.processing,
pendingDocuments: 0,
completedDocuments: counts.completed,
reviewRequiredDocuments: counts.pending_review,
failedDocuments: counts.failed,
cancelledDocuments: 0,
candidateCount: props.state.summary.candidateCount,
openedExistingCount: props.state.summary.openedExistingCount,
};
});
const workflowStageLabel = computed(() => {
const stage = String(injectedWorkflow?.workflow.value?.current_stage || '').trim();
if (!stage) return '';
const key = `chat.shippingWorkflow.itemStatus.${stage}`;
return te(key) ? t(key) : stage;
});
const workflowLastActivityLabel = computed(() => {
const raw = injectedWorkflow?.workflow.value?.last_activity_at;
if (!raw) return '';
const date = new Date(String(raw));
if (Number.isNaN(date.getTime())) return '';
return date.toLocaleString();
});
const handlingItems = computed(() => props.state.handlingItems || []);
@@ -50,10 +98,10 @@ const handlingItems = computed(() => props.state.handlingItems || []);
*/
const isDuplicateOnlyNotice = computed(() => {
if (handlingItems.value.length > 0) return false;
const opened = Math.max(0, Number(props.state.summary.openedExistingCount || 0));
const opened = Math.max(0, Number(displaySummary.value.openedExistingCount || 0));
if (opened <= 0) return false;
const review = Math.max(0, Number(props.state.summary.reviewRequiredDocuments || 0));
const failed = Math.max(0, Number(props.state.summary.failedDocuments || 0));
const review = Math.max(0, Number(displaySummary.value.reviewRequiredDocuments || 0));
const failed = Math.max(0, Number(displaySummary.value.failedDocuments || 0));
return review === 0 && failed === 0;
});
@@ -163,7 +211,7 @@ const activityKey = computed(() => {
const showRetry = computed(() => (
props.state.availableActions.includes('retry_failed_attachments')
|| props.state.summary.failedDocuments > 0
|| displaySummary.value.failedDocuments > 0
));
const showRefresh = computed(() => props.state.availableActions.includes('refresh_status'));
const showCancel = computed(() => (
@@ -319,31 +367,40 @@ function openCancelConfirm() {
<div class="text-sm font-medium">{{ compactLine }}</div>
<div
v-if="state.summary.totalDocuments > 0"
v-if="displaySummary.totalDocuments > 0"
class="mt-1.5 flex flex-wrap gap-1.5 text-[11px] opacity-90"
data-testid="shipping-order-extraction-summary"
>
<span>{{ t('chat.shippingOrderExtractionSummary.total', { count: state.summary.totalDocuments }) }}</span>
<span v-if="state.summary.processingDocuments > 0">
{{ t('chat.shippingOrderExtractionSummary.processing', { count: state.summary.processingDocuments }) }}
<span>{{ t('chat.shippingOrderExtractionSummary.total', { count: displaySummary.totalDocuments }) }}</span>
<span v-if="displaySummary.processingDocuments > 0">
{{ t('chat.shippingOrderExtractionSummary.processing', { count: displaySummary.processingDocuments }) }}
</span>
<span v-if="state.summary.pendingDocuments > 0">
{{ t('chat.shippingOrderExtractionSummary.pending', { count: state.summary.pendingDocuments }) }}
<span v-if="displaySummary.pendingDocuments > 0">
{{ t('chat.shippingOrderExtractionSummary.pending', { count: displaySummary.pendingDocuments }) }}
</span>
<span v-if="state.summary.completedDocuments > 0">
{{ t('chat.shippingOrderExtractionSummary.completed', { count: state.summary.completedDocuments }) }}
<span v-if="displaySummary.completedDocuments > 0">
{{ t('chat.shippingOrderExtractionSummary.completed', { count: displaySummary.completedDocuments }) }}
</span>
<span v-if="state.summary.reviewRequiredDocuments > 0">
{{ t('chat.shippingOrderExtractionSummary.reviewRequired', { count: state.summary.reviewRequiredDocuments }) }}
<span v-if="displaySummary.reviewRequiredDocuments > 0">
{{ t('chat.shippingOrderExtractionSummary.reviewRequired', { count: displaySummary.reviewRequiredDocuments }) }}
</span>
<span v-if="state.summary.failedDocuments > 0">
{{ t('chat.shippingOrderExtractionSummary.failed', { count: state.summary.failedDocuments }) }}
<span v-if="displaySummary.failedDocuments > 0">
{{ t('chat.shippingOrderExtractionSummary.failed', { count: displaySummary.failedDocuments }) }}
</span>
<span v-if="(state.summary.cancelledDocuments || 0) > 0">
{{ t('chat.shippingOrderExtractionSummary.cancelled', { count: state.summary.cancelledDocuments }) }}
<span v-if="(displaySummary.cancelledDocuments || 0) > 0">
{{ t('chat.shippingOrderExtractionSummary.cancelled', { count: displaySummary.cancelledDocuments }) }}
</span>
</div>
<div
v-if="workflowStageLabel || workflowLastActivityLabel"
class="mt-1 text-[11px] opacity-80"
data-testid="shipping-order-extraction-workflow-meta"
>
<span v-if="workflowStageLabel">{{ workflowStageLabel }}</span>
<span v-if="workflowLastActivityLabel" class="ml-1">· {{ workflowLastActivityLabel }}</span>
</div>
<div
v-if="handlingItems.length"
class="mt-2 space-y-1.5"
@@ -0,0 +1,113 @@
/**
* features/chat/components/shipping/ShippingWorkflowItemDetailDrawer.spec.ts
* 用途:覆盖单个 WorkflowItem 详情抽屉的文件名/阶段/事件展示与取消/重识别入口。
* 依赖:Vitest、Vue Test Utils、vue-i18n。
* 逻辑:断言打开时展示 filename 与事件;终态隐藏取消;emit close/cancel/reparse。
* Teleport 到 body 后通过 document.querySelector 读取抽屉根节点。
*/
import { mount } from '@vue/test-utils';
import { afterEach, describe, expect, it } from 'vitest';
import { createI18n } from 'vue-i18n';
import chatZhCn from '@/locales/zh-CN/chat.json';
import ShippingWorkflowItemDetailDrawer from './ShippingWorkflowItemDetailDrawer.vue';
import type { ShippingWorkflowItem } from '../../types/shipping.api.types';
const i18n = createI18n({
legacy: false,
locale: 'zh-CN',
messages: { 'zh-CN': { chat: chatZhCn } },
});
function buildItem(patch: Partial<ShippingWorkflowItem> = {}): ShippingWorkflowItem {
return {
item_no: 'SWI-DETAIL',
workflow_no: 'SNWF-1',
conversation_id: 'conv-1',
root_document_id: 1,
current_document_id: 1,
current_document_filename: 'order-detail.pdf',
current_version_no: 2,
current_run_no: 'SNER-9',
lifecycle_status: 'extracting',
current_stage: 'extracting',
lock_version: 1,
events: [
{
seq_no: 1,
event_code: 'item_created',
actor_type: 'system',
occurred_at: '2026-07-30T10:00:00Z',
},
],
...patch,
};
}
/** Teleport 后从 document 取抽屉根节点。 */
function drawerRoot(): HTMLElement | null {
return document.querySelector('[data-testid="shipping-workflow-item-drawer"]');
}
afterEach(() => {
document.body.innerHTML = '';
});
describe('ShippingWorkflowItemDetailDrawer', () => {
it('renders filename, stage and events when open', () => {
const wrapper = mount(ShippingWorkflowItemDetailDrawer, {
props: { open: true, item: buildItem() },
global: { plugins: [i18n] },
attachTo: document.body,
});
const root = drawerRoot();
expect(root).not.toBeNull();
expect(root?.getAttribute('role')).toBe('dialog');
expect(root?.getAttribute('aria-modal')).toBe('true');
expect(root?.textContent).toContain('order-detail.pdf');
expect(root?.textContent).toContain('SNER-9');
expect(root?.querySelector('[data-testid="shipping-workflow-item-events"]')).not.toBeNull();
expect(root?.querySelector('[data-testid="shipping-workflow-item-drawer-cancel"]')).not.toBeNull();
expect(root?.querySelector('[data-testid="shipping-workflow-item-drawer-reparse"]')).toBeNull();
wrapper.unmount();
});
it('shows reparse for failed items and emits reparse', async () => {
const wrapper = mount(ShippingWorkflowItemDetailDrawer, {
props: {
open: true,
item: buildItem({ lifecycle_status: 'failed', current_document_filename: 'fail.pdf' }),
},
global: { plugins: [i18n] },
attachTo: document.body,
});
const reparseBtn = drawerRoot()?.querySelector(
'[data-testid="shipping-workflow-item-drawer-reparse"]',
) as HTMLButtonElement | null;
expect(reparseBtn).not.toBeNull();
reparseBtn?.click();
await wrapper.vm.$nextTick();
expect(wrapper.emitted('reparse')?.[0]?.[0]).toMatchObject({ item_no: 'SWI-DETAIL' });
wrapper.unmount();
});
it('hides cancel for closed items and emits close', async () => {
const wrapper = mount(ShippingWorkflowItemDetailDrawer, {
props: {
open: true,
item: buildItem({ lifecycle_status: 'closed', closed_reason: 'user_cancelled' }),
},
global: { plugins: [i18n] },
attachTo: document.body,
});
const root = drawerRoot();
expect(root?.querySelector('[data-testid="shipping-workflow-item-drawer-cancel"]')).toBeNull();
const closeBtn = root?.querySelector(
'[data-testid="shipping-workflow-item-drawer-close"]',
) as HTMLButtonElement | null;
expect(closeBtn).not.toBeNull();
closeBtn?.click();
await wrapper.vm.$nextTick();
expect(wrapper.emitted('close')).toBeTruthy();
wrapper.unmount();
});
});
@@ -0,0 +1,312 @@
/**
* features/chat/components/shipping/ShippingWorkflowItemDetailDrawer.vue
* 用途:单个 WorkflowItem(PDF)详情抽屉——文件名、阶段、事件时间线、取消/重识别入口。
* 依赖:vue-i18n、ShippingWorkflowItem / Event 类型、lucide-vue-next。
* 逻辑:由 ShippingWorkflowTimeline 打开;展示 filename / current_stage / events;
* 取消与重识别仅 emit,由父级用应用内原因弹窗收集;禁止发明百分比与 ETA。
* 以模态对话框语义呈现:初始焦点、Tab 陷阱、Escape/关闭后焦点恢复。
*/
<script setup lang="ts">
import { computed, nextTick, onBeforeUnmount, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { X } from 'lucide-vue-next';
import type { ShippingWorkflowEvent, ShippingWorkflowItem } from '@/features/chat/types/shipping.api.types';
const props = defineProps<{
open: boolean;
item: ShippingWorkflowItem | null;
loading?: boolean;
cancelling?: boolean;
reparsing?: boolean;
}>();
const emit = defineEmits<{
close: [];
cancel: [item: ShippingWorkflowItem];
reparse: [item: ShippingWorkflowItem];
}>();
const { t, te, locale } = useI18n();
const panelRef = ref<HTMLElement | null>(null);
const closeButtonRef = ref<HTMLButtonElement | null>(null);
let previouslyFocused: HTMLElement | null = null;
const FOCUSABLE_SELECTOR = [
'a[href]',
'button:not([disabled])',
'textarea:not([disabled])',
'input:not([disabled])',
'select:not([disabled])',
'[tabindex]:not([tabindex="-1"])',
].join(',');
const events = computed((): ShippingWorkflowEvent[] => (
Array.isArray(props.item?.events) ? props.item!.events! : []
));
const canCancel = computed(() => {
const status = String(props.item?.lifecycle_status || '').trim();
return Boolean(props.item) && !['closed', 'cancelled'].includes(status);
});
const canReparse = computed(() => {
const status = String(props.item?.lifecycle_status || '').trim();
return Boolean(props.item) && ['failed', 'reparse_failed', 'pending_review'].includes(status);
});
const filename = computed(() => {
const name = String(props.item?.current_document_filename || '').trim();
if (name) return name;
if (!props.item) return '';
return t('chat.shippingWorkflow.filenameFallback', {
docId: props.item.current_document_id,
});
});
const title = computed(() => t('chat.shippingWorkflow.detail.title'));
/**
* 解析生命周期 / 阶段文案。
*/
function statusLabel(status?: string | null): string {
const normalized = String(status || '').trim();
if (!normalized) return '';
const key = `chat.shippingWorkflow.itemStatus.${normalized}`;
return te(key) ? t(key) : normalized;
}
/**
* 解析事件码文案。
*/
function eventLabel(event: ShippingWorkflowEvent): string {
const code = String(event.message_code || event.event_code || '').trim();
if (!code) return '—';
const key = `chat.shippingWorkflow.event.${code}`;
return te(key) ? t(key) : code;
}
/**
* 格式化时间为本地短时间。
*/
function formatTime(value?: string | null): string {
const date = new Date(String(value || ''));
if (Number.isNaN(date.getTime())) return '';
return new Intl.DateTimeFormat(String(locale.value || 'zh-CN'), {
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
hour12: false,
}).format(date);
}
/** 收集抽屉内可聚焦控件。 */
function focusableNodes(): HTMLElement[] {
if (!panelRef.value) return [];
return Array.from(panelRef.value.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR))
.filter((node) => !node.hasAttribute('disabled') && node.getAttribute('aria-hidden') !== 'true');
}
/** 关闭抽屉。 */
function handleClose(): void {
emit('close');
}
/**
* Escape 关闭;Tab 在抽屉内循环,阻止焦点逃逸到背景页。
*/
function onKeydown(event: KeyboardEvent): void {
if (!props.open) return;
if (event.key === 'Escape') {
event.preventDefault();
event.stopPropagation();
handleClose();
return;
}
if (event.key !== 'Tab') return;
const nodes = focusableNodes();
const first = nodes[0];
const last = nodes[nodes.length - 1];
// noUncheckedIndexedAccess:空数组或下标越界时 first/last 可能为 undefined。
if (!first || !last) {
event.preventDefault();
return;
}
const active = document.activeElement as HTMLElement | null;
const inside = Boolean(active && panelRef.value?.contains(active));
if (event.shiftKey) {
if (!inside || active === first) {
event.preventDefault();
last.focus();
}
return;
}
if (!inside || active === last) {
event.preventDefault();
first.focus();
}
}
watch(
() => props.open,
async (open, wasOpen) => {
if (typeof document === 'undefined') return;
if (open && !wasOpen) {
previouslyFocused = document.activeElement instanceof HTMLElement
? document.activeElement
: null;
document.addEventListener('keydown', onKeydown, true);
await nextTick();
(closeButtonRef.value || focusableNodes()[0])?.focus();
return;
}
if (!open && wasOpen) {
document.removeEventListener('keydown', onKeydown, true);
const restoreTarget = previouslyFocused;
previouslyFocused = null;
await nextTick();
restoreTarget?.focus?.();
}
},
);
onBeforeUnmount(() => {
if (typeof document !== 'undefined') {
document.removeEventListener('keydown', onKeydown, true);
}
});
</script>
<template>
<Teleport to="body">
<div
v-if="open"
class="fixed inset-0 z-40 flex justify-end bg-black/30"
role="dialog"
aria-modal="true"
aria-labelledby="shipping-workflow-item-drawer-title"
data-testid="shipping-workflow-item-drawer"
@click.self="handleClose"
>
<aside
ref="panelRef"
class="flex h-full w-full max-w-md flex-col border-l border-default bg-surface shadow-xl"
>
<header class="flex items-start justify-between gap-2 border-b border-default px-4 py-3">
<div class="min-w-0">
<h2 id="shipping-workflow-item-drawer-title" class="text-sm font-semibold text-primary">
{{ title }}
</h2>
<p
v-if="item"
class="mt-0.5 truncate text-xs text-secondary"
data-testid="shipping-workflow-item-drawer-filename"
>
{{ filename }}
· V{{ item.current_version_no }}
</p>
</div>
<button
ref="closeButtonRef"
type="button"
class="rounded-md p-1 text-muted hover:bg-surface-muted"
:aria-label="t('chat.shippingWorkflow.detail.close')"
data-testid="shipping-workflow-item-drawer-close"
@click="handleClose"
>
<X class="h-4 w-4" />
</button>
</header>
<div class="min-h-0 flex-1 overflow-auto p-4">
<div v-if="loading" class="text-xs text-muted">
{{ t('chat.shippingWorkflow.loading') }}
</div>
<template v-else-if="item">
<dl class="space-y-2 text-xs">
<div class="flex justify-between gap-2">
<dt class="text-secondary">{{ t('chat.shippingWorkflow.detail.filename') }}</dt>
<dd class="max-w-[60%] truncate font-medium text-primary" :title="filename">{{ filename }}</dd>
</div>
<div class="flex justify-between gap-2">
<dt class="text-secondary">{{ t('chat.shippingWorkflow.detail.status') }}</dt>
<dd class="font-medium text-primary">{{ statusLabel(item.lifecycle_status) }}</dd>
</div>
<div class="flex justify-between gap-2">
<dt class="text-secondary">{{ t('chat.shippingWorkflow.detail.stage') }}</dt>
<dd class="font-medium text-primary">{{ statusLabel(item.current_stage) || item.current_stage }}</dd>
</div>
<div v-if="item.current_run_no" class="flex justify-between gap-2">
<dt class="text-secondary">{{ t('chat.shippingWorkflow.detail.runNo') }}</dt>
<dd class="font-medium text-primary">{{ item.current_run_no }}</dd>
</div>
<div v-if="item.current_case_no" class="flex justify-between gap-2">
<dt class="text-secondary">{{ t('chat.shippingWorkflow.detail.caseNo') }}</dt>
<dd class="font-medium text-primary">{{ item.current_case_no }}</dd>
</div>
<div v-if="item.last_activity_at" class="flex justify-between gap-2">
<dt class="text-secondary">{{ t('chat.shippingWorkflow.detail.lastActivity') }}</dt>
<dd class="font-medium text-primary">{{ formatTime(item.last_activity_at) }}</dd>
</div>
<div v-if="item.closed_reason" class="flex justify-between gap-2">
<dt class="text-secondary">{{ t('chat.shippingWorkflow.detail.closedReason') }}</dt>
<dd class="font-medium text-primary">
{{ te(`chat.shippingWorkflow.closedReason.${item.closed_reason}`)
? t(`chat.shippingWorkflow.closedReason.${item.closed_reason}`)
: item.closed_reason }}
</dd>
</div>
</dl>
<section class="mt-4">
<h3 class="text-xs font-semibold text-secondary">
{{ t('chat.shippingWorkflow.detail.eventsTitle') }}
</h3>
<ul v-if="events.length" class="mt-2 space-y-2" data-testid="shipping-workflow-item-events">
<li
v-for="event in events"
:key="`${event.seq_no}-${event.event_code}`"
class="rounded-md border border-default bg-surface-muted/40 px-2.5 py-2 text-xs"
>
<div class="font-medium text-primary">{{ eventLabel(event) }}</div>
<div class="mt-0.5 text-[11px] text-muted">
<span v-if="event.occurred_at">{{ formatTime(event.occurred_at) }}</span>
<span v-if="event.stage_code" class="ml-1">· {{ event.stage_code }}</span>
</div>
<div v-if="event.reason" class="mt-1 text-[11px] text-secondary">{{ event.reason }}</div>
</li>
</ul>
<p v-else class="mt-2 text-xs text-muted">
{{ t('chat.shippingWorkflow.detail.eventsEmpty') }}
</p>
</section>
</template>
<p v-else class="text-xs text-muted">{{ t('chat.shippingWorkflow.detail.empty') }}</p>
</div>
<footer v-if="item && (canCancel || canReparse)" class="space-y-2 border-t border-default p-3">
<button
v-if="canReparse"
type="button"
class="w-full rounded-md border border-amber-200 bg-amber-50 px-3 py-2 text-xs font-medium text-amber-800 hover:bg-amber-100 disabled:opacity-50 dark:border-amber-900/50 dark:bg-amber-950/40 dark:text-amber-100"
:disabled="reparsing || cancelling"
data-testid="shipping-workflow-item-drawer-reparse"
@click="emit('reparse', item)"
>
{{ t('chat.shippingWorkflow.actions.reparse') }}
</button>
<button
v-if="canCancel"
type="button"
class="w-full rounded-md border border-rose-200 bg-rose-50 px-3 py-2 text-xs font-medium text-rose-700 hover:bg-rose-100 disabled:opacity-50 dark:border-rose-900/50 dark:bg-rose-950/40 dark:text-rose-200"
:disabled="cancelling || reparsing"
data-testid="shipping-workflow-item-drawer-cancel"
@click="emit('cancel', item)"
>
{{ t('chat.shippingWorkflow.actions.cancelFile') }}
</button>
</footer>
</aside>
</div>
</Teleport>
</template>
@@ -0,0 +1,189 @@
<!--
features/chat/components/shipping/ShippingWorkflowReasonDialog.vue
用途:Workflow Item 取消 / 重识别的轻量原因确认弹窗(必填 reason)。
依赖:vue-i18n、dialog-overlay / dialog-panel 设计系统样式。
逻辑:由 ShippingWorkflowTimeline / DetailDrawer 以 v-model 控制;确认前校验非空原因。
-->
<script setup lang="ts">
import { computed, nextTick, onBeforeUnmount, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
export type ShippingWorkflowReasonAction = 'cancel' | 'reparse';
const props = withDefaults(defineProps<{
modelValue: boolean;
action: ShippingWorkflowReasonAction;
confirmLoading?: boolean;
}>(), {
confirmLoading: false,
});
const emit = defineEmits<{
'update:modelValue': [value: boolean];
confirm: [payload: { reason: string; comment?: string }];
cancel: [];
}>();
const { t } = useI18n();
const reason = ref('');
const comment = ref('');
const reasonMissing = ref(false);
const reasonInputRef = ref<HTMLTextAreaElement | null>(null);
const title = computed(() => (
props.action === 'reparse'
? t('chat.shippingWorkflow.reasonDialog.reparseTitle')
: t('chat.shippingWorkflow.reasonDialog.cancelTitle')
));
const confirmLabel = computed(() => (
props.action === 'reparse'
? t('chat.shippingWorkflow.reasonDialog.reparseConfirm')
: t('chat.shippingWorkflow.reasonDialog.cancelConfirm')
));
const reasonLabel = computed(() => t('chat.shippingWorkflow.reasonDialog.reasonLabel'));
const reasonRequiredHint = computed(() => t('chat.shippingWorkflow.reasonRequired'));
/**
* 关闭弹窗并重置本地表单。
*/
function closeDialog() {
emit('update:modelValue', false);
}
/**
* 取消:关闭并通知父级。
*/
function handleCancel() {
emit('cancel');
closeDialog();
}
/**
* 校验必填原因后提交。
*/
function handleConfirm() {
reasonMissing.value = false;
const trimmed = reason.value.trim();
if (!trimmed) {
reasonMissing.value = true;
return;
}
const trimmedComment = comment.value.trim();
emit('confirm', {
reason: trimmed,
comment: trimmedComment || undefined,
});
}
/**
* Escape 关闭弹窗。
*/
function onKeydown(event: KeyboardEvent) {
if (!props.modelValue) return;
if (event.key === 'Escape') {
event.preventDefault();
handleCancel();
}
}
watch(
() => props.modelValue,
async (open) => {
if (typeof document === 'undefined') return;
if (open) {
reason.value = '';
comment.value = '';
reasonMissing.value = false;
document.addEventListener('keydown', onKeydown, true);
await nextTick();
reasonInputRef.value?.focus();
return;
}
document.removeEventListener('keydown', onKeydown, true);
},
);
onBeforeUnmount(() => {
if (typeof document !== 'undefined') {
document.removeEventListener('keydown', onKeydown, true);
}
});
</script>
<template>
<Teleport to="body">
<div
v-if="modelValue"
class="dialog-overlay z-50 flex items-center justify-center p-4"
data-testid="shipping-workflow-reason-dialog"
@click.self="handleCancel"
>
<div
class="dialog-panel w-full max-w-md space-y-3 p-5"
role="dialog"
aria-modal="true"
:aria-label="title"
>
<h3 class="text-sm font-semibold text-primary">{{ title }}</h3>
<p class="mt-1 text-xs text-secondary">
{{ t('chat.shippingWorkflow.reasonDialog.impact') }}
</p>
<label class="mt-3 block text-xs text-secondary">
{{ reasonLabel }}
<span class="text-rose-600">*</span>
<textarea
ref="reasonInputRef"
v-model="reason"
rows="3"
class="input-field mt-1 w-full py-1.5 text-xs"
:aria-invalid="reasonMissing"
data-testid="shipping-workflow-reason-input"
:placeholder="t('chat.shippingWorkflow.reasonDialog.reasonPlaceholder')"
/>
</label>
<p v-if="reasonMissing" class="mt-1 text-[11px] text-rose-600" data-testid="shipping-workflow-reason-missing">
{{ reasonRequiredHint }}
</p>
<label
v-if="action === 'reparse'"
class="mt-2 block text-xs text-secondary"
>
{{ t('chat.shippingWorkflow.reasonDialog.commentOptional') }}
<textarea
v-model="comment"
rows="2"
class="input-field mt-1 w-full py-1.5 text-xs"
data-testid="shipping-workflow-comment-input"
/>
</label>
<div class="mt-4 flex flex-wrap justify-end gap-2">
<button
type="button"
class="btn-secondary btn-sm"
:disabled="confirmLoading"
data-testid="shipping-workflow-reason-cancel"
@click="handleCancel"
>
{{ t('chat.shippingWorkflow.reasonDialog.dismiss') }}
</button>
<button
type="button"
class="btn-danger btn-sm"
:disabled="confirmLoading"
data-testid="shipping-workflow-reason-confirm"
@click="handleConfirm"
>
{{ confirmLoading
? t('chat.shippingWorkflow.reasonDialog.submitting')
: confirmLabel }}
</button>
</div>
</div>
</div>
</Teleport>
</template>
@@ -0,0 +1,223 @@
/**
* features/chat/components/shipping/ShippingWorkflowTimeline.spec.ts
* 用途:验证右侧 Workflow 时间线分组、文件名、批次切换、过滤与取消/重识别弹窗。
* 依赖:Vitest、Vue Test Utils、vue-i18n、shipping.api mock。
* 逻辑:断言 layout_parsing 可见;文件名优先;仅看待处理过滤;原因弹窗提交 cancelItem。
*/
import { mount, flushPromises } from '@vue/test-utils';
import { describe, expect, it, vi, beforeEach } from 'vitest';
import { createI18n } from 'vue-i18n';
import { ref } from 'vue';
import chatZhCn from '@/locales/zh-CN/chat.json';
import ShippingWorkflowTimeline from './ShippingWorkflowTimeline.vue';
import type { ShippingWorkflow, ShippingWorkflowItem } from '../../types/shipping.api.types';
import type { UseShippingNoticeWorkflowReturn } from '../../shipping/useShippingNoticeWorkflow';
vi.mock('@/features/chat/api/shipping.api', () => ({
getWorkspaceShippingWorkflowItem: vi.fn(async (itemNo: string) => ({
item_no: itemNo,
workflow_no: 'SNWF-1',
conversation_id: 'conv-1',
root_document_id: 1,
current_document_id: 1,
current_document_filename: 'detail.pdf',
current_version_no: 1,
lifecycle_status: 'layout_parsing',
current_stage: 'layout_parsing',
lock_version: 1,
events: [],
})),
listWorkspaceShippingWorkflows: vi.fn(),
cancelWorkspaceShippingWorkflowItem: vi.fn(),
reparseWorkspaceShippingWorkflowItem: vi.fn(),
}));
vi.mock('@/shared/composables/useMessage', () => ({
useMessage: () => ({
success: vi.fn(),
error: vi.fn(),
warning: vi.fn(),
info: vi.fn(),
}),
}));
const i18n = createI18n({
legacy: false,
locale: 'zh-CN',
messages: { 'zh-CN': { chat: chatZhCn, errors: { generic: '错误' } } },
});
function buildItem(patch: Partial<ShippingWorkflowItem> = {}): ShippingWorkflowItem {
return {
item_no: 'SWI-1',
workflow_no: 'SNWF-1',
conversation_id: 'conv-1',
root_document_id: 10,
current_document_id: 10,
current_document_filename: 'shipping-notice.pdf',
current_version_no: 1,
lifecycle_status: 'layout_parsing',
current_stage: 'layout_parsing',
lock_version: 1,
...patch,
};
}
function buildController(
items: ShippingWorkflowItem[],
extras?: { workflows?: ShippingWorkflow[] },
): UseShippingNoticeWorkflowReturn {
const workflowList = extras?.workflows ?? [{
workflow_no: 'SNWF-1',
conversation_id: 'conv-1',
status: 'open',
current_stage: 'layout_parsing',
lock_version: 1,
counts: {
total: items.length,
processing: items.filter((i) => i.lifecycle_status === 'layout_parsing' || i.lifecycle_status === 'extracting').length,
pending_review: items.filter((i) => i.lifecycle_status === 'pending_review').length,
failed: items.filter((i) => i.lifecycle_status === 'failed' || i.lifecycle_status === 'reparse_failed').length,
completed: items.filter((i) => i.lifecycle_status === 'closed').length,
},
items,
}];
const selectedWorkflowNo = ref(workflowList[0]?.workflow_no || null);
const workflows = ref(workflowList);
const workflow = ref(workflowList[0] || null);
const itemRef = ref(items);
return {
workflows,
selectedWorkflowNo,
selectWorkflow: vi.fn((no: string) => {
selectedWorkflowNo.value = no;
workflow.value = workflows.value.find((row) => row.workflow_no === no) || null;
itemRef.value = workflow.value?.items || [];
}),
workflow,
items: itemRef,
loading: ref(false),
error: ref(null),
refresh: vi.fn(async () => undefined),
cancelItem: vi.fn(async () => null),
reparseItem: vi.fn(async () => null),
stop: vi.fn(),
};
}
describe('ShippingWorkflowTimeline', () => {
beforeEach(() => {
document.body.innerHTML = '';
});
it('shows layout_parsing items with filename before review case exists', async () => {
const controller = buildController([
buildItem({
item_no: 'SWI-LAYOUT',
lifecycle_status: 'layout_parsing',
current_case_no: null,
current_document_filename: 'layout.pdf',
}),
buildItem({ item_no: 'SWI-REVIEW', lifecycle_status: 'pending_review', current_case_no: 'SNRC-1' }),
]);
const wrapper = mount(ShippingWorkflowTimeline, {
props: { conversationId: 'conv-1', controller },
global: { plugins: [i18n] },
});
await flushPromises();
expect(wrapper.find('[data-testid="shipping-workflow-item-SWI-LAYOUT"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="shipping-workflow-item-SWI-LAYOUT"]').text()).toContain('layout.pdf');
expect(wrapper.text()).toContain('尚无复核单');
expect(wrapper.find('[data-testid="shipping-workflow-group-processing"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="shipping-workflow-group-pending_review"]').exists()).toBe(true);
});
it('filters to actionable items when pending-only is checked', async () => {
const controller = buildController([
buildItem({ item_no: 'SWI-A', lifecycle_status: 'extracting' }),
buildItem({ item_no: 'SWI-B', lifecycle_status: 'pending_review' }),
]);
const wrapper = mount(ShippingWorkflowTimeline, {
props: { conversationId: 'conv-1', controller },
global: { plugins: [i18n] },
});
await flushPromises();
await wrapper.find('[data-testid="shipping-workflow-pending-only-filter"]').setValue(true);
expect(wrapper.find('[data-testid="shipping-workflow-item-SWI-B"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="shipping-workflow-item-SWI-A"]').exists()).toBe(false);
});
it('cancels an item via in-app reason dialog', async () => {
const controller = buildController([
buildItem({ item_no: 'SWI-CANCEL', lifecycle_status: 'extracting', lock_version: 3 }),
]);
const wrapper = mount(ShippingWorkflowTimeline, {
props: { conversationId: 'conv-1', controller },
global: {
plugins: [i18n],
stubs: {
// 让 Teleport 就地渲染,便于 setValue / trigger
teleport: true,
},
},
});
await flushPromises();
await wrapper.find('[data-testid="shipping-workflow-action-cancel"]').trigger('click');
await flushPromises();
const reasonInput = wrapper.find('[data-testid="shipping-workflow-reason-input"]');
expect(reasonInput.exists()).toBe(true);
await reasonInput.setValue('cancel reason');
await wrapper.find('[data-testid="shipping-workflow-reason-confirm"]').trigger('click');
await flushPromises();
expect(controller.cancelItem).toHaveBeenCalledWith('SWI-CANCEL', {
reason: 'cancel reason',
expected_lock_version: 3,
});
});
it('shows batch switcher for multiple workflows', async () => {
const itemsA = [buildItem({ item_no: 'SWI-A', workflow_no: 'SNWF-A' })];
const itemsB = [buildItem({ item_no: 'SWI-B', workflow_no: 'SNWF-B', lifecycle_status: 'failed' })];
const workflows = [
{
workflow_no: 'SNWF-A',
conversation_id: 'conv-1',
status: 'open',
current_stage: 'layout_parsing',
lock_version: 1,
counts: { total: 1, processing: 1, pending_review: 0, failed: 0, completed: 0 },
items: itemsA,
},
{
workflow_no: 'SNWF-B',
conversation_id: 'conv-1',
status: 'open',
current_stage: 'failed',
lock_version: 1,
counts: { total: 1, processing: 0, pending_review: 0, failed: 1, completed: 0 },
items: itemsB,
},
];
const controller = buildController(itemsA, { workflows });
const wrapper = mount(ShippingWorkflowTimeline, {
props: { conversationId: 'conv-1', controller },
global: { plugins: [i18n] },
});
await flushPromises();
expect(wrapper.find('[data-testid="shipping-workflow-batch-switcher"]').exists()).toBe(true);
await wrapper.find('[data-testid="shipping-workflow-batch-SNWF-B"]').trigger('click');
expect(controller.selectWorkflow).toHaveBeenCalledWith('SNWF-B');
});
it('shows reparse action for failed items', async () => {
const controller = buildController([
buildItem({ item_no: 'SWI-FAIL', lifecycle_status: 'failed', current_document_filename: 'bad.pdf' }),
]);
const wrapper = mount(ShippingWorkflowTimeline, {
props: { conversationId: 'conv-1', controller },
global: { plugins: [i18n] },
});
await flushPromises();
expect(wrapper.find('[data-testid="shipping-workflow-action-reparse"]').exists()).toBe(true);
});
});
@@ -0,0 +1,568 @@
/**
* features/chat/components/shipping/ShippingWorkflowTimeline.vue
* 用途:聊天页右侧「本次处理」面板——以会话 Workflow / Items 为列表事实源。
* 依赖:vue-i18n、useMessage、useShippingNoticeWorkflow(inject 或自建)、DetailDrawer、ReasonDialog。
* 逻辑:多批次时展示切换器;Items 以文件名为主标题;
* 分组进行中/待处理/待复核/待人工上传登记/失败/已完成(登记前不得进已完成);
* 「仅看待处理」过滤;查看进度 / 取消 / 重试重识别;取消与重识别用应用内原因弹窗。
*/
<script setup lang="ts">
import { computed, inject, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { ChevronDown, ChevronRight, RefreshCw } from 'lucide-vue-next';
import { BusinessError } from '@/shared/api/client';
import { useMessage } from '@/shared/composables/useMessage';
import {
getWorkspaceShippingWorkflowItem,
} from '@/features/chat/api/shipping.api';
import type {
ShippingWorkflow,
ShippingWorkflowItem,
} from '@/features/chat/types/shipping.api.types';
import {
SHIPPING_WORKFLOW_KEY,
useShippingNoticeWorkflow,
type UseShippingNoticeWorkflowReturn,
} from '@/features/chat/shipping/useShippingNoticeWorkflow';
import ShippingWorkflowItemDetailDrawer from './ShippingWorkflowItemDetailDrawer.vue';
import ShippingWorkflowReasonDialog, {
type ShippingWorkflowReasonAction,
} from './ShippingWorkflowReasonDialog.vue';
const props = defineProps<{
conversationId?: string | null;
/** 父级递增以触发立即刷新。 */
refreshTrigger?: number;
/** 测试或父级注入时可直接传入控制器,跳过自建轮询。 */
controller?: UseShippingNoticeWorkflowReturn | null;
}>();
const { t, te, locale } = useI18n();
const msg = useMessage();
const injected = inject(SHIPPING_WORKFLOW_KEY, null);
/** 父级已 provide/传入时本地 composable 以空 conversationId 待机,避免双轮询。 */
const localController = useShippingNoticeWorkflow({
conversationId: () => (
props.controller || injected ? null : props.conversationId
),
refreshTrigger: () => (
props.controller || injected ? undefined : props.refreshTrigger
),
});
const ctl = computed((): UseShippingNoticeWorkflowReturn => (
props.controller || injected || localController
));
const collapsed = ref(false);
const pendingOnlyFilter = ref(false);
const actionBusyItemNo = ref<string | null>(null);
const detailOpen = ref(false);
const detailLoading = ref(false);
const detailItem = ref<ShippingWorkflowItem | null>(null);
const reasonDialogOpen = ref(false);
const reasonDialogAction = ref<ShippingWorkflowReasonAction>('cancel');
const reasonDialogItem = ref<ShippingWorkflowItem | null>(null);
const workflows = computed((): ShippingWorkflow[] => ctl.value.workflows.value);
const selectedWorkflowNo = computed(() => ctl.value.selectedWorkflowNo.value);
const workflow = computed((): ShippingWorkflow | null => ctl.value.workflow.value);
const items = computed((): ShippingWorkflowItem[] => ctl.value.items.value);
const loading = computed(() => ctl.value.loading.value);
const error = computed(() => ctl.value.error.value);
const counts = computed(() => workflow.value?.counts || {
total: items.value.length,
processing: 0,
pending_review: 0,
waiting_manual_upload: 0,
failed: 0,
completed: 0,
});
const showBatchSwitcher = computed(() => workflows.value.length > 1);
type ItemGroupKey =
| 'processing'
| 'queued'
| 'completed'
| 'pending_review'
| 'failed'
| 'waiting_manual_upload';
const PROCESSING_STATUSES = new Set([
'layout_parsing',
'extracting',
'building_order',
'inventory_matching',
'generating_excel',
]);
const QUEUED_STATUSES = new Set(['queued']);
const FAILED_STATUSES = new Set(['failed', 'reparse_failed']);
/** 真正完成/取消;待人工登记不是完成。 */
const COMPLETED_STATUSES = new Set(['closed', 'cancelled']);
const WAITING_MANUAL_UPLOAD_STATUSES = new Set(['manual_upload_pending']);
const PENDING_REVIEW_STATUSES = new Set(['pending_review']);
const ACTIONABLE_FILTER_STATUSES = new Set([
'pending_review',
'failed',
'reparse_failed',
'queued',
'manual_upload_pending',
]);
const REPARSE_STATUSES = new Set(['failed', 'reparse_failed', 'pending_review']);
/**
* 将 Item 归入展示分组。
*/
function resolveGroup(item: ShippingWorkflowItem): ItemGroupKey {
const status = String(item.lifecycle_status || '').trim();
if (PENDING_REVIEW_STATUSES.has(status)) return 'pending_review';
if (FAILED_STATUSES.has(status)) return 'failed';
if (WAITING_MANUAL_UPLOAD_STATUSES.has(status)) return 'waiting_manual_upload';
if (COMPLETED_STATUSES.has(status)) return 'completed';
if (QUEUED_STATUSES.has(status)) return 'queued';
if (PROCESSING_STATUSES.has(status)) return 'processing';
return 'processing';
}
/**
* 是否允许取消(非 closed/cancelled)。
*/
function canCancel(item: ShippingWorkflowItem): boolean {
return !COMPLETED_STATUSES.has(String(item.lifecycle_status || '').trim());
}
/**
* 是否允许重试/重新识别。
*/
function canReparse(item: ShippingWorkflowItem): boolean {
return REPARSE_STATUSES.has(String(item.lifecycle_status || '').trim());
}
/**
* 列表主标题:优先文件名。
*/
function itemTitle(item: ShippingWorkflowItem): string {
const filename = String(item.current_document_filename || '').trim();
if (filename) return filename;
return t('chat.shippingWorkflow.filenameFallback', {
docId: item.current_document_id,
});
}
const filteredItems = computed(() => {
if (!pendingOnlyFilter.value) return items.value;
return items.value.filter((item) =>
ACTIONABLE_FILTER_STATUSES.has(String(item.lifecycle_status || '').trim()),
);
});
const grouped = computed(() => {
const buckets: Record<ItemGroupKey, ShippingWorkflowItem[]> = {
processing: [],
queued: [],
pending_review: [],
waiting_manual_upload: [],
failed: [],
completed: [],
};
for (const item of filteredItems.value) {
buckets[resolveGroup(item)].push(item);
}
return buckets;
});
const groupOrder: ItemGroupKey[] = [
'processing',
'queued',
'pending_review',
'waiting_manual_upload',
'failed',
'completed',
];
/**
* 解析生命周期状态文案。
*/
function statusLabel(status: string): string {
const key = `chat.shippingWorkflow.itemStatus.${status}`;
return te(key) ? t(key) : status;
}
/**
* 格式化更新时间。
*/
function formatUpdatedLabel(value?: string | null): string {
const date = new Date(String(value || ''));
if (Number.isNaN(date.getTime())) return '';
const time = new Intl.DateTimeFormat(String(locale.value || 'zh-CN'), {
hour: '2-digit',
minute: '2-digit',
hour12: false,
}).format(date);
return t('chat.shippingOrderExtractionDocumentTiming.updated', { time });
}
/**
* 格式化批次活动时间(切换器副文案)。
*/
function formatBatchTime(value?: string | null): string {
const date = new Date(String(value || ''));
if (Number.isNaN(date.getTime())) return '';
return new Intl.DateTimeFormat(String(locale.value || 'zh-CN'), {
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
hour12: false,
}).format(date);
}
/**
* 手动刷新。
*/
async function onRefresh() {
await ctl.value.refresh();
}
/**
* 切换批次。
*/
function onSelectWorkflow(workflowNo: string) {
ctl.value.selectWorkflow(workflowNo);
}
/**
* 打开详情:优先拉取含 events 的 Item 详情。
*/
async function openDetail(item: ShippingWorkflowItem) {
const itemNo = String(item.item_no || '').trim();
if (!itemNo) return;
detailOpen.value = true;
detailItem.value = item;
detailLoading.value = true;
try {
detailItem.value = await getWorkspaceShippingWorkflowItem(itemNo, {
include_events: true,
});
} catch {
/* 列表投影仍可展示 */
} finally {
detailLoading.value = false;
}
}
/**
* 打开取消原因弹窗。
*/
function openCancelDialog(item: ShippingWorkflowItem) {
reasonDialogItem.value = item;
reasonDialogAction.value = 'cancel';
reasonDialogOpen.value = true;
}
/**
* 打开重识别原因弹窗。
*/
function openReparseDialog(item: ShippingWorkflowItem) {
reasonDialogItem.value = item;
reasonDialogAction.value = 'reparse';
reasonDialogOpen.value = true;
}
/**
* 原因弹窗确认:按 action 取消或重识别。
*/
async function onReasonConfirm(payload: { reason: string; comment?: string }) {
const item = reasonDialogItem.value;
const itemNo = String(item?.item_no || '').trim();
if (!item || !itemNo || actionBusyItemNo.value) return;
actionBusyItemNo.value = itemNo;
try {
if (reasonDialogAction.value === 'reparse') {
await ctl.value.reparseItem(itemNo, {
reason: payload.reason,
comment: payload.comment,
});
} else {
await ctl.value.cancelItem(itemNo, {
reason: payload.reason,
expected_lock_version: item.lock_version,
});
}
reasonDialogOpen.value = false;
reasonDialogItem.value = null;
if (detailItem.value?.item_no === itemNo) {
detailOpen.value = false;
detailItem.value = null;
}
} catch (err) {
const message = err instanceof BusinessError ? err.message : t('errors.generic');
msg.error(message);
} finally {
actionBusyItemNo.value = null;
}
}
watch(
() => error.value,
() => {
/* 面板内展示 network_recoverable,不弹 toast */
},
);
</script>
<template>
<aside
class="flex w-72 shrink-0 flex-col border-l border-default bg-surface shadow-[-8px_0_24px_rgba(15,23,42,0.04)]"
data-testid="shipping-workflow-timeline"
>
<div class="flex w-full items-center gap-1 border-b border-default px-2 py-2">
<button
type="button"
class="flex min-w-0 flex-1 items-center justify-between gap-2 rounded-md px-1 py-1 text-left hover:bg-surface-muted/60"
@click="collapsed = !collapsed"
>
<div class="min-w-0">
<div class="text-sm font-semibold text-primary">
{{ t('chat.shippingWorkflow.title') }}
</div>
<div class="mt-0.5 text-xs text-secondary">
{{ t('chat.shippingWorkflow.pdfCount', { count: counts.total }) }}
</div>
</div>
<ChevronDown v-if="!collapsed" class="h-4 w-4 shrink-0 text-muted" />
<ChevronRight v-else class="h-4 w-4 shrink-0 text-muted" />
</button>
<button
type="button"
class="shrink-0 rounded-md p-1.5 text-muted hover:bg-surface-muted hover:text-primary disabled:opacity-50"
:disabled="loading"
:title="t('chat.shippingWorkflow.actions.refresh')"
data-testid="shipping-workflow-refresh"
@click="onRefresh"
>
<RefreshCw class="h-3.5 w-3.5" :class="{ 'animate-spin': loading }" />
</button>
</div>
<div v-if="!collapsed" class="min-h-0 flex-1 overflow-auto p-3">
<div
v-if="showBatchSwitcher"
class="mb-3 space-y-1.5"
data-testid="shipping-workflow-batch-switcher"
>
<div class="text-[11px] font-semibold uppercase tracking-wide text-secondary">
{{ t('chat.shippingWorkflow.batchSwitcherTitle') }}
</div>
<button
v-for="batch in workflows"
:key="batch.workflow_no"
type="button"
class="w-full rounded-lg border px-2.5 py-2 text-left transition"
:class="batch.workflow_no === selectedWorkflowNo
? 'border-brand-500 bg-brand-50/80 dark:border-brand-400 dark:bg-brand-950/30'
: 'border-default bg-surface-soft/80 hover:bg-surface-muted/50'"
:data-testid="`shipping-workflow-batch-${batch.workflow_no}`"
@click="onSelectWorkflow(batch.workflow_no)"
>
<div class="truncate text-xs font-semibold text-primary">
{{ batch.workflow_no }}
</div>
<div class="mt-0.5 text-[11px] text-secondary">
{{ statusLabel(batch.current_stage) || batch.current_stage }}
· {{ t('chat.shippingWorkflow.batchCounts', {
processing: batch.counts.processing,
pending: batch.counts.pending_review,
waiting: batch.counts.waiting_manual_upload || 0,
failed: batch.counts.failed,
completed: batch.counts.completed,
}) }}
</div>
<div v-if="batch.last_activity_at" class="mt-0.5 text-[11px] text-muted">
{{ formatBatchTime(batch.last_activity_at) }}
</div>
</button>
</div>
<label class="mb-3 flex cursor-pointer items-center gap-2 text-[11px] text-secondary">
<input
v-model="pendingOnlyFilter"
type="checkbox"
class="rounded border-default"
data-testid="shipping-workflow-pending-only-filter"
/>
{{ t('chat.shippingWorkflow.pendingOnlyFilter') }}
</label>
<div class="mb-3 flex flex-wrap gap-1.5 text-[11px]">
<span class="rounded-md bg-sky-50 px-2 py-0.5 text-sky-700 dark:bg-sky-950/40 dark:text-sky-200">
{{ t('chat.shippingWorkflow.counts.processing', { count: counts.processing }) }}
</span>
<span
v-if="counts.pending_review > 0"
class="rounded-md bg-amber-50 px-2 py-0.5 text-amber-700 dark:bg-amber-950/40 dark:text-amber-200"
>
{{ t('chat.shippingWorkflow.counts.pendingReview', { count: counts.pending_review }) }}
</span>
<span
v-if="(counts.waiting_manual_upload || 0) > 0"
class="rounded-md bg-amber-50 px-2 py-0.5 text-amber-800 dark:bg-amber-950/40 dark:text-amber-100"
>
{{ t('chat.shippingWorkflow.counts.waitingManualUpload', {
count: counts.waiting_manual_upload || 0,
}) }}
</span>
<span class="rounded-md bg-emerald-50 px-2 py-0.5 text-emerald-700 dark:bg-emerald-950/40 dark:text-emerald-200">
{{ t('chat.shippingWorkflow.counts.completed', { count: counts.completed }) }}
</span>
<span
v-if="counts.failed > 0"
class="rounded-md bg-rose-50 px-2 py-0.5 text-rose-700 dark:bg-rose-950/40 dark:text-rose-200"
>
{{ t('chat.shippingWorkflow.counts.failed', { count: counts.failed }) }}
</span>
</div>
<div
v-if="workflow?.current_stage || workflow?.last_activity_at"
class="mb-3 text-[11px] text-secondary"
data-testid="shipping-workflow-stage-summary"
>
<span v-if="workflow?.current_stage">
{{ t('chat.shippingWorkflow.currentStage', {
stage: statusLabel(workflow.current_stage) || workflow.current_stage,
}) }}
</span>
<span v-if="workflow?.last_activity_at" class="ml-1">
· {{ formatUpdatedLabel(workflow.last_activity_at) }}
</span>
</div>
<div
v-if="error === 'network_recoverable'"
class="mb-3 rounded-md border border-amber-200 bg-amber-50 px-2.5 py-2 text-[11px] text-amber-900 dark:border-amber-900/60 dark:bg-amber-950/40 dark:text-amber-100"
data-testid="shipping-workflow-network-error"
>
{{ t('chat.shippingWorkflow.networkRecoverable') }}
</div>
<div
v-else-if="error"
class="mb-3 rounded-md border border-rose-200 bg-rose-50 px-2.5 py-2 text-[11px] text-rose-800 dark:border-rose-900/60 dark:bg-rose-950/40 dark:text-rose-100"
>
{{ error }}
</div>
<div v-if="!filteredItems.length" class="text-xs text-muted">
{{ loading ? t('chat.shippingWorkflow.loading') : t('chat.shippingWorkflow.empty') }}
</div>
<template v-for="groupKey in groupOrder" :key="groupKey">
<section
v-if="grouped[groupKey].length"
class="mb-3"
:data-testid="`shipping-workflow-group-${groupKey}`"
>
<h3 class="mb-1.5 text-[11px] font-semibold uppercase tracking-wide text-secondary">
{{ t(`chat.shippingWorkflow.groups.${groupKey}`) }}
</h3>
<ul class="space-y-2">
<li
v-for="item in grouped[groupKey]"
:key="item.item_no"
class="rounded-lg border border-default bg-surface-soft/80 px-2.5 py-2"
:data-testid="`shipping-workflow-item-${item.item_no}`"
>
<div class="flex items-start justify-between gap-2">
<div class="min-w-0">
<div
class="truncate text-xs font-semibold text-primary"
:title="itemTitle(item)"
data-testid="shipping-workflow-item-filename"
>
{{ itemTitle(item) }}
</div>
<div class="mt-0.5 text-[11px] text-muted">
{{ t('chat.shippingWorkflow.versionLabel', { version: item.current_version_no }) }}
· {{ statusLabel(String(item.current_stage || item.lifecycle_status || '')) }}
<span v-if="!item.current_case_no" class="ml-1 text-secondary">
· {{ t('chat.shippingWorkflow.noReviewCaseYet') }}
</span>
</div>
</div>
<span
class="shrink-0 rounded-full px-1.5 py-0.5 text-[10px] font-medium"
:class="{
'bg-amber-100 text-amber-800 dark:bg-amber-900/50 dark:text-amber-100':
groupKey === 'pending_review'
|| groupKey === 'failed'
|| groupKey === 'waiting_manual_upload',
'bg-sky-100 text-sky-800 dark:bg-sky-900/50 dark:text-sky-100':
groupKey === 'processing' || groupKey === 'queued',
'bg-emerald-100 text-emerald-800 dark:bg-emerald-900/50 dark:text-emerald-100':
groupKey === 'completed',
}"
>
{{ statusLabel(String(item.lifecycle_status || '')) }}
</span>
</div>
<div v-if="item.last_activity_at || item.updated_at" class="mt-0.5 text-[11px] text-muted">
{{ formatUpdatedLabel(item.last_activity_at || item.updated_at) }}
</div>
<div class="mt-2 flex flex-wrap gap-2">
<button
type="button"
class="inline-flex items-center gap-1 text-[11px] font-medium text-brand-700 hover:underline"
data-testid="shipping-workflow-action-view"
@click="openDetail(item)"
>
{{ t('chat.shippingWorkflow.actions.viewProgress') }}
</button>
<button
v-if="canReparse(item)"
type="button"
class="inline-flex items-center gap-1 text-[11px] font-medium text-amber-800 hover:underline disabled:opacity-50 dark:text-amber-200"
:disabled="actionBusyItemNo === item.item_no"
data-testid="shipping-workflow-action-reparse"
@click="openReparseDialog(item)"
>
{{ t('chat.shippingWorkflow.actions.reparse') }}
</button>
<button
v-if="canCancel(item)"
type="button"
class="inline-flex items-center gap-1 text-[11px] font-medium text-rose-700 hover:underline disabled:opacity-50"
:disabled="actionBusyItemNo === item.item_no"
data-testid="shipping-workflow-action-cancel"
@click="openCancelDialog(item)"
>
{{ t('chat.shippingWorkflow.actions.cancelFile') }}
</button>
</div>
</li>
</ul>
</section>
</template>
</div>
<ShippingWorkflowItemDetailDrawer
:open="detailOpen"
:item="detailItem"
:loading="detailLoading"
:cancelling="Boolean(detailItem && actionBusyItemNo === detailItem.item_no && reasonDialogAction === 'cancel')"
:reparsing="Boolean(detailItem && actionBusyItemNo === detailItem.item_no && reasonDialogAction === 'reparse')"
@close="detailOpen = false; detailItem = null"
@cancel="openCancelDialog"
@reparse="openReparseDialog"
/>
<ShippingWorkflowReasonDialog
v-model="reasonDialogOpen"
:action="reasonDialogAction"
:confirm-loading="Boolean(actionBusyItemNo)"
@confirm="onReasonConfirm"
/>
</aside>
</template>