/** * features/chat/shipping/useShippingNoticeIntakes.ts * 用途:发货通知选择即上传、创建 intake 与批量状态轮询编排。 * 依赖:file-assets.api、shipping.api、shipping.types、shippingNoticeAttachmentIntegrity。 * 逻辑:useChatShipping / useChatAttachments 在货代 Agent 下委托本 composable 管理预解析附件; * 完整性判定委托 shippingNoticeAttachmentIntegrity(与后端契约对齐);会话刷新仅恢复未提交的处理中或解析失败附件。 */ import { computed, onBeforeUnmount, ref, type Ref } from 'vue'; import { uploadFileAsset } from '@/shared/api/file-assets.api'; import type { PendingAttachment, ShippingDuplicateAction, ShippingDuplicateResult, ShippingNoticeParseSummary, ShippingNoticePendingAttachment, ShippingNoticeCandidate, } from '../types/shipping.types'; import type { ShippingNoticeCandidateResponse, ShippingNoticeIntakeResponse } from '../types/shipping.api.types'; import { cancelShippingNoticeIntake, createShippingNoticeIntake, getShippingNoticeIntakeStatuses, listActiveShippingNoticeIntakes, resolveShippingNoticeDuplicate, resolveShippingNoticeCandidateDuplicate, retryShippingNoticeIntake, updateShippingNoticeCandidate, } from '@/features/chat/api/shipping.api'; import { isShippingNoticeAttachmentParseIncomplete } from './shippingNoticeAttachmentIntegrity'; export { isShippingNoticeAttachmentParseIncomplete } from './shippingNoticeAttachmentIntegrity'; const TERMINAL_PARSE = new Set(['parsed', 'failed', 'parse_failed', 'consumed', 'cancelled', 'expired']); const ACTIVE_PARSE = new Set(['waiting', 'queued', 'parsing', 'created']); const ACTIVE_ORDER_EXTRACTION = new Set(['extracting']); /** * 判断服务端 Intake 是否应恢复到输入栏。 * AI 触发时机:无;页面刷新或重新打开会话时调用。 * 已解析文件已作为用户消息附件固化在对话气泡中,不能再次显示在输入栏;仅恢复仍在处理中的文件和可手动重试的解析失败文件。 * @param parseStatus - 服务端返回的预解析状态 * @returns 是否恢复为待发送附件卡片 */ export function shouldRestoreShippingNoticeIntake(parseStatus: string | null | undefined): boolean { const status = String(parseStatus || '').trim().toLowerCase(); return ACTIVE_PARSE.has(status) || status === 'parse_failed'; } /** 判断 Intake 是否仍需轮询上传预处理或订单抽取状态。 */ export function shouldPollShippingNoticeIntake( item: Pick, ): boolean { return !TERMINAL_PARSE.has(item.parseStatus) || ACTIVE_ORDER_EXTRACTION.has(String(item.orderExtractionStatus || '').trim().toLowerCase()); } /** 判断附件是否仍可作为新一轮完整订单抽取的输入。 */ export function isOrderExtractionEligibleIntake( item: Pick, ): boolean { return item.parseStatus === 'parsed' && Boolean(item.intakeNo) && !isShippingNoticeAttachmentParseIncomplete(item.parseSummary); } /** 保留刚点击发送的本地 extracting,直到服务端进入真实抽取状态或返回终态。 */ export function resolveShippingOrderExtractionStatus(localStatus?: string, remoteStatus?: string | null): string | undefined { const local = String(localStatus || '').trim().toLowerCase(); const remote = String(remoteStatus || '').trim().toLowerCase(); if (local === 'extracting' && (!remote || remote === 'not_started')) return 'extracting'; return remote || undefined; } function mapServerParseStatus(status: string): ShippingNoticePendingAttachment['parseStatus'] { const normalized = String(status || '').trim().toLowerCase(); if (normalized === 'parsed') return 'parsed'; if (normalized === 'queued' || normalized === 'created') return 'queued'; if (normalized === 'parsing') return 'parsing'; if (normalized === 'parse_failed') return 'failed'; if (normalized === 'consumed') return 'consumed'; if (normalized === 'cancelled') return 'cancelled'; if (normalized === 'expired') return 'expired'; return 'waiting'; } /** * 将服务端 duplicate 结果映射为前端附件状态。 */ function mapServerDuplicate(remote: ShippingNoticeIntakeResponse): { duplicate?: ShippingDuplicateResult; duplicateResolution?: ShippingNoticePendingAttachment['duplicateResolution']; } { const dup = remote.duplicate; if (!dup) return {}; const duplicate: ShippingDuplicateResult = { status: dup.status, blocking: Boolean(dup.blocking), fingerprintStrength: dup.fingerprint_strength, matches: (dup.matches || []).map((item) => ({ taskNo: item.task_no, processStatus: item.process_status, documentVersion: Number(item.document_version || 1), matchType: item.match_type, matchedFields: listSafe(item.matched_fields), createdAt: item.created_at, })), allowedActions: (dup.allowed_actions || []) as ShippingDuplicateAction[], }; const resolution = remote.duplicate_resolution; return { duplicate, duplicateResolution: resolution ? { action: resolution.action, targetTaskNo: resolution.target_task_no || undefined, reason: resolution.reason || undefined, } : undefined, }; } function listSafe(value: unknown): string[] { return Array.isArray(value) ? value.map((item) => String(item)) : []; } /** 将 Candidate API 契约映射为输入区可审核状态。 */ function mapServerCandidate(remote: ShippingNoticeCandidateResponse): ShippingNoticeCandidate { const duplicate = remote.duplicate ? { status: remote.duplicate.status, blocking: Boolean(remote.duplicate.blocking), fingerprintStrength: remote.duplicate.fingerprint_strength, matches: (remote.duplicate.matches || []).map((item) => ({ taskNo: item.task_no, processStatus: item.process_status, documentVersion: Number(item.document_version || 1), matchType: item.match_type, matchedFields: listSafe(item.matched_fields), createdAt: item.created_at, })), allowedActions: (remote.duplicate.allowed_actions || []) as ShippingDuplicateAction[], } : undefined; return { candidateNo: remote.candidate_no, poNumber: remote.po_number || undefined, documentFilename: remote.primary_document_filename || undefined, validationStatus: remote.validation_status, selected: Boolean(remote.selected), conflicts: remote.conflicts || [], missingFields: Array.isArray(remote.missing_fields) ? remote.missing_fields.map((item) => String(item)) : [], fieldConfidence: remote.field_confidence && typeof remote.field_confidence === 'object' ? remote.field_confidence : {}, evidence: Array.isArray(remote.evidence) ? remote.evidence : [], fieldAdjudication: remote.field_adjudication && typeof remote.field_adjudication === 'object' ? remote.field_adjudication : null, customerMatches: Array.isArray(remote.customer_matches) ? remote.customer_matches : [], businessSummary: remote.business_summary || {}, duplicate, duplicateResolution: remote.duplicate_resolution ? { action: remote.duplicate_resolution.action, targetTaskNo: remote.duplicate_resolution.target_task_no || undefined, reason: remote.duplicate_resolution.reason || undefined, } : undefined, consumedTaskId: remote.consumed_task_id || undefined, }; } function createPendingAttachment(file: File): ShippingNoticePendingAttachment { return { id: `${Date.now()}_${Math.random().toString(36).slice(2, 8)}`, kind: 'shipping_notice', file, type: 'document', uploadStatus: 'waiting', parseStatus: 'waiting', uploadProgress: 0, originalFilename: file.name, fileSize: file.size, }; } export interface UseShippingNoticeIntakesOptions { attachments: Ref; conversationId: Ref; msg: { warning: (text: string) => void }; t: (key: string, params?: Record) => string; } export function useShippingNoticeIntakes(options: UseShippingNoticeIntakesOptions) { const pollTimer = ref | null>(null); const pollRound = ref(0); const noticeAttachments = computed(() => options.attachments.value.filter( (item): item is ShippingNoticePendingAttachment => item.kind === 'shipping_notice', ), ); const hasBlockingUploadOrParse = computed(() => noticeAttachments.value.some((item) => item.uploadStatus === 'uploading' || item.uploadStatus === 'waiting' || ACTIVE_PARSE.has(item.parseStatus) || item.parseStatus === 'queued' || item.parseStatus === 'parsing' || ACTIVE_ORDER_EXTRACTION.has(String(item.orderExtractionStatus || '').trim().toLowerCase()), ), ); const hasParseFailures = computed(() => noticeAttachments.value.some( (item) => item.parseStatus === 'failed' || isShippingNoticeAttachmentParseIncomplete(item.parseSummary), ), ); const allParsedReady = computed(() => noticeAttachments.value.length > 0 && noticeAttachments.value.every( (item) => item.parseStatus === 'parsed' && !isShippingNoticeAttachmentParseIncomplete(item.parseSummary), ), ); const hasBlockingDuplicates = computed(() => noticeAttachments.value.some( (item) => (item.candidates?.length ? item.candidates.some((candidate) => candidate.selected && candidate.duplicate?.blocking && !candidate.duplicateResolution?.action, ) : item.duplicate?.blocking && !item.duplicateResolution?.action), ), ); const hasCandidateReviewIssues = computed(() => noticeAttachments.value.some((item) => (item.candidates || []).some((candidate) => candidate.selected && candidate.validationStatus !== 'ready', ), ), ); const allReadyForConfirmation = computed(() => allParsedReady.value && !hasBlockingDuplicates.value && !hasCandidateReviewIssues.value && !hasParseFailures.value && noticeAttachments.value.some((item) => (item.candidates || []).some((candidate) => candidate.selected)), ); const stopPolling = () => { if (pollTimer.value) { clearTimeout(pollTimer.value); pollTimer.value = null; } pollRound.value = 0; }; const schedulePoll = () => { stopPolling(); const intakeNos = noticeAttachments.value .map((item) => item.intakeNo) .filter((item): item is string => Boolean(item)); if (!intakeNos.length) return; if (intakeNos.every((no) => { const item = noticeAttachments.value.find((entry) => entry.intakeNo === no); return item != null && !shouldPollShippingNoticeIntake(item); })) { return; } const delayMs = pollRound.value >= 8 ? 5000 : 2000; pollTimer.value = setTimeout(() => { void refreshStatuses().finally(() => { pollRound.value += 1; schedulePoll(); }); }, delayMs); }; const patchAttachment = (id: string, patch: Partial) => { options.attachments.value = options.attachments.value.map((item) => item.id === id && item.kind === 'shipping_notice' ? { ...item, ...patch } : item, ); }; const refreshStatuses = async () => { const intakeNos = noticeAttachments.value .map((item) => item.intakeNo) .filter((item): item is string => Boolean(item)); if (!intakeNos.length) return; const { items } = await getShippingNoticeIntakeStatuses(intakeNos); for (const remote of items) { const local = noticeAttachments.value.find((item) => item.intakeNo === remote.intake_no); if (!local) continue; patchAttachment(local.id, { parseStatus: mapServerParseStatus(remote.parse_status), orderExtractionStatus: resolveShippingOrderExtractionStatus( local.orderExtractionStatus, remote.order_extraction_status, ), parseSummary: (remote.parse_summary || undefined) as ShippingNoticeParseSummary | undefined, errorCode: remote.order_extraction_error_code || remote.error_code || undefined, errorMessage: remote.order_extraction_error_message || remote.error_message || undefined, expiresAt: remote.expires_at || undefined, assetNo: remote.asset_no || local.assetNo, ...mapServerDuplicate(remote), candidates: (remote.candidates || []).map(mapServerCandidate), }); } }; const processSingleFile = async (attachment: ShippingNoticePendingAttachment) => { if (!attachment.file) return; patchAttachment(attachment.id, { uploadStatus: 'uploading', uploadProgress: 10 }); try { const asset = await uploadFileAsset(attachment.file); patchAttachment(attachment.id, { assetNo: asset.asset_no, uploadStatus: 'uploaded', uploadProgress: 100, parseStatus: 'queued', }); const intake = await createShippingNoticeIntake( asset.asset_no, options.conversationId.value, ); patchAttachment(attachment.id, { intakeNo: intake.intake_no, parseStatus: mapServerParseStatus(intake.parse_status), orderExtractionStatus: intake.order_extraction_status || undefined, parseSummary: (intake.parse_summary || undefined) as ShippingNoticeParseSummary | undefined, errorCode: intake.order_extraction_error_code || intake.error_code || undefined, errorMessage: intake.order_extraction_error_message || intake.error_message || undefined, expiresAt: intake.expires_at || undefined, ...mapServerDuplicate(intake), candidates: (intake.candidates || []).map(mapServerCandidate), }); schedulePoll(); } catch (error) { const message = error instanceof Error ? error.message : options.t('chat.shippingNoticeUploadFailed'); patchAttachment(attachment.id, { uploadStatus: 'failed', parseStatus: 'failed', errorMessage: message, }); options.msg.warning(message); } }; const enqueueNoticeFiles = async (files: File[]) => { for (const file of files) { const attachment = createPendingAttachment(file); options.attachments.value = [...options.attachments.value, attachment]; await processSingleFile(attachment); } }; /** * 移除待建单附件:先从 UI 删除,再取消后端未消费的 intake(含已 parsed)。 * @param id - 本地附件临时 ID */ const removeNoticeAttachment = async (id: string) => { const target = noticeAttachments.value.find((item) => item.id === id); options.attachments.value = options.attachments.value.filter((item) => item.id !== id); // parsed 且未建单的 intake 也应取消,否则刷新后会经 listActive 再次出现 if (target?.intakeNo && target.parseStatus !== 'consumed') { try { await cancelShippingNoticeIntake(target.intakeNo); } catch { // 移除 UI 优先,取消失败由后端 TTL 兜底 } } if (!noticeAttachments.value.length) stopPolling(); }; const retryNoticeAttachment = async (id: string) => { const target = noticeAttachments.value.find((item) => item.id === id); if (!target?.intakeNo) return; patchAttachment(id, { parseStatus: 'queued', errorCode: undefined, errorMessage: undefined }); const intake = await retryShippingNoticeIntake(target.intakeNo); patchAttachment(id, { parseStatus: mapServerParseStatus(intake.parse_status), parseSummary: (intake.parse_summary || undefined) as ShippingNoticeParseSummary | undefined, errorCode: intake.error_code || undefined, errorMessage: intake.error_message || undefined, }); schedulePoll(); }; const getParsedIntakeNos = () => noticeAttachments.value .filter(isOrderExtractionEligibleIntake) .map((item) => String(item.intakeNo)); /** 点击发送后立即展示订单识别阶段,并启动 Intake 状态轮询。 */ const markOrderExtractionStarted = (intakeNos: string[]) => { const selected = new Set(intakeNos.map((item) => String(item || '').trim().toUpperCase()).filter(Boolean)); for (const attachment of noticeAttachments.value) { if (!attachment.intakeNo || !selected.has(attachment.intakeNo.toUpperCase())) continue; patchAttachment(attachment.id, { orderExtractionStatus: 'extracting', errorCode: undefined, errorMessage: undefined, }); } schedulePoll(); }; /** 聊天请求未成功发起时撤销本地即时状态;服务端真实状态由下一次刷新覆盖。 */ const rollbackOrderExtractionStarted = (intakeNos: string[]) => { const selected = new Set(intakeNos.map((item) => String(item || '').trim().toUpperCase()).filter(Boolean)); for (const attachment of noticeAttachments.value) { if (!attachment.intakeNo || !selected.has(attachment.intakeNo.toUpperCase())) continue; if (attachment.orderExtractionStatus === 'extracting') { patchAttachment(attachment.id, { orderExtractionStatus: 'not_started' }); } } schedulePoll(); }; const clearConsumedAttachments = () => { options.attachments.value = options.attachments.value.filter( (item) => item.kind !== 'shipping_notice' || item.parseStatus !== 'consumed', ); if (!noticeAttachments.value.length) stopPolling(); }; const restoreForConversation = async (conversationId?: string | null) => { const { items } = await listActiveShippingNoticeIntakes(conversationId); const restored: ShippingNoticePendingAttachment[] = items .filter((item) => shouldRestoreShippingNoticeIntake(item.parse_status)) .map((item) => ({ id: `restored_${item.intake_no}`, kind: 'shipping_notice' as const, type: 'document' as const, assetNo: item.asset_no || undefined, intakeNo: item.intake_no, uploadStatus: 'uploaded' as const, parseStatus: mapServerParseStatus(item.parse_status), orderExtractionStatus: item.order_extraction_status || undefined, uploadProgress: 100, originalFilename: item.original_filename || item.intake_no, fileSize: Number(item.file_size || 0), parseSummary: (item.parse_summary || undefined) as ShippingNoticeParseSummary | undefined, errorCode: item.order_extraction_error_code || item.error_code || undefined, errorMessage: item.order_extraction_error_message || item.error_message || undefined, expiresAt: item.expires_at || undefined, ...mapServerDuplicate(item), candidates: (item.candidates || []).map(mapServerCandidate), })); const nonNotice = options.attachments.value.filter((item) => item.kind !== 'shipping_notice'); options.attachments.value = [...nonNotice, ...restored]; if (restored.some((item) => shouldPollShippingNoticeIntake(item))) { schedulePoll(); } }; const resolveDuplicateAttachment = async ( id: string, action: ShippingDuplicateAction, targetTaskNo?: string, reason?: string, ) => { const target = noticeAttachments.value.find((item) => item.id === id); if (!target?.intakeNo) return; const intake = await resolveShippingNoticeDuplicate( target.intakeNo, action, targetTaskNo, reason, ); patchAttachment(target.id, { parseStatus: mapServerParseStatus(intake.parse_status), ...mapServerDuplicate(intake), }); }; /** 切换 Candidate 是否参与本次建批。 */ const setCandidateSelected = async (candidateNo: string, selected: boolean) => { const remote = await updateShippingNoticeCandidate(candidateNo, { selected }); for (const attachment of noticeAttachments.value) { if (!(attachment.candidates || []).some((item) => item.candidateNo === candidateNo)) continue; patchAttachment(attachment.id, { candidates: (attachment.candidates || []).map((item) => item.candidateNo === candidateNo ? mapServerCandidate(remote) : item, ), }); } }; /** 保存 Candidate 人工修订后的订单摘要。 */ const updateCandidateSummary = async (candidateNo: string, businessSummary: Record) => { const remote = await updateShippingNoticeCandidate(candidateNo, { business_summary: businessSummary }); for (const attachment of noticeAttachments.value) { if (!(attachment.candidates || []).some((item) => item.candidateNo === candidateNo)) continue; patchAttachment(attachment.id, { candidates: (attachment.candidates || []).map((item) => item.candidateNo === candidateNo ? mapServerCandidate(remote) : item, ), }); } }; /** 保存单个 Candidate 的重复处理决策。 */ const resolveCandidateDuplicate = async ( candidateNo: string, action: ShippingDuplicateAction, targetTaskNo?: string, reason?: string, ) => { const remote = await resolveShippingNoticeCandidateDuplicate(candidateNo, action, targetTaskNo, reason); for (const attachment of noticeAttachments.value) { if (!(attachment.candidates || []).some((item) => item.candidateNo === candidateNo)) continue; patchAttachment(attachment.id, { candidates: (attachment.candidates || []).map((item) => item.candidateNo === candidateNo ? mapServerCandidate(remote) : item, ), }); } }; const getSelectedCandidateNos = () => noticeAttachments.value.flatMap((item) => (item.candidates || []) .filter((candidate) => candidate.selected) .map((candidate) => candidate.candidateNo), ); onBeforeUnmount(() => { stopPolling(); }); return { noticeAttachments, hasBlockingUploadOrParse, hasParseFailures, allParsedReady, hasBlockingDuplicates, hasCandidateReviewIssues, allReadyForConfirmation, enqueueNoticeFiles, removeNoticeAttachment, retryNoticeAttachment, resolveDuplicateAttachment, resolveCandidateDuplicate, setCandidateSelected, updateCandidateSummary, getParsedIntakeNos, markOrderExtractionStarted, rollbackOrderExtractionStarted, getSelectedCandidateNos, refreshStatuses, clearConsumedAttachments, restoreForConversation, stopPolling, }; } export type ShippingNoticeIntakesApi = ReturnType;