Files
syops/frontend/src/features/workspace/shipping-task-center/ShippingTaskCenterPage.vue
T
hugo ea94fb28db feat(shipping-notice): 人工重取库存前置候选刷新并放开行级库存源下拉
- 人工重试库存准备前置幂等重判:任务级整单重路由、行级定向重评目标行,复用裁决与冻结链路,零新动作码零契约变更
- 新版候选集 supersede 时内置失效旧库存事实,导出归档与查询服务同步适配
- 行级「库存源」下拉抽纯函数合并选项:歧义行候选置顶 + 全部已启用源去重兜底,任一已启用源可人工指定
- 库存源门禁归一 Notice→OT 身份解析;任务中心抽屉与表格接入行级重取入口
- 同步四语言文案、技术文档与实施计划
2026-10-13 15:04:40 +08:00

913 lines
34 KiB
Vue
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<!--
features/workspace/shipping-task-center/ShippingTaskCenterPage.vue
用途:发货「任务中心」壳——Pending|Processing|Done + 识别 Run 续办表。
依赖:shipping-tasks.api(my-todos / done-lines / count)、shipping.api(详情/STP retry/批量)、
ShippingStageTabs / ShippingTaskTable / ShippingTaskDrawer / ShippingDoneLineReport、
shippingTaskCenterShared、useShippingTodoBadge、useMessage。
逻辑:列表优先 + 按需抽屉——紧凑表格行点开右侧抽屉(分诊决策面板),移除常驻详情面板;
阶段筛选 tab 消费后端全量聚合计数(stage_counts);批量操作仅货代上传阶段可选、
勾选后浮出操作条;done 桶拆子视图:通知完成=明细报表(done-lines),驳回/作废=
terminal_kind 过滤后的任务表 + 抽屉;主操作深链「订单生命周期工作台」;
不内嵌 ShippingTaskWorkbench;轮询只跟系统 running,silent 刷新不闪加载。
-->
<script setup lang="ts">
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { RefreshCw } from 'lucide-vue-next';
import { useI18n } from 'vue-i18n';
import {
getWorkspaceShippingTask,
listShippingChatAgents,
retryWorkspaceShippingOrderStpAutoCreate,
batchConfirmWorkspaceShippingNoticesUploaded,
batchStartWorkspaceShippingNoticeRpaUpload,
SHIPPING_NOTICE_AGENT_CODE,
type ShippingTaskDetail,
type ShippingTaskSummary,
} from '@/features/chat/api/shipping.api';
import {
countWorkspaceShippingMyTodos,
downloadWorkspaceShippingDoneLinesExcel,
listWorkspaceShippingDoneLines,
listWorkspaceShippingMyTodos,
type ShippingDoneLineFilters,
type ShippingDoneLineItem,
type ShippingMyTodosCount,
} from '@/features/workspace/api/shipping-tasks.api';
import { useShippingTodoBadge } from '../composables/useShippingTodoBadge';
import { useMessage } from '@/shared/composables/useMessage';
import { BusinessError } from '@/shared/api/client';
import {
isBatchDownloadableRow,
lifecycleStageCodeOf,
todoItemKey,
type LifecycleStageCode,
type TodoLike,
} from './shippingTaskCenterShared';
import {
isShippingTodoListItemInProgress,
resolveTodoCenterPollIntervalMs,
} from './shippingTaskCenterPolling';
import ShippingRunProgressTable from './ShippingRunProgressTable.vue';
import ShippingStageTabs from './ShippingStageTabs.vue';
import ShippingTaskTable from './ShippingTaskTable.vue';
import ShippingTaskDrawer from './ShippingTaskDrawer.vue';
import ShippingDoneLineReport from './ShippingDoneLineReport.vue';
import { downloadWorkspaceShippingNoticeExportArchive } from '@/features/chat/shipping/shippingDownload';
const { t } = useI18n();
const msg = useMessage();
const route = useRoute();
const router = useRouter();
const { refreshShippingTodoBadge } = useShippingTodoBadge();
/** todos=建单后待办;runs=建单前识别续办 */
const surface = ref<'todos' | 'runs'>('todos');
const bucket = ref<'pending' | 'processing' | 'done'>('pending');
/** done 桶子视图:通知完成=明细报表;驳回/作废=任务表。 */
const doneSubTab = ref<'upload_complete' | 'reject_void'>('upload_complete');
const filterTodoCategory = ref<'all' | 'review' | 'exception' | 'manual_upload' | 'intake_parse'>('all');
const lifecycleStageFilter = ref<'all' | Exclude<LifecycleStageCode, 'upload_complete'>>('all');
const filterCustomer = ref('');
const filterTaskNo = ref('');
const appliedFilters = ref({
todo_category: '',
customer: '',
task_no: '',
});
const loading = ref(false);
const detailLoading = ref(false);
const tasks = ref<ShippingTaskSummary[]>([]);
/** 货代批量选择只容纳货代上传阶段的正式发货通知,Review/Intake 永不进入集合。 */
const selectedBusinessNos = ref<string[]>([]);
const batchActionBusy = ref<'download' | 'confirm' | 'rpa' | null>(null);
const selectedRef = ref<string | null>(null);
/** 仅直链摘要,供抽屉展示;禁止内嵌履约工作台。 */
const detail = ref<ShippingTaskDetail | null>(null);
const drawerOpen = ref(false);
const currentPage = ref(1);
const pageSize = 20;
const totalTasks = ref(0);
const bucketCounts = ref<ShippingMyTodosCount>({
pending: 0,
processing: 0,
done: 0,
total_pending_badge: 0,
});
const chatAgentId = ref<number | null>(null);
const stpRetrying = ref(false);
// —— 通知完成明细报表(done-lines)状态 ——
const doneLines = ref<ShippingDoneLineItem[]>([]);
const doneLineTotal = ref(0);
const doneLinePage = ref(1);
const doneLineLoading = ref(false);
const doneLineExportBusy = ref(false);
const doneLineFilterDraft = ref<ShippingDoneLineFilters>({});
const doneLineAppliedFilters = ref<ShippingDoneLineFilters>({});
const DONE_LINE_PAGE_SIZE = 50;
let pollTimer: ReturnType<typeof setTimeout> | null = null;
let pollInFlight = false;
let pollFailureCount = 0;
let processingPollStartedAt: number | null = null;
let lastForegroundPullAt = 0;
const totalPages = computed(() => Math.max(1, Math.ceil(totalTasks.value / pageSize)));
const preferredTaskNo = computed(() =>
String(route.params.taskNo || route.query.task_no || '').trim().toUpperCase(),
);
const isDirectTaskRoute = computed(() => Boolean(String(route.params.taskNo || '').trim()));
const selectedItem = computed(() =>
tasks.value.find((item) => todoItemKey(item) === selectedRef.value) || null,
);
/** 抽屉展示对象:优先列表选中项,直链时回退详情摘要。 */
const drawerItem = computed((): ShippingTaskSummary | ShippingTaskDetail | null => {
if (selectedItem.value) return selectedItem.value;
if (isDirectTaskRoute.value && detail.value) return detail.value;
return null;
});
const drawerVisible = computed(() => drawerOpen.value && Boolean(drawerItem.value));
const filteredTasks = computed(() => (
lifecycleStageFilter.value === 'all'
? tasks.value
: tasks.value.filter((item) => lifecycleStageCodeOf(item) === lifecycleStageFilter.value)
));
/** 批量可选行:货代上传阶段的正式 Notice 且当前用户可下载(与批量导出端点同口径)。 */
const selectableRows = computed(() => filteredTasks.value.filter((item) => isBatchDownloadableRow(item)));
const selectedBusinessNoSet = computed(() => new Set(selectedBusinessNos.value));
/** 当前桶是否为通知完成明细报表视图。 */
const isDoneLineReportView = computed(() => (
surface.value === 'todos' && bucket.value === 'done' && doneSubTab.value === 'upload_complete'
));
/**
* 判断详情是否仍处于系统处理中。
* 核心逻辑:与列表项同一 running 谓词;阶段码不得单独维持轮询。
*/
function isDetailInProgress(task: ShippingTaskDetail | null): boolean {
if (!task) return false;
return isShippingTodoListItemInProgress(task);
}
/**
* 判断列表项是否应触发轮询刷新。
* 核心逻辑:委托 isShippingTodoListItemInProgress(Intake created/queued/parsing 必须轮询)。
*/
function isListItemInProgress(item: ShippingTaskSummary): boolean {
return isShippingTodoListItemInProgress(item);
}
/**
* 切换一张正式发货通知的批量选择,始终按 business_no 去重。
*/
function toggleNoticeSelection(item: ShippingTaskSummary): void {
const businessNo = String(item.business_no || '').trim();
if (!businessNo) return;
selectedBusinessNos.value = selectedBusinessNoSet.value.has(businessNo)
? selectedBusinessNos.value.filter((value) => value !== businessNo)
: [...selectedBusinessNos.value, businessNo];
}
/** 对当前筛选下可批量选择的行全选/取消;Review 与 Intake 保持不可选。 */
function toggleAllSelectableRows(): void {
const visible = selectableRows.value.map((item) => String(item.business_no || '').trim()).filter(Boolean);
const allChecked = visible.length > 0
&& visible.every((value) => selectedBusinessNoSet.value.has(value));
selectedBusinessNos.value = allChecked
? selectedBusinessNos.value.filter((value) => !visible.includes(value))
: Array.from(new Set([...selectedBusinessNos.value, ...visible]));
}
/** 批量请求后只提示汇总,逐单状态由服务端结果决定,避免前端自行推断。 */
function summarizeBatchResults(results: Array<Record<string, unknown>>, action: string): void {
const accepted = results.filter((item) => ['accepted', 'confirmed'].includes(String(item.status || ''))).length;
const blocked = results.length - accepted;
if (blocked) msg.warning(t('workspace.shippingNotice.batch.partialResult', { action, accepted, blocked }));
else msg.success(t('workspace.shippingNotice.batch.success', { action, count: accepted }));
}
async function runNoticeBatchAction(action: 'download' | 'confirm' | 'rpa'): Promise<void> {
if (!selectedBusinessNos.value.length || batchActionBusy.value) return;
batchActionBusy.value = action;
try {
if (action === 'download') {
await downloadWorkspaceShippingNoticeExportArchive(selectedBusinessNos.value);
msg.success(t('workspace.shippingNotice.batch.downloadStarted'));
return;
}
const result = action === 'confirm'
? await batchConfirmWorkspaceShippingNoticesUploaded(selectedBusinessNos.value)
: await batchStartWorkspaceShippingNoticeRpaUpload(selectedBusinessNos.value);
summarizeBatchResults(result.results || [], t(`workspace.shippingNotice.batch.${action}`));
await refreshAll();
} catch (error) {
msg.error(error instanceof Error ? error.message : t('workspace.shippingNotice.actions.failed'));
} finally {
batchActionBusy.value = null;
}
}
/**
* 当前页是否存在系统正在自动跑的项。
*/
const hasRunningWork = computed(() => {
if (isDirectTaskRoute.value && isDetailInProgress(detail.value)) return true;
return tasks.value.some((item) => isListItemInProgress(item));
});
/**
* 当前页是否仅为人工等待(用于 30s 低频轮询;已完成桶与报表视图不轮询)。
*/
const hasHumanWaitWork = computed(() => {
if (hasRunningWork.value) return false;
if (surface.value !== 'todos') return false;
if (bucket.value === 'done') return false;
return tasks.value.length > 0;
});
/**
* 是否应继续自动轮询:系统在跑或当前页仍有人工待办。
*/
const shouldAutoRefresh = computed(() => hasRunningWork.value || hasHumanWaitWork.value);
/**
* 解析待办轮询间隔:running 复用批次函数;人工等待 30s。
*/
function resolvePollMs(): number | null {
const visibility = typeof document !== 'undefined' ? document.visibilityState : 'visible';
const elapsedMs = processingPollStartedAt != null ? Date.now() - processingPollStartedAt : 0;
return resolveTodoCenterPollIntervalMs({
hasRunning: hasRunningWork.value,
hasHumanWait: hasHumanWaitWork.value,
elapsedMs,
visibility,
failureCount: pollFailureCount,
});
}
/**
* 停止自动轮询。
*/
function stopAutoRefresh() {
if (pollTimer != null) {
clearTimeout(pollTimer);
pollTimer = null;
}
}
/**
* 调度下一次自动刷新(仅系统在跑或人工等待低频)。
*/
function scheduleAutoRefresh() {
stopAutoRefresh();
const intervalMs = resolvePollMs();
if (intervalMs == null) return;
pollTimer = setTimeout(() => {
void (async () => {
if (pollInFlight) {
scheduleAutoRefresh();
return;
}
const nextInterval = resolvePollMs();
if (nextInterval == null) return;
pollInFlight = true;
try {
await refreshAll({ silent: true });
pollFailureCount = 0;
} catch {
pollFailureCount += 1;
} finally {
pollInFlight = false;
scheduleAutoRefresh();
}
})();
}, intervalMs);
}
/**
* 解析货代 Chat Agent,供订单处理/会话深链。
*/
async function resolveChatAgent() {
try {
const agents = await listShippingChatAgents();
const found = agents.find((a) => String(a.agent_code || '').trim() === SHIPPING_NOTICE_AGENT_CODE);
if (found) chatAgentId.value = found.id;
} catch {
/* ignore */
}
}
/**
* 刷新各 bucket 计数与导航徽标(stage_counts / done_counts 随后端聚合返回)。
*/
async function loadCounts() {
try {
bucketCounts.value = await countWorkspaceShippingMyTodos();
await refreshShippingTodoBadge(true);
} catch {
/* 计数失败不阻断列表 */
}
}
/**
* 将筛选表单同步为已应用条件并重置到第 1 页。
*/
function applyFilters() {
appliedFilters.value = {
todo_category: bucket.value === 'pending' && filterTodoCategory.value !== 'all'
? filterTodoCategory.value
: '',
customer: filterCustomer.value.trim(),
task_no: filterTaskNo.value.trim().toUpperCase(),
};
void loadTodos(true);
}
/**
* 清空筛选并重载。
*/
function resetFilters() {
filterTodoCategory.value = 'all';
filterCustomer.value = '';
filterTaskNo.value = '';
appliedFilters.value = { todo_category: '', customer: '', task_no: '' };
void loadTodos(true);
}
/**
* 拉取当前桶待办列表(通知完成报表视图改走 loadDoneLines)。
* @param resetPage - 切换桶时重置到第一页
* @param options.silent - 为 true 时不切换 loading,保留旧列表(轮询失败也不清空)
*/
async function loadTodos(resetPage = false, options?: { silent?: boolean }) {
if (isDoneLineReportView.value) {
await loadDoneLines(resetPage, options);
return;
}
if (resetPage) currentPage.value = 1;
const silent = Boolean(options?.silent);
if (!silent) loading.value = true;
try {
const category = appliedFilters.value.todo_category || undefined;
const result = await listWorkspaceShippingMyTodos({
bucket: bucket.value,
page: currentPage.value,
page_size: pageSize,
todo_category: category as 'review' | 'exception' | 'manual_upload' | 'intake_parse' | undefined,
customer: appliedFilters.value.customer || undefined,
task_no: appliedFilters.value.task_no || undefined,
terminal_kind: bucket.value === 'done' && doneSubTab.value === 'reject_void'
? 'reject_void'
: undefined,
});
tasks.value = result.items || [];
const visibleBusinessNos = new Set(
tasks.value
.filter((item) => isBatchDownloadableRow(item))
.map((item) => String(item.business_no || '').trim()),
);
selectedBusinessNos.value = selectedBusinessNos.value.filter((value) => visibleBusinessNos.has(value));
totalTasks.value = Number(result.total || 0);
if (preferredTaskNo.value && !selectedRef.value) {
const hit = tasks.value.find(
(item) => String(item.task_no || '').toUpperCase() === preferredTaskNo.value,
);
if (hit) {
selectedRef.value = todoItemKey(hit);
drawerOpen.value = true;
}
}
} catch {
if (!silent) {
tasks.value = [];
totalTasks.value = 0;
}
} finally {
if (!silent) loading.value = false;
}
}
/**
* 拉取通知完成明细报表(按明细行分页,筛选由 applied 同步)。
*/
async function loadDoneLines(resetPage = false, options?: { silent?: boolean }) {
if (resetPage) doneLinePage.value = 1;
const silent = Boolean(options?.silent);
if (!silent) doneLineLoading.value = true;
try {
const result = await listWorkspaceShippingDoneLines({
page: doneLinePage.value,
page_size: DONE_LINE_PAGE_SIZE,
customer: doneLineAppliedFilters.value.customer || undefined,
part_number: doneLineAppliedFilters.value.part_number || undefined,
notice_date_from: doneLineAppliedFilters.value.notice_date_from || undefined,
notice_date_to: doneLineAppliedFilters.value.notice_date_to || undefined,
});
doneLines.value = result.items || [];
doneLineTotal.value = Number(result.total || 0);
} catch {
if (!silent) {
doneLines.value = [];
doneLineTotal.value = 0;
}
} finally {
if (!silent) doneLineLoading.value = false;
}
}
/** 报表筛选应用:草稿 → 已应用并回第一页。 */
function applyDoneLineFilters() {
doneLineAppliedFilters.value = { ...doneLineFilterDraft.value };
void loadDoneLines(true);
}
/** 导出当前筛选的明细 Excel(固定 12 列标准格式)。 */
async function exportDoneLines() {
if (doneLineExportBusy.value) return;
doneLineExportBusy.value = true;
try {
await downloadWorkspaceShippingDoneLinesExcel(doneLineAppliedFilters.value);
msg.success(t('workspace.shippingNotice.myTodos.doneReport.exportStarted'));
} catch (error) {
msg.error(error instanceof Error ? error.message : t('workspace.shippingNotice.actions.failed'));
} finally {
doneLineExportBusy.value = false;
}
}
/**
* 直链场景拉取任务摘要(仅抽屉展示,不挂工作台)。
*/
async function loadDetail(taskNo: string, options?: { silent?: boolean }) {
const silent = Boolean(options?.silent);
if (!silent) detailLoading.value = true;
try {
detail.value = await getWorkspaceShippingTask(taskNo);
} catch {
if (!silent) detail.value = null;
} finally {
if (!silent) detailLoading.value = false;
}
}
/**
* 列表 / 报表与(可选)直链摘要联动刷新。
*/
async function refreshAll(options?: { silent?: boolean }) {
await Promise.all([loadTodos(false, options), loadCounts()]);
if (isDirectTaskRoute.value && preferredTaskNo.value) {
await loadDetail(preferredTaskNo.value, options);
}
}
/**
* 打开订单处理工作台(Chat 主区 order-review;单 OT 全生命周期)。
* 任务中心仅作列表入口,禁止在本页履约写操作(STP 重试除外)。
*/
function openOrderProcessing(
item: TodoLike,
requestedStage?: Exclude<LifecycleStageCode, 'intake_parse'>,
) {
const runNo = String(item.review_run_no || '').trim();
if (!runNo) return;
const agentId = Number(item.owner_agent_id || chatAgentId.value || 0);
if (!agentId) return;
const query: Record<string, string> = {
mode: 'order-review',
run_no: runNo,
};
const stage = requestedStage || undefined;
if (!stage) return;
const entries = item.ui_state?.lifecycle_entries || [];
const entry = entries.find((candidate) => candidate.code === stage);
if (!entry || (entry.state !== 'current' && entry.state !== 'available')) return;
query.lifecycle_stage = stage;
const cid = String(item.conversation_id || '').trim();
if (cid) query.conversation_id = cid;
const caseNo = String(item.review_case_no || '').trim();
if (caseNo) query.case_no = caseNo;
// [PERF] 深链携带正式任务号,工作台挂载即可并行拉取任务详情,与 load() 重叠。
const taskNo = String(item.task_no || '').trim();
if (taskNo) query.task_no = taskNo;
void router.push({ path: `/chat/${agentId}`, query });
}
/** 打开对话中的接收解析工作面,复用批次进度中心的同一深链契约。 */
function openIntakeParse(item: TodoLike) {
const runNo = String(item.review_run_no || '').trim();
const agentId = Number(item.owner_agent_id || chatAgentId.value || 0);
if (!runNo || !agentId || item.ui_state?.intake_parse_authorized !== true) return;
const query: Record<string, string> = {
mode: 'order-review',
run_no: runNo,
lifecycle_stage: 'intake_parse',
};
const cid = String(item.conversation_id || '').trim();
if (cid) query.conversation_id = cid;
const caseNo = String(item.review_case_no || '').trim();
if (caseNo) query.case_no = caseNo;
void router.push({ path: `/chat/${agentId}`, query });
}
/**
* 打开对话「本次处理中」卡,聚焦未建 OT 的 Intake 材料。
*/
function openIntakeConversation(item: TodoLike) {
const agentId = Number(item.owner_agent_id || chatAgentId.value || 0);
if (!agentId) return;
const query: Record<string, string> = {};
const cid = String(item.conversation_id || '').trim();
if (cid) query.conversation_id = cid;
const intakeNo = String((item as ShippingTaskSummary).intake_no
|| (item as ShippingTaskSummary).todo_ref || '').trim();
if (intakeNo) query.intake_no = intakeNo;
void router.push({ path: `/chat/${agentId}`, query });
}
/**
* 可选深链:打开 Chat 会话查看上下文(非履约写入口)。
* Intake 项走会话聚焦;任务/复核项带任务号上下文。
*/
function handleDrawerOpenChat(item: TodoLike) {
const summary = item as ShippingTaskSummary;
if (summary.item_kind === 'order_intake' || (summary.intake_no && !summary.task_no)) {
openIntakeConversation(item);
return;
}
if (!chatAgentId.value) return;
const query: Record<string, string> = {};
const taskNo = String(item.task_no || '').trim();
const orderTaskNo = String(item.order_task_no || '').trim();
if (taskNo) query.task_id = taskNo;
if (orderTaskNo) query.focus_task_no = orderTaskNo;
const cid = String(item.conversation_id || '').trim();
if (/^[0-9a-f]{32}$/i.test(cid)) query.conversation_id = cid;
void router.push({ path: `/chat/${chatAgentId.value}`, query });
}
/**
* 选中列表项:仅更新选中态、query 并打开抽屉;不拉详情工作台。
*/
async function selectTodo(item: ShippingTaskSummary) {
selectedRef.value = todoItemKey(item);
detail.value = null;
drawerOpen.value = true;
const nextQuery: Record<string, string> = { ...route.query as Record<string, string> };
if (item.item_kind === 'review_case' || (item.review_run_no && !item.task_no)) {
delete nextQuery.task_no;
delete nextQuery.intake_no;
if (item.review_run_no) nextQuery.run_no = String(item.review_run_no);
} else if (item.item_kind === 'order_intake' || item.intake_no) {
delete nextQuery.task_no;
delete nextQuery.run_no;
if (item.intake_no) nextQuery.intake_no = String(item.intake_no);
} else if (item.task_no) {
delete nextQuery.run_no;
delete nextQuery.intake_no;
nextQuery.task_no = item.task_no;
}
void router.replace({
name: route.name || 'workspace-shipping-my-tasks',
params: route.params,
query: nextQuery,
});
}
/**
* 显式重试 STP 自动建单入队;与 ReviewWorkbenchFooter 共用 POST retry API。
*/
async function retryStpAutoCreate(item: TodoLike) {
const caseNo = String((item as ShippingTaskSummary).review_case_no || '').trim();
if (!caseNo || stpRetrying.value) return;
stpRetrying.value = true;
try {
await retryWorkspaceShippingOrderStpAutoCreate(caseNo);
msg.success(t('chat.shippingOrderReview.autoProgress.retryStpSuccess'));
await loadTodos();
} catch (error) {
const message = error instanceof BusinessError
? (error.message || t('chat.shippingOrderReview.autoProgress.retryStp'))
: t('chat.shippingOrderReview.autoProgress.retryStp');
msg.error(message);
} finally {
stpRetrying.value = false;
}
}
watch(bucket, () => {
selectedRef.value = null;
detail.value = null;
drawerOpen.value = false;
filterTodoCategory.value = 'all';
doneSubTab.value = 'upload_complete';
appliedFilters.value = {
...appliedFilters.value,
todo_category: '',
};
void loadTodos(true);
});
watch(doneSubTab, () => {
selectedRef.value = null;
detail.value = null;
drawerOpen.value = false;
tasks.value = [];
totalTasks.value = 0;
void loadTodos(true);
});
watch(lifecycleStageFilter, () => {
selectedRef.value = null;
drawerOpen.value = false;
});
watch(hasRunningWork, (running) => {
if (running) {
processingPollStartedAt = processingPollStartedAt ?? Date.now();
} else {
processingPollStartedAt = null;
}
});
watch(shouldAutoRefresh, () => {
scheduleAutoRefresh();
});
/**
* 回到前台时立刻静默拉一次,再按当前间隔重排。
*/
function pullOnForeground() {
const now = Date.now();
if (now - lastForegroundPullAt < 1000) {
scheduleAutoRefresh();
return;
}
lastForegroundPullAt = now;
void refreshAll({ silent: true }).finally(() => scheduleAutoRefresh());
}
/**
* 页面可见性变化时:可见则立刻刷新,隐藏则只拉长间隔。
*/
function onVisibilityChange() {
if (typeof document !== 'undefined' && document.visibilityState === 'visible') {
pullOnForeground();
return;
}
scheduleAutoRefresh();
}
function onWindowFocus() {
pullOnForeground();
}
onMounted(async () => {
await Promise.all([resolveChatAgent(), loadCounts(), loadTodos()]);
if (preferredTaskNo.value) {
if (isDirectTaskRoute.value) {
selectedRef.value = preferredTaskNo.value;
await loadDetail(preferredTaskNo.value);
if (detail.value) drawerOpen.value = true;
} else {
const hit = tasks.value.find((item) => String(item.task_no || '').toUpperCase() === preferredTaskNo.value);
if (hit) {
selectedRef.value = todoItemKey(hit);
drawerOpen.value = true;
} else {
selectedRef.value = preferredTaskNo.value;
await loadDetail(preferredTaskNo.value);
if (detail.value) drawerOpen.value = true;
}
}
}
document.addEventListener('visibilitychange', onVisibilityChange);
window.addEventListener('focus', onWindowFocus);
scheduleAutoRefresh();
});
onBeforeUnmount(() => {
stopAutoRefresh();
document.removeEventListener('visibilitychange', onVisibilityChange);
window.removeEventListener('focus', onWindowFocus);
});
</script>
<template>
<div class="space-y-5 animate-fade-in-up">
<div class="flex items-center justify-between gap-3">
<div>
<h2 class="text-2xl font-bold text-primary">{{ $t('workspace.shippingNotice.myTodos.title') }}</h2>
<p class="text-sm text-muted">{{ $t('workspace.shippingNotice.myTodos.subtitle') }}</p>
</div>
<button
type="button"
class="inline-flex items-center gap-1.5 rounded-xl border border-default px-3 py-1.5 text-sm font-medium text-secondary hover:bg-surface-soft"
@click="refreshAll()"
>
<RefreshCw class="h-3.5 w-3.5" />
{{ $t('workspace.shippingNotice.refresh') }}
</button>
</div>
<div class="flex flex-wrap gap-2">
<button
type="button"
class="rounded-xl px-3 py-1.5 text-sm font-medium"
:class="surface === 'todos' ? 'bg-brand-600 text-white' : 'border border-default text-secondary hover:bg-surface-soft'"
@click="surface = 'todos'"
>
{{ $t('workspace.shippingNotice.myTodos.title') }}
</button>
<button
type="button"
class="rounded-xl px-3 py-1.5 text-sm font-medium"
:class="surface === 'runs' ? 'bg-brand-600 text-white' : 'border border-default text-secondary hover:bg-surface-soft'"
@click="surface = 'runs'"
>
{{ $t('workspace.shippingNotice.myRuns.title') }}
</button>
</div>
<ShippingRunProgressTable v-if="surface === 'runs'" />
<template v-else>
<div class="flex flex-wrap gap-2">
<button
v-for="key in (['pending', 'processing', 'done'] as const)"
:key="key"
type="button"
class="rounded-xl px-3 py-1.5 text-sm font-medium"
:class="bucket === key ? 'bg-brand-600 text-white' : 'border border-default text-secondary hover:bg-surface-soft'"
:data-testid="`my-todos-bucket-${key}`"
@click="bucket = key"
>
{{ $t(`workspace.shippingNotice.myTodos.buckets.${key}`) }}
<span class="ml-1 opacity-80">({{ bucketCounts[key] }})</span>
</button>
</div>
<template v-if="bucket === 'done'">
<div class="flex flex-wrap gap-2" data-testid="my-todos-done-subtabs">
<button
type="button"
class="rounded-full px-3.5 py-1.5 text-sm font-medium"
:class="doneSubTab === 'upload_complete'
? 'bg-brand-600 text-white'
: 'border border-default text-secondary hover:bg-surface-soft'"
data-testid="my-todos-done-subtab-upload-complete"
@click="doneSubTab = 'upload_complete'"
>
{{ $t('workspace.shippingNotice.myTodos.subTabs.uploadComplete') }}
<span class="ml-1 font-mono text-xs opacity-80">{{ bucketCounts.done_counts?.upload_complete ?? 0 }}</span>
</button>
<button
type="button"
class="rounded-full px-3.5 py-1.5 text-sm font-medium"
:class="doneSubTab === 'reject_void'
? 'bg-brand-600 text-white'
: 'border border-default text-secondary hover:bg-surface-soft'"
data-testid="my-todos-done-subtab-reject-void"
@click="doneSubTab = 'reject_void'"
>
{{ $t('workspace.shippingNotice.myTodos.subTabs.rejectVoid') }}
<span class="ml-1 font-mono text-xs opacity-80">{{ bucketCounts.done_counts?.reject_void ?? 0 }}</span>
</button>
</div>
</template>
<ShippingStageTabs
v-else-if="bucket === 'pending'"
v-model="lifecycleStageFilter"
:counts="bucketCounts.stage_counts"
/>
<div
v-if="bucket !== 'done' || doneSubTab === 'reject_void'"
class="flex flex-wrap items-end gap-3 rounded-2xl border border-default bg-surface px-4 py-3"
>
<label v-if="bucket === 'pending'" class="space-y-1">
<span class="text-xs font-medium text-muted">{{ $t('workspace.shippingNotice.myTodos.filters.todoCategory') }}</span>
<select v-model="filterTodoCategory" class="input-field text-sm min-w-[9rem]">
<option value="all">{{ $t('workspace.shippingNotice.myTodos.filters.all') }}</option>
<option value="review">{{ $t('workspace.shippingNotice.myTodos.filters.review') }}</option>
<option value="exception">{{ $t('workspace.shippingNotice.myTodos.filters.exception') }}</option>
<option value="manual_upload">{{ $t('workspace.shippingNotice.myTodos.filters.manualUpload') }}</option>
<option value="intake_parse">{{ $t('workspace.shippingNotice.myTodos.filters.intakeParse') }}</option>
</select>
</label>
<label class="space-y-1 flex-1 min-w-[10rem]">
<span class="text-xs font-medium text-muted">{{ $t('workspace.shippingNotice.myTodos.filters.customer') }}</span>
<input
v-model="filterCustomer"
type="text"
class="input-field text-sm w-full"
:placeholder="$t('workspace.shippingNotice.myTodos.filters.customerPlaceholder')"
@keyup.enter="applyFilters"
/>
</label>
<label class="space-y-1 flex-1 min-w-[10rem]">
<span class="text-xs font-medium text-muted">{{ $t('workspace.shippingNotice.myTodos.filters.taskNo') }}</span>
<input
v-model="filterTaskNo"
type="text"
class="input-field text-sm w-full font-mono uppercase"
:placeholder="$t('workspace.shippingNotice.myTodos.filters.taskNoPlaceholder')"
@keyup.enter="applyFilters"
/>
</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="applyFilters"
>
{{ $t('workspace.shippingNotice.myTodos.filters.apply') }}
</button>
<button
type="button"
class="rounded-xl border border-default px-3 py-1.5 text-sm font-medium text-secondary hover:bg-surface-soft disabled:opacity-50"
:disabled="loading"
@click="resetFilters"
>
{{ $t('workspace.shippingNotice.myTodos.filters.reset') }}
</button>
</div>
</div>
<ShippingDoneLineReport
v-if="isDoneLineReportView"
v-model:filters="doneLineFilterDraft"
:items="doneLines"
:total="doneLineTotal"
:page="doneLinePage"
:page-size="50"
:loading="doneLineLoading"
:export-busy="doneLineExportBusy"
@apply="applyDoneLineFilters"
@page-change="(page) => { doneLinePage = page; void loadDoneLines(); }"
@export="exportDoneLines"
/>
<template v-else>
<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="!filteredTasks.length" class="rounded-2xl border border-dashed border-default py-10 text-center text-sm text-muted">
{{ $t('workspace.shippingNotice.myTodos.empty') }}
</div>
<template v-else>
<ShippingTaskTable
:items="filteredTasks"
:selected-key="selectedRef"
:selectable="bucket === 'pending'"
:selected-business-nos="selectedBusinessNos"
:batch-busy="batchActionBusy"
:terminal-badge="bucket === 'done' && doneSubTab === 'reject_void' ? 'reject_void' : null"
@select="selectTodo"
@toggle="toggleNoticeSelection"
@toggle-all="toggleAllSelectableRows"
@clear-selection="selectedBusinessNos = []"
@batch="runNoticeBatchAction"
/>
<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="currentPage <= 1 || loading"
@click="currentPage -= 1; loadTodos()"
>
{{ $t('workspace.shippingNotice.pagination.previous') }}
</button>
<span>{{ currentPage }}/{{ totalPages }}</span>
<button
type="button"
class="rounded-lg border border-default px-2 py-1 disabled:opacity-50"
:disabled="currentPage >= totalPages || loading"
@click="currentPage += 1; loadTodos()"
>
{{ $t('workspace.shippingNotice.pagination.next') }}
</button>
</div>
</template>
</template>
</template>
<ShippingTaskDrawer
:open="drawerVisible"
:item="drawerItem"
:loading="detailLoading && isDirectTaskRoute"
:chat-agent-id="chatAgentId"
:stp-retrying="stpRetrying"
@close="drawerOpen = false"
@open-intake="openIntakeParse"
@open-processing="(item, stage) => openOrderProcessing(item, stage)"
@open-chat="handleDrawerOpenChat"
@retry-stp="retryStpAutoCreate"
/>
</div>
</template>