/** * features/chat/composables/useChatTransfer.ts * 用途:在途仓自动调拨聊天编排入口——匹配创建/恢复、选择范围(按明细 item_id)、 * 按行直接生成执行 Run(D8 异步 202)、Run 轮询与结果恢复(D9 调拨单清单)、 * 人工重试/关闭、恢复处理(重查)、下载。 * 依赖:transfer.api、transfer.types、useMessage、Vue refs/computed/effect scope。 * 逻辑:前端只消费稳定 DTO;Run 是异步真相源——提交只拿 {run_no,status:'queued'}, * 进度/结果由 4s 轮询 getTransferRun 获取,终态(run.status)即停,刷新/重进由 GET 恢复; * 来源收料 RPA 同为异步收口——重试 202 后投影 fetching,存在 fetching 来源时 * 4s 轮询 GET /sources 直至全部脱离 fetching(ready/failed/expired/none); * 勾选集合以明细行 item_id 为键(历史回放行无 item_id 不可选); * 恢复处理 = 按明细 id 重查库存(batch-requery 是唯一后端); * 防重复点击(busy);错误统一 useMessage 展示 BusinessError。 */ import { computed, getCurrentScope, onScopeDispose, ref, type Ref } from 'vue'; import i18n from '@/i18n'; import { useMessage } from '@/shared/composables/useMessage'; import { batchManualCloseTransferItems, batchRequeryTransferItems, cancelTransferRun, createTransferMatching, downloadTransferErpInventory, downloadTransferExceptions, downloadTransferReceiptFiles, executeTransferItems, getTransferBacklogSummary, getTransferMatching, getTransferRun, listExecutableTransferItems, listTransferBacklog, listTransferSources, manualCloseTransferItem, retryTransferItem, retryTransferSourceRpa, } from '../api/transfer.api'; import type { TransferBacklogItem, TransferBacklogSummary, TransferBatchResult, TransferMatchingDetail, TransferMatchingItem, TransferMatchingSummary, TransferRunResult, TransferSourceOption, TransferSourceProgress, TransferType, } from '../types/transfer.types'; /** Run 轮询间隔(ms):D9 融合卡「调拨单清单=进度=结果」按 4s 定时拉取 GET /runs/{run_no} */ const RUN_POLL_INTERVAL_MS = 4000; /** 轮询连续失败停止上限:防后端持续不可用时无限空转;单次失败保留旧值继续下一轮 */ const RUN_POLL_MAX_CONSECUTIVE_FAILURES = 3; /** 来源状态轮询间隔(ms):来源选择卡存在抓取中来源时按 4s 重拉 GET /sources(与 Run 轮询同节奏) */ const SOURCE_POLL_INTERVAL_MS = 4000; /** 来源轮询连续失败停止上限(口径同 Run 轮询):防后端持续不可用时无限空转 */ const SOURCE_POLL_MAX_CONSECUTIVE_FAILURES = 3; /** * Run 轮询终态集合(口径对齐后端 status.py RUN_TRANSITIONS 收尾): * executing 只流向 success / partial_failed / failed / cancelled—— * success=全单成功族;partial_failed/failed=存在未成单(唯一出边=人工 retrigger, * 由重触发流程重新发起轮询,不作为轮询继续条件);cancelled=人工停止的严格终态 * (防止取消后轮询空转)。「单全终态」由后端 finalize_run 汇总进 run.status, * 前端只判 run.status,无需逐单推断。 */ const TERMINAL_RUN_STATUSES: ReadonlySet = new Set([ 'success', 'partial_failed', 'failed', 'cancelled', ]); /** * Run 是否已处终态(轮询停止判据,口径同 TERMINAL_RUN_STATUSES)。 * 融合卡/视图在挂载与恢复场景用其决定「原位渲染」还是「继续轮询」。 */ export function isTerminalRunStatus(status: string | null | undefined): boolean { return typeof status === 'string' && TERMINAL_RUN_STATUSES.has(status); } export function useChatTransfer() { const { error: notifyError } = useMessage(); const matchingId = ref(null); const matching = ref(null); const items = ref([]); const sources = ref([]); const runNo = ref(null); const run = ref(null); const backlog = ref([]); const backlogSummary = ref(null); const executableItems = ref([]); const sourceOptions = ref([]); const selected = ref>(new Set()); const busy = ref(false); const error = ref(''); // Run 轮询状态(实例级闭包):generation 使被停止/替换轮次的在途回调失效,防止僵尸轮询复活 let pollTimer: ReturnType | null = null; let pollGeneration = 0; let pollConsecutiveFailures = 0; // 轮询连接状态(交互细则 #2:单次失败保留旧值继续轮询,连续失败显示「连接中…」不清空画面) const pollConnecting = ref(false); // 来源状态轮询状态(实例级闭包,generation 语义同 Run 轮询): // 收料 RPA 是异步回调收口(重试 202 后状态先投影 fetching,终态靠后端回调落库), // 前端必须轮询 GET /sources 才能把 抓取中→ready/failed 反映到来源选择卡 let sourcePollTimer: ReturnType | null = null; let sourcePollGeneration = 0; let sourcePollConsecutiveFailures = 0; /** 全部可执行明细行 id(阻断/未成熟/无 item_id 的历史行不可勾选) */ const executableItemIds = computed(() => items.value .filter((item) => item.result === 'executable' && item.item_id != null) .map((item) => item.item_id as number), ); const selectedCount = computed(() => selected.value.size); const estimatedQuantity = computed(() => matching.value?.estimated_transfer_quantity ?? '0'); /** 创建匹配(缺文件时来源级阶段展示等待/失败);transferType 决定收料数据范围,缺省在途仓至HUB仓 */ async function createMatching( sourceCodes: string[], businessDate?: string, dateRange?: { from?: string; to?: string }, transferType?: TransferType, ) { busy.value = true; error.value = ''; try { const summary = await createTransferMatching({ source_codes: sourceCodes, business_date: businessDate, receipt_date_from: dateRange?.from, receipt_date_to: dateRange?.to, transfer_type: transferType, }); matchingId.value = summary.matching_id; await refreshMatching(); return summary; } catch (e) { error.value = String(e); throw e; } finally { busy.value = false; } } /** 恢复匹配进度(页面刷新/会话恢复) */ async function refreshMatching() { if (!matchingId.value) return null; const detail = await getTransferMatching(matchingId.value); applyDetail(detail); return detail; } function applyDetail(detail: TransferMatchingDetail) { matching.value = detail.summary; items.value = detail.items; sources.value = detail.sources; // 默认勾选全部可执行明细行(按 item_id);阻断/未成熟/无 item_id 不可选 selected.value = new Set( detail.items .filter((item) => item.result === 'executable' && item.item_id != null) .map((item) => item.item_id as number), ); } function toggleSelect(itemId: number, checked: boolean) { const next = new Set(selected.value); if (checked) next.add(itemId); else next.delete(itemId); selected.value = next; } /** * 按勾选明细行直接生成调拨单(item-centric:门禁在后端,失败抛 BusinessError)。 * D8 异步 202:提交只拿 { run_no, status: 'queued' }——先 refreshRun 打底一帧, * 随后自动开始 4s 轮询接管进度/结果,直至 run.status 落入终态集合。 */ async function execute() { if (selected.value.size === 0) { // [P2-2] 组合式函数可能运行在组件 setup 之外(单测直调),经 i18n.global 取四语言文案 notifyError(i18n.global.t('chat.transfer.execute.noSelection')); return null; } busy.value = true; error.value = ''; try { const result = await executeTransferItems([...selected.value]); runNo.value = result.run_no; await refreshRun(); // 提交成功即自动轮询(沿既有交互流:busy 复位后卡片可直接消费 run 更新) startRunPolling(result.run_no, () => {}); return result; } catch (e) { error.value = String(e); throw e; } finally { busy.value = false; } } /** 恢复 Run 结果与调拨单清单(D9:run 含 orders 调拨单清单,终态 Run 亦同口径投影)。 * @param runNoArg 显式 run_no(融合卡自驱动轮询用自有实例按卡内 run_no 拉取); * 缺省沿用实例 runNo(既有提交/恢复路径不变)。 */ async function refreshRun(runNoArg?: string) { const target = runNoArg ?? runNo.value; if (!target) return null; const data = await getTransferRun(target); run.value = data; return data; } /** * 停止当前 Run 轮询(幂等,即 startRunPolling 返回的手动句柄)。 * 核心逻辑:递增 generation 使在途请求的回调失效(防止僵尸轮询复活), * 并清掉尚未触发的定时器;重复调用安全。 */ function stopRunPolling() { pollGeneration += 1; if (pollTimer !== null) { clearTimeout(pollTimer); pollTimer = null; } } /** * 启动 Run 轮询(D8 异步 202:提交只拿 run_no,进度/结果靠轮询调拨单清单直至终态)。 * * 【AI 触发时机】:execute 提交拿到 run_no 后自动调用;或页面刷新/会话恢复 * 拿到未终态 run_no 时由调用方手动调用——融合卡靠 onUpdate 逐单亮状态与 ERP 单号。 * * 核心逻辑:[STEP 1] 停掉本实例既有轮询(单实例单轮询,重复调用先停旧轮); * [STEP 2] 间隔制 4s 定时 GET getTransferRun——起始不立即打点(提交流程已 refreshRun); * [STEP 3] 成功才覆盖 run 旧值并回吐 onUpdate;run.status 落入 TERMINAL_RUN_STATUSES 即停; * [STEP 4] 单次失败保留旧值(不清 run、不置 error)继续下一轮;连续失败达 * RUN_POLL_MAX_CONSECUTIVE_FAILURES 上限才停止并按既有模式落 error.value。 * 清理:作用域销毁自动停止(onScopeDispose 在组合式函数创建时注册—— * execute/手动调用都发生在 setup 之后的无作用域上下文,不能在此刻注册);返回手动 stop 句柄。 * * @param pollRunNo - Run 编号(必传;来自 execute 响应或回放 payload 的 run_no; * 参数名带 poll 前缀避免遮蔽外层同名 runNo ref) * @param onUpdate - 每轮成功拉取的回调(参数为最新 TransferRunResult,含 orders; * 业务约束:禁止在该回调内再次调用 startRunPolling,避免同实例轮询互相顶替) * @returns stop 手动停止句柄(幂等,可重复调用) */ function startRunPolling(pollRunNo: string, onUpdate: (run: TransferRunResult) => void): () => void { stopRunPolling(); const generation = ++pollGeneration; pollConsecutiveFailures = 0; pollConnecting.value = false; // 新轮询起点:连接视为正常,失败帧再置位 const scheduleNext = () => { if (generation !== pollGeneration) return; pollTimer = setTimeout(() => { void pollOnce(); }, RUN_POLL_INTERVAL_MS); }; const pollOnce = async () => { if (generation !== pollGeneration) return; try { const data = await getTransferRun(pollRunNo); if (generation !== pollGeneration) return; pollConsecutiveFailures = 0; pollConnecting.value = false; // 成功帧恢复连接态(保留旧值→新值,画面不清空) run.value = data; onUpdate(data); if (TERMINAL_RUN_STATUSES.has(data.status)) { // [P1 双保险] retrigger 窗口不误停:人工重新触发(result_unknown 单)受理时, // 后端已同步把 run.status 置回 executing(T10 同步段),故「retrigger 已受理但 // worker 未领取」的瞬态不会以陈旧终态落入本判定而提前停轮; // 前端半(融合卡 confirmRetrigger)在进入本间隔轮询前先 refreshRun 打一帧兜底。 stopRunPolling(); return; // 终态:不再排下一轮 } } catch (e) { if (generation !== pollGeneration) return; pollConsecutiveFailures += 1; pollConnecting.value = true; // 连续失败显示「连接中…」;终限停止后保留该提示 if (pollConsecutiveFailures >= RUN_POLL_MAX_CONSECUTIVE_FAILURES) { error.value = String(e); stopRunPolling(); return; } // 单次失败:保留旧值,静默进入下一轮 } scheduleNext(); }; scheduleNext(); return stopRunPolling; } // 卸载/作用域销毁清理:必须在组合式函数创建时(setup 作用域内)注册; // stopRunPolling/stopSourcePolling 均幂等,轮询未启动/已停止时调用为空操作。 if (getCurrentScope()) onScopeDispose(() => { stopRunPolling(); stopSourcePolling(); }); /** 请求停止剩余任务(run → cancelled 后本轮轮询一并停止,避免空转) */ async function cancelRun(reason: string) { if (!runNo.value) return null; const result = await cancelTransferRun(runNo.value, reason); await refreshRun(); stopRunPolling(); return result; } /** 人工重试异常项 */ async function retry(itemId: number) { const result = await retryTransferItem(itemId); await refreshMatching(); return result; } /** 人工关闭异常项 */ async function manualClose(itemId: number, reason: string) { const result = await manualCloseTransferItem(itemId, reason); await refreshMatching(); return result; } /** 下载收料来源文件(zip) */ async function downloadReceiptFiles() { if (!runNo.value) return null; const result = await downloadTransferReceiptFiles(runNo.value); saveBlob(result.blob, result.filename ?? `receipt-files-${runNo.value}.zip`); return result; } /** 下载匹配冻结的 ERP 库存表(csv) */ async function downloadErpInventory() { if (!runNo.value) return null; const result = await downloadTransferErpInventory(runNo.value); saveBlob(result.blob, result.filename ?? `external-inventory-${runNo.value}.csv`); return result; } /** 下载七 Sheet 异常 Excel */ async function downloadExceptions() { if (!runNo.value) return null; const result = await downloadTransferExceptions(runNo.value); saveBlob(result.blob, result.filename ?? `transfer-exceptions-${runNo.value}.xlsx`); return result; } /** 加载来源实例列表(决策 3:平台仅分组,每来源附收料文件状态); * 载入后按快照同步来源轮询:存在 fetching 来源即自动接管(触发重试后 RPA 异步收口, * 终态 ready/failed 只有重拉 /sources 才可见——否则来源卡永远停在「抓取中」)。 */ async function loadSources() { sourceOptions.value = await listTransferSources(); syncSourcePolling(); return sourceOptions.value; } /** * 停止来源状态轮询(幂等):递增 generation 使在途回调失效并清掉未触发定时器。 * 【AI 触发时机】:离开来源选择卡(确认匹配切匹配卡/回放替换 payload)与 * 作用域销毁/reset 时由调用方调用,防止离屏后继续请求。 */ function stopSourcePolling() { sourcePollGeneration += 1; if (sourcePollTimer !== null) { clearTimeout(sourcePollTimer); sourcePollTimer = null; } } /** * 启动来源状态轮询(4s 间隔制,语义对齐 Run 轮询):按 interval 重拉 GET /sources, * 成功才覆盖 sourceOptions;全部来源脱离 fetching(ready/failed/expired/none 投影) * 即停止;单次失败保留旧值继续下一轮,连续失败达上限才停止(不落 error——来源卡 * 有手动重试/刷新兜底,避免轮询失败噪声打断主流程)。 * 起始不立即打点:两条进入路径(loadSources 挂载恢复 / retrySourceRpa 触发后)都已有新鲜一帧。 */ function startSourcePolling() { stopSourcePolling(); const generation = ++sourcePollGeneration; sourcePollConsecutiveFailures = 0; const scheduleNext = () => { if (generation !== sourcePollGeneration) return; sourcePollTimer = setTimeout(() => { void pollOnce(); }, SOURCE_POLL_INTERVAL_MS); }; const pollOnce = async () => { if (generation !== sourcePollGeneration) return; try { const options = await listTransferSources(); if (generation !== sourcePollGeneration) return; sourcePollConsecutiveFailures = 0; sourceOptions.value = options; // 直接判服务端快照(不经 syncSourcePolling,防与既有轮询互相顶替) if (!options.some((source) => source.file_status === 'fetching')) { stopSourcePolling(); return; } } catch { if (generation !== sourcePollGeneration) return; sourcePollConsecutiveFailures += 1; if (sourcePollConsecutiveFailures >= SOURCE_POLL_MAX_CONSECUTIVE_FAILURES) { stopSourcePolling(); return; } // 单次失败:保留旧值,静默进入下一轮 } scheduleNext(); }; scheduleNext(); } /** 按当前来源快照同步轮询启停:有抓取中来源→启动(重复调用先停旧轮),无→停止。 */ function syncSourcePolling() { if (sourceOptions.value.some((source) => source.file_status === 'fetching')) { startSourcePolling(); } else { stopSourcePolling(); } } /** 对指定来源重新触发收料 RPA 抓取,并刷新来源状态(触发后 202 + fetching, * loadSources 观察到 fetching 即自动开始来源轮询,RPA 回调收口后状态自动刷新) */ async function retrySourceRpa(sourceCode: string) { const status = await retryTransferSourceRpa(sourceCode); await loadSources(); return status; } /** 加载待处理异常列表与汇总 */ async function loadBacklog() { const [items, summary] = await Promise.all([listTransferBacklog(), getTransferBacklogSummary()]); backlog.value = items; backlogSummary.value = summary; return { items, summary }; } /** 加载可调拨明细(全局可执行行队列;恢复后的行会出现在这里) */ async function loadExecutableItems() { const payload = await listExecutableTransferItems(); executableItems.value = payload.items; return executableItems.value; } /** 批量重查库存(单行隔离,结果由调用方刷新列表后展示) */ async function batchRequery(itemIds: number[]): Promise { return batchRequeryTransferItems(itemIds); } /** 恢复处理(行级/多选):恢复语义 = 按明细 id 重查库存(batch-requery 唯一后端); * 返回批量结果,由视图统计 recovered(status=ready_to_execute)与仍阻断数。 */ async function resume(itemIds: number[]): Promise { return batchRequeryTransferItems(itemIds); } /** 批量人工关闭(原因整批共用;单行隔离) */ async function batchManualClose(itemIds: number[], reason: string): Promise { return batchManualCloseTransferItems(itemIds, reason); } function saveBlob(blob: Blob, filename: string) { const url = URL.createObjectURL(blob); const link = document.createElement('a'); link.href = url; link.download = filename; link.click(); URL.revokeObjectURL(url); } function reset() { stopRunPolling(); stopSourcePolling(); matchingId.value = null; matching.value = null; items.value = []; sources.value = []; runNo.value = null; run.value = null; backlog.value = []; backlogSummary.value = null; executableItems.value = []; sourceOptions.value = []; selected.value = new Set(); error.value = ''; } return { matchingId, matching, items, sources, runNo, run, pollConnecting, backlog, backlogSummary, executableItems, sourceOptions, selected, selectedCount, executableItemIds, estimatedQuantity, busy, error, createMatching, refreshMatching, toggleSelect, execute, refreshRun, startRunPolling, stopRunPolling, startSourcePolling, stopSourcePolling, cancelRun, retry, manualClose, loadSources, retrySourceRpa, loadBacklog, loadExecutableItems, batchRequery, resume, batchManualClose, downloadReceiptFiles, downloadErpInventory, downloadExceptions, reset, }; } export type ChatTransfer = ReturnType; export type { Ref };