refactor(shipping-notice): 重构货代发货通知状态管理,移除废弃的process_status字段

统一货代发货通知的业务阶段为四个标准阶段:接收解析、订单复核、发货准备、上传完成
设置 ui_state 为前端唯一状态数据源,不再依赖 process_status 驱动业务流程
删除 shipping_notices 表的废弃 process_status 列及对应复合索引,新增数据库迁移脚本
替换全栈代码中所有对 process_status 的引用为生命周期、上传状态等领域字段
更新相关文档、测试用例与前端展示逻辑适配新的状态管理规则
This commit is contained in:
hugo committed 2026-08-15 10:19:10 +08:00
1 parent 6684e7181a
commit 5ef8329bd8
178 files changed
+5091 -1734

No files matched your search

@@ -36,10 +36,30 @@ import {
resolveConversationProcessingFromUnified,
} from './conversationProcessingProjection';
const FOREGROUND_POLL_MS = 2000;
const BACKGROUND_POLL_MS = 8000;
const FIRST_ACTIVE_POLL_MS = 2000;
const MID_ACTIVE_POLL_MS = 5000;
const LONG_ACTIVE_POLL_MS = 10000;
const BACKGROUND_POLL_MS = 30000;
const REQUEST_TIMEOUT_MS = 10000;
const MAX_BACKOFF_MS = 8000;
const MAX_BACKOFF_MS = 30000;
const SNAPSHOT_CACHE_LIMIT = 20;
type ProjectionSnapshot = {
conversationId: string;
processing: ConversationProcessingProjection;
workItems: ShippingProcessingProjection[];
semanticKey: string;
receivedAt: number;
lastAccessedAt: number;
processingStartedAt: number | null;
};
export type ProcessingPollContext = {
elapsedMs: number;
visibility: DocumentVisibilityState | 'visible' | 'hidden';
hasProcessing: boolean;
failureCount: number;
};
export type UseShippingNoticeWorkflowOptions = {
/** 当前会话 ID;空则停轮询并清空。 */
@@ -61,6 +81,12 @@ export type UseShippingNoticeWorkflowReturn = {
manualRefreshing: Ref<boolean>;
/** 后台静默轮询中(不显示 loading,不禁用按钮)。 */
polling: Ref<boolean>;
/** 当前会话任意 Projection GET 在途;不得作为整卡遮罩条件。 */
isFetching: Ref<boolean>;
/** 当前会话已有成功 Projection 时的刷新状态。 */
isRefreshing: Ref<boolean>;
/** 当前会话最后一次成功 Projection 接收时间。 */
snapshotUpdatedAt: Ref<number | null>;
error: Ref<string | null>;
refresh: () => Promise<void>;
focusConversationTask: (taskNo: string) => Promise<void>;
@@ -84,26 +110,22 @@ function readOption<T>(source: MaybeRefOrGetter<T>): T {
* 按页面可见性 + 业务状态选择轮询间隔。
* 分层策略:系统处理中 2s;待人工复核 30s;后台标签页 8s(若仍需轮询)。
*/
function resolvePollMs(
processing?: ConversationProcessingProjection | null,
): number {
if (typeof document !== 'undefined' && document.visibilityState === 'hidden') {
return BACKGROUND_POLL_MS;
}
const processingCount = Number(
processing?.summary?.processing || processing?.processing?.length || 0,
);
if (processingCount > 0) return FOREGROUND_POLL_MS;
return FOREGROUND_POLL_MS;
export function resolveProcessingPollIntervalMs(context: ProcessingPollContext): number | null {
if (!context.hasProcessing) return null;
if (context.failureCount > 0) return resolveProcessingPollBackoffMs(context.failureCount);
if (context.visibility === 'hidden') return BACKGROUND_POLL_MS;
if (context.elapsedMs < 15000) return FIRST_ACTIVE_POLL_MS;
if (context.elapsedMs < 60000) return MID_ACTIVE_POLL_MS;
return LONG_ACTIVE_POLL_MS;
}
/**
* 失败退避:2s → 4s → 8s(封顶)。
* 失败退避:10s → 20s → 30s(封顶)。
* @param failureCount - 连续失败次数(≥1)
*/
export function resolveProcessingPollBackoffMs(failureCount: number): number {
const n = Math.max(1, Math.floor(failureCount));
return Math.min(FOREGROUND_POLL_MS * (2 ** (n - 1)), MAX_BACKOFF_MS);
return Math.min(LONG_ACTIVE_POLL_MS * (2 ** (n - 1)), MAX_BACKOFF_MS);
}
/**
@@ -136,20 +158,84 @@ export function useShippingNoticeWorkflow(
const manualRefreshing = ref(false);
const polling = ref(false);
const error = ref<string | null>(null);
const snapshotUpdatedAt = ref<number | null>(null);
const isFetching = ref(false);
const snapshots = new Map<string, ProjectionSnapshot>();
const loading = computed(() => (
initialLoading.value || manualRefreshing.value || polling.value
));
const isRefreshing = computed(() => isFetching.value && processing.value !== null);
let pollTimer: ReturnType<typeof setTimeout> | null = null;
let pollGeneration = 0;
let requestController: AbortController | null = null;
let requestGeneration = 0;
const requestGenerations = new Map<string, number>();
let inFlightRefresh: { conversationId: string; promise: Promise<void> } | null = null;
let failureCount = 0;
let pollingStopped = false;
let lastSemanticKey = '';
const intakeOtStabilizer = createIntakeOtStabilizer();
function touchSnapshot(snapshot: ProjectionSnapshot): ProjectionSnapshot {
snapshot.lastAccessedAt = Date.now();
return snapshot;
}
function readSnapshot(conversationId: string): ProjectionSnapshot | null {
const snapshot = snapshots.get(conversationId);
return snapshot ? touchSnapshot(snapshot) : null;
}
function pruneSnapshots(): void {
while (snapshots.size > SNAPSHOT_CACHE_LIMIT) {
const oldest = [...snapshots.values()]
.sort((left, right) => left.lastAccessedAt - right.lastAccessedAt)[0];
if (!oldest) return;
snapshots.delete(oldest.conversationId);
}
}
function workItemsSemanticKey(items: ShippingProcessingProjection[]): string {
return JSON.stringify(items.map((item) => ({
no: item.workItemNo,
type: item.workItemType,
status: item.uiState?.status ?? item.userStatus ?? item.status,
stage: item.uiState?.stage ?? item.userStage ?? item.stage,
gate: item.uiState?.blocking_reason?.code ?? item.blockingReason?.code ?? null,
action: item.uiState?.primary_action?.code ?? item.primaryAction?.code ?? null,
version: item.progressVersion,
files: (item.aggregateChildren || []).map((child) => ({
no: child.workItemNo,
status: child.uiState?.status ?? child.userStatus ?? child.status,
stage: child.uiState?.stage ?? child.userStage ?? child.stage,
file: child.sourceSummary?.filename ?? null,
})),
})));
}
function applySnapshot(snapshot: ProjectionSnapshot | null): void {
processing.value = snapshot?.processing ?? null;
processingWorkItems.value = snapshot?.workItems ?? [];
snapshotUpdatedAt.value = snapshot?.receivedAt ?? null;
}
function currentPollElapsedMs(): number {
const snapshot = readSnapshot(normalizedConversationId.value);
return snapshot?.processingStartedAt === null || snapshot?.processingStartedAt === undefined
? 0
: Math.max(0, Date.now() - snapshot.processingStartedAt);
}
function resolveCurrentPollInterval(): number | null {
return resolveProcessingPollIntervalMs({
elapsedMs: currentPollElapsedMs(),
visibility: typeof document === 'undefined' ? 'visible' : document.visibilityState,
hasProcessing: shouldContinueProcessingPolling(processing.value),
failureCount,
});
}
/**
* 在 Intake→OT 过渡窗里,若 projection 被稳定器保留为上一轮 OT 视图,
* 则 work_items 也必须同步保留上一轮 order_task;否则卡片正文与侧边进度条
@@ -183,6 +269,12 @@ export function useShippingNoticeWorkflow(
pollTimer = null;
requestController?.abort();
requestController = null;
// 请求属于上一会话代际时 finally 会因 generation 不匹配而跳过清理;
// 必须在此同步清空,才能让新会话首个 GET 固定进入 initialLoading。
initialLoading.value = false;
manualRefreshing.value = false;
polling.value = false;
isFetching.value = false;
requestGeneration += 1;
pollGeneration += 1;
}
@@ -214,22 +306,31 @@ export function useShippingNoticeWorkflow(
mode: 'initial' | 'manual' | 'poll',
): Promise<void> {
const generation = ++requestGeneration;
if (mode === 'initial') initialLoading.value = true;
requestGenerations.set(conversationId, generation);
const existingSnapshot = readSnapshot(conversationId);
if (mode === 'initial' && !existingSnapshot) initialLoading.value = true;
else if (mode === 'manual') manualRefreshing.value = true;
else polling.value = true;
isFetching.value = true;
const controller = createRequestController();
try {
// [STEP 1] 统一投影为唯一读源。
const unified = await getWorkspaceShippingProcessing(conversationId, controller.signal);
if (
controller.signal.aborted
|| generation !== requestGeneration
|| requestGenerations.get(conversationId) !== generation
|| conversationId !== normalizedConversationId.value
|| String(unified?.conversation_id || '').trim() !== conversationId
) return;
const workItems = Array.isArray(unified?.work_items) ? unified.work_items : [];
// 记录该会话已见过 OT,供下一轮 Intake 稀疏响应在稳定窗口内保留上一投影。
if (workItems.some((item) => item.workItemType === 'order_task')) {
intakeOtStabilizer.markSeen(conversationId);
}
const embedded = unified?.conversation_processing as ConversationProcessingProjection | null | undefined;
const prevProjection = processing.value;
const previousSnapshot = readSnapshot(conversationId);
const prevProjection = previousSnapshot?.processing ?? null;
const nextProjection = resolveConversationProcessingFromUnified(
workItems,
embedded,
@@ -241,23 +342,55 @@ export function useShippingNoticeWorkflow(
reset: (cId) => intakeOtStabilizer.reset(cId),
},
);
const nextSemanticKey = buildProcessingSemanticKey(nextProjection);
processingWorkItems.value = resolveStableWorkItems(
if (!nextProjection) {
// 空投影同样是本次后端裁决,但不作为“成功 Projection”缓存;
// 保留已有 Snapshot 可避免短暂稀疏响应把业务卡卸载。
if (!previousSnapshot) applySnapshot(null);
error.value = null;
failureCount = 0;
return;
}
const nextSemanticKey = `${buildProcessingSemanticKey(nextProjection)}:${workItemsSemanticKey(workItems)}`;
const nextWorkItems = resolveStableWorkItems(
workItems,
prevProjection,
nextProjection,
);
if (nextSemanticKey !== lastSemanticKey) {
processing.value = nextProjection;
// Intake→OT 的短暂稀疏响应由稳定器明确裁决为上一版 Projection;
// 此时 work_items 也必须维持同一 Snapshot,不能因原始项差异替换。
const keepPreviousSnapshot = Boolean(
previousSnapshot
&& !workItems.some((item) => item.workItemType === 'order_task')
&& intakeOtStabilizer.hasSeenOrderTaskBefore(conversationId),
);
if (!previousSnapshot || (!keepPreviousSnapshot && nextSemanticKey !== previousSnapshot.semanticKey)) {
const now = Date.now();
const processingStartedAt = shouldContinueProcessingPolling(nextProjection)
? (previousSnapshot?.processingStartedAt ?? now)
: null;
const snapshot: ProjectionSnapshot = {
conversationId,
processing: nextProjection,
workItems: nextWorkItems,
semanticKey: nextSemanticKey,
receivedAt: now,
lastAccessedAt: now,
processingStartedAt,
};
snapshots.set(conversationId, snapshot);
pruneSnapshots();
applySnapshot(snapshot);
lastSemanticKey = nextSemanticKey;
} else {
touchSnapshot(previousSnapshot);
applySnapshot(previousSnapshot);
}
error.value = null;
failureCount = 0;
} catch (reason) {
if (
controller.signal.aborted
|| generation !== requestGeneration
|| requestGenerations.get(conversationId) !== generation
|| conversationId !== normalizedConversationId.value
) return;
failureCount += 1;
@@ -266,10 +399,14 @@ export function useShippingNoticeWorkflow(
: 'network_recoverable';
} finally {
if (requestController === controller) requestController = null;
if (generation === requestGeneration) {
if (
requestGenerations.get(conversationId) === generation
&& requestGeneration === generation
) {
if (mode === 'initial') initialLoading.value = false;
else if (mode === 'manual') manualRefreshing.value = false;
else polling.value = false;
isFetching.value = false;
}
}
}
@@ -281,8 +418,7 @@ export function useShippingNoticeWorkflow(
function refresh(): Promise<void> {
const conversationId = normalizedConversationId.value;
if (!conversationId) {
processing.value = null;
processingWorkItems.value = [];
applySnapshot(null);
error.value = null;
lastSemanticKey = '';
return Promise.resolve();
@@ -291,7 +427,7 @@ export function useShippingNoticeWorkflow(
if (inFlightRefresh?.conversationId === conversationId) {
return inFlightRefresh.promise;
}
const isFirstLoad = processing.value === null && !initialLoading.value && !manualRefreshing.value && !polling.value;
const isFirstLoad = !readSnapshot(conversationId) && !initialLoading.value && !manualRefreshing.value && !polling.value;
const mode: 'initial' | 'manual' = isFirstLoad ? 'initial' : 'manual';
const promise = executeRefresh(conversationId, mode).finally(() => {
if (inFlightRefresh?.promise === promise) inFlightRefresh = null;
@@ -400,10 +536,8 @@ export function useShippingNoticeWorkflow(
if (!shouldContinueProcessingPolling(processing.value)) {
return;
}
const nextDelay = failureCount > 0
? resolveProcessingPollBackoffMs(failureCount)
: resolvePollMs(processing.value);
schedulePoll(generation, nextDelay);
const nextDelay = resolveCurrentPollInterval();
if (nextDelay !== null) schedulePoll(generation, nextDelay);
}, delayMs);
}
@@ -426,7 +560,8 @@ export function useShippingNoticeWorkflow(
return;
}
if (!shouldContinueProcessingPolling(processing.value)) return;
schedulePoll(generation, resolvePollMs(processing.value));
const nextDelay = resolveCurrentPollInterval();
if (nextDelay !== null) schedulePoll(generation, nextDelay);
});
}
@@ -438,10 +573,9 @@ export function useShippingNoticeWorkflow(
watch(normalizedConversationId, (nextConversationId, previousConversationId) => {
if (nextConversationId !== previousConversationId) {
processing.value = null;
processingWorkItems.value = [];
applySnapshot(readSnapshot(nextConversationId));
error.value = null;
lastSemanticKey = '';
lastSemanticKey = readSnapshot(nextConversationId)?.semanticKey || '';
}
restartPolling();
}, { immediate: true });
@@ -477,6 +611,9 @@ export function useShippingNoticeWorkflow(
initialLoading,
manualRefreshing,
polling,
isFetching,
isRefreshing,
snapshotUpdatedAt,
error,
refresh,
focusConversationTask,