feat(shipping-notice): 实现货代发货通知的库存全流程与对话交互
This commit is contained in:
1 parent
a5cc48b6aa
commit
2607f4a9f6
26 files changed
+5013
-256
No files matched your search
@@ -57,4 +57,73 @@ export const getWorkspaceShippingCase = (caseNo: string) =>
|
||||
export const workspaceShippingExportUrl = (caseNo: string) =>
|
||||
`/api/workspace/shipping-cases/${encodeURIComponent(caseNo)}/export`;
|
||||
|
||||
export interface ShippingChatAction {
|
||||
id: string;
|
||||
label: string;
|
||||
message: string;
|
||||
variant: 'primary' | 'secondary' | 'danger';
|
||||
}
|
||||
|
||||
export interface ShippingChatActionsResponse {
|
||||
case_no: string;
|
||||
checkpoint?: string | null;
|
||||
process_status: string;
|
||||
review_status?: string | null;
|
||||
pending_human_reason?: string | null;
|
||||
action_buttons: ShippingChatAction[];
|
||||
}
|
||||
|
||||
export const getShippingChatActions = (caseNo: string) =>
|
||||
getJson<ShippingChatActionsResponse>(
|
||||
`/api/workspace/shipping-cases/${encodeURIComponent(caseNo)}/chat-actions`,
|
||||
);
|
||||
|
||||
export async function uploadWorkspaceShippingInventory(caseNo: string, file: File) {
|
||||
const form = new FormData();
|
||||
form.append('file', file);
|
||||
const headers = getAuthHeaders();
|
||||
delete (headers as Record<string, string>)['Content-Type'];
|
||||
const res = await fetch(
|
||||
`/api/workspace/shipping-cases/${encodeURIComponent(caseNo)}/upload-inventory`,
|
||||
{ method: 'POST', headers, body: form },
|
||||
);
|
||||
const body = (await res.json().catch(() => ({}))) as ShippingInventoryUploadResponse & { error?: string };
|
||||
if (!res.ok) {
|
||||
throw new Error(body.error || body.message || res.statusText);
|
||||
}
|
||||
return body;
|
||||
}
|
||||
|
||||
export interface ShippingInventoryUploadResponse {
|
||||
status: string;
|
||||
message?: string;
|
||||
case_id?: string;
|
||||
checkpoint?: string;
|
||||
data?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export interface ShippingDecisionResponse {
|
||||
status: string;
|
||||
message?: string;
|
||||
case_id?: string;
|
||||
checkpoint?: string;
|
||||
data?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export async function submitWorkspaceShippingDecision(caseNo: string, decision: string, comment?: string) {
|
||||
const res = await fetch(
|
||||
`/api/workspace/shipping-cases/${encodeURIComponent(caseNo)}/submit-decision`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: { ...getAuthHeaders(), 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ decision, ...(comment ? { comment } : {}) }),
|
||||
},
|
||||
);
|
||||
const body = (await res.json().catch(() => ({}))) as ShippingDecisionResponse & { error?: string };
|
||||
if (!res.ok || body.status === 'failed') {
|
||||
throw new Error(body.error || body.message || res.statusText);
|
||||
}
|
||||
return body;
|
||||
}
|
||||
|
||||
export const SHIPPING_NOTICE_AGENT_NAME = '货代发货通知 Agent';
|
||||
@@ -30,6 +30,13 @@ interface ChatMessage {
|
||||
local_id?: string;
|
||||
local_only?: boolean;
|
||||
rated?: boolean;
|
||||
shipping_actions?: Array<{
|
||||
id: string;
|
||||
label: string;
|
||||
message: string;
|
||||
variant?: 'primary' | 'secondary' | 'danger';
|
||||
}>;
|
||||
shipping_actions_used?: boolean;
|
||||
}
|
||||
|
||||
type RunStatus = 'running' | 'done' | 'error';
|
||||
|
||||
+15
-1
@@ -1,4 +1,4 @@
|
||||
import { createI18n } from 'vue-i18n';
|
||||
import { createI18n } from 'vue-i18n';
|
||||
|
||||
const messages = {
|
||||
'en': {
|
||||
@@ -1269,6 +1269,13 @@ const messages = {
|
||||
disclaimer: 'AI can make mistakes. Please verify important information.',
|
||||
createNewChat: 'New Chat',
|
||||
shippingNoticeContinue: 'Please continue shipping case {caseId}. Call get_case_status first and tell me the next step.',
|
||||
shippingNoticeActionsHint: 'Choose an action (no need to type):',
|
||||
shippingNoticeMissingCaseId: 'Case ID not found. Complete shipping notice parsing first.',
|
||||
shippingNoticeUploadDone: 'Inventory file uploaded: {fileName}.',
|
||||
shippingNoticeUploadOk: 'Upload succeeded.',
|
||||
shippingNoticeUploadFailed: 'Inventory upload failed.',
|
||||
shippingNoticePasteHint: 'Paste inventory rows in the input box, then send.',
|
||||
shippingNoticeDecisionDone: 'Action completed.',
|
||||
clearAll: 'Clear All',
|
||||
clearOneRecord: 'Clear This Record',
|
||||
agents: 'Agents',
|
||||
@@ -2768,6 +2775,13 @@ const messages = {
|
||||
disclaimer: 'AI 可能会犯错,请核实重要信息。',
|
||||
createNewChat: '创建新对话',
|
||||
shippingNoticeContinue: '请继续处理发货任务 {caseId},请先调用 get_case_status 查询当前状态并告知我下一步。',
|
||||
shippingNoticeActionsHint: '请选择操作(无需输入文字):',
|
||||
shippingNoticeMissingCaseId: '未找到 case_id,请先完成发货通知解析。',
|
||||
shippingNoticeUploadDone: '库存文件已上传:{fileName}。',
|
||||
shippingNoticeUploadOk: '上传成功。',
|
||||
shippingNoticeUploadFailed: '库存文件上传失败。',
|
||||
shippingNoticePasteHint: '请在输入框粘贴库存小表内容后发送。',
|
||||
shippingNoticeDecisionDone: '操作已完成。',
|
||||
clearAll: '清空全部',
|
||||
clearOneRecord: '清除该记录',
|
||||
agents: '智能体',
|
||||
|
||||
@@ -46,6 +46,12 @@ import {
|
||||
getUserAgent,
|
||||
listUserAgents,
|
||||
} from '../api/user';
|
||||
import {
|
||||
getShippingChatActions,
|
||||
SHIPPING_NOTICE_AGENT_NAME,
|
||||
submitWorkspaceShippingDecision,
|
||||
uploadWorkspaceShippingInventory,
|
||||
} from '../api/shippingNotice';
|
||||
|
||||
const { t, locale } = useI18n();
|
||||
const { appliedTheme, toggleLightDark } = useTheme();
|
||||
@@ -714,6 +720,8 @@ const attachments = ref<PendingAttachment[]>([]);
|
||||
const attachmentUrlInput = ref('');
|
||||
const isUploadingAttachments = ref(false);
|
||||
const filePickerRef = ref<HTMLInputElement | null>(null);
|
||||
const shippingInventoryPickerRef = ref<HTMLInputElement | null>(null);
|
||||
const pendingShippingUploadCaseId = ref('');
|
||||
const attachmentMenuRef = ref<HTMLElement | null>(null);
|
||||
const attachmentUrlInputRef = ref<HTMLInputElement | null>(null);
|
||||
const showAttachmentMenu = ref(false);
|
||||
@@ -2062,6 +2070,427 @@ const shippingCaseIdFromQuery = computed(() => {
|
||||
return typeof value === 'string' ? value.trim() : '';
|
||||
});
|
||||
|
||||
const SHIPPING_CASE_ID_RE = /SN-\d{8}-[A-F0-9]{8}/i;
|
||||
|
||||
const isShippingNoticeAgent = computed(() => currentAgent.value?.name === SHIPPING_NOTICE_AGENT_NAME);
|
||||
|
||||
const findLatestShippingCaseId = (msgs: Array<{ content?: string }>) => {
|
||||
for (let i = msgs.length - 1; i >= 0; i -= 1) {
|
||||
const match = String(msgs[i]?.content || '').match(SHIPPING_CASE_ID_RE);
|
||||
if (match?.[0]) return match[0].toUpperCase();
|
||||
}
|
||||
return '';
|
||||
};
|
||||
|
||||
const shippingActionButtonClass = (variant?: string) => {
|
||||
if (variant === 'primary') {
|
||||
return 'rounded-xl bg-emerald-600 px-4 py-2 text-sm font-medium text-white transition hover:bg-emerald-700 disabled:cursor-not-allowed disabled:opacity-60';
|
||||
}
|
||||
if (variant === 'danger') {
|
||||
return 'rounded-xl border border-rose-200 bg-rose-50 px-4 py-2 text-sm font-medium text-rose-700 transition hover:bg-rose-100 disabled:cursor-not-allowed disabled:opacity-60';
|
||||
}
|
||||
return 'rounded-xl border border-default px-4 py-2 text-sm font-medium text-secondary transition hover:bg-surface-soft disabled:cursor-not-allowed disabled:opacity-60';
|
||||
};
|
||||
|
||||
type ShippingMenuAction = 'upload' | 'paste' | 'retry_rpa' | 'confirm' | 'reparse' | 'reject';
|
||||
|
||||
const SHIPPING_MENU_ACTION_SPECS: Record<
|
||||
ShippingMenuAction,
|
||||
{ id: string; label: string; message: string; variant: 'primary' | 'secondary' | 'danger' }
|
||||
> = {
|
||||
upload: { id: 'upload_inventory_file', label: '选择库存文件', message: '我要上传库存 Excel', variant: 'primary' },
|
||||
paste: { id: 'paste_inventory_json', label: '粘贴库存', message: '我粘贴库存小表', variant: 'secondary' },
|
||||
retry_rpa: { id: 'retry_rpa', label: '重试 RPA', message: '重试 RPA 导出库存', variant: 'secondary' },
|
||||
confirm: { id: 'confirm', label: '确认', message: '确认', variant: 'primary' },
|
||||
reparse: { id: 'reparse', label: '重新解析', message: '重新解析', variant: 'secondary' },
|
||||
reject: { id: 'reject', label: '驳回', message: '驳回', variant: 'danger' },
|
||||
};
|
||||
|
||||
const lastAssistantMessageContent = () => {
|
||||
for (let i = messages.value.length - 1; i >= 0; i -= 1) {
|
||||
const item = messages.value[i];
|
||||
if (item?.role === 'assistant') return String(item.content || '');
|
||||
}
|
||||
return '';
|
||||
};
|
||||
|
||||
const normalizeMenuDigit = (ch: string) => {
|
||||
const full = '0123456789';
|
||||
const idx = full.indexOf(ch);
|
||||
return idx >= 0 ? idx : Number(ch);
|
||||
};
|
||||
|
||||
const classifyShippingMenuLine = (desc: string): ShippingMenuAction | null => {
|
||||
if (/上传|excel|xlsx|xls|csv|库存文件|\.xlsx/i.test(desc)) return 'upload';
|
||||
if (/粘贴|文本|小量|直接发/i.test(desc)) return 'paste';
|
||||
if (/重试|rpa|拉取/i.test(desc)) return 'retry_rpa';
|
||||
if (/重新解析|重解析|reparse/i.test(desc)) return 'reparse';
|
||||
if (/驳回|取消|reject/i.test(desc)) return 'reject';
|
||||
if (/确认|confirm/i.test(desc)) return 'confirm';
|
||||
return null;
|
||||
};
|
||||
|
||||
const parseShippingMenuFromContext = (ctx: string): Map<number, ShippingMenuAction> => {
|
||||
const map = new Map<number, ShippingMenuAction>();
|
||||
for (const line of String(ctx || '').split('\n')) {
|
||||
const m = line.match(/^\s*([1-91-9])[\.、\)::]?\s*(.+)$/);
|
||||
if (!m?.[1] || !m[2]) continue;
|
||||
const num = normalizeMenuDigit(m[1]);
|
||||
if (!Number.isFinite(num) || num < 1) continue;
|
||||
const action = classifyShippingMenuLine(m[2]);
|
||||
if (action) map.set(num, action);
|
||||
}
|
||||
return map;
|
||||
};
|
||||
|
||||
const buildShippingMenuButtons = (ctx: string) => {
|
||||
const menu = parseShippingMenuFromContext(ctx);
|
||||
if (!menu.size) return null;
|
||||
return [...menu.entries()]
|
||||
.sort(([a], [b]) => a - b)
|
||||
.map(([num, action]) => {
|
||||
const spec = SHIPPING_MENU_ACTION_SPECS[action];
|
||||
return {
|
||||
...spec,
|
||||
label: `${num}. ${spec.label}`,
|
||||
};
|
||||
});
|
||||
};
|
||||
|
||||
const resolveShippingNumericChoice = (text: string): ShippingMenuAction | null => {
|
||||
const normalized = text.trim();
|
||||
if (!/^[1-91-9](?:[\.\、\)::]?)$/.test(normalized)) return null;
|
||||
const num = normalizeMenuDigit(normalized.charAt(0));
|
||||
return parseShippingMenuFromContext(lastAssistantMessageContent()).get(num) || null;
|
||||
};
|
||||
|
||||
const isShippingFieldAlignmentPrompt = (text: string) => {
|
||||
if (/无需确认|确认失败|已驳回|rejected|unfulfillable|重新创建|建议方案|不需要确认/.test(text)) {
|
||||
return false;
|
||||
}
|
||||
return (
|
||||
text.includes('【库存字段对齐确认')
|
||||
|| text.includes('字段对齐确认 —')
|
||||
|| (text.includes('请确认后才能匹配') && text.includes('field_alignment'))
|
||||
|| (text.includes('库存字段对齐') && text.includes('请确认'))
|
||||
);
|
||||
};
|
||||
|
||||
const inferShippingActionsFromContent = (content: string) => {
|
||||
const text = String(content || '');
|
||||
if (isShippingFieldAlignmentPrompt(text)) {
|
||||
return [
|
||||
{ id: 'confirm_inventory_mapping', label: '确认', message: '确认', variant: 'primary' as const },
|
||||
{ id: 'correct_inventory_mapping', label: '更正映射', message: '更正映射', variant: 'secondary' as const },
|
||||
{ id: 'reparse_inventory', label: '重新上传', message: '重新上传库存', variant: 'secondary' as const },
|
||||
{ id: 'reject', label: '取消', message: '驳回', variant: 'danger' as const },
|
||||
];
|
||||
}
|
||||
if (
|
||||
text.includes('请确认以上信息')
|
||||
|| text.includes('请确认以上')
|
||||
|| text.includes('请核对')
|
||||
|| text.includes('确认后继续')
|
||||
|| text.includes('回复「确认」')
|
||||
|| text.includes('回复"确认"')
|
||||
) {
|
||||
return [
|
||||
{ id: 'confirm', label: '确认', message: '确认', variant: 'primary' as const },
|
||||
{ id: 'reparse', label: '重新解析', message: '重新解析', variant: 'secondary' as const },
|
||||
{ id: 'reject', label: '驳回', message: '驳回', variant: 'danger' as const },
|
||||
];
|
||||
}
|
||||
if (text.includes('库存数量不足') || text.includes('缺口明细')) {
|
||||
return [
|
||||
{ id: 'confirm', label: '确认部分发货', message: '确认', variant: 'primary' as const },
|
||||
{ id: 'rematch', label: '重新匹配', message: '重新匹配', variant: 'secondary' as const },
|
||||
{ id: 'reject', label: '驳回', message: '驳回', variant: 'danger' as const },
|
||||
];
|
||||
}
|
||||
if (
|
||||
text.includes('waiting_inventory')
|
||||
|| text.includes('inventory_rpa_pending')
|
||||
|| text.includes('重试 RPA')
|
||||
|| text.includes('上传库存')
|
||||
|| text.includes('upload_inventory_file')
|
||||
|| /[1-3][\.\、\)]/.test(text)
|
||||
) {
|
||||
const menuButtons = buildShippingMenuButtons(text);
|
||||
if (menuButtons?.length) return menuButtons;
|
||||
return [
|
||||
{ id: 'upload_inventory_file', label: '选择库存文件', message: '我要上传库存 Excel', variant: 'primary' as const },
|
||||
{ id: 'paste_inventory_json', label: '粘贴库存', message: '我粘贴库存小表', variant: 'secondary' as const },
|
||||
{ id: 'retry_rpa', label: '重试 RPA', message: '重试 RPA 导出库存', variant: 'secondary' as const },
|
||||
];
|
||||
}
|
||||
return [];
|
||||
};
|
||||
|
||||
const SHIPPING_DECISION_ACTIONS = new Set([
|
||||
'confirm',
|
||||
'confirm_inventory_mapping',
|
||||
'correct_inventory_mapping',
|
||||
'reparse_inventory',
|
||||
'reject',
|
||||
'reparse',
|
||||
'rematch',
|
||||
]);
|
||||
|
||||
const resolveShippingDecisionFromText = (text: string): string | null => {
|
||||
const normalized = text.trim();
|
||||
const direct: Record<string, string> = {
|
||||
更正映射: 'correct_inventory_mapping',
|
||||
更正列映射: 'correct_inventory_mapping',
|
||||
重新上传库存: 'reparse_inventory',
|
||||
重新上传: 'reparse_inventory',
|
||||
驳回: 'reject',
|
||||
取消: 'reject',
|
||||
重新解析: 'reparse',
|
||||
重新匹配: 'rematch',
|
||||
};
|
||||
if (direct[normalized]) return direct[normalized];
|
||||
if (normalized === '确认') {
|
||||
const ctx = lastAssistantMessageContent();
|
||||
if (ctx.includes('字段对齐') || ctx.includes('field_alignment') || ctx.includes('库存字段对齐')) {
|
||||
return 'confirm_inventory_mapping';
|
||||
}
|
||||
return 'confirm';
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
const executeShippingDecision = async (decision: string, displayText?: string) => {
|
||||
const caseId = findLatestShippingCaseId(messages.value);
|
||||
if (!caseId) {
|
||||
msg.warning(t('chat.shippingNoticeMissingCaseId'));
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
const result = await submitWorkspaceShippingDecision(caseId, decision);
|
||||
const userText = (displayText || decision).trim();
|
||||
const assistantContent = formatShippingDecisionAssistantMessage(decision, result, caseId);
|
||||
const userMsg = {
|
||||
role: 'user' as const,
|
||||
content: `${userText} case_id=${caseId}`,
|
||||
local_id: newLocalMessageId('shipping-user'),
|
||||
local_only: true,
|
||||
};
|
||||
const assistantMsg = {
|
||||
role: 'assistant' as const,
|
||||
content: assistantContent,
|
||||
local_id: newLocalMessageId('shipping-assistant'),
|
||||
local_only: true,
|
||||
};
|
||||
messages.value.push(userMsg, assistantMsg);
|
||||
await saveLocalMessageToBackend(userMsg, userText);
|
||||
await saveLocalMessageToBackend(assistantMsg, userText);
|
||||
if (result.message) {
|
||||
msg.success(result.message);
|
||||
}
|
||||
if (!conversationId.value && history.value.length === 0) {
|
||||
await loadHistory();
|
||||
} else if (conversationId.value) {
|
||||
const exists = history.value.some((h) => h.conversation_id === conversationId.value);
|
||||
if (!exists) await loadHistory();
|
||||
}
|
||||
void refreshShippingActions();
|
||||
return true;
|
||||
} catch (e: any) {
|
||||
msg.warning(e?.message || t('chat.shippingNoticeUploadFailed'));
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
const formatShippingDecisionAssistantMessage = (
|
||||
decision: string,
|
||||
result: { message?: string; data?: Record<string, unknown>; checkpoint?: string },
|
||||
caseId: string,
|
||||
) => {
|
||||
const lines: string[] = [result.message || t('chat.shippingNoticeDecisionDone')];
|
||||
|
||||
if (decision === 'correct_inventory_mapping') {
|
||||
const preview = (result.data?.schema_preview || {}) as Record<string, any>;
|
||||
const headers = Array.isArray(preview.headers) ? preview.headers.filter(Boolean) : [];
|
||||
const suggested = (preview.suggested_mapping || {}) as Record<string, string>;
|
||||
if (preview.header_row_index) {
|
||||
lines.push('', `表头在第 ${preview.header_row_index} 行:${headers.join(' | ')}`);
|
||||
} else if (headers.length) {
|
||||
lines.push('', `当前表头:${headers.join(' | ')}`);
|
||||
}
|
||||
const mappingLines = [
|
||||
suggested.sku ? `- sku → ${suggested.sku}` : null,
|
||||
suggested.reservation_id ? `- reservation_id → ${suggested.reservation_id}` : null,
|
||||
suggested.available_qty ? `- available_qty → ${suggested.available_qty}` : null,
|
||||
].filter(Boolean);
|
||||
if (mappingLines.length) {
|
||||
lines.push('', '建议列映射:', ...mappingLines);
|
||||
}
|
||||
lines.push(
|
||||
'',
|
||||
'如需调整,请说明要改的列(例如:available_qty 改用 Qty Available)。',
|
||||
'也可点击「选择库存文件」重新上传。',
|
||||
);
|
||||
} else if (decision === 'confirm_inventory_mapping') {
|
||||
lines.push('', '下一步:匹配库存与发货需求(match_inventory)。');
|
||||
} else if (decision === 'reparse_inventory') {
|
||||
lines.push('', '请重新上传或粘贴库存 Excel。');
|
||||
}
|
||||
|
||||
lines.push('', `case_id=${caseId}`);
|
||||
return lines.join('\n');
|
||||
};
|
||||
|
||||
const openShippingInventoryPicker = (): boolean => {
|
||||
const caseId = findLatestShippingCaseId(messages.value);
|
||||
if (!caseId) {
|
||||
msg.warning(t('chat.shippingNoticeMissingCaseId'));
|
||||
return false;
|
||||
}
|
||||
pendingShippingUploadCaseId.value = caseId;
|
||||
shippingInventoryPickerRef.value?.click();
|
||||
return true;
|
||||
};
|
||||
|
||||
const isShippingInventoryUploadIntent = (text: string) => {
|
||||
const normalized = text.trim();
|
||||
if (!normalized) return false;
|
||||
|
||||
const choice = resolveShippingNumericChoice(normalized);
|
||||
if (choice === 'upload') return true;
|
||||
|
||||
return [
|
||||
/^上传库存$/,
|
||||
/上传库存文件/,
|
||||
/手工上传/,
|
||||
/选择库存/,
|
||||
/upload.*inventory/i,
|
||||
].some((pattern) => pattern.test(normalized));
|
||||
};
|
||||
|
||||
const sendShippingMenuMessage = async (message: string) => {
|
||||
const caseId = findLatestShippingCaseId(messages.value);
|
||||
const text = caseId ? `${message} case_id=${caseId}` : message;
|
||||
await sendMessage(text, agentId, selectedKb.value, []);
|
||||
if (!conversationId.value && history.value.length === 0) {
|
||||
await loadHistory();
|
||||
} else if (conversationId.value) {
|
||||
const exists = history.value.some((h) => h.conversation_id === conversationId.value);
|
||||
if (!exists) await loadHistory();
|
||||
}
|
||||
};
|
||||
|
||||
const handleShippingMenuAction = async (action: { id?: string; message: string }, msg?: any) => {
|
||||
if (isThinking.value) return;
|
||||
|
||||
if (action.id === 'upload_inventory_file') {
|
||||
openShippingInventoryPicker();
|
||||
return;
|
||||
}
|
||||
|
||||
if (action.id === 'paste_inventory_json') {
|
||||
if (typeof msg !== 'undefined') msg.shipping_actions_used = true;
|
||||
msg.info(t('chat.shippingNoticePasteHint'));
|
||||
return;
|
||||
}
|
||||
|
||||
if (action.id && SHIPPING_DECISION_ACTIONS.has(action.id)) {
|
||||
if (msg?.shipping_actions_used) return;
|
||||
if (msg) msg.shipping_actions_used = true;
|
||||
await executeShippingDecision(action.id, action.message);
|
||||
return;
|
||||
}
|
||||
|
||||
if (msg?.shipping_actions_used) return;
|
||||
if (msg) msg.shipping_actions_used = true;
|
||||
await sendShippingMenuMessage(action.message);
|
||||
};
|
||||
|
||||
let shippingActionsRequestSeq = 0;
|
||||
|
||||
const assistantMessageHasLaterUserReply = (msgs: Array<{ role?: string }>, index: number) =>
|
||||
msgs.slice(index + 1).some((item) => item.role === 'user');
|
||||
|
||||
const refreshShippingActions = async () => {
|
||||
if (!isShippingNoticeAgent.value) return;
|
||||
|
||||
const msgs = messages.value;
|
||||
if (!msgs.length) return;
|
||||
|
||||
const caseId = findLatestShippingCaseId(msgs);
|
||||
let apiButtons: Array<{ id: string; label: string; message: string; variant?: string }> | null = null;
|
||||
let apiResolved = false;
|
||||
|
||||
if (caseId && !isThinking.value) {
|
||||
const seq = ++shippingActionsRequestSeq;
|
||||
try {
|
||||
const data = await getShippingChatActions(caseId);
|
||||
if (seq === shippingActionsRequestSeq) {
|
||||
apiResolved = true;
|
||||
apiButtons = data.action_buttons?.length ? data.action_buttons : [];
|
||||
}
|
||||
} catch {
|
||||
// fall back to content-based buttons
|
||||
}
|
||||
}
|
||||
|
||||
let lastOpenAssistantIndex = -1;
|
||||
for (let i = msgs.length - 1; i >= 0; i -= 1) {
|
||||
const item = msgs[i];
|
||||
if (item?.role !== 'assistant') continue;
|
||||
if (assistantMessageHasLaterUserReply(msgs, i)) continue;
|
||||
lastOpenAssistantIndex = i;
|
||||
break;
|
||||
}
|
||||
|
||||
msgs.forEach((rawMsg, index) => {
|
||||
const msg = rawMsg as any;
|
||||
if (msg.role !== 'assistant' || msg.shipping_actions_used) {
|
||||
return;
|
||||
}
|
||||
if (msg.type && !['text', undefined].includes(msg.type)) {
|
||||
msg.shipping_actions = undefined;
|
||||
return;
|
||||
}
|
||||
if (assistantMessageHasLaterUserReply(msgs, index)) {
|
||||
msg.shipping_actions = undefined;
|
||||
return;
|
||||
}
|
||||
|
||||
let buttons: Array<{ id: string; label: string; message: string; variant?: string }> = [];
|
||||
if (apiResolved && index === lastOpenAssistantIndex) {
|
||||
buttons = apiButtons || [];
|
||||
} else if (!apiResolved) {
|
||||
buttons = inferShippingActionsFromContent(String(msg.content || ''));
|
||||
}
|
||||
msg.shipping_actions = buttons.length ? buttons : undefined;
|
||||
});
|
||||
};
|
||||
|
||||
watch([messages, isThinking, isShippingNoticeAgent, () => currentAgent.value?.name], () => {
|
||||
void refreshShippingActions();
|
||||
}, { deep: true });
|
||||
|
||||
const handleShippingActionClick = async (msg: any, action: { id?: string; message: string }) => {
|
||||
await handleShippingMenuAction(action, msg);
|
||||
};
|
||||
|
||||
const handleShippingInventorySelected = async (event: Event) => {
|
||||
const input = event.target as HTMLInputElement;
|
||||
const file = input.files?.[0];
|
||||
input.value = '';
|
||||
const caseId = pendingShippingUploadCaseId.value;
|
||||
pendingShippingUploadCaseId.value = '';
|
||||
if (!file || !caseId) return;
|
||||
|
||||
try {
|
||||
const result = await uploadWorkspaceShippingInventory(caseId, file);
|
||||
const hint = result.message || t('chat.shippingNoticeUploadOk');
|
||||
await handleSend(`${t('chat.shippingNoticeUploadDone', { fileName: file.name })} ${hint} case_id=${caseId}`);
|
||||
} catch (e: any) {
|
||||
msg.warning(e?.message || t('chat.shippingNoticeUploadFailed'));
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* handleSend
|
||||
* 用途:将输入框内容发送给当前 Agent
|
||||
@@ -2076,6 +2505,33 @@ const handleSend = async (textOrEvent?: string | Event) => {
|
||||
return;
|
||||
}
|
||||
|
||||
if (isShippingNoticeAgent.value) {
|
||||
const menuChoice = resolveShippingNumericChoice(content);
|
||||
if (menuChoice) {
|
||||
if (typeof textOrEvent !== 'string') input.value = '';
|
||||
if (menuChoice === 'upload') {
|
||||
if (openShippingInventoryPicker()) return;
|
||||
} else if (menuChoice === 'paste') {
|
||||
msg.info(t('chat.shippingNoticePasteHint'));
|
||||
return;
|
||||
} else {
|
||||
await sendShippingMenuMessage(SHIPPING_MENU_ACTION_SPECS[menuChoice].message);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
const shippingDecision = resolveShippingDecisionFromText(content);
|
||||
if (shippingDecision) {
|
||||
if (typeof textOrEvent !== 'string') input.value = '';
|
||||
if (await executeShippingDecision(shippingDecision, content.trim())) return;
|
||||
}
|
||||
|
||||
if (isShippingInventoryUploadIntent(content)) {
|
||||
if (typeof textOrEvent !== 'string') input.value = '';
|
||||
if (openShippingInventoryPicker()) return;
|
||||
}
|
||||
}
|
||||
|
||||
let files: ChatUploadFileSpec[] = [];
|
||||
if (attachmentPolicy.value.anyEnabled && attachments.value.length > 0) {
|
||||
try {
|
||||
@@ -3076,6 +3532,24 @@ const showChatRating = ref(false);
|
||||
@click="handleChatMarkdownClick"
|
||||
v-html="renderMarkdown(msg.content)"
|
||||
></div>
|
||||
<div
|
||||
v-if="isShippingNoticeAgent && msg.shipping_actions?.length && !msg.shipping_actions_used"
|
||||
class="mt-4 space-y-2 border-t border-default pt-4"
|
||||
>
|
||||
<div class="text-xs font-medium text-muted">{{ $t('chat.shippingNoticeActionsHint') }}</div>
|
||||
<div class="flex flex-wrap gap-2">
|
||||
<button
|
||||
v-for="action in msg.shipping_actions"
|
||||
:key="`${msg.local_id || index}-shipping-action-${action.id}`"
|
||||
type="button"
|
||||
:class="shippingActionButtonClass(action.variant)"
|
||||
:disabled="isThinking"
|
||||
@click="handleShippingActionClick(msg, action)"
|
||||
>
|
||||
{{ action.label }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -3224,6 +3698,14 @@ const showChatRating = ref(false);
|
||||
autocapitalize="off"
|
||||
></textarea>
|
||||
|
||||
<input
|
||||
ref="shippingInventoryPickerRef"
|
||||
type="file"
|
||||
class="hidden"
|
||||
accept=".xlsx,.xls,.csv,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel,text/csv"
|
||||
@change="handleShippingInventorySelected"
|
||||
/>
|
||||
|
||||
<input
|
||||
ref="filePickerRef"
|
||||
type="file"
|
||||
|
||||
Reference in new issue
Block a user