/** * features/chat/shipping/useShippingProcessingWorkItem.ts * 用途:按 work_item_type + work_item_no 轮询统一 ShippingProcessingProjection。 * 依赖:shipping.api、normalizeShippingProcessing、mergeWorkbenchProcessingProjection。 * 逻辑:复核台 / 任务中心双读;工作台可启用 monotonicProgressVersion;404 时保持 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'; import { normalizeShippingProcessingProjection } from './normalizeShippingProcessing'; const DEFAULT_POLL_MS = 3000; const TERMINAL_STATUSES = new Set([ 'completed', 'cancelled', ]); export type ShippingProcessingWorkItemTypeArg = 'order_intake' | 'order_task'; /** * 轮询单个统一处理工作项投影。 * * @param workItemType - order_intake | order_task * @param workItemNo - Intake 编号或 OT 编号(MaybeRef) * @param options.enabled - 是否启用;options.pollMs - 轮询间隔; * options.monotonicProgressVersion - 仅工作台:旧 progress_version 不覆盖本地 * @returns projection / loading / error / refresh / stop */ export function useShippingProcessingWorkItem( workItemType: ShippingProcessingWorkItemTypeArg, workItemNo: MaybeRefOrGetter, options: { enabled?: MaybeRefOrGetter; pollMs?: number; /** 仅订单处理工作台开启;任务中心保持默认 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 monotonic = Boolean(options.monotonicProgressVersion); /** * 清除轮询定时器。 */ function clearTimer() { if (timer != null) { window.clearTimeout(timer); timer = null; } } /** * 停止轮询并递增代际,丢弃在途响应写回。 */ function stop() { stopped = true; generation += 1; clearTimer(); } /** * 拉取一次投影;失败保留上一帧。 */ 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 { const raw = await getWorkspaceShippingProcessingWorkItem(workItemType, no); if (stopped || gen !== generation) return; const normalized = normalizeShippingProcessingProjection(raw); // [STEP] 工作台单调合并:旧包丢弃;新包整包替换;同版本浅合并。任务中心不启用。 projection.value = monotonic ? mergeWorkbenchProcessingProjection(projection.value, normalized) : normalized; error.value = null; clearTimer(); const next = projection.value; if (next && !TERMINAL_STATUSES.has(next.status) && !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 (!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, }; }