feat(chat): 更新发货任务处理逻辑和界面文本
- 移除不必要的状态引用 - 更新上传处理提示文本,使用国际化支持 - 扩展发货任务摘要接口,增加错误信息和短缺信息 - 更新多语言支持的文本,改善用户体验 - 增加批次工作区的汇总信息和操作提示
This commit is contained in:
1 parent
0b083cfdbd
commit
1fc9976ca3
60 files changed
+3876
-639
No files matched your search
@@ -20,6 +20,7 @@ export interface ShippingConversationContext {
|
||||
agentId: number,
|
||||
kb: string,
|
||||
files: ChatUploadFileSpec[],
|
||||
context?: { task_id?: string; batch_no?: string; display_query?: string },
|
||||
) => Promise<void>;
|
||||
}
|
||||
|
||||
@@ -40,7 +41,10 @@ export function createShippingConversationHelpers(ctx: ShippingConversationConte
|
||||
const sendShippingMenuMessage = async (message: string) => {
|
||||
const taskId = ctx.getActiveShippingTaskId();
|
||||
const text = taskId ? `${message}\n任务编号:${taskId}` : message;
|
||||
await ctx.sendMessage(text, ctx.currentAgentId.value, ctx.selectedKb.value, []);
|
||||
await ctx.sendMessage(text, ctx.currentAgentId.value, ctx.selectedKb.value, [], {
|
||||
task_id: taskId || undefined,
|
||||
display_query: message,
|
||||
});
|
||||
await ensureShippingHistorySynced(ctx);
|
||||
};
|
||||
|
||||
|
||||
@@ -38,7 +38,7 @@ export function formatShippingDecisionAssistantMessage(
|
||||
);
|
||||
} else if (decision === 'confirm_inventory_mapping') {
|
||||
if (String(result.checkpoint || '').trim() === 'map_ok') {
|
||||
lines.push('', '下一步:匹配库存与发货需求(match_inventory)。');
|
||||
lines.push('', '下一步:匹配库存与发货需求。');
|
||||
}
|
||||
} else if (decision === 'reparse_inventory') {
|
||||
lines.push('', '请重新上传或粘贴库存 Excel。');
|
||||
|
||||
@@ -87,14 +87,20 @@ export function isShippingGenerateExcelIntent(text: string): boolean {
|
||||
].some((pattern) => pattern.test(normalized));
|
||||
}
|
||||
|
||||
function normalizeShippingCommandText(text: string): string {
|
||||
return String(text || '')
|
||||
.trim()
|
||||
.replace(/\s+/g, '')
|
||||
.replace(/[,。!?、,.!?]/g, '')
|
||||
.toLowerCase();
|
||||
}
|
||||
|
||||
export function isShippingDownloadExcelIntent(text: string): boolean {
|
||||
const normalized = text.trim();
|
||||
const normalized = normalizeShippingCommandText(text);
|
||||
if (!normalized) return false;
|
||||
return [
|
||||
/^下载excel$/i,
|
||||
/^下载发货excel$/i,
|
||||
/下载.*excel/i,
|
||||
].some((pattern) => pattern.test(normalized));
|
||||
if (!/(excel|xlsx|表格|发货文件|发货单)/i.test(normalized)) return false;
|
||||
if (/(生成|创建|制作|重新生成|重生成)/.test(normalized)) return false;
|
||||
return /(下载|获取|取得|拿|打开|查看|导出)/.test(normalized);
|
||||
}
|
||||
|
||||
export function parseShippingTaskSwitchIntent(text: string): ShippingTaskSwitchIntent | null {
|
||||
|
||||
@@ -2,9 +2,9 @@
|
||||
* features/chat/shipping/shippingMenu.ts
|
||||
* 用途:发货聊天数字菜单解析、动作按钮合并与决策文本识别(纯函数)。
|
||||
* 依赖:shippingText.extractShippingActionsDirective、types/shipping.types。
|
||||
* 逻辑:useChatShippingSendHandler 在发送前调用;优先 API 按钮,其次 HTML 指令,最后内容推断。
|
||||
* 逻辑:useChatShippingSendHandler 在发送前调用;按钮只来自 API 或结构化 HTML 指令,不从自然语言正文猜测。
|
||||
*/
|
||||
import { extractShippingActionsDirective } from './shippingText';
|
||||
import { extractShippingActionsDirective, stripShippingActionListByButtons } from './shippingText';
|
||||
import type { ShippingActionButton, ShippingMenuAction } from '../types/shipping.types';
|
||||
|
||||
/**
|
||||
@@ -77,7 +77,7 @@ export function normalizeApiShippingButtons(
|
||||
}
|
||||
|
||||
/**
|
||||
* 合并 API 按钮、HTML 指令与内容推断,得到最终 action_buttons 与 cleanedText。
|
||||
* 合并 API 按钮与 HTML 指令,得到最终 action_buttons 与 cleanedText。
|
||||
*/
|
||||
export function resolveShippingActionButtons(
|
||||
content: string,
|
||||
@@ -86,9 +86,10 @@ export function resolveShippingActionButtons(
|
||||
) {
|
||||
const directive = extractShippingActionsDirective(String(content || ''));
|
||||
if (opts?.apiResolved) {
|
||||
const buttons = normalizeApiShippingButtons(apiButtons);
|
||||
return {
|
||||
buttons: normalizeApiShippingButtons(apiButtons),
|
||||
cleanedText: directive.cleanedText,
|
||||
buttons,
|
||||
cleanedText: stripShippingActionListByButtons(directive.cleanedText, buttons),
|
||||
fromDirective: false,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
/**
|
||||
* features/chat/shipping/shippingShortageDetails.ts
|
||||
* 用途:发货通知缺口明细的确定性格式化与查询意图识别。
|
||||
* 依赖:shipping.api 类型。
|
||||
* 逻辑:工作台按钮与聊天输入拦截共用本文件,避免把缺口数量交给 LLM 重新推理。
|
||||
*/
|
||||
import type {
|
||||
ShippingMatchLineResult,
|
||||
ShippingTaskDetail,
|
||||
ShippingTaskSummary,
|
||||
} from '@/features/chat/api/shipping.api';
|
||||
|
||||
export const isShippingShortageQueryIntent = (text: string) => {
|
||||
const value = String(text || '').trim().toLowerCase();
|
||||
if (!value) return false;
|
||||
return [
|
||||
'查询缺口',
|
||||
'缺口明细',
|
||||
'缺哪些',
|
||||
'哪个单缺',
|
||||
'哪些料缺',
|
||||
'库存缺口',
|
||||
'shortage',
|
||||
'shortages',
|
||||
].some((keyword) => value.includes(keyword));
|
||||
};
|
||||
|
||||
export const shortageLinesForTask = (task: ShippingTaskSummary | ShippingTaskDetail | null | undefined) => {
|
||||
if (!task) return [];
|
||||
if (Array.isArray(task.shortage?.lines) && task.shortage.lines.length) {
|
||||
return task.shortage.lines;
|
||||
}
|
||||
if (Array.isArray(task.line_results)) {
|
||||
return task.line_results.filter((line) => Number(line.shortage_qty || 0) > 0);
|
||||
}
|
||||
return [];
|
||||
};
|
||||
|
||||
export const hasShortageLines = (task: ShippingTaskSummary | ShippingTaskDetail | null | undefined) =>
|
||||
shortageLinesForTask(task).length > 0;
|
||||
|
||||
export const formatShippingQty = (value: unknown) => {
|
||||
const num = Number(value || 0);
|
||||
return Number.isFinite(num) ? num.toLocaleString(undefined, { maximumFractionDigits: 3 }) : '-';
|
||||
};
|
||||
|
||||
export const formatShortageLine = (
|
||||
line: ShippingMatchLineResult,
|
||||
index: number,
|
||||
t: (key: string, params?: Record<string, unknown>) => string,
|
||||
) => t('chat.shippingNoticeUi.diagnosisShortageLine', {
|
||||
index: index + 1,
|
||||
sku: line.sku || '-',
|
||||
reservationId: line.reservation_id || '-',
|
||||
required: formatShippingQty(line.required_qty),
|
||||
available: formatShippingQty(line.available_qty),
|
||||
shortage: formatShippingQty(line.shortage_qty),
|
||||
});
|
||||
|
||||
export const buildShortageDetailsMessage = (
|
||||
task: ShippingTaskSummary | ShippingTaskDetail,
|
||||
t: (key: string, params?: Record<string, unknown>) => string,
|
||||
) => {
|
||||
const lines = shortageLinesForTask(task);
|
||||
if (!lines.length) {
|
||||
return t('chat.shippingNoticeUi.shortageNoDetails', { taskId: task.task_no });
|
||||
}
|
||||
return [
|
||||
t('chat.shippingNoticeUi.shortageDetailsMessageTitle', {
|
||||
taskId: task.task_no,
|
||||
file: task.source_file_name || task.customer_name || '-',
|
||||
}),
|
||||
...lines.map((line, index) => formatShortageLine(line, index, t)),
|
||||
].join('\n');
|
||||
};
|
||||
@@ -7,14 +7,115 @@
|
||||
import { SHIPPING_INTERNAL_STATUS_TOKENS, SHIPPING_KNOWN_ACTION_ID_SET } from '@/constants/shippingNoticeActions';
|
||||
import type { ShippingActionButton, ShippingActionVariant } from '../types/shipping.types';
|
||||
|
||||
/**
|
||||
* 文本归一化用于判断 Agent 正文编号项是否重复描述了结构化按钮。
|
||||
*/
|
||||
const normalizeActionComparableText = (value: string) =>
|
||||
String(value || '')
|
||||
.toLowerCase()
|
||||
.replace(/[\s`"'“”‘’《》〈〉()()[\]{}【】|::,,.。;;、\-—_!?!?/\\]+/g, '');
|
||||
|
||||
const isNumberedActionLine = (line: string) =>
|
||||
/^\s*(?:[-*]\s*)?[1-91-9][\.\、\)::]\s*/.test(line);
|
||||
|
||||
const isActionListContextLine = (line: string) =>
|
||||
/(?:请选择操作|选择操作|操作选项|按钮)/.test(line);
|
||||
|
||||
const isActionListTailLine = (line: string) =>
|
||||
/(?:选择哪|希望.*(?:处理|执行|操作)|要.*哪一项|点击.*按钮)/.test(line);
|
||||
|
||||
/**
|
||||
* 根据后端 action_buttons 移除 Agent 正文中重复生成的编号操作列表。
|
||||
*
|
||||
* 核心逻辑:不写死具体按钮文案;只在编号行命中当前 action_buttons 的 label/message 时移除,
|
||||
* 并顺带移除相邻的“请选择操作”类上下文行。正常新链路不应依赖本兜底。
|
||||
*/
|
||||
export function stripShippingActionListByButtons(
|
||||
text: string,
|
||||
buttons: Array<Pick<ShippingActionButton, 'label' | 'message'>> | null | undefined,
|
||||
): string {
|
||||
const source = String(text || '');
|
||||
const normalizedActions = (buttons || [])
|
||||
.flatMap((button) => [button.label, button.message])
|
||||
.map((item) => normalizeActionComparableText(String(item || '')))
|
||||
.filter((item) => item.length >= 2);
|
||||
if (!normalizedActions.length) return source;
|
||||
|
||||
const lines = source.split('\n');
|
||||
const remove = new Set<number>();
|
||||
lines.forEach((line, index) => {
|
||||
if (!isNumberedActionLine(line)) return;
|
||||
const normalizedLine = normalizeActionComparableText(line);
|
||||
if (normalizedActions.some((action) => normalizedLine.includes(action) || action.includes(normalizedLine))) {
|
||||
remove.add(index);
|
||||
}
|
||||
});
|
||||
if (!remove.size) return source;
|
||||
|
||||
for (const index of Array.from(remove)) {
|
||||
for (let cursor = index - 1; cursor >= 0 && cursor >= index - 3; cursor -= 1) {
|
||||
const line = lines[cursor] || '';
|
||||
if (!line.trim()) {
|
||||
remove.add(cursor);
|
||||
continue;
|
||||
}
|
||||
if (isActionListContextLine(line)) {
|
||||
remove.add(cursor);
|
||||
continue;
|
||||
}
|
||||
break;
|
||||
}
|
||||
for (let cursor = index + 1; cursor < lines.length && cursor <= index + 3; cursor += 1) {
|
||||
const line = lines[cursor] || '';
|
||||
if (!line.trim()) {
|
||||
remove.add(cursor);
|
||||
continue;
|
||||
}
|
||||
if (isNumberedActionLine(line)) continue;
|
||||
if (isActionListTailLine(line)) {
|
||||
remove.add(cursor);
|
||||
continue;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return lines
|
||||
.filter((_, index) => !remove.has(index))
|
||||
.join('\n')
|
||||
.replace(/\n{3,}/g, '\n\n')
|
||||
.trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* 隐藏 Agent 回复中的内部状态 token,并将 task_id 统一为「任务编号」展示。
|
||||
*/
|
||||
export function sanitizeShippingConversationText(text: string, enabled: boolean): string {
|
||||
if (!enabled) return text;
|
||||
let result = String(text || '')
|
||||
.replace(/通过\s*(?:Hxops|HXOPS|hxops)\s*聊天区上传/gi, '在当前对话中上传')
|
||||
.replace(/在\s*(?:Hxops|HXOPS|hxops)\s*聊天区上传/gi, '在当前对话中上传')
|
||||
.replace(/(?:Hxops|HXOPS|hxops)\s*聊天区/gi, '当前对话')
|
||||
.replace(/(?:Hxops|HXOPS|hxops)\s*Chat/gi, '当前对话')
|
||||
.replace(/到\s*(?:Hxops|HXOPS|hxops)(\s*[??])?/gi, '到当前对话$1')
|
||||
.replace(/\b(?:Hxops|HXOPS|hxops)\b/g, '当前系统')
|
||||
.replace(/\btask_id\s*[::]/gi, '任务编号:')
|
||||
.replace(/\btask_id\b/gi, '任务编号');
|
||||
result = result
|
||||
.replace(/\bcreate_task\b/gi, '新建任务')
|
||||
.replace(/\bget_task_status\b/gi, '查询任务状态')
|
||||
.replace(/\bparse_notice\b/gi, '解析发货通知')
|
||||
.replace(/\bsubmit_decision\b/gi, '提交处理结果')
|
||||
.replace(/\bmatch_inventory\b/gi, '匹配库存')
|
||||
.replace(/\bgenerate_excel\b/gi, '生成发货 Excel')
|
||||
.replace(/\bgenerate_shipment_excel\b/gi, '生成发货 Excel')
|
||||
.replace(/\bupload_to_freight\b/gi, '上传货代系统')
|
||||
.replace(/\bapply_inventory_mapping\b/gi, '应用库存字段映射')
|
||||
.replace(/\bget_inventory_schema_preview\b/gi, '读取库存表头预览')
|
||||
.replace(/\bretry_rpa\b/gi, '重试库存抓取')
|
||||
.replace(/\bretry_upload\b/gi, '重试上传货代')
|
||||
.replace(/\bstructured\b/gi, '结构化内容')
|
||||
.replace(/\braw_text\b/gi, '通知原文');
|
||||
result = result.replace(/[((]\s*显示\s*[「"'`][^"'`]+[」"'`]\s*[))]/g, '');
|
||||
result = result.replace(
|
||||
/\b(process_status|pending_human_reason|review_status|checkpoint|match_status|human_options)\s*[::=]\s*[「"'`]?[\w.-]+[「"'`]?/gi,
|
||||
|
||||
@@ -37,6 +37,8 @@ export interface ShippingDecisionContext {
|
||||
* @returns 人工决策与手工上传确认处理函数
|
||||
*/
|
||||
export function createShippingDecisionHandlers(ctx: ShippingDecisionContext) {
|
||||
const manualUploadInFlightTaskIds = new Set<string>();
|
||||
|
||||
const syncHistoryIfNeeded = async () => {
|
||||
if (!ctx.conversationId.value && ctx.history.value.length === 0) {
|
||||
await ctx.loadHistory();
|
||||
@@ -108,17 +110,21 @@ export function createShippingDecisionHandlers(ctx: ShippingDecisionContext) {
|
||||
};
|
||||
|
||||
const executeShippingManualUpload = async (taskId: string, displayText?: string) => {
|
||||
const normalizedTaskId = String(taskId || '').trim().toUpperCase();
|
||||
if (!normalizedTaskId || manualUploadInFlightTaskIds.has(normalizedTaskId)) return false;
|
||||
manualUploadInFlightTaskIds.add(normalizedTaskId);
|
||||
try {
|
||||
const result = await markWorkspaceShippingManualUploaded(taskId);
|
||||
const userText = (displayText || '已在货代系统手工上传完成').trim();
|
||||
const assistantContent = [
|
||||
String(result.message || '已标记为手工上传货代系统完成。').trim(),
|
||||
`任务编号:${taskId}`,
|
||||
].join('\n');
|
||||
const result = await markWorkspaceShippingManualUploaded(normalizedTaskId);
|
||||
const userText = (displayText || '我已在货代系统完成上传').trim();
|
||||
const assistantContent = String(
|
||||
result.message || `好的,任务 ${normalizedTaskId} 已确认完成,无需再处理。`,
|
||||
).trim();
|
||||
const lastUserMessage = [...ctx.messages.value].reverse().find((item) => item.role === 'user');
|
||||
const shouldAppendUser = String(lastUserMessage?.content || '').trim() !== userText;
|
||||
const userMsg: ChatMessage = {
|
||||
role: 'user',
|
||||
type: 'text',
|
||||
content: `${userText}\n任务编号:${taskId}`,
|
||||
content: userText,
|
||||
local_id: ctx.newLocalMessageId('shipping-user'),
|
||||
local_only: true,
|
||||
};
|
||||
@@ -130,14 +136,19 @@ export function createShippingDecisionHandlers(ctx: ShippingDecisionContext) {
|
||||
local_only: true,
|
||||
shipping_actions_used: true,
|
||||
};
|
||||
ctx.messages.value.push(userMsg, assistantMsg);
|
||||
if (shouldAppendUser) {
|
||||
ctx.messages.value.push(userMsg);
|
||||
}
|
||||
ctx.messages.value.push(assistantMsg);
|
||||
ctx.messages.value.forEach((rawMsg) => {
|
||||
const m = rawMsg as ChatMessage & { shipping_actions?: unknown };
|
||||
if (m.role === 'assistant') {
|
||||
m.shipping_actions = undefined;
|
||||
}
|
||||
});
|
||||
await ctx.saveLocalMessageToBackend(userMsg, userText);
|
||||
if (shouldAppendUser) {
|
||||
await ctx.saveLocalMessageToBackend(userMsg, userText);
|
||||
}
|
||||
await ctx.saveLocalMessageToBackend(assistantMsg, userText);
|
||||
void ctx.refreshShippingActions();
|
||||
return true;
|
||||
@@ -145,6 +156,8 @@ export function createShippingDecisionHandlers(ctx: ShippingDecisionContext) {
|
||||
const errorMessage = e instanceof Error ? e.message : '标记手工上传失败';
|
||||
ctx.msg.warning(errorMessage);
|
||||
return false;
|
||||
} finally {
|
||||
manualUploadInFlightTaskIds.delete(normalizedTaskId);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
import {
|
||||
generateWorkspaceShippingExcel,
|
||||
matchWorkspaceShippingInventory,
|
||||
retryWorkspaceShippingUpload,
|
||||
type ShippingDecisionResponse,
|
||||
type ShippingMatchLineResult,
|
||||
} from '@/features/chat/api/shipping.api';
|
||||
@@ -71,7 +72,8 @@ export function createShippingMenuHandlers(ctx: ShippingMenuHandlerContext) {
|
||||
) => {
|
||||
if (ctx.isThinking.value) return;
|
||||
if (action.id === 'refresh') {
|
||||
await ctx.sendShippingMenuMessage(action.message || '刷新');
|
||||
await ctx.refreshShippingActions();
|
||||
ctx.msg.info(ctx.t('chat.shippingNoticeRefreshDone'));
|
||||
return;
|
||||
}
|
||||
if (action.id === 'download_excel') {
|
||||
@@ -125,6 +127,41 @@ export function createShippingMenuHandlers(ctx: ShippingMenuHandlerContext) {
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (action.id === 'retry_upload') {
|
||||
if (chatMsg?.shipping_actions_used) return;
|
||||
if (chatMsg) chatMsg.shipping_actions_used = true;
|
||||
const taskId = ctx.getActiveShippingTaskId();
|
||||
if (!taskId) {
|
||||
ctx.msg.warning(ctx.t('chat.shippingNoticeMissingTaskId'));
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const result = await retryWorkspaceShippingUpload(taskId);
|
||||
const userText = action.message || ctx.t('chat.shippingNoticeRetryUploadAction');
|
||||
const userMsg: ChatMessage = {
|
||||
role: 'user',
|
||||
type: 'text',
|
||||
content: `${userText}\n任务编号:${taskId}`,
|
||||
local_id: ctx.newLocalMessageId('shipping-user'),
|
||||
local_only: true,
|
||||
};
|
||||
const assistantMsg: ChatMessage = {
|
||||
role: 'assistant',
|
||||
type: 'text',
|
||||
content: String(result.message || ctx.t('chat.shippingNoticeRetryUploadQueued')).trim(),
|
||||
local_id: ctx.newLocalMessageId('shipping-assistant'),
|
||||
local_only: true,
|
||||
};
|
||||
ctx.messages.value.push(userMsg, assistantMsg);
|
||||
await ctx.saveLocalMessageToBackend(userMsg, userText);
|
||||
await ctx.saveLocalMessageToBackend(assistantMsg, userText);
|
||||
void ctx.refreshShippingActions();
|
||||
} catch (e: unknown) {
|
||||
const errorMessage = e instanceof Error ? e.message : ctx.t('chat.shippingNoticeRetryUploadFailed');
|
||||
ctx.msg.warning(errorMessage);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (action.id === 'edit_inventory_mapping') {
|
||||
const taskId = ctx.getActiveShippingTaskId();
|
||||
if (!taskId) {
|
||||
@@ -175,13 +212,16 @@ export function createShippingMenuHandlers(ctx: ShippingMenuHandlerContext) {
|
||||
}
|
||||
if (action.id === 'mark_manual_uploaded') {
|
||||
if (chatMsg?.shipping_actions_used) return;
|
||||
if (chatMsg) chatMsg.shipping_actions_used = true;
|
||||
if (chatMsg) {
|
||||
chatMsg.shipping_actions_used = true;
|
||||
chatMsg.shipping_actions = undefined;
|
||||
}
|
||||
const taskId = ctx.getActiveShippingTaskId();
|
||||
if (!taskId) {
|
||||
ctx.msg.warning(ctx.t('chat.shippingNoticeMissingTaskId'));
|
||||
return;
|
||||
}
|
||||
await ctx.executeShippingManualUpload(taskId, action.message || '已在货代系统手工上传完成');
|
||||
await ctx.executeShippingManualUpload(taskId, '我已在货代系统完成上传');
|
||||
return;
|
||||
}
|
||||
if (action.id === 'paste_inventory_json') {
|
||||
|
||||
@@ -77,36 +77,11 @@ export function createShippingActionsRefresher(ctx: ShippingRefreshContext) {
|
||||
taskId = taskNo;
|
||||
}
|
||||
} catch {
|
||||
// fall back to content-based buttons
|
||||
// fall back to structured directive buttons embedded in the message
|
||||
}
|
||||
}
|
||||
}
|
||||
if (taskId) ctx.resolvedShippingTaskId.value = taskId;
|
||||
let apiButtons: Array<{ id: string; label: string; message: string; variant?: string }> | null = null;
|
||||
let apiCheckpoint: string | null = null;
|
||||
let apiResolved = false;
|
||||
if (taskId && !ctx.isThinking.value) {
|
||||
const seq = ++shippingActionsRequestSeq;
|
||||
try {
|
||||
const data = await getShippingChatActions(taskId);
|
||||
if (seq === shippingActionsRequestSeq) {
|
||||
apiResolved = true;
|
||||
apiCheckpoint = data.checkpoint ? String(data.checkpoint) : null;
|
||||
apiButtons = data.action_buttons?.length ? data.action_buttons : null;
|
||||
}
|
||||
} catch {
|
||||
// fall back to content-based buttons
|
||||
}
|
||||
}
|
||||
if (apiResolved && apiCheckpoint && SHIPPING_TERMINAL_CHECKPOINTS.has(apiCheckpoint)) {
|
||||
msgs.forEach((rawMsg) => {
|
||||
const m = rawMsg as ChatMessage & { shipping_actions?: unknown };
|
||||
if (m.role === 'assistant') {
|
||||
m.shipping_actions = undefined;
|
||||
}
|
||||
});
|
||||
return;
|
||||
}
|
||||
let lastOpenAssistantIndex = -1;
|
||||
for (let i = msgs.length - 1; i >= 0; i -= 1) {
|
||||
const item = msgs[i];
|
||||
@@ -124,6 +99,42 @@ export function createShippingActionsRefresher(ctx: ShippingRefreshContext) {
|
||||
}
|
||||
}
|
||||
const targetAssistantIndex = lastOpenAssistantIndex >= 0 ? lastOpenAssistantIndex : lastAssistantIndex;
|
||||
if (targetAssistantIndex >= 0) {
|
||||
const target = msgs[targetAssistantIndex] as ChatMessage & { shipping_actions?: ShippingActionButton[] };
|
||||
const resolved = resolveShippingActionButtons(String(target.content || ''), null);
|
||||
if (resolved.cleanedText !== String(target.content || '').trim()) {
|
||||
target.content = resolved.cleanedText;
|
||||
}
|
||||
if (resolved.buttons.length && !target.shipping_actions?.length) {
|
||||
target.shipping_actions = resolved.buttons;
|
||||
}
|
||||
}
|
||||
|
||||
let apiButtons: Array<{ id: string; label: string; message: string; variant?: string }> | null = null;
|
||||
let apiCheckpoint: string | null = null;
|
||||
let apiResolved = false;
|
||||
if (taskId) {
|
||||
const seq = ++shippingActionsRequestSeq;
|
||||
try {
|
||||
const data = await getShippingChatActions(taskId);
|
||||
if (seq === shippingActionsRequestSeq) {
|
||||
apiResolved = true;
|
||||
apiCheckpoint = data.checkpoint ? String(data.checkpoint) : null;
|
||||
apiButtons = data.action_buttons?.length ? data.action_buttons : null;
|
||||
}
|
||||
} catch {
|
||||
// keep structured directive buttons if present
|
||||
}
|
||||
}
|
||||
if (apiResolved && apiCheckpoint && SHIPPING_TERMINAL_CHECKPOINTS.has(apiCheckpoint)) {
|
||||
msgs.forEach((rawMsg) => {
|
||||
const m = rawMsg as ChatMessage & { shipping_actions?: unknown };
|
||||
if (m.role === 'assistant') {
|
||||
m.shipping_actions = undefined;
|
||||
}
|
||||
});
|
||||
return;
|
||||
}
|
||||
msgs.forEach((rawMsg, index) => {
|
||||
const chatMsg = rawMsg as ChatMessage & {
|
||||
shipping_actions_used?: boolean;
|
||||
@@ -147,7 +158,7 @@ export function createShippingActionsRefresher(ctx: ShippingRefreshContext) {
|
||||
apiResolved ? (apiButtons ?? []) : null,
|
||||
{ apiResolved },
|
||||
);
|
||||
if (resolved.fromDirective) {
|
||||
if (resolved.fromDirective || resolved.cleanedText !== String(chatMsg.content || '').trim()) {
|
||||
chatMsg.content = resolved.cleanedText;
|
||||
}
|
||||
buttons = resolved.buttons;
|
||||
|
||||
@@ -10,7 +10,7 @@ import {
|
||||
getWorkspaceShippingBatch,
|
||||
switchWorkspaceShippingBatchFocusTask,
|
||||
} from '@/features/chat/api/shipping.api';
|
||||
import { SHIPPING_MENU_ACTION_SPECS } from '../constants/shipping';
|
||||
import { SHIPPING_DECISION_ACTIONS, SHIPPING_MENU_ACTION_SPECS } from '../constants/shipping';
|
||||
import { buildShippingFieldAlignmentText } from './shippingMapping';
|
||||
import { downloadWorkspaceShippingExcelFile } from './shippingDownload';
|
||||
import {
|
||||
@@ -45,6 +45,7 @@ export interface ShippingSendHandlerContext {
|
||||
attachmentPolicy: ComputedRef<{ anyEnabled: boolean }>;
|
||||
getActiveShippingTaskId: () => string;
|
||||
lastAssistantMessageContent: () => string;
|
||||
lastAssistantShippingActions: () => ChatMessage['shipping_actions'];
|
||||
sendMessage: (
|
||||
content: string,
|
||||
agentId: number,
|
||||
@@ -59,10 +60,13 @@ export interface ShippingSendHandlerContext {
|
||||
openShippingInventoryPicker: () => boolean;
|
||||
executeShippingDecision: (decision: string, displayText?: string) => Promise<boolean>;
|
||||
executeShippingManualUpload: (taskId: string, displayText?: string) => Promise<boolean>;
|
||||
handleShippingMenuAction: (action: { id?: string; message: string }) => Promise<void>;
|
||||
handleShippingAutoUploadFile: (file: File) => Promise<void>;
|
||||
handleShippingAutoUploadNoticeBatch: (files: File[]) => Promise<void>;
|
||||
refreshShippingActions: () => Promise<void>;
|
||||
shippingSuggestedPrompt: ComputedRef<string>;
|
||||
isShippingShortageQueryIntent: (text: string) => boolean;
|
||||
queryShippingShortageDetails: (taskNo?: string, displayText?: string) => Promise<boolean>;
|
||||
msg: { warning: (text: string) => void; info: (text: string) => void };
|
||||
t: (key: string) => string;
|
||||
}
|
||||
@@ -128,6 +132,7 @@ export function createShippingSendHandlers(ctx: ShippingSendHandlerContext) {
|
||||
if (!(ctx.shippingAutoFlowRequested.value || !trimmed)) return false;
|
||||
if (!ctx.isShippingNoticeAgent.value || ctx.attachments.value.length === 0) return false;
|
||||
if (ctx.isThinking.value || ctx.isUploadingAttachments.value) return false;
|
||||
const requestedAutoFlow = ctx.shippingAutoFlowRequested.value;
|
||||
ctx.shippingAutoFlowRequested.value = false;
|
||||
const localFiles = ctx.attachments.value.filter((a) => a.kind === 'local') as Array<Extract<PendingAttachment, { kind: 'local' }>>;
|
||||
const first = localFiles[0];
|
||||
@@ -152,12 +157,10 @@ export function createShippingSendHandlers(ctx: ShippingSendHandlerContext) {
|
||||
}
|
||||
return true;
|
||||
}
|
||||
if (!trimmed) {
|
||||
if (!trimmed || requestedAutoFlow) {
|
||||
if (typeof textOrEvent !== 'string') ctx.input.value = '';
|
||||
ctx.attachments.value = [];
|
||||
try {
|
||||
const prompt = ctx.shippingSuggestedPrompt.value || '解析发货通知并创建任务';
|
||||
await ctx.pushShippingLocalUserMessage(prompt);
|
||||
await ctx.handleShippingAutoUploadNoticeBatch(localFiles.map((item) => item.file));
|
||||
} catch (e: unknown) {
|
||||
const errorMessage = e instanceof Error ? e.message : '文件处理失败';
|
||||
@@ -174,12 +177,31 @@ export function createShippingSendHandlers(ctx: ShippingSendHandlerContext) {
|
||||
_trimmed: string,
|
||||
): Promise<boolean> => {
|
||||
if (!ctx.isShippingNoticeAgent.value) return false;
|
||||
if (ctx.isShippingShortageQueryIntent(content)) {
|
||||
if (typeof textOrEvent !== 'string') ctx.input.value = '';
|
||||
ctx.attachments.value = [];
|
||||
return ctx.queryShippingShortageDetails(undefined, content.trim());
|
||||
}
|
||||
if (await trySwitchShippingTask(content)) {
|
||||
if (typeof textOrEvent !== 'string') ctx.input.value = '';
|
||||
ctx.attachments.value = [];
|
||||
return true;
|
||||
}
|
||||
const assistantCtx = ctx.lastAssistantMessageContent();
|
||||
const numericText = content.trim();
|
||||
if (/^[1-91-9](?:[\.\、\)::]?)$/.test(numericText)) {
|
||||
const num = Number.isFinite(Number(numericText.charAt(0)))
|
||||
? Number(numericText.charAt(0))
|
||||
: '0123456789'.indexOf(numericText.charAt(0));
|
||||
const actions = ctx.lastAssistantShippingActions() || [];
|
||||
const action = num >= 1 ? actions[num - 1] : undefined;
|
||||
if (action) {
|
||||
if (typeof textOrEvent !== 'string') ctx.input.value = '';
|
||||
ctx.attachments.value = [];
|
||||
await ctx.handleShippingMenuAction(action);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
const menuChoice = resolveShippingNumericChoice(content, assistantCtx);
|
||||
if (menuChoice) {
|
||||
if (typeof textOrEvent !== 'string') ctx.input.value = '';
|
||||
@@ -188,6 +210,10 @@ export function createShippingSendHandlers(ctx: ShippingSendHandlerContext) {
|
||||
} else if (menuChoice === 'paste') {
|
||||
ctx.msg.info(ctx.t('chat.shippingNoticePasteHint'));
|
||||
return true;
|
||||
} else if (SHIPPING_DECISION_ACTIONS.has(menuChoice)) {
|
||||
const spec = SHIPPING_MENU_ACTION_SPECS[menuChoice];
|
||||
await ctx.executeShippingDecision(menuChoice, spec?.label || spec?.message || menuChoice);
|
||||
return true;
|
||||
} else {
|
||||
await ctx.sendShippingMenuMessage(SHIPPING_MENU_ACTION_SPECS[menuChoice].message);
|
||||
return true;
|
||||
|
||||
@@ -28,7 +28,6 @@ export interface ShippingUploadHandlerContext {
|
||||
resolvedShippingBatchNo: Ref<string>;
|
||||
shippingBatchSummary: Ref<unknown | null>;
|
||||
shippingBatchTasks: Ref<ShippingTaskSummary[]>;
|
||||
shippingBatchTasksExpanded: Ref<boolean>;
|
||||
shippingInventorySelectionActive: Ref<boolean>;
|
||||
shippingInventorySelectionTaskId: Ref<string>;
|
||||
shippingInventorySchemaPreviewCache: Ref<Record<string, unknown>>;
|
||||
@@ -270,8 +269,8 @@ export function createShippingUploadHandlers(ctx: ShippingUploadHandlerContext)
|
||||
| undefined;
|
||||
if (!first) return '';
|
||||
const kind = classifyShippingUploadFile(first.file, extractExt);
|
||||
if (kind === 'inventory') return '上传库存并进入字段对齐';
|
||||
return '解析发货通知并创建任务';
|
||||
if (kind === 'inventory') return ctx.t('chat.shippingNoticePrompt.notice.autoInventoryAction');
|
||||
return ctx.t('chat.shippingNoticePrompt.notice.autoNoticeAction');
|
||||
});
|
||||
|
||||
const useShippingSuggestedPrompt = () => {
|
||||
|
||||
Reference in new issue
Block a user