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
@@ -7,7 +7,7 @@
|
||||
import { BusinessError, requestJson } from '@/shared/api/client';
|
||||
import type {
|
||||
ShippingBatchSummary,
|
||||
ShippingChatActionsResponse,
|
||||
ShippingBatchUiState,
|
||||
ShippingConversationWorkspace,
|
||||
ShippingDecisionResponse,
|
||||
ShippingInventoryUploadResponse,
|
||||
@@ -17,6 +17,7 @@ import type {
|
||||
ShippingTaskCreateResponse,
|
||||
ShippingTaskDetail,
|
||||
ShippingTaskSummary,
|
||||
ShippingTaskUiState,
|
||||
} from '../types/shipping.api.types';
|
||||
|
||||
type ShippingApiStatusPayload = {
|
||||
@@ -75,10 +76,16 @@ export const listShippingChatAgents = () => requestJson<ShippingChatAgentOption[
|
||||
|
||||
/** 获取批次详情、批次任务列表与当前焦点任务。 */
|
||||
export const getWorkspaceShippingBatch = (batchNo: string) =>
|
||||
requestJson<ShippingBatchSummary & { tasks?: ShippingTaskSummary[]; focus_task?: ShippingTaskSummary | null }>(
|
||||
requestJson<ShippingBatchUiState>(
|
||||
`/api/workspace/shipping-batches/${encodeURIComponent(batchNo)}`,
|
||||
);
|
||||
|
||||
/** 获取批次级 UI State,供工作台、步骤条和任务卡片统一消费。 */
|
||||
export const getWorkspaceShippingBatchUiState = (batchNo: string) =>
|
||||
requestJson<ShippingBatchUiState>(
|
||||
`/api/workspace/shipping-batches/${encodeURIComponent(batchNo)}/ui-state`,
|
||||
);
|
||||
|
||||
/** 获取一个 Agent 会话下的多批次执行工作台快照。 */
|
||||
export const getWorkspaceShippingConversationBatches = (conversationId: string) =>
|
||||
requestJson<ShippingConversationWorkspace>(
|
||||
@@ -95,16 +102,14 @@ export const getWorkspaceShippingBatchFocusTask = (batchNo: string) =>
|
||||
export const getWorkspaceShippingTask = (taskNo: string) =>
|
||||
requestJson<ShippingTaskDetail>(`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}`);
|
||||
|
||||
/** 获取单票任务 UI State,后续 Chat 按钮与顶部步骤条统一读取此状态。 */
|
||||
export const getWorkspaceShippingTaskUiState = (taskNo: string) =>
|
||||
requestJson<ShippingTaskUiState>(`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/ui-state`);
|
||||
|
||||
/** 生成任务导出文件的前端下载 URL。 */
|
||||
export const workspaceShippingExportUrl = (taskNo: string) =>
|
||||
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/export`;
|
||||
|
||||
/** 获取聊天气泡动作按钮、检查点和 human options。 */
|
||||
export const getShippingChatActions = (taskNo: string) =>
|
||||
requestJson<ShippingChatActionsResponse>(
|
||||
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/chat-actions`,
|
||||
);
|
||||
|
||||
/**
|
||||
* 上传库存 Excel,并由后端完成解析与 schema preview 生成。
|
||||
* @param taskNo - 发货任务编号
|
||||
@@ -425,8 +430,8 @@ export const SHIPPING_NOTICE_AGENT_NAME = '货代发货通知 Agent';
|
||||
|
||||
export type {
|
||||
ShippingBatchSummary,
|
||||
ShippingBatchUiState,
|
||||
ShippingChatAction,
|
||||
ShippingChatActionsResponse,
|
||||
ShippingConversationBatch,
|
||||
ShippingConversationWorkspace,
|
||||
ShippingConversationWorkspaceSummary,
|
||||
@@ -440,4 +445,6 @@ export type {
|
||||
ShippingTaskCreateResponse,
|
||||
ShippingTaskDetail,
|
||||
ShippingTaskSummary,
|
||||
ShippingTaskUiState,
|
||||
ShippingWorkflowStep,
|
||||
} from '../types/shipping.api.types';
|
||||
@@ -10,7 +10,7 @@ import { AlertTriangle, List, RefreshCw } from 'lucide-vue-next';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { retryWorkspaceShippingBatchPending } from '@/features/chat/api/shipping.api';
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
import { buildShippingWorkflowSteps } from '@/features/chat/shipping';
|
||||
import { resolveShippingWorkflowSteps } from '@/features/chat/shipping';
|
||||
import type {
|
||||
ShippingBatchSummary,
|
||||
ShippingConversationWorkspace,
|
||||
@@ -102,7 +102,9 @@ const executionStateMeta = computed(() => {
|
||||
};
|
||||
});
|
||||
|
||||
const activeTaskSteps = computed(() => buildShippingWorkflowSteps(props.activeTaskDetail));
|
||||
const activeTaskSteps = computed(() => (
|
||||
resolveShippingWorkflowSteps(props.activeTaskDetail)
|
||||
));
|
||||
const activeStepIndex = computed(() => {
|
||||
const index = activeTaskSteps.value.findIndex((step) => step.status === 'current' || step.status === 'blocked');
|
||||
return index >= 0 ? index : Math.max(0, activeTaskSteps.value.length - 1);
|
||||
@@ -112,7 +114,7 @@ const activeStepLabel = computed(() => {
|
||||
return step ? t('chat.shippingNoticeUi.stepHeadline', {
|
||||
current: activeStepIndex.value + 1,
|
||||
total: activeTaskSteps.value.length,
|
||||
label: t(step.label),
|
||||
label: step.label.startsWith('chat.') ? t(step.label) : step.label,
|
||||
}) : '--';
|
||||
});
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
import { computed, ref } from 'vue';
|
||||
import { RefreshCw, Target, X } from 'lucide-vue-next';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { buildShippingWorkflowSteps, type ShippingWorkflowStepItem } from '@/features/chat/shipping';
|
||||
import { resolveShippingWorkflowSteps, type ShippingWorkflowStepItem } from '@/features/chat/shipping';
|
||||
import { hasShortageLines } from '@/features/chat/shipping/shippingShortageDetails';
|
||||
import type {
|
||||
ShippingBatchSummary,
|
||||
@@ -126,17 +126,21 @@ const resolveTaskStateMeta = (task: ShippingTaskSummary | ShippingTaskDetail) =>
|
||||
return { text: t('chat.shippingNoticeUi.runningState'), className: 'border-sky-100 bg-sky-50 text-brand-700' };
|
||||
};
|
||||
|
||||
const taskWorkflowSteps = (task: ShippingTaskSummary | ShippingTaskDetail) => (
|
||||
resolveShippingWorkflowSteps(task)
|
||||
);
|
||||
|
||||
const taskStepNumber = (task: ShippingTaskSummary | ShippingTaskDetail) =>
|
||||
resolveActiveStep(buildShippingWorkflowSteps(task)) + 1;
|
||||
resolveActiveStep(taskWorkflowSteps(task)) + 1;
|
||||
|
||||
const taskStepHeadline = (task: ShippingTaskSummary | ShippingTaskDetail) => {
|
||||
const steps = buildShippingWorkflowSteps(task);
|
||||
const steps = taskWorkflowSteps(task);
|
||||
const index = resolveActiveStep(steps);
|
||||
const step = steps[index];
|
||||
return step ? t('chat.shippingNoticeUi.stepHeadline', {
|
||||
current: index + 1,
|
||||
total: steps.length,
|
||||
label: t(step.label),
|
||||
label: step.label.startsWith('chat.') ? t(step.label) : step.label,
|
||||
}) : t('chat.shippingNoticeUi.stepFraction', { current: index + 1, total: steps.length });
|
||||
};
|
||||
|
||||
@@ -144,6 +148,13 @@ const currentStepProgress = (task: ShippingTaskSummary | ShippingTaskDetail) =>
|
||||
task.step_payload?.current_step_progress || null;
|
||||
|
||||
const resolveTaskDiagnosis = (task: ShippingTaskSummary | ShippingTaskDetail) => {
|
||||
const uiSummary = task.ui_state?.summary;
|
||||
if (uiSummary?.title || uiSummary?.message || uiSummary?.error_message) {
|
||||
return {
|
||||
title: uiSummary.error_message || uiSummary.title || t('chat.shippingNoticeUi.diagnosisStepWaitingTitle', { step: taskStepNumber(task) }),
|
||||
advice: uiSummary.message || t('chat.shippingNoticeUi.diagnosisStepWaitingAdvice'),
|
||||
};
|
||||
}
|
||||
const reason = String(task.pending_human_reason || '').trim();
|
||||
const reviewStatus = String(task.review_status || '').trim();
|
||||
const processStatus = String(task.process_status || '').trim();
|
||||
@@ -226,6 +237,9 @@ const resolveTaskDiagnosis = (task: ShippingTaskSummary | ShippingTaskDetail) =>
|
||||
};
|
||||
|
||||
const resolveSuggestedAction = (task: ShippingTaskSummary | ShippingTaskDetail) => {
|
||||
if (task.ui_state?.action_buttons?.length) {
|
||||
return task.ui_state.action_buttons.map((action) => action.label).join(' / ');
|
||||
}
|
||||
const reason = String(task.pending_human_reason || '').trim();
|
||||
const reviewStatus = String(task.review_status || '').trim();
|
||||
if (hasShortageLines(task) || reason === 'shortage' || reviewStatus === 'shortage_review') {
|
||||
@@ -246,7 +260,7 @@ const resolveSuggestedAction = (task: ShippingTaskSummary | ShippingTaskDetail)
|
||||
return t('chat.shippingNoticeUi.suggestContinue');
|
||||
};
|
||||
|
||||
const resolveActiveStep = (steps: ShippingWorkflowStepItem[]) => {
|
||||
const resolveActiveStep = (steps: Array<ShippingWorkflowStepItem | { status: string }>) => {
|
||||
const activeIndex = steps.findIndex((step) => step.status === 'current' || step.status === 'blocked');
|
||||
return activeIndex >= 0 ? activeIndex : Math.max(0, steps.length - 1);
|
||||
};
|
||||
@@ -413,7 +427,7 @@ const handleSwitchBatch = (batchNo: string) => {
|
||||
|
||||
<div class="my-3">
|
||||
<div class="scheme-stepper">
|
||||
<template v-for="(step, index) in buildShippingWorkflowSteps(task)" :key="step.id">
|
||||
<template v-for="(step, index) in taskWorkflowSteps(task)" :key="step.id">
|
||||
<div
|
||||
class="scheme-step-node"
|
||||
:class="{
|
||||
@@ -428,7 +442,7 @@ const handleSwitchBatch = (batchNo: string) => {
|
||||
<span v-else-if="step.status === 'blocked'">!</span>
|
||||
<span v-else>{{ index + 1 }}</span>
|
||||
</div>
|
||||
<div class="scheme-step-label">{{ t(step.label) }}</div>
|
||||
<div class="scheme-step-label">{{ step.label.startsWith('chat.') ? t(step.label) : step.label }}</div>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
|
||||
@@ -13,7 +13,8 @@ defineProps<{
|
||||
compact?: boolean;
|
||||
}>();
|
||||
|
||||
const { t } = useI18n();
|
||||
const { t, te } = useI18n();
|
||||
const displayLabel = (label: string) => (te(label) ? t(label) : label);
|
||||
const stepClass = (status: ShippingWorkflowStepItem['status']) => {
|
||||
if (status === 'completed') return 'border-emerald-200 bg-emerald-50 text-emerald-700';
|
||||
if (status === 'current') return 'border-brand-300 bg-brand-50 text-brand-700';
|
||||
@@ -43,7 +44,7 @@ const dotClass = (status: ShippingWorkflowStepItem['status']) => {
|
||||
<span class="inline-flex h-5 min-w-5 items-center justify-center rounded-full text-[11px] font-semibold text-white" :class="dotClass(step.status)">
|
||||
{{ index + 1 }}
|
||||
</span>
|
||||
<span class="text-xs font-semibold">{{ t(step.label) }}</span>
|
||||
<span class="text-xs font-semibold">{{ displayLabel(step.label) }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -192,26 +192,38 @@ const downloadExcel = async () => {
|
||||
<span>开始:{{ formatTime(run.started_at) }} · 完成:{{ formatTime(run.finished_at) }}</span>
|
||||
</div>
|
||||
|
||||
<div class="grid grid-cols-2 gap-2 md:grid-cols-5">
|
||||
<div class="rounded-xl bg-white/80 px-3 py-2">
|
||||
<div class="text-xs text-slate-500">总数</div>
|
||||
<div class="text-lg font-bold text-slate-800">{{ run.total_count }}</div>
|
||||
<div class="grid grid-cols-2 gap-1.5 sm:grid-cols-4 lg:grid-cols-8">
|
||||
<div class="rounded-lg bg-white/80 px-2 py-1.5">
|
||||
<div class="whitespace-nowrap text-xs text-slate-500">总数</div>
|
||||
<div class="text-base font-bold text-slate-800">{{ run.total_count }}</div>
|
||||
</div>
|
||||
<div class="rounded-xl bg-white/80 px-3 py-2">
|
||||
<div class="text-xs text-slate-500">已处理</div>
|
||||
<div class="text-lg font-bold text-sky-700">{{ run.processed_count }}</div>
|
||||
<div class="rounded-lg bg-white/80 px-2 py-1.5">
|
||||
<div class="whitespace-nowrap text-xs text-slate-500">已处理</div>
|
||||
<div class="text-base font-bold text-sky-700">{{ run.processed_count }}</div>
|
||||
</div>
|
||||
<div class="rounded-xl bg-white/80 px-3 py-2">
|
||||
<div class="text-xs text-slate-500">成功</div>
|
||||
<div class="text-lg font-bold text-emerald-700">{{ run.success_count }}</div>
|
||||
<div class="rounded-lg bg-white/80 px-2 py-1.5">
|
||||
<div class="whitespace-nowrap text-xs text-slate-500">成功</div>
|
||||
<div class="text-base font-bold text-emerald-700">{{ run.success_count }}</div>
|
||||
</div>
|
||||
<div class="rounded-xl bg-white/80 px-3 py-2">
|
||||
<div class="text-xs text-slate-500">失败</div>
|
||||
<div class="text-lg font-bold text-rose-700">{{ run.failed_count }}</div>
|
||||
<div class="rounded-lg bg-white/80 px-2 py-1.5">
|
||||
<div class="whitespace-nowrap text-xs text-slate-500">失败</div>
|
||||
<div class="text-base font-bold text-rose-700">{{ run.failed_count }}</div>
|
||||
</div>
|
||||
<div class="rounded-xl bg-white/80 px-3 py-2">
|
||||
<div class="text-xs text-slate-500">跳过</div>
|
||||
<div class="text-lg font-bold text-amber-700">{{ run.skipped_count }}</div>
|
||||
<div class="rounded-lg bg-white/80 px-2 py-1.5">
|
||||
<div class="whitespace-nowrap text-xs text-slate-500">跳过</div>
|
||||
<div class="text-base font-bold text-amber-700">{{ run.skipped_count }}</div>
|
||||
</div>
|
||||
<div class="rounded-lg bg-white/80 px-2 py-1.5">
|
||||
<div class="whitespace-nowrap text-xs text-slate-500">合格笔数</div>
|
||||
<div class="text-base font-bold text-emerald-700">{{ run.judgement?.qualified_count ?? 0 }}</div>
|
||||
</div>
|
||||
<div class="rounded-lg bg-white/80 px-2 py-1.5">
|
||||
<div class="whitespace-nowrap text-xs text-slate-500">不合格笔数</div>
|
||||
<div class="text-base font-bold text-rose-700">{{ run.judgement?.unqualified_count ?? 0 }}</div>
|
||||
</div>
|
||||
<div class="rounded-lg bg-white/80 px-2 py-1.5">
|
||||
<div class="whitespace-nowrap text-xs text-slate-500">人工判定笔数</div>
|
||||
<div class="text-base font-bold text-amber-700">{{ run.judgement?.manual_count ?? 0 }}</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
/**
|
||||
* features/chat/composables/useChat.spec.ts
|
||||
* 用途:验证聊天流对发货通知 UI State SSE 事件的消息级回写行为。
|
||||
* 依赖:vitest、useChat 导出的纯函数、chat.types。
|
||||
* 逻辑:覆盖 batch_ui_state 到 focus_task_ui_state 的投影、focus 切换时按钮跟随更新,以及已消费按钮消息的防回挂保护。
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { applyShippingUiStateToMessage } from './useChat';
|
||||
import type { ChatMessage } from '../types/chat.types';
|
||||
|
||||
const buildBatchUiStateEvent = (
|
||||
taskNo: string,
|
||||
batchNo: string,
|
||||
actionId: string,
|
||||
checkpoint = 'ready_export',
|
||||
) => ({
|
||||
event: 'shipping_ui_state',
|
||||
batch_no: batchNo,
|
||||
batch_ui_state: {
|
||||
batch_no: batchNo,
|
||||
current_focus_task_no: taskNo,
|
||||
tasks: [],
|
||||
focus_task_ui_state: {
|
||||
task_no: taskNo,
|
||||
batch_no: batchNo,
|
||||
checkpoint,
|
||||
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: actionId,
|
||||
label: `动作-${actionId}`,
|
||||
message: `执行 ${actionId}`,
|
||||
variant: 'primary' as const,
|
||||
},
|
||||
],
|
||||
updated_at: '2026-07-01T10:00:00+08:00',
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
describe('useChat shipping_ui_state SSE', () => {
|
||||
it('hydrates focus task ui state from batch payload and does not reattach used actions', () => {
|
||||
const message: ChatMessage = {
|
||||
role: 'assistant',
|
||||
content: '当前正在处理批次任务',
|
||||
type: 'shipping-match-result',
|
||||
payload: { action_buttons: [] },
|
||||
};
|
||||
|
||||
const batchEvent = buildBatchUiStateEvent('SN-UNIT-001', 'SB-UNIT-001', 'generate_excel');
|
||||
|
||||
applyShippingUiStateToMessage(message, batchEvent);
|
||||
|
||||
expect(message.shipping_ui_state?.task_no).toBe('SN-UNIT-001');
|
||||
expect(message.shipping_actions?.map((item) => item.id)).toEqual(['generate_excel']);
|
||||
expect((message.payload as { action_buttons?: unknown[] }).action_buttons).toHaveLength(1);
|
||||
expect((message.payload as { shipping_batch_ui_state?: { batch_no?: string } }).shipping_batch_ui_state?.batch_no).toBe('SB-UNIT-001');
|
||||
|
||||
message.shipping_actions_used = true;
|
||||
message.shipping_actions = undefined;
|
||||
(message.payload as { action_buttons?: unknown[] }).action_buttons = [];
|
||||
|
||||
applyShippingUiStateToMessage(message, batchEvent);
|
||||
|
||||
expect(message.shipping_ui_state?.checkpoint).toBe('ready_export');
|
||||
expect(message.shipping_actions).toBeUndefined();
|
||||
expect((message.payload as { action_buttons?: unknown[] }).action_buttons).toEqual([]);
|
||||
});
|
||||
|
||||
it('switches buttons when batch focus task changes from A to B', () => {
|
||||
const message: ChatMessage = {
|
||||
role: 'assistant',
|
||||
content: '请继续处理当前批次',
|
||||
payload: { action_buttons: [] },
|
||||
};
|
||||
|
||||
applyShippingUiStateToMessage(message, buildBatchUiStateEvent('SN-FOCUS-A', 'SB-FOCUS-001', 'generate_excel'));
|
||||
|
||||
expect(message.shipping_ui_state?.task_no).toBe('SN-FOCUS-A');
|
||||
expect(message.shipping_actions?.map((item) => item.id)).toEqual(['generate_excel']);
|
||||
|
||||
applyShippingUiStateToMessage(message, buildBatchUiStateEvent('SN-FOCUS-B', 'SB-FOCUS-001', 'retry_upload'));
|
||||
|
||||
expect(message.shipping_ui_state?.task_no).toBe('SN-FOCUS-B');
|
||||
expect(message.shipping_actions?.map((item) => item.id)).toEqual(['retry_upload']);
|
||||
expect((message.payload as { shipping_batch_ui_state?: { current_focus_task_no?: string } }).shipping_batch_ui_state?.current_focus_task_no)
|
||||
.toBe('SN-FOCUS-B');
|
||||
});
|
||||
});
|
||||
@@ -7,6 +7,7 @@ import { useI18n } from 'vue-i18n';
|
||||
import { getAuthHeaders } from '@/shared/utils/auth';
|
||||
import { applyStreamErrorToMessage, type StreamErrorLabels } from '../utils/streamErrorMessage';
|
||||
import type { ChatMessage, ChatRun, RetrieverResource } from '../types/chat.types';
|
||||
import type { ShippingBatchUiState, ShippingTaskUiState } from '../types/shipping.api.types';
|
||||
|
||||
export interface SendMessageLifecycleHooks {
|
||||
onAssistantMessageFinished?: (message: ChatMessage, runMessages: ChatMessage[]) => void | Promise<void>;
|
||||
@@ -77,6 +78,63 @@ const addAttributionParts = (msg: ChatMessage, value: unknown) => {
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 解析发货通知 SSE 事件中的统一 UI State 载荷。
|
||||
*
|
||||
* 核心逻辑:优先读取单票 `ui_state`,批次事件则下钻 `batch_ui_state.focus_task_ui_state`;
|
||||
* 同时保留批次态原文,供右侧工作台和后续兼容逻辑继续消费。
|
||||
* @param data - SSE 事件 JSON
|
||||
* @returns 提炼后的单票 UI State 与原始批次 UI State
|
||||
*/
|
||||
export const resolveShippingUiStatePayload = (data: Record<string, unknown>): {
|
||||
uiState?: ShippingTaskUiState;
|
||||
batchUiState?: ShippingBatchUiState;
|
||||
} => {
|
||||
const rawUiState = data.ui_state;
|
||||
const uiState = rawUiState && typeof rawUiState === 'object'
|
||||
? rawUiState as ShippingTaskUiState
|
||||
: undefined;
|
||||
const rawBatchUiState = data.batch_ui_state;
|
||||
const batchUiState = rawBatchUiState && typeof rawBatchUiState === 'object'
|
||||
? rawBatchUiState as ShippingBatchUiState
|
||||
: undefined;
|
||||
const focusTaskUiState = batchUiState?.focus_task_ui_state && typeof batchUiState.focus_task_ui_state === 'object'
|
||||
? batchUiState.focus_task_ui_state
|
||||
: undefined;
|
||||
return {
|
||||
uiState: uiState || focusTaskUiState,
|
||||
batchUiState,
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* 将发货通知状态机事件同步到当前助手消息。
|
||||
*
|
||||
* 说明:shipping_ui_state 是 HXOPS 自有 SSE 事件,不依赖 Dify 正文;收到后立即挂按钮,
|
||||
* 让用户无需等待 `message_end` 才拿到状态机结果。若该消息按钮已被消费,则只更新状态快照,
|
||||
* 不重新挂出可点击按钮,避免首帧旧状态覆盖。
|
||||
*/
|
||||
export const applyShippingUiStateToMessage = (msg: ChatMessage, data: Record<string, unknown>) => {
|
||||
const { uiState, batchUiState } = resolveShippingUiStatePayload(data);
|
||||
if (!uiState) return;
|
||||
const nextActions = Array.isArray(uiState.action_buttons) && uiState.action_buttons.length
|
||||
? uiState.action_buttons
|
||||
: undefined;
|
||||
|
||||
msg.shipping_ui_state = uiState;
|
||||
if (!msg.shipping_actions_used) {
|
||||
msg.shipping_actions = nextActions;
|
||||
}
|
||||
if (msg.type === 'shipping-match-result' && msg.payload && typeof msg.payload === 'object' && !msg.shipping_actions_used) {
|
||||
(msg.payload as { action_buttons?: ChatMessage['shipping_actions'] }).action_buttons = nextActions;
|
||||
}
|
||||
msg.payload = {
|
||||
...(msg.payload && typeof msg.payload === 'object' ? msg.payload as Record<string, unknown> : {}),
|
||||
shipping_ui_state: uiState,
|
||||
...(batchUiState ? { shipping_batch_ui_state: batchUiState } : {}),
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* 把 SSE 事件附带的元数据同步到当前消息对象。
|
||||
*
|
||||
@@ -360,9 +418,6 @@ export function useChat() {
|
||||
while (true) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
if (ignoreFurtherStreamEvents) {
|
||||
continue;
|
||||
}
|
||||
clearLikelyCompletedStreamTimer();
|
||||
|
||||
buffer += decoder.decode(value, { stream: true });
|
||||
@@ -400,7 +455,14 @@ export function useChat() {
|
||||
}
|
||||
|
||||
const eventName = String(data.event || '');
|
||||
if (eventName === 'message' || eventName === 'agent_message') {
|
||||
if (ignoreFurtherStreamEvents && eventName !== 'shipping_ui_state') {
|
||||
continue;
|
||||
}
|
||||
if (eventName === 'shipping_ui_state') {
|
||||
const botMsg = ensureBotMessage();
|
||||
if (!botMsg) continue;
|
||||
applyShippingUiStateToMessage(botMsg, data);
|
||||
} else if (eventName === 'message' || eventName === 'agent_message') {
|
||||
if (typeof data.answer === 'string' && data.answer.length > 0) {
|
||||
const botMsg = ensureBotMessage();
|
||||
if (!botMsg) continue;
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
/**
|
||||
* features/chat/composables/useChatShipping.spec.ts
|
||||
* 用途:验证发货批次切换后的默认焦点解析,避免右侧工作台沿用旧批次的 focused task。
|
||||
* 依赖:vitest、useChatShipping 纯函数导出。
|
||||
* 逻辑:覆盖 current focus、process summary 回退、首票回退与无任务时清空焦点原因四种路径。
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { resolveShippingBatchFocusState } from './useChatShipping';
|
||||
|
||||
describe('useChatShipping batch focus sync', () => {
|
||||
it('prefers batch current focus task and keeps default reason', () => {
|
||||
expect(resolveShippingBatchFocusState(
|
||||
{
|
||||
current_focus_task_no: 'SN-BATCH-B2',
|
||||
process_summary: { current_task_no: 'SN-BATCH-B1' },
|
||||
},
|
||||
[{ task_no: 'SN-BATCH-B0' }],
|
||||
'当前聚焦任务',
|
||||
)).toEqual({
|
||||
taskNo: 'SN-BATCH-B2',
|
||||
focusReason: '当前聚焦任务',
|
||||
});
|
||||
});
|
||||
|
||||
it('falls back to process summary and first task when current focus is absent', () => {
|
||||
expect(resolveShippingBatchFocusState(
|
||||
{
|
||||
current_focus_task_no: '',
|
||||
process_summary: { current_task_no: 'SN-BATCH-C1' },
|
||||
},
|
||||
[{ task_no: 'SN-BATCH-C0' }],
|
||||
'当前聚焦任务',
|
||||
)).toEqual({
|
||||
taskNo: 'SN-BATCH-C1',
|
||||
focusReason: '当前聚焦任务',
|
||||
});
|
||||
|
||||
expect(resolveShippingBatchFocusState(
|
||||
{
|
||||
current_focus_task_no: '',
|
||||
process_summary: { current_task_no: '' },
|
||||
},
|
||||
[{ task_no: 'SN-BATCH-D0' }],
|
||||
'当前聚焦任务',
|
||||
)).toEqual({
|
||||
taskNo: 'SN-BATCH-D0',
|
||||
focusReason: '当前聚焦任务',
|
||||
});
|
||||
});
|
||||
|
||||
it('clears focus state when the new batch has no resolvable task', () => {
|
||||
expect(resolveShippingBatchFocusState(
|
||||
{
|
||||
current_focus_task_no: '',
|
||||
process_summary: { current_task_no: '' },
|
||||
},
|
||||
[],
|
||||
'当前聚焦任务',
|
||||
)).toEqual({
|
||||
taskNo: '',
|
||||
focusReason: '',
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -25,7 +25,6 @@ import {
|
||||
createShippingParseReviewHandlers,
|
||||
createShippingSendHandlers,
|
||||
createShippingUploadHandlers,
|
||||
extractShippingActionsDirective,
|
||||
findHistorySessionForShippingTask,
|
||||
findLatestShippingTaskId,
|
||||
getShippingInventoryMappingPayload,
|
||||
@@ -42,6 +41,7 @@ import {
|
||||
getWorkspaceShippingBatch,
|
||||
getWorkspaceShippingTask,
|
||||
switchWorkspaceShippingBatchFocusTask,
|
||||
type ShippingBatchUiState,
|
||||
type ShippingBatchSummary,
|
||||
type ShippingConversationWorkspace,
|
||||
type ShippingTaskDetail,
|
||||
@@ -90,6 +90,34 @@ export interface UseChatShippingOptions {
|
||||
createNewChatView: () => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析批次切换后的默认焦点状态。
|
||||
* 核心逻辑:优先取状态机记录的 current focus,其次回退到 process summary 当前任务,再回退到任务列表首票;只有拿到 task_no 才回填默认聚焦原因。
|
||||
* @param batchSummary - 当前批次摘要
|
||||
* @param batchTasks - 当前批次任务列表
|
||||
* @param defaultReason - 批次切换后写入输入栏提示的默认焦点原因
|
||||
* @returns 供步骤条、按钮与右侧工作台共用的 focus 状态;取不到 task 时返回空焦点
|
||||
*/
|
||||
export const resolveShippingBatchFocusState = (
|
||||
batchSummary: {
|
||||
current_focus_task_no?: string | null;
|
||||
process_summary?: { current_task_no?: string | null } | null;
|
||||
} | null | undefined,
|
||||
batchTasks: Array<{ task_no?: string | null }> | null | undefined,
|
||||
defaultReason: string,
|
||||
) => {
|
||||
const taskNo = String(
|
||||
batchSummary?.current_focus_task_no
|
||||
|| batchSummary?.process_summary?.current_task_no
|
||||
|| batchTasks?.[0]?.task_no
|
||||
|| '',
|
||||
).trim();
|
||||
return {
|
||||
taskNo,
|
||||
focusReason: taskNo ? defaultReason : '',
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* 组装发货通知聊天所需的状态、动作处理器与发送拦截逻辑。
|
||||
*
|
||||
@@ -142,8 +170,7 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
const shippingInventorySelectionTaskId = ref('');
|
||||
|
||||
const prepareMarkdownDisplayText = (text: string) => {
|
||||
const stripped = isShippingNoticeAgent.value ? extractShippingActionsDirective(text).cleanedText : text;
|
||||
return sanitizeShippingConversationText(stripReasoningPrelude(stripped), isShippingNoticeAgent.value);
|
||||
return sanitizeShippingConversationText(stripReasoningPrelude(text), isShippingNoticeAgent.value);
|
||||
};
|
||||
|
||||
// ── 任务编号状态 ──────────────────────────────────────────
|
||||
@@ -172,7 +199,7 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
let shippingStatusPollTimer: ReturnType<typeof setInterval> | null = null;
|
||||
|
||||
const applyShippingBatchDetail = (
|
||||
detail: ShippingBatchSummary & { tasks?: ShippingTaskSummary[]; focus_task?: ShippingTaskSummary | null },
|
||||
detail: ShippingBatchUiState,
|
||||
fallbackBatchNo: string,
|
||||
) => {
|
||||
const normalizedBatchNo = detail.batch_no || fallbackBatchNo;
|
||||
@@ -200,6 +227,15 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
if (preferredTaskNo) {
|
||||
resolvedShippingTaskId.value = preferredTaskNo;
|
||||
}
|
||||
if (detail.focus_task && detail.focus_task_ui_state) {
|
||||
activeShippingTaskDetail.value = {
|
||||
...(activeShippingTaskDetail.value || {}),
|
||||
...detail.focus_task,
|
||||
lines: activeShippingTaskDetail.value?.lines || [],
|
||||
events: activeShippingTaskDetail.value?.events || [],
|
||||
ui_state: detail.focus_task_ui_state,
|
||||
} as ShippingTaskDetail;
|
||||
}
|
||||
};
|
||||
|
||||
const syncShippingBatchSummary = async (batchNo: string) => {
|
||||
@@ -282,12 +318,14 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
} else {
|
||||
await syncShippingBatchSummary(normalizedBatchNo);
|
||||
}
|
||||
const nextTaskNo = String(
|
||||
shippingBatchSummary.value?.current_focus_task_no
|
||||
|| shippingBatchSummary.value?.process_summary?.current_task_no
|
||||
|| shippingBatchTasks.value[0]?.task_no
|
||||
|| '',
|
||||
).trim();
|
||||
const nextFocusState = resolveShippingBatchFocusState(
|
||||
shippingBatchSummary.value,
|
||||
shippingBatchTasks.value,
|
||||
t('chat.shippingNoticeUi.currentFocusDefaultReason'),
|
||||
);
|
||||
const nextTaskNo = nextFocusState.taskNo;
|
||||
focusedShippingTaskNo.value = nextFocusState.taskNo;
|
||||
shippingFocusReason.value = nextFocusState.focusReason;
|
||||
if (nextTaskNo) {
|
||||
resolvedShippingTaskId.value = nextTaskNo;
|
||||
await syncActiveShippingTaskDetail(nextTaskNo);
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
/**
|
||||
/**
|
||||
* 对话页:当前登录用户展示名、工号与登出/管理入口。
|
||||
*/
|
||||
import { computed, ref } from 'vue';
|
||||
@@ -33,7 +33,7 @@ export function useChatPageUser(router: Router) {
|
||||
const handleLogout = () => {
|
||||
logoutAuth();
|
||||
onAuthLogout();
|
||||
router.push('/');
|
||||
router.push('/login');
|
||||
};
|
||||
|
||||
const goToAdmin = () => {
|
||||
|
||||
@@ -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 || ''));
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
* 逻辑:作为 features/chat 域的类型中枢,向上提供页面编排约束,向下约束消息渲染与交互结构。
|
||||
*/
|
||||
import type { LeaveAgentOption } from './leave.types';
|
||||
import type { ShippingTaskUiState } from './shipping.api.types';
|
||||
|
||||
export type { LeaveAgentOption };
|
||||
|
||||
@@ -35,7 +36,9 @@ export interface ChatMessage {
|
||||
label: string;
|
||||
message: string;
|
||||
variant?: 'primary' | 'secondary' | 'danger';
|
||||
source_code?: string;
|
||||
}>;
|
||||
shipping_ui_state?: ShippingTaskUiState;
|
||||
shipping_actions_used?: boolean;
|
||||
/** 流式对话是否因网络/上游中断而附带错误提示 */
|
||||
stream_error?: boolean;
|
||||
|
||||
@@ -35,6 +35,7 @@ export interface ShippingTaskSummary {
|
||||
inventory_source_resolution?: Record<string, unknown> | null;
|
||||
created_at?: string | null;
|
||||
updated_at?: string | null;
|
||||
ui_state?: ShippingTaskUiState;
|
||||
}
|
||||
|
||||
export interface ShippingTaskEvent {
|
||||
@@ -99,6 +100,7 @@ export interface ShippingTaskDetail extends ShippingTaskSummary {
|
||||
parse_confidence?: number | null;
|
||||
error_message?: string | null;
|
||||
events: ShippingTaskEvent[];
|
||||
ui_state?: ShippingTaskUiState;
|
||||
}
|
||||
|
||||
export interface ShippingChatAction {
|
||||
@@ -109,13 +111,30 @@ export interface ShippingChatAction {
|
||||
source_code?: string;
|
||||
}
|
||||
|
||||
export interface ShippingChatActionsResponse {
|
||||
export interface ShippingWorkflowStep {
|
||||
id: string;
|
||||
code: string;
|
||||
label: string;
|
||||
status: 'completed' | 'current' | 'pending' | 'blocked' | string;
|
||||
}
|
||||
|
||||
export interface ShippingTaskUiState {
|
||||
task_no: string;
|
||||
batch_no?: string | null;
|
||||
checkpoint?: string | null;
|
||||
process_status: string;
|
||||
review_status?: string | null;
|
||||
pending_human_reason?: string | null;
|
||||
match_status?: string | null;
|
||||
current_step?: ShippingWorkflowStep | null;
|
||||
steps: ShippingWorkflowStep[];
|
||||
summary: {
|
||||
title?: string | null;
|
||||
message?: string | null;
|
||||
error_message?: string | null;
|
||||
};
|
||||
action_buttons: ShippingChatAction[];
|
||||
updated_at?: string | null;
|
||||
}
|
||||
|
||||
export interface ShippingBatchSummary {
|
||||
@@ -137,6 +156,12 @@ export interface ShippingBatchSummary {
|
||||
updated_at?: string | null;
|
||||
}
|
||||
|
||||
export interface ShippingBatchUiState extends ShippingBatchSummary {
|
||||
focus_task?: ShippingTaskSummary | null;
|
||||
focus_task_ui_state?: ShippingTaskUiState | null;
|
||||
tasks: ShippingTaskSummary[];
|
||||
}
|
||||
|
||||
export interface ShippingConversationWorkspaceSummary {
|
||||
batch_count: number;
|
||||
total: number;
|
||||
|
||||
@@ -23,7 +23,7 @@ import {
|
||||
type ShippingTaskSummary,
|
||||
} from '@/features/chat/api/shipping.api';
|
||||
import { getAuthHeaders } from '@/shared/utils/auth';
|
||||
import { buildShippingWorkflowSteps } from '@/features/chat/shipping';
|
||||
import { resolveShippingWorkflowSteps } from '@/features/chat/shipping';
|
||||
|
||||
const props = defineProps<{
|
||||
embedded?: boolean;
|
||||
@@ -108,7 +108,9 @@ const eventLabel = (eventType: string) => {
|
||||
return te(key) ? t(key) : t('workspace.shippingNotice.eventTypes.system');
|
||||
};
|
||||
|
||||
const detailWorkflowSteps = computed(() => buildShippingWorkflowSteps(detail.value));
|
||||
const detailWorkflowSteps = computed(() => (
|
||||
resolveShippingWorkflowSteps(detail.value)
|
||||
));
|
||||
const detailStepProgress = computed<ShippingCurrentStepProgress | null>(() => {
|
||||
const payload = detail.value?.step_payload;
|
||||
if (!payload || typeof payload !== 'object') return null;
|
||||
|
||||
Reference in new issue
Block a user