/** * features/chat/shipping/useShippingProcessingWorkItem.ts * 用途:按 work_item_type + work_item_no 轮询统一 ShippingProcessingProjection。 * 依赖:shipping.api(已在边界 normalize)、mergeWorkbenchProcessingProjection。 * 逻辑:复核台 / 任务中心双读;工作台可启用 monotonicProgressVersion;404 时保持 null。 * 禁止对本 composable 再跑 normalize:API 已输出 camelCase,二次 normalize * 只认 snake_case 会把 workItemNo 读空并整包洗成 null(右卡永久「获取中/待机」)。 */ import { getCurrentInstance, onBeforeUnmount, ref, watch, type MaybeRefOrGetter, type Ref, toValue, } from 'vue'; import { BusinessError } from '@/shared/api/client'; import { mergeWorkbenchProcessingProjection } from '@/features/shipping-progress/mergeProcessingProjection'; import { getWorkspaceShippingProcessingWorkItem } from '../api/shipping.api'; import type { ShippingProcessingProjection } from '../types/shipping.api.types'; const DEFAULT_POLL_MS = 3000; const TERMINAL_STATUSES = new Set([ 'completed', 'cancelled', ]); /** 用户态“中断/失败/等待人工”状态:结果不会自行变化,停止轮询(约定:中断不轮询)。 */ const INTERRUPTED_USER_STATUSES = new Set([ 'waiting_human', 'failed', 'interrupted', ]); export type ShippingProcessingWorkItemTypeArg = 'order_intake' | 'order_task'; /** * 轮询单个统一处理工作项投影。 * * @param workItemType - order_intake | order_task * @param workItemNo - Intake 编号或 OT 编号(MaybeRef) * @param options.enabled - 是否启用;options.pollMs - 轮询间隔;options.continuousPolling - 是否由本 composable 持续轮询; * options.monotonicProgressVersion - 仅工作台:旧 progress_version 不覆盖本地 * @returns projection / loading / error / refresh / stop */ export function useShippingProcessingWorkItem( workItemType: ShippingProcessingWorkItemTypeArg, workItemNo: MaybeRefOrGetter, options: { enabled?: MaybeRefOrGetter; pollMs?: number; /** false 时仅由调用方显式 refresh;用于已有页面级协调轮询的工作台。 */ continuousPolling?: boolean; /** 仅订单处理工作台开启;任务中心保持默认 false。 */ monotonicProgressVersion?: boolean; } = {}, ): { projection: Ref; loading: Ref; error: Ref; refresh: () => Promise; stop: () => void; } { const projection = ref(null); const loading = ref(false); const error = ref(null); let timer: ReturnType | null = null; let generation = 0; let stopped = false; let refreshInFlight: { no: string; promise: Promise } | null = null; const pollMs = options.pollMs ?? DEFAULT_POLL_MS; const continuousPolling = options.continuousPolling !== false; const monotonic = Boolean(options.monotonicProgressVersion); /** * 清除轮询定时器。 */ function clearTimer() { if (timer != null) { window.clearTimeout(timer); timer = null; } } /** * 停止轮询并递增代际,丢弃在途响应写回。 */ function stop() { stopped = true; generation += 1; clearTimer(); } /** * 拉取一次投影;失败保留上一帧。 * 核心逻辑:直接消费 API 已 normalize 的 camelCase 投影,禁止二次 normalize。 */ async function refresh(): Promise { const no = String(toValue(workItemNo) || '').trim(); if (refreshInFlight?.no === no) { await refreshInFlight.promise; return; } const enabled = options.enabled == null ? true : Boolean(toValue(options.enabled)); if (!enabled || !no) { projection.value = null; error.value = null; clearTimer(); return; } const gen = generation; loading.value = true; const request = (async () => { try { // [STEP 1] API 边界已完成 snake→camel;此处不得再 normalize(会读空 workItemNo → null)。 const incoming = await getWorkspaceShippingProcessingWorkItem(workItemType, no); if (stopped || gen !== generation) return; // [STEP 2] 工作台单调合并:旧包丢弃;新包整包替换;同版本浅合并。任务中心不启用。 projection.value = monotonic ? mergeWorkbenchProcessingProjection(projection.value, incoming) : incoming; error.value = null; clearTimer(); const next = projection.value; const userStatus = String(next?.userStatus || '').trim().toLowerCase(); const stoppedByState = Boolean(next) && ( TERMINAL_STATUSES.has(next!.status) || INTERRUPTED_USER_STATUSES.has(userStatus) ); if (continuousPolling && next && !stoppedByState && !stopped) { timer = window.setTimeout(() => { void refresh(); }, pollMs); } } catch (err) { if (stopped || gen !== generation) return; // 404 / 业务不存在:清空投影但不抛到页面主流程。 if (err instanceof BusinessError && (err.status === 404 || err.code?.includes('NOT_FOUND'))) { projection.value = null; error.value = null; clearTimer(); return; } error.value = err instanceof BusinessError ? err.message : 'network_recoverable'; clearTimer(); if (continuousPolling && !stopped) { timer = window.setTimeout(() => { void refresh(); }, pollMs); } } finally { if (gen === generation) loading.value = false; } })(); refreshInFlight = { no, promise: request }; try { await request; } finally { if (refreshInFlight?.promise === request) refreshInFlight = null; } } watch( () => [String(toValue(workItemNo) || ''), Boolean(toValue(options.enabled ?? true))] as const, ([no, enabled], _prev, onCleanup) => { stopped = false; generation += 1; clearTimer(); onCleanup(() => { clearTimer(); }); if (!enabled || !no) { projection.value = null; error.value = null; return; } // OT/PDF 切换时先清空旧投影,避免新请求完成前继续展示第一份 PDF 的状态。 projection.value = null; error.value = null; void refresh(); }, { immediate: true }, ); if (getCurrentInstance()) { onBeforeUnmount(() => { stop(); }); } return { projection, loading, error, refresh, stop, }; }