refactor(shipping-notice): 统一料号字段,移除过时的 SKU 相关字段,更新相关逻辑以支持新字段命名
This commit is contained in:
1 parent
dde25344ca
commit
46eb63f5bb
111 files changed
+3116
-1250
No files matched your search
@@ -79,6 +79,7 @@ const emit = defineEmits<{
|
||||
stop: [];
|
||||
'voice-click': [];
|
||||
'remove-attachment': [id: string];
|
||||
'retry-attachment': [id: string];
|
||||
'retry-shipping-notice-attachment': [id: string];
|
||||
'resolve-shipping-notice-duplicate': [id: string];
|
||||
'select-shipping-candidate': [candidateNo: string, selected: boolean];
|
||||
@@ -365,6 +366,22 @@ watch(
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="a.kind === 'local' && a.uploadStatus === 'failed'"
|
||||
class="absolute bottom-1.5 right-2 flex items-center gap-1"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded p-1 text-red-500 hover:bg-red-50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-400 disabled:cursor-not-allowed disabled:opacity-30 dark:hover:bg-red-950/30"
|
||||
:disabled="isUploadingAttachments"
|
||||
:title="t('chat.attachment.retry')"
|
||||
:aria-label="t('chat.attachment.retryNamed', { name: getAttachmentName(a) })"
|
||||
@click="emit('retry-attachment', a.id)"
|
||||
>
|
||||
<RefreshCw class="h-3.5 w-3.5" />
|
||||
</button>
|
||||
</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"
|
||||
|
||||
@@ -287,6 +287,7 @@ watch(() => page.currentAgentId, () => {
|
||||
@stop="page.stopActiveGeneration()"
|
||||
@voice-click="page.handleVoiceFeatureClick"
|
||||
@remove-attachment="page.removeAttachment"
|
||||
@retry-attachment="page.retryAttachment"
|
||||
@retry-shipping-notice-attachment="page.retryShippingNoticeAttachment"
|
||||
@resolve-shipping-notice-duplicate="page.openShippingDuplicateDialog"
|
||||
@select-shipping-candidate="page.setShippingCandidateSelected"
|
||||
|
||||
@@ -11,11 +11,12 @@ import type { ShippingDuplicateAction, ShippingNoticePendingAttachment } from '.
|
||||
|
||||
interface EditableCandidateLine {
|
||||
source: Record<string, unknown>;
|
||||
sku: string;
|
||||
part_number: string;
|
||||
customer_part_number: string;
|
||||
aws_part_number: string;
|
||||
qty: string;
|
||||
reservation_id: string;
|
||||
source_type: string;
|
||||
hub_code: string;
|
||||
inventory_source_hint: string;
|
||||
uom: string;
|
||||
}
|
||||
|
||||
@@ -47,7 +48,7 @@ watch(() => props.attachment.candidates, () => {
|
||||
|
||||
/**
|
||||
* 将 Candidate 摘要投影为可编辑的 PO 与订单行。
|
||||
* 核心逻辑:保留原始扩展字段,并显式映射 SKU、数量、Reservation ID、Source Type、Hub Code 与单位。
|
||||
* 核心逻辑:保留原始扩展字段,并显式映射三类料号、数量、Reservation ID、库存源线索与单位。
|
||||
* @param candidateNo - 待编辑的 Candidate 编号
|
||||
* @returns 无返回值;Candidate 不存在时保持当前编辑状态
|
||||
*/
|
||||
@@ -61,11 +62,12 @@ function startEdit(candidateNo: string): void {
|
||||
editPoNumber.value = String(candidate.businessSummary.po_number || candidate.poNumber || '');
|
||||
editLines.splice(0, editLines.length, ...sourceLines.map((line) => ({
|
||||
source: { ...line },
|
||||
sku: String(line.sku || ''),
|
||||
part_number: String(line.part_number || ''),
|
||||
customer_part_number: String(line.customer_part_number || ''),
|
||||
aws_part_number: String(line.aws_part_number || ''),
|
||||
qty: String(line.qty ?? ''),
|
||||
reservation_id: String(line.reservation_id || ''),
|
||||
source_type: String(line.source_type || ''),
|
||||
hub_code: String(line.hub_code || ''),
|
||||
inventory_source_hint: String(line.inventory_source_hint || ''),
|
||||
uom: String(line.uom || 'EA'),
|
||||
})));
|
||||
if (!editLines.length) addLine();
|
||||
@@ -74,16 +76,25 @@ function startEdit(candidateNo: string): void {
|
||||
|
||||
/**
|
||||
* 新增一条待修订订单行。
|
||||
* 核心逻辑:创建带可选 Source Type / Hub Code 路由线索的空白草稿。
|
||||
* 核心逻辑:创建带三类料号和可选库存源线索的空白草稿。
|
||||
* @returns 无返回值
|
||||
*/
|
||||
function addLine(): void {
|
||||
editLines.push({ source: {}, sku: '', qty: '', reservation_id: '', source_type: '', hub_code: '', uom: 'EA' });
|
||||
editLines.push({
|
||||
source: {},
|
||||
part_number: '',
|
||||
customer_part_number: '',
|
||||
aws_part_number: '',
|
||||
qty: '',
|
||||
reservation_id: '',
|
||||
inventory_source_hint: '',
|
||||
uom: 'EA',
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验并提交 Candidate 修订。
|
||||
* 核心逻辑:保留原始扩展字段;Source Type 与 Hub Code 分开提交,避免编辑时静默丢失 Hub Code。
|
||||
* 核心逻辑:保留原始扩展字段,并按 v2 契约提交三类料号与唯一库存源线索。
|
||||
* @returns 无返回值;校验失败时写入本地错误提示
|
||||
*/
|
||||
function saveEdit(): void {
|
||||
@@ -93,15 +104,16 @@ function saveEdit(): void {
|
||||
const source = { ...line.source };
|
||||
return {
|
||||
...source,
|
||||
sku: line.sku.trim(),
|
||||
part_number: line.part_number.trim(),
|
||||
customer_part_number: line.customer_part_number.trim() || undefined,
|
||||
aws_part_number: line.aws_part_number.trim() || undefined,
|
||||
qty: Number(line.qty),
|
||||
reservation_id: line.reservation_id.trim() || undefined,
|
||||
source_type: line.source_type.trim() || undefined,
|
||||
hub_code: line.hub_code.trim() || undefined,
|
||||
inventory_source_hint: line.inventory_source_hint.trim() || undefined,
|
||||
uom: line.uom.trim() || 'EA',
|
||||
};
|
||||
});
|
||||
if (normalizedLines.some((line) => !line.sku || !Number.isFinite(line.qty) || line.qty <= 0)) {
|
||||
if (normalizedLines.some((line) => !line.part_number || !Number.isFinite(line.qty) || line.qty <= 0)) {
|
||||
editError.value = t('chat.shippingCandidateInvalidLine');
|
||||
return;
|
||||
}
|
||||
@@ -198,6 +210,21 @@ function submitForceCreate(candidateNo: string): void {
|
||||
<div v-if="candidate.conflicts.length" class="mt-1 text-amber-700">
|
||||
{{ t('chat.shippingCandidateConflictCount', { count: candidate.conflicts.length }) }}
|
||||
</div>
|
||||
<div
|
||||
v-if="candidate.fieldAdjudication?.decisions?.length"
|
||||
class="mt-2 rounded-lg border border-sky-200 bg-sky-50/70 px-2 py-1.5"
|
||||
>
|
||||
<div class="font-semibold text-sky-900">{{ t('chat.shippingParsedResult.adjudicationTitle') }}</div>
|
||||
<div class="mt-1 flex flex-wrap gap-1">
|
||||
<span
|
||||
v-for="decision in candidate.fieldAdjudication.decisions"
|
||||
:key="`${decision.line_index}-${decision.field}`"
|
||||
class="rounded border border-sky-100 bg-white px-1.5 py-0.5 font-mono text-[10px] text-sky-900"
|
||||
>
|
||||
#{{ Number(decision.line_index) + 1 }} {{ decision.field }} · {{ decision.status }}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
v-if="editingCandidateNo !== candidate.candidateNo && readonlyLines(candidate).length"
|
||||
class="mt-2 overflow-x-auto rounded-lg border border-default bg-surface"
|
||||
@@ -205,11 +232,12 @@ function submitForceCreate(candidateNo: string): void {
|
||||
<table class="min-w-full text-[11px]">
|
||||
<thead class="bg-surface-soft text-left text-muted">
|
||||
<tr>
|
||||
<th class="px-2 py-1">{{ t('chat.shippingCandidateSku') }}</th>
|
||||
<th class="px-2 py-1">{{ t('chat.shippingNoticeUi.partNumber') }}</th>
|
||||
<th class="px-2 py-1">{{ t('chat.shippingNoticeUi.customerPartNumber') }}</th>
|
||||
<th class="px-2 py-1">{{ t('chat.shippingNoticeUi.awsPartNumber') }}</th>
|
||||
<th class="px-2 py-1">{{ t('chat.shippingCandidateQty') }}</th>
|
||||
<th class="px-2 py-1">{{ t('chat.shippingCandidateReservation') }}</th>
|
||||
<th class="px-2 py-1">{{ t('chat.shippingCandidateSourceType') }}</th>
|
||||
<th class="px-2 py-1">{{ t('chat.shippingCandidateHubCode') }}</th>
|
||||
<th class="px-2 py-1">{{ t('chat.shippingNoticeUi.inventorySourceHint') }}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@@ -218,11 +246,12 @@ function submitForceCreate(candidateNo: string): void {
|
||||
:key="`${candidate.candidateNo}-line-${index}`"
|
||||
class="border-t border-default/60"
|
||||
>
|
||||
<td class="px-2 py-1 font-mono">{{ displayCell(line.sku) }}</td>
|
||||
<td class="px-2 py-1 font-mono">{{ displayCell(line.part_number) }}</td>
|
||||
<td class="px-2 py-1 font-mono">{{ displayCell(line.customer_part_number) }}</td>
|
||||
<td class="px-2 py-1 font-mono">{{ displayCell(line.aws_part_number) }}</td>
|
||||
<td class="px-2 py-1">{{ displayCell(line.qty) }}</td>
|
||||
<td class="px-2 py-1 font-mono">{{ displayCell(line.reservation_id) }}</td>
|
||||
<td class="px-2 py-1">{{ displayCell(line.source_type) }}</td>
|
||||
<td class="px-2 py-1 font-mono">{{ displayCell(line.hub_code) }}</td>
|
||||
<td class="px-2 py-1">{{ displayCell(line.inventory_source_hint) }}</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
@@ -264,12 +293,13 @@ function submitForceCreate(candidateNo: string): void {
|
||||
<span class="text-muted">{{ t('chat.shippingCandidatePoNumber') }}</span>
|
||||
<input v-model="editPoNumber" class="mt-1 w-full rounded border border-default bg-surface px-2 py-1 text-primary" />
|
||||
</label>
|
||||
<div v-for="(line, index) in editLines" :key="index" class="grid grid-cols-2 gap-2 rounded border border-default bg-surface p-2 md:grid-cols-6">
|
||||
<input v-model="line.sku" :placeholder="t('chat.shippingCandidateSku')" class="rounded border border-default px-2 py-1" />
|
||||
<div v-for="(line, index) in editLines" :key="index" class="grid grid-cols-2 gap-2 rounded border border-default bg-surface p-2 md:grid-cols-4">
|
||||
<input v-model="line.part_number" :placeholder="t('chat.shippingNoticeUi.partNumber')" class="rounded border border-default px-2 py-1" />
|
||||
<input v-model="line.customer_part_number" :placeholder="t('chat.shippingNoticeUi.customerPartNumber')" class="rounded border border-default px-2 py-1" />
|
||||
<input v-model="line.aws_part_number" :placeholder="t('chat.shippingNoticeUi.awsPartNumber')" 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.source_type" :placeholder="t('chat.shippingCandidateSourceType')" 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.inventory_source_hint" :placeholder="t('chat.shippingNoticeUi.inventorySourceHint')" 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>
|
||||
|
||||
@@ -65,6 +65,10 @@ const missingFields = computed(() => {
|
||||
return Array.from(new Set([...gateMissing, ...candidateMissing].map((item) => String(item)).filter(Boolean)));
|
||||
});
|
||||
|
||||
const adjudicationDecisions = computed(() => (
|
||||
props.sourceCandidate?.field_adjudication?.decisions || []
|
||||
).filter((item) => item && typeof item === 'object'));
|
||||
|
||||
const hasBlocking = computed(() =>
|
||||
gateIssues.value.some((issue) => String(issue.severity || '') === 'blocking')
|
||||
|| missingFields.value.includes('reservation_id')
|
||||
@@ -167,7 +171,9 @@ function issueReasonLabel(reason?: string | null): string {
|
||||
<span class="font-mono">{{ issue.field }}</span>
|
||||
<span class="ml-1">{{ issueReasonLabel(issue.reason) }}</span>
|
||||
</div>
|
||||
<div v-if="issue.sku" class="mt-0.5 text-[11px] opacity-80">SKU {{ issue.sku }}</div>
|
||||
<div v-if="issue.part_number" class="mt-0.5 text-[11px] opacity-80">
|
||||
{{ t('chat.shippingNoticeUi.partNumber') }} {{ issue.part_number }}
|
||||
</div>
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
@@ -176,31 +182,49 @@ function issueReasonLabel(reason?: string | null): string {
|
||||
<thead class="bg-surface text-left text-[11px] text-muted">
|
||||
<tr>
|
||||
<th class="px-2.5 py-2">#</th>
|
||||
<th class="px-2.5 py-2">{{ t('chat.shippingNoticeUi.sku') }}</th>
|
||||
<th class="px-2.5 py-2">{{ t('chat.shippingNoticeUi.partNumber') }}</th>
|
||||
<th class="px-2.5 py-2">{{ t('chat.shippingNoticeUi.customerPartNumber') }}</th>
|
||||
<th class="px-2.5 py-2">{{ t('chat.shippingNoticeUi.awsPartNumber') }}</th>
|
||||
<th class="px-2.5 py-2">{{ t('chat.shippingNoticeUi.qty') }}</th>
|
||||
<th class="px-2.5 py-2">{{ t('chat.shippingNoticeUi.reservationId') }}</th>
|
||||
<th class="px-2.5 py-2">{{ t('chat.shippingParsedResult.sourceType') }}</th>
|
||||
<th class="px-2.5 py-2">{{ t('chat.shippingParsedResult.hubCode') }}</th>
|
||||
<th class="px-2.5 py-2">{{ t('chat.shippingNoticeUi.inventorySourceHint') }}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr
|
||||
v-for="(line, index) in orderLines"
|
||||
:key="`${line.sku}-${index}`"
|
||||
:key="`${line.part_number}-${index}`"
|
||||
class="border-t border-default/60 text-xs"
|
||||
>
|
||||
<td class="px-2.5 py-2 text-muted">{{ index + 1 }}</td>
|
||||
<td class="px-2.5 py-2 font-mono">{{ displayValue(line.sku) }}</td>
|
||||
<td class="px-2.5 py-2 font-mono">{{ displayValue(line.part_number) }}</td>
|
||||
<td class="px-2.5 py-2 font-mono">{{ displayValue(line.customer_part_number) }}</td>
|
||||
<td class="px-2.5 py-2 font-mono">{{ displayValue(line.aws_part_number) }}</td>
|
||||
<td class="px-2.5 py-2">{{ displayValue(line.qty) }}</td>
|
||||
<td class="px-2.5 py-2 font-mono">{{ displayValue(line.reservation_id) }}</td>
|
||||
<td class="px-2.5 py-2">{{ displayValue(line.source_type) }}</td>
|
||||
<td class="px-2.5 py-2 font-mono">{{ displayValue(line.hub_code) }}</td>
|
||||
<td class="px-2.5 py-2">{{ displayValue(line.inventory_source_hint) }}</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<div v-else class="text-muted">{{ t('chat.shippingParsedResult.noLines') }}</div>
|
||||
|
||||
<div v-if="adjudicationDecisions.length" class="rounded-xl border border-sky-200 bg-sky-50/70 p-2.5">
|
||||
<div class="font-semibold text-sky-900">{{ t('chat.shippingParsedResult.adjudicationTitle') }}</div>
|
||||
<div class="mt-2 grid gap-1.5 md:grid-cols-2">
|
||||
<div
|
||||
v-for="decision in adjudicationDecisions"
|
||||
:key="`${decision.line_index}-${decision.field}`"
|
||||
class="rounded border border-sky-100 bg-white/80 px-2 py-1.5 text-[11px]"
|
||||
>
|
||||
<span class="font-mono">#{{ Number(decision.line_index) + 1 }} {{ decision.field }}</span>
|
||||
<span class="ml-1 font-semibold text-sky-800">{{ decision.status }}</span>
|
||||
<span v-if="decision.score != null" class="ml-1 text-muted">{{ t('chat.shippingParsedResult.score', { score: decision.score }) }}</span>
|
||||
<div class="mt-0.5 truncate text-secondary">{{ displayValue(decision.value) }}</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<ShippingFieldEvidencePanel
|
||||
:evidence="sourceCandidate?.evidence || []"
|
||||
:compact="compact"
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
/**
|
||||
* features/chat/components/messages/ChatMessageAttachmentList.vue
|
||||
* 用途:在用户消息中展示已发送附件快照。
|
||||
* 用途:在用户消息气泡内部展示已发送附件快照。
|
||||
* 依赖:lucide 文件图标、attachmentCard.utils 的大小格式化、chat.types 的消息附件契约。
|
||||
* 逻辑:ChatMessageBubble 将当前用户消息附件传入;本组件只读展示,不提供删除、重试或上传状态操作。
|
||||
* 逻辑:ChatMessageBubble 将当前用户消息附件传入;卡片继承品牌气泡语境,只读展示且不提供删除或重试。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import { FileAudio, FileImage, FileText, FileVideo, Link2 } from 'lucide-vue-next';
|
||||
@@ -35,16 +35,16 @@ function attachmentBadge(attachment: ChatMessageAttachment): string {
|
||||
<div
|
||||
v-if="attachments.length > 0"
|
||||
data-testid="chat-message-attachment-list"
|
||||
class="mb-2 flex w-full flex-wrap justify-end gap-2"
|
||||
class="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]"
|
||||
class="flex min-w-0 basis-full items-center gap-2.5 rounded-xl border border-white/20 bg-white/10 px-3 py-2.5 shadow-sm backdrop-blur-sm 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"
|
||||
class="flex h-10 w-9 shrink-0 flex-col items-center justify-center rounded-lg bg-white/15 text-white"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<component :is="attachmentIcon(attachment)" class="h-4 w-4" />
|
||||
@@ -53,8 +53,8 @@ function attachmentBadge(attachment: ChatMessageAttachment): string {
|
||||
</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">
|
||||
<div class="truncate text-sm font-semibold text-white">{{ attachment.name }}</div>
|
||||
<div v-if="attachment.size !== undefined" class="mt-1 text-[11px] leading-none text-white/70">
|
||||
{{ formatAttachmentSize(attachment.size) }}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
* features/chat/components/messages/ChatMessageBubble.vue
|
||||
* 用途:渲染单条聊天消息,统一承接用户气泡、助手 Markdown、内嵌文件下载、请假/出货子组件与操作栏。
|
||||
* 依赖:Vue computed、lucide 图标、消息附件/Leave/Shipping 子组件、chat.types 与页面级 handlers。
|
||||
* 逻辑:由 ChatMessageList 按消息逐条挂载;用户附件显示在文字气泡上方,助手正文与特殊交互委托页面 handlers。
|
||||
* 逻辑:由 ChatMessageList 按消息逐条挂载;用户附件与文字共用同一气泡,助手正文与特殊交互委托页面 handlers。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import { computed, nextTick, ref, watch } from 'vue';
|
||||
@@ -125,6 +125,8 @@ const showSourceSection = computed(() => {
|
||||
});
|
||||
|
||||
const hasUserContent = computed(() => message.role === 'user' && String(message.content || '').trim().length > 0);
|
||||
const hasUserAttachments = computed(() => message.role === 'user' && !!message.attachments?.length);
|
||||
const hasUserPayload = computed(() => hasUserContent.value || hasUserAttachments.value);
|
||||
const showActions = computed(() => (
|
||||
message.type !== 'leave-form'
|
||||
&& (message.role !== 'user' || hasUserContent.value)
|
||||
@@ -655,18 +657,20 @@ 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"
|
||||
v-if="message.role === 'assistant' || hasUserPayload"
|
||||
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'
|
||||
? 'rounded-2xl rounded-tr-sm bg-brand-600 p-2.5 text-white shadow-sm shadow-brand-500/15'
|
||||
: 'chat-msg-assistant'"
|
||||
>
|
||||
<div v-if="message.role === 'user'" class="whitespace-pre-wrap">{{ message.content }}</div>
|
||||
<template v-if="message.role === 'user'">
|
||||
<ChatMessageAttachmentList
|
||||
v-if="message.attachments?.length"
|
||||
:attachments="message.attachments"
|
||||
/>
|
||||
<div v-if="hasUserContent" class="whitespace-pre-wrap px-2.5 py-1">{{ message.content }}</div>
|
||||
</template>
|
||||
<div v-else>
|
||||
<div
|
||||
v-if="shippingOrderExtractionState"
|
||||
|
||||
@@ -59,20 +59,20 @@ const { message, handlers } = defineProps<{
|
||||
<div class="space-y-2">
|
||||
<div class="text-xs font-bold uppercase tracking-wider text-muted">{{ $t('chat.shippingNoticeMapping.orderDetails') }}</div>
|
||||
<div class="text-xs text-muted">
|
||||
{{ $t('chat.shippingNoticeMapping.orderRowCount', { count: handlers.getPayload(message)!.order.line_count }) }};{{ $t('chat.shippingNoticeMapping.orderSkuPreview', { count: handlers.getPayload(message)!.order.skus.length, skus: handlers.getPayload(message)!.order.skus.join(',') || $t('chat.shippingNoticeMapping.unrecognized') }) }}
|
||||
{{ $t('chat.shippingNoticeMapping.orderRowCount', { count: handlers.getPayload(message)!.order.line_count }) }};{{ $t('chat.shippingNoticeMapping.orderPartNumberPreview', { count: handlers.getPayload(message)!.order.part_numbers.length, partNumbers: handlers.getPayload(message)!.order.part_numbers.join(',') || $t('chat.shippingNoticeMapping.unrecognized') }) }}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="grid gap-4 md:grid-cols-2">
|
||||
<label class="space-y-1.5">
|
||||
<span class="text-xs font-semibold text-muted">{{ $t('chat.shippingNoticeMapping.skuColumnRequired') }}</span>
|
||||
<span class="text-xs font-semibold text-muted">{{ $t('chat.shippingNoticeMapping.partNumberColumnRequired') }}</span>
|
||||
<select
|
||||
v-model="handlers.getPayload(message)!.form.sku"
|
||||
v-model="handlers.getPayload(message)!.form.part_number"
|
||||
class="w-full rounded-xl border border-default px-3 py-2 text-sm text-secondary outline-none transition focus:border-blue-400"
|
||||
:disabled="handlers.getPayload(message)!.applying"
|
||||
>
|
||||
<option value="" disabled>{{ $t('chat.shippingNoticeMapping.selectHeader') }}</option>
|
||||
<option v-for="h in (handlers.getPayload(message)!.schema_preview.headers || [])" :key="`sku-${h}`" :value="h">{{ handlers.normalizeHeader(h) }}</option>
|
||||
<option v-for="h in (handlers.getPayload(message)!.schema_preview.headers || [])" :key="`part-number-${h}`" :value="h">{{ handlers.normalizeHeader(h) }}</option>
|
||||
</select>
|
||||
</label>
|
||||
<label class="space-y-1.5">
|
||||
@@ -87,13 +87,13 @@ const { message, handlers } = defineProps<{
|
||||
</select>
|
||||
</label>
|
||||
<label class="space-y-1.5 md:col-span-2">
|
||||
<span class="text-xs font-semibold text-muted">{{ $t('chat.shippingNoticeMapping.reservationIdColumnOptional') }}</span>
|
||||
<span class="text-xs font-semibold text-muted">{{ $t('chat.shippingNoticeMapping.reservationIdColumnRequired') }}</span>
|
||||
<select
|
||||
v-model="handlers.getPayload(message)!.form.reservation_id"
|
||||
class="w-full rounded-xl border border-default px-3 py-2 text-sm text-secondary outline-none transition focus:border-blue-400"
|
||||
:disabled="handlers.getPayload(message)!.applying"
|
||||
>
|
||||
<option value="">{{ $t('chat.shippingNoticeMapping.reservationIdNotUsed') }}</option>
|
||||
<option value="" disabled>{{ $t('chat.shippingNoticeMapping.selectHeader') }}</option>
|
||||
<option v-for="h in (handlers.getPayload(message)!.schema_preview.headers || [])" :key="`rid-${h}`" :value="h">{{ handlers.normalizeHeader(h) }}</option>
|
||||
</select>
|
||||
</label>
|
||||
|
||||
@@ -76,7 +76,7 @@ const hasShortage = () => Array.isArray(props.shortageLines) && props.shortageLi
|
||||
<tr>
|
||||
<th class="px-3 py-2">#</th>
|
||||
<th class="px-3 py-2">{{ t('chat.shippingNoticeUi.reservationId') }}</th>
|
||||
<th class="px-3 py-2">{{ t('chat.shippingNoticeUi.sku') }}</th>
|
||||
<th class="px-3 py-2">{{ t('chat.shippingNoticeUi.partNumber') }}</th>
|
||||
<th class="px-3 py-2">{{ t('chat.shippingNoticeUi.orderDemand') }}</th>
|
||||
<th class="px-3 py-2">{{ t('chat.shippingNoticeUi.inventoryAvailable') }}</th>
|
||||
<th class="px-3 py-2">{{ t('chat.shippingNoticeUi.shortageQty') }}</th>
|
||||
@@ -91,7 +91,7 @@ const hasShortage = () => Array.isArray(props.shortageLines) && props.shortageLi
|
||||
>
|
||||
<td class="px-3 py-2 text-secondary">{{ index + 1 }}</td>
|
||||
<td class="px-3 py-2 text-secondary">{{ line.reservation_id || '-' }}</td>
|
||||
<td class="px-3 py-2 font-mono text-secondary">{{ line.sku || '-' }}</td>
|
||||
<td class="px-3 py-2 font-mono text-secondary">{{ line.part_number || '-' }}</td>
|
||||
<td class="px-3 py-2 text-secondary">{{ formatQty(line.required_qty) }}</td>
|
||||
<td class="px-3 py-2 text-secondary">{{ formatQty(line.available_qty) }}</td>
|
||||
<td class="px-3 py-2" :class="Number(line.shortage_qty || 0) > 0 ? 'font-semibold text-rose-700' : 'text-secondary'">
|
||||
@@ -121,7 +121,7 @@ const hasShortage = () => Array.isArray(props.shortageLines) && props.shortageLi
|
||||
v-for="(line, index) in shortageLines"
|
||||
:key="`${taskId}-shortage-${index}`"
|
||||
>
|
||||
{{ t('chat.shippingNoticeUi.shortageRowDetail', { index: index + 1, reservationId: line.reservation_id || '-', sku: line.sku || '-', shortage: formatQty(line.shortage_qty) }) }}
|
||||
{{ t('chat.shippingNoticeUi.shortageRowDetail', { index: index + 1, reservationId: line.reservation_id || '-', partNumber: line.part_number || '-', shortage: formatQty(line.shortage_qty) }) }}
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
@@ -36,7 +36,10 @@ const headerForm = reactive<ShippingNoticeHeader>({
|
||||
});
|
||||
const lineForm = reactive<Partial<ShippingNoticeLine>>({
|
||||
reservation_id: '',
|
||||
sku: '',
|
||||
part_number: '',
|
||||
customer_part_number: '',
|
||||
aws_part_number: '',
|
||||
inventory_source_hint: '',
|
||||
qty: 0,
|
||||
required_date: '',
|
||||
uom: '',
|
||||
@@ -61,7 +64,10 @@ watch(
|
||||
const line = payload.value.lines[value];
|
||||
if (!line) return;
|
||||
lineForm.reservation_id = line.reservation_id ?? '';
|
||||
lineForm.sku = line.sku;
|
||||
lineForm.part_number = line.part_number;
|
||||
lineForm.customer_part_number = line.customer_part_number ?? '';
|
||||
lineForm.aws_part_number = line.aws_part_number ?? '';
|
||||
lineForm.inventory_source_hint = line.inventory_source_hint ?? '';
|
||||
lineForm.qty = line.qty;
|
||||
lineForm.required_date = line.required_date ?? '';
|
||||
lineForm.uom = line.uom ?? '';
|
||||
@@ -84,7 +90,10 @@ const saveLine = async () => {
|
||||
if (editingLineIndex.value == null) return;
|
||||
const ok = await handlers.updateLine(message, editingLineIndex.value, {
|
||||
reservation_id: lineForm.reservation_id,
|
||||
sku: lineForm.sku,
|
||||
part_number: lineForm.part_number,
|
||||
customer_part_number: lineForm.customer_part_number,
|
||||
aws_part_number: lineForm.aws_part_number,
|
||||
inventory_source_hint: lineForm.inventory_source_hint,
|
||||
qty: Number(lineForm.qty || 0),
|
||||
required_date: lineForm.required_date,
|
||||
uom: lineForm.uom,
|
||||
@@ -96,7 +105,10 @@ const startAddLine = () => {
|
||||
addingLine.value = true;
|
||||
editingLineIndex.value = null;
|
||||
lineForm.reservation_id = '';
|
||||
lineForm.sku = '';
|
||||
lineForm.part_number = '';
|
||||
lineForm.customer_part_number = '';
|
||||
lineForm.aws_part_number = '';
|
||||
lineForm.inventory_source_hint = '';
|
||||
lineForm.qty = 0;
|
||||
lineForm.required_date = '';
|
||||
lineForm.uom = '';
|
||||
@@ -105,7 +117,10 @@ const startAddLine = () => {
|
||||
const saveAddedLine = async () => {
|
||||
const ok = await handlers.addLine(message, {
|
||||
reservation_id: lineForm.reservation_id,
|
||||
sku: lineForm.sku,
|
||||
part_number: lineForm.part_number,
|
||||
customer_part_number: lineForm.customer_part_number,
|
||||
aws_part_number: lineForm.aws_part_number,
|
||||
inventory_source_hint: lineForm.inventory_source_hint,
|
||||
qty: Number(lineForm.qty || 0),
|
||||
required_date: lineForm.required_date,
|
||||
uom: lineForm.uom,
|
||||
@@ -207,7 +222,9 @@ const removeLine = async (lineIndex: number) => {
|
||||
<tr>
|
||||
<th class="border border-default bg-surface px-3 py-2 text-left text-xs font-semibold text-muted">#</th>
|
||||
<th class="border border-default bg-surface px-3 py-2 text-left text-xs font-semibold text-muted">{{ t('chat.shippingNoticeUi.reservationId') }}</th>
|
||||
<th class="border border-default bg-surface px-3 py-2 text-left text-xs font-semibold text-muted">{{ t('chat.shippingNoticeUi.sku') }}</th>
|
||||
<th class="border border-default bg-surface px-3 py-2 text-left text-xs font-semibold text-muted">{{ t('chat.shippingNoticeUi.partNumber') }}</th>
|
||||
<th class="border border-default bg-surface px-3 py-2 text-left text-xs font-semibold text-muted">{{ t('chat.shippingNoticeUi.customerPartNumber') }}</th>
|
||||
<th class="border border-default bg-surface px-3 py-2 text-left text-xs font-semibold text-muted">{{ t('chat.shippingNoticeUi.awsPartNumber') }}</th>
|
||||
<th class="border border-default bg-surface px-3 py-2 text-left text-xs font-semibold text-muted">{{ t('chat.shippingNoticeUi.qty') }}</th>
|
||||
<th class="border border-default bg-surface px-3 py-2 text-left text-xs font-semibold text-muted">{{ t('chat.shippingNoticeUi.requiredDate') }}</th>
|
||||
<th class="border border-default bg-surface px-3 py-2 text-left text-xs font-semibold text-muted">{{ t('chat.shippingNoticeUi.actions') }}</th>
|
||||
@@ -217,7 +234,9 @@ const removeLine = async (lineIndex: number) => {
|
||||
<tr v-for="(line, lineIndex) in payload.lines" :key="`${payload.taskId}-${line.line_no || lineIndex}`">
|
||||
<td class="border border-default px-3 py-2 text-secondary">{{ lineIndex + 1 }}</td>
|
||||
<td class="border border-default px-3 py-2 text-secondary">{{ line.reservation_id || '-' }}</td>
|
||||
<td class="border border-default px-3 py-2 text-secondary">{{ line.sku }}</td>
|
||||
<td class="border border-default px-3 py-2 text-secondary">{{ line.part_number }}</td>
|
||||
<td class="border border-default px-3 py-2 text-secondary">{{ line.customer_part_number || '-' }}</td>
|
||||
<td class="border border-default px-3 py-2 text-secondary">{{ line.aws_part_number || '-' }}</td>
|
||||
<td class="border border-default px-3 py-2 text-secondary">{{ line.qty }}</td>
|
||||
<td class="border border-default px-3 py-2 text-secondary">{{ line.required_date || '-' }}</td>
|
||||
<td class="border border-default px-3 py-2">
|
||||
@@ -251,8 +270,20 @@ const removeLine = async (lineIndex: number) => {
|
||||
<input v-model="lineForm.reservation_id" class="w-full rounded-xl border border-default px-3 py-2 text-sm text-secondary outline-none transition focus:border-blue-400" />
|
||||
</label>
|
||||
<label class="space-y-1.5">
|
||||
<span class="text-xs font-semibold text-muted">{{ t('chat.shippingNoticeUi.sku') }}</span>
|
||||
<input v-model="lineForm.sku" class="w-full rounded-xl border border-default px-3 py-2 text-sm text-secondary outline-none transition focus:border-blue-400" />
|
||||
<span class="text-xs font-semibold text-muted">{{ t('chat.shippingNoticeUi.partNumber') }}</span>
|
||||
<input v-model="lineForm.part_number" class="w-full rounded-xl border border-default px-3 py-2 text-sm text-secondary outline-none transition focus:border-blue-400" />
|
||||
</label>
|
||||
<label class="space-y-1.5">
|
||||
<span class="text-xs font-semibold text-muted">{{ t('chat.shippingNoticeUi.customerPartNumber') }}</span>
|
||||
<input v-model="lineForm.customer_part_number" class="w-full rounded-xl border border-default px-3 py-2 text-sm text-secondary outline-none transition focus:border-blue-400" />
|
||||
</label>
|
||||
<label class="space-y-1.5">
|
||||
<span class="text-xs font-semibold text-muted">{{ t('chat.shippingNoticeUi.awsPartNumber') }}</span>
|
||||
<input v-model="lineForm.aws_part_number" class="w-full rounded-xl border border-default px-3 py-2 text-sm text-secondary outline-none transition focus:border-blue-400" />
|
||||
</label>
|
||||
<label class="space-y-1.5">
|
||||
<span class="text-xs font-semibold text-muted">{{ t('chat.shippingNoticeUi.inventorySourceHint') }}</span>
|
||||
<input v-model="lineForm.inventory_source_hint" class="w-full rounded-xl border border-default px-3 py-2 text-sm text-secondary outline-none transition focus:border-blue-400" />
|
||||
</label>
|
||||
<label class="space-y-1.5">
|
||||
<span class="text-xs font-semibold text-muted">{{ t('chat.shippingNoticeUi.qty') }}</span>
|
||||
@@ -291,8 +322,20 @@ const removeLine = async (lineIndex: number) => {
|
||||
<input v-model="lineForm.reservation_id" class="w-full rounded-xl border border-default px-3 py-2 text-sm text-secondary outline-none transition focus:border-blue-400" />
|
||||
</label>
|
||||
<label class="space-y-1.5">
|
||||
<span class="text-xs font-semibold text-muted">{{ t('chat.shippingNoticeUi.sku') }}</span>
|
||||
<input v-model="lineForm.sku" class="w-full rounded-xl border border-default px-3 py-2 text-sm text-secondary outline-none transition focus:border-blue-400" />
|
||||
<span class="text-xs font-semibold text-muted">{{ t('chat.shippingNoticeUi.partNumber') }}</span>
|
||||
<input v-model="lineForm.part_number" class="w-full rounded-xl border border-default px-3 py-2 text-sm text-secondary outline-none transition focus:border-blue-400" />
|
||||
</label>
|
||||
<label class="space-y-1.5">
|
||||
<span class="text-xs font-semibold text-muted">{{ t('chat.shippingNoticeUi.customerPartNumber') }}</span>
|
||||
<input v-model="lineForm.customer_part_number" class="w-full rounded-xl border border-default px-3 py-2 text-sm text-secondary outline-none transition focus:border-blue-400" />
|
||||
</label>
|
||||
<label class="space-y-1.5">
|
||||
<span class="text-xs font-semibold text-muted">{{ t('chat.shippingNoticeUi.awsPartNumber') }}</span>
|
||||
<input v-model="lineForm.aws_part_number" class="w-full rounded-xl border border-default px-3 py-2 text-sm text-secondary outline-none transition focus:border-blue-400" />
|
||||
</label>
|
||||
<label class="space-y-1.5">
|
||||
<span class="text-xs font-semibold text-muted">{{ t('chat.shippingNoticeUi.inventorySourceHint') }}</span>
|
||||
<input v-model="lineForm.inventory_source_hint" class="w-full rounded-xl border border-default px-3 py-2 text-sm text-secondary outline-none transition focus:border-blue-400" />
|
||||
</label>
|
||||
<label class="space-y-1.5">
|
||||
<span class="text-xs font-semibold text-muted">{{ t('chat.shippingNoticeUi.qty') }}</span>
|
||||
|
||||
@@ -17,6 +17,7 @@ import type {
|
||||
ShippingOrderExtractionStatus,
|
||||
} from '../types/chat.types';
|
||||
import type { ShippingBatchUiState, ShippingTaskUiState } from '../types/shipping.api.types';
|
||||
import type { ChatMessageSendResult } from '../types/chat-turn.types';
|
||||
import { createStartChatTurn } from './useChatTurn';
|
||||
|
||||
export interface SendMessageLifecycleHooks {
|
||||
@@ -533,7 +534,7 @@ export function useChat() {
|
||||
>,
|
||||
context?: { task_id?: string; batch_no?: string; shipping_intake_nos?: string[]; display_query?: string },
|
||||
hooks?: SendMessageLifecycleHooks,
|
||||
) => {
|
||||
): Promise<ChatMessageSendResult> => {
|
||||
const displayQuery = String(
|
||||
context && Object.prototype.hasOwnProperty.call(context, 'display_query')
|
||||
? context.display_query ?? ''
|
||||
@@ -565,10 +566,12 @@ export function useChat() {
|
||||
if (runs.value.length > 30) runs.value = runs.value.slice(0, 30);
|
||||
activeRunId.value = run.runId;
|
||||
|
||||
runMessages.push(createUserChatMessage(displayQuery, hooks?.userAttachments));
|
||||
const userMessageIndex = runMessages.push(createUserChatMessage(displayQuery, hooks?.userAttachments)) - 1;
|
||||
let botMsgIndex: number | null = null;
|
||||
let hasAssistantContent = false;
|
||||
let hasTerminalEvent = false;
|
||||
let requestAccepted = false;
|
||||
let chatLogId: number | undefined;
|
||||
let ignoreFurtherStreamEvents = false;
|
||||
const ensureBotMessage = () => {
|
||||
if (botMsgIndex === null) {
|
||||
@@ -609,6 +612,7 @@ export function useChat() {
|
||||
const err = await response.json().catch(() => ({}));
|
||||
throw new Error((err as { error?: string }).error || `Request failed with status ${response.status}`);
|
||||
}
|
||||
requestAccepted = true;
|
||||
|
||||
const reader = response.body?.getReader();
|
||||
const decoder = new TextDecoder();
|
||||
@@ -655,6 +659,10 @@ export function useChat() {
|
||||
}
|
||||
|
||||
const eventName = String(data.event || '');
|
||||
const eventChatLogId = Number(data.chat_log_id || 0);
|
||||
if (Number.isInteger(eventChatLogId) && eventChatLogId > 0) {
|
||||
chatLogId = eventChatLogId;
|
||||
}
|
||||
if (ignoreFurtherStreamEvents && !isAllowedAfterStreamTerminal(eventName)) {
|
||||
continue;
|
||||
}
|
||||
@@ -791,11 +799,24 @@ export function useChat() {
|
||||
if (run.status === 'done' && botMsgIndex !== null) {
|
||||
const botMsg = runMessages[botMsgIndex];
|
||||
if (botMsg) {
|
||||
await hooks?.onAssistantMessageFinished?.(botMsg, runMessages);
|
||||
try {
|
||||
await hooks?.onAssistantMessageFinished?.(botMsg, runMessages);
|
||||
} catch (error) {
|
||||
// 助手完成后的领域刷新属于附加动作,失败不能反向改变已被服务端接受的消息结果。
|
||||
console.error('[chat] onAssistantMessageFinished failed', error);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!requestAccepted) {
|
||||
const removeCount = botMsgIndex === null ? 1 : Math.max(botMsgIndex - userMessageIndex + 1, 1);
|
||||
runMessages.splice(userMessageIndex, removeCount);
|
||||
}
|
||||
}
|
||||
return run.status === 'done';
|
||||
return {
|
||||
accepted: requestAccepted,
|
||||
completed: requestAccepted && run.status === 'done',
|
||||
...(chatLogId ? { chatLogId } : {}),
|
||||
};
|
||||
};
|
||||
|
||||
return {
|
||||
|
||||
@@ -20,6 +20,7 @@ const uploadChatFileMock = vi.mocked(uploadChatFile);
|
||||
function createAttachments() {
|
||||
return useChatAttachments({
|
||||
deps: {
|
||||
t: ((key: string, params?: Record<string, unknown>) => `${key}${params ? JSON.stringify(params) : ''}`),
|
||||
msg: { warning: vi.fn() },
|
||||
} as unknown as ChatDeps,
|
||||
currentAgentId: computed(() => 7),
|
||||
@@ -38,7 +39,7 @@ function createAttachments() {
|
||||
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];
|
||||
return api.attachments.value.at(-1);
|
||||
}
|
||||
|
||||
describe('useChatAttachments upload states', () => {
|
||||
@@ -86,6 +87,41 @@ describe('useChatAttachments upload states', () => {
|
||||
expect(attachment && 'errorMessage' in attachment ? attachment.errorMessage : undefined).toBeUndefined();
|
||||
});
|
||||
|
||||
it('explicitly retries only the selected failed attachment', async () => {
|
||||
const api = createAttachments();
|
||||
const first = selectLocalFile(api, 'first.pdf');
|
||||
const second = selectLocalFile(api, 'second.pdf');
|
||||
if (first?.kind === 'local') first.uploadStatus = 'failed';
|
||||
if (second?.kind === 'local') {
|
||||
second.uploadStatus = 'uploaded';
|
||||
second.uploadFileId = 'upload-second';
|
||||
}
|
||||
uploadChatFileMock.mockResolvedValueOnce({ id: 'upload-first-retry' });
|
||||
|
||||
await expect(api.retryAttachment(first?.id || '')).resolves.toBe(true);
|
||||
|
||||
expect(uploadChatFileMock).toHaveBeenCalledOnce();
|
||||
expect(uploadChatFileMock).toHaveBeenCalledWith(7, first && 'file' in first ? first.file : undefined);
|
||||
expect(first).toMatchObject({ uploadStatus: 'uploaded', uploadFileId: 'upload-first-retry' });
|
||||
expect(second).toMatchObject({ uploadStatus: 'uploaded', uploadFileId: 'upload-second' });
|
||||
});
|
||||
|
||||
it('keeps explicit retry failures available for another retry', async () => {
|
||||
const api = createAttachments();
|
||||
const attachment = selectLocalFile(api);
|
||||
if (attachment?.kind === 'local') attachment.uploadStatus = 'failed';
|
||||
uploadChatFileMock.mockRejectedValueOnce(new Error('still unavailable'));
|
||||
|
||||
await expect(api.retryAttachment(attachment?.id || '')).resolves.toBe(false);
|
||||
|
||||
expect(attachment).toMatchObject({
|
||||
uploadStatus: 'failed',
|
||||
uploadProgress: 0,
|
||||
errorMessage: 'still unavailable',
|
||||
});
|
||||
expect(api.attachments.value).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('reuses earlier successful files when a later file failed', async () => {
|
||||
const api = createAttachments();
|
||||
selectLocalFile(api, 'first.pdf');
|
||||
|
||||
@@ -66,7 +66,7 @@ export interface UseChatAttachmentsOptions {
|
||||
|
||||
export function useChatAttachments(options: UseChatAttachmentsOptions) {
|
||||
const { deps, currentAgentId, currentAgent } = options;
|
||||
const { msg } = deps;
|
||||
const { msg, t } = deps;
|
||||
|
||||
const attachments = ref<PendingAttachment[]>([]);
|
||||
const isUploadingAttachments = ref(false);
|
||||
@@ -265,12 +265,12 @@ export function useChatAttachments(options: UseChatAttachmentsOptions) {
|
||||
const files = Array.from(fileList);
|
||||
for (const f of files) {
|
||||
if (attachmentPolicy.value.totalLimit && attachments.value.length >= attachmentPolicy.value.totalLimit) {
|
||||
msg.warning(`附件数量已达上限(${attachmentPolicy.value.totalLimit})`);
|
||||
msg.warning(t('chat.attachment.totalLimit', { limit: attachmentPolicy.value.totalLimit }));
|
||||
break;
|
||||
}
|
||||
const ext = extractExt(f.name || '');
|
||||
if (attachmentPolicy.value.allowedExts && (!ext || !attachmentPolicy.value.allowedExts.has(ext))) {
|
||||
msg.warning(`不支持的附件类型:${f.name}`);
|
||||
msg.warning(t('chat.attachment.unsupportedFile', { name: f.name }));
|
||||
continue;
|
||||
}
|
||||
let type = inferFileTypeFromFile(f);
|
||||
@@ -278,23 +278,23 @@ export function useChatAttachments(options: UseChatAttachmentsOptions) {
|
||||
if (attachmentPolicy.value.enabled.custom.local && !isKnownDifyExt(ext)) {
|
||||
type = 'custom';
|
||||
} else {
|
||||
msg.warning(`不支持的附件类型:${f.name}`);
|
||||
msg.warning(t('chat.attachment.unsupportedFile', { name: f.name }));
|
||||
continue;
|
||||
}
|
||||
}
|
||||
const caps = attachmentPolicy.value.enabled[type];
|
||||
if (!caps?.local) {
|
||||
msg.warning(`当前应用不支持上传此类型附件:${type}`);
|
||||
msg.warning(t('chat.attachment.localTypeDisabled', { type }));
|
||||
continue;
|
||||
}
|
||||
const limit = attachmentPolicy.value.sizeLimitMb[type];
|
||||
if (limit && f.size > limit * 1024 * 1024) {
|
||||
msg.warning(`附件过大(上限 ${limit}MB):${f.name}`);
|
||||
msg.warning(t('chat.attachment.fileTooLarge', { limit, name: f.name }));
|
||||
continue;
|
||||
}
|
||||
const countSameType = attachments.value.filter((a) => a.type === type).length;
|
||||
if (caps.limit && countSameType >= caps.limit) {
|
||||
msg.warning(`该类型附件数量已达上限(${caps.limit})`);
|
||||
msg.warning(t('chat.attachment.typeLimit', { limit: caps.limit }));
|
||||
continue;
|
||||
}
|
||||
attachments.value.push({
|
||||
@@ -314,20 +314,20 @@ export function useChatAttachments(options: UseChatAttachmentsOptions) {
|
||||
if (!raw) return;
|
||||
const url = raw.startsWith('//') ? `${window.location.protocol}${raw}` : raw;
|
||||
if (!/^https?:\/\//i.test(url)) {
|
||||
msg.warning('仅支持 http/https URL');
|
||||
msg.warning(t('chat.attachment.httpOnly'));
|
||||
return;
|
||||
}
|
||||
if (!attachmentPolicy.value.canRemote) {
|
||||
msg.warning('当前应用不支持 URL 附件');
|
||||
msg.warning(t('chat.attachment.remoteDisabled'));
|
||||
return;
|
||||
}
|
||||
if (attachmentPolicy.value.totalLimit && attachments.value.length >= attachmentPolicy.value.totalLimit) {
|
||||
msg.warning(`附件数量已达上限(${attachmentPolicy.value.totalLimit})`);
|
||||
msg.warning(t('chat.attachment.totalLimit', { limit: attachmentPolicy.value.totalLimit }));
|
||||
return;
|
||||
}
|
||||
const ext = extractExt(url);
|
||||
if (attachmentPolicy.value.allowedExts && (!ext || !attachmentPolicy.value.allowedExts.has(ext))) {
|
||||
msg.warning('不支持的 URL 附件类型');
|
||||
msg.warning(t('chat.attachment.unsupportedRemote'));
|
||||
return;
|
||||
}
|
||||
let type = inferFileTypeFromUrl(url);
|
||||
@@ -335,23 +335,70 @@ export function useChatAttachments(options: UseChatAttachmentsOptions) {
|
||||
if (attachmentPolicy.value.enabled.custom.remote && !isKnownDifyExt(ext)) {
|
||||
type = 'custom';
|
||||
} else {
|
||||
msg.warning('不支持的 URL 附件类型');
|
||||
msg.warning(t('chat.attachment.unsupportedRemote'));
|
||||
return;
|
||||
}
|
||||
}
|
||||
const caps = attachmentPolicy.value.enabled[type];
|
||||
if (!caps?.remote) {
|
||||
msg.warning(`当前应用不支持该类型 URL 附件:${type}`);
|
||||
msg.warning(t('chat.attachment.remoteTypeDisabled', { type }));
|
||||
return;
|
||||
}
|
||||
const countSameType = attachments.value.filter((a) => a.type === type).length;
|
||||
if (caps.limit && countSameType >= caps.limit) {
|
||||
msg.warning(`该类型附件数量已达上限(${caps.limit})`);
|
||||
msg.warning(t('chat.attachment.typeLimit', { limit: caps.limit }));
|
||||
return;
|
||||
}
|
||||
attachments.value.push({ id: `${Date.now()}_${Math.random()}`, kind: 'remote', url, type });
|
||||
};
|
||||
|
||||
/**
|
||||
* 上传单个普通本地附件;成功上传 ID 可被发送流程复用。
|
||||
* @param item - 必须是仍存在于输入区的本地附件
|
||||
* @returns Dify 本地文件参数
|
||||
*/
|
||||
const uploadLocalAttachment = async (
|
||||
item: Extract<PendingAttachment, { kind: 'local' }>,
|
||||
): Promise<ChatUploadFileSpec> => {
|
||||
if (item.uploadStatus === 'uploaded' && item.uploadFileId) {
|
||||
return { type: item.type, transfer_method: 'local_file', upload_file_id: item.uploadFileId };
|
||||
}
|
||||
item.uploadStatus = 'uploading';
|
||||
item.uploadProgress = 0;
|
||||
item.errorMessage = undefined;
|
||||
try {
|
||||
const uploaded = await uploadChatFile(currentAgentId.value, item.file);
|
||||
if (!uploaded?.id) throw new Error(t('chat.attachment.missingUploadId'));
|
||||
item.uploadStatus = 'uploaded';
|
||||
item.uploadProgress = 100;
|
||||
item.uploadFileId = uploaded.id;
|
||||
return { 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 : t('chat.attachment.uploadFailed');
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
/** 用户从失败卡片显式重试单个普通附件,不触发整条消息发送。 */
|
||||
const retryAttachment = async (id: string): Promise<boolean> => {
|
||||
const target = attachments.value.find(
|
||||
(item): item is Extract<PendingAttachment, { kind: 'local' }> => item.id === id && item.kind === 'local',
|
||||
);
|
||||
if (!target || target.uploadStatus !== 'failed' || isUploadingAttachments.value) return false;
|
||||
isUploadingAttachments.value = true;
|
||||
try {
|
||||
await uploadLocalAttachment(target);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
} finally {
|
||||
isUploadingAttachments.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 将待发送附件转换为 Dify 文件参数,并逐个更新本地文件的真实上传状态。
|
||||
* 核心逻辑:复用已成功上传的 uploadFileId;失败附件保留并在下次发送时重试。
|
||||
@@ -370,30 +417,7 @@ export function useChatAttachments(options: UseChatAttachmentsOptions) {
|
||||
isUploadingAttachments.value = true;
|
||||
try {
|
||||
for (const item of locals) {
|
||||
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(await uploadLocalAttachment(item));
|
||||
}
|
||||
} finally {
|
||||
isUploadingAttachments.value = false;
|
||||
@@ -424,6 +448,7 @@ export function useChatAttachments(options: UseChatAttachmentsOptions) {
|
||||
isUploadingAttachments,
|
||||
attachmentPolicy,
|
||||
removeAttachment,
|
||||
retryAttachment,
|
||||
handleLocalFilesSelected,
|
||||
addRemoteUrlAttachment,
|
||||
buildFileSpecsForSend,
|
||||
|
||||
@@ -65,6 +65,7 @@ import {
|
||||
|
||||
import type { ChatMessage, ChatRun, ChatSessionItem, ShippingMessageRecoveryPayload } from '../types/chat.types';
|
||||
import type { SendMessageLifecycleHooks } from './useChat';
|
||||
import type { ChatMessageSendResult } from '../types/chat-turn.types';
|
||||
import type { ChatUploadFileSpec, PendingAttachment, ShippingActionButton } from '../types/shipping.types';
|
||||
import type { ChatDeps } from './chat.deps';
|
||||
import { listChatMessages } from '../api/chat.api';
|
||||
@@ -98,7 +99,7 @@ export interface UseChatShippingOptions {
|
||||
files: ChatUploadFileSpec[],
|
||||
context?: { task_id?: string; batch_no?: string; shipping_intake_nos?: string[]; display_query?: string },
|
||||
hooks?: SendMessageLifecycleHooks,
|
||||
) => Promise<boolean | void>;
|
||||
) => Promise<ChatMessageSendResult>;
|
||||
startChatTurn: (options: import('../types/chat-turn.types').StartChatTurnOptions) => Promise<boolean>;
|
||||
buildFileSpecsForSend: () => Promise<ChatUploadFileSpec[]>;
|
||||
loadConversation: (id: string, options?: { force?: boolean }) => Promise<void>;
|
||||
|
||||
@@ -35,7 +35,7 @@ function createContext(overrides: Partial<ChatPageSendContext> = {}): ChatPageSe
|
||||
]),
|
||||
createMessageAttachmentSnapshots: vi.fn(() => attachmentSnapshots.map((item) => ({ ...item }))),
|
||||
clearAttachments: vi.fn(),
|
||||
sendMessage: vi.fn(async () => true),
|
||||
sendMessage: vi.fn(async () => ({ accepted: true, completed: true })),
|
||||
refreshHistoryAfterSend: vi.fn(async () => undefined),
|
||||
refreshConversationAfterSend: vi.fn(async () => undefined),
|
||||
tryHandleShippingAttachmentAutoFlow: vi.fn(async () => false),
|
||||
@@ -62,25 +62,26 @@ describe('createChatPageSendApi attachment lifecycle', () => {
|
||||
expect(ctx.sendMessage).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('keeps uploaded attachments when message sending fails', async () => {
|
||||
it('keeps uploaded attachments and restores input when the request is not accepted', 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),
|
||||
sendMessage: vi.fn(async () => ({ accepted: false, completed: false })),
|
||||
});
|
||||
|
||||
await createChatPageSendApi(ctx).handleSend();
|
||||
|
||||
expect(ctx.clearAttachments).not.toHaveBeenCalled();
|
||||
expect(ctx.refreshHistoryAfterSend).not.toHaveBeenCalled();
|
||||
expect(ctx.input.value).toBe('请分析附件');
|
||||
});
|
||||
|
||||
it('clears attachments when the request is accepted even if the assistant stream fails', async () => {
|
||||
const ctx = createContext({
|
||||
sendMessage: vi.fn(async () => ({ accepted: true, completed: false, chatLogId: 42 })),
|
||||
});
|
||||
|
||||
await createChatPageSendApi(ctx).handleSend();
|
||||
|
||||
expect(ctx.clearAttachments).toHaveBeenCalledOnce();
|
||||
expect(ctx.refreshHistoryAfterSend).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('clears attachments only after message sending succeeds', async () => {
|
||||
|
||||
@@ -10,6 +10,7 @@ import { copyTextToClipboard } from '@/shared/utils/clipboard';
|
||||
import type { ChatMessage, ChatMessageAttachment } from '../types/chat.types';
|
||||
import type { SendMessageLifecycleHooks } from '../composables/useChat';
|
||||
import type { ChatUploadFileSpec } from '../types/shipping.types';
|
||||
import type { ChatMessageSendResult } from '../types/chat-turn.types';
|
||||
import type { ComputedRef, Ref } from 'vue';
|
||||
|
||||
const looksLikeCompletedAssistantReply = (content: string) => {
|
||||
@@ -55,7 +56,7 @@ export interface ChatPageSendContext {
|
||||
files: ChatUploadFileSpec[],
|
||||
context?: { task_id?: string; batch_no?: string; shipping_intake_nos?: string[]; display_query?: string },
|
||||
hooks?: SendMessageLifecycleHooks,
|
||||
) => Promise<boolean | void>;
|
||||
) => Promise<ChatMessageSendResult>;
|
||||
refreshHistoryAfterSend: () => Promise<void>;
|
||||
refreshConversationAfterSend?: () => Promise<void>;
|
||||
tryHandleShippingAttachmentAutoFlow: (
|
||||
@@ -133,7 +134,8 @@ export function createChatPageSendApi(ctx: ChatPageSendContext) {
|
||||
}
|
||||
}
|
||||
|
||||
if (typeof textOrEvent !== 'string') ctx.input.value = '';
|
||||
const shouldClearInput = typeof textOrEvent !== 'string';
|
||||
if (shouldClearInput) ctx.input.value = '';
|
||||
|
||||
const requestContent = trimmed || ctx.t('chat.attachment.defaultPrompt');
|
||||
const sendContext = {
|
||||
@@ -152,7 +154,10 @@ export function createChatPageSendApi(ctx: ChatPageSendContext) {
|
||||
onAssistantMessageFinished: ctx.onAssistantMessageFinished,
|
||||
},
|
||||
);
|
||||
if (sent === false) return;
|
||||
if (!sent.accepted) {
|
||||
if (shouldClearInput) ctx.input.value = content;
|
||||
return;
|
||||
}
|
||||
ctx.clearAttachments();
|
||||
await ctx.refreshHistoryAfterSend();
|
||||
await ctx.refreshConversationAfterSend?.();
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
*/
|
||||
import type { ChatSessionItem } from '../types/chat.types';
|
||||
import type { ChatUploadFileSpec } from '../types/shipping.types';
|
||||
import type { ChatMessageSendResult } from '../types/chat-turn.types';
|
||||
import type { ComputedRef, Ref } from 'vue';
|
||||
|
||||
export interface ShippingConversationContext {
|
||||
@@ -21,7 +22,7 @@ export interface ShippingConversationContext {
|
||||
kb: string,
|
||||
files: ChatUploadFileSpec[],
|
||||
context?: { task_id?: string; batch_no?: string; display_query?: string },
|
||||
) => Promise<boolean | void>;
|
||||
) => Promise<ChatMessageSendResult>;
|
||||
}
|
||||
|
||||
/** 发送菜单类消息后,若当前会话尚未出现在侧栏历史中则刷新列表 */
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
/**
|
||||
* features/chat/shipping/shippingDecisionFormat.spec.ts
|
||||
* 用途:验证库存映射人工修正摘要使用 v2 系统字段名。
|
||||
* 依赖:vitest、shippingDecisionFormat。
|
||||
* 逻辑:锁死建议映射展示中的 part_number,防止旧 sku 契约回流。
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { formatShippingDecisionAssistantMessage } from './shippingDecisionFormat';
|
||||
|
||||
describe('formatShippingDecisionAssistantMessage', () => {
|
||||
it('renders part_number for inventory mapping suggestions', () => {
|
||||
const text = formatShippingDecisionAssistantMessage(
|
||||
'correct_inventory_mapping',
|
||||
{
|
||||
message: '请修正映射',
|
||||
data: {
|
||||
schema_preview: {
|
||||
headers: ['Supplier Sku', 'COM ID', 'Qty Available'],
|
||||
suggested_mapping: {
|
||||
part_number: 'Supplier Sku',
|
||||
reservation_id: 'COM ID',
|
||||
available_qty: 'Qty Available',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
'SN-MAP-001',
|
||||
'操作已完成',
|
||||
);
|
||||
|
||||
expect(text).toContain('- part_number → Supplier Sku');
|
||||
expect(text).not.toContain('- sku →');
|
||||
});
|
||||
});
|
||||
@@ -24,7 +24,7 @@ export function formatShippingDecisionAssistantMessage(
|
||||
lines.push('', `当前表头:${headers.join(' | ')}`);
|
||||
}
|
||||
const mappingLines = [
|
||||
suggested.sku ? `- sku → ${suggested.sku}` : null,
|
||||
suggested.part_number ? `- part_number → ${suggested.part_number}` : null,
|
||||
suggested.reservation_id ? `- reservation_id → ${suggested.reservation_id}` : null,
|
||||
suggested.available_qty ? `- available_qty → ${suggested.available_qty}` : null,
|
||||
].filter((line): line is string => Boolean(line));
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
/**
|
||||
* features/chat/shipping/shippingIntents.spec.ts
|
||||
* 用途:验证发货聊天自然语言库存映射遵循 v2 字段契约。
|
||||
* 依赖:vitest、shippingIntents。
|
||||
* 逻辑:覆盖完整三字段映射与缺 Reservation 拒绝分支。
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { parseShippingColumnMappingFromText } from './shippingIntents';
|
||||
|
||||
describe('parseShippingColumnMappingFromText', () => {
|
||||
it('normalizes SKU wording to the v2 part_number key', () => {
|
||||
expect(parseShippingColumnMappingFromText([
|
||||
'SKU -> Supplier Sku',
|
||||
'Reservation ID -> COM ID',
|
||||
'Available Qty -> Qty Available',
|
||||
].join('\n'))).toEqual({
|
||||
part_number: 'Supplier Sku',
|
||||
reservation_id: 'COM ID',
|
||||
available_qty: 'Qty Available',
|
||||
});
|
||||
});
|
||||
|
||||
it('rejects mappings that omit Reservation ID', () => {
|
||||
expect(parseShippingColumnMappingFromText([
|
||||
'part_number -> Supplier Sku',
|
||||
'available_qty -> Qty Available',
|
||||
].join('\n'))).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -13,7 +13,7 @@ export interface ShippingTaskSwitchIntent {
|
||||
}
|
||||
|
||||
/**
|
||||
* 从自然语言文本解析库存列映射(sku / available_qty / reservation_id → Excel 列名)。
|
||||
* 从自然语言文本解析库存列映射(part_number / reservation_id / available_qty → Excel 列名)。
|
||||
*/
|
||||
export function parseShippingColumnMappingFromText(content: string): Record<string, string> | null {
|
||||
const raw = String(content || '').trim();
|
||||
@@ -31,7 +31,9 @@ export function parseShippingColumnMappingFromText(content: string): Record<stri
|
||||
const s = left.toLowerCase();
|
||||
if (s.includes('reservation') || left.includes('预留') || left.includes('预定')) return 'reservation_id';
|
||||
if (s.includes('qty') || s.includes('available') || left.includes('可用') || left.includes('数量')) return 'available_qty';
|
||||
if (s.includes('sku') || left.includes('料号') || left.includes('物料')) return 'sku';
|
||||
if (s.includes('part_number') || s.includes('part number') || s.includes('sku') || left.includes('料号') || left.includes('物料')) {
|
||||
return 'part_number';
|
||||
}
|
||||
return '';
|
||||
};
|
||||
for (const line of lines) {
|
||||
@@ -46,7 +48,7 @@ export function parseShippingColumnMappingFromText(content: string): Record<stri
|
||||
if (!col) continue;
|
||||
mapping[key] = col;
|
||||
}
|
||||
if (!mapping.sku || !mapping.available_qty) return null;
|
||||
if (!mapping.part_number || !mapping.reservation_id || !mapping.available_qty) return null;
|
||||
return mapping;
|
||||
}
|
||||
|
||||
|
||||
@@ -41,8 +41,8 @@ export function buildShippingFieldAlignmentText(payload: { data?: { field_alignm
|
||||
const invCols = (alignment as { inventory_columns?: { mapping?: Record<string, { source_column?: string }> } }).inventory_columns || {};
|
||||
const mapping = invCols.mapping || {};
|
||||
const rows: Array<[string, string]> = [
|
||||
['sku', normalizeShippingHeaderForDisplay(mapping?.sku?.source_column) || '(未识别)'],
|
||||
['reservation_id', normalizeShippingHeaderForDisplay(mapping?.reservation_id?.source_column) || '(未识别/可选)'],
|
||||
['part_number', normalizeShippingHeaderForDisplay(mapping?.part_number?.source_column) || '(未识别)'],
|
||||
['reservation_id', normalizeShippingHeaderForDisplay(mapping?.reservation_id?.source_column) || '(未识别)'],
|
||||
['available_qty', normalizeShippingHeaderForDisplay(mapping?.available_qty?.source_column) || '(未识别)'],
|
||||
];
|
||||
const lines: string[] = [];
|
||||
|
||||
@@ -50,7 +50,7 @@ export const formatShortageLine = (
|
||||
t: (key: string, params?: Record<string, unknown>) => string,
|
||||
) => t('chat.shippingNoticeUi.diagnosisShortageLine', {
|
||||
index: index + 1,
|
||||
sku: line.sku || '-',
|
||||
partNumber: line.part_number || '-',
|
||||
reservationId: line.reservation_id || '-',
|
||||
required: formatShippingQty(line.required_qty),
|
||||
available: formatShippingQty(line.available_qty),
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
/**
|
||||
* features/chat/shipping/useChatShippingMappingForm.spec.ts
|
||||
* 用途:验证库存人工列映射严格使用 v2 料号与 Reservation 契约。
|
||||
* 依赖:vitest、Vue refs、shipping.api、useChatShippingMappingForm。
|
||||
* 逻辑:覆盖表单预填、完整映射提交和缺 Reservation 本地阻断。
|
||||
*/
|
||||
import { computed, ref } from 'vue';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { createShippingMappingFormHandlers, type ShippingMappingFormContext } from './useChatShippingMappingForm';
|
||||
import type { ChatMessage } from '../types/chat.types';
|
||||
|
||||
const { getWorkspaceShippingTask } = vi.hoisted(() => ({
|
||||
getWorkspaceShippingTask: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('@/features/chat/api/shipping.api', () => ({
|
||||
getWorkspaceShippingTask,
|
||||
}));
|
||||
|
||||
const createContext = (
|
||||
overrides: Partial<ShippingMappingFormContext> = {},
|
||||
): ShippingMappingFormContext => ({
|
||||
messages: ref<ChatMessage[]>([]),
|
||||
chatScrollContainer: ref(null),
|
||||
shippingInventorySchemaPreviewCache: ref({
|
||||
'SN-MAP-001': {
|
||||
headers: ['Supplier Sku', 'COM ID', 'Qty Available'],
|
||||
suggested_mapping: {
|
||||
part_number: 'Supplier Sku',
|
||||
reservation_id: 'COM ID',
|
||||
available_qty: 'Qty Available',
|
||||
},
|
||||
},
|
||||
}),
|
||||
shippingInventoryPickerRef: ref(null),
|
||||
pendingShippingUploadTaskId: ref(''),
|
||||
resolvedShippingTaskId: ref(''),
|
||||
newLocalMessageId: () => 'local-mapping-1',
|
||||
saveLocalMessageToBackend: vi.fn(async () => undefined),
|
||||
startChatTurn: vi.fn(async () => true),
|
||||
currentAgentId: computed(() => 42),
|
||||
refreshShippingActions: vi.fn(async () => undefined),
|
||||
msg: { warning: vi.fn() },
|
||||
...overrides,
|
||||
});
|
||||
|
||||
describe('useChatShippingMappingForm', () => {
|
||||
beforeEach(() => {
|
||||
getWorkspaceShippingTask.mockReset();
|
||||
getWorkspaceShippingTask.mockResolvedValue({
|
||||
lines: [{ part_number: 'D4-A08AR12000002', reservation_id: '3000092917', qty: 10 }],
|
||||
});
|
||||
});
|
||||
|
||||
it('prefills and submits the v2 inventory mapping fields', async () => {
|
||||
const ctx = createContext();
|
||||
const handlers = createShippingMappingFormHandlers(ctx);
|
||||
|
||||
expect(await handlers.openShippingInventoryMappingFormForTask('sn-map-001')).toBe(true);
|
||||
const message = ctx.messages.value[0];
|
||||
expect(message.payload).toMatchObject({
|
||||
order: { line_count: 1, part_numbers: ['D4-A08AR12000002'] },
|
||||
form: {
|
||||
part_number: 'Supplier Sku',
|
||||
reservation_id: 'COM ID',
|
||||
available_qty: 'Qty Available',
|
||||
},
|
||||
});
|
||||
|
||||
await handlers.applyShippingInventoryMappingForm(message);
|
||||
|
||||
expect(ctx.startChatTurn).toHaveBeenCalledWith(expect.objectContaining({
|
||||
actionType: 'shipping.apply_inventory_mapping',
|
||||
payload: {
|
||||
task_no: 'SN-MAP-001',
|
||||
map_json: {
|
||||
part_number: 'Supplier Sku',
|
||||
reservation_id: 'COM ID',
|
||||
available_qty: 'Qty Available',
|
||||
},
|
||||
},
|
||||
}));
|
||||
});
|
||||
|
||||
it('blocks submission when the Reservation ID mapping is missing', async () => {
|
||||
const ctx = createContext();
|
||||
const handlers = createShippingMappingFormHandlers(ctx);
|
||||
await handlers.openShippingInventoryMappingFormForTask('SN-MAP-001');
|
||||
const message = ctx.messages.value[0];
|
||||
const payload = message.payload as { form: { reservation_id: string } };
|
||||
payload.form.reservation_id = '';
|
||||
|
||||
await handlers.applyShippingInventoryMappingForm(message);
|
||||
|
||||
expect(ctx.startChatTurn).not.toHaveBeenCalled();
|
||||
expect(ctx.msg.warning).toHaveBeenCalledWith('请先选择内部料号列、Reservation ID 列与可用数量列');
|
||||
});
|
||||
});
|
||||
@@ -79,9 +79,11 @@ export function createShippingMappingFormHandlers(ctx: ShippingMappingFormContex
|
||||
const rawLines = Array.isArray((detail as { lines?: unknown[] } | null)?.lines)
|
||||
? (detail as { lines: unknown[] }).lines
|
||||
: [];
|
||||
const pickSku = (line: Record<string, unknown>) =>
|
||||
String(line?.sku || line?.SKU || line?.['AWS Sku'] || line?.['AWS SKU'] || '').trim();
|
||||
const skus = [...new Set(rawLines.map((line) => pickSku(line as Record<string, unknown>)).filter(Boolean))].slice(0, 40);
|
||||
const partNumbers = [...new Set(
|
||||
rawLines
|
||||
.map((line) => String((line as Record<string, unknown>)?.part_number || '').trim())
|
||||
.filter(Boolean),
|
||||
)].slice(0, 40);
|
||||
const suggested = (schemaPreview as { suggested_mapping?: Record<string, string> }).suggested_mapping || {};
|
||||
const mappingMsg: ChatMessage = {
|
||||
role: 'assistant',
|
||||
@@ -93,9 +95,9 @@ export function createShippingMappingFormHandlers(ctx: ShippingMappingFormContex
|
||||
payload: {
|
||||
taskId: id,
|
||||
schema_preview: schemaPreview,
|
||||
order: { line_count: rawLines.length, skus },
|
||||
order: { line_count: rawLines.length, part_numbers: partNumbers },
|
||||
form: {
|
||||
sku: String(suggested?.sku || '').trim(),
|
||||
part_number: String(suggested?.part_number || '').trim(),
|
||||
available_qty: String(suggested?.available_qty || '').trim(),
|
||||
reservation_id: String(suggested?.reservation_id || '').trim(),
|
||||
},
|
||||
@@ -120,17 +122,14 @@ export function createShippingMappingFormHandlers(ctx: ShippingMappingFormContex
|
||||
return;
|
||||
}
|
||||
const mapping: Record<string, string> = {
|
||||
sku: String(payload.form?.sku || '').trim(),
|
||||
part_number: String(payload.form?.part_number || '').trim(),
|
||||
available_qty: String(payload.form?.available_qty || '').trim(),
|
||||
reservation_id: String(payload.form?.reservation_id || '').trim(),
|
||||
};
|
||||
if (!mapping.sku || !mapping.available_qty) {
|
||||
ctx.msg.warning('请先选择 SKU 列 与 可用数量列');
|
||||
if (!mapping.part_number || !mapping.reservation_id || !mapping.available_qty) {
|
||||
ctx.msg.warning('请先选择内部料号列、Reservation ID 列与可用数量列');
|
||||
return;
|
||||
}
|
||||
if (!mapping.reservation_id) {
|
||||
delete mapping.reservation_id;
|
||||
}
|
||||
payload.applying = true;
|
||||
try {
|
||||
const turn = buildShippingApplyMappingTurn(taskId, mapping);
|
||||
|
||||
@@ -39,7 +39,7 @@ const createContext = (
|
||||
getActiveShippingTaskId: () => '',
|
||||
lastAssistantMessageContent: () => '',
|
||||
lastAssistantShippingActions: () => [],
|
||||
sendMessage: vi.fn(async () => true),
|
||||
sendMessage: vi.fn(async () => ({ accepted: true, completed: true })),
|
||||
buildFileSpecsForSend: vi.fn(async () => []),
|
||||
loadHistory: vi.fn(async () => undefined),
|
||||
sendShippingMenuMessage: vi.fn(async () => undefined),
|
||||
@@ -263,7 +263,7 @@ describe('useChatShippingSendHandler', () => {
|
||||
intakeNo: 'SNI-HANDLED-FAILURE',
|
||||
}]),
|
||||
getParsedIntakeNos: () => ['SNI-HANDLED-FAILURE'],
|
||||
sendMessage: vi.fn(async () => false),
|
||||
sendMessage: vi.fn(async () => ({ accepted: false, completed: false })),
|
||||
rollbackOrderExtractionStarted: rollback,
|
||||
});
|
||||
const { tryHandleShippingAttachmentAutoFlow } = createShippingSendHandlers(ctx);
|
||||
@@ -274,4 +274,37 @@ describe('useChatShippingSendHandler', () => {
|
||||
expect(rollback).toHaveBeenCalledWith(['SNI-HANDLED-FAILURE']);
|
||||
expect(ctx.loadHistory).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('removes submitted notice attachments after acceptance even when the assistant stream fails', async () => {
|
||||
const submitted = {
|
||||
id: 'notice-accepted-error',
|
||||
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-ACCEPTED-ERROR',
|
||||
};
|
||||
const retained = {
|
||||
...submitted,
|
||||
id: 'notice-retained',
|
||||
originalFilename: 'other.eml',
|
||||
intakeNo: 'SNI-RETAINED',
|
||||
};
|
||||
const ctx = createContext({
|
||||
attachments: ref([submitted, retained]),
|
||||
getParsedIntakeNos: () => ['SNI-ACCEPTED-ERROR'],
|
||||
sendMessage: vi.fn(async () => ({ accepted: true, completed: false, chatLogId: 42 })),
|
||||
});
|
||||
const { tryHandleShippingAttachmentAutoFlow } = createShippingSendHandlers(ctx);
|
||||
|
||||
const consumed = await tryHandleShippingAttachmentAutoFlow(undefined, '', '');
|
||||
|
||||
expect(consumed).toBe(true);
|
||||
expect(ctx.rollbackOrderExtractionStarted).not.toHaveBeenCalled();
|
||||
expect(ctx.attachments.value).toEqual([retained]);
|
||||
expect(ctx.loadHistory).toHaveBeenCalledOnce();
|
||||
});
|
||||
});
|
||||
@@ -24,7 +24,7 @@ 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 { ChatMessageSendResult, StartChatTurnOptions } from '../types/chat-turn.types';
|
||||
import type { ChatMessage, ChatSessionItem } from '../types/chat.types';
|
||||
import type { ChatUploadFileSpec, PendingAttachment, ShippingActionButton } from '../types/shipping.types';
|
||||
import type { ComputedRef, Ref } from 'vue';
|
||||
@@ -54,7 +54,7 @@ export interface ShippingSendHandlerContext {
|
||||
files: ChatUploadFileSpec[],
|
||||
context?: { task_id?: string; batch_no?: string; shipping_intake_nos?: string[]; display_query?: string },
|
||||
hooks?: SendMessageLifecycleHooks,
|
||||
) => Promise<boolean | void>;
|
||||
) => Promise<ChatMessageSendResult>;
|
||||
buildFileSpecsForSend: () => Promise<ChatUploadFileSpec[]>;
|
||||
loadHistory: () => Promise<void>;
|
||||
sendShippingMenuMessage: (message: string) => Promise<void>;
|
||||
@@ -251,10 +251,16 @@ export function createShippingSendHandlers(ctx: ShippingSendHandlerContext) {
|
||||
},
|
||||
},
|
||||
);
|
||||
if (sent === false) {
|
||||
if (!sent.accepted) {
|
||||
ctx.rollbackOrderExtractionStarted?.(intakeNos);
|
||||
return true;
|
||||
}
|
||||
const submittedIntakes = new Set(intakeNos.map((item) => item.trim().toUpperCase()));
|
||||
ctx.attachments.value = ctx.attachments.value.filter(
|
||||
(item) => item.kind !== 'shipping_notice'
|
||||
|| !item.intakeNo
|
||||
|| !submittedIntakes.has(item.intakeNo.trim().toUpperCase()),
|
||||
);
|
||||
await ctx.loadHistory();
|
||||
} catch (e: unknown) {
|
||||
ctx.rollbackOrderExtractionStarted?.(intakeNos);
|
||||
|
||||
@@ -132,6 +132,9 @@ function mapServerCandidate(remote: ShippingNoticeCandidateResponse): ShippingNo
|
||||
? remote.field_confidence
|
||||
: {},
|
||||
evidence: Array.isArray(remote.evidence) ? remote.evidence : [],
|
||||
fieldAdjudication: remote.field_adjudication && typeof remote.field_adjudication === 'object'
|
||||
? remote.field_adjudication
|
||||
: null,
|
||||
businessSummary: remote.business_summary || {},
|
||||
duplicate,
|
||||
duplicateResolution: remote.duplicate_resolution
|
||||
@@ -282,7 +285,6 @@ export function useShippingNoticeIntakes(options: UseShippingNoticeIntakesOption
|
||||
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,
|
||||
errorMessage: remote.order_extraction_error_message || remote.error_message || undefined,
|
||||
@@ -313,7 +315,6 @@ export function useShippingNoticeIntakes(options: UseShippingNoticeIntakesOption
|
||||
intakeNo: intake.intake_no,
|
||||
parseStatus: mapServerParseStatus(intake.parse_status),
|
||||
orderExtractionStatus: intake.order_extraction_status || undefined,
|
||||
orderExtractionVersion: intake.order_extraction_version || undefined,
|
||||
parseSummary: (intake.parse_summary || undefined) as ShippingNoticeParseSummary | undefined,
|
||||
errorCode: intake.order_extraction_error_code || intake.error_code || undefined,
|
||||
errorMessage: intake.order_extraction_error_message || intake.error_message || undefined,
|
||||
@@ -430,7 +431,6 @@ export function useShippingNoticeIntakes(options: UseShippingNoticeIntakesOption
|
||||
uploadStatus: 'uploaded' as const,
|
||||
parseStatus: mapServerParseStatus(item.parse_status),
|
||||
orderExtractionStatus: item.order_extraction_status || undefined,
|
||||
orderExtractionVersion: item.order_extraction_version || undefined,
|
||||
uploadProgress: 100,
|
||||
originalFilename: item.original_filename || item.intake_no,
|
||||
fileSize: Number(item.file_size || 0),
|
||||
|
||||
@@ -39,3 +39,13 @@ export interface ChatTurnStreamRequest {
|
||||
refs?: ChatTurnRefs;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Legacy Chat 消息发送结果,用于区分“用户消息已被服务端接受”和“AI 回答完整结束”。
|
||||
* accepted=true 后输入内容可安全移入消息历史;completed 仅表示本轮助手回答是否成功完成。
|
||||
*/
|
||||
export interface ChatMessageSendResult {
|
||||
accepted: boolean;
|
||||
completed: boolean;
|
||||
chatLogId?: number;
|
||||
}
|
||||
@@ -149,7 +149,7 @@ export interface ShippingCurrentStepProgress {
|
||||
|
||||
export interface ShippingParseIssue {
|
||||
line_index?: number;
|
||||
sku?: string | null;
|
||||
part_number?: string | null;
|
||||
field: string;
|
||||
reason: 'missing' | 'invalid_format' | 'source_conflict' | 'value_corrected' | string;
|
||||
severity: 'blocking' | 'info' | string;
|
||||
@@ -162,7 +162,6 @@ export interface ShippingParseIssue {
|
||||
export interface ShippingParseValidation {
|
||||
status: 'ready' | 'needs_review' | string;
|
||||
issues: ShippingParseIssue[];
|
||||
contract_version?: string;
|
||||
resolution_source?: string;
|
||||
}
|
||||
|
||||
@@ -175,12 +174,12 @@ export interface ShippingNoticeHeader {
|
||||
}
|
||||
|
||||
export interface ShippingNoticeLine {
|
||||
sku: string;
|
||||
part_number: string;
|
||||
customer_part_number?: string | null;
|
||||
aws_part_number?: string | null;
|
||||
reservation_id?: string | null;
|
||||
/** 可选库存路由线索,不代表任务通知来源或已确认的库存连接器类型。 */
|
||||
source_type?: string | null;
|
||||
/** 站点/Hub 线索;与 source_type 独立,编辑时必须显式保留。 */
|
||||
hub_code?: string | null;
|
||||
inventory_source_hint?: string | null;
|
||||
qty: number;
|
||||
required_date?: string | null;
|
||||
uom?: string | null;
|
||||
@@ -191,7 +190,6 @@ export interface ShippingProcessFieldGate {
|
||||
status?: 'needs_enrichment' | 'ready' | string;
|
||||
missing_fields?: string[];
|
||||
issues?: ShippingParseIssue[];
|
||||
contract_version?: string;
|
||||
}
|
||||
|
||||
export interface ShippingFieldEvidenceItem {
|
||||
@@ -209,6 +207,38 @@ export interface ShippingSourceCandidateProjection {
|
||||
field_confidence?: Record<string, number | null | undefined>;
|
||||
evidence?: ShippingFieldEvidenceItem[];
|
||||
conflicts?: Array<Record<string, unknown>>;
|
||||
field_adjudication?: ShippingFieldAdjudication | null;
|
||||
}
|
||||
|
||||
export interface ShippingFieldObservation {
|
||||
observation_id: string;
|
||||
source: string;
|
||||
line_index: number;
|
||||
field: string;
|
||||
value?: unknown;
|
||||
normalized_value?: string;
|
||||
document_id?: number | null;
|
||||
evidence_verified?: boolean;
|
||||
source_confidence?: number;
|
||||
score?: number;
|
||||
score_reasons?: string[];
|
||||
}
|
||||
|
||||
export interface ShippingFieldDecision {
|
||||
line_index: number;
|
||||
field: string;
|
||||
status: 'selected' | 'consensus' | 'conflicted' | 'unresolved' | string;
|
||||
value?: unknown;
|
||||
score?: number;
|
||||
observation_ids?: string[];
|
||||
}
|
||||
|
||||
export interface ShippingFieldAdjudication {
|
||||
schema_version?: string | null;
|
||||
decisions?: ShippingFieldDecision[];
|
||||
observations?: ShippingFieldObservation[];
|
||||
observation_history?: ShippingFieldObservation[];
|
||||
conflicts?: Array<Record<string, unknown>>;
|
||||
}
|
||||
|
||||
export interface ShippingFieldConflict {
|
||||
@@ -228,7 +258,7 @@ export interface ShippingFieldConflict {
|
||||
}
|
||||
|
||||
export interface ShippingMatchLineResult {
|
||||
sku: string;
|
||||
part_number: string;
|
||||
reservation_id?: string | null;
|
||||
required_qty: number;
|
||||
available_qty: number;
|
||||
@@ -425,7 +455,6 @@ export interface ShippingNoticeIntakeResponse {
|
||||
parse_status: string;
|
||||
parser_version?: string;
|
||||
order_extraction_status?: string | null;
|
||||
order_extraction_version?: string | null;
|
||||
order_extraction_error_code?: string | null;
|
||||
order_extraction_error_message?: string | null;
|
||||
parse_summary?: Record<string, unknown> | null;
|
||||
@@ -477,6 +506,7 @@ export interface ShippingNoticeCandidateResponse {
|
||||
missing_fields?: string[];
|
||||
field_confidence?: Record<string, number | null | undefined>;
|
||||
evidence?: ShippingFieldEvidenceItem[];
|
||||
field_adjudication?: ShippingFieldAdjudication | null;
|
||||
business_summary?: Record<string, unknown> | null;
|
||||
duplicate?: ShippingDuplicateResult | null;
|
||||
duplicate_resolution?: {
|
||||
|
||||
@@ -5,6 +5,8 @@
|
||||
* 逻辑:附件 composable、shipping/* composable 与 Chat 消息组件统一引用本文件类型。
|
||||
*/
|
||||
|
||||
import type { ShippingFieldAdjudication } from './shipping.api.types';
|
||||
|
||||
export type ShippingActionVariant = 'primary' | 'secondary' | 'danger';
|
||||
|
||||
export type ShippingMenuAction = 'upload' | 'paste' | 'retry_rpa' | 'confirm' | 'reparse' | 'reject';
|
||||
@@ -76,6 +78,7 @@ export interface ShippingNoticeCandidate {
|
||||
missingFields?: string[];
|
||||
fieldConfidence?: Record<string, number | null | undefined>;
|
||||
evidence?: Array<Record<string, unknown>>;
|
||||
fieldAdjudication?: ShippingFieldAdjudication | null;
|
||||
businessSummary: Record<string, unknown>;
|
||||
duplicate?: ShippingDuplicateResult;
|
||||
duplicateResolution?: ShippingDuplicateResolution;
|
||||
@@ -139,7 +142,6 @@ export type ShippingNoticePendingAttachment = {
|
||||
fileSize: number;
|
||||
parseSummary?: ShippingNoticeParseSummary;
|
||||
orderExtractionStatus?: string;
|
||||
orderExtractionVersion?: string;
|
||||
errorCode?: string;
|
||||
errorMessage?: string;
|
||||
expiresAt?: string;
|
||||
@@ -190,8 +192,8 @@ export interface ShippingSchemaPreview {
|
||||
export interface ShippingInventoryMappingFormPayload {
|
||||
taskId: string;
|
||||
schema_preview: ShippingSchemaPreview;
|
||||
order: { line_count: number; skus: string[] };
|
||||
form: { sku: string; available_qty: string; reservation_id: string };
|
||||
order: { line_count: number; part_numbers: string[] };
|
||||
form: { part_number: string; available_qty: string; reservation_id: string };
|
||||
applying?: boolean;
|
||||
}
|
||||
|
||||
@@ -206,10 +208,11 @@ export interface ShippingParseReviewPayload {
|
||||
required_date?: string | null;
|
||||
};
|
||||
lines: Array<{
|
||||
sku: string;
|
||||
part_number: string;
|
||||
customer_part_number?: string | null;
|
||||
aws_part_number?: string | null;
|
||||
reservation_id?: string | null;
|
||||
/** 可选库存路由线索;与 ShippingTask.source_type 通知来源无关。 */
|
||||
source_type?: string | null;
|
||||
inventory_source_hint?: string | null;
|
||||
qty: number;
|
||||
required_date?: string | null;
|
||||
uom?: string | null;
|
||||
@@ -222,7 +225,7 @@ export interface ShippingMatchResultPayload {
|
||||
taskId: string;
|
||||
match_status?: string | null;
|
||||
line_results: Array<{
|
||||
sku: string;
|
||||
part_number: string;
|
||||
reservation_id?: string | null;
|
||||
required_qty: number;
|
||||
available_qty: number;
|
||||
@@ -230,7 +233,7 @@ export interface ShippingMatchResultPayload {
|
||||
line_status: 'ok' | 'partial' | 'shortage' | string;
|
||||
}>;
|
||||
shortage_lines?: Array<{
|
||||
sku: string;
|
||||
part_number: string;
|
||||
reservation_id?: string | null;
|
||||
required_qty: number;
|
||||
available_qty: number;
|
||||
|
||||
Reference in new issue
Block a user