- 移除不再使用的 SHIPPING_NOTICE_LAYOUT_PARSER_REVISION 配置 - 在环境配置中新增 SHIPPING_NOTICE_WORKER_CONCURRENCY 和 SHIPPING_NOTICE_JOB_RUNNING_TIMEOUT_SECONDS - 实现发货通知 worker 进程,支持并发处理订单抽取任务 - 引入紧急停止功能,允许管理员在运行中控制订单解析状态 - 更新相关 API,支持读取与设置紧急停止状态 - 增强文档与代码注释,反映新的业务逻辑与功能要求
671 lines
28 KiB
TypeScript
671 lines
28 KiB
TypeScript
/**
|
|
* features/chat/shipping/useShippingNoticeIntakes.ts
|
|
* 用途:发货通知选择即上传、创建 intake 与批量状态轮询编排。
|
|
* 依赖:file-assets.api、shipping.api、shipping.types、shippingNoticeAttachmentIntegrity、后端布局状态汇总。
|
|
* 逻辑:useChatShipping / useChatAttachments 在货代 Agent 下委托本 composable 原子加入附件并并发预解析;
|
|
* 点击发送时汇集输入框内全部合格附件,不以某次文件选择生成的 uploadBatchId 截断;
|
|
* 完整性判定委托 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 type { ShippingOrderExtractionReviewAttachment } from '../types/chat.types';
|
|
import {
|
|
cancelShippingNoticeIntake,
|
|
createShippingNoticeIntake,
|
|
getShippingNoticeIntakeStatuses,
|
|
listActiveShippingNoticeIntakes,
|
|
resolveShippingNoticeDuplicate,
|
|
resolveShippingNoticeCandidateDuplicate,
|
|
promoteShippingNoticeCandidate,
|
|
rejectShippingNoticeCandidate,
|
|
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 - 服务端返回的预解析状态。
|
|
* @param orderExtractionStatus - 服务端返回的订单抽取状态。
|
|
* @returns 是否恢复为待发送附件卡片
|
|
*/
|
|
export function shouldRestoreShippingNoticeIntake(
|
|
parseStatus: string | null | undefined,
|
|
orderExtractionStatus?: string | null,
|
|
_candidateCount = 0,
|
|
parseSummary?: ShippingNoticePendingAttachment['parseSummary'],
|
|
): boolean {
|
|
const status = String(parseStatus || '').trim().toLowerCase();
|
|
const extractionStatus = String(orderExtractionStatus || '').trim().toLowerCase();
|
|
return ACTIVE_PARSE.has(status)
|
|
|| status === 'parse_failed'
|
|
|| (
|
|
status === 'parsed'
|
|
&& (!extractionStatus || extractionStatus === 'not_started')
|
|
&& !isShippingNoticeAttachmentParseIncomplete(parseSummary)
|
|
);
|
|
}
|
|
|
|
/** 判断 Intake 是否仍需轮询上传预处理或订单抽取状态。 */
|
|
export function shouldPollShippingNoticeIntake(
|
|
item: Pick<ShippingNoticePendingAttachment, 'parseStatus' | 'orderExtractionStatus' | 'layoutStatus'>,
|
|
): boolean {
|
|
return !TERMINAL_PARSE.has(item.parseStatus)
|
|
|| ACTIVE_ORDER_EXTRACTION.has(String(item.orderExtractionStatus || '').trim().toLowerCase());
|
|
}
|
|
|
|
/** 判断附件是否仍可作为新一轮完整订单抽取的输入。 */
|
|
export function isOrderExtractionEligibleIntake(
|
|
item: Pick<ShippingNoticePendingAttachment, 'intakeNo' | 'parseStatus' | 'parseSummary' | 'orderExtractionStatus' | 'layoutStatus'>,
|
|
): boolean {
|
|
const extractionStatus = String(item.orderExtractionStatus || 'not_started').trim().toLowerCase();
|
|
return item.parseStatus === 'parsed'
|
|
&& Boolean(item.intakeNo)
|
|
&& (extractionStatus === 'not_started' || extractionStatus === 'failed')
|
|
&& !isShippingNoticeAttachmentParseIncomplete(item.parseSummary);
|
|
}
|
|
|
|
/** 把后端布局汇总投影为附件卡片使用的最小状态,旧响应缺字段时保持兼容。 */
|
|
function mapServerLayout(remote: ShippingNoticeIntakeResponse): Pick<ShippingNoticePendingAttachment, 'layoutStatus' | 'layoutSummary'> {
|
|
const summary = remote.layout_summary;
|
|
return {
|
|
layoutStatus: remote.layout_status || summary?.status,
|
|
layoutSummary: summary ? {
|
|
total: Number(summary.total || 0),
|
|
queued: Number(summary.queued || 0),
|
|
running: Number(summary.running || 0),
|
|
ready: Number(summary.ready || 0),
|
|
needs_review: Number(summary.needs_review || 0),
|
|
failed: Number(summary.failed || 0),
|
|
unsupported: Number(summary.unsupported || 0),
|
|
} : undefined,
|
|
};
|
|
}
|
|
|
|
/** 保留刚点击发送的本地 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 契约映射为输入区可审核状态。 */
|
|
export 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,
|
|
reservationDifferences: (item.reservation_differences || []).map((difference) => ({
|
|
reservationId: difference.reservation_id,
|
|
previous: {
|
|
partNumber: difference.previous.part_number,
|
|
qty: difference.previous.qty,
|
|
},
|
|
proposed: {
|
|
partNumber: difference.proposed.part_number,
|
|
qty: difference.proposed.qty,
|
|
},
|
|
})),
|
|
})),
|
|
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,
|
|
candidateStatus: remote.candidate_status || 'provisional',
|
|
acceptanceMode: remote.acceptance_mode || undefined,
|
|
extractionSource: remote.extraction_source || undefined,
|
|
actionButtons: Array.isArray(remote.action_buttons) ? remote.action_buttons : [],
|
|
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, uploadBatchId: string): 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,
|
|
uploadBatchId,
|
|
};
|
|
}
|
|
|
|
export interface UseShippingNoticeIntakesOptions {
|
|
attachments: Ref<PendingAttachment[]>;
|
|
conversationId: Ref<string | null>;
|
|
msg: { warning: (text: string) => void };
|
|
t: (key: string, params?: Record<string, unknown>) => string;
|
|
}
|
|
|
|
export function useShippingNoticeIntakes(options: UseShippingNoticeIntakesOptions) {
|
|
const pollTimer = ref<ReturnType<typeof setTimeout> | null>(null);
|
|
const pollRound = ref(0);
|
|
|
|
const noticeAttachments = computed(() =>
|
|
options.attachments.value.filter(
|
|
(item): item is ShippingNoticePendingAttachment => item.kind === 'shipping_notice',
|
|
),
|
|
);
|
|
|
|
// 输入框就是本次提交边界;多次选择加入的附件必须一起校验和发送。
|
|
const currentBatchAttachments = noticeAttachments;
|
|
|
|
const hasBlockingUploadOrParse = computed(() =>
|
|
currentBatchAttachments.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(() =>
|
|
currentBatchAttachments.value.some(
|
|
(item) =>
|
|
item.parseStatus === 'failed'
|
|
|| isShippingNoticeAttachmentParseIncomplete(item.parseSummary),
|
|
),
|
|
);
|
|
|
|
const allParsedReady = computed(() =>
|
|
currentBatchAttachments.value.length > 0
|
|
&& currentBatchAttachments.value.every(
|
|
(item) =>
|
|
item.parseStatus === 'parsed'
|
|
&& !isShippingNoticeAttachmentParseIncomplete(item.parseSummary),
|
|
),
|
|
);
|
|
|
|
const hasBlockingDuplicates = computed(() =>
|
|
currentBatchAttachments.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(() =>
|
|
currentBatchAttachments.value.some((item) =>
|
|
(item.candidates || []).some((candidate) =>
|
|
candidate.selected && candidate.validationStatus !== 'ready',
|
|
),
|
|
),
|
|
);
|
|
|
|
const allReadyForConfirmation = computed(() =>
|
|
allParsedReady.value
|
|
&& !hasBlockingDuplicates.value
|
|
&& !hasCandidateReviewIssues.value
|
|
&& !hasParseFailures.value
|
|
&& currentBatchAttachments.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<ShippingNoticePendingAttachment>) => {
|
|
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,
|
|
...mapServerLayout(remote),
|
|
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,
|
|
attachment.uploadBatchId,
|
|
);
|
|
patchAttachment(attachment.id, {
|
|
intakeNo: intake.intake_no,
|
|
uploadBatchId: intake.upload_batch_id || attachment.uploadBatchId,
|
|
parseStatus: mapServerParseStatus(intake.parse_status),
|
|
orderExtractionStatus: intake.order_extraction_status || undefined,
|
|
parseSummary: (intake.parse_summary || undefined) as ShippingNoticeParseSummary | undefined,
|
|
...mapServerLayout(intake),
|
|
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);
|
|
}
|
|
};
|
|
|
|
/**
|
|
* 将同一次选择的发货通知作为一个批次加入输入区,并并发完成资产上传与 Intake 创建。
|
|
* 核心逻辑:先原子追加全部附件,确保 UI 立即展示完整批次;再并发预处理,单文件失败由 processSingleFile 独立记录。
|
|
* @param files - 用户同一次选择的本地附件;所有文件共享同一个 uploadBatchId
|
|
* @returns 全部附件的预处理任务结束后完成;单文件失败不会拒绝整个批次
|
|
*/
|
|
const enqueueNoticeFiles = async (files: File[]) => {
|
|
// 同一次选择共享批次 ID,用于上传幂等和状态关联;发送范围由当前输入框决定。
|
|
const uploadBatchId = globalThis.crypto?.randomUUID?.()
|
|
|| `${Date.now()}-${Math.random().toString(36).slice(2, 12)}`;
|
|
const batchAttachments = files.map((file) => createPendingAttachment(file, uploadBatchId));
|
|
options.attachments.value = [...options.attachments.value, ...batchAttachments];
|
|
await Promise.all(batchAttachments.map((attachment) => 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,
|
|
...mapServerLayout(intake),
|
|
errorCode: intake.error_code || undefined,
|
|
errorMessage: intake.error_message || undefined,
|
|
});
|
|
schedulePoll();
|
|
};
|
|
|
|
const getParsedIntakeNos = () => {
|
|
const seen = new Set<string>();
|
|
return noticeAttachments.value
|
|
.filter(isOrderExtractionEligibleIntake)
|
|
.map((item) => String(item.intakeNo || '').trim().toUpperCase())
|
|
.filter((intakeNo) => {
|
|
if (!intakeNo || seen.has(intakeNo)) return false;
|
|
seen.add(intakeNo);
|
|
return true;
|
|
});
|
|
};
|
|
|
|
/** 点击发送后立即展示订单识别阶段,并启动 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,
|
|
item.order_extraction_status,
|
|
item.candidates?.length || 0,
|
|
(item.parse_summary || undefined) as ShippingNoticeParseSummary | undefined,
|
|
))
|
|
.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,
|
|
uploadBatchId: item.upload_batch_id || undefined,
|
|
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,
|
|
...mapServerLayout(item),
|
|
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),
|
|
...mapServerLayout(intake),
|
|
...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,
|
|
),
|
|
});
|
|
}
|
|
};
|
|
|
|
/** 人工采纳已复核的 Dify Candidate;后端决定是否已满足履约门禁。 */
|
|
const promoteCandidate = async (candidateNo: string) => {
|
|
const remote = await promoteShippingNoticeCandidate(candidateNo);
|
|
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) });
|
|
}
|
|
};
|
|
|
|
/** 人工驳回无需进入履约的 Dify Candidate。 */
|
|
const rejectCandidate = async (candidateNo: string, reason?: string) => {
|
|
const remote = await rejectShippingNoticeCandidate(candidateNo, 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) });
|
|
}
|
|
};
|
|
|
|
/** 保存单个 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),
|
|
);
|
|
|
|
/** 为指定 Run 投影可持久化的候选审核快照。 */
|
|
const getOrderExtractionReview = (intakeNos: string[]): ShippingOrderExtractionReviewAttachment[] => {
|
|
const selected = new Set(intakeNos.map((item) => String(item || '').trim().toUpperCase()).filter(Boolean));
|
|
return noticeAttachments.value
|
|
.filter((item) => item.intakeNo && selected.has(item.intakeNo.toUpperCase()) && item.candidates?.length)
|
|
.map((item) => ({
|
|
intakeNo: item.intakeNo!,
|
|
originalFilename: item.originalFilename,
|
|
candidates: item.candidates || [],
|
|
}));
|
|
};
|
|
|
|
onBeforeUnmount(() => {
|
|
stopPolling();
|
|
});
|
|
|
|
return {
|
|
noticeAttachments,
|
|
hasBlockingUploadOrParse,
|
|
hasParseFailures,
|
|
allParsedReady,
|
|
hasBlockingDuplicates,
|
|
hasCandidateReviewIssues,
|
|
allReadyForConfirmation,
|
|
enqueueNoticeFiles,
|
|
removeNoticeAttachment,
|
|
retryNoticeAttachment,
|
|
resolveDuplicateAttachment,
|
|
resolveCandidateDuplicate,
|
|
setCandidateSelected,
|
|
promoteCandidate,
|
|
rejectCandidate,
|
|
getParsedIntakeNos,
|
|
markOrderExtractionStarted,
|
|
rollbackOrderExtractionStarted,
|
|
getSelectedCandidateNos,
|
|
getOrderExtractionReview,
|
|
refreshStatuses,
|
|
clearConsumedAttachments,
|
|
restoreForConversation,
|
|
stopPolling,
|
|
};
|
|
}
|
|
|
|
export type ShippingNoticeIntakesApi = ReturnType<typeof useShippingNoticeIntakes>;
|