236 lines
9.6 KiB
TypeScript
236 lines
9.6 KiB
TypeScript
/**
|
||
* features/chat/shipping/useChatShippingDecision.ts
|
||
* 用途:封装人工决策提交与手工上传标记逻辑。
|
||
* 依赖:shipping.api、shippingDecisionFormat、chat.types。
|
||
* 逻辑:由 useChatShipping 调用本文件;本文件负责把 confirm/reject/reparse 等决策提交到后端,并生成聊天区本地消息。
|
||
*/
|
||
import {
|
||
markWorkspaceShippingManualUploaded,
|
||
submitWorkspaceShippingDecision,
|
||
} from '@/features/chat/api/shipping.api';
|
||
import { formatShippingDecisionAssistantMessage } from './shippingDecisionFormat';
|
||
import { reportShippingDebugEvent } from './shippingDebugReporter';
|
||
import type { ChatMessage, ChatSessionItem } from '../types/chat.types';
|
||
import type { ComputedRef, Ref } from 'vue';
|
||
|
||
export interface ShippingDecisionContext {
|
||
messages: Ref<ChatMessage[]>;
|
||
conversationId: Ref<string | null>;
|
||
history: Ref<ChatSessionItem[]>;
|
||
isShippingNoticeAgent: ComputedRef<boolean>;
|
||
shippingInventorySchemaPreviewCache: Ref<Record<string, unknown>>;
|
||
getActiveShippingTaskId: () => string;
|
||
newLocalMessageId: (prefix: string) => string;
|
||
saveLocalMessageToBackend: (msg: ChatMessage, userQuery?: string) => Promise<void>;
|
||
loadHistory: () => Promise<void>;
|
||
openShippingInventoryMappingFormForTask: (taskId: string) => Promise<boolean>;
|
||
refreshShippingActions: () => Promise<void>;
|
||
msg: { warning: (text: string) => void; success: (text: string) => void };
|
||
t: (key: string, params?: Record<string, unknown>) => string;
|
||
}
|
||
|
||
export interface ExecuteShippingDecisionOptions {
|
||
silent?: boolean;
|
||
taskId?: string;
|
||
}
|
||
|
||
/**
|
||
* 创建发货通知决策处理器。
|
||
*
|
||
* 核心逻辑:根据决策类型调用对应后端接口;默认同步本地用户/助手消息,也支持 silent 模式仅更新状态机与按钮。
|
||
* @param ctx - 决策处理上下文
|
||
* @returns 人工决策与手工上传确认处理函数
|
||
*/
|
||
export function createShippingDecisionHandlers(ctx: ShippingDecisionContext) {
|
||
const manualUploadInFlightTaskIds = new Set<string>();
|
||
|
||
// #region debug-point D:decision-submit
|
||
const reportRetryRpaDebug = (hypothesisId: string, msg: string, data: Record<string, unknown>) =>
|
||
reportShippingDebugEvent('useChatShippingDecision.ts', hypothesisId, msg, data);
|
||
// #endregion
|
||
|
||
const syncHistoryIfNeeded = async () => {
|
||
if (!ctx.conversationId.value && ctx.history.value.length === 0) {
|
||
await ctx.loadHistory();
|
||
} else if (ctx.conversationId.value) {
|
||
const exists = ctx.history.value.some((h) => h.conversation_id === ctx.conversationId.value);
|
||
if (!exists) await ctx.loadHistory();
|
||
}
|
||
};
|
||
|
||
/**
|
||
* 提交发货人工决策,并按需把结果落为本地聊天消息。
|
||
* 核心逻辑:优先使用 options.taskId 提交指定任务的决策;未显式传入时再回退到当前激活任务。
|
||
* 这样可避免工作台多任务场景在焦点刷新抖动时,把 retry_rpa 错投到空任务或直接中断。
|
||
* @param decision - 决策动作 ID,如 confirm、reparse_inventory
|
||
* @param displayText - 用户侧展示文案;未传时回退为 decision
|
||
* @param options.silent - 为 true 时只更新状态与按钮,不追加本地聊天消息
|
||
* @param options.taskId - 显式指定要提交决策的任务编号;工作台多票动作优先传入
|
||
* @returns 是否成功提交决策
|
||
*/
|
||
const executeShippingDecision = async (
|
||
decision: string,
|
||
displayText?: string,
|
||
options?: ExecuteShippingDecisionOptions,
|
||
) => {
|
||
const taskId = String(options?.taskId || ctx.getActiveShippingTaskId() || '').trim().toUpperCase();
|
||
// #region debug-point D:decision-entry
|
||
void reportRetryRpaDebug('D', 'executeShippingDecision entry', {
|
||
decision,
|
||
taskId,
|
||
conversationId: ctx.conversationId.value,
|
||
isShippingNoticeAgent: ctx.isShippingNoticeAgent.value,
|
||
silent: Boolean(options?.silent),
|
||
});
|
||
// #endregion
|
||
if (!taskId) {
|
||
// #region debug-point D:decision-missing-task
|
||
void reportRetryRpaDebug('D', 'executeShippingDecision missing taskId', {
|
||
decision,
|
||
conversationId: ctx.conversationId.value,
|
||
});
|
||
// #endregion
|
||
ctx.msg.warning(ctx.t('chat.shippingNoticeMissingTaskId'));
|
||
return false;
|
||
}
|
||
try {
|
||
// #region debug-point D:decision-before-submit
|
||
void reportRetryRpaDebug('D', 'executeShippingDecision before submit', {
|
||
decision,
|
||
taskId,
|
||
});
|
||
// #endregion
|
||
// 字段对齐确认必须走 submit_decision(confirm_inventory_mapping);
|
||
// auto_progress 在 align_review 只会再次返回同一检查点,造成点击确认后死循环。
|
||
const result = await submitWorkspaceShippingDecision(taskId, decision);
|
||
// #region debug-point D:decision-after-submit
|
||
void reportRetryRpaDebug('D', 'executeShippingDecision after submit', {
|
||
decision,
|
||
taskId,
|
||
message: String(result?.message || ''),
|
||
});
|
||
// #endregion
|
||
if (decision === 'correct_inventory_mapping') {
|
||
const preview = result?.data?.schema_preview;
|
||
const key = String(taskId || '').trim().toUpperCase();
|
||
if (key && preview && typeof preview === 'object') {
|
||
ctx.shippingInventorySchemaPreviewCache.value = {
|
||
...ctx.shippingInventorySchemaPreviewCache.value,
|
||
[key]: preview,
|
||
};
|
||
}
|
||
}
|
||
const userText = (displayText || decision).trim();
|
||
const assistantContent = formatShippingDecisionAssistantMessage(
|
||
decision,
|
||
result,
|
||
taskId,
|
||
ctx.t('chat.shippingNoticeDecisionDone'),
|
||
);
|
||
if (!options?.silent) {
|
||
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: assistantContent,
|
||
local_id: ctx.newLocalMessageId('shipping-assistant'),
|
||
local_only: true,
|
||
};
|
||
ctx.messages.value.push(userMsg, assistantMsg);
|
||
// #region debug-point D:decision-messages-appended
|
||
void reportRetryRpaDebug('D', 'executeShippingDecision appended local messages', {
|
||
decision,
|
||
taskId,
|
||
totalMessages: ctx.messages.value.length,
|
||
lastUserPreview: String(userMsg.content || '').slice(0, 80),
|
||
lastAssistantPreview: String(assistantContent || '').slice(0, 120),
|
||
});
|
||
// #endregion
|
||
await ctx.saveLocalMessageToBackend(userMsg, userText);
|
||
await ctx.saveLocalMessageToBackend(assistantMsg);
|
||
await syncHistoryIfNeeded();
|
||
}
|
||
// 工作台内的 shipping agent 决策以聊天气泡和任务卡刷新为主,避免 retry_rpa 再弹成功 toast 打断操作流。
|
||
if (result.message && !ctx.isShippingNoticeAgent.value) {
|
||
ctx.msg.success(result.message);
|
||
}
|
||
void ctx.refreshShippingActions();
|
||
if (decision === 'correct_inventory_mapping') {
|
||
await ctx.openShippingInventoryMappingFormForTask(taskId);
|
||
}
|
||
return true;
|
||
} catch (e: unknown) {
|
||
// #region debug-point D:decision-catch
|
||
void reportRetryRpaDebug('D', 'executeShippingDecision caught error', {
|
||
decision,
|
||
taskId,
|
||
errorMessage: e instanceof Error ? e.message : String(e),
|
||
});
|
||
// #endregion
|
||
const errorMessage = e instanceof Error ? e.message : ctx.t('chat.shippingNoticeUploadFailed');
|
||
ctx.msg.warning(errorMessage);
|
||
return false;
|
||
}
|
||
};
|
||
|
||
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(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,
|
||
local_id: ctx.newLocalMessageId('shipping-user'),
|
||
local_only: true,
|
||
};
|
||
const assistantMsg: ChatMessage = {
|
||
role: 'assistant',
|
||
type: 'text',
|
||
content: assistantContent,
|
||
local_id: ctx.newLocalMessageId('shipping-assistant'),
|
||
local_only: true,
|
||
shipping_actions_used: true,
|
||
};
|
||
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;
|
||
}
|
||
});
|
||
if (shouldAppendUser) {
|
||
await ctx.saveLocalMessageToBackend(userMsg, userText);
|
||
}
|
||
await ctx.saveLocalMessageToBackend(assistantMsg);
|
||
void ctx.refreshShippingActions();
|
||
return true;
|
||
} catch (e: unknown) {
|
||
const errorMessage = e instanceof Error ? e.message : '标记手工上传失败';
|
||
ctx.msg.warning(errorMessage);
|
||
return false;
|
||
} finally {
|
||
manualUploadInFlightTaskIds.delete(normalizedTaskId);
|
||
}
|
||
};
|
||
|
||
return { executeShippingDecision, executeShippingManualUpload };
|
||
}
|