Merge branch 'dev' into order-delivery-reply

# Conflicts:
#	.env.shared
#	backend/app/api/chat.py
#	backend/app/core/config/settings.py
#	backend/app/models/user.py
#	backend/app/services/admin/permission_service.py
#	docs/demand.md
#	frontend/src/app/router/routes/workspace.routes.ts
#	frontend/src/features/admin/modules/users/components/UserFormModal.vue
#	frontend/src/features/admin/modules/users/composables/useUsersAdmin.ts
#	frontend/src/features/admin/types/user.types.ts
#	frontend/src/features/auth/stores/auth.store.ts
#	frontend/src/features/user/views/UserProfilePage.vue
#	frontend/src/locales/en/admin.json
#	frontend/src/locales/en/errors.json
#	frontend/src/locales/th/admin.json
#	frontend/src/locales/th/errors.json
#	frontend/src/locales/zh-CN/admin.json
#	frontend/src/locales/zh-CN/errors.json
#	frontend/src/locales/zh-TW/admin.json
#	frontend/src/locales/zh-TW/errors.json
#	frontend/src/shared/utils/auth.ts
This commit is contained in:
HTEWJ\26070045 committed 2026-09-22 10:37:59 +08:00
commit 616034a4cd
541 files changed
+43805 -14767

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,
@@ -1,8 +1,9 @@
/**
* features/workspace/api/voucherCheck.api.ts
* 用途:工作台立账凭证检核任务列表、批次明细、企微发送记录与强制重检 API 客户端。
* 用途:工作台立账凭证检核任务列表、最近一次检核、批次明细、企微发送记录、通知配置与强制重检 API 客户端。
* 依赖:@/shared/api/client、getAuthHeaders。
* 逻辑:AccountingVoucherCheckView / DetailView 调用;对应 /api/workspace/accounting-voucher-check/* 与排程 Excel 下载。
* 逻辑:AccountingVoucherCheckView / DetailView / VoucherCheckNotifyConfigPanel 调用;
* 对应 /api/workspace/accounting-voucher-check/* 与排程 Excel 下载。
*/
import { requestJson } from '@/shared/api/client';
import { getAuthHeaders } from '@/shared/utils/auth';
@@ -71,8 +72,45 @@ export interface VoucherCheckForceRunResponse {
status: string;
}
export interface VoucherCheckLatestStep {
step: string;
label?: string | null;
processed_count: number;
}
export interface VoucherCheckLatestRun {
schedule_run_id: number | null;
engine_run_id?: number | null;
run_no: string;
period_month: string | null;
mode: string;
status: string;
progress_percent: number;
subject_count: number;
archived_file_count: number;
missing_file_count: number;
missing_invoice_count: number;
processed_count: number;
started_at?: string | null;
finished_at?: string | null;
error_message?: string | null;
current_step?: VoucherCheckLatestStep | null;
}
/**
* 读取最近一次立账凭证检核(含排队/执行中),不跟列表 period/status。
* @returns 无任何批次时为 null
*/
export function getLatestVoucherCheckRun() {
return requestJson<VoucherCheckLatestRun | null>(
'/api/workspace/accounting-voucher-check/runs/latest',
{ headers: getAuthHeaders() },
);
}
/**
* 分页查询检核任务列表。
* @param params.period - YYYY 表示该年全部月份,YYYY-MM 表示单月
*/
export function listVoucherCheckRuns(params: {
period?: string;
@@ -136,6 +174,7 @@ export interface VoucherCheckNotificationsResponse {
/**
* 分页查询企微缺件汇总发送记录。
* @param params.period - YYYY 表示该年全部月份,YYYY-MM 表示单月
*/
export function listVoucherCheckNotifications(params?: {
period?: string;
@@ -184,6 +223,60 @@ export async function downloadVoucherCheckExcel(scheduleRunId: number, filename?
URL.revokeObjectURL(url);
}
export interface VoucherCheckNotifyUser {
id: number;
username: string;
real_name?: string | null;
employee_id?: string | null;
department?: string | null;
wecom_bound: boolean;
}
export interface VoucherCheckNotifyRule {
code: string;
name: string;
type_folder: string;
user_ids: number[];
}
export interface VoucherCheckNotifyConfig {
profile_code: string;
rules: VoucherCheckNotifyRule[];
users: VoucherCheckNotifyUser[];
updated_at?: string | null;
updated_by?: number | null;
}
/**
* 读取按文件类型的企微接收人(仅平台管理员)。
*/
export function getVoucherCheckNotifyConfig(profileCode?: string) {
const q = new URLSearchParams();
if (profileCode) q.set('profile_code', profileCode);
const qs = q.toString();
return requestJson<VoucherCheckNotifyConfig>(
`/api/workspace/accounting-voucher-check/notify-config${qs ? `?${qs}` : ''}`,
{ headers: getAuthHeaders() },
);
}
/**
* 保存按文件类型的企微接收人(仅平台管理员)。
*/
export function saveVoucherCheckNotifyConfig(payload: {
profile_code?: string;
recipients: Record<string, number[]>;
}) {
return requestJson<VoucherCheckNotifyConfig>(
'/api/workspace/accounting-voucher-check/notify-config',
{
method: 'PUT',
headers: { ...getAuthHeaders(), 'Content-Type': 'application/json' },
body: JSON.stringify(payload),
},
);
}
/**
* 强制重检上一个自然月(不走增量跳过)。
*/
@@ -1,23 +1,21 @@
<script setup lang="ts">
/**
* features/workspace/components/WorkspaceSidebar.vue
* 工作台左侧导航:子路由链接、货代/合同付款二级菜单、关联服务入口、返回聊天与退出登录。
* 依赖:WORKSPACE_PATHS、workspace.context、ExternalSystemLinks、auth.store、contract-payment 权限常量。
* 逻辑:底部关联服务复用 ws-nav-btn,与返回聊天/退出登录对齐;合同付款菜单仅在具备 contract_payment.access 时展示。
* 工作台左侧导航:子路由链接、货代二级菜单、关联服务入口、返回聊天与退出登录。
* 依赖:WORKSPACE_PATHS、workspace.context、ExternalSystemLinks。
* 逻辑:底部关联服务复用 ws-nav-btn,与返回聊天/退出登录对齐。合同付款、立账凭证已迁入 Chat Agent,不再在此展示。
* 矮屏时中间导航独立滚动,底部返回聊天/退出登录始终留在视口内。
*/
import { computed, inject, onBeforeUnmount, onMounted, ref, watch } from 'vue';
import { useRoute } from 'vue-router';
import {
LayoutGrid, Bot, FileText, User, LogOut, Edit, Megaphone, Clock, Package, PanelLeftClose, PanelLeftOpen, ClipboardCheck, CalendarClock,
LayoutGrid, Bot, FileText, User, LogOut, Edit, Megaphone, Clock, Package, PanelLeftClose, PanelLeftOpen,
ChevronDown, ChevronRight, ContactRound, Inbox, FileDown,
} from 'lucide-vue-next';
import { WORKSPACE_PATHS } from '../constants/routes';
import { WORKSPACE_KEY } from '../composables/workspace.context';
import { useShippingTodoBadge } from '../composables/useShippingTodoBadge';
import { ExternalSystemLinks } from '@/features/sso';
import { useAuthStore } from '@/features/auth/stores/auth.store';
import { CONTRACT_PAYMENT_ACCESS_PERMISSION } from '@/features/contract-payment/constants';
const props = defineProps<{
collapsed?: boolean;
@@ -27,15 +25,7 @@ const ws = inject(WORKSPACE_KEY)! as any;
const route = useRoute();
const shippingRouteNames = ['workspace-shipping-customers', 'workspace-shipping-tasks', 'workspace-shipping-my-tasks'] as const;
const shippingExpanded = ref(false);
const contractPaymentRouteNames = ['workspace-contract-payment', 'workspace-contract-payment-review', 'workspace-contract-payment-weekly-batches'] as const;
const contractPaymentExpanded = ref(false);
const isAdmin = computed(() => String(ws.currentUser?.role || '').trim().toLowerCase() === 'admin');
const auth = useAuthStore();
/**
* 当前用户是否可看见并进入合同付款预警工作台。
* 核心逻辑:读取登录态 feature_permissions.contract_payment.access;admin 默认 true,普通用户需显式授予。
*/
const canAccessContractPayment = computed(() => auth.hasFeaturePermission(CONTRACT_PAYMENT_ACCESS_PERMISSION));
const { pendingBadge, startShippingTodoBadgePolling, stopShippingTodoBadgePolling } = useShippingTodoBadge();
const primaryLinkItems = [
@@ -46,7 +36,6 @@ const primaryLinkItems = [
] as const;
const secondaryLinkItems = [
{ path: WORKSPACE_PATHS.accountingVoucherCheck, labelKey: 'workspace.nav.accountingVoucherCheck', icon: ClipboardCheck, match: ['workspace-accounting-voucher-check', 'workspace-accounting-voucher-check-detail'] },
{ path: WORKSPACE_PATHS.feedback, labelKey: 'workspace.nav.feedback', icon: Edit, match: ['workspace-feedback'] },
{ path: WORKSPACE_PATHS.updates, labelKey: 'workspace.nav.updates', icon: Megaphone, match: ['workspace-updates'] },
] as const;
@@ -61,16 +50,13 @@ function isActive(match: readonly string[]) {
return match.includes(String(route.name || ''));
}
/** 当前路由进入货代或合同付款子页面时自动展开对应一级菜单,保证激活项可见。 */
/** 当前路由进入货代子页面时自动展开对应一级菜单,保证激活项可见。 */
watch(
() => route.name,
(routeName) => {
if (shippingRouteNames.includes(String(routeName || '') as typeof shippingRouteNames[number])) {
shippingExpanded.value = true;
}
if (contractPaymentRouteNames.includes(String(routeName || '') as typeof contractPaymentRouteNames[number])) {
contractPaymentExpanded.value = true;
}
},
{ immediate: true },
);
@@ -84,15 +70,6 @@ const toggleShippingMenu = (): void => {
shippingExpanded.value = !shippingExpanded.value;
};
/** 展开或收起合同付款预警目录;侧栏折叠时图标直接进入合同台账。 */
const toggleContractPaymentMenu = (): void => {
if (props.collapsed) {
void ws.router.push(WORKSPACE_PATHS.contractPayment);
return;
}
contractPaymentExpanded.value = !contractPaymentExpanded.value;
};
onMounted(() => {
startShippingTodoBadgePolling();
});
@@ -199,48 +176,6 @@ onBeforeUnmount(() => {
</RouterLink>
</div>
</div>
<div v-if="canAccessContractPayment">
<button
type="button"
class="ws-nav-btn w-full"
:class="[
{ 'ws-nav-btn--active': isActive(contractPaymentRouteNames) },
collapsed ? 'justify-center px-0' : '',
]"
:title="$t('workspace.nav.contractPayment')"
@click="toggleContractPaymentMenu"
>
<CalendarClock class="h-[18px] w-[18px]" />
<span v-if="!collapsed" class="flex-1">{{ $t('workspace.nav.contractPayment') }}</span>
<component v-if="!collapsed" :is="contractPaymentExpanded ? ChevronDown : ChevronRight" class="h-4 w-4" />
</button>
<div v-if="!collapsed && contractPaymentExpanded" class="mt-1 space-y-1 pl-5">
<RouterLink
:to="WORKSPACE_PATHS.contractPayment"
class="ws-nav-btn py-2.5 text-[13px]"
:class="{ 'ws-nav-btn--active': isActive(['workspace-contract-payment']) }"
>
<CalendarClock class="h-4 w-4" />
<span>{{ $t('workspace.nav.contractPaymentLedger') }}</span>
</RouterLink>
<RouterLink
:to="WORKSPACE_PATHS.contractPaymentReview"
class="ws-nav-btn py-2.5 text-[13px]"
:class="{ 'ws-nav-btn--active': isActive(['workspace-contract-payment-review']) }"
>
<ClipboardCheck class="h-4 w-4" />
<span>{{ $t('workspace.nav.contractPaymentReview') }}</span>
</RouterLink>
<RouterLink
:to="WORKSPACE_PATHS.contractPaymentWeeklyBatches"
class="ws-nav-btn py-2.5 text-[13px]"
:class="{ 'ws-nav-btn--active': isActive(['workspace-contract-payment-weekly-batches']) }"
>
<Inbox class="h-4 w-4" />
<span>{{ $t('workspace.nav.contractPaymentWeeklyBatches') }}</span>
</RouterLink>
</div>
</div>
<RouterLink
v-for="item in secondaryLinkItems"
:key="item.path"
@@ -1,7 +1,8 @@
/**
* features/workspace/constants/routes.ts
* 工作台子路由 path 常量,以及旧 ?view= 查询参数到新 path 的映射。
* 立账凭证批次明细:accountingVoucherCheckDetail(scheduleRunId)。
* 立账凭证路径仍保留,供旧书签落到 Chat 重定向页。
* 合同付款路径仍保留,供旧书签落到 Chat 重定向页。
*/
export const WORKSPACE_PATHS = {
root: '/workspace',
@@ -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,400 @@
<!--
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 : [];
});
/**
* 数量/缺口展示值:后端 Numeric(24,8) 透出形如 "24.00000000",
* 统一转 number 去尾零(24.00000000→24、2.50000000→2.5),缺失保持 —。
*/
function formatQty(value: unknown): string {
if (value === null || value === undefined || value === '') return '—';
const num = Number(value);
return Number.isFinite(num) ? String(num) : String(value);
}
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-[52rem] 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="whitespace-nowrap px-2.5 py-2 font-medium">{{ $t('workspace.shippingNotice.myTodos.drawer.lineTable.lineNo') }}</th>
<th class="whitespace-nowrap px-2.5 py-2 font-medium">{{ $t('workspace.shippingNotice.myTodos.drawer.lineTable.partNumber') }}</th>
<th class="whitespace-nowrap px-2.5 py-2 font-medium">{{ $t('workspace.shippingNotice.myTodos.drawer.lineTable.customerPartNumber') }}</th>
<th class="whitespace-nowrap px-2.5 py-2 font-medium">{{ $t('workspace.shippingNotice.myTodos.drawer.lineTable.reservationId') }}</th>
<th class="whitespace-nowrap px-2.5 py-2 font-medium">{{ $t('workspace.shippingNotice.myTodos.drawer.lineTable.shipmentQty') }}</th>
<th class="whitespace-nowrap px-2.5 py-2 font-medium">{{ $t('workspace.shippingNotice.myTodos.drawer.lineTable.availableQty') }}</th>
<th class="whitespace-nowrap px-2.5 py-2 font-medium">{{ $t('workspace.shippingNotice.myTodos.drawer.lineTable.shortageQty') }}</th>
<th class="whitespace-nowrap 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="whitespace-nowrap px-2.5 py-2 font-mono">{{ line.part_number || '—' }}</td>
<td class="whitespace-nowrap px-2.5 py-2">{{ line.customer_part_number || '—' }}</td>
<td class="whitespace-nowrap px-2.5 py-2 font-mono">{{ line.reservation_id || '—' }}</td>
<td class="whitespace-nowrap px-2.5 py-2 tabular-nums">{{ formatQty(line.shipment_qty) }}</td>
<td class="whitespace-nowrap px-2.5 py-2 tabular-nums">{{ formatQty(line.available_qty) }}</td>
<td
class="whitespace-nowrap px-2.5 py-2 tabular-nums"
:class="Number(line.shortage_qty || 0) > 0 ? 'font-bold text-red-600' : ''"
>
{{ formatQty(line.shortage_qty) }}
</td>
<td class="whitespace-nowrap 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>
@@ -1,11 +1,15 @@
/**
* features/workspace/shipping-task-center/shippingTaskCenterPolling.spec.ts
* 用途:锁定任务中心自动轮询的边界,避免人工待处理任务被误判为持续处理中。
* 依赖:isShippingTodoListItemInProgress。
* 逻辑:只有后端明确的进行中状态继续轮询;复核草稿、失败和完成任务停止轮询。
* 依赖:isShippingTodoListItemInProgress、resolveTodoCenterPollIntervalMs。
* 逻辑:只有系统 running 继续高频轮询;复核草稿、失败和完成停止;人工等待 30s。
*/
import { describe, expect, it } from 'vitest';
import { isShippingTodoListItemInProgress } from './shippingTaskCenterPolling';
import {
HUMAN_WAIT_POLL_MS,
isShippingTodoListItemInProgress,
resolveTodoCenterPollIntervalMs,
} from './shippingTaskCenterPolling';
describe('isShippingTodoListItemInProgress', () => {
it('does not poll a review case that is waiting for human editing', () => {
@@ -17,6 +21,32 @@ describe('isShippingTodoListItemInProgress', () => {
} as never)).toBe(false);
});
it('does not poll waiting_review or needs_action as system running', () => {
expect(isShippingTodoListItemInProgress({
item_kind: 'task',
task_no: 'OT-1',
shipping_processing_status: 'waiting_review',
} as never)).toBe(false);
expect(isShippingTodoListItemInProgress({
item_kind: 'task',
task_no: 'OT-2',
shipping_processing_status: 'needs_action',
} as never)).toBe(false);
expect(isShippingTodoListItemInProgress({
item_kind: 'task',
task_no: 'OT-3',
shipping_processing_status: 'blocked',
} as never)).toBe(false);
});
it('does not treat a non-complete lifecycle stage as running', () => {
expect(isShippingTodoListItemInProgress({
item_kind: 'task',
task_no: 'OT-STAGE',
ui_state: { stage: { code: 'order_review', label: '订单复核', index: 1, total: 5 } },
} as never)).toBe(false);
});
it('continues polling a review case with an explicit processing status', () => {
expect(isShippingTodoListItemInProgress({
item_kind: 'review_case',
@@ -26,4 +56,47 @@ describe('isShippingTodoListItemInProgress', () => {
review_run_no: 'RUN-1',
} as never)).toBe(true);
});
it('continues polling queued automating or running execution', () => {
expect(isShippingTodoListItemInProgress({
item_kind: 'task',
task_no: 'OT-Q',
shipping_processing_status: 'queued',
} as never)).toBe(true);
expect(isShippingTodoListItemInProgress({
item_kind: 'task',
task_no: 'OT-A',
shipping_processing_status: 'automating',
} as never)).toBe(true);
expect(isShippingTodoListItemInProgress({
item_kind: 'task',
task_no: 'OT-E',
ui_state: { process_gate: { status: 'active' } },
} as never)).toBe(true);
expect(isShippingTodoListItemInProgress({
item_kind: 'task',
task_no: 'OT-U',
user_status: 'running',
} as never)).toBe(true);
});
});
describe('resolveTodoCenterPollIntervalMs', () => {
it('reuses batch intervals while system work is running', () => {
expect(resolveTodoCenterPollIntervalMs({
hasRunning: true, hasHumanWait: false, elapsedMs: 0, visibility: 'visible', failureCount: 0,
})).toBe(2000);
expect(resolveTodoCenterPollIntervalMs({
hasRunning: true, hasHumanWait: false, elapsedMs: 15000, visibility: 'visible', failureCount: 0,
})).toBe(5000);
});
it('uses 30s for human wait and stops when idle', () => {
expect(resolveTodoCenterPollIntervalMs({
hasRunning: false, hasHumanWait: true, elapsedMs: 0, visibility: 'visible', failureCount: 0,
})).toBe(HUMAN_WAIT_POLL_MS);
expect(resolveTodoCenterPollIntervalMs({
hasRunning: false, hasHumanWait: false, elapsedMs: 0, visibility: 'visible', failureCount: 0,
})).toBeNull();
});
});
@@ -1,18 +1,20 @@
/**
* features/workspace/shipping-task-center/shippingTaskCenterPolling.ts
* 用途:任务中心列表项是否仍需前台轮询(纯函数,供页面与单测共用)。
* 依赖:ShippingTaskSummary、shippingProcessingFulfillment 状态集合。
* 逻辑:ShippingTaskCenterPage 用本函数决定 poll;Intake created/queued/parsing 必须轮询,
* parse_failed 停止;review_case 持续轮询;OT/Notice 走统一投影状态。
* 用途:任务中心列表项是否系统在跑、以及待办页轮询间隔(纯函数)。
* 依赖:ShippingTaskSummary、useShippingNoticeWorkflow 间隔函数。
* 逻辑:ShippingTaskCenterPage 用本模块决定 poll;仅 queued/processing/automating/running
* 或 Execution active/waiting_external 算系统在跑;人工等待走 30s;间隔复用批次函数。
*/
import type { ShippingTaskSummary } from '@/features/chat/api/shipping.api';
import {
IN_PROGRESS_PROCESSING_STATUSES,
TERMINAL_PROCESSING_STATUSES,
} from '@/features/chat/shipping/shippingProcessingFulfillment';
resolveProcessingPollBackoffMs,
resolveProcessingPollIntervalMs,
type ProcessingPollContext,
} from '@/features/chat/shipping/useShippingNoticeWorkflow';
import { TERMINAL_PROCESSING_STATUSES } from '@/features/chat/shipping/shippingProcessingFulfillment';
/** 历史轮询状态集合;正常任务中心优先消费统一 ui_state。 */
/** 历史轮询状态集合;正常任务中心不再用它判定系统处理中。 */
export const IN_PROGRESS_PROCESS = new Set([
'parsing',
'parsed',
@@ -26,41 +28,78 @@ export const IN_PROGRESS_PROCESS = new Set([
'pending_void',
]);
/** Intake 仍在解析、必须轮询的状态。 */
/** Intake 仍在解析、必须高频轮询的状态。 */
export const INTAKE_POLLING_PARSE_STATUSES = new Set([
'created',
'queued',
'parsing',
]);
/** 系统正在自动跑的统一 processing status;不含人工等待。 */
export const SYSTEM_RUNNING_PROCESSING_STATUSES = new Set([
'queued',
'processing',
'automating',
'running',
]);
/** Execution.status 中表示系统仍在推进。 */
const RUNNING_EXECUTION_STATUSES = new Set([
'active',
'waiting_external',
]);
/** 仅人工等待时的待办轮询间隔,与批次中心后台档一致。 */
export const HUMAN_WAIT_POLL_MS = 30000;
/**
* 判断列表项是否应触发轮询刷新。
* 核心逻辑:review_case 持续轮询;order_intake 仅 created/queued/parsing;
* 其余优先 shipping_processing_status,再按统一 ui_state.stage;
* 不复用 WorkflowItem lifecycle。
* 判断列表项是否仍有系统在自动跑,从而需要高频轮询。
* 核心逻辑:Intake created/queued/parsing;其余只认 running 投影
* (shipping_processing_status / user_status / Execution active),
* 不把 waiting_review / needs_action / blocked / 阶段码当成处理中。
* @param item - 我的待办列表项
* @returns 是否需要继续轮询
* @returns 是否系统处理中
*/
export function isShippingTodoListItemInProgress(item: ShippingTaskSummary): boolean {
if (item.item_kind === 'review_case' || (item.review_run_no && !item.task_no)) {
const unified = String(item.shipping_processing_status || '').trim().toLowerCase();
if (unified) {
if (TERMINAL_PROCESSING_STATUSES.has(unified)) return false;
return IN_PROGRESS_PROCESSING_STATUSES.has(unified);
}
return false;
}
if (item.item_kind === 'order_intake') {
const intakeStatus = String(
item.intake_parse_status || '',
).trim().toLowerCase();
if (item.item_kind === 'order_intake' || (item.intake_no && !item.task_no && !item.review_run_no)) {
const intakeStatus = String(item.intake_parse_status || '').trim().toLowerCase();
return INTAKE_POLLING_PARSE_STATUSES.has(intakeStatus);
}
const unified = String(item.shipping_processing_status || '').trim().toLowerCase();
if (unified) {
if (TERMINAL_PROCESSING_STATUSES.has(unified)) return false;
return IN_PROGRESS_PROCESSING_STATUSES.has(unified);
return SYSTEM_RUNNING_PROCESSING_STATUSES.has(unified);
}
const stage = String(item.ui_state?.stage?.code || '').trim();
return Boolean(stage) && stage !== 'upload_complete';
const userStatus = String(
(item as { user_status?: string | null }).user_status
|| (item.ui_state as { user_status?: string; status?: string } | undefined)?.user_status
|| (item.ui_state as { status?: string } | undefined)?.status
|| '',
).trim().toLowerCase();
if (userStatus === 'running') return true;
const executionStatus = String(item.ui_state?.process_gate?.status || '').trim().toLowerCase();
return RUNNING_EXECUTION_STATUSES.has(executionStatus);
}
/**
* 待办页轮询间隔:系统在跑复用批次函数;仅人工等待 30s;否则停。
*/
export function resolveTodoCenterPollIntervalMs(context: {
hasRunning: boolean;
hasHumanWait: boolean;
elapsedMs: number;
visibility: ProcessingPollContext['visibility'];
failureCount: number;
}): number | null {
if (context.hasRunning) {
return resolveProcessingPollIntervalMs({
elapsedMs: context.elapsedMs,
visibility: context.visibility,
hasProcessing: true,
failureCount: context.failureCount,
});
}
if (!context.hasHumanWait) return null;
if (context.failureCount > 0) return resolveProcessingPollBackoffMs(context.failureCount);
return HUMAN_WAIT_POLL_MS;
}
@@ -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';
}
@@ -24,7 +24,6 @@ export type WorkspaceSidebarItem =
| 'schedule_runs'
| 'receipt_reports'
| 'shipping_notice'
| 'contract_payment'
| 'history';
export interface WorkspaceAgent {
@@ -1,6 +1,6 @@
/**
* features/workspace/utils/voucherCheck.display.ts
* 用途:立账凭证检核列表与明细页共用的状态文案、缺件列表、缺件数、缺失占比与企微发送状态展示。
* 用途:立账凭证检核列表、最近一次检核卡片与明细页共用的状态/模式/步骤文案。
* 依赖:vue-i18n 的 t()。
* 逻辑:AccountingVoucherCheckView / AccountingVoucherCheckDetailView 调用。
*/
@@ -18,9 +18,37 @@ export function voucherCheckStatusLabel(t: (key: string) => string, value: strin
if (value === 'technical_error' || value === 'technical_failed') return t('workspace.voucherCheck.statusTechError');
if (value === 'failed') return t('workspace.voucherCheck.statusTechError');
if (value === 'pending') return t('workspace.voucherCheck.statusPending');
if (value === 'queued') return t('workspace.voucherCheck.statusQueued');
if (value === 'running') return t('workspace.voucherCheck.statusRunning');
return value || '-';
}
/**
* 将批次执行模式映射为工作台文案。
* @param t - i18n 翻译函数
* @param value - incremental / force_all / single
*/
export function voucherCheckModeLabel(t: (key: string) => string, value: string): string {
if (value === 'force_all') return t('workspace.voucherCheck.modeForceAll');
if (value === 'single') return t('workspace.voucherCheck.modeSingle');
return t('workspace.voucherCheck.modeIncremental');
}
/**
* 将 runner 步骤码映射为工作台当前步骤文案。
* @param t - i18n 翻译函数
* @param step - current_step.step
*/
export function voucherCheckStepLabel(t: (key: string) => string, step?: string | null): string {
if (step === 'queued') return t('workspace.voucherCheck.stepQueued');
if (step === 'fetch_erp') return t('workspace.voucherCheck.stepFetchErp');
if (step === 'scan_dms') return t('workspace.voucherCheck.stepScanDms');
if (step === 'persist') return t('workspace.voucherCheck.stepPersist');
if (step === 'notify') return t('workspace.voucherCheck.stepNotify');
if (step === 'done') return t('workspace.voucherCheck.stepDone');
return step || '-';
}
/**
* 将企微汇总发送状态码映射为工作台文案。
* @param t - i18n 翻译函数
@@ -3,7 +3,8 @@
* features/workspace/views/AccountingVoucherCheckDetailView.vue
* 用途:立账凭证检核批次明细独立页,支持按 invoice 或按文件类型汇总。
* 依赖:voucherCheck.api、PaginationBar、vue-router、vue-i18n、useMessage、voucherCheck.display。
* 逻辑:路由 /workspace/accounting-voucher-check/runs/:runId;标题下用下划线 Tab 切换汇总维度;状态筛选仅在按 invoice 时出现。
* 逻辑:独立路由或 Chat 嵌入;标题下用下划线 Tab 切换汇总维度;状态筛选仅在按 invoice 时出现。
* Chat 嵌入时 runId / runNo 由父级传入,返回列表通过 close 事件。
*/
import { computed, onMounted, ref, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
@@ -24,6 +25,20 @@ import {
voucherCheckStatusLabel,
} from '../utils/voucherCheck.display';
const props = withDefaults(defineProps<{
embedded?: boolean;
runId?: number;
runNo?: string | null;
}>(), {
embedded: false,
runId: 0,
runNo: null,
});
const emit = defineEmits<{
close: [];
}>();
const { t } = useI18n();
const msg = useMessage();
const route = useRoute();
@@ -40,12 +55,17 @@ const runNo = ref('');
const viewMode = ref<'invoice' | 'fileType'>('invoice');
const scheduleRunId = computed(() => {
if (props.embedded) {
const id = Number(props.runId);
return Number.isInteger(id) && id > 0 ? id : 0;
}
const raw = route.params.runId;
const id = Number(Array.isArray(raw) ? raw[0] : raw);
return Number.isFinite(id) && id > 0 ? id : 0;
});
const titleRunId = computed(() => {
if (props.embedded && props.runNo) return props.runNo;
const q = route.query.runNo;
if (typeof q === 'string' && q.trim()) return q.trim();
return runNo.value || String(scheduleRunId.value || '');
@@ -111,6 +131,10 @@ function setViewMode(mode: 'invoice' | 'fileType') {
* 返回立账凭证检核任务列表。
*/
function backToList() {
if (props.embedded) {
emit('close');
return;
}
void router.push(WORKSPACE_PATHS.accountingVoucherCheck);
}
@@ -1,28 +1,50 @@
<script setup lang="ts">
/**
* features/workspace/views/AccountingVoucherCheckView.vue
* 用途:立账凭证检核任务列表——按资料所属期间查看批次统计。
* 依赖:voucherCheck.api、vue-i18n、useMessage、DeleteConfirmDialog、PaginationBar、formatLocalDateTime、voucherCheck.display。
* 逻辑:路由 /workspace/accounting-voucher-check;Tab 切换检核任务与企微发送记录;查看详情进入独立明细页;企微 ?run_id= 重定向到明细路由。
* 用途:立账凭证检核任务列表——按资料所属期间(年 + 月)查看批次统计,并展示最近一次检核。
* 依赖:voucherCheck.api、vue-i18n、useMessage、DeleteConfirmDialog、PaginationBar、formatLocalDateTime、voucherCheck.display、auth。
* Chat 嵌入时由 VoucherCheckChatPanel 传入 embedded / activeTab。
* 逻辑:独立路由或 Chat 嵌入;进页默认上一个自然月;「最近一次检核」不跟筛选;强制重检仅 admin,进度在本卡轮询。
* 终态用矮指标格;排队/执行中才展开进度条与当前步骤。Chat 嵌入时隐藏页头与内层 Tab。
*/
import { computed, onMounted, onUnmounted, ref } from 'vue';
import { computed, onMounted, onUnmounted, ref, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n';
import { Download, Loader2, RefreshCw, RotateCcw, Search } from 'lucide-vue-next';
import { ChevronDown, Download, Loader2, RotateCcw, Search } from 'lucide-vue-next';
import DeleteConfirmDialog from '@/shared/components/DeleteConfirmDialog.vue';
import PaginationBar from '@/shared/components/PaginationBar.vue';
import { useMessage } from '@/shared/composables/useMessage';
import { getStoredAuthUser } from '@/shared/utils/auth';
import { formatLocalDateTime } from '@/shared/utils/dateTime';
import { WORKSPACE_PATHS } from '../constants/routes';
import {
downloadVoucherCheckExcel,
getLatestVoucherCheckRun,
listVoucherCheckNotifications,
listVoucherCheckRuns,
triggerVoucherCheckForceAll,
type VoucherCheckLatestRun,
type VoucherCheckNotificationItem,
type VoucherCheckRunItem,
} from '../api/voucherCheck.api';
import { voucherCheckNotifyStatusLabel, voucherCheckStatusLabel } from '../utils/voucherCheck.display';
import {
voucherCheckModeLabel,
voucherCheckNotifyStatusLabel,
voucherCheckStatusLabel,
voucherCheckStepLabel,
} from '../utils/voucherCheck.display';
const props = withDefaults(defineProps<{
embedded?: boolean;
activeTab?: 'tasks' | 'notifications';
}>(), {
embedded: false,
activeTab: 'tasks',
});
const emit = defineEmits<{
'open-detail': [payload: { runId: number; runNo?: string | null }];
}>();
const { t } = useI18n();
const msg = useMessage();
@@ -36,28 +58,98 @@ const items = ref<VoucherCheckRunItem[]>([]);
const total = ref(0);
const page = ref(1);
const pageSize = ref(50);
const period = ref('');
const periodYear = ref('');
const periodMonth = ref('');
const status = ref('');
const listTab = ref<'tasks' | 'notifications'>('tasks');
const listTab = ref<'tasks' | 'notifications'>(props.activeTab);
const notifyLoading = ref(false);
const notifyItems = ref<VoucherCheckNotificationItem[]>([]);
const notifyTotal = ref(0);
const notifyPage = ref(1);
const notifyPageSize = ref(50);
const notifyStatus = ref('');
const latestRun = ref<VoucherCheckLatestRun | null>(null);
const latestLoading = ref(false);
let forcePollTimer: ReturnType<typeof setInterval> | null = null;
const isAdmin = computed(() => String(getStoredAuthUser()?.role || '').trim().toLowerCase() === 'admin');
const latestInProgress = computed(() => {
const cardStatus = latestRun.value?.status;
return cardStatus === 'queued' || cardStatus === 'running';
});
const latestHasMissing = computed(() => {
const row = latestRun.value;
if (!row) return false;
return (row.missing_file_count || 0) > 0 || (row.missing_invoice_count || 0) > 0;
});
const latestCanOpenDetail = computed(() => {
const row = latestRun.value;
if (!row?.schedule_run_id) return false;
return row.status === 'missing' || row.status === 'completed';
});
/**
* 默认资料所属期间为上一个自然月 YYYY-MM。
* 最近一次检核的四个指标格,终态矮格与执行中共用。
* 核心逻辑:缺件时后两项(缺件文件 / 缺件 invoice)标红。
*/
function previousPeriod(): string {
const latestMetrics = computed(() => {
const row = latestRun.value;
if (!row) return [];
const warn = latestHasMissing.value;
return [
{ key: 'subject', value: row.subject_count, labelKey: 'workspace.voucherCheck.subjectCount', warn: false },
{ key: 'archived', value: row.archived_file_count, labelKey: 'workspace.voucherCheck.archivedFiles', warn: false },
{ key: 'missingFiles', value: row.missing_file_count, labelKey: 'workspace.voucherCheck.missingFiles', warn },
{ key: 'missingInvoices', value: row.missing_invoice_count, labelKey: 'workspace.voucherCheck.missingInvoices', warn },
];
});
/**
* 终态是否展示失败原因:仅技术失败或带 error_message 时占一行,完整/缺件不再重复完成提示。
*/
const latestShowFailureHint = computed(() => {
const row = latestRun.value;
if (!row || latestInProgress.value) return false;
return row.status === 'technical_failed' || Boolean(row.error_message);
});
const MONTH_VALUES = ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12'] as const;
/**
* 进页默认资料所属期间为上一个自然月。
*/
function previousYearMonth(): { year: string; month: string } {
const d = new Date();
d.setDate(1);
d.setMonth(d.getMonth() - 1);
const m = String(d.getMonth() + 1).padStart(2, '0');
return `${d.getFullYear()}-${m}`;
return {
year: String(d.getFullYear()),
month: String(d.getMonth() + 1).padStart(2, '0'),
};
}
/**
* 组装列表查询 period:有月份则为 YYYY-MM,否则为 YYYY。
*/
const periodQuery = computed(() => {
if (!periodYear.value) return undefined;
if (periodMonth.value) return `${periodYear.value}-${periodMonth.value}`;
return periodYear.value;
});
const yearOptions = computed(() => {
const now = new Date().getFullYear();
const years: string[] = [];
for (let year = now - 5; year <= now; year += 1) {
years.push(String(year));
}
if (periodYear.value && !years.includes(periodYear.value)) {
years.unshift(periodYear.value);
years.sort();
}
return years;
});
const statusOptions = computed(() => [
{ value: '', label: t('workspace.voucherCheck.statusAll') },
{ value: 'missing', label: t('workspace.voucherCheck.statusMissing') },
@@ -89,7 +181,7 @@ async function loadNotifications() {
notifyLoading.value = true;
try {
const data = await listVoucherCheckNotifications({
period: period.value || undefined,
period: periodQuery.value,
send_status: notifyStatus.value || undefined,
page: notifyPage.value,
page_size: notifyPageSize.value,
@@ -117,6 +209,7 @@ function setListTab(tab: 'tasks' | 'notifications') {
}
page.value = 1;
void loadRuns();
void loadLatestRun();
}
/**
@@ -132,17 +225,6 @@ function searchCurrentTab() {
void loadNotifications();
}
/**
* 当前 Tab 刷新列表,不重置页码。
*/
function refreshCurrentTab() {
if (listTab.value === 'tasks') {
void loadRuns();
return;
}
void loadNotifications();
}
/**
* 下载该发送记录对应批次的 Excel。
* @param row - 企微发送记录
@@ -175,6 +257,20 @@ function formatRecipientNames(names?: string[]): string {
return names.join('、');
}
/**
* 打开批次明细:Chat 嵌入时回传父级,独立页则跳转工作台详情路由。
*/
function navigateToDetail(runId: number, runNo?: string | null) {
if (props.embedded) {
emit('open-detail', { runId, runNo: runNo || null });
return;
}
void router.push({
path: WORKSPACE_PATHS.accountingVoucherCheckDetail(runId),
query: runNo ? { runNo } : undefined,
});
}
/**
* 从发送记录跳转对应批次明细。
* @param row - 企微发送记录
@@ -184,10 +280,7 @@ function openNotifyDetail(row: VoucherCheckNotificationItem) {
msg.error(t('workspace.voucherCheck.loadFailed'));
return;
}
void router.push({
path: WORKSPACE_PATHS.accountingVoucherCheckDetail(row.schedule_run_id),
query: row.run_no ? { runNo: row.run_no } : undefined,
});
navigateToDetail(row.schedule_run_id, row.run_no);
}
/**
@@ -197,7 +290,7 @@ async function loadRuns() {
loading.value = true;
try {
const data = await listVoucherCheckRuns({
period: period.value || undefined,
period: periodQuery.value,
status: status.value || undefined,
page: page.value,
page_size: pageSize.value,
@@ -231,22 +324,100 @@ function openRunDetail(row: VoucherCheckRunItem) {
msg.error(t('workspace.voucherCheck.loadFailed'));
return;
}
void router.push({
path: WORKSPACE_PATHS.accountingVoucherCheckDetail(row.schedule_run_id),
query: row.run_no ? { runNo: row.run_no } : undefined,
});
navigateToDetail(row.schedule_run_id, row.run_no);
}
/**
* 停止强制重检后的列表轮询。
* 停止最近一次检核的进度轮询。
*/
function stopForcePoll() {
function stopLatestPoll() {
if (forcePollTimer) {
clearInterval(forcePollTimer);
forcePollTimer = null;
}
}
/**
* 拉取最近一次检核卡片;不跟下方列表的年/月/状态筛选。
* @param options.silent - 轮询时不切换卡片 loading,避免进度条闪烁
*/
async function loadLatestRun(options?: { silent?: boolean }) {
if (!options?.silent) latestLoading.value = true;
try {
latestRun.value = await getLatestVoucherCheckRun();
} catch (e: any) {
if (!options?.silent) {
msg.error(e?.message || t('workspace.voucherCheck.latestLoadFailed'));
}
} finally {
if (!options?.silent) latestLoading.value = false;
}
}
/**
* 排队或执行中时轮询卡片;进入终态后刷新下方列表。
*/
function syncLatestPoll() {
stopLatestPoll();
if (listTab.value !== 'tasks' || !latestInProgress.value) return;
forcePollTimer = setInterval(() => {
void (async () => {
const previous = latestRun.value?.status;
await loadLatestRun({ silent: true });
const next = latestRun.value?.status;
if ((previous === 'queued' || previous === 'running') && next !== 'queued' && next !== 'running') {
stopLatestPoll();
void loadRuns();
}
})();
}, 3000);
}
/**
* 最近一次检核状态徽章样式。
* @param value - 卡片状态
*/
function latestBadgeClass(value: string): string {
if (value === 'missing' || value === 'technical_failed') return 'bg-rose-50 text-rose-700';
if (value === 'completed') return 'bg-emerald-50 text-emerald-700';
if (value === 'queued' || value === 'running') return 'bg-blue-50 text-blue-700';
return 'bg-surface-soft text-secondary';
}
/**
* 卡片当前步骤主文案:终态用完成提示,其余按步骤码翻译。
* @param row - 最近一次检核
*/
function latestStepText(row: VoucherCheckLatestRun): string {
if (row.status === 'queued') return t('workspace.voucherCheck.stepQueued');
if (row.status === 'missing' && (row.current_step?.step === 'done' || !row.current_step)) {
return t('workspace.voucherCheck.latestDoneHint');
}
if (row.status === 'completed' && (row.current_step?.step === 'done' || !row.current_step)) {
return t('workspace.voucherCheck.latestCompleteHint');
}
if (row.status === 'technical_failed' && row.current_step?.step === 'fetch_erp') {
return t('workspace.voucherCheck.stepFetchErpIncomplete');
}
return voucherCheckStepLabel(t, row.current_step?.step);
}
/**
* 卡片步骤辅文案:失败原因、排队等待或扫描进度。
* @param row - 最近一次检核
*/
function latestHintText(row: VoucherCheckLatestRun): string {
if (row.error_message) return row.error_message;
if (row.status === 'queued') return t('workspace.voucherCheck.stepQueuedHint');
if (row.status === 'running' && row.current_step?.step === 'scan_dms' && row.subject_count > 0) {
return t('workspace.voucherCheck.processedHint', {
processed: row.processed_count,
total: row.subject_count,
});
}
return '';
}
/**
* 打开强制重检确认框;用公共 DeleteConfirmDialog 替代原生 window.confirm。
*/
@@ -264,13 +435,8 @@ async function forceRecheck() {
try {
const data = await triggerVoucherCheckForceAll();
msg.success(t('workspace.voucherCheck.forceQueued', { runNo: data.run_no }));
await loadRuns();
stopForcePoll();
const started = Date.now();
forcePollTimer = setInterval(() => {
void loadRuns();
if (Date.now() - started > 120_000) stopForcePoll();
}, 5000);
await loadLatestRun({ silent: true });
syncLatestPoll();
} catch (e: any) {
msg.error(e?.message || t('workspace.voucherCheck.forceFailed'));
} finally {
@@ -278,27 +444,62 @@ async function forceRecheck() {
}
}
/**
* 从最近一次检核卡片打开本批明细。
*/
function openLatestDetail() {
const row = latestRun.value;
if (!row?.schedule_run_id) {
msg.error(t('workspace.voucherCheck.loadFailed'));
return;
}
navigateToDetail(row.schedule_run_id, row.run_no);
}
/**
* 仅在检核任务 Tab 且最近一批仍在排队/执行时轮询卡片。
*/
watch([listTab, latestInProgress], () => {
syncLatestPoll();
});
watch(
() => props.activeTab,
(tab) => {
if (!props.embedded) return;
if (listTab.value === tab) return;
setListTab(tab);
},
);
onMounted(async () => {
if (redirectLegacyRunQuery()) return;
period.value = previousPeriod();
if (!props.embedded && redirectLegacyRunQuery()) return;
const previous = previousYearMonth();
periodYear.value = previous.year;
periodMonth.value = previous.month;
const qStatus = route.query.status;
if (typeof qStatus === 'string' && qStatus) status.value = qStatus;
await loadRuns();
if (props.embedded) listTab.value = props.activeTab;
if (listTab.value === 'notifications') {
await loadNotifications();
return;
}
await Promise.all([loadRuns(), loadLatestRun()]);
});
onUnmounted(() => {
stopForcePoll();
stopLatestPoll();
});
</script>
<template>
<div class="space-y-5 animate-fade-in-up">
<header class="space-y-1">
<div class="space-y-4 animate-fade-in-up">
<header v-if="!embedded" class="space-y-1">
<h1 class="text-2xl font-bold text-primary">{{ $t('workspace.voucherCheck.title') }}</h1>
<p class="text-sm text-muted">{{ $t('workspace.voucherCheck.subtitle') }}</p>
</header>
<div class="flex gap-1 border-b border-default" role="tablist">
<div v-if="!embedded" class="flex gap-1 border-b border-default" role="tablist">
<button
type="button"
role="tab"
@@ -321,22 +522,137 @@ onUnmounted(() => {
</button>
</div>
<article
v-if="listTab === 'tasks'"
class="overflow-hidden rounded-2xl border border-default bg-surface"
aria-live="polite"
>
<div
class="flex flex-wrap items-start justify-between gap-3 px-4 py-2.5"
:class="latestInProgress ? 'bg-blue-50' : ''"
>
<div>
<h2 class="text-sm font-semibold text-primary">{{ $t('workspace.voucherCheck.latestTitle') }}</h2>
<p v-if="latestRun" class="mt-0.5 text-xs text-muted">
<span class="mr-3">{{ $t('workspace.voucherCheck.latestBatch', { runNo: latestRun.run_no }) }}</span>
<span class="mr-3">{{ $t('workspace.voucherCheck.latestPeriod', { period: latestRun.period_month || '-' }) }}</span>
<span>{{ voucherCheckModeLabel(t, latestRun.mode) }}</span>
</p>
</div>
<div class="flex shrink-0 items-center gap-2">
<button
v-if="latestCanOpenDetail"
type="button"
class="text-sm font-semibold text-brand-700 hover:underline"
@click="openLatestDetail"
>
{{ $t('workspace.voucherCheck.viewLatestDetail') }}
</button>
<span
v-if="latestRun"
class="inline-flex rounded-full px-2.5 py-0.5 text-xs font-semibold"
:class="latestBadgeClass(latestRun.status)"
>
{{ voucherCheckStatusLabel(t, latestRun.status) }}
</span>
<button
v-if="isAdmin"
type="button"
class="inline-flex items-center gap-1 rounded-xl border border-amber-300 bg-amber-50 px-3 py-1.5 text-sm font-medium text-amber-900 transition-colors hover:bg-amber-100 disabled:opacity-50"
:disabled="forcing || latestInProgress"
@click="openForceRecheck()"
>
<Loader2 v-if="forcing" class="h-3.5 w-3.5 animate-spin" />
<RotateCcw v-else class="h-3.5 w-3.5" />
{{ $t('workspace.voucherCheck.forceRecheck') }}
</button>
</div>
</div>
<div v-if="latestLoading && !latestRun" class="flex items-center justify-center gap-2 px-4 py-6 text-sm text-muted">
<Loader2 class="h-4 w-4 animate-spin" />
{{ $t('workspace.voucherCheck.loading') }}
</div>
<p v-else-if="!latestRun" class="px-4 py-6 text-center text-sm text-muted">
{{ $t('workspace.voucherCheck.latestEmpty') }}
</p>
<div v-else class="px-4 pb-3">
<template v-if="latestInProgress">
<div class="h-2 overflow-hidden rounded-full bg-slate-200">
<div
class="h-full rounded-full bg-teal-700 transition-[width] duration-300"
:style="{ width: `${latestRun.progress_percent || 0}%` }"
/>
</div>
<div class="mt-1.5 mb-2.5 flex flex-wrap justify-between gap-3 text-xs text-muted">
<span>{{ $t('workspace.voucherCheck.progress', { percent: latestRun.progress_percent || 0 }) }}</span>
<span>
{{ $t('workspace.voucherCheck.startedAt') }}:{{ formatLocalDateTime(latestRun.started_at) }}
 {{ $t('workspace.voucherCheck.finishedAt') }}:{{ $t('workspace.voucherCheck.inProgress') }}
</span>
</div>
<p class="mb-2.5 text-[13px] text-slate-700">
{{ latestStepText(latestRun) }}
<small v-if="latestHintText(latestRun)" class="mt-0.5 block text-muted">{{ latestHintText(latestRun) }}</small>
</p>
</template>
<div class="grid grid-cols-2 gap-2 md:grid-cols-4">
<div
v-for="metric in latestMetrics"
:key="metric.key"
class="rounded-[10px] border border-default bg-slate-50 px-2.5 py-2"
>
<b
class="block text-lg font-semibold leading-tight tabular-nums"
:class="metric.warn ? 'text-rose-700' : 'text-primary'"
>{{ metric.value }}</b>
<span class="text-[11px] text-muted">{{ $t(metric.labelKey) }}</span>
</div>
</div>
<p v-if="latestShowFailureHint" class="mt-2 text-[13px] text-slate-700">
{{ latestStepText(latestRun) }}
<small v-if="latestHintText(latestRun)" class="mt-0.5 block text-muted">{{ latestHintText(latestRun) }}</small>
</p>
</div>
</article>
<section class="flex flex-wrap items-end gap-3 rounded-2xl border border-default/80 bg-surface/70 px-4 py-3 shadow-sm">
<label class="flex flex-col gap-1 text-xs font-medium text-muted">
{{ $t('workspace.voucherCheck.period') }}
<input v-model="period" type="month" class="rounded-xl border border-default bg-surface px-3 py-1.5 text-sm text-primary" />
<span class="flex items-center gap-2">
<span class="period-select">
<select v-model="periodYear" class="period-select__control w-[4.75rem]">
<option v-for="year in yearOptions" :key="year" :value="year">{{ year }}</option>
</select>
<ChevronDown class="period-select__icon" aria-hidden="true" />
</span>
<span class="period-select">
<select v-model="periodMonth" class="period-select__control w-[4.75rem]">
<option value="">{{ $t('workspace.voucherCheck.periodMonthAll') }}</option>
<option v-for="month in MONTH_VALUES" :key="month" :value="month">
{{ $t('workspace.voucherCheck.periodMonthValue', { n: Number(month) }) }}
</option>
</select>
<ChevronDown class="period-select__icon" aria-hidden="true" />
</span>
</span>
</label>
<label v-if="listTab === 'tasks'" class="flex flex-col gap-1 text-xs font-medium text-muted">
{{ $t('workspace.voucherCheck.status') }}
<select v-model="status" class="rounded-xl border border-default bg-surface px-3 py-1.5 text-sm text-primary">
<option v-for="opt in statusOptions" :key="opt.value || 'all'" :value="opt.value">{{ opt.label }}</option>
</select>
<span class="period-select">
<select v-model="status" class="period-select__control w-[6rem]">
<option v-for="opt in statusOptions" :key="opt.value || 'all'" :value="opt.value">{{ opt.label }}</option>
</select>
<ChevronDown class="period-select__icon" aria-hidden="true" />
</span>
</label>
<label v-else class="flex flex-col gap-1 text-xs font-medium text-muted">
{{ $t('workspace.voucherCheck.notifyStatus') }}
<select v-model="notifyStatus" class="rounded-xl border border-default bg-surface px-3 py-1.5 text-sm text-primary">
<option v-for="opt in notifyStatusOptions" :key="opt.value || 'all'" :value="opt.value">{{ opt.label }}</option>
</select>
<span class="period-select">
<select v-model="notifyStatus" class="period-select__control w-[7.25rem]">
<option v-for="opt in notifyStatusOptions" :key="opt.value || 'all'" :value="opt.value">{{ opt.label }}</option>
</select>
<ChevronDown class="period-select__icon" aria-hidden="true" />
</span>
</label>
<button
type="button"
@@ -346,25 +662,6 @@ onUnmounted(() => {
<Search class="h-3.5 w-3.5" />
{{ $t('workspace.voucherCheck.search') }}
</button>
<button
type="button"
class="inline-flex items-center gap-1 rounded-xl border border-default px-3 py-1.5 text-sm font-medium text-secondary transition-colors hover:bg-surface-soft"
@click="refreshCurrentTab"
>
<RefreshCw class="h-3.5 w-3.5" />
{{ $t('workspace.voucherCheck.refresh') }}
</button>
<button
v-if="listTab === 'tasks'"
type="button"
class="ml-auto inline-flex items-center gap-1 rounded-xl border border-amber-300 bg-amber-50 px-3 py-1.5 text-sm font-medium text-amber-900 transition-colors hover:bg-amber-100 disabled:opacity-50"
:disabled="forcing"
@click="openForceRecheck()"
>
<Loader2 v-if="forcing" class="h-3.5 w-3.5 animate-spin" />
<RotateCcw v-else class="h-3.5 w-3.5" />
{{ $t('workspace.voucherCheck.forceRecheck') }}
</button>
</section>
<section v-if="listTab === 'tasks'" class="overflow-hidden rounded-2xl border border-default bg-surface">
@@ -524,3 +821,51 @@ onUnmounted(() => {
/>
</div>
</template>
<style scoped>
/**
* 隐藏系统原生下拉箭头(含 Chromium ::picker-icon / Edge ::-ms-expand)。
* 只保留模板里的 ChevronDown,避免 Windows 下年份与月份箭头叠在一起。
*/
.period-select {
position: relative;
display: inline-flex;
align-items: center;
}
.period-select__control {
box-sizing: border-box;
border-radius: 0.75rem;
border: 1px solid var(--border-default);
background-color: var(--bg-surface);
background-image: none;
padding: 0.375rem 1.75rem 0.375rem 0.625rem;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
color: var(--text-primary);
font-size: 0.875rem;
line-height: 1.25rem;
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
}
.period-select__control::-ms-expand {
display: none;
}
.period-select__control::picker-icon {
display: none;
content: none;
}
.period-select__icon {
pointer-events: none;
position: absolute;
right: 0.5rem;
height: 0.875rem;
width: 0.875rem;
color: var(--text-muted);
}
</style>