feat(shipping-notice): 新增货代客户管理功能,支持客户导入、识别证据管理与客户确认

This commit is contained in:
hugo committed 2026-07-16 08:16:19 +08:00
1 parent b595e157e9
commit 4fbaed2b4c
176 files changed
+14011 -994

No files matched your search

@@ -0,0 +1,87 @@
/**
* features/chat/api/chat.api.spec.ts
* 用途:验证聊天历史接口适配层不会在 hydrate 过程中丢失用户附件快照。
* 依赖:Vitest、mock 后的 shared/api/client 与 auth、chat.api。
* 逻辑:覆盖历史消息过滤 shipping-parse-review、恢复订单识别状态时仍保留 attachments。
*/
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { listChatMessages } from './chat.api';
vi.mock('@/shared/utils/auth', () => ({
getAuthHeaders: vi.fn(() => ({ Authorization: 'Bearer test-token' })),
}));
vi.mock('@/shared/api/client', () => ({
requestJson: vi.fn(),
}));
import { requestJson } from '@/shared/api/client';
const requestJsonMock = vi.mocked(requestJson);
describe('chat.api history hydration', () => {
beforeEach(() => {
requestJsonMock.mockReset();
});
it('keeps user attachment snapshots while hydrating persisted assistant payload', async () => {
requestJsonMock.mockResolvedValue([
{
role: 'user',
content: '',
attachments: [{
id: 'attachment-only-1',
name: 'notice.eml',
type: 'document',
source: 'shipping_notice',
}],
},
{
role: 'assistant',
content: '中间态消息',
type: 'shipping-parse-review',
},
{
role: 'assistant',
content: '订单识别完成',
payload: {
shipping_order_extraction_state: {
status: 'completed',
phase: 'result_persisted',
message: '已创建 1 个任务',
created_count: 1,
opened_existing_count: 0,
pending_count: 0,
non_shipping_count: 0,
created_with_missing_fields_count: 0,
batch_no: 'SB-HISTORY-001',
terminal: true,
},
},
},
]);
const messages = await listChatMessages('conv-history-1', 24);
expect(requestJsonMock).toHaveBeenCalledWith(
'/api/chat/messages?conversation_id=conv-history-1&agent_id=24',
{ headers: { Authorization: 'Bearer test-token' } },
);
expect(messages).toHaveLength(2);
expect(messages[0]).toEqual({
role: 'user',
content: '',
attachments: [{
id: 'attachment-only-1',
name: 'notice.eml',
type: 'document',
source: 'shipping_notice',
}],
});
expect(messages[1]?.shipping_order_extraction_state).toMatchObject({
status: 'completed',
batch_no: 'SB-HISTORY-001',
terminal: true,
});
});
});
+25 -2
View File
@@ -1,6 +1,8 @@
/**
* features/chat/api/chat.api.ts
* 聊天域 HTTP API:会话、消息、源文件、附件上传。
* 用途:封装聊天会话、消息、源文件与附件上传 HTTP API,并恢复结构化历史消息状态。
* 依赖:shared/api/client、鉴权工具、chat.types。
* 逻辑:页面 composable 调用本模块;历史消息响应在返回前将 ChatLog.payload 中的领域状态投影到 ChatMessage。
*/
import { getAuthHeaders } from '@/shared/utils/auth';
import { requestJson } from '@/shared/api/client';
@@ -14,6 +16,7 @@ import type {
ChatSourceFileResult,
ChatUploadResult,
OaEmployeesResponse,
ShippingOrderExtractionState,
} from '../types/chat.types';
const auth = () => ({ headers: getAuthHeaders() });
@@ -28,10 +31,30 @@ export const deleteAllChatSessions = (agentId: number) =>
export const deleteChatSession = (conversationId: string, agentId: number) =>
requestJson(`/api/chat/sessions/${conversationId}?agent_id=${agentId}`, { method: 'DELETE', ...auth() });
/**
* 从 ChatLog.payload 恢复订单识别终态,保证刷新会话后与实时 SSE 消息形状一致。
* 核心逻辑:仅接受带合法 status 的对象;服务端仍是终态事实源,本函数不推导或改写计数。
* @param message - 历史接口返回的单条消息。
* @returns 原消息或已补充 shipping_order_extraction_state 的消息。
*/
export const hydrateShippingOrderExtractionState = (message: ChatMessage): ChatMessage => {
const payload = message.payload && typeof message.payload === 'object'
? message.payload as Record<string, unknown>
: {};
const state = payload.shipping_order_extraction_state;
if (!state || typeof state !== 'object') return message;
const status = String((state as Record<string, unknown>).status || '');
if (!['extracting', 'completed', 'partially_completed', 'failed'].includes(status)) return message;
message.shipping_order_extraction_state = state as ShippingOrderExtractionState;
return message;
};
export const listChatMessages = async (conversationId: string, agentId: number) => {
const messages = await requestJson<ChatMessage[]>(`/api/chat/messages?conversation_id=${conversationId}&agent_id=${agentId}`, auth());
return Array.isArray(messages)
? messages.filter((message) => message?.type !== 'shipping-parse-review')
? messages
.filter((message) => message?.type !== 'shipping-parse-review')
.map(hydrateShippingOrderExtractionState)
: messages;
};
@@ -20,6 +20,7 @@ import type {
ShippingTaskCreateResponse,
ShippingTaskDetail,
ShippingTaskSummary,
ShippingCustomerOption,
ShippingTaskUiState,
} from '../types/shipping.api.types';
@@ -154,6 +155,20 @@ export async function confirmWorkspaceShippingInventorySource(taskNo: string, so
return assertShippingOk(body);
}
/** 搜索可供业务用户确认的启用标准客户。 */
export const listWorkspaceShippingCustomerOptions = (query = '') => {
const params = new URLSearchParams({ limit: '200' });
if (query.trim()) params.set('q', query.trim());
return requestJson<ShippingCustomerOption[]>(`/api/workspace/shipping-customers?${params.toString()}`);
};
/** 为任务确认标准客户;确认成功后响应包含正式业务编号。 */
export const confirmWorkspaceShippingCustomer = (taskNo: string, customerId: number) =>
requestJson<ShippingTaskDetail>(
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/confirm-customer`,
jsonPost({ customer_id: customerId }),
);
/**
* 提交库存字段映射。
* @param taskNo - 发货任务编号
@@ -1,7 +1,8 @@
/**
* features/chat/components/ChatInputBar.vue
* 聊天输入栏:文本框、附件、语音、知识库选择与发送按钮。
* 逻辑:设备维保助手的管理入口(设备台账、登记维修)与语音按钮同侧排列,发送按钮独占右侧。
* 用途:承载聊天文本输入、附件预览、语音、知识库选择与发送操作。
* 依赖:lucide 图标、ShippingNoticeCandidateReview、附件完整性判断工具。
* 逻辑:附件卡片位于文本框上方;发货通知保留解析/重复处理能力,普通附件展示逐文件上传状态。
*/
<script setup lang="ts">
import { nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue';
@@ -10,7 +11,13 @@ import type { Ref } from 'vue';
import {
Check,
ChevronDown,
CircleAlert,
CircleCheck,
Database,
FileAudio,
FileImage,
FileText,
FileVideo,
Link2,
Loader2,
Mic,
@@ -26,6 +33,13 @@ import {
isBlockingWarning,
isShippingNoticeAttachmentParseIncomplete,
} from '../shipping/shippingNoticeAttachmentIntegrity';
import {
getAttachmentCardStatus,
getAttachmentExtension,
getAttachmentName,
getAttachmentSize,
isAttachmentRemoveDisabled,
} from '../utils/attachmentCard.utils';
export interface ChatInputAttachmentPolicy {
anyEnabled: boolean;
@@ -156,6 +170,15 @@ function shippingNoticeAttachmentTitle(attachment: ShippingNoticePendingAttachme
return lines.join('\n');
}
/** 根据附件业务类型选择文件图标,帮助用户快速区分媒体与文档。 */
function attachmentIcon(attachment: PendingAttachment) {
if (attachment.kind === 'remote') return Link2;
if (attachment.type === 'image') return FileImage;
if (attachment.type === 'audio') return FileAudio;
if (attachment.type === 'video') return FileVideo;
return FileText;
}
const closeAttachmentMenu = () => {
showAttachmentMenu.value = false;
showAttachmentUrlPanel.value = false;
@@ -293,6 +316,92 @@ watch(
@resolve-duplicate="(candidateNo, action, targetTaskNo, reason, done) => emit('resolve-shipping-candidate-duplicate', candidateNo, action, targetTaskNo, reason, done)"
/>
</div>
<div
v-if="attachments.length > 0"
data-testid="chat-attachment-list"
class="flex flex-wrap gap-2 px-2.5 pb-2 pt-1"
>
<article
v-for="a in attachments"
:key="a.id"
class="group relative flex min-w-0 basis-full items-center gap-3 rounded-xl border border-default bg-surface-soft px-3 py-2.5 transition-colors sm:basis-[calc(50%-0.25rem)] lg:max-w-[310px]"
:title="a.kind === 'shipping_notice' ? shippingNoticeAttachmentTitle(a) : getAttachmentName(a)"
>
<div
class="flex h-11 w-10 shrink-0 flex-col items-center justify-center rounded-lg bg-brand-50 text-brand-700 dark:bg-brand-900/30 dark:text-brand-300"
aria-hidden="true"
>
<component :is="attachmentIcon(a)" class="h-4.5 w-4.5" />
<span class="mt-0.5 max-w-9 truncate text-[9px] font-bold leading-none">{{ getAttachmentExtension(a) }}</span>
</div>
<div class="min-w-0 flex-1 pr-5">
<p class="truncate text-sm font-medium text-primary">{{ getAttachmentName(a) }}</p>
<div class="mt-1 flex min-w-0 items-center gap-1.5 text-[11px] leading-none">
<span v-if="getAttachmentSize(a)" class="shrink-0 text-muted">{{ getAttachmentSize(a) }}</span>
<span v-if="getAttachmentSize(a)" class="text-slate-300">·</span>
<span
class="flex min-w-0 items-center gap-1 truncate"
:class="{
'text-muted': getAttachmentCardStatus(a).state === 'pending',
'text-brand-600': ['uploading', 'processing'].includes(getAttachmentCardStatus(a).state),
'text-amber-700': getAttachmentCardStatus(a).state === 'attention',
'text-emerald-600': getAttachmentCardStatus(a).state === 'ready',
'text-red-500': getAttachmentCardStatus(a).state === 'failed',
}"
>
<Loader2
v-if="['uploading', 'processing'].includes(getAttachmentCardStatus(a).state)"
class="h-3 w-3 shrink-0 animate-spin"
/>
<CircleCheck v-else-if="getAttachmentCardStatus(a).state === 'ready'" class="h-3 w-3 shrink-0" />
<CircleAlert v-else-if="['attention', 'failed'].includes(getAttachmentCardStatus(a).state)" class="h-3 w-3 shrink-0" />
<span class="truncate">{{ t(getAttachmentCardStatus(a).labelKey) }}</span>
<template v-if="a.kind === 'shipping_notice' && shippingNoticeAttachmentHint(a)">
<span class="truncate">· {{ shippingNoticeAttachmentHint(a) }}</span>
</template>
</span>
</div>
</div>
<div
v-if="a.kind === 'shipping_notice' && (canRetryShippingNoticeParse(a) || (!a.candidates?.length && a.duplicate?.blocking && !a.duplicateResolution?.action))"
class="absolute bottom-1.5 right-2 flex items-center gap-1"
>
<button
v-if="!a.candidates?.length && a.duplicate?.blocking && !a.duplicateResolution?.action"
type="button"
class="rounded px-1.5 py-1 text-[10px] font-medium text-amber-700 hover:bg-amber-50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-amber-400"
:title="t('chat.shippingNoticeDuplicateHandle')"
@click="emit('resolve-shipping-notice-duplicate', a.id)"
>
{{ t('chat.shippingNoticeDuplicateHandle') }}
</button>
<button
v-if="canRetryShippingNoticeParse(a)"
type="button"
class="rounded p-1 text-muted hover:bg-surface hover:text-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-400"
:title="t('chat.shippingNoticeRetryParse')"
@click="emit('retry-shipping-notice-attachment', a.id)"
>
<RefreshCw class="h-3.5 w-3.5" />
</button>
</div>
<button
type="button"
class="absolute right-1.5 top-1.5 flex h-6 w-6 items-center justify-center rounded-full text-muted opacity-80 transition hover:bg-surface hover:text-red-500 focus-visible:opacity-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-400 disabled:cursor-not-allowed disabled:opacity-30"
:disabled="isAttachmentRemoveDisabled(a)"
:title="t('chat.attachment.remove')"
:aria-label="t('chat.attachment.removeNamed', { name: getAttachmentName(a) })"
@click="emit('remove-attachment', a.id)"
>
<X class="h-3.5 w-3.5" />
</button>
</article>
</div>
<textarea
ref="textareaRef"
v-model="inputValue"
@@ -324,77 +433,6 @@ watch(
@change="emit('local-files-selected', $event)"
/>
<div v-if="attachments.length > 0" class="flex flex-wrap gap-2 px-3 pb-1">
<div
v-for="a in attachments"
:key="a.id"
class="flex items-center gap-2 rounded-lg border border-default bg-surface-soft px-2 py-1 text-xs text-secondary"
>
<span class="max-w-[220px] truncate">
<template v-if="a.kind === 'shipping_notice'">
{{ a.originalFilename }}
<span v-if="a.uploadStatus === 'uploading'" class="text-muted"> · {{ t('chat.shippingNoticeUploading') }}</span>
<span v-else-if="a.parseStatus === 'queued' || a.parseStatus === 'parsing'" class="text-muted"> · {{ t('chat.shippingNoticeParsing') }}</span>
<span
v-else-if="a.parseStatus === 'parsed' && !a.candidates?.length && a.duplicate?.status === 'possible_duplicate' && !a.duplicateResolution?.action"
class="font-medium text-amber-700"
> · {{ t('chat.shippingNoticeDuplicatePossibleBadge') }}</span>
<span
v-else-if="a.parseStatus === 'parsed' && !a.candidates?.length && a.duplicate?.blocking && !a.duplicateResolution?.action"
class="font-medium text-amber-700"
> · {{ t('chat.shippingNoticeDuplicateBlockingBadge') }}</span>
<span
v-else-if="a.parseStatus === 'parsed' && a.duplicateResolution?.action === 'create_revision'"
class="text-brand-700"
> · {{ t('chat.shippingNoticeDuplicateRevisionChosen') }}</span>
<span
v-else-if="a.parseStatus === 'parsed' && a.duplicateResolution?.action === 'force_create'"
class="text-amber-700"
> · {{ t('chat.shippingNoticeDuplicateForceChosen') }}</span>
<span
v-else-if="a.parseStatus === 'parsed' && a.duplicateResolution?.action === 'open_existing'"
class="text-muted"
> · {{ t('chat.shippingNoticeDuplicateOpenChosen') }}</span>
<span
v-else-if="a.parseStatus === 'parsed'"
class="text-muted"
:title="shippingNoticeAttachmentTitle(a)"
>
· {{ t('chat.shippingNoticeParsed') }}
<template v-if="shippingNoticeAttachmentHint(a)">
· {{ shippingNoticeAttachmentHint(a) }}
</template>
</span>
<span v-else-if="a.parseStatus === 'failed'" class="text-muted"> · {{ t('chat.shippingNoticeParseFailed') }}</span>
</template>
<template v-else>
{{ a.kind === 'local' ? a.file.name : a.url }}
</template>
</span>
<button
v-if="a.kind === 'shipping_notice' && !a.candidates?.length && a.duplicate?.blocking && !a.duplicateResolution?.action"
type="button"
class="text-amber-700 hover:text-amber-800"
:title="t('chat.shippingNoticeDuplicateHandle')"
@click="emit('resolve-shipping-notice-duplicate', a.id)"
>
{{ t('chat.shippingNoticeDuplicateHandle') }}
</button>
<button
v-if="a.kind === 'shipping_notice' && canRetryShippingNoticeParse(a)"
type="button"
class="text-muted hover:text-primary"
:title="t('chat.shippingNoticeRetryParse')"
@click="emit('retry-shipping-notice-attachment', a.id)"
>
<RefreshCw class="h-3.5 w-3.5" />
</button>
<button type="button" class="text-muted hover:text-red-500" @click="emit('remove-attachment', a.id)">
<X class="h-3.5 w-3.5" />
</button>
</div>
</div>
<div
v-if="isShippingNoticeAgent && attachments.length > 0"
class="flex flex-wrap items-center gap-2 px-3 pb-1 text-xs text-muted"
@@ -11,6 +11,7 @@ import ChatLeaveAgentDialog from '@/features/chat/components/ChatLeaveAgentDialo
import ChatOALoginDialog from '@/features/chat/components/ChatOALoginDialog.vue';
import ChatGuideModal from '@/features/chat/components/ChatGuideModal.vue';
import ShippingNoticeDuplicateDialog from '@/features/chat/components/ShippingNoticeDuplicateDialog.vue';
import ShippingCustomerConfirmDialog from '@/features/chat/components/ShippingCustomerConfirmDialog.vue';
import { Check, Loader2, X } from 'lucide-vue-next';
import { nextTick } from 'vue';
import { useChatPageContext } from '@/features/chat/composables/chat.context';
@@ -155,4 +156,12 @@ async function handleQueryPreviewAssetImage(assetId: string, assetName: string)
@remove="() => void page.removeShippingDuplicateDialogAttachment?.()"
@cancel="page.closeShippingDuplicateDialog?.()"
/>
<ShippingCustomerConfirmDialog
:open="!!page.showShippingCustomerDialog"
:options="page.shippingCustomerOptions || []"
:loading="!!page.shippingCustomerLoading"
@close="page.closeShippingCustomerDialog?.()"
@search="(query) => void page.searchShippingCustomers?.(query)"
@confirm="(customerId) => void page.confirmShippingCustomer?.(customerId)"
/>
</template>
@@ -563,7 +563,12 @@ const handleSwitchBatch = (batchNo: string) => {
></div>
<div class="flex items-start justify-between gap-3">
<div class="min-w-0">
<div class="truncate font-mono text-sm font-bold text-primary">{{ task.task_no }}</div>
<div class="truncate font-mono text-sm font-bold text-primary">
{{ task.business_no || task.task_no }}
</div>
<div v-if="task.business_no" class="mt-0.5 truncate font-mono text-[10px] text-muted">
{{ t('chat.shippingNoticeUi.technicalTaskNo', { taskNo: task.task_no }) }}
</div>
<div class="mt-0.5 truncate text-xs text-muted">
{{ task.source_file_name || task.customer_name || t('chat.shippingNoticeUi.currentNotice') }}
</div>
@@ -0,0 +1,41 @@
<!--
features/chat/components/ShippingCustomerConfirmDialog.vue
用途:在 customer_review 检查点搜索并确认启用标准客户。
依赖:ShippingCustomerOption、vue-i18n。
逻辑:父 composable 提供选项与提交动作;本组件不解析邮件客户名,也不创建客户资料。
-->
<script setup lang="ts">
import { ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import type { ShippingCustomerOption } from '@/features/chat/types/shipping.api.types';
const props = defineProps<{ open: boolean; options: ShippingCustomerOption[]; loading: boolean }>();
const emit = defineEmits<{ close: []; search: [query: string]; confirm: [customerId: number] }>();
const { t } = useI18n();
const query = ref('');
const selectedId = ref<number | null>(null);
/** 每次打开对话框时清空上次选择。 */
watch(() => props.open, (open) => {
if (open) {
query.value = '';
selectedId.value = null;
}
});
</script>
<template>
<div v-if="open" class="admin-modal-overlay animate-fade-in items-center z-[170]">
<div class="admin-modal-panel max-w-xl max-h-[90vh] scale-100">
<div class="px-6 py-5 border-b border-subtle"><h3 class="section-title">{{ t('chat.shippingCustomer.title') }}</h3><p class="section-desc mt-1">{{ t('chat.shippingCustomer.subtitle') }}</p></div>
<div class="px-6 py-5 space-y-4 overflow-y-auto">
<div class="flex gap-2"><input v-model="query" class="input-field text-sm" :placeholder="t('chat.shippingCustomer.searchPlaceholder')" @keyup.enter="emit('search', query)" /><button type="button" class="btn-ghost" @click="emit('search', query)">{{ t('chat.shippingCustomer.search') }}</button></div>
<div class="space-y-2 max-h-80 overflow-y-auto">
<label v-for="customer in options" :key="customer.id" class="flex items-center gap-3 rounded-xl border border-default p-3 cursor-pointer hover:border-brand-300"><input v-model="selectedId" type="radio" :value="customer.id" /><span class="flex-1"><span class="font-medium text-primary">{{ customer.standard_name }}</span><span class="ml-2 font-mono text-xs text-muted">{{ customer.short_code }}</span></span></label>
<div v-if="!loading && !options.length" class="text-sm text-muted py-8 text-center">{{ t('chat.shippingCustomer.empty') }}</div>
</div>
</div>
<div class="admin-modal-footer"><button type="button" class="btn-ghost" @click="emit('close')">{{ t('common.cancel') }}</button><button type="button" class="btn-primary" :disabled="!selectedId || loading" @click="selectedId && emit('confirm', selectedId)">{{ t('chat.shippingCustomer.confirm') }}</button></div>
</div>
</div>
</template>
@@ -14,7 +14,7 @@ interface EditableCandidateLine {
sku: string;
qty: string;
reservation_id: string;
hub_code: string;
source_type: string;
uom: string;
}
@@ -44,7 +44,12 @@ watch(() => props.attachment.candidates, () => {
}
});
/** 将 Candidate 摘要投影为业务用户可编辑的 PO、SKU、Qty、Reservation 与 Hub 字段。 */
/**
* 将 Candidate 摘要投影为可编辑的 PO 与订单行。
* 核心逻辑:保留原始扩展字段,并显式映射 SKU、数量、Reservation ID、Source Type 与单位。
* @param candidateNo - 待编辑的 Candidate 编号
* @returns 无返回值;Candidate 不存在时保持当前编辑状态
*/
function startEdit(candidateNo: string): void {
const candidate = candidates.value.find((item) => item.candidateNo === candidateNo);
if (!candidate) return;
@@ -58,30 +63,41 @@ function startEdit(candidateNo: string): void {
sku: String(line.sku || ''),
qty: String(line.qty ?? ''),
reservation_id: String(line.reservation_id || ''),
hub_code: String(line.hub_code || ''),
source_type: String(line.source_type || ''),
uom: String(line.uom || 'EA'),
})));
if (!editLines.length) addLine();
editError.value = '';
}
/** 新增一条待修订订单行。 */
/**
* 新增一条待修订订单行。
* 核心逻辑:创建带可选 Source Type 路由线索的空白草稿。
* @returns 无返回值
*/
function addLine(): void {
editLines.push({ source: {}, sku: '', qty: '', reservation_id: '', hub_code: '', uom: 'EA' });
editLines.push({ source: {}, sku: '', qty: '', reservation_id: '', source_type: '', uom: 'EA' });
}
/** 校验所有订单行后提交,不允许空 SKU、非正数数量或空行静默通过。 */
/**
* 校验并提交 Candidate 修订。
* 核心逻辑:保留原始扩展字段,并将 Source Type 作为唯一可选库存路由线索提交。
* @returns 无返回值;校验失败时写入本地错误提示
*/
function saveEdit(): void {
const candidate = candidates.value.find((item) => item.candidateNo === editingCandidateNo.value);
if (!candidate || !editLines.length) return;
const normalizedLines = editLines.map((line) => ({
...line.source,
sku: line.sku.trim(),
qty: Number(line.qty),
reservation_id: line.reservation_id.trim() || undefined,
hub_code: line.hub_code.trim() || undefined,
uom: line.uom.trim() || 'EA',
}));
const normalizedLines = editLines.map((line) => {
const source = { ...line.source };
return {
...source,
sku: line.sku.trim(),
qty: Number(line.qty),
reservation_id: line.reservation_id.trim() || undefined,
source_type: line.source_type.trim() || undefined,
uom: line.uom.trim() || 'EA',
};
});
if (normalizedLines.some((line) => !line.sku || !Number.isFinite(line.qty) || line.qty <= 0)) {
editError.value = t('chat.shippingCandidateInvalidLine');
return;
@@ -200,7 +216,7 @@ function submitForceCreate(candidateNo: string): void {
<input v-model="line.sku" :placeholder="t('chat.shippingCandidateSku')" class="rounded border border-default px-2 py-1" />
<input v-model="line.qty" type="number" min="0.0001" step="any" :placeholder="t('chat.shippingCandidateQty')" class="rounded border border-default px-2 py-1" />
<input v-model="line.reservation_id" :placeholder="t('chat.shippingCandidateReservation')" class="rounded border border-default px-2 py-1" />
<input v-model="line.hub_code" :placeholder="t('chat.shippingCandidateHubCode')" class="rounded border border-default px-2 py-1" />
<input v-model="line.source_type" :placeholder="t('chat.shippingCandidateSourceType')" class="rounded border border-default px-2 py-1" />
<div class="flex gap-1">
<input v-model="line.uom" :placeholder="t('chat.shippingCandidateUom')" class="min-w-0 flex-1 rounded border border-default px-2 py-1" />
<button v-if="editLines.length > 1" type="button" class="text-red-600" @click="editLines.splice(index, 1)">×</button>
@@ -0,0 +1,63 @@
/**
* features/chat/components/messages/ChatMessageAttachmentList.vue
* 用途:在用户消息中展示已发送附件快照。
* 依赖:lucide 文件图标、attachmentCard.utils 的大小格式化、chat.types 的消息附件契约。
* 逻辑:ChatMessageBubble 将当前用户消息附件传入;本组件只读展示,不提供删除、重试或上传状态操作。
*/
<script setup lang="ts">
import { FileAudio, FileImage, FileText, FileVideo, Link2 } from 'lucide-vue-next';
import { formatAttachmentSize } from '../../utils/attachmentCard.utils';
import type { ChatMessageAttachment } from '../../types/chat.types';
const { attachments } = defineProps<{
attachments: ChatMessageAttachment[];
}>();
/** 根据附件来源与业务类型选择只读消息卡片图标。 */
function attachmentIcon(attachment: ChatMessageAttachment) {
if (attachment.source === 'remote') return Link2;
if (attachment.type === 'image') return FileImage;
if (attachment.type === 'audio') return FileAudio;
if (attachment.type === 'video') return FileVideo;
return FileText;
}
/** 生成附件类型徽标,优先使用快照扩展名。 */
function attachmentBadge(attachment: ChatMessageAttachment): string {
const extension = String(attachment.extension || '').trim().toUpperCase();
if (extension) return extension.slice(0, 5);
if (attachment.source === 'remote') return 'URL';
return attachment.type.toUpperCase().slice(0, 5);
}
</script>
<template>
<div
v-if="attachments.length > 0"
data-testid="chat-message-attachment-list"
class="mb-2 flex w-full flex-wrap justify-end gap-2"
>
<article
v-for="(attachment, attachmentIndex) in attachments"
:key="attachment.id || `${attachment.name}-${attachment.size ?? 'unknown'}-${attachmentIndex}`"
class="flex min-w-0 basis-full items-center gap-2.5 rounded-xl border border-default bg-surface px-3 py-2.5 shadow-sm dark:bg-slate-900 sm:basis-[calc(50%-0.25rem)] sm:min-w-[220px] sm:max-w-[290px]"
:title="attachment.name"
>
<div
class="flex h-10 w-9 shrink-0 flex-col items-center justify-center rounded-lg bg-brand-50 text-brand-700 dark:bg-brand-900/30 dark:text-brand-300"
aria-hidden="true"
>
<component :is="attachmentIcon(attachment)" class="h-4 w-4" />
<span class="mt-0.5 max-w-8 truncate text-[8px] font-bold leading-none">
{{ attachmentBadge(attachment) }}
</span>
</div>
<div class="min-w-0 flex-1">
<div class="truncate text-sm font-semibold text-primary">{{ attachment.name }}</div>
<div v-if="attachment.size !== undefined" class="mt-1 text-[11px] leading-none text-muted">
{{ formatAttachmentSize(attachment.size) }}
</div>
</div>
</article>
</div>
</template>
@@ -1,14 +1,29 @@
/**
* features/chat/components/messages/ChatMessageBubble.vue
* 用途:渲染单条聊天消息,统一承接用户气泡、助手 Markdown、内嵌文件下载、请假/出货子组件与操作栏。
* 依赖:Vue computed、lucide 图标、Leave/Shipping 子消息组件、chat.types 与页面级 handlers。
* 逻辑:由 ChatMessageList 按消息逐条挂载;正文渲染与特殊交互委托 useChatPageMarkdown 等页面编排层提供的 handlers。
* 依赖:Vue computed、lucide 图标、消息附件/Leave/Shipping 子组件、chat.types 与页面级 handlers。
* 逻辑:由 ChatMessageList 按消息逐条挂载;用户附件显示在文字气泡上方,助手正文与特殊交互委托页面 handlers。
*/
<script setup lang="ts">
import { computed, nextTick, ref, watch } from 'vue';
import { Check, Copy, Download, Edit2, Eye, LayoutGrid, MessageSquareText, RotateCw, X } from 'lucide-vue-next';
import {
Check,
CircleCheck,
CircleX,
Copy,
Download,
Edit2,
Eye,
LayoutGrid,
LoaderCircle,
MessageSquareText,
RotateCw,
TriangleAlert,
X,
} from 'lucide-vue-next';
import { useAuthStore } from '@/features/auth/stores/auth.store';
import LeaveMessageBlock, { type LeaveMessageHandlers } from './LeaveMessageBlock.vue';
import ChatMessageAttachmentList from './ChatMessageAttachmentList.vue';
import MaintenanceDeviceResultCard from './MaintenanceDeviceResultCard.vue';
import ShippingInventoryMappingMessage, { type ShippingMappingHandlers } from './ShippingInventoryMappingMessage.vue';
import ShippingMatchResultCard from './ShippingMatchResultCard.vue';
@@ -109,12 +124,30 @@ const showSourceSection = computed(() => {
|| sourceLinks.value.length > 0;
});
const showActions = computed(() => message.type !== 'leave-form');
const hasUserContent = computed(() => message.role === 'user' && String(message.content || '').trim().length > 0);
const showActions = computed(() => (
message.type !== 'leave-form'
&& (message.role !== 'user' || hasUserContent.value)
));
const showShippingActionsPanel = computed(() =>
isShippingNoticeAgent
&& !!message.shipping_actions?.length
&& message.type !== 'shipping-match-result',
);
const shippingOrderExtractionState = computed(() => message.shipping_order_extraction_state);
const shippingOrderExtractionTitleKey = computed(() => {
switch (shippingOrderExtractionState.value?.status) {
case 'completed': return 'chat.shippingOrderExtractionCompleted';
case 'partially_completed': return 'chat.shippingOrderExtractionPartiallyCompleted';
case 'failed': return 'chat.shippingOrderExtractionFailed';
default: return 'chat.shippingOrderExtractionProcessing';
}
});
const showShippingOrderExtractionMessage = computed(() => {
const stateMessage = String(shippingOrderExtractionState.value?.message || '').trim();
const assistantContent = String(message.content || '').trim();
return !!stateMessage && stateMessage !== assistantContent && !assistantContent.includes(stateMessage);
});
const isLastMessage = computed(() => index === messageCount - 1 || (message.role === 'assistant' && isLatestAssistantMessage));
const isCopied = computed(() => copiedIndex === index);
const renderedMarkdown = computed(() => (
@@ -622,7 +655,12 @@ function handleInlineDownload(file: InlineDownloadFile): void {
class="flex flex-col"
:class="message.role === 'user' ? 'max-w-[88%] md:max-w-[74%] items-end' : 'w-full'"
>
<ChatMessageAttachmentList
v-if="message.role === 'user' && message.attachments?.length"
:attachments="message.attachments"
/>
<div
v-if="message.role === 'assistant' || hasUserContent"
class="text-[15px] leading-relaxed"
:class="message.role === 'user'
? 'rounded-2xl rounded-tr-sm bg-brand-600 px-5 py-2.5 text-white shadow-sm shadow-brand-500/15'
@@ -630,6 +668,80 @@ function handleInlineDownload(file: InlineDownloadFile): void {
>
<div v-if="message.role === 'user'" class="whitespace-pre-wrap">{{ message.content }}</div>
<div v-else>
<div
v-if="shippingOrderExtractionState"
class="mb-3 flex min-h-[60px] items-start gap-3 rounded-lg border px-3.5 py-3"
:class="{
'border-sky-200 bg-sky-50/80 text-sky-900 dark:border-sky-800 dark:bg-sky-950/35 dark:text-sky-100': shippingOrderExtractionState.status === 'extracting',
'border-emerald-200 bg-emerald-50/80 text-emerald-900 dark:border-emerald-800 dark:bg-emerald-950/35 dark:text-emerald-100': shippingOrderExtractionState.status === 'completed',
'border-amber-200 bg-amber-50/80 text-amber-950 dark:border-amber-800 dark:bg-amber-950/35 dark:text-amber-100': shippingOrderExtractionState.status === 'partially_completed',
'border-rose-200 bg-rose-50/80 text-rose-900 dark:border-rose-800 dark:bg-rose-950/35 dark:text-rose-100': shippingOrderExtractionState.status === 'failed',
}"
>
<LoaderCircle
v-if="shippingOrderExtractionState.status === 'extracting'"
class="mt-0.5 h-5 w-5 shrink-0 animate-spin"
/>
<CircleCheck
v-else-if="shippingOrderExtractionState.status === 'completed'"
class="mt-0.5 h-5 w-5 shrink-0"
/>
<TriangleAlert
v-else-if="shippingOrderExtractionState.status === 'partially_completed'"
class="mt-0.5 h-5 w-5 shrink-0"
/>
<CircleX v-else class="mt-0.5 h-5 w-5 shrink-0" />
<div class="min-w-0 flex-1">
<div class="text-sm font-semibold">{{ $t(shippingOrderExtractionTitleKey) }}</div>
<div
data-testid="shipping-order-extraction-progress"
class="mt-2 h-1.5 w-full overflow-hidden rounded-full bg-black/10 dark:bg-white/15"
role="progressbar"
:aria-label="$t(shippingOrderExtractionTitleKey)"
aria-valuemin="0"
aria-valuemax="100"
:aria-valuenow="shippingOrderExtractionState.terminal ? 100 : undefined"
:aria-busy="shippingOrderExtractionState.status === 'extracting'"
>
<div
v-if="shippingOrderExtractionState.status === 'extracting'"
class="shipping-order-extraction-indeterminate h-full w-2/5 rounded-full bg-sky-500"
/>
<div
v-else
class="h-full w-full rounded-full"
:class="{
'bg-emerald-500': shippingOrderExtractionState.status === 'completed',
'bg-amber-500': shippingOrderExtractionState.status === 'partially_completed',
'bg-rose-500': shippingOrderExtractionState.status === 'failed',
}"
/>
</div>
<div
v-if="shippingOrderExtractionState.terminal"
class="mt-1 flex flex-wrap gap-x-3 gap-y-1 text-xs"
>
<span v-if="shippingOrderExtractionState.created_count > 0">
{{ $t('chat.shippingOrderExtractionCreatedCount', { count: shippingOrderExtractionState.created_count }) }}
</span>
<span v-if="shippingOrderExtractionState.opened_existing_count > 0">
{{ $t('chat.shippingOrderExtractionOpenedExistingCount', { count: shippingOrderExtractionState.opened_existing_count }) }}
</span>
<span v-if="shippingOrderExtractionState.pending_count > 0">
{{ $t('chat.shippingOrderExtractionPendingCount', { count: shippingOrderExtractionState.pending_count }) }}
</span>
<span v-if="shippingOrderExtractionState.non_shipping_count > 0">
{{ $t('chat.shippingOrderExtractionIgnoredCount', { count: shippingOrderExtractionState.non_shipping_count }) }}
</span>
<span v-if="shippingOrderExtractionState.created_with_missing_fields_count > 0">
{{ $t('chat.shippingOrderExtractionMissingFieldsCount', { count: shippingOrderExtractionState.created_with_missing_fields_count }) }}
</span>
</div>
<div v-if="showShippingOrderExtractionMessage" class="mt-1 break-words text-xs opacity-80">
{{ shippingOrderExtractionState.message }}
</div>
</div>
</div>
<LeaveMessageBlock
v-if="isLeaveMessage"
:message="message"
@@ -1034,6 +1146,28 @@ function handleInlineDownload(file: InlineDownloadFile): void {
</template>
<style scoped>
.shipping-order-extraction-indeterminate {
animation: shipping-order-extraction-progress 1.25s ease-in-out infinite;
will-change: transform;
}
@keyframes shipping-order-extraction-progress {
from {
transform: translateX(-100%);
}
to {
transform: translateX(250%);
}
}
@media (prefers-reduced-motion: reduce) {
.shipping-order-extraction-indeterminate {
animation: none;
transform: translateX(75%);
}
}
:deep(.chat-markdown) {
max-width: 100%;
}
@@ -1,13 +1,43 @@
/**
* features/chat/composables/useChat.spec.ts
* 用途:验证聊天流对发货通知 UI State SSE 事件的消息级回写行为。
* 依赖:vitest、useChat 导出的纯函数、chat.types。
* 逻辑:覆盖 batch_ui_state 到 focus_task_ui_state 的投影、focus 切换时按钮跟随更新,以及已消费按钮消息的防回挂保护。
* 用途:验证聊天流对发货通知 UI State 与订单识别生命周期 SSE 的消息级回写行为。
* 依赖:vitest、useChat/chat.api 导出的纯函数、chat.types。
* 逻辑:覆盖任务状态投影、订单识别终态保护、terminal 后事件放行及历史 payload 恢复。
*/
import { describe, expect, it } from 'vitest';
import { applyShippingUiStateToMessage } from './useChat';
import {
applyShippingOrderExtractionStateToMessage,
applyShippingUiStateToMessage,
createUserChatMessage,
isAllowedAfterStreamTerminal,
} from './useChat';
import { hydrateShippingOrderExtractionState } from '../api/chat.api';
import type { ChatMessage } from '../types/chat.types';
describe('useChat user attachment snapshots', () => {
it('copies sent attachments onto the user message without inheriting them for text-only messages', () => {
const attachments = [{
id: 'attachment-1',
name: 'purchase-order.pdf',
size: 144_456,
extension: 'pdf',
type: 'document' as const,
source: 'local' as const,
}];
const message = createUserChatMessage('总结附件', attachments);
attachments[0]!.name = 'changed.pdf';
expect(message).toMatchObject({
role: 'user',
content: '总结附件',
attachments: [{ name: 'purchase-order.pdf', size: 144_456 }],
});
expect(message.attachments).not.toBe(attachments);
expect(createUserChatMessage('仅重发文字')).toEqual({ role: 'user', content: '仅重发文字' });
});
});
const buildBatchUiStateEvent = (
taskNo: string,
batchNo: string,
@@ -97,3 +127,93 @@ describe('useChat shipping_ui_state SSE', () => {
.toBe('SN-FOCUS-B');
});
});
describe('useChat shipping_order_extraction_state SSE', () => {
it('replaces extracting with persisted facts without overwriting Dify content', () => {
const message: ChatMessage = {
role: 'assistant',
content: 'Dify 最终正文保持不变',
payload: { existing_key: 'kept' },
};
applyShippingOrderExtractionStateToMessage(message, {
event: 'shipping_order_extraction_state',
status: 'extracting',
phase: 'llm_extraction',
message: '正在识别邮件及附件中的订单',
created_count: -1,
terminal: false,
});
expect(message.shipping_order_extraction_state?.status).toBe('extracting');
expect(message.shipping_order_extraction_state?.created_count).toBe(0);
applyShippingOrderExtractionStateToMessage(message, {
event: 'shipping_order_extraction_state',
status: 'completed',
phase: 'result_persisted',
message: '已创建 1 个发货任务',
created_count: 1,
opened_existing_count: 2,
pending_count: 0,
non_shipping_count: 3,
created_with_missing_fields_count: 1,
batch_no: 'SB-STATE-001',
terminal: true,
});
expect(message.content).toBe('Dify 最终正文保持不变');
expect(message.shipping_order_extraction_state).toMatchObject({
status: 'completed',
created_count: 1,
opened_existing_count: 2,
non_shipping_count: 3,
batch_no: 'SB-STATE-001',
terminal: true,
});
expect((message.payload as Record<string, unknown>).existing_key).toBe('kept');
expect((message.payload as { shipping_order_extraction_state?: { created_count?: number } })
.shipping_order_extraction_state?.created_count).toBe(1);
// 关键断言:网络重排导致的迟到进行态不能覆盖已经展示的终态。
applyShippingOrderExtractionStateToMessage(message, {
status: 'extracting',
phase: 'llm_extraction',
message: '迟到事件',
terminal: false,
});
expect(message.shipping_order_extraction_state?.status).toBe('completed');
});
it('allows HXOPS domain states after the upstream terminal event', () => {
expect(isAllowedAfterStreamTerminal('shipping_order_extraction_state')).toBe(true);
expect(isAllowedAfterStreamTerminal('shipping_ui_state')).toBe(true);
expect(isAllowedAfterStreamTerminal('agent_message')).toBe(false);
});
it('hydrates persisted terminal state from ChatLog payload', () => {
const message: ChatMessage = {
role: 'assistant',
content: '订单识别完成',
payload: {
shipping_order_extraction_state: {
status: 'partially_completed',
phase: 'result_persisted',
message: '仍有 1 个订单需要补充信息',
created_count: 1,
opened_existing_count: 0,
pending_count: 1,
non_shipping_count: 0,
created_with_missing_fields_count: 0,
batch_no: 'SB-HISTORY-001',
terminal: true,
},
},
};
hydrateShippingOrderExtractionState(message);
expect(message.shipping_order_extraction_state?.status).toBe('partially_completed');
expect(message.shipping_order_extraction_state?.pending_count).toBe(1);
expect(message.shipping_order_extraction_state?.batch_no).toBe('SB-HISTORY-001');
});
});
@@ -1,19 +1,49 @@
/**
* features/chat/composables/useChat.ts
* SSE 流式对话核心:消息列表、runs、发送与接收。
* 用途:维护聊天消息、并行 run 与 legacy SSE 流式收发,并投影货代领域状态。
* 依赖:Vue、vue-i18n、useChatTurn、streamErrorMessage、chat/shipping 类型。
* 逻辑:页面调用 useChat 发起消息;Dify/HXOPS SSE 被归并到当前助手消息,领域终态可继续在上游终止事件后写入。
*/
import { ref } from 'vue';
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 {
ChatMessage,
ChatMessageAttachment,
ChatRun,
RetrieverResource,
ShippingOrderExtractionState,
ShippingOrderExtractionStatus,
} from '../types/chat.types';
import type { ShippingBatchUiState, ShippingTaskUiState } from '../types/shipping.api.types';
import { createStartChatTurn } from './useChatTurn';
export interface SendMessageLifecycleHooks {
/** 当前轮用户消息的已发送附件快照;仅用于界面展示与后续持久化。 */
userAttachments?: ChatMessageAttachment[];
onAssistantMessageFinished?: (message: ChatMessage, runMessages: ChatMessage[]) => void | Promise<void>;
}
/**
* 创建当前轮乐观用户消息,并复制附件快照避免调用方后续修改污染消息历史。
* @param content - 用户可见问题文本
* @param attachments - 已上传并固化的附件快照
* @returns 可直接推入消息列表的用户消息
*/
export function createUserChatMessage(
content: string,
attachments?: ChatMessageAttachment[],
): ChatMessage {
return {
role: 'user',
content,
...(attachments?.length
? { attachments: attachments.map((attachment) => ({ ...attachment })) }
: {}),
};
}
const normalizeResources = (resources: unknown) => {
if (!resources) return [];
if (Array.isArray(resources)) return resources;
@@ -136,6 +166,74 @@ export const applyShippingUiStateToMessage = (msg: ChatMessage, data: Record<str
};
};
const SHIPPING_ORDER_EXTRACTION_STATUSES = new Set<ShippingOrderExtractionStatus>([
'extracting',
'completed',
'partially_completed',
'failed',
]);
/**
* 将未知 SSE payload 规范为订单识别状态。
* 核心逻辑:只接受固定状态枚举;计数字段统一约束为非负整数,避免异常上游值破坏卡片布局。
* @param data - shipping_order_extraction_state 事件对象。
* @returns 合法状态;协议不匹配时返回 undefined。
*/
const resolveShippingOrderExtractionState = (
data: Record<string, unknown>,
): ShippingOrderExtractionState | undefined => {
const status = String(data.status || '') as ShippingOrderExtractionStatus;
if (!SHIPPING_ORDER_EXTRACTION_STATUSES.has(status)) return undefined;
const phase = String(data.phase || '');
if (!['llm_extraction', 'result_persisted', 'failed'].includes(phase)) return undefined;
const count = (value: unknown) => {
const parsed = Number(value);
return Number.isFinite(parsed) ? Math.max(Math.trunc(parsed), 0) : 0;
};
return {
status,
phase: phase as ShippingOrderExtractionState['phase'],
message: String(data.message || '').trim(),
created_count: count(data.created_count),
opened_existing_count: count(data.opened_existing_count),
pending_count: count(data.pending_count),
non_shipping_count: count(data.non_shipping_count),
created_with_missing_fields_count: count(data.created_with_missing_fields_count),
batch_no: typeof data.batch_no === 'string' && data.batch_no.trim() ? data.batch_no.trim() : null,
terminal: data.terminal === true || status !== 'extracting',
};
};
/**
* 将订单识别领域事件同步到当前助手消息及可持久化 payload。
* 核心逻辑:终态不得被迟到的 extracting 覆盖;正文由 Dify 独立维护,本函数只更新结构化状态。
* @param msg - 当前助手消息。
* @param data - shipping_order_extraction_state SSE 事件。
*/
export const applyShippingOrderExtractionStateToMessage = (
msg: ChatMessage,
data: Record<string, unknown>,
): void => {
const state = resolveShippingOrderExtractionState(data);
if (!state) return;
if (msg.shipping_order_extraction_state?.terminal && !state.terminal) return;
msg.shipping_order_extraction_state = state;
msg.payload = {
...(msg.payload && typeof msg.payload === 'object' ? msg.payload as Record<string, unknown> : {}),
shipping_order_extraction_state: state,
};
};
/**
* 判断上游终态之后仍允许写入当前消息的领域事件。
* 核心逻辑:普通 Dify 文本在 terminal 后丢弃,但 HXOPS 的抽取终态和任务 UI State 由 Handler 在 terminal 后生成。
* @param eventName - SSE event 字段。
* @returns 是否允许继续消费。
*/
export const isAllowedAfterStreamTerminal = (eventName: string): boolean => (
eventName === 'shipping_ui_state' || eventName === 'shipping_order_extraction_state'
);
/**
* 把 SSE 事件附带的元数据同步到当前消息对象。
*
@@ -436,7 +534,11 @@ export function useChat() {
context?: { task_id?: string; batch_no?: string; shipping_intake_nos?: string[]; display_query?: string },
hooks?: SendMessageLifecycleHooks,
) => {
const displayQuery = String(context?.display_query || query || '').trim();
const displayQuery = String(
context && Object.prototype.hasOwnProperty.call(context, 'display_query')
? context.display_query ?? ''
: query || '',
).trim();
clearLikelyCompletedStreamTimer();
const shouldDetachPreviousStream = Boolean(activeStreamController.value) && hasVisibleCompletedAssistantReply(messages.value);
if (shouldDetachPreviousStream) {
@@ -463,7 +565,7 @@ export function useChat() {
if (runs.value.length > 30) runs.value = runs.value.slice(0, 30);
activeRunId.value = run.runId;
runMessages.push({ role: 'user', content: displayQuery });
runMessages.push(createUserChatMessage(displayQuery, hooks?.userAttachments));
let botMsgIndex: number | null = null;
let hasAssistantContent = false;
let hasTerminalEvent = false;
@@ -496,7 +598,10 @@ export function useChat() {
task_id: context?.task_id || undefined,
batch_no: context?.batch_no || undefined,
shipping_intake_nos: context?.shipping_intake_nos?.length ? context.shipping_intake_nos : undefined,
display_query: context?.display_query || undefined,
display_query: context && Object.prototype.hasOwnProperty.call(context, 'display_query')
? context.display_query
: undefined,
user_attachments: hooks?.userAttachments?.length ? hooks.userAttachments : undefined,
}),
});
@@ -550,13 +655,17 @@ export function useChat() {
}
const eventName = String(data.event || '');
if (ignoreFurtherStreamEvents && eventName !== 'shipping_ui_state') {
if (ignoreFurtherStreamEvents && !isAllowedAfterStreamTerminal(eventName)) {
continue;
}
if (eventName === 'shipping_ui_state') {
const botMsg = ensureBotMessage();
if (!botMsg) continue;
applyShippingUiStateToMessage(botMsg, data);
} else if (eventName === 'shipping_order_extraction_state') {
const botMsg = ensureBotMessage();
if (!botMsg) continue;
applyShippingOrderExtractionStateToMessage(botMsg, data);
} else if (eventName === 'message' || eventName === 'agent_message') {
if (typeof data.answer === 'string' && data.answer.length > 0) {
const botMsg = ensureBotMessage();
@@ -686,6 +795,7 @@ export function useChat() {
}
}
}
return run.status === 'done';
};
return {
@@ -0,0 +1,132 @@
/**
* features/chat/composables/useChatAttachments.spec.ts
* 用途:验证普通聊天附件的逐文件上传状态、成功缓存、失败重试与删除保护。
* 依赖:Vitest、Vue 响应式 API、mock 后的 chat.api。
* 逻辑:直接调用 useChatAttachments,断言附件状态与生成的 Dify 文件参数保持一致。
*/
import { computed, ref } from 'vue';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { uploadChatFile } from '../api/chat.api';
import { useChatAttachments } from './useChatAttachments';
import type { ChatDeps } from './chat.deps';
vi.mock('../api/chat.api', () => ({
uploadChatFile: vi.fn(),
}));
const uploadChatFileMock = vi.mocked(uploadChatFile);
/** 创建满足 composable 依赖的最小测试上下文。 */
function createAttachments() {
return useChatAttachments({
deps: {
msg: { warning: vi.fn() },
} as unknown as ChatDeps,
currentAgentId: computed(() => 7),
currentAgent: ref({
capabilities: { file_upload: true },
dify_parameters: {
file_upload: {
document: { enabled: true, transfer_methods: ['local_file'] },
},
},
}),
});
}
/** 向附件状态中加入一个普通本地文件。 */
function selectLocalFile(api: ReturnType<typeof createAttachments>, name = 'order.pdf') {
const file = new File(['content'], name, { type: 'application/pdf' });
api.handleLocalFilesSelected({ target: { files: [file], value: 'selected' } } as unknown as Event);
return api.attachments.value[0];
}
describe('useChatAttachments upload states', () => {
beforeEach(() => {
uploadChatFileMock.mockReset();
});
it('marks a successful local upload ready and reuses its upload id', async () => {
const api = createAttachments();
const attachment = selectLocalFile(api);
uploadChatFileMock.mockResolvedValue({ id: 'upload-1' });
const firstSpecs = await api.buildFileSpecsForSend();
const secondSpecs = await api.buildFileSpecsForSend();
expect(attachment).toMatchObject({
kind: 'local',
uploadStatus: 'uploaded',
uploadProgress: 100,
uploadFileId: 'upload-1',
});
expect(firstSpecs).toEqual([{ type: 'document', transfer_method: 'local_file', upload_file_id: 'upload-1' }]);
expect(secondSpecs).toEqual(firstSpecs);
expect(uploadChatFileMock).toHaveBeenCalledTimes(1);
});
it('keeps a failed attachment and retries it on the next send', async () => {
const api = createAttachments();
const attachment = selectLocalFile(api);
uploadChatFileMock
.mockRejectedValueOnce(new Error('network unavailable'))
.mockResolvedValueOnce({ id: 'upload-retry' });
await expect(api.buildFileSpecsForSend()).rejects.toThrow('network unavailable');
expect(attachment).toMatchObject({
uploadStatus: 'failed',
uploadProgress: 0,
errorMessage: 'network unavailable',
});
await expect(api.buildFileSpecsForSend()).resolves.toEqual([
{ type: 'document', transfer_method: 'local_file', upload_file_id: 'upload-retry' },
]);
expect(attachment).toMatchObject({ uploadStatus: 'uploaded', uploadFileId: 'upload-retry' });
expect(attachment && 'errorMessage' in attachment ? attachment.errorMessage : undefined).toBeUndefined();
});
it('reuses earlier successful files when a later file failed', async () => {
const api = createAttachments();
selectLocalFile(api, 'first.pdf');
selectLocalFile(api, 'second.pdf');
uploadChatFileMock
.mockResolvedValueOnce({ id: 'upload-first' })
.mockRejectedValueOnce(new Error('second failed'))
.mockResolvedValueOnce({ id: 'upload-second' });
await expect(api.buildFileSpecsForSend()).rejects.toThrow('second failed');
expect(api.attachments.value[0]).toMatchObject({
uploadStatus: 'uploaded',
uploadFileId: 'upload-first',
});
expect(api.attachments.value[1]).toMatchObject({ uploadStatus: 'failed' });
await expect(api.buildFileSpecsForSend()).resolves.toEqual([
{ type: 'document', transfer_method: 'local_file', upload_file_id: 'upload-first' },
{ type: 'document', transfer_method: 'local_file', upload_file_id: 'upload-second' },
]);
expect(uploadChatFileMock).toHaveBeenCalledTimes(3);
});
it('does not remove a local attachment while its request is uploading', async () => {
const api = createAttachments();
const attachment = selectLocalFile(api);
let resolveUpload: ((value: { id: string }) => void) | undefined;
uploadChatFileMock.mockImplementation(() => new Promise((resolve) => {
resolveUpload = resolve;
}));
const buildPromise = api.buildFileSpecsForSend();
await Promise.resolve();
expect(attachment && 'uploadStatus' in attachment ? attachment.uploadStatus : undefined).toBe('uploading');
api.removeAttachment(attachment?.id || '');
expect(api.attachments.value).toHaveLength(1);
resolveUpload?.({ id: 'upload-finished' });
await buildPromise;
api.removeAttachment(attachment?.id || '');
expect(api.attachments.value).toHaveLength(0);
});
});
@@ -1,9 +1,12 @@
/**
* features/chat/composables/useChatAttachments.ts
* Dify 附件策略解析、本地/URL 附件管理与发送前上传。
* 用途:解析 Dify 附件策略,管理本地/URL 附件,并在发送前逐文件上传。
* 依赖:chat.api 的附件上传接口、chat.deps 的消息提示能力。
* 逻辑:Chat 页面通过本 composable 维护附件状态;发送流程调用 buildFileSpecsForSend 生成 Dify 文件参数。
*/
import { computed, ref, type ComputedRef, type Ref } from 'vue';
import { uploadChatFile } from '../api/chat.api';
import { createChatMessageAttachmentSnapshots } from '../utils/attachmentCard.utils';
import type { PendingAttachment } from '../types/shipping.types';
import type { ChatDeps } from './chat.deps';
@@ -245,7 +248,13 @@ export function useChatAttachments(options: UseChatAttachmentsOptions) {
return resolveDifyType(ext, file.type || '');
};
/**
* 删除未在上传中的附件,避免界面移除后网络请求仍继续造成状态失配。
* @param id - 待删除附件的本地唯一标识
*/
const removeAttachment = (id: string) => {
const target = attachments.value.find((attachment) => attachment.id === id);
if (target?.kind === 'local' && target.uploadStatus === 'uploading') return;
attachments.value = attachments.value.filter((a) => a.id !== id);
};
@@ -288,7 +297,14 @@ export function useChatAttachments(options: UseChatAttachmentsOptions) {
msg.warning(`该类型附件数量已达上限(${caps.limit})`);
continue;
}
attachments.value.push({ id: `${Date.now()}_${Math.random()}`, kind: 'local', file: f, type });
attachments.value.push({
id: `${Date.now()}_${Math.random()}`,
kind: 'local',
file: f,
type,
uploadStatus: 'waiting',
uploadProgress: 0,
});
}
if (inputEl) inputEl.value = '';
};
@@ -336,6 +352,12 @@ export function useChatAttachments(options: UseChatAttachmentsOptions) {
attachments.value.push({ id: `${Date.now()}_${Math.random()}`, kind: 'remote', url, type });
};
/**
* 将待发送附件转换为 Dify 文件参数,并逐个更新本地文件的真实上传状态。
* 核心逻辑:复用已成功上传的 uploadFileId;失败附件保留并在下次发送时重试。
* @returns 可直接传给聊天接口的文件参数列表
* @throws 任一本地附件上传失败时抛出原始错误,中止本次消息发送
*/
const buildFileSpecsForSend = async (): Promise<ChatUploadFileSpec[]> => {
if (!attachmentPolicy.value.anyEnabled) return [];
if (attachments.value.length === 0) return [];
@@ -348,11 +370,30 @@ export function useChatAttachments(options: UseChatAttachmentsOptions) {
isUploadingAttachments.value = true;
try {
for (const item of locals) {
const uploaded = await uploadChatFile(currentAgentId.value, item.file);
if (!uploaded?.id) {
throw new Error('Missing upload id');
if (item.uploadStatus === 'uploaded' && item.uploadFileId) {
specs.push({ type: item.type, transfer_method: 'local_file', upload_file_id: item.uploadFileId });
continue;
}
item.uploadStatus = 'uploading';
item.uploadProgress = 0;
item.errorMessage = undefined;
try {
const uploaded = await uploadChatFile(currentAgentId.value, item.file);
if (!uploaded?.id) {
throw new Error('Missing upload id');
}
item.uploadStatus = 'uploaded';
item.uploadProgress = 100;
item.uploadFileId = uploaded.id;
specs.push({ type: item.type, transfer_method: 'local_file', upload_file_id: uploaded.id });
} catch (error: unknown) {
item.uploadStatus = 'failed';
item.uploadProgress = 0;
item.uploadFileId = undefined;
item.errorMessage = error instanceof Error ? error.message : 'File upload failed';
throw error;
}
specs.push({ type: item.type, transfer_method: 'local_file', upload_file_id: uploaded.id });
}
} finally {
isUploadingAttachments.value = false;
@@ -370,6 +411,14 @@ export function useChatAttachments(options: UseChatAttachmentsOptions) {
attachments.value = [];
};
/**
* 固化当前待发送附件,供发送成功后的用户消息展示。
* @returns 与当前附件顺序一致、可 JSON 序列化的安全快照
*/
const createMessageAttachmentSnapshots = () => (
createChatMessageAttachmentSnapshots(attachments.value)
);
return {
attachments,
isUploadingAttachments,
@@ -378,6 +427,7 @@ export function useChatAttachments(options: UseChatAttachmentsOptions) {
handleLocalFilesSelected,
addRemoteUrlAttachment,
buildFileSpecsForSend,
createMessageAttachmentSnapshots,
clearAttachments,
};
}
@@ -415,6 +415,7 @@ export function useChatPage() {
attachments: attachmentApi.attachments,
allowsSendWithAttachmentsOnly: shipping.allowsSendWithAttachmentsOnly,
buildFileSpecsForSend: attachmentApi.buildFileSpecsForSend,
createMessageAttachmentSnapshots: attachmentApi.createMessageAttachmentSnapshots,
clearAttachments: attachmentApi.clearAttachments,
sendMessage,
getChatContext: shipping.isShippingNoticeAgent ? shipping.getCurrentShippingChatContext : undefined,
@@ -561,6 +562,12 @@ export function useChatPage() {
resolveShippingDuplicateDialog: shipping.resolveShippingDuplicateDialog,
removeShippingDuplicateDialogAttachment: shipping.removeShippingDuplicateDialogAttachment,
closeShippingDuplicateDialog: shipping.closeShippingDuplicateDialog,
showShippingCustomerDialog: shipping.showShippingCustomerDialog,
shippingCustomerOptions: shipping.shippingCustomerOptions,
shippingCustomerLoading: shipping.shippingCustomerLoading,
searchShippingCustomers: shipping.searchShippingCustomers,
confirmShippingCustomer: shipping.confirmShippingCustomer,
closeShippingCustomerDialog: shipping.closeShippingCustomerDialog,
filePreviewVisible,
previewFile,
previewFiles,
@@ -5,7 +5,12 @@
* 逻辑:覆盖 current focus、process summary 回退、首票回退与无任务时清空焦点原因四种路径。
*/
import { describe, expect, it } from 'vitest';
import { resolveShippingBatchFocusState } from './useChatShipping';
import {
resolveLatestShippingMessageRecoveryPayload,
resolveLatestShippingBatchSnapshot,
resolveShippingBatchFocusState,
selectShippingConversationBatch,
} from './useChatShipping';
describe('useChatShipping batch focus sync', () => {
it('prefers batch current focus task and keeps default reason', () => {
@@ -62,3 +67,84 @@ describe('useChatShipping batch focus sync', () => {
});
});
});
describe('useChatShipping conversation workspace selection', () => {
const batches = [
{ batch_no: 'SB-OLD', focus_task: { task_no: 'SN-OLD' } },
{ batch_no: 'SB-NEW', focus_task: { task_no: 'SN-NEW' } },
];
it('keeps the active batch during a normal refresh', () => {
expect(selectShippingConversationBatch(batches, 'SB-OLD', '', false)?.batch_no).toBe('SB-OLD');
});
it('selects the latest batch after an order extraction turn', () => {
expect(selectShippingConversationBatch(batches, 'SB-OLD', '', true)?.batch_no).toBe('SB-NEW');
});
});
describe('useChatShipping persisted batch snapshot', () => {
it('restores the latest valid batch snapshot from assistant message payloads', () => {
const snapshot = resolveLatestShippingBatchSnapshot([
{
role: 'assistant',
content: '旧结果',
payload: { shipping_batch_ui_state: { batch_no: 'SB-OLD', tasks: [] } },
},
{
role: 'assistant',
content: '无效结果',
payload: { shipping_batch_ui_state: { batch_no: 'SB-INVALID' } },
},
{
role: 'assistant',
content: '已打开已有任务',
payload: {
shipping_batch_ui_state: {
batch_no: 'SB-EXISTING',
current_focus_task_no: 'SN-EXISTING',
tasks: [{ task_no: 'SN-EXISTING', source_type: 'email', process_status: 'pending_review' }],
},
},
},
]);
expect(snapshot?.batch_no).toBe('SB-EXISTING');
expect(snapshot?.current_focus_task_no).toBe('SN-EXISTING');
});
it('ignores malformed snapshots', () => {
expect(resolveLatestShippingBatchSnapshot([
{ role: 'assistant', content: '', payload: { shipping_batch_ui_state: { batch_no: 'SB-NO-TASKS' } } },
{ role: 'user', content: '继续' },
])).toBeNull();
});
});
describe('useChatShipping message recovery payload', () => {
it('falls back to task anchor when batch snapshot is absent', () => {
const payload = resolveLatestShippingMessageRecoveryPayload([
{
role: 'assistant',
content: '已打开已有任务',
payload: {
task_no: 'SN-OPEN-EXISTING',
batch_no: 'SB-OPEN-EXISTING',
shipping_ui_state: {
task_no: 'SN-OPEN-EXISTING',
batch_no: 'SB-OPEN-EXISTING',
process_status: 'waiting_inventory',
steps: [],
summary: {},
action_buttons: [],
},
},
},
]);
expect(payload?.task_no).toBe('SN-OPEN-EXISTING');
expect(payload?.batch_no).toBe('SB-OPEN-EXISTING');
expect(payload?.shipping_ui_state?.task_no).toBe('SN-OPEN-EXISTING');
expect(payload?.shipping_batch_ui_state).toBeUndefined();
});
});
@@ -30,7 +30,6 @@ import {
createShippingSendHandlers,
createShippingUploadHandlers,
onNoticeBatchConversationChanging,
findHistorySessionForShippingTask,
findLatestShippingTaskId,
getShippingInventoryMappingPayload,
getShippingMatchResultPayload,
@@ -48,6 +47,8 @@ import {
getWorkspaceShippingConversationBatches,
getWorkspaceShippingBatch,
getWorkspaceShippingTask,
listWorkspaceShippingCustomerOptions,
confirmWorkspaceShippingCustomer,
switchWorkspaceShippingBatchFocusTask,
type ShippingBatchUiState,
type ShippingBatchSummary,
@@ -55,13 +56,15 @@ import {
type ShippingTaskDetail,
type ShippingTaskSummary,
} from '@/features/chat/api/shipping.api';
import type { ShippingCustomerOption } from '../types/shipping.api.types';
import { buildShippingQueryShortageTurn } from '../shipping/shippingTurnActions';
import {
hasShortageLines,
isShippingShortageQueryIntent,
} from '../shipping/shippingShortageDetails';
import type { ChatMessage, ChatRun, ChatSessionItem } from '../types/chat.types';
import type { ChatMessage, ChatRun, ChatSessionItem, ShippingMessageRecoveryPayload } from '../types/chat.types';
import type { SendMessageLifecycleHooks } from './useChat';
import type { ChatUploadFileSpec, PendingAttachment, ShippingActionButton } from '../types/shipping.types';
import type { ChatDeps } from './chat.deps';
import { listChatMessages } from '../api/chat.api';
@@ -94,8 +97,8 @@ export interface UseChatShippingOptions {
kb: string,
files: ChatUploadFileSpec[],
context?: { task_id?: string; batch_no?: string; shipping_intake_nos?: string[]; display_query?: string },
hooks?: { onAssistantMessageFinished?: (message: ChatMessage, runMessages: ChatMessage[]) => void | Promise<void> },
) => Promise<void>;
hooks?: SendMessageLifecycleHooks,
) => Promise<boolean | void>;
startChatTurn: (options: import('../types/chat-turn.types').StartChatTurnOptions) => Promise<boolean>;
buildFileSpecsForSend: () => Promise<ChatUploadFileSpec[]>;
loadConversation: (id: string, options?: { force?: boolean }) => Promise<void>;
@@ -130,6 +133,104 @@ export const resolveShippingBatchFocusState = (
};
};
/**
* 从会话工作台选择本轮应展示的批次。
* 核心逻辑:订单抽取完成后选服务端按创建时间升序返回的最后一个批次;普通续办优先保留当前批次。
*/
export const selectShippingConversationBatch = <T extends { batch_no: string; focus_task?: unknown }>(
batches: T[],
currentBatchNo: string,
queryBatchNo: string,
preferLatest = false,
): T | undefined => (
(preferLatest ? batches[batches.length - 1] : undefined)
|| batches.find((item) => item.batch_no === currentBatchNo)
|| (queryBatchNo ? batches.find((item) => item.batch_no === queryBatchNo) : undefined)
|| batches.find((item) => Boolean(item.focus_task))
|| batches[0]
);
/**
* 从消息列表解析最近一次权威批次快照。
* 核心逻辑:只接受包含批次号和任务数组的 `shipping_batch_ui_state`,供实时终态与历史会话共用。
* @param sourceMessages - 当前会话消息
* @returns 最近的合法批次快照;不存在时返回 null
*/
export const resolveLatestShippingBatchSnapshot = (
sourceMessages: ChatMessage[],
): ShippingBatchUiState | null => {
for (let index = sourceMessages.length - 1; index >= 0; index -= 1) {
const message = sourceMessages[index];
const payload = message?.payload && typeof message.payload === 'object'
? message.payload as Record<string, unknown>
: null;
const rawSnapshot = payload?.shipping_batch_ui_state;
if (!rawSnapshot || typeof rawSnapshot !== 'object') continue;
const snapshot = rawSnapshot as ShippingBatchUiState;
if (String(snapshot.batch_no || '').trim() && Array.isArray(snapshot.tasks)) {
return snapshot;
}
}
return null;
};
/**
* 从单条助手消息中提取工作台恢复锚点。
* 核心逻辑:优先识别合法 `shipping_batch_ui_state`,其次回退到 `task_no / batch_no / shipping_ui_state`;
* 供实时终态、历史回放与刷新恢复共用。
*/
export const resolveShippingMessageRecoveryPayload = (
message: ChatMessage | null | undefined,
): ShippingMessageRecoveryPayload | null => {
const payload = message?.payload && typeof message.payload === 'object'
? message.payload as ShippingMessageRecoveryPayload
: null;
if (!payload) return null;
const batchSnapshot = payload.shipping_batch_ui_state;
const hasBatchSnapshot = Boolean(
batchSnapshot
&& String(batchSnapshot.batch_no || '').trim()
&& Array.isArray(batchSnapshot.tasks),
);
const taskNo = String(
payload.task_no
|| payload.shipping_ui_state?.task_no
|| batchSnapshot?.current_focus_task_no
|| batchSnapshot?.focus_task?.task_no
|| batchSnapshot?.tasks?.[0]?.task_no
|| '',
).trim();
const batchNo = String(
payload.batch_no
|| payload.shipping_ui_state?.batch_no
|| batchSnapshot?.batch_no
|| '',
).trim();
const hasTaskUiState = Boolean(payload.shipping_ui_state && typeof payload.shipping_ui_state === 'object');
if (!hasBatchSnapshot && !taskNo && !batchNo && !hasTaskUiState) {
return null;
}
return {
...payload,
...(taskNo ? { task_no: taskNo } : {}),
...(batchNo ? { batch_no: batchNo } : {}),
};
};
/**
* 从消息列表中选择最近一条可恢复工作台的消息载荷。
* 核心逻辑:从后往前找最近的权威恢复锚点,允许 `open_existing` 只靠 `task_no/ui_state` 恢复。
*/
export const resolveLatestShippingMessageRecoveryPayload = (
sourceMessages: ChatMessage[],
): ShippingMessageRecoveryPayload | null => {
for (let index = sourceMessages.length - 1; index >= 0; index -= 1) {
const payload = resolveShippingMessageRecoveryPayload(sourceMessages[index]);
if (payload) return payload;
}
return null;
};
/**
* 组装发货通知聊天所需的状态、动作处理器与发送拦截逻辑。
*
@@ -163,7 +264,6 @@ export function useChatShipping(options: UseChatShippingOptions) {
sendMessage,
startChatTurn,
buildFileSpecsForSend,
loadConversation,
createNewChatView,
} = options;
@@ -280,34 +380,152 @@ export function useChatShipping(options: UseChatShippingOptions) {
}
};
const applyConversationWorkspaceFocus = (workspace: ShippingConversationWorkspace) => {
const applyConversationWorkspaceFocus = (
workspace: ShippingConversationWorkspace,
options?: { preferLatest?: boolean },
) => {
const batches = Array.isArray(workspace.batches) ? workspace.batches : [];
if (!batches.length) return;
const queryBatchNo = String(shippingBatchNoFromQuery.value || '').trim();
const currentBatchNo = String(activeShippingBatchNo.value || resolvedShippingBatchNo.value || queryBatchNo || '').trim();
const selectedBatch = batches.find((item) => item.batch_no === currentBatchNo)
|| (queryBatchNo ? batches.find((item) => item.batch_no === queryBatchNo) : null)
|| batches.find((item) => item.focus_task?.task_no)
|| batches[0];
const selectedBatch = selectShippingConversationBatch(
batches,
currentBatchNo,
queryBatchNo,
Boolean(options?.preferLatest),
);
if (!selectedBatch) return;
if (options?.preferLatest) {
activeShippingBatchNo.value = selectedBatch.batch_no;
}
applyShippingBatchDetail(selectedBatch, selectedBatch.batch_no);
};
const syncShippingConversationWorkspace = async () => {
const syncShippingConversationWorkspace = async (
options?: { preferLatest?: boolean },
): Promise<boolean> => {
const localConversationId = String(conversationId.value || '').trim();
if (!localConversationId || !isShippingNoticeAgent.value) {
shippingConversationWorkspace.value = null;
return;
return false;
}
try {
const workspace = await getWorkspaceShippingConversationBatches(localConversationId);
shippingConversationWorkspace.value = workspace;
applyConversationWorkspaceFocus(workspace);
applyConversationWorkspaceFocus(workspace, options);
return true;
} catch {
shippingConversationWorkspace.value = null;
return false;
}
};
/**
* 从本轮 SSE 助手消息恢复权威批次快照。
*
* 核心逻辑:订单识别可能打开属于旧会话的已有任务,此时按当前会话补拉工作台会返回空批次;
* 优先应用 `shipping_ui_state` 事件随消息持久化的 `shipping_batch_ui_state`,再由接口刷新后续状态。
* @param message - 当前流式回答完成后的助手消息
* @returns 是否找到并应用了合法批次快照
*/
const applyResolvedShippingBatchSnapshot = (snapshot: ShippingBatchUiState | null): boolean => {
if (!snapshot) return false;
const batchNo = String(snapshot.batch_no || '').trim();
applyShippingBatchDetail(snapshot, batchNo);
return true;
};
const applyShippingBatchSnapshot = (message: ChatMessage): boolean => (
applyResolvedShippingBatchSnapshot(resolveLatestShippingBatchSnapshot([message]))
);
/**
* 按“批次快照 -> 任务/批次锚点 -> 会话工作台”顺序恢复聊天工作台。
*
* 核心逻辑:`open_existing` 可能只携带 `task_no / shipping_ui_state`;此时先恢复任务锚点并补拉任务详情,
* 再尝试按任务所属批次加载批次详情,最后才回退到当前会话工作台。
* @param payload - 从消息中解析出的恢复载荷
* @returns 是否至少恢复出一层任务或批次上下文
*/
const applyResolvedShippingMessageRecovery = async (
payload: ShippingMessageRecoveryPayload | null,
): Promise<boolean> => {
if (!payload) return false;
let recovered = false;
const snapshot = payload.shipping_batch_ui_state ?? null;
if (applyResolvedShippingBatchSnapshot(snapshot)) {
recovered = true;
}
const taskNo = String(
payload.task_no
|| payload.shipping_ui_state?.task_no
|| '',
).trim().toUpperCase();
let batchNo = String(
payload.batch_no
|| payload.shipping_ui_state?.batch_no
|| snapshot?.batch_no
|| '',
).trim();
if (batchNo) {
resolvedShippingBatchNo.value = batchNo;
activeShippingBatchNo.value = batchNo;
}
if (taskNo) {
resolvedShippingTaskId.value = taskNo;
focusedShippingTaskNo.value = taskNo;
if (!shippingFocusReason.value) {
shippingFocusReason.value = t('chat.shippingNoticeUi.currentFocusDefaultReason');
}
}
if (payload.shipping_ui_state && taskNo) {
activeShippingTaskDetail.value = {
...(activeShippingTaskDetail.value || {}),
task_no: taskNo,
batch_no: batchNo || payload.shipping_ui_state.batch_no || null,
lines: activeShippingTaskDetail.value?.lines || [],
events: activeShippingTaskDetail.value?.events || [],
ui_state: payload.shipping_ui_state,
} as ShippingTaskDetail;
recovered = true;
}
if (!snapshot && batchNo) {
try {
const detail = await getWorkspaceShippingBatch(batchNo);
applyShippingBatchDetail(detail, batchNo);
recovered = true;
} catch {
// ignore and continue with task-first recovery
}
}
if (taskNo) {
await syncActiveShippingTaskDetail(taskNo);
const detailBatchNo = String(activeShippingTaskDetail.value?.batch_no || '').trim();
if (detailBatchNo) {
batchNo = detailBatchNo;
resolvedShippingBatchNo.value = detailBatchNo;
activeShippingBatchNo.value = detailBatchNo;
}
if (!snapshot && batchNo && String(shippingBatchSummary.value?.batch_no || '').trim() !== batchNo) {
try {
const detail = await getWorkspaceShippingBatch(batchNo);
applyShippingBatchDetail(detail, batchNo);
recovered = true;
} catch {
// ignore and keep task-only recovery
}
}
recovered = recovered || Boolean(activeShippingTaskDetail.value);
}
return recovered || Boolean(batchNo);
};
const applyShippingMessageRecovery = async (message: ChatMessage): Promise<boolean> => (
applyResolvedShippingMessageRecovery(resolveShippingMessageRecoveryPayload(message))
);
const switchShippingFocusTask = async (taskNo: string) => {
const batchNo = getActiveShippingBatchNo();
const normalizedTaskNo = String(taskNo || '').trim().toUpperCase();
@@ -529,7 +747,6 @@ export function useChatShipping(options: UseChatShippingOptions) {
messages,
conversationId,
isThinking,
history,
resolvedShippingTaskId,
shippingTaskIdFromQuery,
getActiveBatchTaskId,
@@ -563,6 +780,10 @@ export function useChatShipping(options: UseChatShippingOptions) {
const finalizeShippingAssistantMessage = async () => {
if (!isShippingNoticeAgent.value) return;
await shippingIntakes.refreshStatuses();
if (!(await syncShippingConversationWorkspace())) {
await new Promise((resolve) => setTimeout(resolve, 300));
await syncShippingConversationWorkspace();
}
shippingIntakes.clearConsumedAttachments();
await refreshShippingActions();
};
@@ -672,6 +893,10 @@ export function useChatShipping(options: UseChatShippingOptions) {
});
const showShippingDuplicateDialog = ref(false);
const showShippingCustomerDialog = ref(false);
const shippingCustomerDialogTaskId = ref('');
const shippingCustomerOptions = ref<ShippingCustomerOption[]>([]);
const shippingCustomerLoading = ref(false);
const shippingDuplicateAttachmentId = ref<string | null>(null);
const shippingDuplicateAttachment = computed(() => {
const id = shippingDuplicateAttachmentId.value;
@@ -733,6 +958,50 @@ export function useChatShipping(options: UseChatShippingOptions) {
shippingDuplicateAttachmentId.value = null;
};
/** 打开客户确认对话框并加载启用标准客户。 */
const openShippingCustomerDialog = async (taskId: string): Promise<void> => {
shippingCustomerDialogTaskId.value = String(taskId || '').trim().toUpperCase();
showShippingCustomerDialog.value = true;
shippingCustomerLoading.value = true;
try {
shippingCustomerOptions.value = await listWorkspaceShippingCustomerOptions();
} catch (error: unknown) {
shippingCustomerOptions.value = [];
msg.warning(error instanceof Error ? error.message : t('chat.shippingCustomer.loadFailed'));
} finally {
shippingCustomerLoading.value = false;
}
};
/** 按关键词刷新客户选项。 */
const searchShippingCustomers = async (query: string): Promise<void> => {
shippingCustomerLoading.value = true;
try {
shippingCustomerOptions.value = await listWorkspaceShippingCustomerOptions(query);
} catch (error: unknown) {
msg.warning(error instanceof Error ? error.message : t('chat.shippingCustomer.loadFailed'));
} finally {
shippingCustomerLoading.value = false;
}
};
/** 确认客户后刷新任务详情与动作菜单;业务号仍由后续阶段生成。 */
const confirmShippingCustomer = async (customerId: number): Promise<void> => {
const taskId = shippingCustomerDialogTaskId.value;
if (!taskId) return;
shippingCustomerLoading.value = true;
try {
await confirmWorkspaceShippingCustomer(taskId, customerId);
showShippingCustomerDialog.value = false;
await Promise.all([syncActiveShippingTaskDetail(taskId), refreshShippingActions()]);
msg.success(t('chat.shippingCustomer.confirmed'));
} catch (error: unknown) {
msg.warning(error instanceof Error ? error.message : t('chat.shippingCustomer.confirmFailed'));
} finally {
shippingCustomerLoading.value = false;
}
};
/** 更新 Candidate 选择状态,并将 API 失败统一反馈给用户。 */
const setShippingCandidateSelected = async (candidateNo: string, selected: boolean) => {
try {
@@ -825,6 +1094,7 @@ export function useChatShipping(options: UseChatShippingOptions) {
openShippingInventoryMappingFormForTask,
openShippingInventoryPicker,
openShippingNoticePicker,
openShippingCustomerDialog,
executeShippingDecision,
executeShippingManualUpload,
refreshShippingActions,
@@ -870,8 +1140,13 @@ export function useChatShipping(options: UseChatShippingOptions) {
hasSelectedNoticeCandidates: () => shippingIntakes.getSelectedCandidateNos().length > 0,
openShippingDuplicateDialog,
getParsedIntakeNos: shippingIntakes.getParsedIntakeNos,
markOrderExtractionStarted: shippingIntakes.markOrderExtractionStarted,
rollbackOrderExtractionStarted: shippingIntakes.rollbackOrderExtractionStarted,
refreshNoticeIntakeStatuses: shippingIntakes.refreshStatuses,
clearConsumedNoticeAttachments: shippingIntakes.clearConsumedAttachments,
applyShippingMessageRecovery,
applyShippingBatchSnapshot,
syncShippingConversationWorkspace,
refreshShippingActions,
shippingSuggestedPrompt,
isShippingShortageQueryIntent,
@@ -881,6 +1156,12 @@ export function useChatShipping(options: UseChatShippingOptions) {
});
// ── 路由 / 会话生命周期 ───────────────────────────────────
/**
* 根据路由中的 `task_id/batch_no` 恢复发货任务上下文。
* 核心逻辑:优先同步显式传入的批次摘要;若仍缺少会话,则直接基于 `task_id` 发起一次继续任务请求,
* 禁止再按历史标题模糊猜测旧会话,避免多批次/多票场景跳进错误会话。
* @returns Promise<void>
*/
const resumeShippingTaskFromQuery = async () => {
const batchNo = shippingBatchNoFromQuery.value;
if (batchNo && isShippingNoticeAgent.value) {
@@ -894,11 +1175,6 @@ export function useChatShipping(options: UseChatShippingOptions) {
if (route.query.conversation_id) return;
if (presetQuestion.value) return;
if (autoResumedShippingTasks.value[taskId]) return;
const existing = findHistorySessionForShippingTask(history.value, taskId);
if (existing) {
await loadConversation(existing.conversation_id, { force: true });
return;
}
autoResumedShippingTasks.value[taskId] = true;
const displayText = t('chat.shippingNoticeUi.retrySingleTaskMessage', { taskId });
await sendMessage(
@@ -1010,6 +1286,8 @@ export function useChatShipping(options: UseChatShippingOptions) {
kind: 'local',
file,
type: kind === 'inventory' ? 'document' : 'document',
uploadStatus: 'waiting',
uploadProgress: 0,
},
];
}
@@ -1089,6 +1367,23 @@ export function useChatShipping(options: UseChatShippingOptions) {
String(last?.content || '').slice(-120),
].join('|');
});
const shippingRecoveryWatchKey = computed(() => {
const recovery = resolveLatestShippingMessageRecoveryPayload(messages.value);
const snapshot = recovery?.shipping_batch_ui_state;
const uiState = recovery?.shipping_ui_state;
return [
String(conversationId.value || ''),
String(recovery?.batch_no || snapshot?.batch_no || uiState?.batch_no || ''),
String(recovery?.task_no || snapshot?.current_focus_task_no || uiState?.task_no || ''),
String(snapshot?.updated_at || ''),
String(uiState?.updated_at || ''),
String(snapshot?.tasks.length || 0),
].join('|');
});
watch([shippingRecoveryWatchKey, isShippingNoticeAgent], () => {
if (!isShippingNoticeAgent.value) return;
void applyResolvedShippingMessageRecovery(resolveLatestShippingMessageRecoveryPayload(messages.value));
}, { immediate: true });
watch([shippingActionsWatchKey, isThinking, isShippingNoticeAgent, () => currentAgent.value?.name], () => {
void refreshShippingActions().then(async () => {
const taskId = getActiveBatchTaskId() || getActiveShippingTaskId();
@@ -1188,6 +1483,14 @@ export function useChatShipping(options: UseChatShippingOptions) {
updateShippingCandidateSummary,
resolveShippingCandidateDuplicate,
showShippingDuplicateDialog,
showShippingCustomerDialog,
shippingCustomerOptions,
shippingCustomerLoading,
searchShippingCustomers,
confirmShippingCustomer,
closeShippingCustomerDialog: () => {
showShippingCustomerDialog.value = false;
},
shippingDuplicateAttachment,
canForceCreateShippingDuplicate,
openShippingDuplicateDialog,
@@ -9,7 +9,10 @@ import { getAuthHeaders } from '@/shared/utils/auth';
import { applyStreamErrorToMessage, type StreamErrorLabels } from '../utils/streamErrorMessage';
import type { StartChatTurnOptions } from '../types/chat-turn.types';
import type { ChatMessage, ChatRun } from '../types/chat.types';
import { applyShippingUiStateToMessage } from './useChat';
import {
applyShippingOrderExtractionStateToMessage,
applyShippingUiStateToMessage,
} from './useChat';
export interface CreateStartChatTurnOptions {
messages: Ref<ChatMessage[]>;
@@ -169,6 +172,9 @@ export function createStartChatTurn(options: CreateStartChatTurnOptions) {
if (eventName === 'shipping_ui_state' || eventName === 'ui_state.updated') {
const botMsg = ensureBotMessage();
if (botMsg) applyShippingUiStateToMessage(botMsg, data);
} else if (eventName === 'shipping_order_extraction_state') {
const botMsg = ensureBotMessage();
if (botMsg) applyShippingOrderExtractionStateToMessage(botMsg, data);
} else if (
eventName === 'message'
|| eventName === 'agent_message'
@@ -36,6 +36,7 @@ vi.mock('../shipping/shippingNoticeBatchIdempotency', () => ({
const createConversationContext = () => {
const conversationId = ref<string | null>('conv-a');
const messages = ref([]);
const loadConversationState = vi.fn();
const createNewChatView = vi.fn(() => {
conversationId.value = null;
messages.value = [];
@@ -44,6 +45,7 @@ const createConversationContext = () => {
return {
conversationId,
messages,
loadConversationState,
createNewChatView,
api: createChatPageConversationApi({
deps: { t: (key: string) => key, msg: { warning: vi.fn() } },
@@ -54,7 +56,7 @@ const createConversationContext = () => {
activeRunId: ref(null),
messages,
isThinking: ref(false),
loadConversationState: vi.fn(),
loadConversationState,
createNewChatView,
clearPendingNoticeBatchRetry,
onConversationIdChanging: vi.fn(),
@@ -163,4 +165,32 @@ describe('useChatPageConversation', () => {
expect(secondKey).toBeTruthy();
expect(secondKey).not.toBe(firstKey);
});
it('loadConversation keeps attachment-only history snapshots intact', async () => {
const { api, loadConversationState } = createConversationContext();
listChatMessages.mockResolvedValue([{
role: 'user',
content: '',
attachments: [{
id: 'attachment-only-1',
name: 'notice.eml',
type: 'document',
source: 'shipping_notice',
}],
}]);
await api.loadConversation('conv-attachment-only', { force: true });
expect(listChatMessages).toHaveBeenCalledWith('conv-attachment-only', 42);
expect(loadConversationState).toHaveBeenCalledWith('conv-attachment-only', [{
role: 'user',
content: '',
attachments: [{
id: 'attachment-only-1',
name: 'notice.eml',
type: 'document',
source: 'shipping_notice',
}],
}]);
});
});
@@ -0,0 +1,87 @@
/**
* features/chat/page/useChatPageMarkdown.spec.ts
* 用途:验证聊天消息可见性与思考提示在订单识别生命周期中的切换行为。
* 依赖:Vitest、Vue 响应式 API、useChatPageMarkdown。
* 逻辑:构造最小 Markdown 上下文,确保空正文的订单识别状态可见且替代通用思考提示。
*/
import { ref } from 'vue';
import { describe, expect, it } from 'vitest';
import type { ChatMessage } from '../types/chat.types';
import {
createChatPageMarkdownApi,
type ChatPageMarkdownContext,
} from './useChatPageMarkdown';
/**
* 创建消息可见性测试所需的最小 Markdown 上下文。
* 核心逻辑:所有外部解析器返回空结果,让断言只受消息正文和订单识别状态影响。
* @param messages - 当前聊天消息列表。
* @param isThinking - 是否仍在等待助手回复。
* @returns 可直接传给 createChatPageMarkdownApi 的上下文。
*/
function createContext(
messages: ChatMessage[],
isThinking = true,
): ChatPageMarkdownContext {
return {
messages: ref(messages),
isThinking: ref(isThinking),
prepareMarkdownDisplayText: (text) => text,
handleLeaveMarkdownClick: () => undefined,
parsePlmPreviewLink: () => null,
openPreview: async () => undefined,
openAssetHistory: () => undefined,
openAssetImage: () => undefined,
getMessageLinks: () => [],
getDisplayRetrieverResources: () => [],
getSourceLinks: () => [],
shouldExpandSourceDetails: () => false,
getSourceTitle: () => '',
getSourceMeta: () => '',
getSourceBrief: () => '',
getShippingInventoryMappingPayload: () => null,
getShippingMatchResultPayload: () => null,
canOpenQueryPreview: () => false,
getQueryPreviewSummary: () => '',
openQueryPreviewDialog: () => undefined,
shippingActionButtonClass: () => '',
onShippingActionClick: () => undefined,
};
}
const extractionMessage: ChatMessage = {
role: 'assistant',
content: '',
shipping_order_extraction_state: {
status: 'extracting',
phase: 'llm_extraction',
message: '正在识别邮件及附件中的订单',
created_count: 0,
opened_existing_count: 0,
pending_count: 0,
non_shipping_count: 0,
created_with_missing_fields_count: 0,
batch_no: null,
terminal: false,
},
};
describe('useChatPageMarkdown order extraction visibility', () => {
it('renders an extraction-state message before Dify content arrives', () => {
const api = createChatPageMarkdownApi(createContext([]));
// 关键断言:结构化进度不能因为 assistant 正文为空而被消息过滤器隐藏。
expect(api.shouldRenderMessage(extractionMessage)).toBe(true);
expect(api.shouldRenderMessage({ role: 'assistant', content: '' })).toBe(false);
});
it('hides the generic thinking bubble when extraction progress is visible', () => {
const api = createChatPageMarkdownApi(createContext([
{ role: 'user', content: '请解析当前邮件中的发货订单' },
extractionMessage,
]));
// 关键断言:领域进度已出现时不再叠加通用“思考中”,避免重复反馈。
expect(api.shouldShowThinkingBubble.value).toBe(false);
});
});
@@ -338,10 +338,18 @@ function enhanceAssetHistoryTableLinks(html: string): string {
export function createChatPageMarkdownApi(ctx: ChatPageMarkdownContext) {
const message = useMessage();
/**
* 判断消息是否具备可展示内容。
* 核心逻辑:订单识别状态本身就是用户可见反馈,即使 Dify 正文尚未到达也必须渲染;
* 其余消息继续沿用正文、链接、引用源和结构化消息的既有判断。
* @param msgItem - 当前聊天消息。
* @returns 消息是否应进入聊天列表渲染。
*/
const shouldRenderMessage = (msgItem: ChatMessage): boolean => {
if (msgItem?.role === 'user') return true;
if (msgItem?.type === 'shipping-parse-review') return false;
if (msgItem?.type === 'leave-form' || msgItem?.type === 'leave-confirmation' || msgItem?.type === 'leave-result') return true;
if (msgItem?.shipping_order_extraction_state) return true;
const content = (msgItem?.content || '').trim();
if (content) return true;
if (ctx.getMessageLinks(msgItem as unknown as Record<string, unknown>).length > 0) return true;
@@ -356,6 +364,7 @@ export function createChatPageMarkdownApi(ctx: ChatPageMarkdownContext) {
*/
const hasMeaningfulAssistantReply = (msgItem: ChatMessage): boolean => {
if (msgItem?.role !== 'assistant') return false;
if (msgItem?.shipping_order_extraction_state) return true;
if (msgItem?.type === 'leave-form'
|| msgItem?.type === 'leave-confirmation'
|| msgItem?.type === 'leave-result'
@@ -0,0 +1,121 @@
/**
* features/chat/page/useChatPageSend.spec.ts
* 用途:验证普通聊天发送时附件失败保留、消息成功后清空的恢复语义。
* 依赖:Vitest、Vue 响应式 API、useChatPageSend。
* 逻辑:构造最小发送上下文,分别模拟上传失败、SSE 发送失败与发送成功。
*/
import { computed, ref } from 'vue';
import { describe, expect, it, vi } from 'vitest';
import { createChatPageSendApi, type ChatPageSendContext } from './useChatPageSend';
import type { ChatMessageAttachment } from '../types/chat.types';
const attachmentSnapshots: ChatMessageAttachment[] = [{
id: 'attachment-1',
name: 'purchase-order.pdf',
size: 3,
extension: 'pdf',
type: 'document',
source: 'local',
}];
/** 创建普通聊天发送测试上下文。 */
function createContext(overrides: Partial<ChatPageSendContext> = {}): ChatPageSendContext {
return {
input: ref('请分析附件'),
messages: ref([]),
isThinking: ref(false),
currentAgentId: computed(() => 1),
selectedKb: ref(''),
isUploadingAttachments: ref(false),
attachmentPolicy: computed(() => ({ anyEnabled: true })),
attachments: ref([{ id: 'attachment-1' }]),
allowsSendWithAttachmentsOnly: computed(() => true),
buildFileSpecsForSend: vi.fn(async () => [
{ type: 'document', transfer_method: 'local_file', upload_file_id: 'upload-1' },
]),
createMessageAttachmentSnapshots: vi.fn(() => attachmentSnapshots.map((item) => ({ ...item }))),
clearAttachments: vi.fn(),
sendMessage: vi.fn(async () => true),
refreshHistoryAfterSend: vi.fn(async () => undefined),
refreshConversationAfterSend: vi.fn(async () => undefined),
tryHandleShippingAttachmentAutoFlow: vi.fn(async () => false),
tryHandleLeaveSend: vi.fn(() => false),
tryHandleShippingSend: vi.fn(async () => false),
refreshToolRunProgressAfterSend: vi.fn(async () => undefined),
prepareToolRunProgressBeforeSend: vi.fn(async () => undefined),
msg: { warning: vi.fn(), info: vi.fn() },
t: (key: string) => key,
copiedIndex: ref(null),
...overrides,
};
}
describe('createChatPageSendApi attachment lifecycle', () => {
it('keeps attachments when file upload fails', async () => {
const ctx = createContext({
buildFileSpecsForSend: vi.fn(async () => { throw new Error('upload failed'); }),
});
await createChatPageSendApi(ctx).handleSend();
expect(ctx.clearAttachments).not.toHaveBeenCalled();
expect(ctx.sendMessage).not.toHaveBeenCalled();
});
it('keeps uploaded attachments when message sending fails', async () => {
const ctx = createContext({
sendMessage: vi.fn(async () => { throw new Error('stream failed'); }),
});
await expect(createChatPageSendApi(ctx).handleSend()).rejects.toThrow('stream failed');
expect(ctx.clearAttachments).not.toHaveBeenCalled();
});
it('keeps uploaded attachments when the real send result reports failure', async () => {
const ctx = createContext({
sendMessage: vi.fn(async () => false),
});
await createChatPageSendApi(ctx).handleSend();
expect(ctx.clearAttachments).not.toHaveBeenCalled();
expect(ctx.refreshHistoryAfterSend).not.toHaveBeenCalled();
});
it('clears attachments only after message sending succeeds', async () => {
const ctx = createContext();
await createChatPageSendApi(ctx).handleSend();
expect(ctx.sendMessage).toHaveBeenCalledOnce();
expect(ctx.sendMessage).toHaveBeenCalledWith(
'请分析附件',
1,
'',
[{ type: 'document', transfer_method: 'local_file', upload_file_id: 'upload-1' }],
undefined,
expect.objectContaining({ userAttachments: attachmentSnapshots }),
);
expect(ctx.clearAttachments).toHaveBeenCalledOnce();
expect(vi.mocked(ctx.sendMessage).mock.invocationCallOrder[0]).toBeLessThan(
vi.mocked(ctx.clearAttachments).mock.invocationCallOrder[0],
);
});
it('sends attachment-only messages with an internal prompt and an empty display query', async () => {
const ctx = createContext({ input: ref('') });
await createChatPageSendApi(ctx).handleSend();
expect(ctx.sendMessage).toHaveBeenCalledWith(
'chat.attachment.defaultPrompt',
1,
'',
[{ type: 'document', transfer_method: 'local_file', upload_file_id: 'upload-1' }],
{ display_query: '' },
expect.objectContaining({ userAttachments: attachmentSnapshots }),
);
expect(ctx.clearAttachments).toHaveBeenCalledOnce();
});
});
@@ -1,10 +1,14 @@
/**
* 对话页:发送消息编排(出货/请假前置拦截 → Dify SSE)、复制与重新生成。
* features/chat/page/useChatPageSend.ts
* 用途:编排聊天消息发送、业务前置拦截、复制与重新生成。
* 依赖:统一 BusinessError、剪贴板工具、Chat 消息与附件参数类型。
* 逻辑:附件上传成功后调用 Dify SSE;仅在消息发送成功后清空附件,失败时保留供重试。
*/
import { computed } from 'vue';
import { BusinessError } from '@/shared/api/client';
import { copyTextToClipboard } from '@/shared/utils/clipboard';
import type { ChatMessage } from '../types/chat.types';
import type { ChatMessage, ChatMessageAttachment } from '../types/chat.types';
import type { SendMessageLifecycleHooks } from '../composables/useChat';
import type { ChatUploadFileSpec } from '../types/shipping.types';
import type { ComputedRef, Ref } from 'vue';
@@ -42,6 +46,7 @@ export interface ChatPageSendContext {
attachments: Ref<unknown[]>;
allowsSendWithAttachmentsOnly: ComputedRef<boolean>;
buildFileSpecsForSend: () => Promise<ChatUploadFileSpec[]>;
createMessageAttachmentSnapshots: () => ChatMessageAttachment[];
clearAttachments: () => void;
sendMessage: (
content: string,
@@ -49,8 +54,8 @@ export interface ChatPageSendContext {
kb: string,
files: ChatUploadFileSpec[],
context?: { task_id?: string; batch_no?: string; shipping_intake_nos?: string[]; display_query?: string },
hooks?: { onAssistantMessageFinished?: (message: ChatMessage, runMessages: ChatMessage[]) => void | Promise<void> },
) => Promise<void>;
hooks?: SendMessageLifecycleHooks,
) => Promise<boolean | void>;
refreshHistoryAfterSend: () => Promise<void>;
refreshConversationAfterSend?: () => Promise<void>;
tryHandleShippingAttachmentAutoFlow: (
@@ -78,6 +83,11 @@ export function createChatPageSendApi(ctx: ChatPageSendContext) {
const allowSendWhileThinking = canContinueSendWhileThinking(ctx.messages.value);
if (ctx.isUploadingAttachments.value) return false;
if (ctx.input.value.trim()) return !ctx.isThinking.value || allowSendWhileThinking;
if (
ctx.attachments.value.length > 0
&& ctx.attachmentPolicy.value.anyEnabled
&& (!ctx.isThinking.value || allowSendWhileThinking)
) return true;
if (ctx.allowsSendWithAttachmentsOnly.value) return true;
return false;
});
@@ -85,11 +95,12 @@ export function createChatPageSendApi(ctx: ChatPageSendContext) {
const handleSend = async (textOrEvent?: string | Event) => {
const content = (typeof textOrEvent === 'string' ? textOrEvent : null) || ctx.input.value;
const trimmed = content.trim();
const hasAttachments = ctx.attachmentPolicy.value.anyEnabled && ctx.attachments.value.length > 0;
const allowSendWhileThinking = canContinueSendWhileThinking(ctx.messages.value);
if (await ctx.tryHandleShippingAttachmentAutoFlow(textOrEvent, content, trimmed)) {
return;
}
if (!trimmed || ctx.isUploadingAttachments.value || (ctx.isThinking.value && !allowSendWhileThinking)) {
if ((!trimmed && !hasAttachments) || ctx.isUploadingAttachments.value || (ctx.isThinking.value && !allowSendWhileThinking)) {
return;
}
if (ctx.tryHandleLeaveSend(content)) {
@@ -100,9 +111,11 @@ export function createChatPageSendApi(ctx: ChatPageSendContext) {
}
let files: ChatUploadFileSpec[] = [];
let messageAttachments: ChatMessageAttachment[] = [];
if (ctx.attachmentPolicy.value.anyEnabled && ctx.attachments.value.length > 0) {
try {
files = await ctx.buildFileSpecsForSend();
messageAttachments = ctx.createMessageAttachmentSnapshots();
} catch (e: unknown) {
let suffix = '';
if (e instanceof BusinessError) {
@@ -121,17 +134,26 @@ export function createChatPageSendApi(ctx: ChatPageSendContext) {
}
if (typeof textOrEvent !== 'string') ctx.input.value = '';
ctx.clearAttachments();
const requestContent = trimmed || ctx.t('chat.attachment.defaultPrompt');
const sendContext = {
...(ctx.getChatContext?.() || {}),
...(!trimmed && messageAttachments.length > 0 ? { display_query: '' } : {}),
};
await ctx.prepareToolRunProgressBeforeSend();
await ctx.sendMessage(
content,
const sent = await ctx.sendMessage(
requestContent,
ctx.currentAgentId.value,
ctx.selectedKb.value,
files,
ctx.getChatContext?.(),
{ onAssistantMessageFinished: ctx.onAssistantMessageFinished },
Object.keys(sendContext).length > 0 ? sendContext : undefined,
{
userAttachments: messageAttachments,
onAssistantMessageFinished: ctx.onAssistantMessageFinished,
},
);
if (sent === false) return;
ctx.clearAttachments();
await ctx.refreshHistoryAfterSend();
await ctx.refreshConversationAfterSend?.();
await ctx.refreshToolRunProgressAfterSend();
@@ -21,7 +21,7 @@ export interface ShippingConversationContext {
kb: string,
files: ChatUploadFileSpec[],
context?: { task_id?: string; batch_no?: string; display_query?: string },
) => Promise<void>;
) => Promise<boolean | void>;
}
/** 发送菜单类消息后,若当前会话尚未出现在侧栏历史中则刷新列表 */
@@ -1,11 +1,10 @@
/**
* features/chat/shipping/shippingTaskId.ts
* 用途:从消息或会话历史中识别发货任务编号(SN- 格式)。
* 用途:从聊天消息中识别发货任务编号(SN- 格式)。
* 依赖:constants/shipping.SHIPPING_TASK_ID_RE、chat.types。
* 逻辑:useChatShipping 切换任务/恢复会话时调用。
* 逻辑:useChatShipping 与 shipping refresh 只把这里作为消息级兜底,不再承担历史标题猜测。
*/
import { SHIPPING_TASK_ID_RE } from '../constants/shipping';
import type { ChatSessionItem } from '../types/chat.types';
/** 从消息列表倒序查找最近出现的 SN- 任务编号。 */
export function findLatestShippingTaskId(msgs: Array<{ content?: string }>): string {
@@ -15,13 +14,3 @@ export function findLatestShippingTaskId(msgs: Array<{ content?: string }>): str
}
return '';
}
/** 在侧栏历史中按标题模糊匹配含 taskId 的会话。 */
export function findHistorySessionForShippingTask(
history: ChatSessionItem[],
taskId: string,
): ChatSessionItem | null {
const needle = taskId.trim().toUpperCase();
if (!needle) return null;
return history.find((item) => String(item.title || '').toUpperCase().includes(needle)) || null;
}
@@ -23,6 +23,7 @@ export interface ShippingMenuHandlerContext {
openShippingInventoryMappingFormForTask: (taskId: string) => Promise<boolean>;
openShippingInventoryPicker: (taskId?: string) => boolean;
openShippingNoticePicker: (taskId?: string) => boolean;
openShippingCustomerDialog: (taskId: string) => Promise<void>;
executeShippingDecision: (
decision: string,
displayText?: string,
@@ -142,6 +143,15 @@ export function createShippingMenuHandlers(ctx: ShippingMenuHandlerContext) {
}
return;
}
if (action.id === 'confirm_customer') {
const taskId = resolveTaskId();
if (!taskId) {
ctx.msg.warning(ctx.t('chat.shippingNoticeMissingTaskId'));
return;
}
await ctx.openShippingCustomerDialog(taskId);
return;
}
const chatTurnActionIds = new Set([
'generate_excel',
@@ -21,13 +21,12 @@ describe('useChatShippingRefresh', () => {
getWorkspaceShippingTaskUiState.mockReset();
});
it('prefers current batch focus task over message and history fallbacks', () => {
it('prefers current batch focus task over other explicit anchors', () => {
expect(resolvePreferredShippingTaskId({
batchTaskId: 'sn-batch-001',
messageTaskId: 'sn-message-001',
resolvedTaskId: 'sn-resolved-001',
queryTaskId: 'sn-query-001',
historyTaskId: 'sn-history-001',
})).toBe('SN-BATCH-001');
});
@@ -37,7 +36,6 @@ describe('useChatShippingRefresh', () => {
messageTaskId: '',
resolvedTaskId: '',
queryTaskId: '',
historyTaskId: '',
})).toBe('');
});
@@ -88,7 +86,6 @@ describe('useChatShippingRefresh', () => {
messages,
conversationId: ref('conv-focus-switch'),
isThinking: ref(false),
history: ref([]),
resolvedShippingTaskId,
shippingTaskIdFromQuery: computed(() => ''),
getActiveBatchTaskId: () => 'SN-FOCUS-B',
@@ -159,7 +156,6 @@ describe('useChatShippingRefresh', () => {
messages,
conversationId: ref('conv-source'),
isThinking: ref(false),
history: ref([]),
resolvedShippingTaskId: ref('SN-SOURCE-001'),
shippingTaskIdFromQuery: computed(() => ''),
getActiveBatchTaskId: () => 'SN-SOURCE-001',
@@ -170,4 +166,27 @@ describe('useChatShippingRefresh', () => {
expect(messages.value[0].shipping_actions?.map((item) => item.id)).toEqual(['download_excel']);
expect(messages.value[0].shipping_ui_state?.action_buttons?.map((item) => item.id)).toEqual(['download_excel']);
});
it('does not guess a task id from history metadata when no explicit anchor exists', async () => {
const messages = ref([
{
role: 'assistant' as const,
content: '请继续处理当前任务',
},
]);
const { refreshShippingActions } = createShippingActionsRefresher({
isShippingNoticeAgent: computed(() => true),
messages,
conversationId: ref('conv-no-anchor'),
isThinking: ref(false),
resolvedShippingTaskId: ref(''),
shippingTaskIdFromQuery: computed(() => ''),
getActiveBatchTaskId: () => '',
});
await refreshShippingActions();
expect(getWorkspaceShippingTaskUiState).not.toHaveBeenCalled();
expect(messages.value[0].shipping_actions).toBeUndefined();
});
});
@@ -2,14 +2,13 @@
* features/chat/shipping/useChatShippingRefresh.ts
* 用途:刷新聊天区发货通知 UI State,把后端状态机 action_buttons 同步到消息气泡。
* 依赖:shipping.api、shippingTaskId、shippingNoticeActions 常量、chat.types。
* 逻辑:由 useChatShipping 调用本文件;本文件只读取后端 /ui-state,不再从 Dify 正文解析按钮。
* 逻辑:由 useChatShipping 调用本文件;本文件只读取后端 /ui-state,不再从会话标题猜任务号或从 Dify 正文解析按钮。
*/
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 { stripShippingActionListByButtons, stripShippingPlainActionMenu } from './shippingText';
import type { ChatMessage, ChatSessionItem } from '../types/chat.types';
import type { ChatMessage } 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';
@@ -19,7 +18,6 @@ export interface ShippingRefreshContext {
messages: Ref<ChatMessage[]>;
conversationId: Ref<string | null>;
isThinking: Ref<boolean>;
history: Ref<ChatSessionItem[]>;
resolvedShippingTaskId: Ref<string>;
shippingTaskIdFromQuery: ComputedRef<string>;
getActiveBatchTaskId: () => string;
@@ -29,7 +27,7 @@ export interface ShippingRefreshContext {
* 解析当前聊天页最可靠的发货任务编号。
*
* 核心逻辑:优先使用批次当前焦点任务,其次才回退到消息内嵌任务号、已解析状态和路由参数;
* 禁止再按 conversation 扫任务列表“猜”一票,避免多票会话把动作按钮挂错任务。
* 禁止再按 conversation 标题“猜”一票,避免多票会话把动作按钮挂错任务。
* @param params - 当前聊天页中可用的任务定位线索
* @returns 可信的任务编号;无法明确定位时返回空字符串
*/
@@ -38,14 +36,12 @@ export function resolvePreferredShippingTaskId(params: {
messageTaskId?: string | null;
resolvedTaskId?: string | null;
queryTaskId?: string | null;
historyTaskId?: string | null;
}) {
return String(
params.batchTaskId
|| params.messageTaskId
|| params.resolvedTaskId
|| params.queryTaskId
|| params.historyTaskId
|| '',
).trim().toUpperCase();
}
@@ -74,20 +70,11 @@ export function createShippingActionsRefresher(ctx: ShippingRefreshContext) {
if (!ctx.isShippingNoticeAgent.value) return;
const msgs = ctx.messages.value;
if (!msgs.length) return;
const cid = String(ctx.conversationId.value || '').trim();
const historyTaskId = (() => {
if (!cid) return '';
const session = ctx.history.value.find((item) => String(item.conversation_id || '') === cid);
const title = String(session?.title || '');
const match = title.match(SHIPPING_TASK_ID_RE);
return match?.[0] ? match[0].toUpperCase() : '';
})();
const taskId = resolvePreferredShippingTaskId({
batchTaskId: ctx.getActiveBatchTaskId(),
messageTaskId: findLatestShippingTaskId(msgs),
resolvedTaskId: ctx.resolvedShippingTaskId.value,
queryTaskId: ctx.shippingTaskIdFromQuery.value,
historyTaskId,
});
if (taskId) ctx.resolvedShippingTaskId.value = taskId;
let lastOpenAssistantIndex = -1;
@@ -22,7 +22,14 @@ const createContext = (
conversationId: ref('conv-send'),
history: ref([]),
input: ref(''),
attachments: ref([{ kind: 'local', file: new File(['notice'], 'notice.txt', { type: 'text/plain' }) }]),
attachments: ref([{
id: 'local-notice',
kind: 'local',
file: new File(['notice'], 'notice.txt', { type: 'text/plain' }),
type: 'document',
uploadStatus: 'waiting',
uploadProgress: 0,
}]),
shippingAutoFlowRequested: ref(true),
resolvedShippingTaskId: ref(''),
getActiveShippingBatchNo: () => '',
@@ -32,7 +39,7 @@ const createContext = (
getActiveShippingTaskId: () => '',
lastAssistantMessageContent: () => '',
lastAssistantShippingActions: () => [],
sendMessage: vi.fn(async () => undefined),
sendMessage: vi.fn(async () => true),
buildFileSpecsForSend: vi.fn(async () => []),
loadHistory: vi.fn(async () => undefined),
sendShippingMenuMessage: vi.fn(async () => undefined),
@@ -44,6 +51,9 @@ const createContext = (
handleShippingAutoUploadFile: vi.fn(async () => undefined),
handleShippingAutoUploadNoticeBatch: vi.fn(async () => undefined),
isShippingNoticeBatchSubmitting: () => isShippingNoticeBatchSubmitting(),
markOrderExtractionStarted: vi.fn(),
rollbackOrderExtractionStarted: vi.fn(),
syncShippingConversationWorkspace: vi.fn(async () => true),
refreshShippingActions: vi.fn(async () => undefined),
shippingSuggestedPrompt: computed(() => ''),
isShippingShortageQueryIntent: () => false,
@@ -73,6 +83,7 @@ describe('useChatShippingSendHandler', () => {
});
it('sends parsed intakes to the existing Chatflow without requiring upload-time candidates', async () => {
const completionOrder: string[] = [];
const attachment = {
id: 'notice-1',
kind: 'shipping_notice' as const,
@@ -89,8 +100,11 @@ describe('useChatShippingSendHandler', () => {
hasCandidateReviewIssues: () => true,
hasSelectedNoticeCandidates: () => true,
getParsedIntakeNos: () => ['SNI-1'],
refreshNoticeIntakeStatuses: vi.fn(async () => undefined),
clearConsumedNoticeAttachments: vi.fn(),
applyShippingMessageRecovery: vi.fn(async () => { completionOrder.push('recovery'); return true; }),
refreshNoticeIntakeStatuses: vi.fn(async () => { completionOrder.push('intakes'); }),
syncShippingConversationWorkspace: vi.fn(async () => { completionOrder.push('workspace'); return true; }),
clearConsumedNoticeAttachments: vi.fn(() => { completionOrder.push('clear'); }),
refreshShippingActions: vi.fn(async () => { completionOrder.push('actions'); }),
});
const { tryHandleShippingAttachmentAutoFlow } = createShippingSendHandlers(ctx);
@@ -107,8 +121,26 @@ describe('useChatShippingSendHandler', () => {
shipping_intake_nos: ['SNI-1'],
display_query: 'chat.shippingOrderExtractionDefaultPrompt',
},
expect.objectContaining({ onAssistantMessageFinished: expect.any(Function) }),
expect.objectContaining({
userAttachments: [{
id: 'notice-1',
name: 'orders.eml',
size: 100,
extension: 'eml',
type: 'document',
source: 'shipping_notice',
}],
onAssistantMessageFinished: expect.any(Function),
}),
);
expect(ctx.markOrderExtractionStarted).toHaveBeenCalledWith(['SNI-1']);
const hooks = vi.mocked(ctx.sendMessage).mock.calls[0]?.[5];
const assistantMessage = { role: 'assistant', content: '已打开已有任务' } as const;
await hooks?.onAssistantMessageFinished?.(assistantMessage, []);
expect(ctx.applyShippingMessageRecovery).toHaveBeenCalledWith(assistantMessage);
expect(completionOrder).toEqual(['recovery', 'intakes', 'workspace', 'clear', 'actions']);
expect(ctx.syncShippingConversationWorkspace).toHaveBeenCalledWith({ preferLatest: true });
});
it('uses the user query for full extraction even when no candidate exists before send', async () => {
@@ -144,7 +176,102 @@ describe('useChatShippingSendHandler', () => {
shipping_intake_nos: ['SNI-1'],
display_query: '请解析这些附件',
},
expect.objectContaining({ onAssistantMessageFinished: expect.any(Function) }),
expect.objectContaining({
userAttachments: [{
id: 'notice-1',
name: 'orders.eml',
size: 100,
extension: 'eml',
type: 'document',
source: 'shipping_notice',
}],
onAssistantMessageFinished: expect.any(Function),
}),
);
});
it('retries the conversation workspace once when the first refresh fails', async () => {
const syncWorkspace = vi.fn()
.mockResolvedValueOnce(false)
.mockResolvedValueOnce(true);
const ctx = createContext({
attachments: ref([{
id: 'notice-retry',
kind: 'shipping_notice' as const,
type: 'document' as const,
uploadStatus: 'uploaded' as const,
parseStatus: 'parsed' as const,
uploadProgress: 100,
originalFilename: 'orders.eml',
fileSize: 100,
intakeNo: 'SNI-RETRY',
}]),
getParsedIntakeNos: () => ['SNI-RETRY'],
syncShippingConversationWorkspace: syncWorkspace,
});
const { tryHandleShippingAttachmentAutoFlow } = createShippingSendHandlers(ctx);
await tryHandleShippingAttachmentAutoFlow(undefined, '', '');
const hooks = vi.mocked(ctx.sendMessage).mock.calls[0]?.[5];
await hooks?.onAssistantMessageFinished?.({} as never, []);
expect(syncWorkspace).toHaveBeenCalledTimes(2);
expect(syncWorkspace).toHaveBeenNthCalledWith(1, { preferLatest: true });
expect(syncWorkspace).toHaveBeenNthCalledWith(2, { preferLatest: true });
expect(ctx.refreshShippingActions).toHaveBeenCalledTimes(1);
});
it('rolls back the local extracting state when the chat request fails', async () => {
const rollback = vi.fn();
const ctx = createContext({
attachments: ref([{
id: 'notice-failed-send',
kind: 'shipping_notice' as const,
type: 'document' as const,
uploadStatus: 'uploaded' as const,
parseStatus: 'parsed' as const,
uploadProgress: 100,
originalFilename: 'orders.eml',
fileSize: 100,
intakeNo: 'SNI-FAILED-SEND',
}]),
getParsedIntakeNos: () => ['SNI-FAILED-SEND'],
sendMessage: vi.fn(async () => { throw new Error('network failed'); }),
rollbackOrderExtractionStarted: rollback,
});
const { tryHandleShippingAttachmentAutoFlow } = createShippingSendHandlers(ctx);
const consumed = await tryHandleShippingAttachmentAutoFlow(undefined, '', '');
expect(consumed).toBe(true);
expect(rollback).toHaveBeenCalledWith(['SNI-FAILED-SEND']);
expect(ctx.msg.warning).toHaveBeenCalledWith('network failed');
});
it('rolls back extraction state when sendMessage reports a handled stream failure', async () => {
const rollback = vi.fn();
const ctx = createContext({
attachments: ref([{
id: 'notice-handled-failure',
kind: 'shipping_notice' as const,
type: 'document' as const,
uploadStatus: 'uploaded' as const,
parseStatus: 'parsed' as const,
uploadProgress: 100,
originalFilename: 'orders.eml',
fileSize: 100,
intakeNo: 'SNI-HANDLED-FAILURE',
}]),
getParsedIntakeNos: () => ['SNI-HANDLED-FAILURE'],
sendMessage: vi.fn(async () => false),
rollbackOrderExtractionStarted: rollback,
});
const { tryHandleShippingAttachmentAutoFlow } = createShippingSendHandlers(ctx);
const consumed = await tryHandleShippingAttachmentAutoFlow(undefined, '', '');
expect(consumed).toBe(true);
expect(rollback).toHaveBeenCalledWith(['SNI-HANDLED-FAILURE']);
expect(ctx.loadHistory).not.toHaveBeenCalled();
});
});
@@ -22,6 +22,8 @@ import {
import { resolveShippingDecisionFromText, resolveShippingNumericChoice } from './shippingMenu';
import { classifyShippingUploadFile } from './shippingUploadPrompt';
import { extractExt } from '../constants/shipping';
import { createChatMessageAttachmentSnapshots } from '../utils/attachmentCard.utils';
import type { SendMessageLifecycleHooks } from '../composables/useChat';
import type { StartChatTurnOptions } from '../types/chat-turn.types';
import type { ChatMessage, ChatSessionItem } from '../types/chat.types';
import type { ChatUploadFileSpec, PendingAttachment, ShippingActionButton } from '../types/shipping.types';
@@ -51,8 +53,8 @@ export interface ShippingSendHandlerContext {
kb: string,
files: ChatUploadFileSpec[],
context?: { task_id?: string; batch_no?: string; shipping_intake_nos?: string[]; display_query?: string },
hooks?: { onAssistantMessageFinished?: (message: ChatMessage, runMessages: ChatMessage[]) => void | Promise<void> },
) => Promise<void>;
hooks?: SendMessageLifecycleHooks,
) => Promise<boolean | void>;
buildFileSpecsForSend: () => Promise<ChatUploadFileSpec[]>;
loadHistory: () => Promise<void>;
sendShippingMenuMessage: (message: string) => Promise<void>;
@@ -71,8 +73,13 @@ export interface ShippingSendHandlerContext {
hasSelectedNoticeCandidates?: () => boolean;
openShippingDuplicateDialog?: (attachmentId?: string) => void;
getParsedIntakeNos?: () => string[];
markOrderExtractionStarted?: (intakeNos: string[]) => void;
rollbackOrderExtractionStarted?: (intakeNos: string[]) => void;
refreshNoticeIntakeStatuses?: () => Promise<void>;
clearConsumedNoticeAttachments?: () => void;
applyShippingMessageRecovery?: (message: ChatMessage) => Promise<boolean>;
applyShippingBatchSnapshot?: (message: ChatMessage) => boolean;
syncShippingConversationWorkspace: (options?: { preferLatest?: boolean }) => Promise<boolean>;
refreshShippingActions: () => Promise<void>;
shippingSuggestedPrompt: ComputedRef<string>;
isShippingShortageQueryIntent: (text: string) => boolean;
@@ -211,11 +218,13 @@ export function createShippingSendHandlers(ctx: ShippingSendHandlerContext) {
}
const intakeNos = ctx.getParsedIntakeNos?.() || [];
if (intakeNos.length) {
const userAttachments = createChatMessageAttachmentSnapshots(noticeItems);
const query = trimmed || ctx.t('chat.shippingOrderExtractionDefaultPrompt');
ctx.shippingAutoFlowRequested.value = false;
if (typeof textOrEvent !== 'string') ctx.input.value = '';
ctx.markOrderExtractionStarted?.(intakeNos);
try {
await ctx.sendMessage(
const sent = await ctx.sendMessage(
query,
ctx.currentAgentId.value,
ctx.selectedKb.value,
@@ -225,15 +234,30 @@ export function createShippingSendHandlers(ctx: ShippingSendHandlerContext) {
display_query: query,
},
{
onAssistantMessageFinished: async () => {
userAttachments,
onAssistantMessageFinished: async (assistantMessage) => {
if (ctx.applyShippingMessageRecovery) {
await ctx.applyShippingMessageRecovery(assistantMessage);
} else {
ctx.applyShippingBatchSnapshot?.(assistantMessage);
}
await ctx.refreshNoticeIntakeStatuses?.();
if (!(await ctx.syncShippingConversationWorkspace({ preferLatest: true }))) {
await new Promise((resolve) => setTimeout(resolve, 300));
await ctx.syncShippingConversationWorkspace({ preferLatest: true });
}
ctx.clearConsumedNoticeAttachments?.();
await ctx.refreshShippingActions();
},
},
);
if (sent === false) {
ctx.rollbackOrderExtractionStarted?.(intakeNos);
return true;
}
await ctx.loadHistory();
} catch (e: unknown) {
ctx.rollbackOrderExtractionStarted?.(intakeNos);
const errorMessage = e instanceof Error ? e.message : '文件处理失败';
ctx.msg.warning(errorMessage);
}
@@ -0,0 +1,35 @@
/**
* features/chat/shipping/useShippingNoticeIntakes.spec.ts
* 用途:验证订单抽取阶段的轮询与本地即时状态合并规则。
* 依赖:Vitest、useShippingNoticeIntakes 纯函数导出。
* 逻辑:确保 parsed 不会提前停止 extracting 轮询,且服务端 not_started 不覆盖刚点击发送的本地状态。
*/
import { describe, expect, it } from 'vitest';
import {
resolveShippingOrderExtractionStatus,
shouldPollShippingNoticeIntake,
} from './useShippingNoticeIntakes';
describe('shipping notice order extraction state', () => {
it('keeps polling after preprocessing is parsed while order extraction is active', () => {
expect(shouldPollShippingNoticeIntake({
parseStatus: 'parsed',
orderExtractionStatus: 'extracting',
})).toBe(true);
expect(shouldPollShippingNoticeIntake({
parseStatus: 'parsed',
orderExtractionStatus: 'completed',
})).toBe(false);
expect(shouldPollShippingNoticeIntake({
parseStatus: 'parsed',
orderExtractionStatus: 'failed',
})).toBe(false);
});
it('preserves the immediate extracting state until the backend leaves not_started', () => {
expect(resolveShippingOrderExtractionStatus('extracting', 'not_started')).toBe('extracting');
expect(resolveShippingOrderExtractionStatus('extracting', 'extracting')).toBe('extracting');
expect(resolveShippingOrderExtractionStatus('extracting', 'completed')).toBe('completed');
expect(resolveShippingOrderExtractionStatus(undefined, 'not_started')).toBe('not_started');
});
});
@@ -32,6 +32,23 @@ export { isShippingNoticeAttachmentParseIncomplete } from './shippingNoticeAttac
const TERMINAL_PARSE = new Set(['parsed', 'failed', 'parse_failed', 'consumed', 'cancelled', 'expired']);
const ACTIVE_PARSE = new Set(['waiting', 'queued', 'parsing', 'created']);
const ACTIVE_ORDER_EXTRACTION = new Set(['extracting']);
/** 判断 Intake 是否仍需轮询上传预处理或订单抽取状态。 */
export function shouldPollShippingNoticeIntake(
item: Pick<ShippingNoticePendingAttachment, 'parseStatus' | 'orderExtractionStatus'>,
): boolean {
return !TERMINAL_PARSE.has(item.parseStatus)
|| ACTIVE_ORDER_EXTRACTION.has(String(item.orderExtractionStatus || '').trim().toLowerCase());
}
/** 保留刚点击发送的本地 extracting,直到服务端进入真实抽取状态或返回终态。 */
export function resolveShippingOrderExtractionStatus(localStatus?: string, remoteStatus?: string | null): string | undefined {
const local = String(localStatus || '').trim().toLowerCase();
const remote = String(remoteStatus || '').trim().toLowerCase();
if (local === 'extracting' && (!remote || remote === 'not_started')) return 'extracting';
return remote || undefined;
}
function mapServerParseStatus(status: string): ShippingNoticePendingAttachment['parseStatus'] {
const normalized = String(status || '').trim().toLowerCase();
@@ -160,7 +177,8 @@ export function useShippingNoticeIntakes(options: UseShippingNoticeIntakesOption
|| item.uploadStatus === 'waiting'
|| ACTIVE_PARSE.has(item.parseStatus)
|| item.parseStatus === 'queued'
|| item.parseStatus === 'parsing',
|| item.parseStatus === 'parsing'
|| ACTIVE_ORDER_EXTRACTION.has(String(item.orderExtractionStatus || '').trim().toLowerCase()),
),
);
@@ -223,7 +241,7 @@ export function useShippingNoticeIntakes(options: UseShippingNoticeIntakesOption
if (!intakeNos.length) return;
if (intakeNos.every((no) => {
const item = noticeAttachments.value.find((entry) => entry.intakeNo === no);
return item != null && TERMINAL_PARSE.has(item.parseStatus);
return item != null && !shouldPollShippingNoticeIntake(item);
})) {
return;
}
@@ -255,7 +273,10 @@ export function useShippingNoticeIntakes(options: UseShippingNoticeIntakesOption
if (!local) continue;
patchAttachment(local.id, {
parseStatus: mapServerParseStatus(remote.parse_status),
orderExtractionStatus: remote.order_extraction_status || undefined,
orderExtractionStatus: resolveShippingOrderExtractionStatus(
local.orderExtractionStatus,
remote.order_extraction_status,
),
orderExtractionVersion: remote.order_extraction_version || undefined,
parseSummary: (remote.parse_summary || undefined) as ShippingNoticeParseSummary | undefined,
errorCode: remote.order_extraction_error_code || remote.error_code || undefined,
@@ -357,6 +378,32 @@ export function useShippingNoticeIntakes(options: UseShippingNoticeIntakesOption
)
.map((item) => String(item.intakeNo));
/** 点击发送后立即展示订单识别阶段,并启动 Intake 状态轮询。 */
const markOrderExtractionStarted = (intakeNos: string[]) => {
const selected = new Set(intakeNos.map((item) => String(item || '').trim().toUpperCase()).filter(Boolean));
for (const attachment of noticeAttachments.value) {
if (!attachment.intakeNo || !selected.has(attachment.intakeNo.toUpperCase())) continue;
patchAttachment(attachment.id, {
orderExtractionStatus: 'extracting',
errorCode: undefined,
errorMessage: undefined,
});
}
schedulePoll();
};
/** 聊天请求未成功发起时撤销本地即时状态;服务端真实状态由下一次刷新覆盖。 */
const rollbackOrderExtractionStarted = (intakeNos: string[]) => {
const selected = new Set(intakeNos.map((item) => String(item || '').trim().toUpperCase()).filter(Boolean));
for (const attachment of noticeAttachments.value) {
if (!attachment.intakeNo || !selected.has(attachment.intakeNo.toUpperCase())) continue;
if (attachment.orderExtractionStatus === 'extracting') {
patchAttachment(attachment.id, { orderExtractionStatus: 'not_started' });
}
}
schedulePoll();
};
const clearConsumedAttachments = () => {
options.attachments.value = options.attachments.value.filter(
(item) => item.kind !== 'shipping_notice' || item.parseStatus !== 'consumed',
@@ -391,7 +438,7 @@ export function useShippingNoticeIntakes(options: UseShippingNoticeIntakesOption
}));
const nonNotice = options.attachments.value.filter((item) => item.kind !== 'shipping_notice');
options.attachments.value = [...nonNotice, ...restored];
if (restored.some((item) => item.parseStatus === 'queued' || item.parseStatus === 'parsing')) {
if (restored.some((item) => shouldPollShippingNoticeIntake(item))) {
schedulePoll();
}
};
@@ -486,6 +533,8 @@ export function useShippingNoticeIntakes(options: UseShippingNoticeIntakesOption
setCandidateSelected,
updateCandidateSummary,
getParsedIntakeNos,
markOrderExtractionStarted,
rollbackOrderExtractionStarted,
getSelectedCandidateNos,
refreshStatuses,
clearConsumedAttachments,
+54 -1
View File
@@ -5,7 +5,7 @@
* 逻辑:作为 features/chat 域的类型中枢,向上提供页面编排约束,向下约束消息渲染与交互结构。
*/
import type { LeaveAgentOption } from './leave.types';
import type { ShippingTaskUiState } from './shipping.api.types';
import type { ShippingBatchUiState, ShippingTaskUiState } from './shipping.api.types';
export type { LeaveAgentOption };
@@ -18,15 +18,66 @@ export interface RetrieverResource {
[key: string]: unknown;
}
export type ShippingOrderExtractionStatus = 'extracting' | 'completed' | 'partially_completed' | 'failed';
export interface ShippingOrderExtractionState {
status: ShippingOrderExtractionStatus;
phase: 'llm_extraction' | 'result_persisted' | 'failed';
message: string;
created_count: number;
opened_existing_count: number;
pending_count: number;
non_shipping_count: number;
created_with_missing_fields_count: number;
batch_no?: string | null;
terminal: boolean;
}
/**
* 货代消息在实时 SSE 与历史回放之间共享的最小恢复载荷。
* 核心逻辑:`open_existing` 终态至少要保留 `task_no`;若已知所属批次或已拿到工作台快照,
* 则继续补齐 `batch_no`、`shipping_ui_state`、`shipping_batch_ui_state`,供聊天页恢复右侧工作台。
*/
export interface ShippingMessageRecoveryPayload extends Record<string, unknown> {
task_no?: string;
batch_no?: string | null;
shipping_ui_state?: ShippingTaskUiState;
shipping_batch_ui_state?: ShippingBatchUiState;
shipping_order_extraction_state?: ShippingOrderExtractionState;
}
export type ChatMessageAttachmentType = 'image' | 'document' | 'audio' | 'video' | 'custom';
export type ChatMessageAttachmentSource = 'local' | 'remote' | 'shipping_notice';
/**
* 已发送消息中的附件快照。
* 约束:只保留可展示、可 JSON 序列化的信息,不得包含 File、完整 URL、上传凭据或内部资产编号。
readonly id: string;
*/
export interface ChatMessageAttachment {
readonly id: string;
readonly name: string;
readonly size?: number;
readonly extension?: string;
readonly type: ChatMessageAttachmentType;
readonly source: ChatMessageAttachmentSource;
}
export interface ChatMessage {
role: 'user' | 'assistant';
content: string;
/** 用户提交时固化的附件展示快照;助手消息不使用此字段。 */
attachments?: ChatMessageAttachment[];
type?: 'text' | 'leave-form' | 'leave-confirmation' | 'leave-result' | 'shipping-inventory-mapping' | 'shipping-parse-review' | 'shipping-match-result' | 'maintenance-device-result';
retriever_resources?: RetrieverResource[];
attribution_parts?: string[];
chat_log_id?: number;
/** 文件检核等异步任务批次 ID(按轮问答绑定) */
run_id?: number;
/**
* 结构化回放载荷。
* 约束:货代消息需兼容 `ShippingMessageRecoveryPayload`,保证历史刷新后仍可恢复任务锚点与批次工作台。
*/
payload?: unknown;
local_id?: string;
local_only?: boolean;
@@ -39,6 +90,8 @@ export interface ChatMessage {
source_code?: string;
}>;
shipping_ui_state?: ShippingTaskUiState;
/** 点击发送后的 Intake 级订单识别生命周期;终态同时持久化在 payload 供历史回放。 */
shipping_order_extraction_state?: ShippingOrderExtractionState;
shipping_actions_used?: boolean;
/** 流式对话是否因网络/上游中断而附带错误提示 */
stream_error?: boolean;
@@ -23,7 +23,7 @@ export interface ShippingInventorySourceCandidate {
display_name?: string | null;
site_id?: string | null;
warehouse_id?: string | null;
source_type?: string | null;
connector_type?: string | null;
match_score?: number | null;
matched_by?: string | null;
}
@@ -58,6 +58,9 @@ export interface ShippingInventorySnapshot {
export interface ShippingTaskSummary {
id: number;
task_no: string;
shipping_case_id?: number | null;
case_no?: string | null;
business_no?: string | null;
batch_no?: string | null;
source_type: string;
source_file_name?: string | null;
@@ -65,6 +68,11 @@ export interface ShippingTaskSummary {
batch_index?: number | null;
batch_total?: number | null;
customer_name?: string | null;
customer_id?: number | null;
customer_resolution_status?: string | null;
customer_resolution_method?: string | null;
customer_name_snapshot?: string | null;
customer_short_code_snapshot?: string | null;
current_step?: string | null;
process_status: string;
review_status?: string | null;
@@ -91,7 +99,7 @@ export interface ShippingTaskSummary {
destination_country?: string | null;
warehouse_hint?: string | null;
inventory_source_code?: string | null;
inventory_source_type?: string | null;
inventory_connector_type?: string | null;
inventory_site_id?: string | null;
inventory_warehouse_id?: string | null;
inventory_source_status?: InventorySourceStatus | null;
@@ -169,6 +177,8 @@ export interface ShippingNoticeHeader {
export interface ShippingNoticeLine {
sku: string;
reservation_id?: string | null;
/** 可选库存路由线索,不代表任务通知来源或已确认的库存连接器类型。 */
source_type?: string | null;
qty: number;
required_date?: string | null;
uom?: string | null;
@@ -189,6 +199,11 @@ export interface ShippingShortageSummary {
}
export interface ShippingTaskDetail extends ShippingTaskSummary {
customer_id?: number | null;
customer_resolution_status?: string | null;
customer_resolution_method?: string | null;
customer_name_snapshot?: string | null;
customer_short_code_snapshot?: string | null;
customer_code?: string | null;
ship_to?: string | null;
po_number?: string | null;
@@ -205,6 +220,12 @@ export interface ShippingTaskDetail extends ShippingTaskSummary {
ui_state?: ShippingTaskUiState;
}
export interface ShippingCustomerOption {
id: number;
standard_name: string;
short_code: string;
}
export interface ShippingChatAction {
id: string;
label: string;
@@ -241,6 +262,21 @@ export interface ShippingTaskUiState {
updated_at?: string | null;
}
/**
* `shipping_ui_state` SSE 与历史回放共用的恢复契约。
* 核心逻辑:任务锚点 `task_no` 是 open_existing 场景恢复聊天工作台的最小必需字段;
* 若后端能解析到所属批次或完整批次快照,应继续补齐 `batch_no`、`batch_ui_state` 与 `ui_state`。
*/
export interface ShippingUiStateEventPayload {
event?: 'shipping_ui_state';
conversation_id?: string;
task_no?: string | null;
batch_no?: string | null;
ui_state?: ShippingTaskUiState;
batch_ui_state?: ShippingBatchUiState;
source?: string;
}
export interface ShippingBatchSummary {
id: number;
batch_no: string;
@@ -1,8 +1,8 @@
/**
* features/chat/types/shipping.types.ts
* 用途:发货通知聊天流程相关 TypeScript 类型定义。
* 用途:聊天附件与发货通知流程相关 TypeScript 类型定义。
* 依赖:无(纯类型模块)。
* 逻辑:shipping/* composable 与 Chat 消息组件统一引用本文件类型。
* 逻辑:附件 composable、shipping/* composable 与 Chat 消息组件统一引用本文件类型。
*/
export type ShippingActionVariant = 'primary' | 'secondary' | 'danger';
@@ -11,7 +11,13 @@ export type ShippingMenuAction = 'upload' | 'paste' | 'retry_rpa' | 'confirm' |
export type ChatUploadFileType = 'image' | 'document' | 'audio' | 'video' | 'custom';
export type ShippingNoticeUploadStatus = 'waiting' | 'uploading' | 'uploaded' | 'failed';
/** 附件卡片统一展示状态,由各附件类型的真实业务字段映射得到。 */
export type AttachmentUiStatus = 'pending' | 'uploading' | 'processing' | 'attention' | 'ready' | 'failed';
/** 普通本地附件的上传状态;语义与发货通知上传状态保持一致。 */
export type ChatAttachmentUploadStatus = 'waiting' | 'uploading' | 'uploaded' | 'failed';
export type ShippingNoticeUploadStatus = ChatAttachmentUploadStatus;
export type ShippingNoticeParseStatus =
| 'waiting'
| 'queued'
@@ -139,10 +145,30 @@ export type ShippingNoticePendingAttachment = {
candidates?: ShippingNoticeCandidate[];
};
/** 普通本地附件:选择后等待发送,实际上传由发送流程触发。 */
export interface ChatLocalPendingAttachment {
id: string;
kind: 'local';
file: File;
type: ChatUploadFileType;
uploadStatus: ChatAttachmentUploadStatus;
uploadProgress: number;
uploadFileId?: string;
errorMessage?: string;
}
/** 远程 URL 附件:发送时直接传 URL,不伪造本地文件大小或上传进度。 */
export interface ChatRemotePendingAttachment {
id: string;
kind: 'remote';
url: string;
type: ChatUploadFileType;
}
/** 待发送附件(本地文件、远程 URL 或货代通知预解析) */
export type PendingAttachment =
| { id: string; kind: 'local'; file: File; type: ChatUploadFileType }
| { id: string; kind: 'remote'; url: string; type: ChatUploadFileType }
| ChatLocalPendingAttachment
| ChatRemotePendingAttachment
| ShippingNoticePendingAttachment;
export type ChatUploadFileSpec =
@@ -179,6 +205,8 @@ export interface ShippingParseReviewPayload {
lines: Array<{
sku: string;
reservation_id?: string | null;
/** 可选库存路由线索;与 ShippingTask.source_type 通知来源无关。 */
source_type?: string | null;
qty: number;
required_date?: string | null;
uom?: string | null;
@@ -0,0 +1,188 @@
/**
* features/chat/utils/attachmentCard.utils.spec.ts
* 用途:验证附件卡片名称、大小、状态与删除约束的纯函数映射。
* 依赖:Vitest、attachmentCard.utils。
* 逻辑:用普通附件、远程 URL 和发货通知覆盖用户可见的关键状态分支。
*/
import { describe, expect, it } from 'vitest';
import type { PendingAttachment, ShippingNoticePendingAttachment } from '../types/shipping.types';
import {
createChatMessageAttachmentSnapshots,
formatAttachmentSize,
getAttachmentCardStatus,
getAttachmentExtension,
getAttachmentName,
getAttachmentSize,
isAttachmentRemoveDisabled,
} from './attachmentCard.utils';
/** 创建普通本地附件夹具。 */
function localAttachment(status: 'waiting' | 'uploading' | 'uploaded' | 'failed' = 'waiting'): PendingAttachment {
return {
id: 'local-1',
kind: 'local',
file: new File(['pdf'], 'purchase-order.pdf', { type: 'application/pdf' }),
type: 'document',
uploadStatus: status,
uploadProgress: status === 'uploaded' ? 100 : 0,
};
}
/** 创建发货通知附件夹具。 */
function shippingAttachment(
patch: Partial<ShippingNoticePendingAttachment> = {},
): ShippingNoticePendingAttachment {
return {
id: 'shipping-1',
kind: 'shipping_notice',
type: 'document',
uploadStatus: 'uploaded',
parseStatus: 'parsed',
uploadProgress: 100,
originalFilename: 'notice.eml',
fileSize: 2048,
...patch,
};
}
describe('attachment card utils', () => {
it('formats real file sizes without inventing remote URL sizes', () => {
expect(formatAttachmentSize(0)).toBe('0 B');
expect(formatAttachmentSize(144.46 * 1024)).toBe('144.46 KB');
expect(formatAttachmentSize(2.31 * 1024 * 1024)).toBe('2.31 MB');
expect(formatAttachmentSize(undefined)).toBe('');
const remote: PendingAttachment = {
id: 'remote-1', kind: 'remote', url: 'https://example.com/files/report.xlsx', type: 'document',
};
expect(getAttachmentName(remote)).toBe('report.xlsx');
expect(getAttachmentExtension(remote)).toBe('XLSX');
expect(getAttachmentSize(remote)).toBe('');
});
it('maps local upload lifecycle and disables removal only while uploading', () => {
expect(getAttachmentCardStatus(localAttachment('waiting')).state).toBe('pending');
expect(getAttachmentCardStatus(localAttachment('uploading')).state).toBe('uploading');
expect(getAttachmentCardStatus(localAttachment('uploaded')).state).toBe('ready');
expect(getAttachmentCardStatus(localAttachment('failed')).state).toBe('failed');
expect(isAttachmentRemoveDisabled(localAttachment('uploading'))).toBe(true);
expect(isAttachmentRemoveDisabled(localAttachment('failed'))).toBe(false);
});
it('preserves shipping parsing, failure and duplicate attention states', () => {
expect(getAttachmentCardStatus(shippingAttachment({ parseStatus: 'parsing' })).state).toBe('processing');
expect(getAttachmentCardStatus(shippingAttachment({ parseStatus: 'failed' }))).toEqual({
state: 'failed', labelKey: 'chat.attachment.parseFailed',
});
expect(getAttachmentCardStatus(shippingAttachment({
duplicate: {
status: 'possible_duplicate',
blocking: true,
fingerprintStrength: 'strong',
matches: [],
allowedActions: [],
},
})).state).toBe('attention');
expect(getAttachmentCardStatus(shippingAttachment()).state).toBe('ready');
});
it('shows the order extraction lifecycle separately from attachment parsing', () => {
expect(getAttachmentCardStatus(shippingAttachment({ orderExtractionStatus: 'extracting' }))).toEqual({
state: 'processing', labelKey: 'chat.shippingOrderExtractionProcessing',
});
expect(getAttachmentCardStatus(shippingAttachment({ orderExtractionStatus: 'partially_completed' }))).toEqual({
state: 'attention', labelKey: 'chat.shippingOrderExtractionPartiallyCompleted',
});
expect(getAttachmentCardStatus(shippingAttachment({ orderExtractionStatus: 'completed' }))).toEqual({
state: 'ready', labelKey: 'chat.shippingOrderExtractionCompleted',
});
expect(getAttachmentCardStatus(shippingAttachment({ orderExtractionStatus: 'failed' }))).toEqual({
state: 'failed', labelKey: 'chat.shippingOrderExtractionFailed',
});
});
it('creates ordered JSON-safe snapshots for local, remote and shipping attachments', () => {
const local = localAttachment('uploaded');
if (local.kind === 'local') {
local.uploadFileId = 'internal-upload-id';
local.errorMessage = 'internal error';
}
const remote: PendingAttachment = {
id: 'remote-secret',
kind: 'remote',
url: 'https://example.com/files/report.xlsx?signature=secret-token',
type: 'document',
};
const shipping = shippingAttachment({
assetNo: 'ASSET-INTERNAL',
intakeNo: 'INTAKE-INTERNAL',
originalFilename: 'notice.EML',
fileSize: 229_877,
});
const snapshots = createChatMessageAttachmentSnapshots([local, remote, shipping]);
expect(snapshots).toEqual([
{
id: 'local-1',
name: 'purchase-order.pdf',
size: 3,
extension: 'pdf',
type: 'document',
source: 'local',
},
{
id: 'remote-secret',
name: 'report.xlsx',
extension: 'xlsx',
type: 'document',
source: 'remote',
},
{
id: 'shipping-1',
name: 'notice.EML',
size: 229_877,
extension: 'eml',
type: 'document',
source: 'shipping_notice',
},
]);
const serialized = JSON.stringify(snapshots);
expect(serialized).not.toContain('secret-token');
expect(serialized).not.toContain('internal-upload-id');
expect(serialized).not.toContain('ASSET-INTERNAL');
expect(serialized).not.toContain('INTAKE-INTERNAL');
if (local.kind === 'local') local.file = new File(['changed'], 'changed.pdf');
shipping.originalFilename = 'changed.eml';
expect(snapshots[0]?.name).toBe('purchase-order.pdf');
expect(snapshots[2]?.name).toBe('notice.EML');
});
it('uses a safe fallback for remote URLs without a filename and never invents size', () => {
const snapshots = createChatMessageAttachmentSnapshots([{
id: 'remote-root',
kind: 'remote',
url: 'https://example.com/?signature=hidden',
type: 'custom',
}]);
expect(snapshots).toEqual([{
id: 'remote-root',
name: 'remote-file',
type: 'custom',
source: 'remote',
}]);
});
it('strips path fragments and control characters from snapshot names', () => {
const snapshots = createChatMessageAttachmentSnapshots([
shippingAttachment({ originalFilename: 'C:\\mail\\notice\u0000.eml' }),
]);
expect(snapshots[0]).toMatchObject({
id: 'shipping-1',
name: 'notice.eml',
});
});
});
@@ -0,0 +1,179 @@
/**
* features/chat/utils/attachmentCard.utils.ts
* 用途:统一计算聊天附件卡片的名称、大小、扩展名、状态、删除约束与已发送快照。
* 依赖:chat.types 的消息附件契约、shipping.types 的待发送附件联合类型。
* 逻辑:ChatInputBar 只负责渲染;发送层通过快照函数把可变待发送附件固化为安全展示数据。
*/
import type { ChatMessageAttachment } from '../types/chat.types';
import type { AttachmentUiStatus, PendingAttachment } from '../types/shipping.types';
export interface AttachmentCardStatus {
state: AttachmentUiStatus;
labelKey: string;
}
/** 获取附件卡片文件名;URL 优先展示路径末段。 */
export function getAttachmentName(attachment: PendingAttachment): string {
if (attachment.kind === 'local') return attachment.file.name;
if (attachment.kind === 'shipping_notice') return attachment.originalFilename;
try {
const pathname = new URL(attachment.url).pathname;
return decodeURIComponent(pathname.split('/').filter(Boolean).pop() || attachment.url);
} catch {
return attachment.url;
}
}
/** 将字节数格式化为紧凑的 B/KB/MB/GB 文本;未知大小返回空字符串。 */
export function formatAttachmentSize(bytes?: number): string {
if (!Number.isFinite(bytes) || bytes === undefined || bytes < 0) return '';
if (bytes < 1024) return `${bytes} B`;
const units = ['KB', 'MB', 'GB'];
let value = bytes / 1024;
let unitIndex = 0;
while (value >= 1024 && unitIndex < units.length - 1) {
value /= 1024;
unitIndex += 1;
}
const formatted = value.toFixed(2).replace(/\.00$/, '').replace(/(\.\d)0$/, '$1');
return `${formatted} ${units[unitIndex]}`;
}
/** 根据附件来源返回真实文件大小;远程 URL 不伪造大小。 */
export function getAttachmentSize(attachment: PendingAttachment): string {
if (attachment.kind === 'local') return formatAttachmentSize(attachment.file.size);
if (attachment.kind === 'shipping_notice') return formatAttachmentSize(attachment.fileSize);
return '';
}
/** 根据文件名扩展名生成卡片类型徽标。 */
export function getAttachmentExtension(attachment: PendingAttachment): string {
const name = getAttachmentName(attachment);
const extension = name.includes('.') ? name.split('.').pop()?.toUpperCase() : '';
if (extension && extension.length <= 5) return extension;
if (attachment.kind === 'remote') return 'URL';
return attachment.type.toUpperCase().slice(0, 5);
}
/** 将普通上传状态与发货通知上传/解析状态映射为统一卡片状态。 */
export function getAttachmentCardStatus(attachment: PendingAttachment): AttachmentCardStatus {
if (attachment.kind === 'remote') return { state: 'ready', labelKey: 'chat.attachment.ready' };
if (attachment.kind === 'local') {
if (attachment.uploadStatus === 'uploading') return { state: 'uploading', labelKey: 'chat.attachment.uploading' };
if (attachment.uploadStatus === 'uploaded') return { state: 'ready', labelKey: 'chat.attachment.ready' };
if (attachment.uploadStatus === 'failed') return { state: 'failed', labelKey: 'chat.attachment.uploadFailed' };
return { state: 'pending', labelKey: 'chat.attachment.pending' };
}
if (attachment.uploadStatus === 'uploading') return { state: 'uploading', labelKey: 'chat.attachment.uploading' };
if (attachment.uploadStatus === 'failed') return { state: 'failed', labelKey: 'chat.attachment.uploadFailed' };
if (attachment.parseStatus === 'queued' || attachment.parseStatus === 'parsing') {
return { state: 'processing', labelKey: 'chat.attachment.processing' };
}
if (attachment.parseStatus === 'failed') return { state: 'failed', labelKey: 'chat.attachment.parseFailed' };
const extractionStatus = String(attachment.orderExtractionStatus || '').trim().toLowerCase();
if (extractionStatus === 'extracting') {
return { state: 'processing', labelKey: 'chat.shippingOrderExtractionProcessing' };
}
if (extractionStatus === 'partially_completed') {
return { state: 'attention', labelKey: 'chat.shippingOrderExtractionPartiallyCompleted' };
}
if (extractionStatus === 'failed') {
return { state: 'failed', labelKey: 'chat.shippingOrderExtractionFailed' };
}
if (extractionStatus === 'completed') {
return { state: 'ready', labelKey: 'chat.shippingOrderExtractionCompleted' };
}
if (attachment.parseStatus === 'parsed' && !attachment.duplicateResolution?.action) {
if (attachment.duplicate?.blocking) {
return { state: 'attention', labelKey: 'chat.shippingNoticeDuplicateBlockingBadge' };
}
if (attachment.duplicate?.status === 'possible_duplicate') {
return { state: 'attention', labelKey: 'chat.shippingNoticeDuplicatePossibleBadge' };
}
}
if (attachment.parseStatus === 'parsed' || attachment.parseStatus === 'consumed') {
return { state: 'ready', labelKey: 'chat.attachment.ready' };
}
return { state: 'pending', labelKey: 'chat.attachment.pending' };
}
/** 上传中的普通附件没有取消接口,因此禁止删除直至请求结束。 */
export function isAttachmentRemoveDisabled(attachment: PendingAttachment): boolean {
return attachment.kind === 'local' && attachment.uploadStatus === 'uploading';
}
/**
* 提取可持久化的安全文件名,避免远程 URL 查询参数或临时签名进入聊天记录。
* @param attachment - 当前待发送附件
* @returns 最长 255 字符的文件名;远程 URL 无有效末段时返回 remote-file
*/
function getSnapshotAttachmentName(attachment: PendingAttachment): string {
let name = '';
if (attachment.kind === 'local') {
name = attachment.file.name;
} else if (attachment.kind === 'shipping_notice') {
name = attachment.originalFilename;
} else {
try {
const pathname = new URL(attachment.url).pathname;
name = decodeURIComponent(pathname.split('/').filter(Boolean).pop() || '');
} catch {
name = '';
}
if (!name) name = 'remote-file';
}
const basename = String(name || 'attachment')
.split(/[\\/]/)
.filter(Boolean)
.pop() || 'attachment';
return basename.replace(/[\u0000-\u001f\u007f]/g, '').trim().slice(0, 255) || 'attachment';
}
/**
* 鐢熸垚鍙寔涔呭寲鐨勯檮浠跺揩鐓?ID锛屼紭鍏堝鐢ㄥ緟鍙戦€侀檮浠剁殑鏈湴鏍囪瘑锛岄伩鍏嶅紩鍏?File 鎴栧唴閮ㄨ祫浜ф寚閽堛€?
*/
function getSnapshotAttachmentId(attachment: PendingAttachment, index: number): string {
const candidate = String(attachment.id || '')
.replace(/[\u0000-\u001f\u007f]/g, '')
.trim()
.slice(0, 128);
return candidate || `attachment-${index + 1}`;
}
/** 从安全文件名提取小写扩展名;无明确扩展名时不制造类型后缀。 */
function getSnapshotAttachmentExtension(name: string): string | undefined {
const dotIndex = name.lastIndexOf('.');
if (dotIndex <= 0 || dotIndex === name.length - 1) return undefined;
const extension = name.slice(dotIndex + 1).trim().toLowerCase();
return extension && extension.length <= 16 ? extension : undefined;
}
/**
* 把待发送附件固化为已发送消息快照。
* 核心逻辑:创建全新纯对象并仅复制展示白名单;远程附件不保存 URL 或伪造大小。
* @param attachments - 按用户选择顺序排列的待发送附件
* @returns 可直接 JSON 序列化、顺序不变的消息附件快照
*/
export function createChatMessageAttachmentSnapshots(
attachments: readonly PendingAttachment[],
): ChatMessageAttachment[] {
return attachments.map((attachment, index) => {
const name = getSnapshotAttachmentName(attachment);
const size = attachment.kind === 'local'
? attachment.file.size
: attachment.kind === 'shipping_notice'
? attachment.fileSize
: undefined;
const extension = getSnapshotAttachmentExtension(name);
return {
id: getSnapshotAttachmentId(attachment, index),
name,
type: attachment.type,
source: attachment.kind,
...(extension ? { extension } : {}),
...(Number.isFinite(size) && size !== undefined && size >= 0
? { size: Math.round(size) }
: {}),
};
});
}