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

338 lines
13 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/useChatShippingUploadHandler.ts
* 用途:处理发货通知与库存文件上传、订单抽取提交和附件建议提示。
* 依赖:shipping.api、file-assets.api、shippingUploadPrompt、shipping 常量、chat.types。
* 逻辑:co8 后不再走 shipping_batches Chat Turn;新通知经 enqueueNoticeFiles / startOrderExtractionRun;
* 单票覆盖仍经 replace_notice Turn;库存文件先成为私有临时资产再进 Dify 分析分支。
*/
import { computed } from 'vue';
import { uploadFileAsset } from '@/shared/api/file-assets.api';
import { extractExt } from '../constants/shipping';
import { buildShippingReplaceNoticeTurn, buildShippingTurnRefs } from './shippingTurnActions';
import { createChatMessageAttachmentSnapshots } from '../utils/attachmentCard.utils';
import type { StartChatTurnOptions } from '../types/chat-turn.types';
import type { ChatMessage, ChatMessageAttachment } from '../types/chat.types';
import type { PendingAttachment } from '../types/shipping.types';
import type { ComputedRef, Ref } from 'vue';
let noticeBatchSubmitting = false;
/**
* 查询发货通知建批是否正在提交中(供发送拦截器消费重复点击)。
*/
export function isShippingNoticeBatchSubmitting(): boolean {
return noticeBatchSubmitting;
}
/** 单测重置模块级建批提交状态。 */
export function resetShippingNoticeBatchSubmitStateForTests(): void {
noticeBatchSubmitting = false;
}
export interface ShippingUploadHandlerContext {
conversationId: Ref<string | null>;
currentAgentId: ComputedRef<number>;
attachments: Ref<PendingAttachment[]>;
input: Ref<string>;
shippingAutoFlowRequested: Ref<boolean>;
shippingInventoryPickerRef: Ref<HTMLInputElement | null>;
shippingNoticePickerRef: Ref<HTMLInputElement | null>;
pendingShippingUploadTaskId: Ref<string>;
pendingShippingNoticeTaskId: Ref<string>;
pendingShippingInventoryFile: Ref<File | null>;
resolvedShippingTaskId: Ref<string>;
shippingInventorySelectionActive: Ref<boolean>;
shippingInventorySelectionTaskId: Ref<string>;
getActiveShippingTaskId: () => string;
startChatTurn: (options: StartChatTurnOptions) => Promise<boolean>;
refreshShippingActions: () => Promise<void>;
msg: { warning: (text: string) => void; info?: (text: string) => void };
t: (key: string, params?: Record<string, unknown>) => string;
getParsedIntakeNos?: () => string[];
getSelectedCandidateNos?: () => string[];
clearConsumedNoticeAttachments?: () => void;
/** 将本地文件加入输入栏并创建 Intake(替代旧 create_batch_from_notices)。 */
enqueueNoticeFiles?: (files: File[]) => Promise<void>;
/** 对已解析 Intake 发起订单抽取提交。 */
startOrderExtractionRun?: (
query: string,
intakeNos: string[],
attachments: ChatMessageAttachment[],
uploadBatchId?: string,
) => Promise<boolean>;
sendTemporaryInventoryMessage: (assetNo: string, fileName: string) => Promise<unknown>;
}
/**
* 创建发货通知上传处理器。
*
* 核心逻辑:通知附件触发建单/建批;临时库存文件只能由发送层在用户明确声明后调用,避免根据后缀误判业务类型。
* @param ctx - 上传处理上下文
* @returns 自动上传、文件选择器和建议提示相关处理函数
*/
export function createShippingUploadHandlers(ctx: ShippingUploadHandlerContext) {
const resetInventoryTaskSelection = () => {
ctx.shippingInventorySelectionActive.value = false;
ctx.shippingInventorySelectionTaskId.value = '';
};
const runInventoryUploadChatTurn = async (taskId: string, file: File) => {
const normalizedTaskId = String(taskId || '').trim().toUpperCase();
const ok = await ctx.startChatTurn({
agentId: ctx.currentAgentId.value,
inputType: 'upload_followup',
displayText: `上传库存文件:${file.name}`,
actionType: 'shipping.upload_inventory',
payload: { task_no: normalizedTaskId },
files: [file],
refs: buildShippingTurnRefs(normalizedTaskId),
hooks: {
onAssistantMessageFinished: async (assistantMsg) => {
syncBatchContextFromTurnMessage(assistantMsg);
void ctx.refreshShippingActions();
},
},
});
if (!ok) ctx.msg.warning(ctx.t('chat.shippingInventoryUploadFailed'));
return ok;
};
const uploadInventoryForTask = async (taskId: string, file: File) => {
ctx.resolvedShippingTaskId.value = taskId;
await runInventoryUploadChatTurn(taskId, file);
};
const selectShippingInventoryUploadTask = (taskId: string): boolean => {
const normalizedTaskId = String(taskId || '').trim().toUpperCase();
if (!normalizedTaskId) {
ctx.msg.warning(ctx.t('chat.shippingNoticeMissingTaskId'));
return false;
}
ctx.resolvedShippingTaskId.value = normalizedTaskId;
ctx.shippingInventorySelectionTaskId.value = normalizedTaskId;
ctx.pendingShippingUploadTaskId.value = normalizedTaskId;
ctx.shippingInventorySelectionActive.value = false;
const pendingFile = ctx.pendingShippingInventoryFile.value;
if (pendingFile) {
ctx.pendingShippingInventoryFile.value = null;
ctx.pendingShippingUploadTaskId.value = '';
void uploadInventoryForTask(normalizedTaskId, pendingFile).catch((e: unknown) => {
const errorMessage = e instanceof Error ? e.message : ctx.t('chat.shippingInventoryUploadFailed');
ctx.msg.warning(errorMessage);
});
return true;
}
ctx.shippingInventoryPickerRef.value?.click();
return true;
};
const cancelShippingInventoryTaskSelection = () => {
ctx.pendingShippingInventoryFile.value = null;
ctx.pendingShippingUploadTaskId.value = '';
resetInventoryTaskSelection();
};
const syncBatchContextFromTurnMessage = (assistantMsg: ChatMessage) => {
const payload = assistantMsg.payload && typeof assistantMsg.payload === 'object'
? assistantMsg.payload as { task_no?: string; orchestrator_started?: boolean }
: {};
const taskId = String(payload.task_no || assistantMsg.shipping_ui_state?.task_no || '').trim();
if (taskId) ctx.resolvedShippingTaskId.value = taskId;
};
/**
* 将本地通知文件加入输入栏并创建 Intake(不再走 shipping_batches Chat Turn)。
* @param files - 用户选择的发货通知文件
* @returns 是否完成入队
*/
const runNoticeBatchChatTurn = async (files: File[]) => {
if (noticeBatchSubmitting) {
return true;
}
noticeBatchSubmitting = true;
try {
if (!ctx.enqueueNoticeFiles) {
ctx.msg.warning(ctx.t('chat.shippingNoticeUploadFailed'));
return false;
}
await ctx.enqueueNoticeFiles(files);
ctx.msg.info?.(ctx.t('chat.shippingNoticeWaitingForParse'));
void ctx.refreshShippingActions();
return true;
} catch {
ctx.msg.warning(ctx.t('chat.shippingNoticeUploadFailed'));
return false;
} finally {
noticeBatchSubmitting = false;
}
};
const runReplaceNoticeChatTurn = async (taskId: string, file: File) => {
const turn = buildShippingReplaceNoticeTurn(taskId, file);
const ok = await ctx.startChatTurn({
agentId: ctx.currentAgentId.value,
inputType: 'upload_followup',
displayText: turn.displayText,
actionType: turn.actionType,
payload: turn.payload,
files: turn.files,
refs: turn.refs,
hooks: {
onAssistantMessageFinished: async (assistantMsg) => {
syncBatchContextFromTurnMessage(assistantMsg);
void ctx.refreshShippingActions();
},
},
});
if (!ok) ctx.msg.warning(ctx.t('chat.shippingNoticeUploadFailed'));
return ok;
};
/**
* 对已解析 Intake 发起订单抽取提交(替代 create_batch_from_intakes)。
* @param intakeNos - 已解析 Intake 编号
* @param _candidateNos - 保留签名;候选选择由提交服务侧裁决
* @returns 是否提交成功
*/
const runNoticeBatchFromIntakes = async (intakeNos: string[], _candidateNos: string[]) => {
if (noticeBatchSubmitting) {
return true;
}
noticeBatchSubmitting = true;
try {
if (!ctx.startOrderExtractionRun) {
ctx.msg.warning(ctx.t('chat.shippingNoticeUploadFailed'));
return false;
}
const query = ctx.input.value.trim();
// 已解析的通知附件仍要固化到用户消息;此前传空数组会使发送后对话区丢失附件卡片。
const attachmentSnapshots = createChatMessageAttachmentSnapshots(
ctx.attachments.value.filter((attachment) => attachment.kind === 'shipping_notice'),
);
const ok = await ctx.startOrderExtractionRun(query, intakeNos, attachmentSnapshots);
if (ok) {
ctx.clearConsumedNoticeAttachments?.();
void ctx.refreshShippingActions();
} else {
ctx.msg.warning(ctx.t('chat.shippingNoticeUploadFailed'));
}
return ok;
} catch {
ctx.msg.warning(ctx.t('chat.shippingNoticeUploadFailed'));
return false;
} finally {
noticeBatchSubmitting = false;
}
};
const handleReplaceNoticeForCurrentTask = async (taskId: string, file: File) => {
ctx.resolvedShippingTaskId.value = taskId;
await runReplaceNoticeChatTurn(taskId, file);
};
const handleShippingAutoUploadFile = async (file: File) => {
// 调用方已验证用户明确声明库存;此处只创建隔离的临时资产,绝不建单或写正式库存。
const asset = await uploadFileAsset(file);
await ctx.sendTemporaryInventoryMessage(asset.asset_no, file.name);
};
const handleShippingAutoUploadNoticeBatch = async (files: File[]) => {
const noticeFiles = files.filter(Boolean);
const intakeNos = ctx.getParsedIntakeNos?.() || [];
const candidateNos = ctx.getSelectedCandidateNos?.() || [];
if (!noticeFiles.length && intakeNos.length) {
await runNoticeBatchFromIntakes(intakeNos, candidateNos);
return;
}
if (!noticeFiles.length) return;
const pendingNoticeTaskId = String(ctx.pendingShippingNoticeTaskId.value || '').trim().toUpperCase();
ctx.pendingShippingNoticeTaskId.value = '';
const activeTaskId = pendingNoticeTaskId || String(ctx.getActiveShippingTaskId() || '').trim().toUpperCase();
const singleNoticeFile = noticeFiles[0];
if (noticeFiles.length === 1 && activeTaskId && singleNoticeFile) {
await handleReplaceNoticeForCurrentTask(activeTaskId, singleNoticeFile);
return;
}
await runNoticeBatchChatTurn(noticeFiles);
};
const openShippingInventoryPicker = (taskId?: string): boolean => {
const resolvedTaskId = String(taskId || ctx.getActiveShippingTaskId() || '').trim().toUpperCase();
if (!resolvedTaskId) {
ctx.msg.warning(ctx.t('chat.shippingNoticeMissingTaskId'));
return false;
}
return selectShippingInventoryUploadTask(resolvedTaskId);
};
/**
* 打开发货通知文件选择器,并在需要覆盖既有任务时锁定目标任务。
* 核心逻辑:优先使用显式 taskId 记录待覆盖任务;后续用户选中文件后,自动上传流程会消费该锁定任务而不是回退到最近聊天上下文。
* @param taskId - 可选任务编号;工作台/动作按钮重传时必须显式传入
* @returns 是否成功打开文件选择器
*/
const openShippingNoticePicker = (taskId?: string): boolean => {
const resolvedTaskId = String(taskId || ctx.getActiveShippingTaskId() || '').trim().toUpperCase();
if (!resolvedTaskId) {
ctx.msg.warning(ctx.t('chat.shippingNoticeMissingTaskId'));
return false;
}
ctx.pendingShippingNoticeTaskId.value = resolvedTaskId;
ctx.shippingNoticePickerRef.value?.click();
return true;
};
const handleShippingInventorySelected = async (event: Event) => {
const fileInput = event.target as HTMLInputElement;
const file = fileInput.files?.[0];
fileInput.value = '';
const taskId = ctx.pendingShippingUploadTaskId.value;
ctx.pendingShippingUploadTaskId.value = '';
if (!file || !taskId) {
ctx.shippingInventorySelectionTaskId.value = '';
return;
}
try {
await uploadInventoryForTask(taskId, file);
} catch (e: unknown) {
const errorMessage = e instanceof Error ? e.message : ctx.t('chat.shippingInventoryUploadFailed');
ctx.msg.warning(errorMessage);
} finally {
ctx.shippingInventorySelectionTaskId.value = '';
}
};
const shippingSuggestedPrompt = computed(() => {
const first = ctx.attachments.value.find((a) => a.kind === 'local') as
| Extract<PendingAttachment, { kind: 'local' }>
| undefined;
if (!first) return '';
if (['xlsx', 'xls', 'csv'].includes(extractExt(first.file.name || '').toLowerCase())) {
return ctx.t('chat.shippingNoticePrompt.notice.autoSpreadsheetAction');
}
return ctx.t('chat.shippingNoticePrompt.notice.autoNoticeAction');
});
const useShippingSuggestedPrompt = () => {
const prompt = shippingSuggestedPrompt.value;
if (!prompt) return;
ctx.input.value = prompt;
ctx.shippingAutoFlowRequested.value = true;
};
return {
handleShippingAutoUploadFile,
handleShippingAutoUploadNoticeBatch,
openShippingInventoryPicker,
openShippingNoticePicker,
selectShippingInventoryUploadTask,
cancelShippingInventoryTaskSelection,
handleShippingInventorySelected,
shippingSuggestedPrompt,
useShippingSuggestedPrompt,
isShippingNoticeBatchSubmitting,
};
}