refactor(frontend): 重构前端第二版
This commit is contained in:
1 parent
2631f78b00
commit
4b562cfa82
205 files changed
+15399
-12015
No files matched your search
@@ -0,0 +1,17 @@
|
||||
/** 出货(shipping)子模块 barrel:纯函数 + handler 工厂 + 动作刷新 */
|
||||
export * from './shippingText';
|
||||
export * from './shippingMenu';
|
||||
export * from './shippingIntents';
|
||||
export * from './shippingMapping';
|
||||
export * from './shippingTaskId';
|
||||
export * from './shippingDownload';
|
||||
export * from './shippingDecisionFormat';
|
||||
export * from './shippingUploadPrompt';
|
||||
export * from './shippingLocalMessages';
|
||||
export * from './shippingConversation';
|
||||
export * from './useChatShippingRefresh';
|
||||
export * from './useChatShippingMappingForm';
|
||||
export * from './useChatShippingDecision';
|
||||
export * from './useChatShippingMenuHandler';
|
||||
export * from './useChatShippingUploadHandler';
|
||||
export * from './useChatShippingSendHandler';
|
||||
@@ -0,0 +1,42 @@
|
||||
/**
|
||||
* 出货聊天:会话侧栏同步、带任务编号的菜单消息发送。
|
||||
*/
|
||||
import type { ChatSessionItem } from '../types/chat.types';
|
||||
import type { ChatUploadFileSpec } from '../types/shipping.types';
|
||||
import type { ComputedRef, Ref } from 'vue';
|
||||
|
||||
export interface ShippingConversationContext {
|
||||
conversationId: Ref<string | null>;
|
||||
history: Ref<ChatSessionItem[]>;
|
||||
loadHistory: () => Promise<void>;
|
||||
getActiveShippingTaskId: () => string;
|
||||
currentAgentId: ComputedRef<number>;
|
||||
selectedKb: Ref<string>;
|
||||
sendMessage: (
|
||||
content: string,
|
||||
agentId: number,
|
||||
kb: string,
|
||||
files: ChatUploadFileSpec[],
|
||||
) => Promise<void>;
|
||||
}
|
||||
|
||||
/** 发送菜单类消息后,若当前会话尚未出现在侧栏历史中则刷新列表 */
|
||||
export async function ensureShippingHistorySynced(ctx: ShippingConversationContext) {
|
||||
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();
|
||||
}
|
||||
}
|
||||
|
||||
export function createShippingConversationHelpers(ctx: ShippingConversationContext) {
|
||||
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 ensureShippingHistorySynced(ctx);
|
||||
};
|
||||
|
||||
return { sendShippingMenuMessage, ensureShippingHistorySynced };
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
/**
|
||||
* 出货聊天:决策 API 响应 → 助手消息 Markdown 文案(纯函数)。
|
||||
*/
|
||||
export function formatShippingDecisionAssistantMessage(
|
||||
decision: string,
|
||||
result: { message?: string; data?: Record<string, unknown>; checkpoint?: string },
|
||||
taskId: string,
|
||||
fallbackDoneMessage: string,
|
||||
): string {
|
||||
const lines: string[] = [result.message || fallbackDoneMessage];
|
||||
if (decision === 'correct_inventory_mapping') {
|
||||
const preview = (result.data?.schema_preview || {}) as Record<string, unknown>;
|
||||
const headers = Array.isArray(preview.headers) ? (preview.headers as unknown[]).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((line): line is string => Boolean(line));
|
||||
if (mappingLines.length) {
|
||||
lines.push('', '建议列映射:', ...mappingLines);
|
||||
}
|
||||
lines.push(
|
||||
'',
|
||||
'如需调整,请说明要改的列(例如:available_qty 改用 Qty Available)。',
|
||||
'也可点击「选择库存文件」重新上传。',
|
||||
);
|
||||
} else if (decision === 'confirm_inventory_mapping') {
|
||||
if (String(result.checkpoint || '').trim() === 'map_ok') {
|
||||
lines.push('', '下一步:匹配库存与发货需求(match_inventory)。');
|
||||
}
|
||||
} else if (decision === 'reparse_inventory') {
|
||||
lines.push('', '请重新上传或粘贴库存 Excel。');
|
||||
}
|
||||
lines.push('', `任务编号:${taskId}`);
|
||||
return lines.join('\n');
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
/**
|
||||
* 出货聊天:发货 Excel 浏览器下载(触发 a[download])。
|
||||
*/
|
||||
import { workspaceShippingExportUrl } from '@/features/chat/api/shipping.api';
|
||||
import { getAuthHeaders } from '@/shared/utils/auth';
|
||||
|
||||
export async function downloadWorkspaceShippingExcelFile(taskId: string): Promise<void> {
|
||||
const url = workspaceShippingExportUrl(taskId);
|
||||
const res = await fetch(url, { headers: getAuthHeaders() });
|
||||
if (!res.ok) {
|
||||
const body = await res.json().catch(() => ({}));
|
||||
throw new Error((body as { error?: string; message?: string })?.error || (body as { message?: string })?.message || res.statusText);
|
||||
}
|
||||
const disposition = res.headers.get('content-disposition');
|
||||
const blob = await res.blob();
|
||||
const objectUrl = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = objectUrl;
|
||||
const rawName = disposition?.match(/filename\*?=(?:UTF-8'')?["']?([^;"'\n]+)/)?.[1] || `${taskId}.xlsx`;
|
||||
try {
|
||||
a.download = decodeURIComponent(rawName);
|
||||
} catch {
|
||||
a.download = rawName;
|
||||
}
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
document.body.removeChild(a);
|
||||
URL.revokeObjectURL(objectUrl);
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
/**
|
||||
* 出货聊天:用户输入意图识别(纯函数,供 handleSend 前置拦截)。
|
||||
*
|
||||
* 覆盖:手工上传声明、库存上传、生成/下载 Excel、自然语言列映射(sku→列名)。
|
||||
*/
|
||||
import { resolveShippingNumericChoice } from './shippingMenu';
|
||||
import type { ShippingMenuAction } from '../types/shipping.types';
|
||||
|
||||
export function parseShippingColumnMappingFromText(content: string): Record<string, string> | null {
|
||||
const raw = String(content || '').trim();
|
||||
if (!raw) return null;
|
||||
if (!/[→>=-]/.test(raw)) return null;
|
||||
const lines = raw.split(/\r?\n/).map((s) => s.trim()).filter(Boolean);
|
||||
const mapping: Record<string, string> = {};
|
||||
const normalizeRight = (s: string) => String(s || '')
|
||||
.replace(/[::]/g, '')
|
||||
.replace(/列$/g, '')
|
||||
.replace(/字段$/g, '')
|
||||
.replace(/^\[|\]$/g, '')
|
||||
.trim();
|
||||
const toKey = (left: string) => {
|
||||
const s = left.toLowerCase();
|
||||
if (s.includes('reservation') || left.includes('预留') || left.includes('预定')) return 'reservation_id';
|
||||
if (s.includes('qty') || s.includes('available') || left.includes('可用') || left.includes('数量')) return 'available_qty';
|
||||
if (s.includes('sku') || left.includes('料号') || left.includes('物料')) return 'sku';
|
||||
return '';
|
||||
};
|
||||
for (const line of lines) {
|
||||
const m = line.match(/^\s*(.+?)\s*(?:→|->|=>|=|:|:)\s*(.+?)\s*$/);
|
||||
if (!m) continue;
|
||||
const left = m[1];
|
||||
const right = m[2];
|
||||
if (!left || !right) continue;
|
||||
const key = toKey(left.trim());
|
||||
if (!key) continue;
|
||||
const col = normalizeRight(right);
|
||||
if (!col) continue;
|
||||
mapping[key] = col;
|
||||
}
|
||||
if (!mapping.sku || !mapping.available_qty) return null;
|
||||
return mapping;
|
||||
}
|
||||
|
||||
export function isShippingManualUploadIntent(text: string): boolean {
|
||||
const normalized = text.trim();
|
||||
if (!normalized) return false;
|
||||
return [
|
||||
/已在货代系统手工上传/,
|
||||
/已手工上传/,
|
||||
/手工上传完成/,
|
||||
/手动上传完成/,
|
||||
/货代.*上传完成/,
|
||||
].some((pattern) => pattern.test(normalized));
|
||||
}
|
||||
|
||||
export function isShippingInventoryUploadIntent(text: string, assistantContext: string): boolean {
|
||||
const normalized = text.trim();
|
||||
if (!normalized) return false;
|
||||
const choice = resolveShippingNumericChoice(normalized, assistantContext);
|
||||
if (choice === 'upload') return true;
|
||||
return [
|
||||
/^上传库存$/,
|
||||
/上传库存文件/,
|
||||
/手工上传/,
|
||||
/选择库存/,
|
||||
/upload.*inventory/i,
|
||||
].some((pattern) => pattern.test(normalized));
|
||||
}
|
||||
|
||||
export function isShippingGenerateExcelIntent(text: string): boolean {
|
||||
const normalized = text.trim();
|
||||
if (!normalized) return false;
|
||||
return [
|
||||
/^生成发货excel$/i,
|
||||
/^生成发货\s*excel$/i,
|
||||
/生成发货.*excel/i,
|
||||
/生成.*发货.*excel/i,
|
||||
].some((pattern) => pattern.test(normalized));
|
||||
}
|
||||
|
||||
export function isShippingDownloadExcelIntent(text: string): boolean {
|
||||
const normalized = text.trim();
|
||||
if (!normalized) return false;
|
||||
return [
|
||||
/^下载excel$/i,
|
||||
/^下载发货excel$/i,
|
||||
/下载.*excel/i,
|
||||
].some((pattern) => pattern.test(normalized));
|
||||
}
|
||||
|
||||
export type { ShippingMenuAction };
|
||||
@@ -0,0 +1,43 @@
|
||||
/**
|
||||
* 出货聊天:本地消息写入(不经过 Dify SSE,直接 push 到 messages 并落库)。
|
||||
*/
|
||||
import type { ChatMessage } from '../types/chat.types';
|
||||
import type { Ref } from 'vue';
|
||||
|
||||
export interface ShippingLocalMessageContext {
|
||||
messages: Ref<ChatMessage[]>;
|
||||
newLocalMessageId: (prefix: string) => string;
|
||||
saveLocalMessageToBackend: (msg: ChatMessage, userQuery?: string) => Promise<void>;
|
||||
}
|
||||
|
||||
export function createShippingLocalMessages(ctx: ShippingLocalMessageContext) {
|
||||
const pushShippingLocalUserMessage = async (text: string) => {
|
||||
const content = String(text || '').trim();
|
||||
if (!content) return;
|
||||
const userMsg: ChatMessage = {
|
||||
role: 'user',
|
||||
type: 'text',
|
||||
content,
|
||||
local_id: ctx.newLocalMessageId('shipping-user'),
|
||||
local_only: true,
|
||||
};
|
||||
ctx.messages.value.push(userMsg);
|
||||
await ctx.saveLocalMessageToBackend(userMsg, content);
|
||||
};
|
||||
|
||||
const pushShippingLocalAssistantMessage = async (text: string) => {
|
||||
const content = String(text || '').trim();
|
||||
if (!content) return;
|
||||
const assistantMsg: ChatMessage = {
|
||||
role: 'assistant',
|
||||
type: 'text',
|
||||
content,
|
||||
local_id: ctx.newLocalMessageId('shipping-assistant'),
|
||||
local_only: true,
|
||||
};
|
||||
ctx.messages.value.push(assistantMsg);
|
||||
await ctx.saveLocalMessageToBackend(assistantMsg);
|
||||
};
|
||||
|
||||
return { pushShippingLocalUserMessage, pushShippingLocalAssistantMessage };
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
/**
|
||||
* 出货聊天:库存列映射 payload 读取与字段对齐 Markdown 生成(纯函数)。
|
||||
*
|
||||
* 消息 type === 'shipping-inventory-mapping' 时 payload 含 schema_preview + form。
|
||||
*/
|
||||
import { normalizeShippingHeaderForDisplay } from './shippingText';
|
||||
import type { ChatMessage } from '../types/chat.types';
|
||||
import type { ShippingInventoryMappingFormPayload } from '../types/shipping.types';
|
||||
|
||||
export function getShippingInventoryMappingPayload(chatMsg: ChatMessage): ShippingInventoryMappingFormPayload | null {
|
||||
if (!chatMsg || chatMsg.type !== 'shipping-inventory-mapping') return null;
|
||||
const payload = chatMsg.payload;
|
||||
if (!payload || typeof payload !== 'object') return null;
|
||||
const taskId = String((payload as ShippingInventoryMappingFormPayload).taskId || '').trim();
|
||||
const schemaPreview = (payload as ShippingInventoryMappingFormPayload).schema_preview;
|
||||
const form = (payload as ShippingInventoryMappingFormPayload).form;
|
||||
if (!taskId || !schemaPreview || !form) return null;
|
||||
return payload as ShippingInventoryMappingFormPayload;
|
||||
}
|
||||
|
||||
export function hasShippingInventorySampleRows(chatMsg: ChatMessage): boolean {
|
||||
const rows = getShippingInventoryMappingPayload(chatMsg)?.schema_preview?.sample_rows;
|
||||
return Array.isArray(rows) && rows.length > 0;
|
||||
}
|
||||
|
||||
export function getShippingInventorySampleRowText(chatMsg: ChatMessage): string {
|
||||
const row = getShippingInventoryMappingPayload(chatMsg)?.schema_preview?.sample_rows?.[0];
|
||||
return Array.isArray(row) ? row.map((cell) => String(cell)).join(' | ') : '';
|
||||
}
|
||||
|
||||
export function buildShippingFieldAlignmentText(payload: { data?: { field_alignment?: Record<string, unknown> } }): string {
|
||||
const alignment = payload?.data?.field_alignment;
|
||||
if (!alignment || typeof alignment !== 'object') return '';
|
||||
const invCols = (alignment as { inventory_columns?: { mapping?: Record<string, { source_column?: string }> } }).inventory_columns || {};
|
||||
const mapping = invCols.mapping || {};
|
||||
const rows: Array<[string, string]> = [
|
||||
['sku', normalizeShippingHeaderForDisplay(mapping?.sku?.source_column) || '(未识别)'],
|
||||
['reservation_id', normalizeShippingHeaderForDisplay(mapping?.reservation_id?.source_column) || '(未识别/可选)'],
|
||||
['available_qty', normalizeShippingHeaderForDisplay(mapping?.available_qty?.source_column) || '(未识别)'],
|
||||
];
|
||||
const lines: string[] = [];
|
||||
const matchRule = String((alignment as { match_rule?: string }).match_rule || '').trim();
|
||||
if (matchRule) lines.push(`匹配规则:${matchRule}`);
|
||||
lines.push('', '字段对齐表:', '', '|系统字段|库存列|', '|---|---|');
|
||||
for (const [k, v] of rows) {
|
||||
lines.push(`|${k}|${v}|`);
|
||||
}
|
||||
const warnings = Array.isArray((alignment as { warnings?: unknown[] }).warnings)
|
||||
? (alignment as { warnings: unknown[] }).warnings.filter(Boolean)
|
||||
: [];
|
||||
if (warnings.length) {
|
||||
lines.push('', '提示:', ...warnings.map((w) => `- ${String(w)}`));
|
||||
}
|
||||
return lines.join('\n').trim();
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
/**
|
||||
* 出货聊天:数字菜单解析、动作按钮合并、决策文本识别(纯函数)。
|
||||
*
|
||||
* 菜单行格式示例:「1. 上传库存文件」→ action: upload
|
||||
* resolveShippingActionButtons:优先 API 按钮,其次 HTML 指令,最后内容推断
|
||||
*/
|
||||
import { extractShippingActionsDirective } from './shippingText';
|
||||
import type { ShippingActionButton, ShippingMenuAction } from '../types/shipping.types';
|
||||
|
||||
export function shippingActionButtonClass(variant?: string): 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';
|
||||
}
|
||||
|
||||
export function normalizeMenuDigit(ch: string): number {
|
||||
const full = '0123456789';
|
||||
const idx = full.indexOf(ch);
|
||||
return idx >= 0 ? idx : Number(ch);
|
||||
}
|
||||
|
||||
export function classifyShippingMenuLine(desc: string): ShippingMenuAction | null {
|
||||
const normalized = String(desc || '').trim();
|
||||
if (!normalized) return null;
|
||||
if (/已确认/.test(normalized)) return null;
|
||||
if (/(?:选择|上传).*(?:库存|excel|xlsx|xls|csv)/i.test(normalized)) return 'upload';
|
||||
if (/粘贴|文本|小量|直接发/i.test(desc)) return 'paste';
|
||||
if (/(?:重试|重新)\s*RPA|重试.*(?:导出|获取|拉取)|RPA.*(?:导出|获取|拉取).*重试/i.test(desc)) return 'retry_rpa';
|
||||
if (/重新解析|重解析|reparse/i.test(desc)) return 'reparse';
|
||||
if (/驳回|取消|reject/i.test(desc)) return 'reject';
|
||||
if (/^(?:确认|confirm)\b/i.test(normalized)) return 'confirm';
|
||||
return null;
|
||||
}
|
||||
|
||||
export function parseShippingMenuFromContext(
|
||||
ctx: string,
|
||||
): Map<number, { action: ShippingMenuAction; desc: string }> {
|
||||
const map = new Map<number, { action: ShippingMenuAction; desc: string }>();
|
||||
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 desc = String(m[2] || '').trim();
|
||||
const action = classifyShippingMenuLine(desc);
|
||||
if (action) map.set(num, { action, desc });
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
export function resolveShippingNumericChoice(
|
||||
text: string,
|
||||
assistantContext: string,
|
||||
): ShippingMenuAction | null {
|
||||
const normalized = text.trim();
|
||||
if (!/^[1-91-9](?:[\.\、\)::]?)$/.test(normalized)) return null;
|
||||
const num = normalizeMenuDigit(normalized.charAt(0));
|
||||
return parseShippingMenuFromContext(assistantContext).get(num)?.action || null;
|
||||
}
|
||||
|
||||
export function normalizeApiShippingButtons(
|
||||
apiButtons: Array<{ id: string; label: string; message: string; variant?: string }> | null,
|
||||
): ShippingActionButton[] {
|
||||
return (apiButtons || []).map((button) => ({
|
||||
...button,
|
||||
variant: (button.variant === 'primary' || button.variant === 'secondary' || button.variant === 'danger')
|
||||
? button.variant
|
||||
: undefined,
|
||||
}));
|
||||
}
|
||||
|
||||
export function resolveShippingActionButtons(
|
||||
content: string,
|
||||
apiButtons: Array<{ id: string; label: string; message: string; variant?: string }> | null,
|
||||
opts?: { apiResolved?: boolean },
|
||||
) {
|
||||
const directive = extractShippingActionsDirective(String(content || ''));
|
||||
if (opts?.apiResolved) {
|
||||
return {
|
||||
buttons: normalizeApiShippingButtons(apiButtons),
|
||||
cleanedText: directive.cleanedText,
|
||||
fromDirective: false,
|
||||
};
|
||||
}
|
||||
if (directive.buttons.length) {
|
||||
return { buttons: directive.buttons, cleanedText: directive.cleanedText, fromDirective: true };
|
||||
}
|
||||
if (apiButtons?.length) {
|
||||
return { buttons: normalizeApiShippingButtons(apiButtons), cleanedText: directive.cleanedText, fromDirective: false };
|
||||
}
|
||||
return { buttons: [], cleanedText: directive.cleanedText, fromDirective: false };
|
||||
}
|
||||
|
||||
export function resolveShippingDecisionFromText(text: string, assistantContext: 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 === '确认') {
|
||||
if (assistantContext.includes('字段对齐') || assistantContext.includes('field_alignment') || assistantContext.includes('库存字段对齐')) {
|
||||
return 'confirm_inventory_mapping';
|
||||
}
|
||||
return 'confirm';
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
/**
|
||||
* 出货聊天:任务编号提取(纯函数)。
|
||||
*
|
||||
* 从消息正文匹配 SHIPPING_TASK_ID_RE,或从侧栏会话标题模糊查找。
|
||||
*/
|
||||
import { SHIPPING_TASK_ID_RE } from '../constants/shipping';
|
||||
import type { ChatSessionItem } from '../types/chat.types';
|
||||
|
||||
export function findLatestShippingTaskId(msgs: Array<{ content?: string }>): string {
|
||||
for (let i = msgs.length - 1; i >= 0; i -= 1) {
|
||||
const match = String(msgs[i]?.content || '').match(SHIPPING_TASK_ID_RE);
|
||||
if (match?.[0]) return match[0].toUpperCase();
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
export function findHistorySessionForShippingTask(
|
||||
history: ChatSessionItem[],
|
||||
taskId: string,
|
||||
): ChatSessionItem | null {
|
||||
const needle = taskId.trim().toUpperCase();
|
||||
if (!needle) return null;
|
||||
return history.find((item) => String(item.title || '').toUpperCase().includes(needle)) || null;
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
/**
|
||||
* 出货聊天:消息文本净化与动作指令解析(纯函数,无 Vue 依赖)。
|
||||
*
|
||||
* - sanitizeShippingConversationText:隐藏后台状态 token,统一 task_id 展示
|
||||
* - extractShippingActionsDirective:解析 <!-- HXOPS_SHIPPING_ACTIONS --> 注释块
|
||||
* - normalizeShippingHeaderForDisplay:表头列名展示(空格转 NBSP)
|
||||
*/
|
||||
import { SHIPPING_INTERNAL_STATUS_TOKENS, SHIPPING_KNOWN_ACTION_ID_SET } from '@/constants/shippingNoticeActions';
|
||||
import type { ShippingActionButton, ShippingActionVariant } from '../types/shipping.types';
|
||||
|
||||
export function sanitizeShippingConversationText(text: string, enabled: boolean): string {
|
||||
if (!enabled) return text;
|
||||
let result = String(text || '')
|
||||
.replace(/\btask_id\s*[::]/gi, '任务编号:')
|
||||
.replace(/\btask_id\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,
|
||||
'',
|
||||
);
|
||||
for (const token of SHIPPING_INTERNAL_STATUS_TOKENS) {
|
||||
const quoted = new RegExp(`[「"'“”‘’]\\s*${token}\\s*[」"'“”‘’]`, 'gi');
|
||||
result = result.replace(quoted, '');
|
||||
result = result.replace(new RegExp(`\`${token}\``, 'gi'), '');
|
||||
}
|
||||
return result.replace(/\n{3,}/g, '\n\n').trim();
|
||||
}
|
||||
|
||||
export function extractShippingActionsDirective(rawText: string): {
|
||||
cleanedText: string;
|
||||
buttons: ShippingActionButton[];
|
||||
} {
|
||||
const text = String(rawText || '');
|
||||
const re = /<!--\s*HXOPS_SHIPPING_ACTIONS\s*:\s*([\s\S]*?)\s*-->/gi;
|
||||
const buttons: ShippingActionButton[] = [];
|
||||
for (;;) {
|
||||
const m = re.exec(text);
|
||||
if (!m) break;
|
||||
const body = String(m[1] || '').trim();
|
||||
if (!body) continue;
|
||||
try {
|
||||
const parsed = JSON.parse(body);
|
||||
if (Array.isArray(parsed)) {
|
||||
for (const item of parsed) {
|
||||
if (!item || typeof item !== 'object') continue;
|
||||
const id = String((item as Record<string, unknown>).id || '').trim();
|
||||
const label = String((item as Record<string, unknown>).label || '').trim();
|
||||
const message = String((item as Record<string, unknown>).message || '').trim();
|
||||
const variantRaw = String((item as Record<string, unknown>).variant || '').trim();
|
||||
const variant: ShippingActionVariant | undefined = (variantRaw === 'primary' || variantRaw === 'secondary' || variantRaw === 'danger')
|
||||
? (variantRaw as ShippingActionVariant)
|
||||
: undefined;
|
||||
if (!id || !label || !message) continue;
|
||||
if (!SHIPPING_KNOWN_ACTION_ID_SET.has(id)) {
|
||||
console.warn(`[shipping] unknown action id in HXOPS_SHIPPING_ACTIONS: ${id}`);
|
||||
}
|
||||
buttons.push({ id, label, message, variant });
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// ignore malformed directive
|
||||
}
|
||||
}
|
||||
const cleaned = text.replace(re, '').trim();
|
||||
return { cleanedText: cleaned, buttons };
|
||||
}
|
||||
|
||||
export function normalizeShippingHeaderForDisplay(raw: unknown): string {
|
||||
const text = String(raw ?? '').replace(/\s+/g, ' ').trim();
|
||||
return text.replace(/ /g, '\u00A0');
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
/**
|
||||
* 出货聊天:库存上传后发给 Dify 的提示语、附件类型分类(纯函数)。
|
||||
*/
|
||||
export function buildShippingInventoryUploadPrompt(
|
||||
result: Record<string, unknown> | null | undefined,
|
||||
fileName?: string,
|
||||
): string {
|
||||
const checkpoint = String(result?.checkpoint || '').trim();
|
||||
const hasAlignment = Boolean(result?.data && typeof result.data === 'object'
|
||||
&& (result.data as { field_alignment?: unknown }).field_alignment
|
||||
&& typeof (result.data as { field_alignment?: unknown }).field_alignment === 'object');
|
||||
const suggestOk = Boolean((result?.data as { suggest_ok?: boolean } | undefined)?.suggest_ok);
|
||||
const prefix = fileName ? `我已上传库存文件《${fileName}》` : '我已上传库存文件';
|
||||
if (checkpoint === 'map_infer') {
|
||||
if (suggestOk) {
|
||||
return `${prefix}。请继续处理库存列映射;如果系统已识别出完整映射,请直接应用映射,并展示字段对齐结果给我确认。`;
|
||||
}
|
||||
return `${prefix}。请继续解析库存列映射,并在拿到可用映射后展示字段对齐结果给我确认。`;
|
||||
}
|
||||
if (checkpoint === 'align_review' || hasAlignment) {
|
||||
return `${prefix}。请展示库存字段对齐结果,并引导我确认或更正映射。`;
|
||||
}
|
||||
return `${prefix}。请继续处理库存导入,并告诉我下一步。`;
|
||||
}
|
||||
|
||||
export function classifyShippingUploadFile(
|
||||
file: File,
|
||||
extractExt: (name: string) => string,
|
||||
): 'inventory' | 'notice' {
|
||||
const ext = extractExt(file.name || '').toLowerCase();
|
||||
if (['xlsx', 'xls', 'csv'].includes(ext)) return 'inventory';
|
||||
return 'notice';
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
/**
|
||||
* 出货聊天:人工决策提交(confirm/reject/reparse 等)与手工上传标记。
|
||||
*/
|
||||
import {
|
||||
autoProgressWorkspaceShippingTask,
|
||||
markWorkspaceShippingManualUploaded,
|
||||
submitWorkspaceShippingDecision,
|
||||
} from '@/features/chat/api/shipping.api';
|
||||
import { formatShippingDecisionAssistantMessage } from './shippingDecisionFormat';
|
||||
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 function createShippingDecisionHandlers(ctx: ShippingDecisionContext) {
|
||||
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();
|
||||
}
|
||||
};
|
||||
|
||||
const executeShippingDecision = async (decision: string, displayText?: string) => {
|
||||
const taskId = ctx.getActiveShippingTaskId();
|
||||
if (!taskId) {
|
||||
ctx.msg.warning(ctx.t('chat.shippingNoticeMissingTaskId'));
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
const result =
|
||||
decision === 'confirm_inventory_mapping'
|
||||
? await autoProgressWorkspaceShippingTask(taskId)
|
||||
: await submitWorkspaceShippingDecision(taskId, decision);
|
||||
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'),
|
||||
);
|
||||
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);
|
||||
await ctx.saveLocalMessageToBackend(userMsg, userText);
|
||||
await ctx.saveLocalMessageToBackend(assistantMsg, userText);
|
||||
if (result.message && !ctx.isShippingNoticeAgent.value) {
|
||||
ctx.msg.success(result.message);
|
||||
}
|
||||
await syncHistoryIfNeeded();
|
||||
void ctx.refreshShippingActions();
|
||||
if (decision === 'correct_inventory_mapping') {
|
||||
await ctx.openShippingInventoryMappingFormForTask(taskId);
|
||||
}
|
||||
return true;
|
||||
} catch (e: unknown) {
|
||||
const errorMessage = e instanceof Error ? e.message : ctx.t('chat.shippingNoticeUploadFailed');
|
||||
ctx.msg.warning(errorMessage);
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
const executeShippingManualUpload = async (taskId: string, displayText?: string) => {
|
||||
try {
|
||||
const result = await markWorkspaceShippingManualUploaded(taskId);
|
||||
const userText = (displayText || '已在货代系统手工上传完成').trim();
|
||||
const assistantContent = [
|
||||
String(result.message || '已标记为手工上传货代系统完成。').trim(),
|
||||
`任务编号:${taskId}`,
|
||||
].join('\n');
|
||||
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,
|
||||
shipping_actions_used: true,
|
||||
};
|
||||
ctx.messages.value.push(userMsg, 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);
|
||||
await ctx.saveLocalMessageToBackend(assistantMsg, userText);
|
||||
void ctx.refreshShippingActions();
|
||||
return true;
|
||||
} catch (e: unknown) {
|
||||
const errorMessage = e instanceof Error ? e.message : '标记手工上传失败';
|
||||
ctx.msg.warning(errorMessage);
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
return { executeShippingDecision, executeShippingManualUpload };
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
/**
|
||||
* 出货聊天:库存列映射表单(打开、应用、重传)。
|
||||
*/
|
||||
import { nextTick } from 'vue';
|
||||
import {
|
||||
applyWorkspaceShippingInventoryMapping,
|
||||
getWorkspaceShippingTask,
|
||||
} from '@/features/chat/api/shipping.api';
|
||||
import { buildShippingFieldAlignmentText, getShippingInventoryMappingPayload } from './shippingMapping';
|
||||
import type { ChatMessage } from '../types/chat.types';
|
||||
import type { ShippingInventoryMappingFormPayload } from '../types/shipping.types';
|
||||
import type { Ref } from 'vue';
|
||||
|
||||
export interface ShippingMappingFormContext {
|
||||
messages: Ref<ChatMessage[]>;
|
||||
chatScrollContainer: Ref<HTMLElement | null>;
|
||||
shippingInventorySchemaPreviewCache: Ref<Record<string, unknown>>;
|
||||
shippingInventoryPickerRef: Ref<HTMLInputElement | null>;
|
||||
pendingShippingUploadTaskId: Ref<string>;
|
||||
resolvedShippingTaskId: Ref<string>;
|
||||
newLocalMessageId: (prefix: string) => string;
|
||||
saveLocalMessageToBackend: (msg: ChatMessage, userQuery?: string) => Promise<void>;
|
||||
pushShippingLocalAssistantMessage: (text: string) => Promise<void>;
|
||||
refreshShippingActions: () => Promise<void>;
|
||||
msg: { warning: (text: string) => void };
|
||||
}
|
||||
|
||||
export function createShippingMappingFormHandlers(ctx: ShippingMappingFormContext) {
|
||||
const scrollToLastShippingInventoryMapping = async (): Promise<boolean> => {
|
||||
const container = ctx.chatScrollContainer.value;
|
||||
if (!container) return false;
|
||||
let idx = -1;
|
||||
for (let i = ctx.messages.value.length - 1; i >= 0; i -= 1) {
|
||||
if ((ctx.messages.value[i] as ChatMessage)?.type === 'shipping-inventory-mapping') {
|
||||
idx = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (idx < 0) return false;
|
||||
await nextTick();
|
||||
await nextTick();
|
||||
const el = container.querySelector(`[data-msg-index="${idx}"]`) as HTMLElement | null;
|
||||
if (!el) return false;
|
||||
el.scrollIntoView({ behavior: 'smooth', block: 'start' });
|
||||
return true;
|
||||
};
|
||||
|
||||
const openShippingInventoryMappingFormForTask = async (taskId: string): Promise<boolean> => {
|
||||
const id = String(taskId || '').trim().toUpperCase();
|
||||
if (!id) return false;
|
||||
const existingIdx = (() => {
|
||||
for (let i = ctx.messages.value.length - 1; i >= 0; i -= 1) {
|
||||
const chatMsg = ctx.messages.value[i] as ChatMessage;
|
||||
if (chatMsg?.type !== 'shipping-inventory-mapping') continue;
|
||||
const payload = getShippingInventoryMappingPayload(chatMsg);
|
||||
if (payload?.taskId?.trim().toUpperCase() === id) return i;
|
||||
}
|
||||
return -1;
|
||||
})();
|
||||
if (existingIdx >= 0) {
|
||||
return scrollToLastShippingInventoryMapping();
|
||||
}
|
||||
const schemaPreview = ctx.shippingInventorySchemaPreviewCache.value[id];
|
||||
if (!schemaPreview || typeof schemaPreview !== 'object') {
|
||||
ctx.msg.warning('未找到表头预览,请重新上传库存文件后再点击“修改映射”');
|
||||
return false;
|
||||
}
|
||||
const detail = await getWorkspaceShippingTask(id).catch(() => null);
|
||||
const rawLines = Array.isArray((detail as { lines?: unknown[] } | null)?.lines)
|
||||
? (detail as { lines: unknown[] }).lines
|
||||
: [];
|
||||
const pickSku = (line: Record<string, unknown>) =>
|
||||
String(line?.sku || line?.SKU || line?.['AWS Sku'] || line?.['AWS SKU'] || '').trim();
|
||||
const skus = [...new Set(rawLines.map((line) => pickSku(line as Record<string, unknown>)).filter(Boolean))].slice(0, 40);
|
||||
const suggested = (schemaPreview as { suggested_mapping?: Record<string, string> }).suggested_mapping || {};
|
||||
const mappingMsg: ChatMessage = {
|
||||
role: 'assistant',
|
||||
type: 'shipping-inventory-mapping',
|
||||
content: [
|
||||
'请用下拉框选择库存列映射(必须从表头中选择)。',
|
||||
`任务编号:${id}`,
|
||||
].filter(Boolean).join('\n'),
|
||||
payload: {
|
||||
taskId: id,
|
||||
schema_preview: schemaPreview,
|
||||
order: { line_count: rawLines.length, skus },
|
||||
form: {
|
||||
sku: String(suggested?.sku || '').trim(),
|
||||
available_qty: String(suggested?.available_qty || '').trim(),
|
||||
reservation_id: String(suggested?.reservation_id || '').trim(),
|
||||
},
|
||||
applying: false,
|
||||
} as ShippingInventoryMappingFormPayload,
|
||||
local_id: ctx.newLocalMessageId('shipping-assistant'),
|
||||
local_only: true,
|
||||
};
|
||||
ctx.messages.value.push(mappingMsg);
|
||||
await ctx.saveLocalMessageToBackend(mappingMsg);
|
||||
await scrollToLastShippingInventoryMapping();
|
||||
return true;
|
||||
};
|
||||
|
||||
const applyShippingInventoryMappingForm = async (msgObj: ChatMessage) => {
|
||||
const payload = getShippingInventoryMappingPayload(msgObj);
|
||||
if (!payload) return;
|
||||
if (payload.applying) return;
|
||||
const taskId = String(payload.taskId || '').trim();
|
||||
if (!taskId) {
|
||||
ctx.msg.warning('未找到任务编号');
|
||||
return;
|
||||
}
|
||||
const mapping: Record<string, string> = {
|
||||
sku: String(payload.form?.sku || '').trim(),
|
||||
available_qty: String(payload.form?.available_qty || '').trim(),
|
||||
reservation_id: String(payload.form?.reservation_id || '').trim(),
|
||||
};
|
||||
if (!mapping.sku || !mapping.available_qty) {
|
||||
ctx.msg.warning('请先选择 SKU 列 与 可用数量列');
|
||||
return;
|
||||
}
|
||||
if (!mapping.reservation_id) {
|
||||
delete mapping.reservation_id;
|
||||
}
|
||||
payload.applying = true;
|
||||
try {
|
||||
const result = await applyWorkspaceShippingInventoryMapping(taskId, mapping);
|
||||
const alignmentText = buildShippingFieldAlignmentText(result);
|
||||
const hint = alignmentText || String(result.message || '').trim();
|
||||
await ctx.pushShippingLocalAssistantMessage(
|
||||
[
|
||||
'映射已应用并解析库存。',
|
||||
`任务编号:${taskId}`,
|
||||
hint,
|
||||
].filter(Boolean).join('\n'),
|
||||
);
|
||||
ctx.resolvedShippingTaskId.value = taskId;
|
||||
void ctx.refreshShippingActions();
|
||||
} catch (e: unknown) {
|
||||
const errorMessage = e instanceof Error ? e.message : '应用映射失败';
|
||||
ctx.msg.warning(errorMessage);
|
||||
} finally {
|
||||
payload.applying = false;
|
||||
await ctx.saveLocalMessageToBackend(msgObj);
|
||||
}
|
||||
};
|
||||
|
||||
const reuploadShippingInventoryFromMappingForm = (msgObj: ChatMessage) => {
|
||||
const payload = getShippingInventoryMappingPayload(msgObj);
|
||||
if (!payload) return;
|
||||
const taskId = String(payload.taskId || '').trim();
|
||||
if (!taskId) return;
|
||||
ctx.pendingShippingUploadTaskId.value = taskId;
|
||||
ctx.shippingInventoryPickerRef.value?.click();
|
||||
};
|
||||
|
||||
return {
|
||||
openShippingInventoryMappingFormForTask,
|
||||
applyShippingInventoryMappingForm,
|
||||
reuploadShippingInventoryFromMappingForm,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
/**
|
||||
* 出货聊天:消息气泡动作按钮与菜单项点击分发。
|
||||
*
|
||||
* 按 action.id 路由到 API 调用、决策提交、文件选择器或 Dify 菜单消息。
|
||||
*/
|
||||
import {
|
||||
generateWorkspaceShippingExcel,
|
||||
matchWorkspaceShippingInventory,
|
||||
} from '@/features/chat/api/shipping.api';
|
||||
import { SHIPPING_DECISION_ACTIONS } from '../constants/shipping';
|
||||
import { downloadWorkspaceShippingExcelFile } from './shippingDownload';
|
||||
import type { ChatMessage } from '../types/chat.types';
|
||||
import type { Ref } from 'vue';
|
||||
|
||||
export interface ShippingMenuHandlerContext {
|
||||
isThinking: Ref<boolean>;
|
||||
getActiveShippingTaskId: () => string;
|
||||
messages: Ref<ChatMessage[]>;
|
||||
newLocalMessageId: (prefix: string) => string;
|
||||
saveLocalMessageToBackend: (msg: ChatMessage, userQuery?: string) => Promise<void>;
|
||||
sendShippingMenuMessage: (message: string) => Promise<void>;
|
||||
openShippingInventoryMappingFormForTask: (taskId: string) => Promise<boolean>;
|
||||
openShippingInventoryPicker: () => boolean;
|
||||
executeShippingDecision: (decision: string, displayText?: string) => Promise<boolean>;
|
||||
executeShippingManualUpload: (taskId: string, displayText?: string) => Promise<boolean>;
|
||||
refreshShippingActions: () => Promise<void>;
|
||||
msg: { warning: (text: string) => void; info: (text: string) => void };
|
||||
t: (key: string) => string;
|
||||
}
|
||||
|
||||
export function createShippingMenuHandlers(ctx: ShippingMenuHandlerContext) {
|
||||
const handleShippingMenuAction = async (
|
||||
action: { id?: string; message: string },
|
||||
chatMsg?: ChatMessage & { shipping_actions_used?: boolean },
|
||||
) => {
|
||||
if (ctx.isThinking.value) return;
|
||||
if (action.id === 'refresh') {
|
||||
await ctx.sendShippingMenuMessage(action.message || '刷新');
|
||||
return;
|
||||
}
|
||||
if (action.id === 'download_excel') {
|
||||
const taskId = ctx.getActiveShippingTaskId();
|
||||
if (!taskId) {
|
||||
ctx.msg.warning(ctx.t('chat.shippingNoticeMissingTaskId'));
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await downloadWorkspaceShippingExcelFile(taskId);
|
||||
} catch (e: unknown) {
|
||||
const errorMessage = e instanceof Error ? e.message : '下载 Excel 失败';
|
||||
ctx.msg.warning(errorMessage);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (action.id === 'generate_excel') {
|
||||
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 generateWorkspaceShippingExcel(taskId);
|
||||
const userMsg: ChatMessage = {
|
||||
role: 'user',
|
||||
type: 'text',
|
||||
content: `${action.message || '生成发货 Excel'}(任务编号:${taskId})`,
|
||||
local_id: ctx.newLocalMessageId('shipping-user'),
|
||||
local_only: true,
|
||||
};
|
||||
const assistantMsg: ChatMessage = {
|
||||
role: 'assistant',
|
||||
type: 'text',
|
||||
content: [
|
||||
String(result.message || '').trim(),
|
||||
`任务编号:${taskId}`,
|
||||
].filter(Boolean).join('\n'),
|
||||
local_id: ctx.newLocalMessageId('shipping-assistant'),
|
||||
local_only: true,
|
||||
};
|
||||
ctx.messages.value.push(userMsg, assistantMsg);
|
||||
await ctx.saveLocalMessageToBackend(userMsg, action.message || '生成发货 Excel');
|
||||
await ctx.saveLocalMessageToBackend(assistantMsg, action.message || '生成发货 Excel');
|
||||
void ctx.refreshShippingActions();
|
||||
} catch (e: unknown) {
|
||||
const errorMessage = e instanceof Error ? e.message : '生成发货 Excel 失败';
|
||||
ctx.msg.warning(errorMessage);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (action.id === 'edit_inventory_mapping') {
|
||||
const taskId = ctx.getActiveShippingTaskId();
|
||||
if (!taskId) {
|
||||
ctx.msg.warning(ctx.t('chat.shippingNoticeMissingTaskId'));
|
||||
return;
|
||||
}
|
||||
await ctx.openShippingInventoryMappingFormForTask(taskId);
|
||||
return;
|
||||
}
|
||||
if (action.id === 'upload_inventory_file') {
|
||||
ctx.openShippingInventoryPicker();
|
||||
return;
|
||||
}
|
||||
if (action.id === 'match_inventory') {
|
||||
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 matchWorkspaceShippingInventory(taskId);
|
||||
const userMsg: ChatMessage = {
|
||||
role: 'user',
|
||||
type: 'text',
|
||||
content: `${action.message || '匹配库存'}(任务编号:${taskId})`,
|
||||
local_id: ctx.newLocalMessageId('shipping-user'),
|
||||
local_only: true,
|
||||
};
|
||||
const assistantMsg: ChatMessage = {
|
||||
role: 'assistant',
|
||||
type: 'text',
|
||||
content: [
|
||||
String(result.message || '').trim(),
|
||||
`任务编号:${taskId}`,
|
||||
].filter(Boolean).join('\n'),
|
||||
local_id: ctx.newLocalMessageId('shipping-assistant'),
|
||||
local_only: true,
|
||||
};
|
||||
ctx.messages.value.push(userMsg, assistantMsg);
|
||||
await ctx.saveLocalMessageToBackend(userMsg, action.message || '匹配库存');
|
||||
await ctx.saveLocalMessageToBackend(assistantMsg, action.message || '匹配库存');
|
||||
void ctx.refreshShippingActions();
|
||||
} catch (e: unknown) {
|
||||
const errorMessage = e instanceof Error ? e.message : '匹配库存失败';
|
||||
ctx.msg.warning(errorMessage);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (action.id === 'mark_manual_uploaded') {
|
||||
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;
|
||||
}
|
||||
await ctx.executeShippingManualUpload(taskId, action.message || '已在货代系统手工上传完成');
|
||||
return;
|
||||
}
|
||||
if (action.id === 'paste_inventory_json') {
|
||||
ctx.msg.info(ctx.t('chat.shippingNoticePasteHint'));
|
||||
return;
|
||||
}
|
||||
if (action.id && SHIPPING_DECISION_ACTIONS.has(action.id)) {
|
||||
if (chatMsg?.shipping_actions_used) return;
|
||||
if (chatMsg) chatMsg.shipping_actions_used = true;
|
||||
await ctx.executeShippingDecision(action.id, action.message);
|
||||
return;
|
||||
}
|
||||
if (chatMsg?.shipping_actions_used) return;
|
||||
if (chatMsg) chatMsg.shipping_actions_used = true;
|
||||
await ctx.sendShippingMenuMessage(action.message);
|
||||
};
|
||||
|
||||
const handleShippingActionClick = async (
|
||||
chatMsg: ChatMessage & { shipping_actions_used?: boolean },
|
||||
action: { id?: string; message: string },
|
||||
) => {
|
||||
await handleShippingMenuAction(action, chatMsg);
|
||||
};
|
||||
|
||||
return { handleShippingMenuAction, handleShippingActionClick };
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
/**
|
||||
* 出货聊天:助手消息动作按钮刷新(有状态 composable 工厂)。
|
||||
*
|
||||
* 按 taskId 拉取 getShippingChatActions,写入 messages[].shipping_actions;
|
||||
* 终态 checkpoint 时清除所有按钮。
|
||||
*/
|
||||
import {
|
||||
getShippingChatActions,
|
||||
listWorkspaceShippingTasks,
|
||||
} from '@/features/chat/api/shipping.api';
|
||||
import { SHIPPING_TERMINAL_CHECKPOINTS } from '@/constants/shippingNoticeActions';
|
||||
import { SHIPPING_TASK_ID_RE } from '../constants/shipping';
|
||||
import { findLatestShippingTaskId } from './shippingTaskId';
|
||||
import { resolveShippingActionButtons } from './shippingMenu';
|
||||
import type { ChatMessage, ChatSessionItem } from '../types/chat.types';
|
||||
import type { ShippingActionButton } from '../types/shipping.types';
|
||||
import type { ComputedRef, Ref } from 'vue';
|
||||
|
||||
export interface ShippingRefreshContext {
|
||||
isShippingNoticeAgent: ComputedRef<boolean>;
|
||||
messages: Ref<ChatMessage[]>;
|
||||
conversationId: Ref<string | null>;
|
||||
isThinking: Ref<boolean>;
|
||||
history: Ref<ChatSessionItem[]>;
|
||||
resolvedShippingTaskId: Ref<string>;
|
||||
shippingTaskIdFromQuery: ComputedRef<string>;
|
||||
shippingConversationTaskIdCache: Ref<Record<string, string>>;
|
||||
}
|
||||
|
||||
export function assistantMessageHasLaterUserReply(msgs: Array<{ role?: string }>, index: number): boolean {
|
||||
return msgs.slice(index + 1).some((item) => item.role === 'user');
|
||||
}
|
||||
|
||||
export function createShippingActionsRefresher(ctx: ShippingRefreshContext) {
|
||||
let shippingActionsRequestSeq = 0;
|
||||
|
||||
const refreshShippingActions = async () => {
|
||||
if (!ctx.isShippingNoticeAgent.value) return;
|
||||
const msgs = ctx.messages.value;
|
||||
if (!msgs.length) return;
|
||||
const cid = String(ctx.conversationId.value || '').trim();
|
||||
const historyTaskId = (() => {
|
||||
if (!cid) return '';
|
||||
const session = ctx.history.value.find((item) => String(item.conversation_id || '') === cid);
|
||||
const title = String(session?.title || '');
|
||||
const match = title.match(SHIPPING_TASK_ID_RE);
|
||||
return match?.[0] ? match[0].toUpperCase() : '';
|
||||
})();
|
||||
let taskId = findLatestShippingTaskId(msgs)
|
||||
|| ctx.resolvedShippingTaskId.value
|
||||
|| ctx.shippingTaskIdFromQuery.value
|
||||
|| historyTaskId;
|
||||
if (!taskId && cid && !ctx.isThinking.value) {
|
||||
const cached = ctx.shippingConversationTaskIdCache.value[cid];
|
||||
if (cached) {
|
||||
taskId = cached;
|
||||
} else {
|
||||
try {
|
||||
const rows = await listWorkspaceShippingTasks({ limit: 500 });
|
||||
const hit = rows.find((row) => String(row.conversation_id || '') === cid);
|
||||
const taskNo = hit?.task_no ? String(hit.task_no).trim().toUpperCase() : '';
|
||||
if (taskNo) {
|
||||
ctx.shippingConversationTaskIdCache.value = { ...ctx.shippingConversationTaskIdCache.value, [cid]: taskNo };
|
||||
taskId = taskNo;
|
||||
}
|
||||
} catch {
|
||||
// fall back to content-based buttons
|
||||
}
|
||||
}
|
||||
}
|
||||
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];
|
||||
if (item?.role !== 'assistant') continue;
|
||||
if (assistantMessageHasLaterUserReply(msgs, i)) continue;
|
||||
lastOpenAssistantIndex = i;
|
||||
break;
|
||||
}
|
||||
let lastAssistantIndex = -1;
|
||||
for (let i = msgs.length - 1; i >= 0; i -= 1) {
|
||||
const item = msgs[i];
|
||||
if (item?.role === 'assistant') {
|
||||
lastAssistantIndex = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
const targetAssistantIndex = lastOpenAssistantIndex >= 0 ? lastOpenAssistantIndex : lastAssistantIndex;
|
||||
msgs.forEach((rawMsg, index) => {
|
||||
const chatMsg = rawMsg as ChatMessage & {
|
||||
shipping_actions_used?: boolean;
|
||||
shipping_actions?: ShippingActionButton[];
|
||||
};
|
||||
if (chatMsg.role !== 'assistant' || chatMsg.shipping_actions_used) {
|
||||
return;
|
||||
}
|
||||
if (chatMsg.type && !['text', undefined].includes(chatMsg.type)) {
|
||||
chatMsg.shipping_actions = undefined;
|
||||
return;
|
||||
}
|
||||
if (assistantMessageHasLaterUserReply(msgs, index) && index !== targetAssistantIndex) {
|
||||
chatMsg.shipping_actions = undefined;
|
||||
return;
|
||||
}
|
||||
let buttons: ShippingActionButton[] = [];
|
||||
if (index === targetAssistantIndex) {
|
||||
const resolved = resolveShippingActionButtons(
|
||||
String(chatMsg.content || ''),
|
||||
apiResolved ? (apiButtons ?? []) : null,
|
||||
{ apiResolved },
|
||||
);
|
||||
if (resolved.fromDirective) {
|
||||
chatMsg.content = resolved.cleanedText;
|
||||
}
|
||||
buttons = resolved.buttons;
|
||||
} else if (!apiResolved) {
|
||||
const resolved = resolveShippingActionButtons(String(chatMsg.content || ''), null);
|
||||
if (resolved.fromDirective) {
|
||||
chatMsg.content = resolved.cleanedText;
|
||||
}
|
||||
buttons = resolved.buttons;
|
||||
}
|
||||
chatMsg.shipping_actions = buttons.length ? buttons : undefined;
|
||||
});
|
||||
};
|
||||
|
||||
return { refreshShippingActions };
|
||||
}
|
||||
@@ -0,0 +1,243 @@
|
||||
/**
|
||||
* 出货聊天:handleSend 前置拦截(菜单数字、决策文本、列映射、附件自动流程)。
|
||||
*
|
||||
* 返回 true 表示已消费本次发送,ChatView 不再走默认 Dify 流程。
|
||||
*/
|
||||
import { applyWorkspaceShippingInventoryMapping, generateWorkspaceShippingExcel } from '@/features/chat/api/shipping.api';
|
||||
import { SHIPPING_MENU_ACTION_SPECS } from '../constants/shipping';
|
||||
import { buildShippingFieldAlignmentText } from './shippingMapping';
|
||||
import { downloadWorkspaceShippingExcelFile } from './shippingDownload';
|
||||
import {
|
||||
isShippingDownloadExcelIntent,
|
||||
isShippingGenerateExcelIntent,
|
||||
isShippingInventoryUploadIntent,
|
||||
isShippingManualUploadIntent,
|
||||
parseShippingColumnMappingFromText,
|
||||
} from './shippingIntents';
|
||||
import { resolveShippingDecisionFromText, resolveShippingNumericChoice } from './shippingMenu';
|
||||
import { classifyShippingUploadFile } from './shippingUploadPrompt';
|
||||
import { extractExt } from '../constants/shipping';
|
||||
import { ensureShippingHistorySynced } from './shippingConversation';
|
||||
import type { ChatMessage, ChatSessionItem } from '../types/chat.types';
|
||||
import type { ChatUploadFileSpec, PendingAttachment } from '../types/shipping.types';
|
||||
import type { ComputedRef, Ref } from 'vue';
|
||||
|
||||
export interface ShippingSendHandlerContext {
|
||||
isShippingNoticeAgent: ComputedRef<boolean>;
|
||||
isThinking: Ref<boolean>;
|
||||
isUploadingAttachments: Ref<boolean>;
|
||||
messages: Ref<ChatMessage[]>;
|
||||
conversationId: Ref<string | null>;
|
||||
history: Ref<ChatSessionItem[]>;
|
||||
input: Ref<string>;
|
||||
attachments: Ref<PendingAttachment[]>;
|
||||
shippingAutoFlowRequested: Ref<boolean>;
|
||||
resolvedShippingTaskId: Ref<string>;
|
||||
currentAgentId: ComputedRef<number>;
|
||||
selectedKb: Ref<string>;
|
||||
attachmentPolicy: ComputedRef<{ anyEnabled: boolean }>;
|
||||
getActiveShippingTaskId: () => string;
|
||||
lastAssistantMessageContent: () => string;
|
||||
sendMessage: (
|
||||
content: string,
|
||||
agentId: number,
|
||||
kb: string,
|
||||
files: ChatUploadFileSpec[],
|
||||
) => Promise<void>;
|
||||
buildFileSpecsForSend: () => Promise<ChatUploadFileSpec[]>;
|
||||
loadHistory: () => Promise<void>;
|
||||
sendShippingMenuMessage: (message: string) => Promise<void>;
|
||||
pushShippingLocalUserMessage: (text: string) => Promise<void>;
|
||||
pushShippingLocalAssistantMessage: (text: string) => Promise<void>;
|
||||
openShippingInventoryPicker: () => boolean;
|
||||
executeShippingDecision: (decision: string, displayText?: string) => Promise<boolean>;
|
||||
executeShippingManualUpload: (taskId: string, displayText?: string) => Promise<boolean>;
|
||||
handleShippingAutoUploadFile: (file: File) => Promise<void>;
|
||||
refreshShippingActions: () => Promise<void>;
|
||||
shippingSuggestedPrompt: ComputedRef<string>;
|
||||
msg: { warning: (text: string) => void; info: (text: string) => void };
|
||||
t: (key: string) => string;
|
||||
}
|
||||
|
||||
export function createShippingSendHandlers(ctx: ShippingSendHandlerContext) {
|
||||
const tryHandleShippingAttachmentAutoFlow = async (
|
||||
textOrEvent: string | Event | undefined,
|
||||
_content: string,
|
||||
trimmed: string,
|
||||
): Promise<boolean> => {
|
||||
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;
|
||||
ctx.shippingAutoFlowRequested.value = false;
|
||||
const localFiles = ctx.attachments.value.filter((a) => a.kind === 'local') as Array<Extract<PendingAttachment, { kind: 'local' }>>;
|
||||
const first = localFiles[0];
|
||||
if (!first) {
|
||||
ctx.msg.warning('当前仅支持本地附件触发自动流程');
|
||||
return true;
|
||||
}
|
||||
const kind = classifyShippingUploadFile(first.file, extractExt);
|
||||
if (kind === 'inventory') {
|
||||
ctx.attachments.value = [];
|
||||
if (typeof textOrEvent !== 'string') ctx.input.value = '';
|
||||
if (localFiles.length > 1) {
|
||||
ctx.msg.warning('一次仅支持处理一个文件,将自动处理第一个');
|
||||
}
|
||||
try {
|
||||
const prompt = trimmed || ctx.shippingSuggestedPrompt.value || '上传库存并进入字段对齐';
|
||||
await ctx.pushShippingLocalUserMessage(prompt);
|
||||
await ctx.handleShippingAutoUploadFile(first.file);
|
||||
} catch (e: unknown) {
|
||||
const errorMessage = e instanceof Error ? e.message : '文件处理失败';
|
||||
ctx.msg.warning(errorMessage);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
if (!trimmed) {
|
||||
const prompt = ctx.shippingSuggestedPrompt.value || '解析发货通知并创建任务';
|
||||
let files: ChatUploadFileSpec[] = [];
|
||||
if (ctx.attachmentPolicy.value.anyEnabled && ctx.attachments.value.length > 0) {
|
||||
try {
|
||||
files = await ctx.buildFileSpecsForSend();
|
||||
} catch (e: unknown) {
|
||||
const errorMessage = e instanceof Error ? e.message : 'unknown error';
|
||||
ctx.msg.warning(`附件处理失败:${errorMessage}`);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
if (typeof textOrEvent !== 'string') ctx.input.value = '';
|
||||
ctx.attachments.value = [];
|
||||
await ctx.sendMessage(prompt, ctx.currentAgentId.value, ctx.selectedKb.value, files);
|
||||
await ensureShippingHistorySynced({
|
||||
conversationId: ctx.conversationId,
|
||||
history: ctx.history,
|
||||
loadHistory: ctx.loadHistory,
|
||||
getActiveShippingTaskId: ctx.getActiveShippingTaskId,
|
||||
currentAgentId: ctx.currentAgentId,
|
||||
selectedKb: ctx.selectedKb,
|
||||
sendMessage: ctx.sendMessage,
|
||||
});
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
const tryHandleShippingSend = async (
|
||||
textOrEvent: string | Event | undefined,
|
||||
content: string,
|
||||
_trimmed: string,
|
||||
): Promise<boolean> => {
|
||||
if (!ctx.isShippingNoticeAgent.value) return false;
|
||||
const assistantCtx = ctx.lastAssistantMessageContent();
|
||||
const menuChoice = resolveShippingNumericChoice(content, assistantCtx);
|
||||
if (menuChoice) {
|
||||
if (typeof textOrEvent !== 'string') ctx.input.value = '';
|
||||
if (menuChoice === 'upload') {
|
||||
if (ctx.openShippingInventoryPicker()) return true;
|
||||
} else if (menuChoice === 'paste') {
|
||||
ctx.msg.info(ctx.t('chat.shippingNoticePasteHint'));
|
||||
return true;
|
||||
} else {
|
||||
await ctx.sendShippingMenuMessage(SHIPPING_MENU_ACTION_SPECS[menuChoice].message);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
const shippingDecision = resolveShippingDecisionFromText(content, assistantCtx);
|
||||
if (shippingDecision) {
|
||||
if (typeof textOrEvent !== 'string') ctx.input.value = '';
|
||||
if (await ctx.executeShippingDecision(shippingDecision, content.trim())) return true;
|
||||
}
|
||||
if (assistantCtx.includes('schema_preview') || assistantCtx.includes('列映射') || assistantCtx.includes('字段对齐')) {
|
||||
const mapping = parseShippingColumnMappingFromText(content);
|
||||
if (mapping) {
|
||||
const taskId = ctx.getActiveShippingTaskId();
|
||||
if (!taskId) {
|
||||
ctx.msg.warning('未找到任务编号,请先上传库存文件');
|
||||
return true;
|
||||
}
|
||||
ctx.resolvedShippingTaskId.value = taskId;
|
||||
if (typeof textOrEvent !== 'string') ctx.input.value = '';
|
||||
ctx.attachments.value = [];
|
||||
await ctx.pushShippingLocalUserMessage(content.trim());
|
||||
try {
|
||||
const result = await applyWorkspaceShippingInventoryMapping(taskId, mapping);
|
||||
const alignmentText = buildShippingFieldAlignmentText(result);
|
||||
const hint = alignmentText || String(result.message || '').trim();
|
||||
await ctx.pushShippingLocalAssistantMessage(
|
||||
[
|
||||
`映射已应用:${Object.entries(mapping).map(([k, v]) => `${k}=${v}`).join(',')}`,
|
||||
`任务编号:${taskId}`,
|
||||
hint,
|
||||
].filter(Boolean).join('\n'),
|
||||
);
|
||||
void ctx.refreshShippingActions();
|
||||
} catch (e: unknown) {
|
||||
const errorMessage = e instanceof Error ? e.message : '应用映射失败';
|
||||
ctx.msg.warning(errorMessage);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
if (isShippingManualUploadIntent(content)) {
|
||||
const taskId = ctx.getActiveShippingTaskId();
|
||||
if (!taskId) {
|
||||
ctx.msg.warning('未找到任务编号,请先完成前面的步骤');
|
||||
return true;
|
||||
}
|
||||
ctx.resolvedShippingTaskId.value = taskId;
|
||||
if (typeof textOrEvent !== 'string') ctx.input.value = '';
|
||||
ctx.attachments.value = [];
|
||||
await ctx.executeShippingManualUpload(taskId, content.trim());
|
||||
return true;
|
||||
}
|
||||
if (isShippingInventoryUploadIntent(content, assistantCtx)) {
|
||||
if (typeof textOrEvent !== 'string') ctx.input.value = '';
|
||||
if (ctx.openShippingInventoryPicker()) return true;
|
||||
}
|
||||
if (isShippingGenerateExcelIntent(content)) {
|
||||
const taskId = ctx.getActiveShippingTaskId();
|
||||
if (!taskId) {
|
||||
ctx.msg.warning('未找到任务编号,请先完成解析与库存匹配');
|
||||
return true;
|
||||
}
|
||||
ctx.resolvedShippingTaskId.value = taskId;
|
||||
if (typeof textOrEvent !== 'string') ctx.input.value = '';
|
||||
ctx.attachments.value = [];
|
||||
await ctx.pushShippingLocalUserMessage(content.trim());
|
||||
try {
|
||||
const result = await generateWorkspaceShippingExcel(taskId);
|
||||
await ctx.pushShippingLocalAssistantMessage(
|
||||
[
|
||||
String(result.message || '').trim() || '已生成发货 Excel',
|
||||
`任务编号:${taskId}`,
|
||||
].filter(Boolean).join('\n'),
|
||||
);
|
||||
void ctx.refreshShippingActions();
|
||||
} catch (e: unknown) {
|
||||
const errorMessage = e instanceof Error ? e.message : '生成发货 Excel 失败';
|
||||
ctx.msg.warning(errorMessage);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
if (isShippingDownloadExcelIntent(content)) {
|
||||
const taskId = ctx.getActiveShippingTaskId();
|
||||
if (!taskId) {
|
||||
ctx.msg.warning('未找到任务编号,请先完成解析与库存匹配');
|
||||
return true;
|
||||
}
|
||||
ctx.resolvedShippingTaskId.value = taskId;
|
||||
if (typeof textOrEvent !== 'string') ctx.input.value = '';
|
||||
ctx.attachments.value = [];
|
||||
await ctx.pushShippingLocalUserMessage(content.trim());
|
||||
try {
|
||||
await downloadWorkspaceShippingExcelFile(taskId);
|
||||
} catch (e: unknown) {
|
||||
const errorMessage = e instanceof Error ? e.message : '下载 Excel 失败';
|
||||
ctx.msg.warning(errorMessage);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
return { tryHandleShippingSend, tryHandleShippingAttachmentAutoFlow };
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
/**
|
||||
* 出货聊天:库存/发货通知文件上传、隐藏 file input、附件建议提示。
|
||||
*/
|
||||
import { computed } from 'vue';
|
||||
import {
|
||||
createWorkspaceShippingTask,
|
||||
createWorkspaceShippingTaskFromNotice,
|
||||
uploadWorkspaceShippingInventory,
|
||||
} from '@/features/chat/api/shipping.api';
|
||||
import { extractExt } from '../constants/shipping';
|
||||
import { buildShippingInventoryUploadPrompt, classifyShippingUploadFile } from './shippingUploadPrompt';
|
||||
import type { PendingAttachment } from '../types/shipping.types';
|
||||
import type { Ref } from 'vue';
|
||||
|
||||
export interface ShippingUploadHandlerContext {
|
||||
conversationId: Ref<string | null>;
|
||||
attachments: Ref<PendingAttachment[]>;
|
||||
input: Ref<string>;
|
||||
shippingAutoFlowRequested: Ref<boolean>;
|
||||
shippingInventoryPickerRef: Ref<HTMLInputElement | null>;
|
||||
pendingShippingUploadTaskId: Ref<string>;
|
||||
resolvedShippingTaskId: Ref<string>;
|
||||
shippingInventorySchemaPreviewCache: Ref<Record<string, unknown>>;
|
||||
getActiveShippingTaskId: () => string;
|
||||
sendShippingMenuMessage: (message: string) => Promise<void>;
|
||||
pushShippingLocalAssistantMessage: (text: string) => Promise<void>;
|
||||
refreshShippingActions: () => Promise<void>;
|
||||
msg: { warning: (text: string) => void };
|
||||
t: (key: string) => string;
|
||||
}
|
||||
|
||||
export function createShippingUploadHandlers(ctx: ShippingUploadHandlerContext) {
|
||||
const continueShippingInventoryUploadWithDify = async (
|
||||
taskId: string,
|
||||
result: Record<string, unknown> | null | undefined,
|
||||
fileName?: string,
|
||||
) => {
|
||||
const key = String(taskId || '').trim().toUpperCase();
|
||||
const schemaPreview = (result?.data as { schema_preview?: unknown } | undefined)?.schema_preview;
|
||||
if (key && schemaPreview && typeof schemaPreview === 'object') {
|
||||
ctx.shippingInventorySchemaPreviewCache.value = {
|
||||
...ctx.shippingInventorySchemaPreviewCache.value,
|
||||
[key]: schemaPreview,
|
||||
};
|
||||
}
|
||||
ctx.resolvedShippingTaskId.value = taskId;
|
||||
await ctx.sendShippingMenuMessage(buildShippingInventoryUploadPrompt(result, fileName));
|
||||
};
|
||||
|
||||
const handleShippingAutoUploadFile = async (file: File) => {
|
||||
const kind = classifyShippingUploadFile(file, extractExt);
|
||||
if (kind === 'inventory') {
|
||||
let taskId = ctx.getActiveShippingTaskId();
|
||||
if (!taskId) {
|
||||
const created = await createWorkspaceShippingTask({
|
||||
source_type: 'manual',
|
||||
conversation_id: String(ctx.conversationId.value || '').trim() || undefined,
|
||||
});
|
||||
taskId = String(created.task_id || '').trim();
|
||||
if (!taskId) {
|
||||
ctx.msg.warning('自动创建发货任务失败');
|
||||
return;
|
||||
}
|
||||
}
|
||||
ctx.resolvedShippingTaskId.value = taskId;
|
||||
const result = await uploadWorkspaceShippingInventory(taskId, file);
|
||||
await continueShippingInventoryUploadWithDify(taskId, result as unknown as Record<string, unknown>, file.name);
|
||||
return;
|
||||
}
|
||||
const result = await createWorkspaceShippingTaskFromNotice(
|
||||
file,
|
||||
String(ctx.conversationId.value || '').trim() || undefined,
|
||||
);
|
||||
const taskId = String(result.task_id || '').trim();
|
||||
if (taskId) ctx.resolvedShippingTaskId.value = taskId;
|
||||
const hint = String(result.message || '').trim();
|
||||
const status = String((result as { status?: string }).status || '').trim();
|
||||
const tail = status === 'needs_human' ? '请根据提示进行确认/驳回。' : '';
|
||||
await ctx.pushShippingLocalAssistantMessage(
|
||||
[
|
||||
hint || `已处理发货通知附件:${file.name}`,
|
||||
taskId ? `任务编号:${taskId}` : '',
|
||||
tail,
|
||||
].filter(Boolean).join('\n'),
|
||||
);
|
||||
void ctx.refreshShippingActions();
|
||||
};
|
||||
|
||||
const openShippingInventoryPicker = (): boolean => {
|
||||
const taskId = ctx.getActiveShippingTaskId();
|
||||
if (!taskId) {
|
||||
ctx.msg.warning(ctx.t('chat.shippingNoticeMissingTaskId'));
|
||||
return false;
|
||||
}
|
||||
ctx.pendingShippingUploadTaskId.value = taskId;
|
||||
ctx.shippingInventoryPickerRef.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) return;
|
||||
try {
|
||||
const result = await uploadWorkspaceShippingInventory(taskId, file);
|
||||
await continueShippingInventoryUploadWithDify(taskId, result as unknown as Record<string, unknown>, file.name);
|
||||
} catch (e: unknown) {
|
||||
const errorMessage = e instanceof Error ? e.message : ctx.t('chat.shippingNoticeUploadFailed');
|
||||
ctx.msg.warning(errorMessage);
|
||||
}
|
||||
};
|
||||
|
||||
const shippingSuggestedPrompt = computed(() => {
|
||||
const first = ctx.attachments.value.find((a) => a.kind === 'local') as
|
||||
| Extract<PendingAttachment, { kind: 'local' }>
|
||||
| undefined;
|
||||
if (!first) return '';
|
||||
const kind = classifyShippingUploadFile(first.file, extractExt);
|
||||
if (kind === 'inventory') return '上传库存并进入字段对齐';
|
||||
return '解析发货通知并创建任务';
|
||||
});
|
||||
|
||||
const useShippingSuggestedPrompt = () => {
|
||||
const prompt = shippingSuggestedPrompt.value;
|
||||
if (!prompt) return;
|
||||
ctx.input.value = prompt;
|
||||
ctx.shippingAutoFlowRequested.value = true;
|
||||
};
|
||||
|
||||
return {
|
||||
handleShippingAutoUploadFile,
|
||||
openShippingInventoryPicker,
|
||||
handleShippingInventorySelected,
|
||||
shippingSuggestedPrompt,
|
||||
useShippingSuggestedPrompt,
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user