feat(shipping-notice): 新增发货批次和任务管理功能,支持批次创建与任务处理
This commit is contained in:
1 parent
457f0f4e5e
commit
634dee4b81
81 files changed
+9088
-3625
No files matched your search
@@ -1,4 +1,9 @@
|
||||
/** 出货(shipping)子模块 barrel:纯函数 + handler 工厂 + 动作刷新 */
|
||||
/**
|
||||
* features/chat/shipping/index.ts
|
||||
* 用途:统一导出发货通知聊天子模块的纯函数、handler 工厂与辅助工具。
|
||||
* 依赖:shipping/* 子模块本身,不承载业务逻辑。
|
||||
* 逻辑:由 useChatShipping 作为聚合入口导入本 barrel,再分发到具体 handler/composable 文件。
|
||||
*/
|
||||
export * from './shippingText';
|
||||
export * from './shippingMenu';
|
||||
export * from './shippingIntents';
|
||||
@@ -7,10 +12,14 @@ export * from './shippingTaskId';
|
||||
export * from './shippingDownload';
|
||||
export * from './shippingDecisionFormat';
|
||||
export * from './shippingUploadPrompt';
|
||||
export * from './shippingParseReview';
|
||||
export * from './shippingMatchResult';
|
||||
export * from './shippingStepper';
|
||||
export * from './shippingLocalMessages';
|
||||
export * from './shippingConversation';
|
||||
export * from './useChatShippingRefresh';
|
||||
export * from './useChatShippingMappingForm';
|
||||
export * from './useChatShippingParseReview';
|
||||
export * from './useChatShippingDecision';
|
||||
export * from './useChatShippingMenuHandler';
|
||||
export * from './useChatShippingUploadHandler';
|
||||
|
||||
@@ -6,6 +6,11 @@
|
||||
import { resolveShippingNumericChoice } from './shippingMenu';
|
||||
import type { ShippingMenuAction } from '../types/shipping.types';
|
||||
|
||||
export interface ShippingTaskSwitchIntent {
|
||||
mode: 'next' | 'prev' | 'task';
|
||||
taskNo?: string;
|
||||
}
|
||||
|
||||
export function parseShippingColumnMappingFromText(content: string): Record<string, string> | null {
|
||||
const raw = String(content || '').trim();
|
||||
if (!raw) return null;
|
||||
@@ -88,4 +93,20 @@ export function isShippingDownloadExcelIntent(text: string): boolean {
|
||||
].some((pattern) => pattern.test(normalized));
|
||||
}
|
||||
|
||||
export function parseShippingTaskSwitchIntent(text: string): ShippingTaskSwitchIntent | null {
|
||||
const normalized = String(text || '').trim();
|
||||
if (!normalized) return null;
|
||||
const taskMatch = normalized.match(/SN-\d{8}-[A-F0-9]{8}/i);
|
||||
if (taskMatch?.[0] && /(切|切到|切换|goto|go to|switch)/i.test(normalized)) {
|
||||
return { mode: 'task', taskNo: taskMatch[0].toUpperCase() };
|
||||
}
|
||||
if (/^(下一票|下一单|下一个|next)$/i.test(normalized) || /切到下一票/.test(normalized)) {
|
||||
return { mode: 'next' };
|
||||
}
|
||||
if (/^(上一票|上一单|上一个|prev|previous)$/i.test(normalized) || /切到上一票/.test(normalized)) {
|
||||
return { mode: 'prev' };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export type { ShippingMenuAction };
|
||||
@@ -0,0 +1,15 @@
|
||||
/**
|
||||
* 出货聊天:匹配结果卡片 payload 读取。
|
||||
*/
|
||||
import type { ChatMessage } from '../types/chat.types';
|
||||
import type { ShippingMatchResultPayload } from '../types/shipping.types';
|
||||
|
||||
export function getShippingMatchResultPayload(chatMsg: ChatMessage): ShippingMatchResultPayload | null {
|
||||
if (!chatMsg || chatMsg.type !== 'shipping-match-result') return null;
|
||||
const payload = chatMsg.payload;
|
||||
if (!payload || typeof payload !== 'object') return null;
|
||||
const taskId = String((payload as ShippingMatchResultPayload).taskId || '').trim();
|
||||
const lineResults = (payload as ShippingMatchResultPayload).line_results;
|
||||
if (!taskId || !Array.isArray(lineResults)) return null;
|
||||
return payload as ShippingMatchResultPayload;
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
/**
|
||||
* 出货聊天:parse_review 订单表消息 payload 读取。
|
||||
*/
|
||||
import type { ChatMessage } from '../types/chat.types';
|
||||
import type { ShippingParseReviewPayload } from '../types/shipping.types';
|
||||
|
||||
export function getShippingParseReviewPayload(chatMsg: ChatMessage): ShippingParseReviewPayload | null {
|
||||
if (!chatMsg || chatMsg.type !== 'shipping-parse-review') return null;
|
||||
const payload = chatMsg.payload;
|
||||
if (!payload || typeof payload !== 'object') return null;
|
||||
const taskId = String((payload as ShippingParseReviewPayload).taskId || '').trim();
|
||||
const checkpoint = String((payload as ShippingParseReviewPayload).checkpoint || '').trim();
|
||||
const lines = (payload as ShippingParseReviewPayload).lines;
|
||||
if (!taskId || !checkpoint || !Array.isArray(lines)) return null;
|
||||
return payload as ShippingParseReviewPayload;
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
/**
|
||||
* 出货七步 Stepper:基于现有 shipping task 状态推导前端步骤展示。
|
||||
*/
|
||||
export interface ShippingTaskStepperSource {
|
||||
process_status?: string | null;
|
||||
review_status?: string | null;
|
||||
pending_human_reason?: string | null;
|
||||
match_status?: string | null;
|
||||
export_file_name?: string | null;
|
||||
current_step?: string | null;
|
||||
}
|
||||
|
||||
export interface ShippingWorkflowStepItem {
|
||||
id: string;
|
||||
label: string;
|
||||
status: 'completed' | 'current' | 'pending' | 'blocked';
|
||||
}
|
||||
|
||||
export const SHIPPING_WORKFLOW_STEP_LABELS = [
|
||||
'chat.shippingNoticeUi.stepper.noticeSubmit',
|
||||
'chat.shippingNoticeUi.stepper.parseConfirm',
|
||||
'chat.shippingNoticeUi.stepper.inventoryPrepare',
|
||||
'chat.shippingNoticeUi.stepper.alignConfirm',
|
||||
'chat.shippingNoticeUi.stepper.matchInventory',
|
||||
'chat.shippingNoticeUi.stepper.generateFile',
|
||||
'chat.shippingNoticeUi.stepper.uploadFreight',
|
||||
] as const;
|
||||
|
||||
function deriveCurrentIndex(task: ShippingTaskStepperSource | null | undefined): number {
|
||||
const processStatus = String(task?.process_status || '').trim();
|
||||
const reviewStatus = String(task?.review_status || '').trim();
|
||||
const pendingReason = String(task?.pending_human_reason || '').trim();
|
||||
const matchStatus = String(task?.match_status || '').trim();
|
||||
const hasExport = !!String(task?.export_file_name || '').trim();
|
||||
|
||||
if (processStatus === 'uploaded' || processStatus === 'closed') return 6;
|
||||
if (processStatus === 'waiting_upload' || processStatus === 'upload_failed' || hasExport) return 5;
|
||||
if (processStatus === 'matched') return 4;
|
||||
if (reviewStatus === 'shortage_review' || pendingReason === 'shortage_review' || pendingReason === 'shortage') return 4;
|
||||
if (reviewStatus === 'align_review' || pendingReason === 'align_review') return 3;
|
||||
if (processStatus === 'inventory_ready' || matchStatus) return 4;
|
||||
if (
|
||||
processStatus === 'waiting_inventory'
|
||||
|| pendingReason === 'map_infer'
|
||||
|| pendingReason === 'rpa_pending'
|
||||
|| pendingReason === 'inv_unavail'
|
||||
|| pendingReason === 'rpa_exhausted'
|
||||
) {
|
||||
return 2;
|
||||
}
|
||||
if (
|
||||
processStatus === 'parsed'
|
||||
|| processStatus === 'pending_review'
|
||||
|| reviewStatus === 'pending_confirm'
|
||||
|| reviewStatus === 'parse_review'
|
||||
|| reviewStatus === 'rsv_required'
|
||||
|| pendingReason === 'low_confidence'
|
||||
|| pendingReason === 'rsv_required'
|
||||
) {
|
||||
return 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
export function buildShippingWorkflowSteps(
|
||||
task: ShippingTaskStepperSource | null | undefined,
|
||||
): ShippingWorkflowStepItem[] {
|
||||
const currentIndex = deriveCurrentIndex(task);
|
||||
const reviewStatus = String(task?.review_status || '').trim();
|
||||
const pendingReason = String(task?.pending_human_reason || '').trim();
|
||||
const processStatus = String(task?.process_status || '').trim();
|
||||
|
||||
return SHIPPING_WORKFLOW_STEP_LABELS.map((label, index) => {
|
||||
let status: ShippingWorkflowStepItem['status'] = 'pending';
|
||||
if (index < currentIndex) {
|
||||
status = 'completed';
|
||||
} else if (index === currentIndex) {
|
||||
status = 'current';
|
||||
}
|
||||
|
||||
if (
|
||||
(index === 1 && (reviewStatus === 'parse_review' || pendingReason === 'low_confidence' || pendingReason === 'rsv_required'))
|
||||
|| (index === 3 && (reviewStatus === 'align_review' || pendingReason === 'align_review'))
|
||||
|| (index === 4 && (reviewStatus === 'shortage_review' || pendingReason === 'shortage_review' || pendingReason === 'shortage'))
|
||||
|| (index === 6 && processStatus === 'upload_failed')
|
||||
) {
|
||||
status = 'blocked';
|
||||
}
|
||||
|
||||
return {
|
||||
id: `shipping-step-${index + 1}`,
|
||||
label,
|
||||
status,
|
||||
};
|
||||
});
|
||||
}
|
||||
@@ -1,5 +1,8 @@
|
||||
/**
|
||||
* 出货聊天:人工决策提交(confirm/reject/reparse 等)与手工上传标记。
|
||||
/**
|
||||
* features/chat/shipping/useChatShippingDecision.ts
|
||||
* 用途:封装人工决策提交与手工上传标记逻辑。
|
||||
* 依赖:shipping.api、shippingDecisionFormat、chat.types。
|
||||
* 逻辑:由 useChatShipping 调用本文件;本文件负责把 confirm/reject/reparse 等决策提交到后端,并生成聊天区本地消息。
|
||||
*/
|
||||
import {
|
||||
autoProgressWorkspaceShippingTask,
|
||||
@@ -26,6 +29,13 @@ export interface ShippingDecisionContext {
|
||||
t: (key: string, params?: Record<string, unknown>) => string;
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建发货通知决策处理器。
|
||||
*
|
||||
* 核心逻辑:根据决策类型调用对应后端接口,同步本地用户/助手消息,并在需要时刷新历史与动作按钮。
|
||||
* @param ctx - 决策处理上下文
|
||||
* @returns 人工决策与手工上传确认处理函数
|
||||
*/
|
||||
export function createShippingDecisionHandlers(ctx: ShippingDecisionContext) {
|
||||
const syncHistoryIfNeeded = async () => {
|
||||
if (!ctx.conversationId.value && ctx.history.value.length === 0) {
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
/**
|
||||
* 出货聊天:库存列映射表单(打开、应用、重传)。
|
||||
/**
|
||||
* features/chat/shipping/useChatShippingMappingForm.ts
|
||||
* 用途:管理库存列映射表单的打开、提交和重新上传交互。
|
||||
* 依赖:shipping.api、shippingMapping、chat.types、Vue nextTick。
|
||||
* 逻辑:由 useChatShipping 调用本文件;本文件负责把 schema preview 渲染成聊天卡片,并把表单提交回后端映射接口。
|
||||
*/
|
||||
import { nextTick } from 'vue';
|
||||
import {
|
||||
@@ -25,6 +28,13 @@ export interface ShippingMappingFormContext {
|
||||
msg: { warning: (text: string) => void };
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建库存列映射表单处理器。
|
||||
*
|
||||
* 核心逻辑:按任务号打开或复用映射卡片,提交 map_json 到后端,并在成功后刷新动作按钮。
|
||||
* @param ctx - 库存映射表单上下文
|
||||
* @returns 打开、应用和重传库存映射表单的处理函数
|
||||
*/
|
||||
export function createShippingMappingFormHandlers(ctx: ShippingMappingFormContext) {
|
||||
const scrollToLastShippingInventoryMapping = async (): Promise<boolean> => {
|
||||
const container = ctx.chatScrollContainer.value;
|
||||
|
||||
@@ -1,15 +1,19 @@
|
||||
/**
|
||||
* 出货聊天:消息气泡动作按钮与菜单项点击分发。
|
||||
*
|
||||
* 按 action.id 路由到 API 调用、决策提交、文件选择器或 Dify 菜单消息。
|
||||
/**
|
||||
* features/chat/shipping/useChatShippingMenuHandler.ts
|
||||
* 用途:分发聊天气泡动作按钮点击,连接 API、决策处理、下载和文件选择器。
|
||||
* 依赖:shipping.api、shippingDownload、shipping 常量、chat.types。
|
||||
* 逻辑:由 useChatShipping 调用本文件;本文件根据 action.id 决定触发后端接口、本地消息落库或前端 UI 行为。
|
||||
*/
|
||||
import {
|
||||
generateWorkspaceShippingExcel,
|
||||
matchWorkspaceShippingInventory,
|
||||
type ShippingDecisionResponse,
|
||||
type ShippingMatchLineResult,
|
||||
} 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 { ShippingMatchResultPayload } from '../types/shipping.types';
|
||||
import type { Ref } from 'vue';
|
||||
|
||||
export interface ShippingMenuHandlerContext {
|
||||
@@ -28,7 +32,39 @@ export interface ShippingMenuHandlerContext {
|
||||
t: (key: string) => string;
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建发货通知动作菜单处理器。
|
||||
*
|
||||
* 核心逻辑:按 action.id 分流到生成 Excel、库存匹配、人工决策、手工上传确认等前后端动作。
|
||||
* @param ctx - 动作菜单上下文
|
||||
* @returns 菜单动作与按钮点击处理函数
|
||||
*/
|
||||
export function createShippingMenuHandlers(ctx: ShippingMenuHandlerContext) {
|
||||
const buildMatchResultPayload = (
|
||||
taskId: string,
|
||||
result: ShippingDecisionResponse & { action_buttons?: Array<{ id: string; label: string; message: string; variant?: 'primary' | 'secondary' | 'danger' }> },
|
||||
): ShippingMatchResultPayload => {
|
||||
const data = (result?.data && typeof result.data === 'object') ? result.data as Record<string, unknown> : {};
|
||||
const lineResults = Array.isArray(data.line_results)
|
||||
? data.line_results as ShippingMatchLineResult[]
|
||||
: [];
|
||||
const shortageRaw = data.shortage && typeof data.shortage === 'object'
|
||||
? data.shortage as { lines?: ShippingMatchLineResult[] }
|
||||
: null;
|
||||
return {
|
||||
taskId,
|
||||
match_status: typeof data.match_status === 'string' ? data.match_status : null,
|
||||
line_results: lineResults,
|
||||
shortage_lines: Array.isArray(shortageRaw?.lines) ? shortageRaw.lines : [],
|
||||
action_buttons: Array.isArray(result.action_buttons)
|
||||
? result.action_buttons.map((action) => ({
|
||||
...action,
|
||||
variant: action.variant || 'secondary',
|
||||
}))
|
||||
: [],
|
||||
};
|
||||
};
|
||||
|
||||
const handleShippingMenuAction = async (
|
||||
action: { id?: string; message: string },
|
||||
chatMsg?: ChatMessage & { shipping_actions_used?: boolean },
|
||||
@@ -71,11 +107,12 @@ export function createShippingMenuHandlers(ctx: ShippingMenuHandlerContext) {
|
||||
};
|
||||
const assistantMsg: ChatMessage = {
|
||||
role: 'assistant',
|
||||
type: 'text',
|
||||
type: 'shipping-match-result',
|
||||
content: [
|
||||
String(result.message || '').trim(),
|
||||
`任务编号:${taskId}`,
|
||||
].filter(Boolean).join('\n'),
|
||||
payload: buildMatchResultPayload(taskId, result),
|
||||
local_id: ctx.newLocalMessageId('shipping-assistant'),
|
||||
local_only: true,
|
||||
};
|
||||
|
||||
@@ -0,0 +1,209 @@
|
||||
/**
|
||||
* features/chat/shipping/useChatShippingParseReview.ts
|
||||
* 用途:管理 parse_review 阶段的订单表卡片,包括打开、同步和增删改保存。
|
||||
* 依赖:shipping.api、shippingParseReview、chat.types。
|
||||
* 逻辑:由 useChatShipping 调用本文件;本文件在聊天区维护解析复核卡片,并把用户修订同步回后端 notice 编辑接口。
|
||||
*/
|
||||
import {
|
||||
addWorkspaceShippingNoticeLine,
|
||||
getShippingChatActions,
|
||||
getWorkspaceShippingTask,
|
||||
removeWorkspaceShippingNoticeLine,
|
||||
updateWorkspaceShippingNoticeFields,
|
||||
updateWorkspaceShippingNoticeLine,
|
||||
type ShippingNoticeHeader,
|
||||
type ShippingNoticeLine,
|
||||
} from '@/features/chat/api/shipping.api';
|
||||
import { getShippingParseReviewPayload } from './shippingParseReview';
|
||||
import type { ChatMessage } from '../types/chat.types';
|
||||
import type { ShippingParseReviewPayload } from '../types/shipping.types';
|
||||
import type { Ref } from 'vue';
|
||||
|
||||
export interface ShippingParseReviewContext {
|
||||
messages: Ref<ChatMessage[]>;
|
||||
resolvedShippingTaskId: Ref<string>;
|
||||
newLocalMessageId: (prefix: string) => string;
|
||||
saveLocalMessageToBackend: (msg: ChatMessage, userQuery?: string) => Promise<void>;
|
||||
refreshShippingActions: () => Promise<void>;
|
||||
msg: { warning: (text: string) => void };
|
||||
}
|
||||
|
||||
function buildParseReviewPayload(
|
||||
taskId: string,
|
||||
detail: Awaited<ReturnType<typeof getWorkspaceShippingTask>>,
|
||||
checkpoint: string,
|
||||
): ShippingParseReviewPayload {
|
||||
return {
|
||||
taskId,
|
||||
checkpoint,
|
||||
header: {
|
||||
customer_name: detail.customer_name ?? null,
|
||||
customer_code: detail.customer_code ?? null,
|
||||
ship_to: detail.ship_to ?? null,
|
||||
po_number: detail.po_number ?? null,
|
||||
required_date: detail.required_date ?? null,
|
||||
},
|
||||
lines: Array.isArray(detail.lines) ? detail.lines : [],
|
||||
saving: false,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建发货通知 parse review 卡片处理器。
|
||||
*
|
||||
* 核心逻辑:根据任务详情与 checkpoint 维护本地复核卡片,并把单头/订单行编辑回写到后端。
|
||||
* @param ctx - parse review 卡片上下文
|
||||
* @returns 复核卡片同步与编辑处理函数集合
|
||||
*/
|
||||
export function createShippingParseReviewHandlers(ctx: ShippingParseReviewContext) {
|
||||
const removeParseReviewMessageForTask = (taskId: string) => {
|
||||
const normalized = String(taskId || '').trim().toUpperCase();
|
||||
if (!normalized) return;
|
||||
ctx.messages.value = ctx.messages.value.filter((msg) => {
|
||||
const payload = getShippingParseReviewPayload(msg);
|
||||
return payload?.taskId?.trim().toUpperCase() !== normalized;
|
||||
});
|
||||
};
|
||||
|
||||
const upsertParseReviewMessage = async (payload: ShippingParseReviewPayload) => {
|
||||
const normalized = String(payload.taskId || '').trim().toUpperCase();
|
||||
const existing = ctx.messages.value.find((msg) => {
|
||||
const current = getShippingParseReviewPayload(msg);
|
||||
return current?.taskId?.trim().toUpperCase() === normalized;
|
||||
});
|
||||
if (existing) {
|
||||
existing.content = `请确认或修订以下解析结果。\n任务编号:${normalized}`;
|
||||
existing.payload = payload;
|
||||
existing.local_only = true;
|
||||
return;
|
||||
}
|
||||
const reviewMsg: ChatMessage = {
|
||||
role: 'assistant',
|
||||
type: 'shipping-parse-review',
|
||||
content: `请确认或修订以下解析结果。\n任务编号:${normalized}`,
|
||||
payload,
|
||||
local_id: ctx.newLocalMessageId('shipping-parse-review'),
|
||||
local_only: true,
|
||||
};
|
||||
ctx.messages.value.push(reviewMsg);
|
||||
await ctx.saveLocalMessageToBackend(reviewMsg);
|
||||
};
|
||||
|
||||
const syncShippingParseReviewCard = async (taskId?: string): Promise<boolean> => {
|
||||
const normalized = String(taskId || ctx.resolvedShippingTaskId.value || '').trim().toUpperCase();
|
||||
if (!normalized) return false;
|
||||
try {
|
||||
const [detail, actions] = await Promise.all([
|
||||
getWorkspaceShippingTask(normalized),
|
||||
getShippingChatActions(normalized),
|
||||
]);
|
||||
const checkpoint = String(actions.checkpoint || '').trim();
|
||||
if (checkpoint !== 'parse_review') {
|
||||
removeParseReviewMessageForTask(normalized);
|
||||
return false;
|
||||
}
|
||||
await upsertParseReviewMessage(buildParseReviewPayload(normalized, detail, checkpoint));
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
const updateShippingParseReviewHeader = async (
|
||||
msgObj: ChatMessage,
|
||||
fields: Partial<ShippingNoticeHeader>,
|
||||
) => {
|
||||
const payload = getShippingParseReviewPayload(msgObj);
|
||||
if (!payload || payload.saving) return false;
|
||||
payload.saving = true;
|
||||
const taskId = String(payload.taskId || '').trim().toUpperCase();
|
||||
try {
|
||||
await updateWorkspaceShippingNoticeFields(taskId, fields, '聊天区订单表修订');
|
||||
await syncShippingParseReviewCard(taskId);
|
||||
await ctx.refreshShippingActions();
|
||||
return true;
|
||||
} catch (e: unknown) {
|
||||
ctx.msg.warning(e instanceof Error ? e.message : '更新解析结果失败');
|
||||
return false;
|
||||
} finally {
|
||||
const current = getShippingParseReviewPayload(msgObj);
|
||||
if (current) current.saving = false;
|
||||
}
|
||||
};
|
||||
|
||||
const updateShippingParseReviewLine = async (
|
||||
msgObj: ChatMessage,
|
||||
lineIndex: number,
|
||||
patch: Partial<ShippingNoticeLine>,
|
||||
) => {
|
||||
const payload = getShippingParseReviewPayload(msgObj);
|
||||
if (!payload || payload.saving) return false;
|
||||
payload.saving = true;
|
||||
const taskId = String(payload.taskId || '').trim().toUpperCase();
|
||||
try {
|
||||
await updateWorkspaceShippingNoticeLine(taskId, lineIndex, patch, '聊天区订单表修订');
|
||||
await syncShippingParseReviewCard(taskId);
|
||||
await ctx.refreshShippingActions();
|
||||
return true;
|
||||
} catch (e: unknown) {
|
||||
ctx.msg.warning(e instanceof Error ? e.message : '更新解析结果失败');
|
||||
return false;
|
||||
} finally {
|
||||
const current = getShippingParseReviewPayload(msgObj);
|
||||
if (current) current.saving = false;
|
||||
}
|
||||
};
|
||||
|
||||
const addShippingParseReviewLine = async (
|
||||
msgObj: ChatMessage,
|
||||
line: Partial<ShippingNoticeLine>,
|
||||
) => {
|
||||
const payload = getShippingParseReviewPayload(msgObj);
|
||||
if (!payload || payload.saving) return false;
|
||||
payload.saving = true;
|
||||
const taskId = String(payload.taskId || '').trim().toUpperCase();
|
||||
try {
|
||||
await addWorkspaceShippingNoticeLine(taskId, line, '聊天区订单表新增行');
|
||||
await syncShippingParseReviewCard(taskId);
|
||||
await ctx.refreshShippingActions();
|
||||
return true;
|
||||
} catch (e: unknown) {
|
||||
ctx.msg.warning(e instanceof Error ? e.message : '新增订单行失败');
|
||||
return false;
|
||||
} finally {
|
||||
const current = getShippingParseReviewPayload(msgObj);
|
||||
if (current) current.saving = false;
|
||||
}
|
||||
};
|
||||
|
||||
const removeShippingParseReviewLine = async (
|
||||
msgObj: ChatMessage,
|
||||
lineIndex: number,
|
||||
) => {
|
||||
const payload = getShippingParseReviewPayload(msgObj);
|
||||
if (!payload || payload.saving) return false;
|
||||
payload.saving = true;
|
||||
const taskId = String(payload.taskId || '').trim().toUpperCase();
|
||||
try {
|
||||
await removeWorkspaceShippingNoticeLine(taskId, lineIndex, '聊天区订单表删除行');
|
||||
await syncShippingParseReviewCard(taskId);
|
||||
await ctx.refreshShippingActions();
|
||||
return true;
|
||||
} catch (e: unknown) {
|
||||
ctx.msg.warning(e instanceof Error ? e.message : '删除订单行失败');
|
||||
return false;
|
||||
} finally {
|
||||
const current = getShippingParseReviewPayload(msgObj);
|
||||
if (current) current.saving = false;
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
getShippingParseReviewPayload,
|
||||
syncShippingParseReviewCard,
|
||||
updateShippingParseReviewHeader,
|
||||
updateShippingParseReviewLine,
|
||||
addShippingParseReviewLine,
|
||||
removeShippingParseReviewLine,
|
||||
};
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
/**
|
||||
* 出货聊天:助手消息动作按钮刷新(有状态 composable 工厂)。
|
||||
*
|
||||
* 按 taskId 拉取 getShippingChatActions,写入 messages[].shipping_actions;
|
||||
* 终态 checkpoint 时清除所有按钮。
|
||||
/**
|
||||
* features/chat/shipping/useChatShippingRefresh.ts
|
||||
* 用途:刷新聊天区发货通知动作按钮,把后端 checkpoint/action_buttons 同步到消息气泡。
|
||||
* 依赖:shipping.api、shippingMenu、shippingTaskId、shippingNoticeActions 常量、chat.types。
|
||||
* 逻辑:由 useChatShipping 调用本文件;本文件根据当前 taskId 拉取动作配置并回写到 messages[].shipping_actions。
|
||||
*/
|
||||
import {
|
||||
getShippingChatActions,
|
||||
@@ -27,10 +27,23 @@ export interface ShippingRefreshContext {
|
||||
shippingConversationTaskIdCache: Ref<Record<string, string>>;
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断某条助手消息后面是否已经出现新的用户回复。
|
||||
* @param msgs - 当前消息列表
|
||||
* @param index - 目标助手消息索引
|
||||
* @returns `true` 表示该消息已被后续用户输入“盖住”
|
||||
*/
|
||||
export function assistantMessageHasLaterUserReply(msgs: Array<{ role?: string }>, index: number): boolean {
|
||||
return msgs.slice(index + 1).some((item) => item.role === 'user');
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建发货通知动作按钮刷新器。
|
||||
*
|
||||
* 核心逻辑:优先按 taskId 拉取后端 action_buttons,失败时回退到消息文本指令解析,并在终态 checkpoint 清空旧按钮。
|
||||
* @param ctx - 发货通知聊天上下文
|
||||
* @returns 动作刷新函数
|
||||
*/
|
||||
export function createShippingActionsRefresher(ctx: ShippingRefreshContext) {
|
||||
let shippingActionsRequestSeq = 0;
|
||||
|
||||
@@ -145,6 +158,9 @@ export function createShippingActionsRefresher(ctx: ShippingRefreshContext) {
|
||||
}
|
||||
buttons = resolved.buttons;
|
||||
}
|
||||
if (chatMsg.type === 'shipping-match-result' && chatMsg.payload && typeof chatMsg.payload === 'object') {
|
||||
(chatMsg.payload as { action_buttons?: ShippingActionButton[] }).action_buttons = buttons;
|
||||
}
|
||||
chatMsg.shipping_actions = buttons.length ? buttons : undefined;
|
||||
});
|
||||
};
|
||||
|
||||
@@ -1,9 +1,15 @@
|
||||
/**
|
||||
* 出货聊天:handleSend 前置拦截(菜单数字、决策文本、列映射、附件自动流程)。
|
||||
*
|
||||
* 返回 true 表示已消费本次发送,ChatView 不再走默认 Dify 流程。
|
||||
/**
|
||||
* features/chat/shipping/useChatShippingSendHandler.ts
|
||||
* 用途:在聊天发送前拦截发货通知专属意图,如切票、决策文本、列映射和附件自动流程。
|
||||
* 依赖:shipping.api、shippingIntents、shippingMenu、shippingMapping、shippingDownload、chat.types。
|
||||
* 逻辑:由 useChatShipping 调用本文件;本文件优先消费 shipping 领域意图,只有未命中时才放行到默认 Dify 对话链路。
|
||||
*/
|
||||
import { applyWorkspaceShippingInventoryMapping, generateWorkspaceShippingExcel } from '@/features/chat/api/shipping.api';
|
||||
import {
|
||||
applyWorkspaceShippingInventoryMapping,
|
||||
generateWorkspaceShippingExcel,
|
||||
getWorkspaceShippingBatch,
|
||||
switchWorkspaceShippingBatchFocusTask,
|
||||
} from '@/features/chat/api/shipping.api';
|
||||
import { SHIPPING_MENU_ACTION_SPECS } from '../constants/shipping';
|
||||
import { buildShippingFieldAlignmentText } from './shippingMapping';
|
||||
import { downloadWorkspaceShippingExcelFile } from './shippingDownload';
|
||||
@@ -12,12 +18,12 @@ import {
|
||||
isShippingGenerateExcelIntent,
|
||||
isShippingInventoryUploadIntent,
|
||||
isShippingManualUploadIntent,
|
||||
parseShippingTaskSwitchIntent,
|
||||
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';
|
||||
@@ -33,6 +39,7 @@ export interface ShippingSendHandlerContext {
|
||||
attachments: Ref<PendingAttachment[]>;
|
||||
shippingAutoFlowRequested: Ref<boolean>;
|
||||
resolvedShippingTaskId: Ref<string>;
|
||||
getActiveShippingBatchNo: () => string;
|
||||
currentAgentId: ComputedRef<number>;
|
||||
selectedKb: Ref<string>;
|
||||
attachmentPolicy: ComputedRef<{ anyEnabled: boolean }>;
|
||||
@@ -53,13 +60,66 @@ export interface ShippingSendHandlerContext {
|
||||
executeShippingDecision: (decision: string, displayText?: string) => Promise<boolean>;
|
||||
executeShippingManualUpload: (taskId: string, displayText?: string) => Promise<boolean>;
|
||||
handleShippingAutoUploadFile: (file: File) => Promise<void>;
|
||||
handleShippingAutoUploadNoticeBatch: (files: File[]) => Promise<void>;
|
||||
refreshShippingActions: () => Promise<void>;
|
||||
shippingSuggestedPrompt: ComputedRef<string>;
|
||||
msg: { warning: (text: string) => void; info: (text: string) => void };
|
||||
t: (key: string) => string;
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建发货通知发送拦截器。
|
||||
*
|
||||
* 核心逻辑:识别切换任务、数字菜单、决策文本、映射文本、上传/导出意图,并在命中时直接走本地前后端流程。
|
||||
* @param ctx - 发送拦截上下文
|
||||
* @returns 发送前文本与附件自动流程处理函数;返回 true 表示已消费本次发送
|
||||
*/
|
||||
export function createShippingSendHandlers(ctx: ShippingSendHandlerContext) {
|
||||
const trySwitchShippingTask = async (content: string): Promise<boolean> => {
|
||||
const intent = parseShippingTaskSwitchIntent(content);
|
||||
if (!intent) return false;
|
||||
const batchNo = ctx.getActiveShippingBatchNo();
|
||||
if (!batchNo) {
|
||||
ctx.msg.warning('当前没有可切换的批次');
|
||||
return true;
|
||||
}
|
||||
try {
|
||||
const detail = await getWorkspaceShippingBatch(batchNo);
|
||||
const tasks = Array.isArray(detail.tasks) ? detail.tasks : [];
|
||||
if (tasks.length <= 1) {
|
||||
ctx.msg.info('当前批次只有 1 票,无需切换');
|
||||
return true;
|
||||
}
|
||||
const focusTaskNo = String(detail.focus_task?.task_no || detail.current_focus_task_no || '').trim().toUpperCase();
|
||||
const currentIndex = Math.max(tasks.findIndex((item) => String(item.task_no || '').trim().toUpperCase() === focusTaskNo), 0);
|
||||
let targetTaskNo = '';
|
||||
if (intent.mode === 'task') {
|
||||
targetTaskNo = String(intent.taskNo || '').trim().toUpperCase();
|
||||
} else if (intent.mode === 'next') {
|
||||
targetTaskNo = String(tasks[Math.min(currentIndex + 1, tasks.length - 1)]?.task_no || '').trim().toUpperCase();
|
||||
} else {
|
||||
targetTaskNo = String(tasks[Math.max(currentIndex - 1, 0)]?.task_no || '').trim().toUpperCase();
|
||||
}
|
||||
if (!targetTaskNo) {
|
||||
ctx.msg.warning('未找到要切换的任务');
|
||||
return true;
|
||||
}
|
||||
if (targetTaskNo === focusTaskNo) {
|
||||
ctx.msg.info(intent.mode === 'next' ? '已经是最后一票' : intent.mode === 'prev' ? '已经是第一票' : '已在当前任务');
|
||||
return true;
|
||||
}
|
||||
await switchWorkspaceShippingBatchFocusTask(batchNo, targetTaskNo);
|
||||
ctx.resolvedShippingTaskId.value = targetTaskNo;
|
||||
await ctx.pushShippingLocalUserMessage(content.trim());
|
||||
await ctx.pushShippingLocalAssistantMessage(`已切换到任务 ${targetTaskNo},请继续当前票处理。`);
|
||||
void ctx.refreshShippingActions();
|
||||
} catch (e: unknown) {
|
||||
const errorMessage = e instanceof Error ? e.message : '切换任务失败';
|
||||
ctx.msg.warning(errorMessage);
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
const tryHandleShippingAttachmentAutoFlow = async (
|
||||
textOrEvent: string | Event | undefined,
|
||||
_content: string,
|
||||
@@ -93,29 +153,16 @@ export function createShippingSendHandlers(ctx: ShippingSendHandlerContext) {
|
||||
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,
|
||||
});
|
||||
try {
|
||||
const prompt = ctx.shippingSuggestedPrompt.value || '解析发货通知并创建任务';
|
||||
await ctx.pushShippingLocalUserMessage(prompt);
|
||||
await ctx.handleShippingAutoUploadNoticeBatch(localFiles.map((item) => item.file));
|
||||
} catch (e: unknown) {
|
||||
const errorMessage = e instanceof Error ? e.message : '文件处理失败';
|
||||
ctx.msg.warning(errorMessage);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
@@ -127,6 +174,11 @@ export function createShippingSendHandlers(ctx: ShippingSendHandlerContext) {
|
||||
_trimmed: string,
|
||||
): Promise<boolean> => {
|
||||
if (!ctx.isShippingNoticeAgent.value) return false;
|
||||
if (await trySwitchShippingTask(content)) {
|
||||
if (typeof textOrEvent !== 'string') ctx.input.value = '';
|
||||
ctx.attachments.value = [];
|
||||
return true;
|
||||
}
|
||||
const assistantCtx = ctx.lastAssistantMessageContent();
|
||||
const menuChoice = resolveShippingNumericChoice(content, assistantCtx);
|
||||
if (menuChoice) {
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
/**
|
||||
* 出货聊天:库存/发货通知文件上传、隐藏 file input、附件建议提示。
|
||||
/**
|
||||
* features/chat/shipping/useChatShippingUploadHandler.ts
|
||||
* 用途:处理发货通知与库存文件上传、批量建单和附件建议提示。
|
||||
* 依赖:shipping.api、shippingUploadPrompt、shipping 常量、chat.types。
|
||||
* 逻辑:由 useChatShipping 调用本文件;本文件识别附件类型后决定是创建任务/批次还是上传库存,并把结果同步到聊天上下文。
|
||||
*/
|
||||
import { computed } from 'vue';
|
||||
import {
|
||||
createWorkspaceShippingBatchFromNotices,
|
||||
createWorkspaceShippingTask,
|
||||
createWorkspaceShippingTaskFromNotice,
|
||||
uploadWorkspaceShippingInventory,
|
||||
} from '@/features/chat/api/shipping.api';
|
||||
import { extractExt } from '../constants/shipping';
|
||||
@@ -20,6 +23,8 @@ export interface ShippingUploadHandlerContext {
|
||||
shippingInventoryPickerRef: Ref<HTMLInputElement | null>;
|
||||
pendingShippingUploadTaskId: Ref<string>;
|
||||
resolvedShippingTaskId: Ref<string>;
|
||||
resolvedShippingBatchNo: Ref<string>;
|
||||
shippingBatchSummary: Ref<unknown | null>;
|
||||
shippingInventorySchemaPreviewCache: Ref<Record<string, unknown>>;
|
||||
getActiveShippingTaskId: () => string;
|
||||
sendShippingMenuMessage: (message: string) => Promise<void>;
|
||||
@@ -29,6 +34,13 @@ export interface ShippingUploadHandlerContext {
|
||||
t: (key: string) => string;
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建发货通知上传处理器。
|
||||
*
|
||||
* 核心逻辑:识别附件属于发货通知还是库存文件,分别触发建单/建批或库存上传,并维护 task/batch 本地上下文。
|
||||
* @param ctx - 上传处理上下文
|
||||
* @returns 自动上传、文件选择器和建议提示相关处理函数
|
||||
*/
|
||||
export function createShippingUploadHandlers(ctx: ShippingUploadHandlerContext) {
|
||||
const continueShippingInventoryUploadWithDify = async (
|
||||
taskId: string,
|
||||
@@ -47,6 +59,25 @@ export function createShippingUploadHandlers(ctx: ShippingUploadHandlerContext)
|
||||
await ctx.sendShippingMenuMessage(buildShippingInventoryUploadPrompt(result, fileName));
|
||||
};
|
||||
|
||||
const syncBatchContextFromNoticeResponse = (result: Record<string, unknown> | null | undefined) => {
|
||||
const batchNo = String(
|
||||
(result?.batch_no as string | undefined)
|
||||
|| ((result?.data as { batch?: { batch_no?: string } } | undefined)?.batch?.batch_no)
|
||||
|| '',
|
||||
).trim();
|
||||
const focusTaskNo = String(
|
||||
((result?.data as { focus_task?: { task_no?: string } } | undefined)?.focus_task?.task_no)
|
||||
|| (result?.task_id as string | undefined)
|
||||
|| '',
|
||||
).trim();
|
||||
const batchSummary = ((result?.data as { batch?: unknown } | undefined)?.batch) || null;
|
||||
if (batchNo) ctx.resolvedShippingBatchNo.value = batchNo;
|
||||
if (focusTaskNo) ctx.resolvedShippingTaskId.value = focusTaskNo;
|
||||
if (batchSummary && typeof batchSummary === 'object') {
|
||||
ctx.shippingBatchSummary.value = batchSummary;
|
||||
}
|
||||
};
|
||||
|
||||
const handleShippingAutoUploadFile = async (file: File) => {
|
||||
const kind = classifyShippingUploadFile(file, extractExt);
|
||||
if (kind === 'inventory') {
|
||||
@@ -67,18 +98,28 @@ export function createShippingUploadHandlers(ctx: ShippingUploadHandlerContext)
|
||||
await continueShippingInventoryUploadWithDify(taskId, result as unknown as Record<string, unknown>, file.name);
|
||||
return;
|
||||
}
|
||||
const result = await createWorkspaceShippingTaskFromNotice(
|
||||
file,
|
||||
const result = await createWorkspaceShippingBatchFromNotices(
|
||||
[file],
|
||||
String(ctx.conversationId.value || '').trim() || undefined,
|
||||
);
|
||||
const taskId = String(result.task_id || '').trim();
|
||||
if (taskId) ctx.resolvedShippingTaskId.value = taskId;
|
||||
syncBatchContextFromNoticeResponse(result as unknown as Record<string, unknown>);
|
||||
const taskId = String(
|
||||
((result.data as { focus_task?: { task_no?: string } } | undefined)?.focus_task?.task_no)
|
||||
|| result.task_id
|
||||
|| '',
|
||||
).trim();
|
||||
const batchNo = String(
|
||||
result.batch_no
|
||||
|| ((result.data as { batch?: { batch_no?: string } } | undefined)?.batch?.batch_no)
|
||||
|| '',
|
||||
).trim();
|
||||
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}`,
|
||||
batchNo ? `批次编号:${batchNo}` : '',
|
||||
taskId ? `任务编号:${taskId}` : '',
|
||||
tail,
|
||||
].filter(Boolean).join('\n'),
|
||||
@@ -86,6 +127,51 @@ export function createShippingUploadHandlers(ctx: ShippingUploadHandlerContext)
|
||||
void ctx.refreshShippingActions();
|
||||
};
|
||||
|
||||
const handleShippingAutoUploadNoticeBatch = async (files: File[]) => {
|
||||
const noticeFiles = files.filter(Boolean);
|
||||
if (!noticeFiles.length) return;
|
||||
const result = await createWorkspaceShippingBatchFromNotices(
|
||||
noticeFiles,
|
||||
String(ctx.conversationId.value || '').trim() || undefined,
|
||||
);
|
||||
syncBatchContextFromNoticeResponse(result as unknown as Record<string, unknown>);
|
||||
const taskId = String(
|
||||
((result.data as { focus_task?: { task_no?: string } } | undefined)?.focus_task?.task_no)
|
||||
|| result.task_id
|
||||
|| '',
|
||||
).trim();
|
||||
const batchNo = String(
|
||||
result.batch_no
|
||||
|| ((result.data as { batch?: { batch_no?: string } } | undefined)?.batch?.batch_no)
|
||||
|| '',
|
||||
).trim();
|
||||
const batch = (result.data as {
|
||||
batch?: { file_count?: number };
|
||||
tasks?: Array<{ batch_index?: number; batch_total?: number }>;
|
||||
} | undefined)?.batch;
|
||||
const tasks = Array.isArray((result.data as { tasks?: unknown[] } | undefined)?.tasks)
|
||||
? (result.data as { tasks: Array<{ batch_index?: number; batch_total?: number }> }).tasks
|
||||
: [];
|
||||
const focusTask = tasks[0];
|
||||
const focusProgress = focusTask?.batch_index && focusTask?.batch_total
|
||||
? `当前第 ${focusTask.batch_index}/${focusTask.batch_total} 票`
|
||||
: '';
|
||||
const fileCount = Number(batch?.file_count || noticeFiles.length || 0);
|
||||
const hint = String(result.message || '').trim();
|
||||
const status = String((result as { status?: string }).status || '').trim();
|
||||
const tail = status === 'needs_human' ? '请根据提示进行确认/驳回。' : '';
|
||||
await ctx.pushShippingLocalAssistantMessage(
|
||||
[
|
||||
hint || `已处理 ${fileCount} 份发货通知附件`,
|
||||
batchNo ? `批次编号:${batchNo}` : '',
|
||||
taskId ? `当前任务:${taskId}` : '',
|
||||
focusProgress,
|
||||
tail,
|
||||
].filter(Boolean).join('\n'),
|
||||
);
|
||||
void ctx.refreshShippingActions();
|
||||
};
|
||||
|
||||
const openShippingInventoryPicker = (): boolean => {
|
||||
const taskId = ctx.getActiveShippingTaskId();
|
||||
if (!taskId) {
|
||||
@@ -132,6 +218,7 @@ export function createShippingUploadHandlers(ctx: ShippingUploadHandlerContext)
|
||||
|
||||
return {
|
||||
handleShippingAutoUploadFile,
|
||||
handleShippingAutoUploadNoticeBatch,
|
||||
openShippingInventoryPicker,
|
||||
handleShippingInventorySelected,
|
||||
shippingSuggestedPrompt,
|
||||
|
||||
Reference in new issue
Block a user