refactor(chat/shipping): 重构发货通知模块为统一UI State驱动模式
- 重构发货通知的状态与动作获取逻辑:移除从聊天文本解析HXOPS_SHIPPING_ACTIONS注释的旧逻辑,改为统一从后端shipping_ui_state获取任务状态、动作按钮与工作流步骤 - 新增SSE实时推送shipping_ui_state事件,支持前端即时更新聊天气泡与工作台的状态与按钮 - 优化路由与登录流程:调整根路径重定向逻辑,退出登录时跳转到登录页;移除chat路由不必要的props传参;将原路由守卫中的根路径判断迁移到路由配置中 - 完善库存RPA与本地导入流程:新增本地库存文件托管接口,优化RPA回调的文件落盘与任务关联逻辑 - 新增多组单元测试覆盖焦点切换、决策处理、SSE同步等核心场景 - 修复多语言显示逻辑,使用te方法判断翻译key是否存在,避免缺失翻译时的渲染异常 - 新增reparse_inventory菜单动作,支持静默重新解析库存且不追加额外聊天消息 - 重构工作流步骤渲染函数,优先使用后端返回的步骤数据, fallback到本地推导的旧逻辑 - 清理后端旧的chat-actions API接口,将相关逻辑迁移到统一的ui_state接口中
This commit is contained in:
commit
9c036c825b
39 files changed
+3114
-456
No files matched your search
@@ -1,10 +1,9 @@
|
||||
/**
|
||||
* features/chat/shipping/shippingMenu.ts
|
||||
* 用途:发货聊天数字菜单解析、动作按钮合并与决策文本识别(纯函数)。
|
||||
* 依赖:shippingText.extractShippingActionsDirective、types/shipping.types。
|
||||
* 逻辑:useChatShippingSendHandler 在发送前调用;按钮只来自 API 或结构化 HTML 指令,不从自然语言正文猜测。
|
||||
* 依赖:types/shipping.types。
|
||||
* 逻辑:useChatShippingSendHandler 在发送前调用;按钮只来自后端状态机 UI State,不从自然语言正文猜测。
|
||||
*/
|
||||
import { extractShippingActionsDirective, stripShippingActionListByButtons } from './shippingText';
|
||||
import type { ShippingActionButton, ShippingMenuAction } from '../types/shipping.types';
|
||||
|
||||
/**
|
||||
@@ -76,32 +75,6 @@ export function normalizeApiShippingButtons(
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* 合并 API 按钮与 HTML 指令,得到最终 action_buttons 与 cleanedText。
|
||||
*/
|
||||
export function resolveShippingActionButtons(
|
||||
content: string,
|
||||
apiButtons: Array<{ id: string; label: string; message: string; variant?: string; source_code?: string }> | null,
|
||||
opts?: { apiResolved?: boolean },
|
||||
) {
|
||||
const directive = extractShippingActionsDirective(String(content || ''));
|
||||
if (opts?.apiResolved) {
|
||||
const buttons = normalizeApiShippingButtons(apiButtons);
|
||||
return {
|
||||
buttons,
|
||||
cleanedText: stripShippingActionListByButtons(directive.cleanedText, buttons),
|
||||
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 };
|
||||
}
|
||||
|
||||
/**
|
||||
* 从用户文本与助手上下文识别 submit_decision 所需的 action id。
|
||||
*/
|
||||
|
||||
@@ -19,6 +19,13 @@ export interface ShippingWorkflowStepItem {
|
||||
status: 'completed' | 'current' | 'pending' | 'blocked';
|
||||
}
|
||||
|
||||
type ShippingWorkflowStepSource = {
|
||||
id?: string | null;
|
||||
code?: string | null;
|
||||
label?: string | null;
|
||||
status?: string | null;
|
||||
};
|
||||
|
||||
export const SHIPPING_WORKFLOW_STEP_LABELS = [
|
||||
'chat.shippingNoticeUi.stepper.noticeSubmit',
|
||||
'chat.shippingNoticeUi.stepper.parseConfirm',
|
||||
@@ -46,6 +53,44 @@ const CURRENT_STEP_INDEX_MAP: Record<string, number> = {
|
||||
};
|
||||
|
||||
const TERMINAL_PROCESS_STATUSES = new Set(['uploaded', 'closed']);
|
||||
const WORKFLOW_STEP_STATUSES = new Set<ShippingWorkflowStepItem['status']>([
|
||||
'completed',
|
||||
'current',
|
||||
'pending',
|
||||
'blocked',
|
||||
]);
|
||||
|
||||
/**
|
||||
* 将后端 UI State steps 收窄为 Stepper 可渲染的前端结构。
|
||||
*/
|
||||
export function normalizeShippingWorkflowSteps(
|
||||
steps: ShippingWorkflowStepSource[] | null | undefined,
|
||||
): ShippingWorkflowStepItem[] {
|
||||
if (!Array.isArray(steps)) return [];
|
||||
return steps
|
||||
.map((step, index) => {
|
||||
const status = String(step?.status || '').trim();
|
||||
if (!WORKFLOW_STEP_STATUSES.has(status as ShippingWorkflowStepItem['status'])) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
id: String(step?.id || step?.code || `shipping-step-${index + 1}`),
|
||||
label: String(step?.label || SHIPPING_WORKFLOW_STEP_LABELS[index] || ''),
|
||||
status: status as ShippingWorkflowStepItem['status'],
|
||||
};
|
||||
})
|
||||
.filter((step): step is ShippingWorkflowStepItem => !!step);
|
||||
}
|
||||
|
||||
/**
|
||||
* 优先消费后端状态机 UI State steps;没有时按 task 状态本地推导。
|
||||
*/
|
||||
export function resolveShippingWorkflowSteps(
|
||||
task: (ShippingTaskStepperSource & { ui_state?: { steps?: ShippingWorkflowStepSource[] | null } | null }) | null | undefined,
|
||||
): ShippingWorkflowStepItem[] {
|
||||
const uiStateSteps = normalizeShippingWorkflowSteps(task?.ui_state?.steps);
|
||||
return uiStateSteps.length ? uiStateSteps : buildShippingWorkflowSteps(task);
|
||||
}
|
||||
|
||||
function deriveCurrentIndex(task: ShippingTaskStepperSource | null | undefined): number {
|
||||
const currentStep = String(task?.current_step || '').trim();
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
/**
|
||||
* features/chat/shipping/shippingText.ts
|
||||
* 用途:发货聊天消息文本净化与 HTML 动作指令解析(纯函数,无 Vue 依赖)。
|
||||
* 用途:发货聊天消息文本净化(纯函数,无 Vue 依赖)。
|
||||
* 依赖:constants/shippingNoticeActions、types/shipping.types。
|
||||
* 逻辑:ChatView 渲染前 sanitize;shippingMenu 解析 <!-- HXOPS_SHIPPING_ACTIONS --> 注释块。
|
||||
* 逻辑:ChatView 渲染前 sanitize;动作按钮统一来自后端 shipping_ui_state。
|
||||
*/
|
||||
import { SHIPPING_INTERNAL_STATUS_TOKENS, SHIPPING_KNOWN_ACTION_ID_SET } from '@/constants/shippingNoticeActions';
|
||||
import type { ShippingActionButton, ShippingActionVariant } from '../types/shipping.types';
|
||||
import { SHIPPING_INTERNAL_STATUS_TOKENS } from '@/constants/shippingNoticeActions';
|
||||
import type { ShippingActionButton } from '../types/shipping.types';
|
||||
|
||||
/**
|
||||
* 文本归一化用于判断 Agent 正文编号项是否重复描述了结构化按钮。
|
||||
@@ -249,49 +249,16 @@ export function sanitizeShippingConversationText(text: string, enabled: boolean)
|
||||
result = result.replace(quoted, '');
|
||||
result = result.replace(new RegExp(`\`${token}\``, 'gi'), '');
|
||||
}
|
||||
return stripShippingPlainActionMenu(stripShippingRedundantNumberedActionList(result.replace(/\n{3,}/g, '\n\n').trim()));
|
||||
return stripShippingPlainActionMenu(stripShippingRedundantNumberedActionList(stripShippingActionsDirectiveComment(result).replace(/\n{3,}/g, '\n\n').trim()));
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析消息中的 HXOPS_SHIPPING_ACTIONS HTML 注释,提取 action_buttons 并返回净化后文本。
|
||||
* 移除历史 HXOPS_SHIPPING_ACTIONS HTML 注释。
|
||||
*
|
||||
* 按钮已经切换为后端状态机 shipping_ui_state,正文注释只作为脏文本清理,不再产生 action_buttons。
|
||||
*/
|
||||
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 stripShippingActionsDirectiveComment(rawText: string): string {
|
||||
return String(rawText || '').replace(/<!--\s*HXOPS_SHIPPING_ACTIONS\s*:\s*[\s\S]*?\s*-->/gi, '').trim();
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
/**
|
||||
* features/chat/shipping/useChatShippingDecision.spec.ts
|
||||
* 用途:验证发货通知决策处理器的 silent 模式,避免纯 UI 操作追加本地聊天气泡。
|
||||
* 依赖:vitest、vue refs、shipping.api、useChatShippingDecision。
|
||||
* 逻辑:分别覆盖 silent 与普通决策路径,确保 silent 仅更新状态,不写入本地消息或后端消息存档。
|
||||
*/
|
||||
import { computed, ref } from 'vue';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { createShippingDecisionHandlers, type ShippingDecisionContext } from './useChatShippingDecision';
|
||||
|
||||
const {
|
||||
autoProgressWorkspaceShippingTask,
|
||||
markWorkspaceShippingManualUploaded,
|
||||
submitWorkspaceShippingDecision,
|
||||
} = vi.hoisted(() => ({
|
||||
autoProgressWorkspaceShippingTask: vi.fn(),
|
||||
markWorkspaceShippingManualUploaded: vi.fn(),
|
||||
submitWorkspaceShippingDecision: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('@/features/chat/api/shipping.api', () => ({
|
||||
autoProgressWorkspaceShippingTask,
|
||||
markWorkspaceShippingManualUploaded,
|
||||
submitWorkspaceShippingDecision,
|
||||
}));
|
||||
|
||||
const createContext = (
|
||||
overrides: Partial<ShippingDecisionContext> = {},
|
||||
): ShippingDecisionContext => ({
|
||||
messages: ref([]),
|
||||
conversationId: ref('conv-001'),
|
||||
history: ref([{ conversation_id: 'conv-001' }]),
|
||||
isShippingNoticeAgent: computed(() => true),
|
||||
shippingInventorySchemaPreviewCache: ref({}),
|
||||
getActiveShippingTaskId: () => 'SN-FOCUS-001',
|
||||
newLocalMessageId: vi.fn((prefix: string) => `${prefix}-local-id`),
|
||||
saveLocalMessageToBackend: vi.fn(async () => undefined),
|
||||
loadHistory: vi.fn(async () => undefined),
|
||||
openShippingInventoryMappingFormForTask: vi.fn(async () => true),
|
||||
refreshShippingActions: vi.fn(async () => undefined),
|
||||
msg: {
|
||||
warning: vi.fn(),
|
||||
success: vi.fn(),
|
||||
},
|
||||
t: (key: string) => key,
|
||||
...overrides,
|
||||
});
|
||||
|
||||
describe('useChatShippingDecision', () => {
|
||||
it('does not append local chat messages when decision runs in silent mode', async () => {
|
||||
submitWorkspaceShippingDecision.mockResolvedValue({
|
||||
message: '已清除库存快照,请重新上传库存。',
|
||||
data: {},
|
||||
});
|
||||
const ctx = createContext();
|
||||
const { executeShippingDecision } = createShippingDecisionHandlers(ctx);
|
||||
|
||||
const ok = await executeShippingDecision('reparse_inventory', '重新上传库存', { silent: true });
|
||||
|
||||
expect(ok).toBe(true);
|
||||
expect(submitWorkspaceShippingDecision).toHaveBeenCalledWith('SN-FOCUS-001', 'reparse_inventory');
|
||||
expect(ctx.messages.value).toEqual([]);
|
||||
expect(ctx.saveLocalMessageToBackend).not.toHaveBeenCalled();
|
||||
expect(ctx.refreshShippingActions).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('keeps appending local chat messages for normal decisions', async () => {
|
||||
submitWorkspaceShippingDecision.mockResolvedValue({
|
||||
message: '已确认,请继续下一步。',
|
||||
data: {},
|
||||
});
|
||||
const ctx = createContext();
|
||||
const { executeShippingDecision } = createShippingDecisionHandlers(ctx);
|
||||
|
||||
const ok = await executeShippingDecision('confirm', '确认');
|
||||
|
||||
expect(ok).toBe(true);
|
||||
expect(ctx.messages.value).toHaveLength(2);
|
||||
expect(ctx.messages.value[0]?.role).toBe('user');
|
||||
expect(ctx.messages.value[1]?.role).toBe('assistant');
|
||||
expect(ctx.saveLocalMessageToBackend).toHaveBeenCalledTimes(2);
|
||||
expect(ctx.refreshShippingActions).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
@@ -29,10 +29,14 @@ export interface ShippingDecisionContext {
|
||||
t: (key: string, params?: Record<string, unknown>) => string;
|
||||
}
|
||||
|
||||
export interface ExecuteShippingDecisionOptions {
|
||||
silent?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建发货通知决策处理器。
|
||||
*
|
||||
* 核心逻辑:根据决策类型调用对应后端接口,同步本地用户/助手消息,并在需要时刷新历史与动作按钮。
|
||||
* 核心逻辑:根据决策类型调用对应后端接口;默认同步本地用户/助手消息,也支持 silent 模式仅更新状态机与按钮。
|
||||
* @param ctx - 决策处理上下文
|
||||
* @returns 人工决策与手工上传确认处理函数
|
||||
*/
|
||||
@@ -48,7 +52,19 @@ export function createShippingDecisionHandlers(ctx: ShippingDecisionContext) {
|
||||
}
|
||||
};
|
||||
|
||||
const executeShippingDecision = async (decision: string, displayText?: string) => {
|
||||
/**
|
||||
* 提交发货人工决策,并按需把结果落为本地聊天消息。
|
||||
* 核心逻辑:先基于 taskId 调后端决策接口,再根据 silent 选项决定是否写入本地 user/assistant 气泡。
|
||||
* @param decision - 决策动作 ID,如 confirm、reparse_inventory
|
||||
* @param displayText - 用户侧展示文案;未传时回退为 decision
|
||||
* @param options.silent - 为 true 时只更新状态与按钮,不追加本地聊天消息
|
||||
* @returns 是否成功提交决策
|
||||
*/
|
||||
const executeShippingDecision = async (
|
||||
decision: string,
|
||||
displayText?: string,
|
||||
options?: ExecuteShippingDecisionOptions,
|
||||
) => {
|
||||
const taskId = ctx.getActiveShippingTaskId();
|
||||
if (!taskId) {
|
||||
ctx.msg.warning(ctx.t('chat.shippingNoticeMissingTaskId'));
|
||||
@@ -76,27 +92,29 @@ export function createShippingDecisionHandlers(ctx: ShippingDecisionContext) {
|
||||
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);
|
||||
if (!options?.silent) {
|
||||
const userMsg: ChatMessage = {
|
||||
role: 'user',
|
||||
type: 'text',
|
||||
content: `${userText}\n任务编号:${taskId}`,
|
||||
local_id: ctx.newLocalMessageId('shipping-user'),
|
||||
local_only: true,
|
||||
};
|
||||
const assistantMsg: ChatMessage = {
|
||||
role: 'assistant',
|
||||
type: 'text',
|
||||
content: assistantContent,
|
||||
local_id: ctx.newLocalMessageId('shipping-assistant'),
|
||||
local_only: true,
|
||||
};
|
||||
ctx.messages.value.push(userMsg, assistantMsg);
|
||||
await ctx.saveLocalMessageToBackend(userMsg, userText);
|
||||
await ctx.saveLocalMessageToBackend(assistantMsg);
|
||||
await syncHistoryIfNeeded();
|
||||
}
|
||||
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);
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
/**
|
||||
* features/chat/shipping/useChatShippingMenuHandler.spec.ts
|
||||
* 用途:验证发货通知聊天菜单动作分流,避免 UI 按钮误走普通对话链路。
|
||||
* 依赖:vitest、vue refs、useChatShippingMenuHandler。
|
||||
* 逻辑:直接调用 createShippingMenuHandlers,覆盖 reparse_inventory 的 silent 决策提交、缺少 task 提示与上传器打开条件。
|
||||
*/
|
||||
import { ref } from 'vue';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { createShippingMenuHandlers, type ShippingMenuHandlerContext } from './useChatShippingMenuHandler';
|
||||
import type { ChatMessage } from '../types/chat.types';
|
||||
|
||||
const createContext = (
|
||||
overrides: Partial<ShippingMenuHandlerContext> = {},
|
||||
): ShippingMenuHandlerContext => ({
|
||||
isThinking: ref(false),
|
||||
getActiveShippingTaskId: () => 'SN-FOCUS-001',
|
||||
messages: ref([]),
|
||||
newLocalMessageId: vi.fn(() => 'local-id'),
|
||||
saveLocalMessageToBackend: vi.fn(async () => undefined),
|
||||
sendShippingMenuMessage: vi.fn(async () => undefined),
|
||||
openShippingInventoryMappingFormForTask: vi.fn(async () => true),
|
||||
openShippingInventoryPicker: vi.fn(() => true),
|
||||
openShippingNoticePicker: vi.fn(() => true),
|
||||
executeShippingDecision: vi.fn(async () => true),
|
||||
executeShippingManualUpload: vi.fn(async () => true),
|
||||
refreshShippingActions: vi.fn(async () => undefined),
|
||||
msg: {
|
||||
warning: vi.fn(),
|
||||
info: vi.fn(),
|
||||
},
|
||||
t: (key: string) => key,
|
||||
...overrides,
|
||||
});
|
||||
|
||||
describe('useChatShippingMenuHandler', () => {
|
||||
it('clears inventory state and opens picker for reparse_inventory without sending chat text', async () => {
|
||||
const ctx = createContext();
|
||||
const { handleShippingMenuAction } = createShippingMenuHandlers(ctx);
|
||||
const chatMsg = { role: 'assistant', content: '请重新上传库存' } as ChatMessage & { shipping_actions_used?: boolean };
|
||||
|
||||
await handleShippingMenuAction(
|
||||
{ id: 'reparse_inventory', message: '重新上传库存' },
|
||||
chatMsg,
|
||||
);
|
||||
|
||||
expect(chatMsg.shipping_actions_used).toBe(true);
|
||||
expect(ctx.executeShippingDecision).toHaveBeenCalledTimes(1);
|
||||
expect(ctx.executeShippingDecision).toHaveBeenCalledWith('reparse_inventory', '重新上传库存', { silent: true });
|
||||
expect(ctx.openShippingInventoryPicker).toHaveBeenCalledTimes(1);
|
||||
expect(ctx.sendShippingMenuMessage).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('keeps existing missing task warning when reparse_inventory has no active task', async () => {
|
||||
const ctx = createContext({
|
||||
getActiveShippingTaskId: () => '',
|
||||
});
|
||||
const { handleShippingMenuAction } = createShippingMenuHandlers(ctx);
|
||||
|
||||
await handleShippingMenuAction({ id: 'reparse_inventory', message: '重新上传库存' });
|
||||
|
||||
expect(ctx.msg.warning).toHaveBeenCalledWith('chat.shippingNoticeMissingTaskId');
|
||||
expect(ctx.executeShippingDecision).not.toHaveBeenCalled();
|
||||
expect(ctx.openShippingInventoryPicker).not.toHaveBeenCalled();
|
||||
expect(ctx.sendShippingMenuMessage).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('does not open picker when reparse_inventory decision fails', async () => {
|
||||
const ctx = createContext({
|
||||
executeShippingDecision: vi.fn(async () => false),
|
||||
});
|
||||
const { handleShippingMenuAction } = createShippingMenuHandlers(ctx);
|
||||
|
||||
await handleShippingMenuAction({ id: 'reparse_inventory', message: '重新上传库存' });
|
||||
|
||||
expect(ctx.executeShippingDecision).toHaveBeenCalledWith('reparse_inventory', '重新上传库存', { silent: true });
|
||||
expect(ctx.openShippingInventoryPicker).not.toHaveBeenCalled();
|
||||
expect(ctx.sendShippingMenuMessage).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('does not mark button used when reparse_inventory has no active task', async () => {
|
||||
const ctx = createContext({
|
||||
getActiveShippingTaskId: () => '',
|
||||
});
|
||||
const { handleShippingMenuAction } = createShippingMenuHandlers(ctx);
|
||||
const chatMsg = { role: 'assistant', content: '请重新上传库存' } as ChatMessage & { shipping_actions_used?: boolean };
|
||||
|
||||
await handleShippingMenuAction({ id: 'reparse_inventory', message: '重新上传库存' }, chatMsg);
|
||||
|
||||
expect(chatMsg.shipping_actions_used).toBeUndefined();
|
||||
expect(ctx.executeShippingDecision).not.toHaveBeenCalled();
|
||||
expect(ctx.openShippingInventoryPicker).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -29,7 +29,11 @@ export interface ShippingMenuHandlerContext {
|
||||
openShippingInventoryMappingFormForTask: (taskId: string) => Promise<boolean>;
|
||||
openShippingInventoryPicker: () => boolean;
|
||||
openShippingNoticePicker: () => boolean;
|
||||
executeShippingDecision: (decision: string, displayText?: string) => Promise<boolean>;
|
||||
executeShippingDecision: (
|
||||
decision: string,
|
||||
displayText?: string,
|
||||
options?: { silent?: boolean },
|
||||
) => Promise<boolean>;
|
||||
executeShippingManualUpload: (taskId: string, displayText?: string) => Promise<boolean>;
|
||||
refreshShippingActions: () => Promise<void>;
|
||||
msg: { warning: (text: string) => void; info: (text: string) => void };
|
||||
@@ -330,6 +334,18 @@ export function createShippingMenuHandlers(ctx: ShippingMenuHandlerContext) {
|
||||
ctx.msg.info(ctx.t('chat.shippingNoticePasteHint'));
|
||||
return;
|
||||
}
|
||||
if (action.id === 'reparse_inventory') {
|
||||
if (chatMsg?.shipping_actions_used) return;
|
||||
const taskId = ctx.getActiveShippingTaskId();
|
||||
if (!taskId) {
|
||||
ctx.msg.warning(ctx.t('chat.shippingNoticeMissingTaskId'));
|
||||
return;
|
||||
}
|
||||
if (chatMsg) chatMsg.shipping_actions_used = true;
|
||||
const ok = await ctx.executeShippingDecision('reparse_inventory', action.message, { silent: true });
|
||||
if (ok) ctx.openShippingInventoryPicker();
|
||||
return;
|
||||
}
|
||||
if (action.id && SHIPPING_DECISION_ACTIONS.has(action.id)) {
|
||||
if (chatMsg?.shipping_actions_used) return;
|
||||
if (chatMsg) chatMsg.shipping_actions_used = true;
|
||||
|
||||
@@ -1,13 +1,26 @@
|
||||
/**
|
||||
* useChatShippingRefresh.spec.ts
|
||||
* 用途:验证发货动作按钮刷新时的任务定位优先级,避免按 conversation 猜任务导致按钮绑错票。
|
||||
* 依赖:vitest、useChatShippingRefresh 纯函数导出。
|
||||
* 逻辑:只覆盖任务编号解析优先级,不触碰 Vue 组件或网络请求。
|
||||
* 用途:验证发货动作按钮刷新时的任务定位优先级与 focus 切换刷新保护。
|
||||
* 依赖:vitest、vue refs、useChatShippingRefresh 纯函数导出。
|
||||
* 逻辑:覆盖任务编号解析优先级,以及批次 focus 变化后应先锁定新 task 再拉取按钮。
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { resolvePreferredShippingTaskId } from './useChatShippingRefresh';
|
||||
import { computed, ref } from 'vue';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { createShippingActionsRefresher, resolvePreferredShippingTaskId } from './useChatShippingRefresh';
|
||||
|
||||
const { getWorkspaceShippingTaskUiState } = vi.hoisted(() => ({
|
||||
getWorkspaceShippingTaskUiState: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('@/features/chat/api/shipping.api', () => ({
|
||||
getWorkspaceShippingTaskUiState,
|
||||
}));
|
||||
|
||||
describe('useChatShippingRefresh', () => {
|
||||
beforeEach(() => {
|
||||
getWorkspaceShippingTaskUiState.mockReset();
|
||||
});
|
||||
|
||||
it('prefers current batch focus task over message and history fallbacks', () => {
|
||||
expect(resolvePreferredShippingTaskId({
|
||||
batchTaskId: 'sn-batch-001',
|
||||
@@ -27,4 +40,66 @@ describe('useChatShippingRefresh', () => {
|
||||
historyTaskId: '',
|
||||
})).toBe('');
|
||||
});
|
||||
|
||||
it('locks onto the latest focus task before refreshing chat buttons', async () => {
|
||||
getWorkspaceShippingTaskUiState.mockResolvedValue({
|
||||
task_no: 'SN-FOCUS-B',
|
||||
batch_no: 'SB-FOCUS-001',
|
||||
checkpoint: 'ready_export',
|
||||
process_status: 'matched',
|
||||
review_status: null,
|
||||
pending_human_reason: null,
|
||||
match_status: 'fulfillable',
|
||||
current_step: null,
|
||||
steps: [],
|
||||
summary: {
|
||||
title: '可生成发货文件',
|
||||
message: '库存匹配已满足发货条件,可以生成发货文件。',
|
||||
error_message: null,
|
||||
},
|
||||
action_buttons: [
|
||||
{
|
||||
id: 'generate_excel',
|
||||
label: '生成发货文件',
|
||||
message: '请生成发货文件',
|
||||
variant: 'primary',
|
||||
},
|
||||
],
|
||||
updated_at: '2026-07-01T10:00:00+08:00',
|
||||
});
|
||||
|
||||
const messages = ref([
|
||||
{
|
||||
role: 'assistant' as const,
|
||||
content: '请继续处理当前批次',
|
||||
shipping_actions: [
|
||||
{
|
||||
id: 'old-action',
|
||||
label: '旧动作',
|
||||
message: '旧动作',
|
||||
variant: 'secondary' as const,
|
||||
},
|
||||
],
|
||||
},
|
||||
]);
|
||||
const resolvedShippingTaskId = ref('SN-FOCUS-A');
|
||||
const { refreshShippingActions } = createShippingActionsRefresher({
|
||||
isShippingNoticeAgent: computed(() => true),
|
||||
messages,
|
||||
conversationId: ref('conv-focus-switch'),
|
||||
isThinking: ref(false),
|
||||
history: ref([]),
|
||||
resolvedShippingTaskId,
|
||||
shippingTaskIdFromQuery: computed(() => ''),
|
||||
getActiveBatchTaskId: () => 'SN-FOCUS-B',
|
||||
});
|
||||
|
||||
await refreshShippingActions();
|
||||
|
||||
expect(resolvedShippingTaskId.value).toBe('SN-FOCUS-B');
|
||||
expect(getWorkspaceShippingTaskUiState).toHaveBeenCalledTimes(1);
|
||||
expect(getWorkspaceShippingTaskUiState).toHaveBeenCalledWith('SN-FOCUS-B');
|
||||
expect(messages.value[0].shipping_ui_state?.task_no).toBe('SN-FOCUS-B');
|
||||
expect(messages.value[0].shipping_actions?.map((item) => item.id)).toEqual(['generate_excel']);
|
||||
});
|
||||
});
|
||||
@@ -1,17 +1,17 @@
|
||||
/**
|
||||
* features/chat/shipping/useChatShippingRefresh.ts
|
||||
* 用途:刷新聊天区发货通知动作按钮,把后端 checkpoint/action_buttons 同步到消息气泡。
|
||||
* 依赖:shipping.api、shippingMenu、shippingTaskId、shippingNoticeActions 常量、chat.types。
|
||||
* 逻辑:由 useChatShipping 调用本文件;本文件根据当前 taskId 拉取动作配置并回写到 messages[].shipping_actions。
|
||||
* 用途:刷新聊天区发货通知 UI State,把后端状态机 action_buttons 同步到消息气泡。
|
||||
* 依赖:shipping.api、shippingTaskId、shippingNoticeActions 常量、chat.types。
|
||||
* 逻辑:由 useChatShipping 调用本文件;本文件只读取后端 /ui-state,不再从 Dify 正文解析按钮。
|
||||
*/
|
||||
import { getShippingChatActions } from '@/features/chat/api/shipping.api';
|
||||
import { getWorkspaceShippingTaskUiState } 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 { stripShippingPlainActionMenu } from './shippingText';
|
||||
import type { ChatMessage, ChatSessionItem } from '../types/chat.types';
|
||||
import type { ShippingActionButton } from '../types/shipping.types';
|
||||
import type { ShippingTaskUiState } from '../types/shipping.api.types';
|
||||
import type { ComputedRef, Ref } from 'vue';
|
||||
|
||||
export interface ShippingRefreshContext {
|
||||
@@ -63,7 +63,7 @@ export function assistantMessageHasLaterUserReply(msgs: Array<{ role?: string }>
|
||||
/**
|
||||
* 创建发货通知动作按钮刷新器。
|
||||
*
|
||||
* 核心逻辑:优先按 taskId 拉取后端 action_buttons,失败时回退到消息文本指令解析,并在终态 checkpoint 清空旧按钮。
|
||||
* 核心逻辑:按 taskId 拉取后端 ui_state/action_buttons,并在终态 checkpoint 清空旧按钮。
|
||||
* @param ctx - 发货通知聊天上下文
|
||||
* @returns 动作刷新函数
|
||||
*/
|
||||
@@ -108,35 +108,34 @@ export function createShippingActionsRefresher(ctx: ShippingRefreshContext) {
|
||||
}
|
||||
const targetAssistantIndex = lastOpenAssistantIndex >= 0 ? lastOpenAssistantIndex : lastAssistantIndex;
|
||||
if (targetAssistantIndex >= 0) {
|
||||
const target = msgs[targetAssistantIndex] as ChatMessage & { shipping_actions?: ShippingActionButton[] };
|
||||
const resolved = resolveShippingActionButtons(String(target.content || ''), null);
|
||||
const cleanedText = stripShippingPlainActionMenu(resolved.cleanedText);
|
||||
const target = msgs[targetAssistantIndex] as ChatMessage;
|
||||
const cleanedText = stripShippingPlainActionMenu(String(target.content || ''));
|
||||
if (cleanedText !== String(target.content || '').trim()) {
|
||||
target.content = cleanedText;
|
||||
}
|
||||
}
|
||||
|
||||
let apiButtons: Array<{ id: string; label: string; message: string; variant?: string }> | null = null;
|
||||
let apiCheckpoint: string | null = null;
|
||||
let apiState: ShippingTaskUiState | null = null;
|
||||
let apiResolved = false;
|
||||
if (taskId) {
|
||||
const seq = ++shippingActionsRequestSeq;
|
||||
try {
|
||||
const data = await getShippingChatActions(taskId);
|
||||
const data = await getWorkspaceShippingTaskUiState(taskId);
|
||||
if (seq === shippingActionsRequestSeq) {
|
||||
apiResolved = true;
|
||||
apiCheckpoint = data.checkpoint ? String(data.checkpoint) : null;
|
||||
apiButtons = data.action_buttons?.length ? data.action_buttons : null;
|
||||
apiState = data;
|
||||
}
|
||||
} catch {
|
||||
// keep structured directive buttons if present
|
||||
// keep existing SSE-delivered ui_state if present
|
||||
}
|
||||
}
|
||||
const apiCheckpoint = apiState?.checkpoint ? String(apiState.checkpoint) : null;
|
||||
if (apiResolved && apiCheckpoint && SHIPPING_TERMINAL_CHECKPOINTS.has(apiCheckpoint)) {
|
||||
msgs.forEach((rawMsg) => {
|
||||
const m = rawMsg as ChatMessage & { shipping_actions?: unknown };
|
||||
const m = rawMsg as ChatMessage;
|
||||
if (m.role === 'assistant') {
|
||||
m.shipping_actions = undefined;
|
||||
m.shipping_ui_state = apiState || undefined;
|
||||
}
|
||||
});
|
||||
return;
|
||||
@@ -159,23 +158,16 @@ export function createShippingActionsRefresher(ctx: ShippingRefreshContext) {
|
||||
}
|
||||
let buttons: ShippingActionButton[] = [];
|
||||
if (index === targetAssistantIndex) {
|
||||
const resolved = resolveShippingActionButtons(
|
||||
String(chatMsg.content || ''),
|
||||
apiResolved ? (apiButtons ?? []) : null,
|
||||
{ apiResolved },
|
||||
);
|
||||
const cleanedText = stripShippingPlainActionMenu(resolved.cleanedText);
|
||||
if (resolved.fromDirective || cleanedText !== String(chatMsg.content || '').trim()) {
|
||||
const cleanedText = stripShippingPlainActionMenu(String(chatMsg.content || ''));
|
||||
if (cleanedText !== String(chatMsg.content || '').trim()) {
|
||||
chatMsg.content = cleanedText;
|
||||
}
|
||||
buttons = resolved.buttons;
|
||||
} else if (!apiResolved) {
|
||||
const resolved = resolveShippingActionButtons(String(chatMsg.content || ''), null);
|
||||
const cleanedText = stripShippingPlainActionMenu(resolved.cleanedText);
|
||||
if (resolved.fromDirective || cleanedText !== String(chatMsg.content || '').trim()) {
|
||||
chatMsg.content = cleanedText;
|
||||
if (apiState?.action_buttons?.length) {
|
||||
buttons = apiState.action_buttons;
|
||||
chatMsg.shipping_ui_state = apiState;
|
||||
} else if (!apiResolved && chatMsg.shipping_ui_state?.action_buttons?.length) {
|
||||
buttons = chatMsg.shipping_ui_state.action_buttons;
|
||||
}
|
||||
buttons = resolved.buttons;
|
||||
} else {
|
||||
chatMsg.content = stripShippingPlainActionMenu(String(chatMsg.content || ''));
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user