Merge branch 'hugo-shipping-notice' into dev

# Conflicts:
#	frontend/src/features/chat/components/ChatViewContent.vue
This commit is contained in:
hugo committed 2026-09-17 16:29:10 +08:00
commit 80d78130f8
121 files changed
+9621 -1263

No files matched your search

@@ -24,11 +24,57 @@ export interface ShippingMyTodosCount {
processing: number;
done: number;
total_pending_badge: number;
/** 待处理桶按可动作生命周期阶段的全量聚合计数(阶段筛选 tab)。 */
stage_counts?: {
intake_parse: number;
order_review: number;
fulfillment_prep: number;
freight_upload: number;
};
/** done 桶终态拆分:通知完成 vs 复核驳回/作废。 */
done_counts?: {
upload_complete: number;
reject_void: number;
};
}
/** 已完成通知明细行(通知完成报表):标准 12 字段 + 溯源编号。 */
export interface ShippingDoneLineItem {
task_no: string;
business_no: string | null;
customer_name: string | null;
customer_code: string | null;
order_date: string | null;
line_no: number;
part_number: string | null;
qty: number | null;
required_date: string | null;
customer_po_number: string | null;
/** 无数据源,契约占位恒为 null(页面与导出留空)。 */
used_qty: number | null;
open_qty: number | null;
source_order_number: string | null;
unit_price: number | null;
}
export interface ShippingDoneLinesPage {
items: ShippingDoneLineItem[];
page: number;
page_size: number;
total: number;
}
export interface ShippingDoneLineFilters {
customer?: string;
part_number?: string;
notice_date_from?: string;
notice_date_to?: string;
}
/**
* 分页拉取「我的待办」。
* @param params.bucket - pending | processing | done
* @param params.terminal_kind - done 桶终态子视图(upload_complete | reject_void)
*/
export function listWorkspaceShippingMyTodos(params?: {
bucket?: 'pending' | 'processing' | 'done' | string;
@@ -37,6 +83,7 @@ export function listWorkspaceShippingMyTodos(params?: {
todo_category?: string;
customer?: string;
task_no?: string;
terminal_kind?: string;
}) {
const sp = new URLSearchParams();
if (params?.bucket) sp.set('bucket', params.bucket);
@@ -45,6 +92,7 @@ export function listWorkspaceShippingMyTodos(params?: {
if (params?.todo_category) sp.set('todo_category', params.todo_category);
if (params?.customer) sp.set('customer', params.customer);
if (params?.task_no) sp.set('task_no', params.task_no);
if (params?.terminal_kind) sp.set('terminal_kind', params.terminal_kind);
const q = sp.toString();
return requestJson<ShippingMyTodosPage>(
`/api/workspace/shipping-tasks/my-todos${q ? `?${q}` : ''}`,
@@ -58,6 +106,68 @@ export function countWorkspaceShippingMyTodos() {
return requestJson<ShippingMyTodosCount>('/api/workspace/shipping-tasks/my-todos/count');
}
/**
* 分页拉取已完成通知的平铺明细行(通知完成报表)。
* 明细行跨 Notice 混排、不按 OT 聚合,仅含已核验上传成功的通知。
*/
export function listWorkspaceShippingDoneLines(params?: {
page?: number;
page_size?: number;
} & ShippingDoneLineFilters) {
const sp = new URLSearchParams();
if (params?.page) sp.set('page', String(params.page));
if (params?.page_size) sp.set('page_size', String(params.page_size));
if (params?.customer) sp.set('customer', params.customer);
if (params?.part_number) sp.set('part_number', params.part_number);
if (params?.notice_date_from) sp.set('notice_date_from', params.notice_date_from);
if (params?.notice_date_to) sp.set('notice_date_to', params.notice_date_to);
const q = sp.toString();
return requestJson<ShippingDoneLinesPage>(
`/api/workspace/shipping-tasks/my-todos/done-lines${q ? `?${q}` : ''}`,
);
}
/**
* 下载当前筛选下的已完成通知明细 Excel(固定 12 列标准格式,不含 OT 编号)。
* 核心逻辑:浏览器受控 a[download] 下载,后端复核可见性与筛选参数。
*/
export async function downloadWorkspaceShippingDoneLinesExcel(
filters?: ShippingDoneLineFilters,
): Promise<void> {
const sp = new URLSearchParams();
if (filters?.customer) sp.set('customer', filters.customer);
if (filters?.part_number) sp.set('part_number', filters.part_number);
if (filters?.notice_date_from) sp.set('notice_date_from', filters.notice_date_from);
if (filters?.notice_date_to) sp.set('notice_date_to', filters.notice_date_to);
const q = sp.toString();
const url = `/api/workspace/shipping-tasks/my-todos/done-lines/export${q ? `?${q}` : ''}`;
const { getAuthHeaders } = await import('@/shared/utils/auth');
const res = await fetch(url, { headers: getAuthHeaders() });
if (!res.ok) {
const body = await res.json().catch(() => ({}));
throw new Error(
(body as { error?: string; message?: string })?.error
|| (body as { message?: string })?.message
|| res.statusText,
);
}
const disposition = res.headers.get('content-disposition');
const blob = await res.blob();
const objectUrl = URL.createObjectURL(blob);
const anchor = document.createElement('a');
anchor.href = objectUrl;
const rawName = disposition?.match(/filename\*?=(?:UTF-8'')?["']?([^;"'\n]+)/)?.[1] || 'done-lines.xlsx';
try {
anchor.download = decodeURIComponent(rawName);
} catch {
anchor.download = rawName;
}
document.body.appendChild(anchor);
anchor.click();
document.body.removeChild(anchor);
URL.revokeObjectURL(objectUrl);
}
export {
downloadWorkspaceShippingExcelFile,
markWorkspaceShippingManualUploaded,
@@ -0,0 +1,181 @@
<!--
features/workspace/shipping-task-center/ShippingDoneLineReport.vue
用途:已完成桶「通知完成」子视图——跨 OT 平铺的明细行报表(13 列 + 筛选 + 导出)。
依赖:shipping-tasks.api 类型;导出下载由父级执行。
逻辑:只读报表(无抽屉、无行操作);首列 OT/business 编号仅页面展示,
导出为固定 12 列标准格式(后端裁决);分页按明细行计。
-->
<script setup lang="ts">
import { Download } from 'lucide-vue-next';
import type { ShippingDoneLineItem } from '@/features/workspace/api/shipping-tasks.api';
import type { ShippingDoneLineFilters } from '@/features/workspace/api/shipping-tasks.api';
const props = defineProps<{
items: ShippingDoneLineItem[];
total: number;
page: number;
pageSize: number;
loading?: boolean;
exportBusy?: boolean;
filters?: ShippingDoneLineFilters;
}>();
const emit = defineEmits<{
(event: 'update:filters', value: ShippingDoneLineFilters): void;
(event: 'apply'): void;
(event: 'page-change', page: number): void;
(event: 'export'): void;
}>();
const totalPages = () => Math.max(1, Math.ceil(props.total / props.pageSize));
function setFilter(key: keyof ShippingDoneLineFilters, event: Event) {
const value = String((event.target as HTMLInputElement).value || '');
emit('update:filters', { ...props.filters, [key]: value });
}
function onExport(): void {
emit('export');
}
</script>
<template>
<div class="space-y-3">
<div class="flex flex-wrap items-end gap-3 rounded-2xl border border-default bg-surface px-4 py-3">
<label class="space-y-1">
<span class="text-xs font-medium text-muted">{{ $t('workspace.shippingNotice.myTodos.doneReport.filters.customer') }}</span>
<input
type="text"
class="input-field text-sm min-w-[10rem]"
:value="filters?.customer || ''"
:placeholder="$t('workspace.shippingNotice.myTodos.filters.customerPlaceholder')"
data-testid="done-lines-filter-customer"
@change="setFilter('customer', $event)"
@keyup.enter="emit('apply')"
>
</label>
<label class="space-y-1">
<span class="text-xs font-medium text-muted">{{ $t('workspace.shippingNotice.myTodos.doneReport.filters.partNumber') }}</span>
<input
type="text"
class="input-field text-sm min-w-[10rem]"
:value="filters?.part_number || ''"
data-testid="done-lines-filter-part"
@change="setFilter('part_number', $event)"
@keyup.enter="emit('apply')"
>
</label>
<label class="space-y-1">
<span class="text-xs font-medium text-muted">{{ $t('workspace.shippingNotice.myTodos.doneReport.filters.dateFrom') }}</span>
<input
type="date"
class="input-field text-sm"
:value="filters?.notice_date_from || ''"
data-testid="done-lines-filter-date-from"
@change="setFilter('notice_date_from', $event)"
>
</label>
<label class="space-y-1">
<span class="text-xs font-medium text-muted">{{ $t('workspace.shippingNotice.myTodos.doneReport.filters.dateTo') }}</span>
<input
type="date"
class="input-field text-sm"
:value="filters?.notice_date_to || ''"
data-testid="done-lines-filter-date-to"
@change="setFilter('notice_date_to', $event)"
>
</label>
<div class="flex gap-2">
<button
type="button"
class="rounded-xl bg-brand-600 px-3 py-1.5 text-sm font-medium text-white hover:bg-brand-700 disabled:opacity-50"
:disabled="loading"
@click="emit('apply')"
>
{{ $t('workspace.shippingNotice.myTodos.filters.apply') }}
</button>
<button
type="button"
class="inline-flex items-center gap-1.5 rounded-xl border border-brand-300 px-3 py-1.5 text-sm font-medium text-brand-700 hover:bg-brand-50 disabled:opacity-50"
:disabled="exportBusy || loading || !total"
data-testid="done-lines-export"
@click="onExport"
>
<Download class="h-3.5 w-3.5" />
{{ $t('workspace.shippingNotice.myTodos.doneReport.export') }}
</button>
</div>
</div>
<div v-if="loading" class="rounded-2xl border border-dashed border-default py-10 text-center text-sm text-muted">
{{ $t('workspace.shippingNotice.loading') }}
</div>
<div v-else-if="!items.length" class="rounded-2xl border border-dashed border-default py-10 text-center text-sm text-muted">
{{ $t('workspace.shippingNotice.myTodos.empty') }}
</div>
<div v-else class="overflow-x-auto rounded-2xl border border-default bg-surface">
<table class="w-full min-w-[1200px] border-collapse text-[13px]" data-testid="done-lines-table">
<thead>
<tr class="border-b border-default bg-surface-soft/60 text-left text-xs text-muted">
<th class="px-3 py-2.5 font-medium">{{ $t('workspace.shippingNotice.myTodos.doneReport.columns.taskNo') }}</th>
<th class="px-3 py-2.5 font-medium">{{ $t('workspace.shippingNotice.myTodos.doneReport.columns.customer') }}</th>
<th class="px-3 py-2.5 font-medium">{{ $t('workspace.shippingNotice.myTodos.doneReport.columns.customerCode') }}</th>
<th class="px-3 py-2.5 font-medium">{{ $t('workspace.shippingNotice.myTodos.doneReport.columns.orderDate') }}</th>
<th class="px-3 py-2.5 font-medium">{{ $t('workspace.shippingNotice.myTodos.doneReport.columns.lineNo') }}</th>
<th class="px-3 py-2.5 font-medium">{{ $t('workspace.shippingNotice.myTodos.doneReport.columns.partNumber') }}</th>
<th class="px-3 py-2.5 font-medium">{{ $t('workspace.shippingNotice.myTodos.doneReport.columns.qty') }}</th>
<th class="px-3 py-2.5 font-medium">{{ $t('workspace.shippingNotice.myTodos.doneReport.columns.requiredDate') }}</th>
<th class="px-3 py-2.5 font-medium">{{ $t('workspace.shippingNotice.myTodos.doneReport.columns.customerPo') }}</th>
<th class="px-3 py-2.5 font-medium">{{ $t('workspace.shippingNotice.myTodos.doneReport.columns.usedQty') }}</th>
<th class="px-3 py-2.5 font-medium">{{ $t('workspace.shippingNotice.myTodos.doneReport.columns.openQty') }}</th>
<th class="px-3 py-2.5 font-medium">{{ $t('workspace.shippingNotice.myTodos.doneReport.columns.sourceOrderNo') }}</th>
<th class="px-3 py-2.5 font-medium">{{ $t('workspace.shippingNotice.myTodos.doneReport.columns.unitPrice') }}</th>
</tr>
</thead>
<tbody>
<tr
v-for="line in items"
:key="`${line.task_no}-${line.line_no}`"
class="border-b border-[#f0f3f8]"
>
<td class="px-3 py-2 font-mono text-xs font-semibold text-primary">
{{ line.business_no || line.task_no }}
</td>
<td class="px-3 py-2">{{ line.customer_name || '—' }}</td>
<td class="px-3 py-2">{{ line.customer_code || '—' }}</td>
<td class="px-3 py-2 tabular-nums">{{ line.order_date || '—' }}</td>
<td class="px-3 py-2 tabular-nums">{{ line.line_no }}</td>
<td class="px-3 py-2 font-mono">{{ line.part_number || '—' }}</td>
<td class="px-3 py-2 tabular-nums">{{ line.qty ?? '' }}</td>
<td class="px-3 py-2 tabular-nums">{{ line.required_date || '—' }}</td>
<td class="px-3 py-2">{{ line.customer_po_number || '—' }}</td>
<td class="px-3 py-2 tabular-nums">{{ line.used_qty ?? '' }}</td>
<td class="px-3 py-2 tabular-nums">{{ line.open_qty ?? '' }}</td>
<td class="px-3 py-2 font-mono">{{ line.source_order_number || '—' }}</td>
<td class="px-3 py-2 tabular-nums">{{ line.unit_price ?? '' }}</td>
</tr>
</tbody>
</table>
</div>
<div v-if="totalPages() > 1" class="flex items-center justify-between gap-2 text-xs text-muted">
<button
type="button"
class="rounded-lg border border-default px-2 py-1 disabled:opacity-50"
:disabled="page <= 1 || loading"
@click="emit('page-change', page - 1)"
>
{{ $t('workspace.shippingNotice.pagination.previous') }}
</button>
<span>{{ page }}/{{ totalPages() }}</span>
<button
type="button"
class="rounded-lg border border-default px-2 py-1 disabled:opacity-50"
:disabled="page >= totalPages() || loading"
@click="emit('page-change', page + 1)"
>
{{ $t('workspace.shippingNotice.pagination.next') }}
</button>
</div>
</div>
</template>
@@ -0,0 +1,63 @@
<!--
features/workspace/shipping-task-center/ShippingStageTabs.vue
用途:阶段筛选 tab(全部 + 四个可动作阶段),计数来自后端全量聚合。
依赖:shippingTaskCenterShared 的 ACTIONABLE_TODO_STAGES 口径。
逻辑:点击切换筛选并向上同步;「通知完成」不再作为筛选维度(归 done 桶终态子视图)。
-->
<script setup lang="ts">
import { useI18n } from 'vue-i18n';
import { ACTIONABLE_TODO_STAGES, type LifecycleStageCode } from './shippingTaskCenterShared';
const { t } = useI18n();
const props = defineProps<{
modelValue: 'all' | LifecycleStageCode;
/** 后端聚合的阶段计数(缺省按 0 展示)。 */
counts?: Partial<Record<LifecycleStageCode, number>>;
}>();
const emit = defineEmits<{
(event: 'update:modelValue', value: 'all' | LifecycleStageCode): void;
}>();
function countOf(stage: LifecycleStageCode): number {
return Number(props.counts?.[stage] ?? 0);
}
function stageLabel(stage: LifecycleStageCode): string {
return t(`workspace.shippingNotice.myTodos.lifecycleStages.${stage}`);
}
</script>
<template>
<div
class="flex flex-wrap gap-2"
data-testid="my-todos-lifecycle-stage-filter"
>
<button
type="button"
class="rounded-full px-3.5 py-1.5 text-sm font-medium transition-colors"
:class="modelValue === 'all'
? 'bg-brand-600 text-white'
: 'border border-default text-secondary hover:bg-surface-soft'"
data-testid="my-todos-stage-filter-all"
@click="emit('update:modelValue', 'all')"
>
{{ $t('workspace.shippingNotice.myTodos.filters.all') }}
</button>
<button
v-for="stage in ACTIONABLE_TODO_STAGES"
:key="stage"
type="button"
class="rounded-full px-3.5 py-1.5 text-sm font-medium transition-colors"
:class="modelValue === stage
? 'bg-brand-600 text-white'
: 'border border-default text-secondary hover:bg-surface-soft'"
:data-testid="`my-todos-stage-filter-${stage}`"
@click="emit('update:modelValue', stage)"
>
{{ stageLabel(stage) }}
<span class="ml-1 font-mono text-xs opacity-80">{{ countOf(stage) }}</span>
</button>
</div>
</template>
@@ -1,8 +1,10 @@
/**
* features/workspace/shipping-task-center/ShippingTaskCenterPage.notice-batch.spec.ts
* 用途:验收任务中心只按发货通知单 business_no 展示与执行货代批量操作。
* 用途:验收任务中心改版——紧凑表格、货代上传阶段限定批量、阶段 tab 后端计数、
* done 桶子视图(通知完成明细报表 / 驳回作废任务表)与详情抽屉。
* 依赖:ShippingTaskCenterPage、货代 API、我的待办 API、Vue Test Utils。
* 逻辑:正式 Notice 可选择并传 business_nos;Review/Intake 不能进入选择集;列表行只显示服务端投影的通知明细。
* 逻辑:批量仅正式 Notice 且货代上传阶段可选;明细行详情进抽屉(Teleport 到 body);
* 通知完成子视图消费 done-lines 平铺报表;驳回作废子视图带 terminal_kind 过滤。
*/
import { afterEach, describe, expect, it, vi } from 'vitest';
import { flushPromises, mount } from '@vue/test-utils';
@@ -14,6 +16,11 @@ const batchConfirm = vi.fn(async () => ({ results: [{ status: 'confirmed' }] }))
const batchRpa = vi.fn(async () => ({ results: [{ status: 'accepted' }] }));
const downloadArchive = vi.fn(async () => undefined);
const listTodos = vi.fn(async () => ({ items: [], page: 1, page_size: 20, total: 0 }));
const listDoneLines = vi.fn(async () => ({ items: [], page: 1, page_size: 50, total: 0 }));
const downloadDoneLinesExcel = vi.fn(async () => undefined);
const countTodos = vi.fn(async () => ({
pending: 0, processing: 0, done: 0, total_pending_badge: 0,
}));
vi.mock('@/features/chat/api/shipping.api', () => ({
SHIPPING_NOTICE_AGENT_CODE: 'shipping_notice',
@@ -26,7 +33,9 @@ vi.mock('@/features/chat/api/shipping.api', () => ({
vi.mock('@/features/workspace/api/shipping-tasks.api', () => ({
listWorkspaceShippingMyTodos: (...args: unknown[]) => listTodos(...args),
countWorkspaceShippingMyTodos: vi.fn(async () => ({ pending: 0, processing: 0, done: 0, total_pending_badge: 0 })),
countWorkspaceShippingMyTodos: (...args: unknown[]) => countTodos(...args),
listWorkspaceShippingDoneLines: (...args: unknown[]) => listDoneLines(...args),
downloadWorkspaceShippingDoneLinesExcel: (...args: unknown[]) => downloadDoneLinesExcel(...args),
}));
vi.mock('@/features/workspace/composables/useShippingTodoBadge', () => ({
@@ -53,6 +62,7 @@ const i18n = createI18n({
subtitle: '按文件查看进度',
lifecycleStages: {
filterLabel: '阶段',
viewStage: '查看阶段',
intake_parse: '接收解析',
order_review: '订单复核',
fulfillment_prep: '通知准备',
@@ -60,6 +70,12 @@ const i18n = createI18n({
upload_complete: '通知完成',
},
buckets: { pending: '待处理', processing: '处理中', done: '已完成' },
subTabs: { uploadComplete: '通知完成', rejectVoid: '复核驳回 / 已作废' },
table: {
no: '编号', stage: '阶段', summary: '状态摘要', lines: '项次',
lineUnit: '项', shortage: '缺 {count}', freightStatus: '货代状态',
},
terminal: { uploadComplete: '上传完成', rejectVoid: '复核驳回' },
filters: {
todoCategory: '待办类型', all: '全部', review: '待复核', exception: '异常',
manualUpload: '人工上传', intakeParse: '接收解析', customer: '客户',
@@ -75,9 +91,44 @@ const i18n = createI18n({
intakeParseBadge: '材料解析',
progressSummary: '当前阶段:{stage}',
progressBlocker: '当前阻断:{reason}',
viewStage: '查看阶段',
drawer: {
details: '逐行明细',
files: '文件',
close: '关闭',
exportExcel: '导出 Excel',
lineTable: {
lineNo: '行', partNumber: '料号', customerPartNumber: '客户料号',
reservationId: '预约号', shipmentQty: '本次发货', availableQty: '可用库存',
shortageQty: '缺口', status: '状态',
},
},
doneReport: {
export: '导出 Excel(当前筛选)',
exportStarted: '已开始下载',
filters: { customer: '客户', partNumber: '料号', dateFrom: '通知日期起', dateTo: '通知日期止' },
columns: {
taskNo: 'OT 编号', customer: '客户', customerCode: '客户编号', orderDate: '订单日期',
lineNo: '订单项次', partNumber: '料号', qty: '数量', requiredDate: '约定出货日期',
customerPo: '客户PO', usedQty: '已用数量', openQty: 'open qty',
sourceOrderNo: '订单单号', unitPrice: '单价',
},
},
},
openChat: '打开对话',
batch: {
selectAll: '全选当前页通知单',
selected: '已选 {count} 张',
download: '批量下载 Excel',
confirm: '批量确认已上传',
rpa: '批量发起 RPA',
clearSelection: '清除选择',
downloadStarted: '已开始下载',
success: '成功 {count} 张',
partialResult: '部分成功 {accepted}/{accepted}/{blocked}',
},
todo: { adminViewOnlyShort: '只读' },
actions: { failed: '操作失败' },
pagination: { previous: '上一页', next: '下一页' },
},
},
},
@@ -90,12 +141,17 @@ const routes = [{
component: ShippingTaskCenterPage,
}];
/** 待处理货代上传阶段 Notice:批量可选 + 列表投影。 */
function notice(businessNo: string, poNumber: string, partNumber: string) {
return {
id: Number(businessNo.slice(-2)), task_no: `SN-${businessNo}`, business_no: businessNo,
item_kind: 'task', todo_ref: `SN-${businessNo}`, source_type: 'post_ot_fulfillment_wave',
po_number: poNumber, customer_name: 'Customer', upload_status: 'pending',
notice_line_summary: [{ line_no: '10', part_number: partNumber, shipment_qty: '4', available_qty: '9' }],
ui_state: { stage: { code: 'freight_upload', label: '货代上传' }, lifecycle_entries: [] },
notice_line_summary: [
{ line_no: '10', part_number: partNumber, shipment_qty: '4', available_qty: '9' },
{ line_no: '20', part_number: `${partNumber}-B`, shipment_qty: '2', available_qty: '9', shortage_qty: 1 },
],
artifact_summary: { export_file_name: `${businessNo}.xlsx` },
};
}
@@ -115,12 +171,17 @@ async function mountPage() {
});
}
function drawerText(): string {
return document.body.querySelector('[data-testid="my-todos-drawer"]')?.textContent || '';
}
describe('ShippingTaskCenterPage notice batch operations', () => {
afterEach(() => {
vi.clearAllMocks();
document.body.innerHTML = '';
});
it('only makes formal Notices selectable and displays each Notice projection', async () => {
it('only makes freight-upload Notices selectable and shows line details in drawer', async () => {
listTodos.mockResolvedValueOnce({
items: [
notice('WYC26082301', 'PO-100', 'PART-A'),
@@ -132,13 +193,20 @@ describe('ShippingTaskCenterPage notice batch operations', () => {
const wrapper = await mountPage();
await flushPromises();
// 断言:货代上传阶段 Notice 可勾选;Review/Intake 行无复选框。
expect(wrapper.get('[aria-label="WYC26082301"]').exists()).toBe(true);
expect(wrapper.get('[aria-label="WYC26082302"]').exists()).toBe(true);
expect(wrapper.find('[aria-label="SNRC-30"]').exists()).toBe(false);
// 断言:表格副行展示 客户 · PO · 文件。
expect(wrapper.text()).toContain('PO-100');
expect(wrapper.text()).toContain('PART-A');
expect(wrapper.text()).toContain('PART-B');
expect(wrapper.text()).toContain('WYC26082301.xlsx');
// 断言:点行打开抽屉,逐行明细承载料号(列表不再堆明细)。
await wrapper.get('[data-testid="my-todos-row-WYC26082301"]').trigger('click');
await flushPromises();
expect(document.body.querySelector('[data-testid="my-todos-drawer"]')).not.toBeNull();
const drawer = drawerText();
expect(drawer).toContain('PART-A');
expect(drawer).toContain('PART-A-B');
wrapper.unmount();
});
@@ -152,53 +220,106 @@ describe('ShippingTaskCenterPage notice batch operations', () => {
await wrapper.get('[aria-label="WYC26082301"]').setValue(true);
await wrapper.get('[aria-label="WYC26082302"]').setValue(true);
const toolbar = wrapper.get('[data-testid="shipping-notice-batch-toolbar"]');
const buttons = toolbar.findAll('button');
// 断言:勾选后浮出操作条,三个动作按序对应 download/confirm/rpa。
// 每次 action 后列表会静默重载(表格重挂载),因此逐次重新查询按钮。
const toolbarButtons = () => wrapper
.get('[data-testid="shipping-notice-batch-toolbar"]')
.findAll('button');
const buttons = toolbarButtons();
expect(buttons.length).toBeGreaterThanOrEqual(3);
await buttons[0].trigger('click');
expect(downloadArchive).toHaveBeenCalledWith(['WYC26082301', 'WYC26082302']);
await buttons[1].trigger('click');
await flushPromises();
await toolbarButtons()[1].trigger('click');
await flushPromises();
expect(batchConfirm).toHaveBeenCalledWith(['WYC26082301', 'WYC26082302']);
await buttons[2].trigger('click');
await toolbarButtons()[2].trigger('click');
await flushPromises();
expect(batchRpa).toHaveBeenCalledWith(['WYC26082301', 'WYC26082302']);
wrapper.unmount();
});
it('keeps all five lifecycle stage filters on one wide-screen row', async () => {
it('renders one row of stage tabs covering all plus four actionable stages', async () => {
const wrapper = await mountPage();
await flushPromises();
const track = wrapper.get('[data-testid="my-todos-lifecycle-stage-filter"]');
expect(track.classes()).toContain('xl:grid-cols-5');
// 断言:全部 + 四个可动作阶段;「通知完成」不再是筛选维度。
expect(track.findAll('button')).toHaveLength(5);
expect(track.text()).toContain('货代上传');
expect(track.text()).not.toContain('通知完成');
expect(track.text()).not.toContain('workspace.shippingNotice.myTodos.lifecycleStages.freight_upload');
wrapper.unmount();
});
it('counts a pending review item from its backend stage even without an enterable lifecycle entry', async () => {
listTodos.mockResolvedValueOnce({
items: [{
item_kind: 'review_case',
task_no: '',
review_run_no: 'RUN-1',
review_case_no: 'CASE-1',
ui_state: {
stage: { code: 'order_review', label: '订单复核', index: 2, total: 5 },
lifecycle_entries: [],
},
}],
page: 1,
page_size: 20,
total: 1,
it('shows backend aggregated stage counts instead of current-page counting', async () => {
countTodos.mockResolvedValueOnce({
pending: 13, processing: 0, done: 0, total_pending_badge: 13,
stage_counts: { intake_parse: 2, order_review: 4, fulfillment_prep: 3, freight_upload: 4 },
done_counts: { upload_complete: 0, reject_void: 0 },
});
listTodos.mockResolvedValueOnce({ items: [], page: 1, page_size: 20, total: 0 });
const wrapper = await mountPage();
await flushPromises();
expect(wrapper.get('[data-testid="my-todos-stage-filter-order_review"]').text()).toContain('1');
// 断言:阶段计数来自后端聚合(当前页为空列表也显示全量计数)。
expect(wrapper.get('[data-testid="my-todos-stage-filter-order_review"]').text()).toContain('4');
expect(wrapper.get('[data-testid="my-todos-stage-filter-fulfillment_prep"]').text()).toContain('3');
wrapper.unmount();
});
it('defaults done bucket to the flat done-lines report and exports current filters', async () => {
listDoneLines.mockResolvedValue({
items: [{
task_no: 'SN-DONE-1', business_no: 'BIZ-1', customer_name: 'HYVE CS', customer_code: 'HC001',
order_date: '2026-06-01', line_no: 1, part_number: 'B3-A08AR1', qty: 80,
required_date: '2026-06-15', customer_po_number: '306085', used_qty: null,
open_qty: null, source_order_number: '8301-1', unit_price: 1525.08,
}],
page: 1, page_size: 50, total: 1,
});
const wrapper = await mountPage();
await flushPromises();
await wrapper.get('[data-testid="my-todos-bucket-done"]').trigger('click');
await flushPromises();
// 断言:done 桶默认进入通知完成明细报表,消费 done-lines 接口。
expect(listDoneLines).toHaveBeenCalled();
const table = wrapper.get('[data-testid="done-lines-table"]');
expect(table.text()).toContain('B3-A08AR1');
expect(table.text()).toContain('8301-1');
// 断言:导出按钮把当前筛选交给受控下载。
await wrapper.get('[data-testid="done-lines-export"]').trigger('click');
await flushPromises();
expect(downloadDoneLinesExcel).toHaveBeenCalled();
wrapper.unmount();
});
it('loads reject_void sub tab with terminal_kind filter and badges rows', async () => {
listTodos.mockResolvedValue({
items: [{
id: 41, task_no: 'SN-REJ-1', business_no: 'BIZ-R1', item_kind: 'task',
todo_ref: 'SN-REJ-1', todo_category: 'done',
ui_state: { stage: { code: 'upload_complete', label: '通知完成' }, lifecycle_entries: [] },
}],
page: 1, page_size: 20, total: 1,
});
const wrapper = await mountPage();
await flushPromises();
await wrapper.get('[data-testid="my-todos-bucket-done"]').trigger('click');
await flushPromises();
const subtabs = wrapper.findAll('[data-testid="my-todos-done-subtabs"] button');
await subtabs[1].trigger('click');
await flushPromises();
// 断言:驳回/作废子视图按 terminal_kind 拉任务表,行带终态角标。
expect(listTodos).toHaveBeenCalledWith(expect.objectContaining({
bucket: 'done',
terminal_kind: 'reject_void',
}));
expect(wrapper.get('[data-testid="my-todos-row-BIZ-R1"]').text()).toContain('复核驳回');
wrapper.unmount();
});
});
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,390 @@
<!--
features/workspace/shipping-task-center/ShippingTaskDrawer.vue
用途:任务详情抽屉——分诊决策面板(头部阻断 + 逐行明细 + 文件 + 底部操作)。
依赖:shippingTaskCenterShared(阶段口径)、gateReasonLabel。
逻辑:review/intake/task 三分支迁移自原任务中心右侧入口卡,行为与深链契约不变;
深链/重试只向上 emit,由页面统一执行;阶段目标下拉仍由后端
ui_state.lifecycle_entries 裁决(current/available 才可进)。
-->
<script setup lang="ts">
import { computed, onBeforeUnmount, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { Download, ExternalLink, RefreshCw, X } from 'lucide-vue-next';
import type {
ShippingTaskDetail,
ShippingTaskSummary,
} from '@/features/chat/api/shipping.api';
import {
canOpenIntakeParse,
defaultLifecycleTarget,
lifecycleEntriesOf,
lifecycleEntryFor,
lifecycleEntryIsEnterable,
todoBlockerText,
todoDisplayNo,
type LifecycleStageCode,
type TodoLike,
} from './shippingTaskCenterShared';
const { t, te } = useI18n();
const props = defineProps<{
open: boolean;
item: ShippingTaskSummary | ShippingTaskDetail | null;
loading?: boolean;
chatAgentId: number | null;
/** 重试 STP 进行中(页面持有状态)。 */
stpRetrying?: boolean;
}>();
const emit = defineEmits<{
(event: 'close'): void;
(event: 'open-intake', item: TodoLike): void;
(event: 'open-processing', item: TodoLike, stage: Exclude<LifecycleStageCode, 'intake_parse'>): void;
(event: 'open-chat', item: TodoLike): void;
(event: 'retry-stp', item: TodoLike): void;
}>();
type EnterableStage = Exclude<LifecycleStageCode, 'intake_parse'>;
const stageTarget = ref<EnterableStage>('order_review');
const isReviewItem = computed(() => {
const item = props.item as ShippingTaskSummary | null;
if (!item) return false;
return item.item_kind === 'review_case' || Boolean(item.review_run_no && !item.task_no);
});
const isIntakeItem = computed(() => {
const item = props.item as ShippingTaskSummary | null;
if (!item) return false;
return item.item_kind === 'order_intake'
|| Boolean(item.intake_no && !item.task_no && !item.review_run_no);
});
const displayNo = computed(() => {
if (!props.item) return '—';
if ('task_no' in props.item && props.item.task_no
&& !isReviewItem.value && !isIntakeItem.value) {
return String(props.item.task_no);
}
return todoDisplayNo(props.item as ShippingTaskSummary);
});
const subTitle = computed(() => {
const item = props.item;
if (!item) return '';
const segments = [
String(item.customer_name || '').trim(),
String(item.po_number || '').trim() ? `PO ${String(item.po_number).trim()}` : '',
String(item.source_file_name || '').trim()
|| String(item.artifact_summary?.export_file_name || '').trim(),
].filter(Boolean);
return segments.join(' · ');
});
const stageLabel = computed(() => {
const item = props.item;
if (!item) return '';
const code = String(item.ui_state?.stage?.code || '').trim();
const key = code ? `workspace.shippingNotice.myTodos.lifecycleStages.${code}` : '';
if (key && te(key)) return t(key);
return String(item.ui_state?.stage?.label || '');
});
const blocker = computed(() => (props.item ? todoBlockerText(props.item, t, te) : ''));
const summaryMessage = computed(() => String(
props.item?.ui_state?.summary?.message
|| props.item?.ui_state?.summary?.current_todo
|| '',
));
const stageTargetOptions = computed(() => {
if (!props.item) return [];
return lifecycleEntriesOf(props.item)
.filter((entry) => entry.code !== 'intake_parse')
.map((entry) => ({
code: entry.code as EnterableStage,
disabled: entry.state !== 'current' && entry.state !== 'available',
}));
});
/** 后端仅授权 current/available;目标不可进时主按钮禁用。 */
function canOpenProcessing(stage: EnterableStage | null): boolean {
const item = props.item;
if (!item) return false;
const runNo = String(item.review_run_no || '').trim();
const agentId = Number(item.owner_agent_id || props.chatAgentId || 0);
const target = stage || defaultLifecycleTarget(item);
if (!target) return false;
return Boolean(runNo && agentId && lifecycleEntryIsEnterable(lifecycleEntryFor(item, target)));
}
const canOpenIntake = computed(() => canOpenIntakeParse(props.item, props.chatAgentId));
/** 摘要允许动作里是否含 STP 自动推进重试(与工作台底栏同一契约)。 */
const canRetryStp = computed(() => {
const item = props.item as ShippingTaskSummary | null;
if (!item || item.can_handle === false) return false;
if (!String(item.review_case_no || '').trim()) return false;
const summaryActions = item.ui_state?.summary?.allowed_actions || [];
const actions = [item.ui_state?.actions?.primary, ...(item.ui_state?.actions?.secondary || [])]
.filter(Boolean)
.map((action) => String(action?.code || ''));
return summaryActions.includes('retry_stp_auto_create') || actions.includes('retry_stp_auto_create');
});
const exportFileName = computed(() => String(
props.item?.artifact_summary?.export_file_name || '',
));
const lineRows = computed(() => {
const item = props.item as ShippingTaskSummary | null;
return Array.isArray(item?.notice_line_summary) ? item!.notice_line_summary : [];
});
watch(() => props.item, (item) => {
if (!item) return;
const stage = defaultLifecycleTarget(item);
if (stage) stageTarget.value = stage;
}, { immediate: true });
function onEsc(event: KeyboardEvent) {
if (event.key === 'Escape') emit('close');
}
// Esc 关闭抽屉;打开时挂监听,关闭/卸载时移除,避免监听串扰。
watch(() => props.open, (open) => {
if (open) document.addEventListener('keydown', onEsc);
else document.removeEventListener('keydown', onEsc);
}, { immediate: true });
onBeforeUnmount(() => document.removeEventListener('keydown', onEsc));
</script>
<template>
<Teleport to="body">
<div
v-if="open"
class="fixed inset-0 z-50 flex"
data-testid="my-todos-drawer"
>
<div
class="flex-1 bg-[rgba(23,32,51,0.35)]"
data-testid="my-todos-drawer-scrim"
@click="emit('close')"
/>
<aside class="flex w-[34rem] max-w-[94vw] flex-col bg-surface shadow-2xl">
<div class="border-b border-default px-5 py-4">
<div class="flex items-start justify-between gap-3">
<h3 class="break-all font-mono text-base font-bold text-primary" data-testid="my-todos-drawer-title">
{{ displayNo }}
</h3>
<button
type="button"
class="rounded-lg bg-surface-soft px-2 py-1 text-xs text-secondary hover:bg-surface-soft/70"
:aria-label="$t('workspace.shippingNotice.myTodos.drawer.close')"
data-testid="my-todos-drawer-close"
@click="emit('close')"
>
<X class="h-4 w-4" />
</button>
</div>
<p v-if="subTitle" class="mt-1 text-xs text-muted">{{ subTitle }}</p>
<div class="mt-2 flex flex-wrap items-center gap-2">
<span
v-if="stageLabel"
class="rounded-full bg-brand-50 px-2.5 py-0.5 text-xs font-medium text-brand-800"
data-testid="my-todos-drawer-stage"
>
{{ stageLabel }}
</span>
<span
v-if="isReviewItem"
class="rounded bg-amber-50 px-1.5 py-0.5 text-[10px] text-amber-700"
>{{ $t('workspace.shippingNotice.myTodos.openReview') }}</span>
<span
v-else-if="isIntakeItem"
class="rounded bg-violet-50 px-1.5 py-0.5 text-[10px] text-violet-700"
>{{ $t('workspace.shippingNotice.myTodos.intakeParseBadge') }}</span>
</div>
</div>
<div class="flex-1 overflow-y-auto px-5 py-4">
<div v-if="loading" class="py-16 text-center text-sm text-muted">
{{ $t('workspace.shippingNotice.loading') }}
</div>
<template v-else-if="item">
<div
v-if="blocker"
class="mb-4 rounded-xl border border-red-200 bg-red-50 px-3.5 py-2.5 text-[13px] text-red-700"
data-testid="my-todos-progress-blocker"
>
{{ $t('workspace.shippingNotice.myTodos.progressBlocker', { reason: blocker }) }}
</div>
<p
v-if="stageLabel"
class="mb-2 text-sm font-medium text-primary"
data-testid="my-todos-progress-summary"
>
{{ $t('workspace.shippingNotice.myTodos.progressSummary', { stage: stageLabel }) }}
</p>
<p v-if="summaryMessage" class="text-sm text-secondary">{{ summaryMessage }}</p>
<template v-if="lineRows.length">
<h4 class="mb-2 mt-5 text-[13px] font-bold text-primary">
{{ $t('workspace.shippingNotice.myTodos.drawer.details') }}
</h4>
<div class="overflow-x-auto rounded-xl border border-default">
<table class="w-full border-collapse text-xs" data-testid="my-todos-drawer-lines">
<thead>
<tr class="border-b border-default bg-surface-soft/60 text-left text-muted">
<th class="px-2.5 py-2 font-medium">{{ $t('workspace.shippingNotice.myTodos.drawer.lineTable.lineNo') }}</th>
<th class="px-2.5 py-2 font-medium">{{ $t('workspace.shippingNotice.myTodos.drawer.lineTable.partNumber') }}</th>
<th class="px-2.5 py-2 font-medium">{{ $t('workspace.shippingNotice.myTodos.drawer.lineTable.customerPartNumber') }}</th>
<th class="px-2.5 py-2 font-medium">{{ $t('workspace.shippingNotice.myTodos.drawer.lineTable.reservationId') }}</th>
<th class="px-2.5 py-2 font-medium">{{ $t('workspace.shippingNotice.myTodos.drawer.lineTable.shipmentQty') }}</th>
<th class="px-2.5 py-2 font-medium">{{ $t('workspace.shippingNotice.myTodos.drawer.lineTable.availableQty') }}</th>
<th class="px-2.5 py-2 font-medium">{{ $t('workspace.shippingNotice.myTodos.drawer.lineTable.shortageQty') }}</th>
<th class="px-2.5 py-2 font-medium">{{ $t('workspace.shippingNotice.myTodos.drawer.lineTable.status') }}</th>
</tr>
</thead>
<tbody>
<tr
v-for="line in lineRows"
:key="`${line.line_no}-${line.part_number}`"
class="border-b border-[#f0f3f8]"
>
<td class="px-2.5 py-2 font-mono">{{ line.line_no }}</td>
<td class="px-2.5 py-2 font-mono">{{ line.part_number || '—' }}</td>
<td class="px-2.5 py-2">{{ line.customer_part_number || '—' }}</td>
<td class="px-2.5 py-2 font-mono">{{ line.reservation_id || '—' }}</td>
<td class="px-2.5 py-2 tabular-nums">{{ line.shipment_qty ?? '—' }}</td>
<td class="px-2.5 py-2 tabular-nums">{{ line.available_qty ?? '—' }}</td>
<td
class="px-2.5 py-2 tabular-nums"
:class="Number(line.shortage_qty || 0) > 0 ? 'font-bold text-red-600' : ''"
>
{{ line.shortage_qty ?? '—' }}
</td>
<td class="px-2.5 py-2">{{ line.inventory_status || '—' }}</td>
</tr>
</tbody>
</table>
</div>
</template>
<template v-if="exportFileName">
<h4 class="mb-2 mt-5 text-[13px] font-bold text-primary">
{{ $t('workspace.shippingNotice.myTodos.drawer.files') }}
</h4>
<div class="rounded-xl border border-default px-3 py-2 text-[13px] text-secondary">
<span class="mr-2 rounded bg-brand-50 px-1.5 py-0.5 text-[10px] text-brand-800">Excel</span>
{{ exportFileName }}
</div>
</template>
<p class="mt-5 text-xs text-muted">
{{ $t('workspace.shippingNotice.myTodos.openProcessingHint') }}
</p>
</template>
<div v-else class="py-16 text-center text-sm text-muted">
{{ $t('workspace.shippingNotice.selectCase') }}
</div>
</div>
<div v-if="item && !loading" class="space-y-2.5 border-t border-default px-5 py-4">
<div class="flex flex-wrap gap-2">
<label class="sr-only" for="drawer-stage-target">{{ $t('workspace.shippingNotice.myTodos.lifecycleStages.viewStage') }}</label>
<select
v-if="stageTargetOptions.length"
id="drawer-stage-target"
v-model="stageTarget"
class="input-field max-w-40 text-sm"
data-testid="my-todos-lifecycle-stage-target"
>
<option
v-for="option in stageTargetOptions"
:key="option.code"
:value="option.code"
:disabled="option.disabled"
>
{{ $t(`workspace.shippingNotice.myTodos.lifecycleStages.${option.code}`) }}
</option>
</select>
<button
v-if="canOpenIntake"
type="button"
class="inline-flex items-center gap-1.5 rounded-xl bg-brand-600 px-4 py-2 text-sm font-medium text-white hover:bg-brand-700 disabled:opacity-50"
data-testid="my-todos-open-intake-parse"
@click="emit('open-intake', item)"
>
<ExternalLink class="h-3.5 w-3.5" />
{{ $t('workspace.shippingNotice.myTodos.openIntakeParse') }}
</button>
<button
v-else-if="!isIntakeItem"
type="button"
class="inline-flex items-center gap-1.5 rounded-xl bg-brand-600 px-4 py-2 text-sm font-medium text-white hover:bg-brand-700 disabled:opacity-50"
:disabled="!canOpenProcessing(stageTarget)"
data-testid="my-todos-open-order-processing"
@click="emit('open-processing', item, stageTarget)"
>
<ExternalLink class="h-3.5 w-3.5" />
{{ $t('workspace.shippingNotice.myTodos.openLifecycleWorkbench') }}
</button>
<button
v-else
type="button"
class="inline-flex items-center gap-1.5 rounded-xl bg-brand-600 px-4 py-2 text-sm font-medium text-white hover:bg-brand-700 disabled:opacity-50"
:disabled="!(item.owner_agent_id || chatAgentId)"
data-testid="my-todos-open-intake-conversation"
@click="emit('open-chat', item)"
>
<ExternalLink class="h-3.5 w-3.5" />
{{ $t('workspace.shippingNotice.myTodos.openConversation') }}
</button>
<button
v-if="chatAgentId && !isIntakeItem"
type="button"
class="inline-flex items-center gap-1 rounded-xl border border-default px-3 py-1.5 text-xs font-medium text-secondary hover:bg-surface-soft"
@click="emit('open-chat', item)"
>
<ExternalLink class="h-3.5 w-3.5" />
{{ $t('workspace.shippingNotice.openChat') }}
</button>
</div>
<div class="flex flex-wrap items-center gap-3">
<button
v-if="canRetryStp"
type="button"
class="inline-flex items-center gap-1.5 rounded-xl border border-amber-400 bg-amber-50 px-4 py-2 text-sm font-medium text-amber-950 hover:bg-amber-100 disabled:opacity-50 dark:border-amber-700 dark:bg-amber-950/40 dark:text-amber-100"
:disabled="stpRetrying"
data-testid="my-todos-retry-stp-auto-create"
@click="emit('retry-stp', item)"
>
<RefreshCw class="h-3.5 w-3.5" />
{{ $t('chat.shippingOrderReview.autoProgress.retryStp') }}
</button>
<a
v-if="exportFileName"
class="inline-flex cursor-pointer items-center gap-1 text-xs text-brand-700 hover:underline"
:href="`/api/workspace/shipping-notices/${encodeURIComponent(String(item.business_no || ''))}/export`"
target="_blank"
rel="noopener"
>
<Download class="h-3.5 w-3.5" />
{{ $t('workspace.shippingNotice.myTodos.drawer.exportExcel') }}
</a>
<p
v-if="!canOpenIntake && !canOpenProcessing(stageTarget) && !isIntakeItem"
class="text-xs text-amber-700 dark:text-amber-300"
data-testid="my-todos-open-processing-unavailable"
>
{{ $t('workspace.shippingNotice.myTodos.openProcessingUnavailable') }}
</p>
</div>
</div>
</aside>
</div>
</Teleport>
</template>
@@ -0,0 +1,240 @@
<!--
features/workspace/shipping-task-center/ShippingTaskTable.vue
用途:任务中心紧凑表格(一行一待办):编号/阶段/状态摘要/项次缺口/货代状态。
依赖:shippingTaskCenterShared(编号、阶段、批量可选口径)。
逻辑:行点击向上冒泡选中;复选框仅「货代上传」阶段的正式 Notice 行存在;
勾选 ≥1 后浮出深色批量操作条(低频操作不常驻);分页由父级渲染。
-->
<script setup lang="ts">
import { computed } from 'vue';
import { useI18n } from 'vue-i18n';
import { CheckSquare, Download, Upload, X } from 'lucide-vue-next';
import type { ShippingTaskSummary } from '@/features/chat/api/shipping.api';
import {
isFreightUploadRow,
lifecycleStageCodeOf,
todoBlockerText,
todoDisplayNo,
todoItemKey,
todoLineBrief,
todoSubTitleText,
todoTitleText,
} from './shippingTaskCenterShared';
const { t, te } = useI18n();
const props = defineProps<{
items: ShippingTaskSummary[];
/** 当前选中行主键(抽屉联动)。 */
selectedKey?: string | null;
/** 是否渲染复选框列(仅待处理桶)。 */
selectable?: boolean;
/** 已勾选 business_no 集合。 */
selectedBusinessNos?: string[];
/** 批量动作进行中标记,禁用按钮。 */
batchBusy?: 'download' | 'confirm' | 'rpa' | null;
/** done 桶行统一终态角标(驳回/作废子视图由服务端过滤保证)。 */
terminalBadge?: 'upload_complete' | 'reject_void' | null;
}>();
const emit = defineEmits<{
(event: 'select', item: ShippingTaskSummary): void;
(event: 'toggle', item: ShippingTaskSummary): void;
(event: 'toggle-all'): void;
(event: 'clear-selection'): void;
(event: 'batch', action: 'download' | 'confirm' | 'rpa'): void;
}>();
const selectedSet = computed(() => new Set(props.selectedBusinessNos || []));
const selectableRows = computed(() => props.items.filter((item) => isFreightUploadRow(item)));
const hasSelection = computed(() => (props.selectedBusinessNos?.length || 0) > 0);
const allSelectableChecked = computed(() => (
selectableRows.value.length > 0
&& selectableRows.value.every((item) => selectedSet.value.has(String(item.business_no)))
));
/** 阶段徽章文案:优先本地化阶段名,后端 label 兜底。 */
function stageLabel(item: ShippingTaskSummary): string {
const code = lifecycleStageCodeOf(item);
const key = code ? `workspace.shippingNotice.myTodos.lifecycleStages.${code}` : '';
if (key && te(key)) return t(key);
return String(item.ui_state?.stage?.label || '—');
}
function rowTitle(item: ShippingTaskSummary): string {
return todoTitleText(item);
}
function rowBlocker(item: ShippingTaskSummary): string {
return todoBlockerText(item, t, te);
}
function lineBriefText(item: ShippingTaskSummary): string {
const brief = todoLineBrief(item);
if (!brief.total) return '—';
return `${brief.total} ${t('workspace.shippingNotice.myTodos.table.lineUnit')}`;
}
function onToggleAll(): void {
emit('toggle-all');
}
</script>
<template>
<div class="overflow-hidden rounded-2xl border border-default bg-surface">
<div
v-if="hasSelection"
class="flex flex-wrap items-center gap-2 bg-[#1b2740] px-4 py-2.5 text-sm text-slate-100"
data-testid="shipping-notice-batch-toolbar"
>
<span class="rounded-full bg-brand-600 px-3 py-0.5 text-xs font-semibold">
{{ $t('workspace.shippingNotice.batch.selected', { count: selectedBusinessNos?.length || 0 }) }}
</span>
<button
type="button"
class="rounded-lg border border-white/20 px-2.5 py-1 text-xs hover:bg-white/10 disabled:opacity-50"
:disabled="Boolean(batchBusy)"
@click="emit('batch', 'download')"
>
<Download class="mr-1 inline h-3.5 w-3.5" />
{{ $t('workspace.shippingNotice.batch.download') }}
</button>
<button
type="button"
class="rounded-lg border border-white/20 px-2.5 py-1 text-xs hover:bg-white/10 disabled:opacity-50"
:disabled="Boolean(batchBusy)"
@click="emit('batch', 'confirm')"
>
<CheckSquare class="mr-1 inline h-3.5 w-3.5" />
{{ $t('workspace.shippingNotice.batch.confirm') }}
</button>
<button
type="button"
class="rounded-lg border border-white/20 px-2.5 py-1 text-xs hover:bg-white/10 disabled:opacity-50"
:disabled="Boolean(batchBusy)"
@click="emit('batch', 'rpa')"
>
<Upload class="mr-1 inline h-3.5 w-3.5" />
{{ $t('workspace.shippingNotice.batch.rpa') }}
</button>
<span class="flex-1" />
<button
type="button"
class="rounded-lg px-2.5 py-1 text-xs text-slate-300 hover:text-white"
@click="emit('clear-selection')"
>
<X class="mr-1 inline h-3.5 w-3.5" />
{{ $t('workspace.shippingNotice.batch.clearSelection') }}
</button>
</div>
<div class="overflow-x-auto">
<table class="w-full border-collapse text-sm">
<thead>
<tr class="border-b border-default bg-surface-soft/60 text-left text-xs text-muted">
<th v-if="selectable" class="w-10 px-3 py-2.5">
<input
type="checkbox"
:checked="allSelectableChecked"
:aria-label="$t('workspace.shippingNotice.batch.selectAll')"
@change="onToggleAll"
>
</th>
<th class="px-3 py-2.5 font-medium">{{ $t('workspace.shippingNotice.myTodos.table.no') }}</th>
<th class="w-24 px-3 py-2.5 font-medium">{{ $t('workspace.shippingNotice.myTodos.table.stage') }}</th>
<th class="px-3 py-2.5 font-medium">{{ $t('workspace.shippingNotice.myTodos.table.summary') }}</th>
<th class="w-28 px-3 py-2.5 font-medium">{{ $t('workspace.shippingNotice.myTodos.table.lines') }}</th>
<th class="w-24 px-3 py-2.5 font-medium">{{ $t('workspace.shippingNotice.myTodos.table.freightStatus') }}</th>
</tr>
</thead>
<tbody>
<tr
v-for="item in items"
:key="todoItemKey(item)"
class="cursor-pointer border-b border-[#f0f3f8] transition-colors hover:bg-brand-50/40"
:class="selectedKey === todoItemKey(item) ? 'bg-brand-50/70 dark:bg-brand-950/30' : ''"
:data-testid="`my-todos-row-${todoDisplayNo(item)}`"
@click="emit('select', item)"
>
<td v-if="selectable" class="px-3 py-2.5 align-middle">
<input
v-if="isFreightUploadRow(item)"
type="checkbox"
:checked="selectedSet.has(String(item.business_no))"
:aria-label="String(item.business_no)"
@click.stop
@change="emit('toggle', item)"
>
</td>
<td class="max-w-[22rem] px-3 py-2.5 align-middle">
<div class="flex items-center gap-2">
<span class="truncate font-mono text-[13px] font-semibold text-primary">{{ todoDisplayNo(item) }}</span>
<span
v-if="item.todo_category === 'review' || item.item_kind === 'review_case'"
class="shrink-0 rounded bg-amber-50 px-1.5 py-0.5 text-[10px] text-amber-700"
>
{{ $t('workspace.shippingNotice.myTodos.openReview') }}
</span>
<span
v-else-if="item.todo_category === 'intake_parse' || item.item_kind === 'order_intake'"
class="shrink-0 rounded bg-violet-50 px-1.5 py-0.5 text-[10px] text-violet-700"
>
{{ $t('workspace.shippingNotice.myTodos.intakeParseBadge') }}
</span>
<span
v-else-if="item.can_handle === false"
class="shrink-0 rounded bg-slate-100 px-1.5 py-0.5 text-[10px] text-slate-600"
>
{{ $t('workspace.shippingNotice.todo.adminViewOnlyShort') }}
</span>
<span
v-else-if="terminalBadge === 'upload_complete'"
class="shrink-0 rounded bg-emerald-50 px-1.5 py-0.5 text-[10px] text-emerald-700"
>
{{ $t('workspace.shippingNotice.myTodos.terminal.uploadComplete') }}
</span>
<span
v-else-if="terminalBadge === 'reject_void'"
class="shrink-0 rounded bg-red-50 px-1.5 py-0.5 text-[10px] text-red-700"
>
{{ $t('workspace.shippingNotice.myTodos.terminal.rejectVoid') }}
</span>
</div>
<div class="mt-0.5 truncate text-xs text-muted">{{ todoSubTitleText(item) || '—' }}</div>
</td>
<td class="px-3 py-2.5 align-middle">
<span class="whitespace-nowrap rounded-full bg-brand-50 px-2 py-0.5 text-xs text-brand-800">
{{ stageLabel(item) }}
</span>
</td>
<td class="max-w-[18rem] px-3 py-2.5 align-middle">
<div class="truncate text-[13px] text-secondary">{{ rowTitle(item) }}</div>
<div
v-if="rowBlocker(item)"
class="mt-0.5 truncate text-xs text-red-600"
data-testid="my-todos-row-blocker"
>
{{ rowBlocker(item) }}
</div>
</td>
<td class="px-3 py-2.5 align-middle text-xs">
<template v-if="item.business_no">
<span>{{ lineBriefText(item) }}</span>
<span
v-if="todoLineBrief(item).shortage"
class="ml-1 font-semibold text-red-600"
>
{{ $t('workspace.shippingNotice.myTodos.table.shortage', { count: todoLineBrief(item).shortage }) }}
</span>
</template>
<span v-else class="text-muted">—</span>
</td>
<td class="px-3 py-2.5 align-middle text-xs text-secondary">
{{ item.business_no ? (item.upload_status || '—') : '—' }}
</td>
</tr>
</tbody>
</table>
</div>
</div>
</template>
@@ -0,0 +1,174 @@
/**
* features/workspace/shipping-task-center/shippingTaskCenterShared.ts
* 用途:任务中心列表 / 表格 / 抽屉共用的纯函数与类型(阶段口径、编号、选择)。
* 依赖:chat shipping.api 类型、gateReasonLabel。
* 逻辑:阶段只消费后端 ui_state.lifecycle_entries / ui_state.stage(与页面同口径);
* 本模块不发起请求、不操作路由,供 TaskTable / Drawer / Page 复用。
*/
import type { ShippingTaskDetail, ShippingTaskSummary } from '@/features/chat/api/shipping.api';
import { resolveGateReasonLabel } from '@/features/shipping-progress/gateReasonLabel';
export type LifecycleStageCode = 'intake_parse' | 'order_review' | 'fulfillment_prep'
| 'freight_upload' | 'upload_complete';
/** 五阶段完整序列(抽屉阶段下拉消费后端 entries,仍需全集做过滤)。 */
export const LIFECYCLE_STAGES: LifecycleStageCode[] = [
'intake_parse',
'order_review',
'fulfillment_prep',
'freight_upload',
'upload_complete',
];
/** 阶段筛选 tab 仅覆盖四个可动作阶段;「通知完成」归 done 桶终态。 */
export const ACTIONABLE_TODO_STAGES: Exclude<LifecycleStageCode, 'upload_complete'>[] = [
'intake_parse',
'order_review',
'fulfillment_prep',
'freight_upload',
];
export type TodoLike = ShippingTaskSummary | ShippingTaskDetail;
/**
* 待办列表项稳定主键:复核用 case_no,Intake 用 intake_no,任务用 task_no。
*/
export function todoItemKey(item: ShippingTaskSummary): string {
if (item.item_kind === 'review_case' || item.review_case_no) {
return String(item.todo_ref || item.review_case_no || item.review_run_no || '');
}
if (item.item_kind === 'order_intake' || item.intake_no) {
return String(item.todo_ref || item.intake_no || '');
}
return String(item.todo_ref || item.task_no || '');
}
/**
* 列表展示编号:复核显示 case_no,Intake 显示 intake_no,任务显示业务编号/SN。
*/
export function todoDisplayNo(item: ShippingTaskSummary): string {
if (item.item_kind === 'review_case' || item.review_case_no) {
return String(item.review_case_no || item.review_run_no || item.todo_ref || '—');
}
if (item.item_kind === 'order_intake' || item.intake_no) {
return String(item.intake_no || item.todo_ref || '—');
}
return String(item.business_no || item.task_no || item.todo_ref || '—');
}
/**
* 读取后端已裁决的生命周期入口;缺失即无授权,绝不按 task/case/intake 身份补造入口。
*/
export function lifecycleEntriesOf(item: TodoLike) {
const entries = item.ui_state?.lifecycle_entries;
if (!Array.isArray(entries)) return [];
return entries.filter((entry) => LIFECYCLE_STAGES.includes(entry.code as LifecycleStageCode));
}
/** 当前阶段只取后端标为 current 的入口,必要时回退 ui_state.stage(仅统计口径)。 */
export function lifecycleStageCodeOf(item: TodoLike): LifecycleStageCode | null {
const current = lifecycleEntriesOf(item).find((entry) => entry.state === 'current');
if (current) return current.code as LifecycleStageCode;
// [AUTHORITY] 待人工处理的 Review Case 可能没有可进入工作台的 lifecycle entry,
// 但后端仍会下发 ui_state.stage 作为当前业务阶段;统计与筛选必须保留该阶段。
const stage = String(item.ui_state?.stage?.code || '').trim();
return LIFECYCLE_STAGES.includes(stage as LifecycleStageCode)
? stage as LifecycleStageCode
: null;
}
/** 可进入工作台的业务阶段仅由后端 entry.state 授权。 */
export function lifecycleEntryFor(
item: TodoLike,
stage: Exclude<LifecycleStageCode, 'intake_parse'>,
) {
return lifecycleEntriesOf(item).find((entry) => entry.code === stage) || null;
}
/** 后端仅以 current / available 表示可进入工作台;未知状态一律拒绝深链。 */
export function lifecycleEntryIsEnterable(
entry: ReturnType<typeof lifecycleEntryFor>,
): boolean {
return entry?.state === 'current' || entry?.state === 'available';
}
/** 阶段目标下拉默认值:优先 current,其次 available。 */
export function defaultLifecycleTarget(
item: TodoLike,
): Exclude<LifecycleStageCode, 'intake_parse'> | null {
const current = lifecycleEntriesOf(item).find(
(entry) => entry.code !== 'intake_parse' && entry.state === 'current',
);
const available = lifecycleEntriesOf(item).find(
(entry) => entry.code !== 'intake_parse' && entry.state === 'available',
);
return (current || available)?.code as Exclude<LifecycleStageCode, 'intake_parse'> | undefined || null;
}
/** 接收解析入口只消费后端独立授权 + run/agent 前提,不从阶段名称推导可写权限。 */
export function canOpenIntakeParse(item: TodoLike | null, chatAgentId: number | null): boolean {
if (!item) return false;
const runNo = String(item.review_run_no || '').trim();
const agentId = Number(item.owner_agent_id || chatAgentId || 0);
return Boolean(
runNo
&& agentId
&& item.ui_state?.intake_parse_authorized === true,
);
}
/**
* 行状态摘要标题:后端待办标题优先,逐级回退到阶段标签。
*/
export function todoTitleText(item: ShippingTaskSummary): string {
return String(
item.ui_state?.todo?.title
|| item.ui_state?.summary?.current_todo
|| item.ui_state?.summary?.title
|| item.ui_state?.stage?.label
|| '—',
);
}
/**
* 行阻断原因文本:优先后端 reason.message,其次 Gate 原因码的本地化标签。
* 空串表示当前无阻断(调用方据此决定红色高亮)。
*/
export function todoBlockerText(
item: TodoLike,
t: (key: string, named?: Record<string, unknown>) => string,
te: (key: string) => boolean,
): string {
const reason = item.ui_state?.reason;
const text = String(reason?.message || '').trim();
if (text) return text;
const code = String(reason?.code || '').trim();
if (!code) return '';
return resolveGateReasonLabel(code, { t, te });
}
/** 表格副行:客户 · PO · 源文件/导出文件,缺省段自动跳过。 */
export function todoSubTitleText(item: ShippingTaskSummary): string {
const segments = [
String(item.customer_name || '').trim(),
String(item.po_number || '').trim() ? `PO ${String(item.po_number).trim()}` : '',
String(item.source_file_name || '').trim()
|| String(item.artifact_summary?.export_file_name || '').trim(),
].filter(Boolean);
return segments.join(' · ');
}
/** 项次/缺口摘要:total 项 + 缺 n(缺口>0 的行数)。 */
export function todoLineBrief(item: ShippingTaskSummary): { total: number; shortage: number } {
const lines = Array.isArray(item.notice_line_summary) ? item.notice_line_summary : [];
const shortage = lines.filter((line) => Number(line.shortage_qty || 0) > 0).length;
return { total: lines.length, shortage };
}
/**
* 批量可选行:正式 Notice 且处于货代上传阶段(业务约束:批量操作仅该阶段可用)。
*/
export function isFreightUploadRow(item: ShippingTaskSummary): boolean {
return Boolean(String(item.business_no || '').trim())
&& lifecycleStageCodeOf(item) === 'freight_upload';
}