Files
syops/frontend/src/features/chat/shipping/normalizeShippingProcessing.ts
T

497 lines
23 KiB
TypeScript
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/chat/shipping/normalizeShippingProcessing.ts
* 用途:将后端 snake_case ShippingProcessingProjection 规范为前端 camelCase DTO。
* 依赖:shipping.api.types ShippingProcessingProjection / ProcessGateSummary。
* 逻辑:API 边界一次性转换;透传 Gate attemptNo 与 Intake 失败恢复摘要字段。
*/
import type {
ConversationProcessingUiState,
OrderIntakeSourceType,
ProcessGateSummary,
ShippingInventoryPerSourceAttempt,
ShippingInventoryPreparationSummary,
ShippingOrderTaskSummary,
ShippingProcessingBlockingReason,
ShippingProcessingFacts,
ShippingProcessingPrimaryAction,
ShippingProcessingProjection,
ShippingProcessingStage,
ShippingProcessingStageNode,
ShippingProcessingStageNodeStatus,
ShippingProcessingStatus,
ShippingProcessingWorkItemType,
ShippingProcessGateUserSummary,
} from '../types/shipping.api.types';
/** 后端可裁决并透传到订单生命周期工作台的阶段;前端不根据本地状态补造入口。 */
const lifecycleStages = ['intake_parse', 'order_review', 'fulfillment_prep', 'freight_upload', 'upload_complete'] as const;
/** 读取后端正式 snake_case DTO 的字符串字段。 */
function readString(raw: Record<string, unknown>, snake: string, _removedLegacyCamel?: string): string {
const value = raw[snake];
return value == null ? '' : String(value);
}
/**
* 读取后端正式 snake_case DTO 的可空字符串。
*/
function readNullableString(
raw: Record<string, unknown>,
snake: string,
_removedLegacyCamel?: string,
): string | null {
const value = raw[snake];
if (value == null || value === '') return null;
return String(value);
}
/**
* 规范单个 OT 摘要。
*/
function normalizeChildTask(raw: unknown): ShippingOrderTaskSummary | null {
if (!raw || typeof raw !== 'object') return null;
const item = raw as Record<string, unknown>;
const orderTaskNo = readString(item, 'order_task_no', 'orderTaskNo');
if (!orderTaskNo) return null;
return {
orderTaskNo,
status: readString(item, 'status', 'status') as ShippingProcessingStatus,
stage: readString(item, 'stage', 'stage') as ShippingProcessingStage,
customerName: readNullableString(item, 'customer_name', 'customerName'),
poNumber: readNullableString(item, 'po_number', 'poNumber'),
lastActivityAt: readNullableString(item, 'last_activity_at', 'lastActivityAt'),
};
}
/**
* 规范 Gate 摘要。
*/
function normalizeGate(raw: unknown): ProcessGateSummary | null {
if (!raw || typeof raw !== 'object') return null;
const item = raw as Record<string, unknown>;
const gateCode = readString(item, 'gate_code', 'gateCode');
if (!gateCode) return null;
return {
gateCode,
status: readString(item, 'status', 'status') || 'unknown',
nextActionCode: readNullableString(item, 'next_action_code', 'nextActionCode'),
blockingReasonCode: readNullableString(item, 'blocking_reason_code', 'blockingReasonCode'),
attemptNo: (() => {
const rawAttempt = item.attempt_no ?? item.attemptNo;
if (rawAttempt == null || rawAttempt === '') return null;
const n = Number(rawAttempt);
return Number.isFinite(n) ? n : null;
})(),
};
}
/**
* 规范单个 stage_node(兼容 snake / camel)。
*/
function normalizeStageNode(raw: unknown): ShippingProcessingStageNode | null {
if (!raw || typeof raw !== 'object') return null;
const item = raw as Record<string, unknown>;
const stage = readString(item, 'stage', 'stage') as ShippingProcessingStage;
if (!stage) return null;
const absoluteIndexRaw = item.absolute_index ?? item.absoluteIndex;
const absoluteIndex = Number.isFinite(Number(absoluteIndexRaw))
? Number(absoluteIndexRaw)
: 0;
const status = readString(item, 'status', 'status') as ShippingProcessingStageNodeStatus;
return {
stage,
absoluteIndex,
status: status || 'pending',
};
}
/**
* [T9 用户态 Projection] 规范 blocking_reason(后端 snake_case {code, i18n_key, details})。
*/
function normalizeBlockingReason(raw: unknown): ShippingProcessingBlockingReason | null {
if (!raw || typeof raw !== 'object') return null;
const item = raw as Record<string, unknown>;
const code = String(item.code ?? '').trim();
if (!code) return null;
return {
code,
i18nKey: item.i18n_key != null ? String(item.i18n_key) : null,
details:
typeof item.details === 'object' && item.details != null
? (item.details as Record<string, unknown>)
: {},
};
}
/**
* [T9 用户态 Projection] 规范 primary_action(后端 snake_case {code, i18n_key, parameters})。
*/
function normalizePrimaryAction(raw: unknown): ShippingProcessingPrimaryAction | null {
if (!raw || typeof raw !== 'object') return null;
const item = raw as Record<string, unknown>;
const code = String(item.code ?? '').trim();
if (!code) return null;
return {
code,
i18nKey: item.i18n_key != null ? String(item.i18n_key) : null,
parameters:
typeof item.parameters === 'object' && item.parameters != null
? (item.parameters as Record<string, unknown>)
: {},
executionMode: item.execution_mode === 'navigate'
? 'navigate'
: item.execution_mode === 'execute'
? 'execute'
: undefined,
targetSurface: item.target_surface === 'order_lifecycle_workbench'
? 'order_lifecycle_workbench'
: null,
targetLifecycleStage: lifecycleStages.includes(
String(item.target_lifecycle_stage ?? '') as typeof lifecycleStages[number],
)
? String(item.target_lifecycle_stage) as ShippingProcessingPrimaryAction['targetLifecycleStage']
: null,
};
}
/** 规范后端生命周期入口,前端不得由候选数或当前阶段补造入口。 */
function normalizeLifecycleEntries(raw: unknown): NonNullable<ConversationProcessingUiState['lifecycleEntries']> {
if (!Array.isArray(raw)) return [];
return raw
.filter((item): item is Record<string, unknown> => Boolean(item && typeof item === 'object'))
.map((item) => ({
code: String(item.code ?? '') as NonNullable<ConversationProcessingUiState['lifecycleEntries']>[number]['code'],
state: String(item.state ?? '') as NonNullable<ConversationProcessingUiState['lifecycleEntries']>[number]['state'],
targetSurface: String(item.target_surface ?? '') as NonNullable<ConversationProcessingUiState['lifecycleEntries']>[number]['targetSurface'],
disabledReasonKey: item.disabled_reason_key != null
? String(item.disabled_reason_key)
: null,
}))
.filter((item) => lifecycleStages.includes(item.code as typeof lifecycleStages[number])
&& ['available', 'current', 'unavailable'].includes(item.state)
&& item.targetSurface === 'order_lifecycle_workbench');
}
/**
* [T9 用户态 Projection] 规范 facts(后端 snake_case 子状态字典;camelCase key)。
*/
function normalizeFacts(raw: unknown): ShippingProcessingFacts | undefined {
if (!raw || typeof raw !== 'object') return undefined;
const item = raw as Record<string, unknown>;
const out: ShippingProcessingFacts = {};
const toStrArr = (value: unknown): string[] => {
if (!Array.isArray(value)) return [];
return value.map((c) => String(c ?? '').trim()).filter(Boolean);
};
const toLineArr = (value: unknown): Record<string, unknown>[] => {
if (!Array.isArray(value)) return [];
return value.filter((row): row is Record<string, unknown> => Boolean(row) && typeof row === 'object');
};
// 冻结选择计划中「已选但尚未物化/未识别」的附件诊断标记;仅 false 显式落盘,
// 已识别/缺省不设 recognize,便于前端以 facts.recognized === false 识别未识别行。
if (item.recognized === false) out.recognized = false;
if (item.plan_state != null || item.planState != null) {
out.planState = String(item.plan_state ?? item.planState);
}
if ('inventory_source_status' in item || 'inventorySourceStatus' in item) {
out.inventorySourceStatus =
item.inventory_source_status != null
? String(item.inventory_source_status)
: item.inventorySourceStatus != null
? String(item.inventorySourceStatus)
: null;
}
if ('inventory_milestones' in item || 'inventoryMilestones' in item) {
const rawMilestones = item.inventory_milestones ?? item.inventoryMilestones;
if (rawMilestones && typeof rawMilestones === 'object') {
const milestones = rawMilestones as Record<string, unknown>;
const state = (value: unknown): 'pending' | 'completed' => value === 'completed' ? 'completed' : 'pending';
out.inventoryMilestones = {
candidatesCalculated: state(milestones.candidates_calculated ?? milestones.candidatesCalculated),
candidatesFrozen: state(milestones.candidates_frozen ?? milestones.candidatesFrozen),
snapshotsReady: state(milestones.snapshots_ready ?? milestones.snapshotsReady),
matched: state(milestones.matched),
};
}
}
if ('candidate_set_id' in item || 'candidateSetId' in item) {
const v = item.candidate_set_id ?? item.candidateSetId;
out.candidateSetId = v == null || v === '' ? null : Number(v);
}
if ('candidate_set_version' in item || 'candidateSetVersion' in item) {
const v = item.candidate_set_version ?? item.candidateSetVersion;
out.candidateSetVersion = v == null || v === '' ? null : Number(v);
}
if ('candidate_set_status' in item || 'candidateSetStatus' in item) {
const v = item.candidate_set_status ?? item.candidateSetStatus;
out.candidateSetStatus = v == null || v === '' ? null : String(v) as ShippingProcessingFacts['candidateSetStatus'];
}
if ('candidate_source_codes' in item || 'candidateSourceCodes' in item) {
out.candidateSourceCodes = toStrArr(item.candidate_source_codes ?? item.candidateSourceCodes);
}
if ('prepared_source_codes' in item || 'preparedSourceCodes' in item) {
out.preparedSourceCodes = toStrArr(item.prepared_source_codes ?? item.preparedSourceCodes);
}
if ('pending_source_codes' in item || 'pendingSourceCodes' in item) {
out.pendingSourceCodes = toStrArr(item.pending_source_codes ?? item.pendingSourceCodes);
}
if ('failed_source_codes' in item || 'failedSourceCodes' in item) {
out.failedSourceCodes = toStrArr(item.failed_source_codes ?? item.failedSourceCodes);
}
if ('source_attempts' in item || 'sourceAttempts' in item) {
const v = item.source_attempts ?? item.sourceAttempts;
out.sourceAttempts = typeof v === 'object' && v != null ? v as Record<string, unknown> : {};
}
if ('line_resolutions' in item || 'lineResolutions' in item) {
out.lineResolutions = toLineArr(item.line_resolutions ?? item.lineResolutions);
}
if ('export_state' in item || 'exportState' in item) {
const v = item.export_state ?? item.exportState;
out.exportState = v == null ? 'not_created' : String(v);
}
if ('upload_state' in item || 'uploadState' in item) {
const v = item.upload_state ?? item.uploadState;
out.uploadState = v == null ? 'not_created' : String(v);
}
if ('switch_state' in item || 'switchState' in item) {
const v = item.switch_state ?? item.switchState;
out.switchState = v == null ? 'not_triggered' : String(v);
}
if ('forced_match_source_code' in item || 'forcedMatchSourceCode' in item) {
const v = item.forced_match_source_code ?? item.forcedMatchSourceCode;
out.forcedMatchSourceCode = v == null || v === '' ? null : String(v).toUpperCase();
}
for (const [k, v] of Object.entries(item)) {
if (!(k in out)) {
out[k] = v;
}
}
return out;
}
function normalizeAggregateSummary(
raw: unknown,
): ShippingProcessingProjection['aggregateSummary'] {
if (!raw || typeof raw !== 'object') return null;
const item = raw as Record<string, unknown>;
const array = (value: unknown): string[] => Array.isArray(value)
? value.map((entry) => String(entry || '').trim()).filter(Boolean)
: [];
const count = (key: string): number => Number(item[key] || 0) || 0;
const intakeNo = String(item.intake_no ?? item.intakeNo ?? '').trim();
if (!intakeNo) return null;
return {
intakeNo,
total: count('total'),
inGroup: count('in_group') || count('inGroup'),
completed: count('completed'),
processing: count('processing'),
needsAction: count('needs_action') || count('needsAction'),
failed: count('failed'),
stages: array(item.stages),
reasonCodes: array(item.reason_codes ?? item.reasonCodes),
};
}
/**
* 题4A:规范 inventory_preparation 结构化字段(snake_case → camelCase)。
* 注意:只投影当前准备结果;失败后由具体 Gate 动作决定下一步。
*/
function normalizeInventoryPreparation(raw: unknown): ShippingInventoryPreparationSummary | null {
if (!raw || typeof raw !== 'object') return null;
const item = raw as Record<string, unknown>;
const toStrArr = (value: unknown): string[] => {
if (!Array.isArray(value)) return [];
return value.map((c) => String(c ?? '').trim()).filter(Boolean);
};
const requiredSources = toStrArr(item.required_sources ?? item.requiredSources);
if (!requiredSources.length) {
// required_sources 空代表 inventory_preparation 实际尚未进入 inventory 阶段,返回 null 避免前端误判。
return null;
}
const preparedSources = toStrArr(item.prepared_sources ?? item.preparedSources);
const pendingSources = toStrArr(item.pending_sources ?? item.pendingSources);
const failedSources = toStrArr(item.failed_sources ?? item.failedSources);
const activeAttemptCount = Number(item.active_attempt_count ?? item.activeAttemptCount ?? 0) || 0;
const gateAttemptActive = Boolean(item.gate_attempt_active ?? item.gateAttemptActive ?? false);
const latestRaw = (item.latest_attempts ?? item.latestAttempts) as Record<string, unknown> | undefined;
const latestAttempts: Record<string, ShippingInventoryPerSourceAttempt> = {};
if (latestRaw && typeof latestRaw === 'object') {
for (const [key, val] of Object.entries(latestRaw)) {
if (!val || typeof val !== 'object') continue;
const row = val as Record<string, unknown>;
const sourceCode = String(row.source_code ?? row.sourceCode ?? key ?? '').trim().toUpperCase();
if (!sourceCode) continue;
const attemptNo = Number(row.attempt_no ?? row.attemptNo ?? 0) || 0;
const status = String(row.status || '').trim().toLowerCase() || 'unknown';
const entry: ShippingInventoryPerSourceAttempt = {
sourceCode,
attemptNo,
status,
manualRetryable: (() => {
if (row.manual_retryable != null) return Boolean(row.manual_retryable);
if (row.manualRetryable != null) return Boolean(row.manualRetryable);
return ['failed', 'exhausted'].includes(status);
})(),
message:
(row.error_message as string | null | undefined) ??
(row.errorMessage as string | null | undefined) ??
(row.message as string | null | undefined) ??
null,
updatedAt:
readNullableString(row, 'updated_at', 'updatedAt') ??
readNullableString(row, 'finished_at', 'finishedAt') ??
readNullableString(row, 'started_at', 'startedAt'),
};
latestAttempts[sourceCode] = entry;
}
}
return {
requiredSources,
preparedSources,
pendingSources,
failedSources,
activeAttemptCount,
gateAttemptActive,
latestAttempts: Object.keys(latestAttempts).length ? latestAttempts : undefined,
};
}
/**
* 将后端 / 混合字段投影规范为 ShippingProcessingProjection。
* 核心逻辑:缺字段给安全默认值,保证四页面可渲染;非法输入返回 null。
*
* @param raw - API 原始对象
* @returns 规范化投影;无法识别时 null
*/
export function normalizeShippingProcessingProjection(
raw: unknown,
): ShippingProcessingProjection | null {
if (!raw || typeof raw !== 'object') return null;
const item = raw as Record<string, unknown>;
const workItemNo = readString(item, 'work_item_no', 'workItemNo');
if (!workItemNo) return null;
const summaryRaw = (item.source_summary ?? item.sourceSummary ?? {}) as Record<string, unknown>;
const childrenRaw = item.child_order_tasks ?? item.childOrderTasks;
const children = Array.isArray(childrenRaw)
? childrenRaw.map(normalizeChildTask).filter((row): row is ShippingOrderTaskSummary => Boolean(row))
: [];
// ui_state 是处理进度唯一的用户态/动作合同。旧顶层动作字段已下线,
// 客户端只能由该合同派生本地展示索引,不能读取或补造历史 available_actions。
const uiState = normalizeProcessingUiState(item.ui_state);
const availableActions = uiState
? [uiState.primary_action, ...uiState.secondary_actions]
.map((action) => String(action?.code || '').trim())
.filter(Boolean)
: [];
const stageNodesRaw = item.stage_nodes ?? item.stageNodes;
const stageNodes = Array.isArray(stageNodesRaw)
? stageNodesRaw.map(normalizeStageNode).filter((row): row is ShippingProcessingStageNode => Boolean(row))
: undefined;
const aggregateChildrenRaw = item.aggregate_children ?? item.aggregateChildren;
const aggregateChildren = Array.isArray(aggregateChildrenRaw)
? aggregateChildrenRaw
.map(normalizeShippingProcessingProjection)
.filter((entry): entry is ShippingProcessingProjection => Boolean(entry))
: undefined;
return {
workItemType: (readString(item, 'work_item_type', 'workItemType') || 'order_task') as ShippingProcessingWorkItemType,
workItemNo,
sourceType: (readNullableString(item, 'source_type', 'sourceType') || 'eml') as OrderIntakeSourceType,
rootOrderTaskNo: readNullableString(item, 'root_order_task_no', 'rootOrderTaskNo'),
shippingNoticeNo: readNullableString(item, 'shipping_notice_no', 'shippingNoticeNo'),
runNo: readNullableString(item, 'run_no', 'runNo'),
caseNo: readNullableString(item, 'case_no', 'caseNo'),
conversationId: readNullableString(item, 'conversation_id', 'conversationId'),
submissionNo: readString(item, 'submission_no', 'submissionNo'),
intakeNo: readString(item, 'intake_no', 'intakeNo'),
status: (readString(item, 'status', 'status') || 'processing') as ShippingProcessingStatus,
stage: (readString(item, 'stage', 'stage') || 'upload_received') as ShippingProcessingStage,
stageLabelKey: readNullableString(item, 'stage_label_key', 'stageLabelKey'),
progressVersion: Number(item.progress_version ?? item.progressVersion ?? 0) || 0,
lastActivityAt: readString(item, 'last_activity_at', 'lastActivityAt'),
stageNodes: stageNodes?.length ? stageNodes : undefined,
currentGate: normalizeGate(item.current_gate ?? item.currentGate),
processGate: normalizeProcessGateSummary(item.process_gate ?? item.processGate),
availableActions,
sourceSummary: {
emailSubject: readNullableString(summaryRaw, 'email_subject', 'emailSubject'),
filename: readNullableString(summaryRaw, 'filename', 'filename'),
documentId: Number(summaryRaw.document_id ?? summaryRaw.documentId ?? 0) || null,
documentCount: Number(summaryRaw.document_count ?? summaryRaw.documentCount ?? 0) || 0,
parsedDocumentCount: Number(summaryRaw.parsed_document_count ?? summaryRaw.parsedDocumentCount ?? 0) || 0,
candidateCount: Number(summaryRaw.candidate_count ?? summaryRaw.candidateCount ?? 0) || 0,
customerName: readNullableString(summaryRaw, 'customer_name', 'customerName'),
poNumber: readNullableString(summaryRaw, 'po_number', 'poNumber'),
failureReasonCode: readNullableString(summaryRaw, 'failure_reason_code', 'failureReasonCode'),
parseAttemptCount: Number(summaryRaw.parse_attempt_count ?? summaryRaw.parseAttemptCount ?? 0) || 0,
assetStatus: readNullableString(summaryRaw, 'asset_status', 'assetStatus'),
},
childOrderTasks: children,
// [T9 用户态 Projection 6 字段] 优先读后端 user_* / blocking_reason / primary_action / facts;
// 缺省为 null(旧后端不会下发,旧前端不读取,完全兼容)。
userStatus: readNullableString(item, 'user_status', 'userStatus') as ShippingProcessingProjection['userStatus'],
userStage: readNullableString(item, 'user_stage', 'userStage') as ShippingProcessingProjection['userStage'],
userCurrentGateCode: readNullableString(item, 'user_current_gate_code', 'userCurrentGateCode'),
blockingReason: normalizeBlockingReason(item.blocking_reason ?? item.blockingReason),
primaryAction: uiState?.primary_action ?? null,
uiState,
facts: normalizeFacts(item.facts),
userGroup: readNullableString(item, 'user_group', 'userGroup') as ShippingProcessingProjection['userGroup'],
aggregateSummary: normalizeAggregateSummary(item.aggregate_summary ?? item.aggregateSummary),
aggregateChildren: aggregateChildren?.length ? aggregateChildren : undefined,
hasFormalOt:
(item.has_formal_ot as boolean | undefined) == null ? false : Boolean(item.has_formal_ot),
inventoryPreparation: normalizeInventoryPreparation(
item.inventory_preparation ?? item.inventoryPreparation,
),
};
}
/** 保留后端 Gate 摘要原字段;写操作需要 execution_no 与 evaluation_version,不能降级为展示节点。 */
function normalizeProcessGateSummary(raw: unknown): ShippingProcessGateUserSummary | null {
if (!raw || typeof raw !== 'object') return null;
const item = raw as Record<string, unknown>;
return readString(item, 'execution_no', 'executionNo')
? item as unknown as ShippingProcessGateUserSummary
: null;
}
/** 规范化单项后端 UI 裁决;缺失时不展示动作,禁止从旧顶层字段回退。 */
function normalizeProcessingUiState(raw: unknown): ShippingProcessingProjection['uiState'] {
if (!raw || typeof raw !== 'object') return undefined;
const state = raw as Record<string, unknown>;
const secondaryRaw = state.secondary_actions;
const secondaryActions = Array.isArray(secondaryRaw)
? secondaryRaw
.filter((item): item is Record<string, unknown> => Boolean(item && typeof item === 'object'))
.map((item) => {
const normalized = normalizePrimaryAction(item);
return normalized ? { ...normalized, enabled: item.enabled !== false } : null;
})
.filter((item): item is NonNullable<typeof item> => item !== null)
: [];
return {
status: (readString(state, 'status', 'status') || 'running') as NonNullable<ShippingProcessingProjection['userStatus']>,
stage: readString(state, 'stage', 'stage'),
lifecycleStage: readString(state, 'lifecycle_stage') as ConversationProcessingUiState['lifecycleStage'],
lifecycleEntries: normalizeLifecycleEntries(state.lifecycle_entries),
blocking_reason: normalizeBlockingReason(state.blocking_reason),
primary_action: normalizePrimaryAction(state.primary_action),
secondary_actions: secondaryActions,
};
}
/**
* 将会话级统一投影响应中的 work_items 规范为数组。
*/
export function normalizeShippingProcessingWorkItems(raw: unknown): ShippingProcessingProjection[] {
if (!Array.isArray(raw)) return [];
return raw
.map(normalizeShippingProcessingProjection)
.filter((item): item is ShippingProcessingProjection => Boolean(item));
}