Merge branch 'dev' of https://gitee.com/justop/hxops into dev

This commit is contained in:
sophie committed 2026-07-15 08:52:30 +08:00
commit ffccf19ba2
143 files changed
+27635 -1021

No files matched your search

@@ -1,8 +1,8 @@
/**
* features/admin/modules/schedules/composables/schedule-admin/useScheduleAdminDeepLink.ts
* 用途:解析企微深链 query,定位排程执行记录并标记原始库存手动下载入口。
* 用途:解析企微深链 query,定位排程执行记录并在登录后自动下载原始库存包。
* 依赖:vue-router、schedule-admin.state、useScheduleAdminRuns。
* 逻辑:SchedulesPage onMounted 在 loadAll 后调用;消费 task_id/run_id/raw_zip,不自动下载。
* 逻辑:SchedulesPage onMounted 在 loadAll 后调用;消费 task_id/run_id/raw_zip/download,自动下载失败时保留手动入口。
*/
import { useRoute, useRouter } from 'vue-router';
import type { ScheduleAdminState } from './schedule-admin.state';
@@ -15,12 +15,12 @@ function parsePositiveInt(raw: unknown): number | null {
}
/**
* 根据路由 query 打开工作台执行记录;raw_zip=1 时仅展开 run 并突出手动下载按钮。
* 核心逻辑:不自动触发下载,避免企微内置浏览器拦截异步下载。
* 根据路由 query 打开工作台执行记录;raw_zip=1 时展开 run 并保留手动下载按钮。
* 核心逻辑:download=inventory_raw_zip 时登录后自动下载一次;若企微内置浏览器拦截,用户仍可点醒目按钮重试。
*/
export function useScheduleAdminDeepLink(
state: ScheduleAdminState,
runs: Pick<ScheduleAdminRuns, 'viewScheduleRuns'>,
runs: Pick<ScheduleAdminRuns, 'viewScheduleRuns' | 'downloadScheduleInventoryRawZip'>,
) {
const route = useRoute();
const router = useRouter();
@@ -31,6 +31,7 @@ export function useScheduleAdminDeepLink(
const runId = parsePositiveInt(route.query.run_id);
const rawZipPrompt = String(route.query.raw_zip || '') === '1';
const shouldAutoDownloadRawZip = rawZipPrompt && String(route.query.download || '') === 'inventory_raw_zip';
state.scheduleViewMode.value = 'workbench';
state.selectedScheduleId.value = taskId;
@@ -43,6 +44,9 @@ export function useScheduleAdminDeepLink(
const target = state.selectedScheduleRuns.value.find((item) => item.id === runId);
if (target?.inventory_raw_zip_available) {
state.wecomRawZipPromptRunId.value = runId;
if (shouldAutoDownloadRawZip) {
await runs.downloadScheduleInventoryRawZip(runId);
}
}
}
}
@@ -51,6 +55,7 @@ export function useScheduleAdminDeepLink(
delete nextQuery.task_id;
delete nextQuery.run_id;
delete nextQuery.raw_zip;
delete nextQuery.download;
await router.replace({ path: route.path, query: nextQuery });
};
+106 -2
View File
@@ -15,6 +15,8 @@ import type {
ShippingNoticeHeader,
ShippingNoticeLine,
ShippingNoticeUploadResponse,
ShippingNoticeIntakeResponse,
ShippingCreateBatchFromIntakesResponse,
ShippingTaskCreateResponse,
ShippingTaskDetail,
ShippingTaskSummary,
@@ -222,15 +224,30 @@ export async function replaceWorkspaceShippingTaskNotice(taskNo: string, file: F
* @param conversationId - 可选会话 ID
* @returns 批次与任务创建结果
*/
export async function createWorkspaceShippingBatchFromNotices(files: File[], conversationId?: string) {
export async function createWorkspaceShippingBatchFromNotices(
files: File[],
conversationId?: string,
idempotencyKey?: string,
) {
const form = new FormData();
files.forEach((file) => form.append('files', file));
if (conversationId) form.append('conversation_id', conversationId);
if (idempotencyKey) form.append('idempotency_key', idempotencyKey);
const headers: Record<string, string> = {};
if (idempotencyKey) {
headers['Idempotency-Key'] = idempotencyKey;
}
const body = await requestJson<ShippingNoticeUploadResponse & ShippingApiStatusPayload & {
error?: string;
batch_no?: string;
idempotent_replay?: boolean;
file_summary?: unknown;
data?: unknown;
}>('/api/workspace/shipping-batches/create-from-notices', { method: 'POST', body: form });
}>('/api/workspace/shipping-batches/create-from-notices', {
method: 'POST',
body: form,
headers,
});
return assertShippingOk(body);
}
@@ -456,6 +473,91 @@ export async function generateWorkspaceShippingExcel(taskNo: string) {
/** 发货通知 Agent 应用类型标识(运行时识别)。 */
export const SHIPPING_NOTICE_AGENT_CODE = 'shipping_notice';
export const createShippingNoticeIntake = (
assetNo: string,
conversationId?: string | null,
) => requestJson<ShippingNoticeIntakeResponse>('/api/workspace/shipping-notice/intakes', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
asset_no: assetNo,
conversation_id: conversationId || undefined,
}),
});
export const getShippingNoticeIntake = (intakeNo: string) =>
requestJson<ShippingNoticeIntakeResponse>(`/api/workspace/shipping-notice/intakes/${encodeURIComponent(intakeNo)}`);
export const getShippingNoticeIntakeStatuses = (intakeNos: string[]) =>
requestJson<{ items: ShippingNoticeIntakeResponse[] }>('/api/workspace/shipping-notice/intakes/status', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ intake_nos: intakeNos }),
});
export const listActiveShippingNoticeIntakes = (conversationId?: string | null) => {
const sp = new URLSearchParams({ status: 'active' });
if (conversationId) sp.set('conversation_id', conversationId);
return requestJson<{ items: ShippingNoticeIntakeResponse[] }>(
`/api/workspace/shipping-notice/intakes?${sp.toString()}`,
);
};
export const retryShippingNoticeIntake = (intakeNo: string) =>
requestJson<ShippingNoticeIntakeResponse>(
`/api/workspace/shipping-notice/intakes/${encodeURIComponent(intakeNo)}/retry`,
{ method: 'POST' },
);
export const cancelShippingNoticeIntake = (intakeNo: string) =>
requestJson<{ cancelled: boolean }>(
`/api/workspace/shipping-notice/intakes/${encodeURIComponent(intakeNo)}`,
{ method: 'DELETE' },
);
export const resolveShippingNoticeDuplicate = (
intakeNo: string,
action: string,
targetTaskNo?: string | null,
reason?: string | null,
) =>
requestJson<ShippingNoticeIntakeResponse>(
`/api/workspace/shipping-notice/intakes/${encodeURIComponent(intakeNo)}/duplicate-resolution`,
{
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
action,
target_task_no: targetTaskNo || undefined,
reason: reason || undefined,
}),
},
);
export const refreshShippingNoticeDuplicate = (intakeNo: string) =>
requestJson<ShippingNoticeIntakeResponse>(
`/api/workspace/shipping-notice/intakes/${encodeURIComponent(intakeNo)}/duplicate-refresh`,
{ method: 'POST' },
);
export const createWorkspaceShippingBatchFromIntakes = (
intakeNos: string[],
conversationId?: string | null,
idempotencyKey?: string,
) =>
requestJson<ShippingCreateBatchFromIntakesResponse>('/api/workspace/shipping-batches/create-from-intakes', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
...(idempotencyKey ? { 'Idempotency-Key': idempotencyKey } : {}),
},
body: JSON.stringify({
intake_nos: intakeNos,
conversation_id: conversationId || undefined,
idempotency_key: idempotencyKey,
}),
});
export type {
ShippingBatchSummary,
ShippingBatchUiState,
@@ -470,6 +572,8 @@ export type {
ShippingNoticeHeader,
ShippingNoticeLine,
ShippingNoticeUploadResponse,
ShippingNoticeIntakeResponse,
ShippingCreateBatchFromIntakesResponse,
ShippingTaskCreateResponse,
ShippingTaskDetail,
ShippingTaskSummary,
@@ -5,6 +5,7 @@
*/
<script setup lang="ts">
import { nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import type { Ref } from 'vue';
import {
Check,
@@ -14,11 +15,16 @@ import {
Loader2,
Mic,
Paperclip,
RefreshCw,
Send,
Square,
X,
} from 'lucide-vue-next';
import type { PendingAttachment } from '../types/shipping.types';
import type { PendingAttachment, ShippingNoticePendingAttachment } from '../types/shipping.types';
import {
isBlockingWarning,
isShippingNoticeAttachmentParseIncomplete,
} from '../shipping/shippingNoticeAttachmentIntegrity';
export interface ChatInputAttachmentPolicy {
anyEnabled: boolean;
@@ -57,6 +63,8 @@ const emit = defineEmits<{
stop: [];
'voice-click': [];
'remove-attachment': [id: string];
'retry-shipping-notice-attachment': [id: string];
'resolve-shipping-notice-duplicate': [id: string];
'local-files-selected': [event: Event];
'add-remote-url': [url: string];
'shipping-inventory-selected': [event: Event];
@@ -67,6 +75,7 @@ const emit = defineEmits<{
}>();
const filePickerRef = ref<HTMLInputElement | null>(null);
const { t } = useI18n();
const textareaRef = ref<HTMLTextAreaElement | null>(null);
const attachmentMenuRef = ref<HTMLElement | null>(null);
const kbMenuRef = ref<HTMLElement | null>(null);
@@ -75,6 +84,73 @@ const showAttachmentMenu = ref(false);
const showAttachmentUrlPanel = ref(false);
const showKbDropdown = ref(false);
const attachmentUrlInput = ref('');
/**
* 汇总 EML 附件解析进度,供输入栏徽标展示。
* 核心逻辑:failed/empty/skipped/超限/文本预算耗尽计为问题;duplicate 单独提示,不记为失败。
*/
function shippingNoticeAttachmentHint(attachment: ShippingNoticePendingAttachment): string {
const summary = attachment.parseSummary;
const total = Number(summary?.attachment_count || 0);
const rows = summary?.attachments || [];
const warnings = summary?.warnings || [];
const hasBlockingWarning = warnings.some((w) => isBlockingWarning(String(w || '')));
if (!total && !hasBlockingWarning && !rows.length) return '';
const effectiveTotal = total || rows.length;
const ok = rows.filter((item) => item.parse_status === 'parsed').length;
const problematic = rows.filter((item) =>
['failed', 'empty', 'skipped'].includes(String(item.parse_status || '')),
).length;
const duplicates = rows.filter((item) => item.parse_status === 'duplicate').length;
const overflow = Math.max(0, effectiveTotal - rows.length);
const issues = problematic + overflow + (hasBlockingWarning && problematic === 0 && overflow === 0 ? 1 : 0);
if (issues > 0) {
return t('chat.shippingNoticeAttachmentHintPartial', {
ok,
total: effectiveTotal || Math.max(ok + issues, 1),
failed: issues,
});
}
if (duplicates > 0) {
return t('chat.shippingNoticeAttachmentHintWithDup', { ok, total: effectiveTotal, duplicates });
}
if (!effectiveTotal) return '';
return t('chat.shippingNoticeAttachmentHint', { ok, total: effectiveTotal });
}
/**
* 是否展示「重试解析」:顶层失败,或已 parsed 但附件不完整。
*/
function canRetryShippingNoticeParse(attachment: ShippingNoticePendingAttachment): boolean {
if (attachment.kind !== 'shipping_notice') return false;
if (attachment.parseStatus === 'failed') return true;
return (
attachment.parseStatus === 'parsed'
&& isShippingNoticeAttachmentParseIncomplete(attachment.parseSummary)
);
}
/**
* 生成附件明细 title(文件名 + 状态 + 关键警告),便于悬停查看完整性。
*/
function shippingNoticeAttachmentTitle(attachment: ShippingNoticePendingAttachment): string {
const rows = attachment.parseSummary?.attachments || [];
const warnings = attachment.parseSummary?.warnings || [];
const lines: string[] = [];
for (const item of rows) {
const name = item.filename || item.attachment_key || 'attachment';
const status = item.parse_status || 'unknown';
lines.push(`${name}: ${status}`);
}
for (const warning of warnings) {
const text = String(warning || '').trim();
if (text) lines.push(`warning: ${text}`);
}
return lines.join('\n');
}
const closeAttachmentMenu = () => {
showAttachmentMenu.value = false;
showAttachmentUrlPanel.value = false;
@@ -218,7 +294,7 @@ watch(
:ref="bindShippingPickerRef"
type="file"
class="hidden"
accept=".xlsx,.xls,.csv,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel,text/csv"
accept=".xlsx,.csv,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,text/csv"
@change="emit('shipping-inventory-selected', $event)"
/>
@@ -238,8 +314,64 @@ watch(
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">
{{ a.kind === 'local' ? a.file.name : a.url }}
<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.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.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.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>
@@ -257,7 +389,7 @@ watch(
>
{{ shippingSuggestedPrompt || '推荐问题' }}
</button>
<span>点发送开始处理</span>
<span>{{ t('chat.shippingNoticeConfirmBatchHint') }}</span>
</div>
<div class="mt-1.5 flex items-center justify-between px-1.5 pb-0.5">
@@ -286,6 +286,8 @@ watch(() => page.currentAgentId, () => {
@stop="page.stopActiveGeneration()"
@voice-click="page.handleVoiceFeatureClick"
@remove-attachment="page.removeAttachment"
@retry-shipping-notice-attachment="page.retryShippingNoticeAttachment"
@resolve-shipping-notice-duplicate="page.openShippingDuplicateDialog"
@local-files-selected="page.handleLocalFilesSelected"
@add-remote-url="page.addRemoteUrlAttachment"
@shipping-inventory-selected="page.handleShippingInventorySelected"
@@ -10,6 +10,7 @@ import ChatQueryPreviewDialog from '@/features/chat/components/ChatQueryPreviewD
import ChatLeaveAgentDialog from '@/features/chat/components/ChatLeaveAgentDialog.vue';
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 { Check, Loader2, X } from 'lucide-vue-next';
import { nextTick } from 'vue';
import { useChatPageContext } from '@/features/chat/composables/chat.context';
@@ -145,4 +146,13 @@ async function handleQueryPreviewAssetImage(assetId: string, assetName: string)
:guides="page.agentGuides"
:active-guide="page.activeGuide"
/>
<ShippingNoticeDuplicateDialog
:open="!!page.showShippingDuplicateDialog"
:attachment="page.shippingDuplicateAttachment || null"
:can-force-create="!!page.canForceCreateShippingDuplicate"
@update:open="(v) => { if (!v) page.closeShippingDuplicateDialog?.(); }"
@resolve="(payload) => void page.resolveShippingDuplicateDialog?.(payload)"
@remove="() => void page.removeShippingDuplicateDialogAttachment?.()"
@cancel="page.closeShippingDuplicateDialog?.()"
/>
</template>
@@ -4,7 +4,7 @@
* 用途:发货通知 Agent 的右侧批次工作台抽屉,承载多批次切换、任务筛选、步骤诊断与统一动作入口。
* 依赖:shippingStepper、shippingMenu、shipping.api.types、vue-i18n、lucide-vue-next。
* 逻辑:上游传入会话级 workspace 与当前批次任务;本组件只渲染后端 `ui_state.action_buttons` 和查看类辅助入口。
* 「重试所有失败」仅 emit `retry-pending`,由父级打开确认弹窗后再调用 useChatShipping 执行。
* 解析阶段诊断优先展示 `ui_state.summary.issues` 完整问题列表;「重试所有失败」仅 emit `retry-pending`,由父级打开确认弹窗后再调用 useChatShipping 执行。
*/
import { computed, ref, watch } from 'vue';
import { RefreshCw, Target, X } from 'lucide-vue-next';
@@ -247,12 +247,42 @@ const currentStepProgress = (task: ShippingTaskSummary | ShippingTaskDetail) =>
const sanitizeDiagnosisCopy = (text: string | null | undefined) =>
sanitizeShippingRuntimeStatusText(String(text || '').trim());
/**
* 读取任务诊断卡要展示的全部问题列表。
* 核心逻辑:优先消费后端 `ui_state.summary.issues`(解析阶段已汇总库存源+warnings);
* 若缺失则回退到单一 error_message,保证旧数据仍有可读文案。
*/
const resolveTaskDiagnosisIssues = (task: ShippingTaskSummary | ShippingTaskDetail): string[] => {
const uiIssues = task.ui_state?.summary?.issues;
if (Array.isArray(uiIssues) && uiIssues.length) {
return uiIssues
.map((item) => sanitizeDiagnosisCopy(item))
.filter(Boolean);
}
const fallback = sanitizeDiagnosisCopy(task.ui_state?.summary?.error_message || task.error_message);
return fallback ? [fallback] : [];
};
/**
* 解析右侧工作台诊断标题/建议/问题列表。
* 核心逻辑:解析阶段若 issues 多于 1 条,使用「发现问题」标题并列出全部条目,避免只显示库存源一条。
*/
const resolveTaskDiagnosis = (task: ShippingTaskSummary | ShippingTaskDetail) => {
const uiSummary = task.ui_state?.summary;
if (uiSummary?.title || uiSummary?.message || uiSummary?.error_message) {
const issues = resolveTaskDiagnosisIssues(task);
if (uiSummary?.title || uiSummary?.message || uiSummary?.error_message || issues.length) {
const multiIssue = issues.length > 1;
return {
title: sanitizeDiagnosisCopy(uiSummary.error_message || uiSummary.title) || t('chat.shippingNoticeUi.diagnosisStepWaitingTitle', { step: taskStepNumber(task) }),
advice: sanitizeDiagnosisCopy(uiSummary.message) || t('chat.shippingNoticeUi.diagnosisStepWaitingAdvice'),
title: multiIssue
? t('chat.shippingNoticeUi.diagnosisIssuesTitle', { count: issues.length })
: (
sanitizeDiagnosisCopy(issues[0] || uiSummary?.error_message || uiSummary?.title)
|| t('chat.shippingNoticeUi.diagnosisStepWaitingTitle', { step: taskStepNumber(task) })
),
advice: multiIssue
? t('chat.shippingNoticeUi.diagnosisIssuesAdvice')
: (sanitizeDiagnosisCopy(uiSummary?.message) || t('chat.shippingNoticeUi.diagnosisStepWaitingAdvice')),
issues: multiIssue ? issues : [],
};
}
const reason = String(task.pending_human_reason || '').trim();
@@ -324,6 +354,21 @@ const resolveTaskDiagnosis = (task: ShippingTaskSummary | ShippingTaskDetail) =>
advice: t('chat.shippingNoticeUi.diagnosisReservationRequiredAdvice'),
};
}
if (reason === 'inventory_source_unresolved') {
const resolution = (task as ShippingTaskDetail).inventory_source_resolution;
const status = resolution && typeof resolution === 'object'
? String((resolution as { status?: unknown }).status || '').trim()
: '';
const isAmbiguous = status === 'ambiguous';
return {
title: t(isAmbiguous
? 'chat.shippingNoticeUi.diagnosisInventorySourceAmbiguousTitle'
: 'chat.shippingNoticeUi.diagnosisInventorySourceTitle'),
advice: t(isAmbiguous
? 'chat.shippingNoticeUi.diagnosisInventorySourceAmbiguousAdvice'
: 'chat.shippingNoticeUi.diagnosisInventorySourceAdvice'),
};
}
if (reason === 'map_infer' || processStatus === 'waiting_inventory') {
return {
title: t('chat.shippingNoticeUi.diagnosisInventoryWaitingTitle'),
@@ -352,6 +397,9 @@ const resolveSuggestedAction = (task: ShippingTaskSummary | ShippingTaskDetail)
if (reason === 'low_confidence' || reviewStatus === 'parse_review') {
return t('chat.shippingNoticeUi.suggestReviewParse');
}
if (reason === 'inventory_source_unresolved') {
return t('chat.shippingNoticeUi.suggestConfirmInventorySource');
}
if (isFailedTask(task)) {
return t('chat.shippingNoticeUi.suggestRetryStep');
}
@@ -559,11 +607,24 @@ const handleSwitchBatch = (batchNo: string) => {
</div>
<div
v-for="diagnosis in [resolveTaskDiagnosis(task)]"
:key="`${task.task_no}-diagnosis`"
class="mb-2 rounded-lg border p-2.5 text-xs font-medium leading-5"
:class="isFailedTask(task) ? 'border-rose-100 bg-rose-50 text-rose-700' : isAbnormalTask(task) ? 'border-amber-100 bg-amber-50 text-amber-700' : 'border-emerald-100 bg-emerald-50 text-emerald-700'"
>
<div class="font-semibold">{{ resolveTaskDiagnosis(task).title }}</div>
<div class="mt-1 font-normal text-slate-600">{{ resolveTaskDiagnosis(task).advice }}</div>
<div class="font-semibold">{{ diagnosis.title }}</div>
<ul
v-if="(diagnosis.issues || []).length"
class="mt-1.5 list-disc space-y-1 pl-4 font-normal text-slate-700"
>
<li
v-for="(issue, issueIndex) in diagnosis.issues"
:key="`${task.task_no}-issue-${issueIndex}`"
>
{{ issue }}
</li>
</ul>
<div class="mt-1 font-normal text-slate-600">{{ diagnosis.advice }}</div>
</div>
<div v-if="!resolveWorkspaceActionButtons(task).length" class="mb-3 text-xs leading-5 text-muted">
<span class="font-semibold text-secondary">{{ t('chat.shippingNoticeUi.suggestedAction') }}</span>
@@ -0,0 +1,201 @@
/**
* features/chat/components/ShippingNoticeDuplicateDialog.vue
* 用途:发货通知阻断型重复处理弹窗(打开已有 / 修订 / 强制新建)。
* 依赖:shipping.types Duplicate 类型、vue-i18n。
* 逻辑:ChatViewOverlays 展示;确认后回写 resolveDuplicateAttachment,再允许确认建单。
*/
<script setup lang="ts">
import { computed, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import type {
ShippingDuplicateAction,
ShippingNoticePendingAttachment,
} from '../types/shipping.types';
const props = defineProps<{
open: boolean;
attachment: ShippingNoticePendingAttachment | null;
canForceCreate: boolean;
}>();
const emit = defineEmits<{
'update:open': [value: boolean];
resolve: [payload: { action: ShippingDuplicateAction; targetTaskNo?: string; reason?: string }];
remove: [];
cancel: [];
}>();
const { t } = useI18n();
const reason = ref('');
const selectedAction = ref<ShippingDuplicateAction>('open_existing');
const submitting = ref(false);
const localError = ref('');
const match = computed(() => props.attachment?.duplicate?.matches?.[0] || null);
const allowed = computed(() => new Set(props.attachment?.duplicate?.allowedActions || []));
watch(
() => props.open,
(open) => {
if (!open) return;
reason.value = '';
localError.value = '';
submitting.value = false;
const actions = props.attachment?.duplicate?.allowedActions || [];
selectedAction.value = (actions[0] as ShippingDuplicateAction) || 'open_existing';
},
);
/**
* 关闭弹窗。
*/
function close() {
emit('update:open', false);
emit('cancel');
}
/**
* 提交所选重复处理动作。
*/
async function confirm() {
if (!props.attachment?.duplicate || !match.value) return;
const action = selectedAction.value;
if (!allowed.value.has(action)) {
localError.value = t('chat.shippingNoticeDuplicateActionUnavailable');
return;
}
if (action === 'force_create') {
if (!props.canForceCreate) {
localError.value = t('chat.shippingNoticeDuplicateForceForbidden');
return;
}
if (!reason.value.trim()) {
localError.value = t('chat.shippingNoticeDuplicateReasonRequired');
return;
}
}
submitting.value = true;
localError.value = '';
try {
emit('resolve', {
action,
targetTaskNo: match.value.taskNo,
reason: action === 'force_create' ? reason.value.trim() : undefined,
});
emit('update:open', false);
} finally {
submitting.value = false;
}
}
const statusLabel = computed(() => {
const status = props.attachment?.duplicate?.status;
if (status === 'exact_file') return t('chat.shippingNoticeDuplicateExactFile');
if (status === 'same_active_task') return t('chat.shippingNoticeDuplicateSameActive');
if (status === 'same_completed_task') return t('chat.shippingNoticeDuplicateSameCompleted');
if (status === 'possible_duplicate') return t('chat.shippingNoticeDuplicatePossible');
return t('chat.shippingNoticeDuplicateNeedsResolution');
});
</script>
<template>
<div
v-if="open && attachment"
class="fixed inset-0 z-[160] flex items-center justify-center bg-black/40 px-4"
role="dialog"
aria-modal="true"
>
<div class="w-full max-w-lg rounded-xl border border-default bg-surface p-5 shadow-xl">
<h3 class="text-base font-semibold text-primary">
{{ t('chat.shippingNoticeDuplicateTitle') }}
</h3>
<p class="mt-2 text-sm text-secondary">{{ statusLabel }}</p>
<p class="mt-1 text-xs text-muted">
{{ attachment.originalFilename }}
</p>
<div
v-if="match"
class="mt-4 rounded-lg border border-default bg-surface-soft px-3 py-2 text-sm text-secondary"
>
<div>{{ t('chat.shippingNoticeDuplicateMatchTask', { taskNo: match.taskNo }) }}</div>
<div class="mt-1 text-xs text-muted">
{{ t('chat.shippingNoticeDuplicateMatchStatus', { status: match.processStatus }) }}
· v{{ match.documentVersion }}
</div>
<div v-if="match.matchedFields?.length" class="mt-1 text-xs text-muted">
{{ t('chat.shippingNoticeDuplicateMatchFields', { fields: match.matchedFields.join(', ') }) }}
</div>
</div>
<div class="mt-4 space-y-2">
<label
v-if="allowed.has('open_existing')"
class="flex cursor-pointer items-start gap-2 rounded-lg border border-default px-3 py-2 text-sm"
:class="selectedAction === 'open_existing' ? 'border-brand-500 bg-brand-50/40' : ''"
>
<input v-model="selectedAction" type="radio" value="open_existing" class="mt-1" />
<span>
<span class="font-medium text-primary">{{ t('chat.shippingNoticeDuplicateOpenExisting') }}</span>
<span class="mt-0.5 block text-xs text-muted">{{ t('chat.shippingNoticeDuplicateOpenExistingHint') }}</span>
</span>
</label>
<label
v-if="allowed.has('create_revision')"
class="flex cursor-pointer items-start gap-2 rounded-lg border border-default px-3 py-2 text-sm"
:class="selectedAction === 'create_revision' ? 'border-brand-500 bg-brand-50/40' : ''"
>
<input v-model="selectedAction" type="radio" value="create_revision" class="mt-1" />
<span>
<span class="font-medium text-primary">{{ t('chat.shippingNoticeDuplicateCreateRevision') }}</span>
<span class="mt-0.5 block text-xs text-muted">{{ t('chat.shippingNoticeDuplicateCreateRevisionHint') }}</span>
</span>
</label>
<label
v-if="allowed.has('force_create') && canForceCreate"
class="flex cursor-pointer items-start gap-2 rounded-lg border border-default px-3 py-2 text-sm"
:class="selectedAction === 'force_create' ? 'border-amber-500 bg-amber-50/50' : ''"
>
<input v-model="selectedAction" type="radio" value="force_create" class="mt-1" />
<span>
<span class="font-medium text-primary">{{ t('chat.shippingNoticeDuplicateForceCreate') }}</span>
<span class="mt-0.5 block text-xs text-muted">{{ t('chat.shippingNoticeDuplicateForceCreateHint') }}</span>
</span>
</label>
</div>
<div v-if="selectedAction === 'force_create'" class="mt-3">
<label class="text-xs font-medium text-secondary">{{ t('chat.shippingNoticeDuplicateReasonLabel') }}</label>
<textarea
v-model="reason"
rows="2"
class="mt-1 w-full rounded-lg border border-default bg-surface px-3 py-2 text-sm"
:placeholder="t('chat.shippingNoticeDuplicateReasonPlaceholder')"
/>
</div>
<p v-if="localError" class="mt-2 text-xs text-red-600">{{ localError }}</p>
<div class="mt-5 flex flex-wrap justify-end gap-2">
<button type="button" class="rounded-lg px-3 py-1.5 text-sm text-muted hover:text-primary" @click="close">
{{ t('common.cancel') }}
</button>
<button
type="button"
class="rounded-lg px-3 py-1.5 text-sm text-red-600 hover:bg-red-50"
@click="emit('remove'); emit('update:open', false)"
>
{{ t('chat.shippingNoticeDuplicateRemoveFile') }}
</button>
<button
type="button"
class="rounded-lg bg-brand-600 px-3 py-1.5 text-sm font-medium text-white disabled:opacity-50"
:disabled="submitting || !match"
@click="confirm"
>
{{ t('chat.shippingNoticeDuplicateConfirm') }}
</button>
</div>
</div>
</div>
</template>
@@ -31,6 +31,7 @@ import { useChatStore } from '../stores/chat.store';
import { useTrainingWorkspace } from './useTrainingWorkspace';
import { matchesTrainingAgent } from '../training/trainingWorkspace.utils';
import { hasActiveRunningChatRun } from '../shipping/shippingActionBusy';
import { clearPendingNoticeBatchRetry } from '../shipping/useChatShippingUploadHandler';
import {
createChatPageConversationApi,
createChatPageLocalMessageApi,
@@ -337,6 +338,7 @@ export function useChatPage() {
isThinking,
loadConversationState,
createNewChatView,
clearPendingNoticeBatchRetry,
onConversationIdChanging: shipping.onConversationIdChanging,
onConversationLoadedEmpty: shipping.onConversationLoadedEmpty,
onConversationLoadFailed: shipping.onConversationLoadFailed,
@@ -536,6 +538,26 @@ export function useChatPage() {
showGuideSidebar: chatGuides.showSidebar,
openGuideModal: chatGuides.openModal,
...attachmentApi,
handleLocalFilesSelected: (event: Event) => {
if (shipping.handleShippingLocalFilesSelected(event)) return;
attachmentApi.handleLocalFilesSelected(event);
},
removeAttachment: (id: string) => {
const target = attachmentApi.attachments.value.find((item) => item.id === id);
if (target?.kind === 'shipping_notice') {
void shipping.removeShippingNoticeAttachment(id);
return;
}
attachmentApi.removeAttachment(id);
},
retryShippingNoticeAttachment: shipping.retryShippingNoticeAttachment,
showShippingDuplicateDialog: shipping.showShippingDuplicateDialog,
shippingDuplicateAttachment: shipping.shippingDuplicateAttachment,
canForceCreateShippingDuplicate: shipping.canForceCreateShippingDuplicate,
openShippingDuplicateDialog: shipping.openShippingDuplicateDialog,
resolveShippingDuplicateDialog: shipping.resolveShippingDuplicateDialog,
removeShippingDuplicateDialogAttachment: shipping.removeShippingDuplicateDialogAttachment,
closeShippingDuplicateDialog: shipping.closeShippingDuplicateDialog,
filePreviewVisible,
previewFile,
previewFiles,
@@ -14,10 +14,12 @@ import {
type ComputedRef,
type Ref,
} from 'vue';
import { useAuthStore } from '@/features/auth/stores/auth.store';
import { agentUsesWorkspaceStepperProgress, isShippingNoticeAgent as resolveShippingNoticeAgent } from '@/shared/utils/agent-registry.utils';
import type { AgentRegistryFields } from '@/shared/utils/agent-registry.utils';
import { hasActiveRunningChatRun } from '../shipping/shippingActionBusy';
import { useShippingNoticeIntakes } from '../shipping/useShippingNoticeIntakes';
import {
createShippingActionsRefresher,
createShippingConversationHelpers,
@@ -27,6 +29,7 @@ import {
createShippingParseReviewHandlers,
createShippingSendHandlers,
createShippingUploadHandlers,
onNoticeBatchConversationChanging,
findHistorySessionForShippingTask,
findLatestShippingTaskId,
getShippingInventoryMappingPayload,
@@ -39,6 +42,8 @@ import {
shippingActionButtonClass,
} from '../shipping';
import { reportShippingDebugEvent } from '../shipping/shippingDebugReporter';
import { classifyShippingUploadFile } from '../shipping/shippingUploadPrompt';
import { extractExt } from '../constants/shipping';
import {
getWorkspaceShippingConversationBatches,
getWorkspaceShippingBatch,
@@ -656,6 +661,75 @@ export function useChatShipping(options: UseChatShippingOptions) {
msg,
});
const shippingIntakes = useShippingNoticeIntakes({
attachments,
conversationId,
msg,
t,
});
const showShippingDuplicateDialog = ref(false);
const shippingDuplicateAttachmentId = ref<string | null>(null);
const shippingDuplicateAttachment = computed(() => {
const id = shippingDuplicateAttachmentId.value;
if (!id) return null;
return shippingIntakes.noticeAttachments.value.find((item) => item.id === id) || null;
});
const canForceCreateShippingDuplicate = computed(() => {
const user = useAuthStore().user;
if (!user) return false;
if (String(user.role || '') === 'admin') return true;
return Boolean(user.feature_permissions?.shipping_notice_force_create);
});
/**
* 打开首个(或指定)阻断型重复附件的处理弹窗。
*/
const openShippingDuplicateDialog = (attachmentId?: string) => {
const targetId =
attachmentId
|| shippingIntakes.noticeAttachments.value.find(
(item) => item.duplicate?.blocking && !item.duplicateResolution?.action,
)?.id
|| null;
if (!targetId) {
msg.warning(t('chat.shippingNoticeDuplicateNeedsResolution'));
return;
}
shippingDuplicateAttachmentId.value = targetId;
showShippingDuplicateDialog.value = true;
};
/**
* 提交重复决策并写回附件状态。
*/
const resolveShippingDuplicateDialog = async (payload: {
action: import('../types/shipping.types').ShippingDuplicateAction;
targetTaskNo?: string;
reason?: string;
}) => {
const id = shippingDuplicateAttachmentId.value;
if (!id) return;
try {
await shippingIntakes.resolveDuplicateAttachment(
id,
payload.action,
payload.targetTaskNo,
payload.reason,
);
msg.success(t('chat.shippingNoticeDuplicateResolved'));
} catch (e: unknown) {
msg.warning(e instanceof Error ? e.message : t('chat.shippingNoticeDuplicateResolveFailed'));
}
};
const removeShippingDuplicateDialogAttachment = async () => {
const id = shippingDuplicateAttachmentId.value;
if (!id) return;
await shippingIntakes.removeNoticeAttachment(id);
shippingDuplicateAttachmentId.value = null;
};
const {
handleShippingAutoUploadFile,
handleShippingAutoUploadNoticeBatch,
@@ -666,6 +740,7 @@ export function useChatShipping(options: UseChatShippingOptions) {
handleShippingInventorySelected,
shippingSuggestedPrompt,
useShippingSuggestedPrompt,
isShippingNoticeBatchSubmitting,
} = createShippingUploadHandlers({
conversationId,
currentAgentId,
@@ -687,6 +762,8 @@ export function useChatShipping(options: UseChatShippingOptions) {
getActiveShippingTaskId,
startChatTurn,
refreshShippingActions,
getParsedIntakeNos: shippingIntakes.getParsedIntakeNos,
clearConsumedNoticeAttachments: shippingIntakes.clearConsumedAttachments,
msg,
t,
});
@@ -738,6 +815,12 @@ export function useChatShipping(options: UseChatShippingOptions) {
handleShippingMenuAction,
handleShippingAutoUploadFile,
handleShippingAutoUploadNoticeBatch,
isShippingNoticeBatchSubmitting,
hasBlockingNoticeIntake: () => shippingIntakes.hasBlockingUploadOrParse.value,
hasNoticeIntakeFailures: () => shippingIntakes.hasParseFailures.value,
hasBlockingNoticeDuplicates: () => shippingIntakes.hasBlockingDuplicates.value,
openShippingDuplicateDialog,
getParsedIntakeNos: shippingIntakes.getParsedIntakeNos,
refreshShippingActions,
shippingSuggestedPrompt,
isShippingShortageQueryIntent,
@@ -778,6 +861,11 @@ export function useChatShipping(options: UseChatShippingOptions) {
};
const onConversationIdChanging = (nextId: string, prevId: string | null | undefined) => {
onNoticeBatchConversationChanging(nextId, prevId);
shippingIntakes.stopPolling();
if (nextId && nextId !== prevId) {
void shippingIntakes.restoreForConversation(nextId);
}
if (prevId !== nextId) {
resolvedShippingTaskId.value = '';
if (!shippingBatchNoFromQuery.value) {
@@ -851,6 +939,33 @@ export function useChatShipping(options: UseChatShippingOptions) {
}
};
const handleShippingLocalFilesSelected = (event: Event): boolean => {
if (!isShippingNoticeAgent.value) return false;
const inputEl = event.target as HTMLInputElement | null;
const files = inputEl?.files ? Array.from(inputEl.files) : [];
if (!files.length) return false;
const noticeFiles = files.filter((file) => classifyShippingUploadFile(file, extractExt) === 'notice');
const otherFiles = files.filter((file) => classifyShippingUploadFile(file, extractExt) !== 'notice');
if (noticeFiles.length) {
void shippingIntakes.enqueueNoticeFiles(noticeFiles);
}
// 同一次选择中的库存/其他文件直接落入本地附件,避免清空 input 后通用 handler 丢失 FileList
for (const file of otherFiles) {
const kind = classifyShippingUploadFile(file, extractExt);
attachments.value = [
...attachments.value,
{
id: `${Date.now()}_${Math.random().toString(36).slice(2, 8)}`,
kind: 'local',
file,
type: kind === 'inventory' ? 'document' : 'document',
},
];
}
if (inputEl) inputEl.value = '';
return true;
};
const onConversationLoadedEmpty = async () => {
if (!isShippingNoticeAgent.value || !shippingTaskIdFromQuery.value || isShippingActionBusy.value) return;
const nextQuery: Record<string, string> = { task_id: shippingTaskIdFromQuery.value };
@@ -1013,6 +1128,19 @@ export function useChatShipping(options: UseChatShippingOptions) {
shippingActionButtonClass,
shippingSuggestedPrompt,
useShippingSuggestedPrompt,
enqueueShippingNoticeFiles: shippingIntakes.enqueueNoticeFiles,
handleShippingLocalFilesSelected,
removeShippingNoticeAttachment: shippingIntakes.removeNoticeAttachment,
retryShippingNoticeAttachment: shippingIntakes.retryNoticeAttachment,
showShippingDuplicateDialog,
shippingDuplicateAttachment,
canForceCreateShippingDuplicate,
openShippingDuplicateDialog,
resolveShippingDuplicateDialog,
removeShippingDuplicateDialogAttachment,
closeShippingDuplicateDialog: () => {
showShippingDuplicateDialog.value = false;
},
tryHandleShippingAttachmentAutoFlow,
tryHandleShippingSend,
onConversationIdChanging,
@@ -0,0 +1,166 @@
/**
* features/chat/page/useChatPageConversation.spec.ts
* 用途:验证新建聊天与 Agent 切换时清理发货通知待重试建批幂等状态。
* 依赖:vitest、vue refs/computed、useChatPageConversation、useChatShippingUploadHandler。
* 逻辑:覆盖 createNewChatView 不经 onConversationIdChanging 时仍生成新幂等键的回归场景。
*/
import { computed, ref } from 'vue';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { createChatPageConversationApi } from './useChatPageConversation';
import {
clearPendingNoticeBatchRetry,
createShippingUploadHandlers,
resetShippingNoticeBatchSubmitStateForTests,
type ShippingUploadHandlerContext,
} from '../shipping/useChatShippingUploadHandler';
const { listChatMessages } = vi.hoisted(() => ({
listChatMessages: vi.fn(),
}));
const { computeNoticeFilesContentFingerprint } = vi.hoisted(() => ({
computeNoticeFilesContentFingerprint: vi.fn(async (files: File[]) => {
const content = await files[0]?.text();
return `fp-${content || 'empty'}`;
}),
}));
vi.mock('../api/chat.api', () => ({
listChatMessages,
}));
vi.mock('../shipping/shippingNoticeBatchIdempotency', () => ({
computeNoticeFilesContentFingerprint,
}));
const createConversationContext = () => {
const conversationId = ref<string | null>('conv-a');
const messages = ref([]);
const createNewChatView = vi.fn(() => {
conversationId.value = null;
messages.value = [];
});
return {
conversationId,
messages,
createNewChatView,
api: createChatPageConversationApi({
deps: { t: (key: string) => key, msg: { warning: vi.fn() } },
route: { path: '/chat/42', query: {} } as never,
router: { replace: vi.fn() } as never,
currentAgentId: computed(() => 42),
conversationId,
activeRunId: ref(null),
messages,
isThinking: ref(false),
loadConversationState: vi.fn(),
createNewChatView,
clearPendingNoticeBatchRetry,
onConversationIdChanging: vi.fn(),
onConversationLoadedEmpty: vi.fn(async () => undefined),
onConversationLoadFailed: vi.fn(async () => undefined),
isShippingNoticeAgent: computed(() => true),
shippingTaskIdFromQuery: computed(() => ''),
shippingBatchNoFromQuery: computed(() => ''),
clearHistory: vi.fn(),
clearAttachments: vi.fn(),
input: ref(''),
resetCurrentAgent: vi.fn(),
copiedIndex: ref(null),
resetPeripheralState: vi.fn(),
filePreviewVisible: ref(false),
previewFile: ref(null),
previewFiles: ref([]),
currentPreviewIndex: ref(0),
}),
};
};
const createUploadContext = (
conversationId: ReturnType<typeof ref<string | null>>,
startChatTurn: ReturnType<typeof vi.fn>,
): ShippingUploadHandlerContext => ({
conversationId,
currentAgentId: computed(() => 42),
attachments: ref([]),
input: ref(''),
shippingAutoFlowRequested: ref(false),
shippingInventoryPickerRef: ref({ click: vi.fn() } as unknown as HTMLInputElement),
shippingNoticePickerRef: ref({ click: vi.fn() } as unknown as HTMLInputElement),
pendingShippingUploadTaskId: ref(''),
pendingShippingNoticeTaskId: ref(''),
pendingShippingInventoryFile: ref(null),
resolvedShippingTaskId: ref(''),
resolvedShippingBatchNo: ref(''),
shippingBatchSummary: ref(null),
shippingBatchTasks: ref([]),
shippingInventorySelectionActive: ref(false),
shippingInventorySelectionTaskId: ref(''),
shippingInventorySchemaPreviewCache: ref({}),
getActiveShippingTaskId: () => '',
startChatTurn,
refreshShippingActions: vi.fn(async () => undefined),
msg: { warning: vi.fn() },
t: (key: string) => key,
});
describe('useChatPageConversation', () => {
beforeEach(() => {
listChatMessages.mockReset();
computeNoticeFilesContentFingerprint.mockReset();
computeNoticeFilesContentFingerprint.mockImplementation(async (files: File[]) => {
const content = await files[0]?.text();
return `fp-${content || 'empty'}`;
});
resetShippingNoticeBatchSubmitStateForTests();
});
it('startNewChat clears pending notice batch retry and next upload uses a new idempotency key', async () => {
const startChatTurn = vi.fn(async () => false);
const { conversationId, createNewChatView, api } = createConversationContext();
const { handleShippingAutoUploadNoticeBatch } = createShippingUploadHandlers(
createUploadContext(conversationId, startChatTurn),
);
const file = new File(['notice'], 'notice.pdf', { type: 'application/pdf' });
await handleShippingAutoUploadNoticeBatch([file]);
const firstKey = (startChatTurn.mock.calls[0]?.[0] as { payload?: Record<string, unknown> })?.payload?.idempotency_key;
api.startNewChat();
expect(createNewChatView).toHaveBeenCalledTimes(1);
expect(conversationId.value).toBeNull();
await handleShippingAutoUploadNoticeBatch([file]);
const secondKey = (startChatTurn.mock.calls[1]?.[0] as { payload?: Record<string, unknown> })?.payload?.idempotency_key;
expect(firstKey).toBeTruthy();
expect(secondKey).toBeTruthy();
expect(secondKey).not.toBe(firstKey);
});
it('resetChatStateForAgentChange clears pending notice batch retry and next upload uses a new idempotency key', async () => {
const startChatTurn = vi.fn(async () => false);
const { conversationId, createNewChatView, api } = createConversationContext();
const { handleShippingAutoUploadNoticeBatch } = createShippingUploadHandlers(
createUploadContext(conversationId, startChatTurn),
);
const file = new File(['notice'], 'notice.pdf', { type: 'application/pdf' });
await handleShippingAutoUploadNoticeBatch([file]);
const firstKey = (startChatTurn.mock.calls[0]?.[0] as { payload?: Record<string, unknown> })?.payload?.idempotency_key;
api.resetChatStateForAgentChange();
expect(createNewChatView).toHaveBeenCalledTimes(1);
expect(conversationId.value).toBeNull();
await handleShippingAutoUploadNoticeBatch([file]);
const secondKey = (startChatTurn.mock.calls[1]?.[0] as { payload?: Record<string, unknown> })?.payload?.idempotency_key;
expect(firstKey).toBeTruthy();
expect(secondKey).toBeTruthy();
expect(secondKey).not.toBe(firstKey);
});
});
@@ -17,6 +17,7 @@ export interface ChatPageConversationContext {
isThinking: Ref<boolean>;
loadConversationState: (id: string, loaded: ChatMessage[]) => void;
createNewChatView: () => void;
clearPendingNoticeBatchRetry: () => void;
onConversationIdChanging: (nextId: string, prevId: string | null | undefined) => void;
onConversationLoadedEmpty: () => Promise<void>;
onConversationLoadFailed: () => Promise<void>;
@@ -71,6 +72,7 @@ export function createChatPageConversationApi(ctx: ChatPageConversationContext)
};
const startNewChat = () => {
ctx.clearPendingNoticeBatchRetry();
ctx.createNewChatView();
ctx.clearAttachments();
ctx.input.value = '';
@@ -84,6 +86,7 @@ export function createChatPageConversationApi(ctx: ChatPageConversationContext)
};
const resetChatStateForAgentChange = () => {
ctx.clearPendingNoticeBatchRetry();
ctx.createNewChatView();
ctx.clearHistory();
ctx.clearAttachments();
@@ -0,0 +1,56 @@
/**
* features/chat/shipping/shippingNoticeAttachmentIntegrity.spec.ts
* 用途:附件完整性门禁单测;阻断码与截断路径须能阻止建单判定。
*/
import { describe, expect, it } from 'vitest';
import {
BLOCKING_WARNING_PREFIXES,
isShippingNoticeAttachmentParseIncomplete,
} from './shippingNoticeAttachmentIntegrity';
describe('shippingNoticeAttachmentIntegrity', () => {
it('treats each blocking warning prefix as incomplete', () => {
for (const prefix of BLOCKING_WARNING_PREFIXES) {
expect(
isShippingNoticeAttachmentParseIncomplete({
warnings: [`${prefix}demo`],
attachments: [],
}),
).toBe(true);
}
});
it('treats per-attachment text truncation as incomplete', () => {
expect(
isShippingNoticeAttachmentParseIncomplete({
attachment_count: 1,
attachments: [
{
parse_status: 'parsed',
warnings: ['eml_attachment_text_truncated:10'],
},
],
warnings: [],
}),
).toBe(true);
});
it('treats notice_text_truncated as incomplete', () => {
expect(
isShippingNoticeAttachmentParseIncomplete({
warnings: ['notice_text_truncated:200000'],
attachments: [],
}),
).toBe(true);
});
it('allows clean parsed summary', () => {
expect(
isShippingNoticeAttachmentParseIncomplete({
attachment_count: 1,
attachments: [{ parse_status: 'parsed', warnings: [] }],
warnings: [],
}),
).toBe(false);
});
});
@@ -0,0 +1,54 @@
/**
* features/chat/shipping/shippingNoticeAttachmentIntegrity.ts
* 用途:发货通知附件完整性门禁契约(阻断 warning 前缀与 incomplete 判定)。
* 依赖:shipping.types(ParseSummary 形状)。
* 逻辑:与后端 attachment_integrity.BLOCKING_WARNING_PREFIXES /
* is_attachment_parse_incomplete 保持一致;契约测试校验两端前缀集合。
*/
import type { ShippingNoticeParseSummary } from '../types/shipping.types';
/** 阻断 warning 前缀;须与 backend BLOCKING_WARNING_PREFIXES 完全一致(顺序可不同)。 */
export const BLOCKING_WARNING_PREFIXES = [
'eml_nesting_depth_exceeded:',
'eml_attachment_limit_exceeded:',
'eml_total_attachment_size_exceeded:',
'eml_nested_message_unreadable',
'eml_attachment_text_budget_exhausted:',
'eml_attachment_text_truncated:',
'notice_text_truncated:',
] as const;
const INCOMPLETE_ATTACHMENT_STATUSES = new Set(['failed', 'empty', 'skipped']);
/**
* 判定单条 warning 是否为完整性阻断项。
*/
export function isBlockingWarning(text: string): boolean {
const normalized = String(text || '');
return BLOCKING_WARNING_PREFIXES.some((prefix) => normalized.startsWith(prefix));
}
/**
* 判定 EML 等 intake 是否存在未完整解析的附件(含超深/超限/截断警告)。
* 核心逻辑:阻断警告、登记数少于发现数、或 failed/empty/skipped 均视为不完整;
* duplicate 仅为去重,不阻断建单。
*/
export function isShippingNoticeAttachmentParseIncomplete(
summary?: ShippingNoticeParseSummary | null,
): boolean {
if (!summary) return false;
const warnings = summary.warnings || [];
if (warnings.some((item) => isBlockingWarning(String(item || '')))) {
return true;
}
const rows = summary.attachments || [];
const total = Number(summary.attachment_count || 0);
if (total > rows.length) return true;
return rows.some((item) => {
if (INCOMPLETE_ATTACHMENT_STATUSES.has(String(item.parse_status || ''))) {
return true;
}
return (item.warnings || []).some((w) => isBlockingWarning(String(w || '')));
});
}
@@ -0,0 +1,23 @@
/**
* features/chat/shipping/shippingNoticeBatchIdempotency.spec.ts
* 用途:验证前端文件集合指纹与后端 compute_notice_items_content_fingerprint 对齐。
*/
import { describe, expect, it } from 'vitest';
import { computeNoticeFilesContentFingerprint } from './shippingNoticeBatchIdempotency';
describe('shippingNoticeBatchIdempotency', () => {
it('treats duplicate files as one content set', async () => {
const content = 'same-notice-content';
const single = new File([content], 'a.txt', { type: 'text/plain' });
const duplicatePair = [
new File([content], 'a.txt', { type: 'text/plain' }),
new File([content], 'b.txt', { type: 'text/plain' }),
];
const singleFp = await computeNoticeFilesContentFingerprint([single]);
const duplicateFp = await computeNoticeFilesContentFingerprint(duplicatePair);
expect(singleFp).toBeTruthy();
expect(duplicateFp).toBe(singleFp);
});
});
@@ -0,0 +1,38 @@
/**
* features/chat/shipping/shippingNoticeBatchIdempotency.ts
* 用途:发货通知建批幂等键与文件集合指纹计算。
* 依赖:浏览器 Web Crypto API。
* 逻辑:useChatShippingUploadHandler 在重试时绑定「幂等键 + 文件指纹」,文件变化时生成新键。
*/
/**
* 将 File 列表转为与后端 notice_items 对齐的内容指纹(排序哈希后二次 SHA-256)。
*/
export async function computeNoticeFilesContentFingerprint(files: File[]): Promise<string> {
const hashes: string[] = [];
for (const file of files) {
if (!file) continue;
const buffer = await file.arrayBuffer();
const digest = await crypto.subtle.digest('SHA-256', buffer);
const hex = Array.from(new Uint8Array(digest))
.map((byte) => byte.toString(16).padStart(2, '0'))
.join('');
hashes.push(hex.toLowerCase());
}
const uniqueHashes = [...new Set(hashes)].sort();
if (!uniqueHashes.length) return '';
const joined = uniqueHashes.join('|');
const encoded = new TextEncoder().encode(joined);
const fingerprintDigest = await crypto.subtle.digest('SHA-256', encoded);
return Array.from(new Uint8Array(fingerprintDigest))
.map((byte) => byte.toString(16).padStart(2, '0'))
.join('')
.toLowerCase();
}
/**
* 将 intake 编号列表转为建批重试指纹(排序去重后拼接)。
*/
export function computeNoticeIntakeNosFingerprint(intakeNos: string[]): string {
return [...new Set(intakeNos.map((item) => String(item || '').trim().toUpperCase()).filter(Boolean))].sort().join('|');
}
@@ -130,6 +130,7 @@ function deriveCurrentIndex(task: ShippingTaskStepperSource | null | undefined):
|| reviewStatus === 'rsv_required'
|| pendingReason === 'low_confidence'
|| pendingReason === 'rsv_required'
|| pendingReason === 'inventory_source_unresolved'
) {
return 1;
}
@@ -159,7 +160,12 @@ export function buildShippingWorkflowSteps(
}
if (
(index === 1 && (reviewStatus === 'parse_review' || pendingReason === 'low_confidence' || pendingReason === 'rsv_required'))
(index === 1 && (
reviewStatus === 'parse_review'
|| pendingReason === 'low_confidence'
|| pendingReason === 'rsv_required'
|| pendingReason === 'inventory_source_unresolved'
))
|| (index === 2 && (pendingReason === 'inv_unavail' || pendingReason === 'rpa_exhausted'))
|| (index === 3 && (reviewStatus === 'align_review' || pendingReason === 'align_review'))
|| (index === 4 && (reviewStatus === 'shortage_review' || pendingReason === 'shortage_review' || pendingReason === 'shortage'))
@@ -0,0 +1,22 @@
/**
* features/chat/shipping/shippingTurnActions.spec.ts
* 用途:验证建批 Chat Turn payload 包含幂等键与会话映射。
*/
import { describe, expect, it } from 'vitest';
import { buildShippingCreateBatchTurn } from './shippingTurnActions';
describe('shippingTurnActions', () => {
it('buildShippingCreateBatchTurn includes idempotency_key in payload', () => {
const files = [
new File(['notice-a'], 'notice-a.txt', { type: 'text/plain' }),
new File(['notice-b'], 'notice-b.txt', { type: 'text/plain' }),
];
const turn = buildShippingCreateBatchTurn(files, 'conv-001', 'idem-key-001');
expect(turn.actionType).toBe('shipping.create_batch_from_notices');
expect(turn.payload.conversation_id).toBe('conv-001');
expect(turn.payload.file_count).toBe(2);
expect(turn.payload.idempotency_key).toBe('idem-key-001');
expect(turn.files).toEqual(files);
});
});
@@ -78,6 +78,7 @@ export function buildShippingSubmitDecisionTurn(
export function buildShippingCreateBatchTurn(
files: File[],
conversationId?: string | null,
idempotencyKey?: string,
): { actionType: string; displayText: string; payload: Record<string, unknown>; files: File[] } {
const count = files.length;
const displayText = count === 1
@@ -89,11 +90,35 @@ export function buildShippingCreateBatchTurn(
payload: {
conversation_id: conversationId || undefined,
file_count: count,
idempotency_key: idempotencyKey,
},
files,
};
}
/**
* 构造发货通知建批 Chat Turn(基于已解析 intake,不再携带 files)。
*/
export function buildShippingCreateBatchFromIntakesTurn(
intakeNos: string[],
conversationId?: string | null,
idempotencyKey?: string,
): { actionType: string; displayText: string; payload: Record<string, unknown> } {
const count = intakeNos.length;
const displayText = count === 1
? `确认建单:${intakeNos[0]}`
: `确认建单:${count} 份发货通知`;
return {
actionType: 'shipping.create_batch_from_intakes',
displayText,
payload: {
intake_nos: intakeNos,
conversation_id: conversationId || undefined,
idempotency_key: idempotencyKey,
},
};
}
/**
* 构造货代领域 refs,键名与 agent_runtime_context.refs 对齐。
*/
@@ -32,7 +32,7 @@ export interface ShippingMenuHandlerContext {
refreshShippingActions: () => Promise<void>;
startChatTurn: (options: StartChatTurnOptions) => Promise<boolean>;
msg: { warning: (text: string) => void; info: (text: string) => void };
t: (key: string) => string;
t: (key: string, ...args: unknown[]) => string;
}
export interface HandleShippingMenuActionOptions {
@@ -97,8 +97,8 @@ export function createShippingMenuHandlers(ctx: ShippingMenuHandlerContext) {
if (!turnSpec) return false;
const displayBase = String(action.message || actionId || '操作').trim();
const displayText = actionId === 'confirm_inventory_source'
? `${displayBase}\n任务编号:${taskId}`
: `${displayBase}(任务编号:${taskId})`;
? ctx.t('chat.shippingNoticeUi.inventorySource.confirmWithTask', { taskId })
: ctx.t('chat.shippingNoticeUi.inventorySource.actionWithTask', { message: displayBase, taskId });
await ctx.startChatTurn({
agentId: ctx.currentAgentId.value,
inputType: 'action',
@@ -168,7 +168,7 @@ export function createShippingMenuHandlers(ctx: ShippingMenuHandlerContext) {
sourceCode = await resolveInventorySourceCodeFromContext(taskId);
}
if (!sourceCode) {
ctx.msg.warning('请直接输入要使用的库存源线索,例如 AWSDU、Dublin 或 Singapore。');
ctx.msg.warning(ctx.t('chat.shippingNoticeUi.inventorySource.inputHint'));
if (chatMsg) chatMsg.shipping_actions_used = false;
return;
}
@@ -179,7 +179,7 @@ export function createShippingMenuHandlers(ctx: ShippingMenuHandlerContext) {
}
const label = String(('label' in action ? action.label : '') || sourceCode).trim();
const displayMessage = action.id === 'confirm_inventory_source'
? `确认库存查询来源:${label || sourceCode}`
? ctx.t('chat.shippingNoticeUi.inventorySource.confirmDisplay', { label: label || sourceCode })
: action.message;
await runShippingActionTurn(
{ ...action, message: displayMessage },
@@ -195,7 +195,7 @@ export function createShippingMenuHandlers(ctx: ShippingMenuHandlerContext) {
if (action.id === 'retry_resolve_inventory_source') {
await ctx.refreshShippingActions();
ctx.msg.info('已重新刷新库存源状态');
ctx.msg.info(ctx.t('chat.shippingNoticeUi.inventorySource.retryResolveDone'));
return;
}
if (action.id === 'edit_inventory_mapping') {
@@ -0,0 +1,74 @@
/**
* features/chat/shipping/useChatShippingSendHandler.spec.ts
* 用途:验证建批提交中发送拦截不会回退到普通聊天发送。
*/
import { computed, ref } from 'vue';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { createShippingSendHandlers, type ShippingSendHandlerContext } from './useChatShippingSendHandler';
const isShippingNoticeBatchSubmitting = vi.hoisted(() => vi.fn(() => false));
vi.mock('./useChatShippingUploadHandler', () => ({
isShippingNoticeBatchSubmitting,
}));
const createContext = (
overrides: Partial<ShippingSendHandlerContext> = {},
): ShippingSendHandlerContext => ({
isShippingNoticeAgent: computed(() => true),
isThinking: ref(false),
isUploadingAttachments: ref(false),
messages: ref([]),
conversationId: ref('conv-send'),
history: ref([]),
input: ref(''),
attachments: ref([{ kind: 'local', file: new File(['notice'], 'notice.txt', { type: 'text/plain' }) }]),
shippingAutoFlowRequested: ref(true),
resolvedShippingTaskId: ref(''),
getActiveShippingBatchNo: () => '',
currentAgentId: computed(() => 1),
selectedKb: ref(''),
attachmentPolicy: computed(() => ({ anyEnabled: true })),
getActiveShippingTaskId: () => '',
lastAssistantMessageContent: () => '',
lastAssistantShippingActions: () => [],
sendMessage: vi.fn(async () => undefined),
buildFileSpecsForSend: vi.fn(async () => []),
loadHistory: vi.fn(async () => undefined),
sendShippingMenuMessage: vi.fn(async () => undefined),
startChatTurn: vi.fn(async () => true),
openShippingInventoryPicker: vi.fn(() => true),
executeShippingDecision: vi.fn(async () => true),
executeShippingManualUpload: vi.fn(async () => true),
handleShippingMenuAction: vi.fn(async () => undefined),
handleShippingAutoUploadFile: vi.fn(async () => undefined),
handleShippingAutoUploadNoticeBatch: vi.fn(async () => undefined),
isShippingNoticeBatchSubmitting: () => isShippingNoticeBatchSubmitting(),
refreshShippingActions: vi.fn(async () => undefined),
shippingSuggestedPrompt: computed(() => ''),
isShippingShortageQueryIntent: () => false,
queryShippingShortageDetails: vi.fn(async () => true),
msg: { warning: vi.fn(), info: vi.fn() },
t: (key: string) => key,
...overrides,
});
describe('useChatShippingSendHandler', () => {
beforeEach(() => {
isShippingNoticeBatchSubmitting.mockReset();
isShippingNoticeBatchSubmitting.mockReturnValue(false);
});
it('consumes send while notice batch is submitting and does not call sendMessage', async () => {
isShippingNoticeBatchSubmitting.mockReturnValue(true);
const ctx = createContext();
const { tryHandleShippingAttachmentAutoFlow } = createShippingSendHandlers(ctx);
const consumed = await tryHandleShippingAttachmentAutoFlow(undefined, '', '');
expect(consumed).toBe(true);
expect(ctx.sendMessage).not.toHaveBeenCalled();
expect(ctx.handleShippingAutoUploadNoticeBatch).not.toHaveBeenCalled();
expect(ctx.msg.info).toHaveBeenCalledWith('chat.shippingNoticeBatchSubmitting');
});
});
@@ -61,12 +61,18 @@ export interface ShippingSendHandlerContext {
handleShippingMenuAction: (action: ShippingActionButton | { id?: string; message: string; label?: string; source_code?: string }) => Promise<void>;
handleShippingAutoUploadFile: (file: File) => Promise<void>;
handleShippingAutoUploadNoticeBatch: (files: File[]) => Promise<void>;
isShippingNoticeBatchSubmitting?: () => boolean;
hasBlockingNoticeIntake?: () => boolean;
hasNoticeIntakeFailures?: () => boolean;
hasBlockingNoticeDuplicates?: () => boolean;
openShippingDuplicateDialog?: (attachmentId?: string) => void;
getParsedIntakeNos?: () => string[];
refreshShippingActions: () => Promise<void>;
shippingSuggestedPrompt: ComputedRef<string>;
isShippingShortageQueryIntent: (text: string) => boolean;
queryShippingShortageDetails: (taskNo?: string, displayText?: string) => Promise<boolean>;
msg: { warning: (text: string) => void; info: (text: string) => void };
t: (key: string) => string;
t: (key: string, ...args: unknown[]) => string;
}
/**
@@ -114,13 +120,13 @@ export function createShippingSendHandlers(ctx: ShippingSendHandlerContext) {
const label = String(hit?.display_name || sourceCode).trim();
await ctx.handleShippingMenuAction({
id: 'confirm_inventory_source',
message: `确认库存查询来源:${label}`,
message: ctx.t('chat.shippingNoticeUi.inventorySource.confirmDisplay', { label }),
label,
source_code: sourceCode,
});
return true;
} catch (e: unknown) {
const errorMessage = e instanceof Error ? e.message : '确认库存源失败';
const errorMessage = e instanceof Error ? e.message : ctx.t('chat.shippingNoticeUi.inventorySource.confirmFailed');
ctx.msg.warning(errorMessage);
return true;
}
@@ -186,9 +192,42 @@ export function createShippingSendHandlers(ctx: ShippingSendHandlerContext) {
_content: string,
trimmed: string,
): Promise<boolean> => {
if (!ctx.isShippingNoticeAgent.value) return false;
const noticeItems = ctx.attachments.value.filter((item) => item.kind === 'shipping_notice');
if (noticeItems.length > 0) {
if (ctx.hasBlockingNoticeIntake?.()) {
ctx.msg.info(ctx.t('chat.shippingNoticeWaitingForParse'));
return true;
}
if (ctx.hasNoticeIntakeFailures?.()) {
ctx.msg.warning(ctx.t('chat.shippingNoticeParseFailedHint'));
return true;
}
if (ctx.hasBlockingNoticeDuplicates?.()) {
ctx.openShippingDuplicateDialog?.();
ctx.msg.warning(ctx.t('chat.shippingNoticeDuplicateNeedsResolution'));
return true;
}
const intakeNos = ctx.getParsedIntakeNos?.() || [];
if (intakeNos.length && (!trimmed || ctx.shippingAutoFlowRequested.value)) {
ctx.shippingAutoFlowRequested.value = false;
if (typeof textOrEvent !== 'string') ctx.input.value = '';
try {
await ctx.handleShippingAutoUploadNoticeBatch([]);
} catch (e: unknown) {
const errorMessage = e instanceof Error ? e.message : '文件处理失败';
ctx.msg.warning(errorMessage);
}
return true;
}
}
if (!(ctx.shippingAutoFlowRequested.value || !trimmed)) return false;
if (!ctx.isShippingNoticeAgent.value || ctx.attachments.value.length === 0) return false;
if (ctx.isThinking.value || ctx.isUploadingAttachments.value) return false;
if (ctx.isShippingNoticeBatchSubmitting?.()) {
ctx.msg.info(ctx.t('chat.shippingNoticeBatchSubmitting'));
return true;
}
const requestedAutoFlow = ctx.shippingAutoFlowRequested.value;
ctx.shippingAutoFlowRequested.value = false;
const localFiles = ctx.attachments.value.filter((a) => a.kind === 'local') as Array<Extract<PendingAttachment, { kind: 'local' }>>;
@@ -7,7 +7,10 @@
import { computed, ref } from 'vue';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import {
clearPendingNoticeBatchRetry,
createShippingUploadHandlers,
onNoticeBatchConversationChanging,
resetShippingNoticeBatchSubmitStateForTests,
type ShippingUploadHandlerContext,
} from './useChatShippingUploadHandler';
@@ -15,10 +18,21 @@ const { createWorkspaceShippingTask } = vi.hoisted(() => ({
createWorkspaceShippingTask: vi.fn(),
}));
const { computeNoticeFilesContentFingerprint } = vi.hoisted(() => ({
computeNoticeFilesContentFingerprint: vi.fn(async (files: File[]) => {
const content = await files[0]?.text();
return `fp-${content || 'empty'}`;
}),
}));
vi.mock('@/features/chat/api/shipping.api', () => ({
createWorkspaceShippingTask,
}));
vi.mock('./shippingNoticeBatchIdempotency', () => ({
computeNoticeFilesContentFingerprint,
}));
const createContext = (
overrides: Partial<ShippingUploadHandlerContext> = {},
): ShippingUploadHandlerContext => ({
@@ -50,6 +64,12 @@ const createContext = (
describe('useChatShippingUploadHandler', () => {
beforeEach(() => {
createWorkspaceShippingTask.mockReset();
computeNoticeFilesContentFingerprint.mockReset();
computeNoticeFilesContentFingerprint.mockImplementation(async (files: File[]) => {
const content = await files[0]?.text();
return `fp-${content || 'empty'}`;
});
resetShippingNoticeBatchSubmitStateForTests();
});
it('opens inventory picker for explicit taskId instead of current active task', () => {
@@ -103,6 +123,186 @@ describe('useChatShippingUploadHandler', () => {
);
});
it('double click only calls startChatTurn once and keeps stable idempotency key', async () => {
const startChatTurn = vi.fn(async () => {
await new Promise((resolve) => setTimeout(resolve, 20));
return true;
});
const ctx = createContext({
getActiveShippingTaskId: () => '',
startChatTurn,
});
const { handleShippingAutoUploadNoticeBatch } = createShippingUploadHandlers(ctx);
const file = new File(['notice'], 'notice.pdf', { type: 'application/pdf' });
const first = handleShippingAutoUploadNoticeBatch([file]);
const second = handleShippingAutoUploadNoticeBatch([file]);
await Promise.all([first, second]);
expect(startChatTurn).toHaveBeenCalledTimes(1);
const payload = (startChatTurn.mock.calls[0]?.[0] as { payload?: Record<string, unknown> })?.payload;
expect(payload?.idempotency_key).toBeTruthy();
});
it('reuses idempotency key on retry and generates new key after success', async () => {
let attempt = 0;
const startChatTurn = vi.fn(async () => {
attempt += 1;
return attempt >= 2;
});
const ctx = createContext({
getActiveShippingTaskId: () => '',
startChatTurn,
});
const { handleShippingAutoUploadNoticeBatch } = createShippingUploadHandlers(ctx);
const file = new File(['notice'], 'notice.pdf', { type: 'application/pdf' });
await handleShippingAutoUploadNoticeBatch([file]);
const firstKey = (startChatTurn.mock.calls[0]?.[0] as { payload?: Record<string, unknown> })?.payload?.idempotency_key;
await handleShippingAutoUploadNoticeBatch([file]);
const secondKey = (startChatTurn.mock.calls[1]?.[0] as { payload?: Record<string, unknown> })?.payload?.idempotency_key;
await handleShippingAutoUploadNoticeBatch([file]);
const thirdKey = (startChatTurn.mock.calls[2]?.[0] as { payload?: Record<string, unknown> })?.payload?.idempotency_key;
expect(firstKey).toBe(secondKey);
expect(thirdKey).not.toBe(secondKey);
});
it('generates new idempotency key when files change after a failed attempt', async () => {
const startChatTurn = vi.fn(async () => false);
const ctx = createContext({
getActiveShippingTaskId: () => '',
startChatTurn,
});
const { handleShippingAutoUploadNoticeBatch } = createShippingUploadHandlers(ctx);
const firstFile = new File(['notice-a'], 'notice-a.pdf', { type: 'application/pdf' });
const secondFile = new File(['notice-b'], 'notice-b.pdf', { type: 'application/pdf' });
await handleShippingAutoUploadNoticeBatch([firstFile]);
const firstKey = (startChatTurn.mock.calls[0]?.[0] as { payload?: Record<string, unknown> })?.payload?.idempotency_key;
await handleShippingAutoUploadNoticeBatch([secondFile]);
const secondKey = (startChatTurn.mock.calls[1]?.[0] as { payload?: Record<string, unknown> })?.payload?.idempotency_key;
expect(firstKey).toBeTruthy();
expect(secondKey).toBeTruthy();
expect(secondKey).not.toBe(firstKey);
});
it('reuses idempotency key when conversation upgrades from empty to server-assigned after network failure', async () => {
const conversationId = ref<string | null>(null);
const startChatTurn = vi.fn(async () => {
conversationId.value = 'conv-server-new';
return false;
});
const ctx = createContext({
conversationId,
getActiveShippingTaskId: () => '',
startChatTurn,
});
const { handleShippingAutoUploadNoticeBatch } = createShippingUploadHandlers(ctx);
const file = new File(['notice'], 'notice.pdf', { type: 'application/pdf' });
await handleShippingAutoUploadNoticeBatch([file]);
const firstKey = (startChatTurn.mock.calls[0]?.[0] as { payload?: Record<string, unknown> })?.payload?.idempotency_key;
await handleShippingAutoUploadNoticeBatch([file]);
const secondKey = (startChatTurn.mock.calls[1]?.[0] as { payload?: Record<string, unknown> })?.payload?.idempotency_key;
expect(firstKey).toBeTruthy();
expect(secondKey).toBe(firstKey);
});
it('generates new idempotency key when switching from new chat to historical session', async () => {
const startChatTurn = vi.fn(async () => false);
const conversationId = ref<string | null>(null);
const ctx = createContext({
conversationId,
getActiveShippingTaskId: () => '',
startChatTurn,
});
const { handleShippingAutoUploadNoticeBatch } = createShippingUploadHandlers(ctx);
const file = new File(['notice'], 'notice.pdf', { type: 'application/pdf' });
await handleShippingAutoUploadNoticeBatch([file]);
const firstKey = (startChatTurn.mock.calls[0]?.[0] as { payload?: Record<string, unknown> })?.payload?.idempotency_key;
onNoticeBatchConversationChanging('conv-history', '');
conversationId.value = 'conv-history';
await handleShippingAutoUploadNoticeBatch([file]);
const secondKey = (startChatTurn.mock.calls[1]?.[0] as { payload?: Record<string, unknown> })?.payload?.idempotency_key;
expect(firstKey).toBeTruthy();
expect(secondKey).toBeTruthy();
expect(secondKey).not.toBe(firstKey);
});
it('generates new idempotency key after explicit clearPendingNoticeBatchRetry', async () => {
const startChatTurn = vi.fn(async () => false);
const conversationId = ref('conv-a');
const ctx = createContext({
conversationId,
getActiveShippingTaskId: () => '',
startChatTurn,
});
const { handleShippingAutoUploadNoticeBatch } = createShippingUploadHandlers(ctx);
const file = new File(['notice'], 'notice.pdf', { type: 'application/pdf' });
await handleShippingAutoUploadNoticeBatch([file]);
const firstKey = (startChatTurn.mock.calls[0]?.[0] as { payload?: Record<string, unknown> })?.payload?.idempotency_key;
clearPendingNoticeBatchRetry();
conversationId.value = null;
await handleShippingAutoUploadNoticeBatch([file]);
const secondKey = (startChatTurn.mock.calls[1]?.[0] as { payload?: Record<string, unknown> })?.payload?.idempotency_key;
expect(firstKey).toBeTruthy();
expect(secondKey).toBeTruthy();
expect(secondKey).not.toBe(firstKey);
});
it('generates new idempotency key when conversation changes after a failed attempt', async () => {
const startChatTurn = vi.fn(async () => false);
const conversationId = ref('conv-a');
const ctx = createContext({
conversationId,
getActiveShippingTaskId: () => '',
startChatTurn,
});
const { handleShippingAutoUploadNoticeBatch } = createShippingUploadHandlers(ctx);
const file = new File(['notice'], 'notice.pdf', { type: 'application/pdf' });
await handleShippingAutoUploadNoticeBatch([file]);
const firstKey = (startChatTurn.mock.calls[0]?.[0] as { payload?: Record<string, unknown> })?.payload?.idempotency_key;
onNoticeBatchConversationChanging('conv-b', 'conv-a');
conversationId.value = 'conv-b';
await handleShippingAutoUploadNoticeBatch([file]);
const secondKey = (startChatTurn.mock.calls[1]?.[0] as { payload?: Record<string, unknown> })?.payload?.idempotency_key;
expect(firstKey).toBeTruthy();
expect(secondKey).toBeTruthy();
expect(secondKey).not.toBe(firstKey);
});
it('releases submit lock when fingerprint computation fails', async () => {
computeNoticeFilesContentFingerprint.mockRejectedValueOnce(new Error('digest failed'));
const startChatTurn = vi.fn(async () => true);
const ctx = createContext({
getActiveShippingTaskId: () => '',
startChatTurn,
});
const { handleShippingAutoUploadNoticeBatch, isShippingNoticeBatchSubmitting } = createShippingUploadHandlers(ctx);
const file = new File(['notice'], 'notice.pdf', { type: 'application/pdf' });
await expect(handleShippingAutoUploadNoticeBatch([file])).rejects.toThrow('digest failed');
expect(startChatTurn).not.toHaveBeenCalled();
expect(isShippingNoticeBatchSubmitting()).toBe(false);
computeNoticeFilesContentFingerprint.mockResolvedValueOnce('fp-notice');
await handleShippingAutoUploadNoticeBatch([file]);
expect(startChatTurn).toHaveBeenCalledTimes(1);
});
it('does not open notice picker when both explicit taskId and active task are missing', () => {
const noticeClick = vi.fn();
const warning = vi.fn();
@@ -2,7 +2,7 @@
* features/chat/shipping/useChatShippingUploadHandler.ts
* 用途:处理发货通知与库存文件上传、批量建单和附件建议提示。
* 依赖:shipping.api、shippingUploadPrompt、shipping 常量、chat.types。
* 逻辑:发货通知建批/库存上传/单票覆盖均经 startChatTurn + multipart SSE。
* 逻辑:发货通知建批/库存上传/单票覆盖均经 startChatTurn + multipart SSE;待重试幂等键绑定 conversation_id。
*/
import { computed } from 'vue';
import {
@@ -10,13 +10,92 @@ import {
type ShippingTaskSummary,
} from '@/features/chat/api/shipping.api';
import { extractExt } from '../constants/shipping';
import { buildShippingCreateBatchTurn, buildShippingReplaceNoticeTurn, buildShippingUploadInventoryTurn } from './shippingTurnActions';
import { buildShippingCreateBatchTurn, buildShippingCreateBatchFromIntakesTurn, buildShippingReplaceNoticeTurn, buildShippingUploadInventoryTurn } from './shippingTurnActions';
import { computeNoticeFilesContentFingerprint, computeNoticeIntakeNosFingerprint } from './shippingNoticeBatchIdempotency';
import { classifyShippingUploadFile } from './shippingUploadPrompt';
import type { StartChatTurnOptions } from '../types/chat-turn.types';
import type { ChatMessage } from '../types/chat.types';
import type { PendingAttachment } from '../types/shipping.types';
import type { ComputedRef, Ref } from 'vue';
let noticeBatchSubmitting = false;
interface PendingNoticeBatchRetryState {
conversationId: string;
idempotencyKey: string;
fileFingerprint: string;
}
let pendingNoticeBatchRetry: PendingNoticeBatchRetryState | null = null;
function normalizeConversationId(conversationId: string | null | undefined): string {
return String(conversationId || '').trim();
}
function clearPendingNoticeBatchRetryState(): void {
pendingNoticeBatchRetry = null;
}
/**
* 显式清理待重试建批幂等状态(新建聊天、切换 Agent 等不经 onConversationIdChanging 的路径)。
*/
export function clearPendingNoticeBatchRetry(): void {
clearPendingNoticeBatchRetryState();
}
/**
* 判断待重试状态是否应绑定到当前会话。
* 核心逻辑:允许「尚未分配会话」升级绑定服务端新 ID;两个非空且不同、或旧非空而新为空时清理。
*/
function reconcilePendingNoticeBatchConversation(
pending: PendingNoticeBatchRetryState,
conversationKey: string,
): void {
const pendingKey = pending.conversationId;
if (pendingKey === conversationKey) {
return;
}
if (!pendingKey && conversationKey) {
pending.conversationId = conversationKey;
return;
}
if (pendingKey && !conversationKey) {
clearPendingNoticeBatchRetryState();
return;
}
if (pendingKey && conversationKey && pendingKey !== conversationKey) {
clearPendingNoticeBatchRetryState();
}
}
/**
* 用户主动切换会话时清理待重试建批状态,避免跨会话复用幂等键。
* 仅由 onConversationIdChanging 调用;SSE 自动分配 conversation_id 不经过此函数。
*/
export function onNoticeBatchConversationChanging(
nextId: string,
prevId?: string | null,
): void {
const next = normalizeConversationId(nextId);
const prev = normalizeConversationId(prevId);
if (next !== prev) {
clearPendingNoticeBatchRetryState();
}
}
/**
* 查询发货通知建批是否正在提交中(供发送拦截器消费重复点击)。
*/
export function isShippingNoticeBatchSubmitting(): boolean {
return noticeBatchSubmitting;
}
/** 单测重置模块级建批提交状态。 */
export function resetShippingNoticeBatchSubmitStateForTests(): void {
noticeBatchSubmitting = false;
clearPendingNoticeBatchRetry();
}
export interface ShippingUploadHandlerContext {
conversationId: Ref<string | null>;
currentAgentId: ComputedRef<number>;
@@ -40,6 +119,8 @@ export interface ShippingUploadHandlerContext {
refreshShippingActions: () => Promise<void>;
msg: { warning: (text: string) => void };
t: (key: string, params?: Record<string, unknown>) => string;
getParsedIntakeNos?: () => string[];
clearConsumedNoticeAttachments?: () => void;
}
/**
@@ -135,25 +216,58 @@ export function createShippingUploadHandlers(ctx: ShippingUploadHandlerContext)
};
const runNoticeBatchChatTurn = async (files: File[]) => {
const turn = buildShippingCreateBatchTurn(files, ctx.conversationId.value);
const ok = await ctx.startChatTurn({
agentId: ctx.currentAgentId.value,
inputType: 'upload_followup',
displayText: turn.displayText,
actionType: turn.actionType,
payload: turn.payload,
files: turn.files,
hooks: {
onAssistantMessageFinished: async (assistantMsg) => {
syncBatchContextFromTurnMessage(assistantMsg);
void ctx.refreshShippingActions();
if (noticeBatchSubmitting) {
return true;
}
noticeBatchSubmitting = true;
try {
const conversationKey = normalizeConversationId(ctx.conversationId.value);
const fileFingerprint = await computeNoticeFilesContentFingerprint(files);
if (pendingNoticeBatchRetry) {
reconcilePendingNoticeBatchConversation(pendingNoticeBatchRetry, conversationKey);
}
if (
pendingNoticeBatchRetry
&& pendingNoticeBatchRetry.fileFingerprint !== fileFingerprint
) {
clearPendingNoticeBatchRetryState();
}
if (!pendingNoticeBatchRetry) {
pendingNoticeBatchRetry = {
conversationId: conversationKey,
idempotencyKey: crypto.randomUUID(),
fileFingerprint,
};
} else {
pendingNoticeBatchRetry.fileFingerprint = fileFingerprint;
}
const idempotencyKey = pendingNoticeBatchRetry.idempotencyKey;
const turn = buildShippingCreateBatchTurn(files, ctx.conversationId.value, idempotencyKey);
const ok = await ctx.startChatTurn({
agentId: ctx.currentAgentId.value,
inputType: 'upload_followup',
displayText: turn.displayText,
actionType: turn.actionType,
payload: turn.payload,
files: turn.files,
hooks: {
onAssistantMessageFinished: async (assistantMsg) => {
syncBatchContextFromTurnMessage(assistantMsg);
void ctx.refreshShippingActions();
},
},
},
});
if (!ok) {
ctx.msg.warning(ctx.t('chat.shippingNoticeUploadFailed'));
});
if (ok) {
if (pendingNoticeBatchRetry?.conversationId === conversationKey) {
clearPendingNoticeBatchRetryState();
}
} else {
ctx.msg.warning(ctx.t('chat.shippingNoticeUploadFailed'));
}
return ok;
} finally {
noticeBatchSubmitting = false;
}
return ok;
};
const syncBatchContextFromNoticeResponse = (result: Record<string, unknown> | null | undefined) => {
@@ -196,6 +310,61 @@ export function createShippingUploadHandlers(ctx: ShippingUploadHandlerContext)
return ok;
};
const runNoticeBatchFromIntakes = async (intakeNos: string[]) => {
if (noticeBatchSubmitting) {
return true;
}
noticeBatchSubmitting = true;
try {
const conversationKey = normalizeConversationId(ctx.conversationId.value);
const intakeFingerprint = computeNoticeIntakeNosFingerprint(intakeNos);
if (pendingNoticeBatchRetry) {
reconcilePendingNoticeBatchConversation(pendingNoticeBatchRetry, conversationKey);
}
if (
pendingNoticeBatchRetry
&& pendingNoticeBatchRetry.fileFingerprint !== intakeFingerprint
) {
clearPendingNoticeBatchRetryState();
}
if (!pendingNoticeBatchRetry) {
pendingNoticeBatchRetry = {
conversationId: conversationKey,
idempotencyKey: crypto.randomUUID(),
fileFingerprint: intakeFingerprint,
};
} else {
pendingNoticeBatchRetry.fileFingerprint = intakeFingerprint;
}
const idempotencyKey = pendingNoticeBatchRetry.idempotencyKey;
const turn = buildShippingCreateBatchFromIntakesTurn(intakeNos, ctx.conversationId.value, idempotencyKey);
const ok = await ctx.startChatTurn({
agentId: ctx.currentAgentId.value,
inputType: 'upload_followup',
displayText: turn.displayText,
actionType: turn.actionType,
payload: turn.payload,
hooks: {
onAssistantMessageFinished: async (assistantMsg) => {
syncBatchContextFromTurnMessage(assistantMsg);
void ctx.refreshShippingActions();
},
},
});
if (ok) {
if (pendingNoticeBatchRetry?.conversationId === conversationKey) {
clearPendingNoticeBatchRetryState();
}
ctx.clearConsumedNoticeAttachments?.();
} else {
ctx.msg.warning(ctx.t('chat.shippingNoticeUploadFailed'));
}
return ok;
} finally {
noticeBatchSubmitting = false;
}
};
const handleReplaceNoticeForCurrentTask = async (taskId: string, file: File) => {
ctx.resolvedShippingTaskId.value = taskId;
await runReplaceNoticeChatTurn(taskId, file);
@@ -232,6 +401,11 @@ export function createShippingUploadHandlers(ctx: ShippingUploadHandlerContext)
const handleShippingAutoUploadNoticeBatch = async (files: File[]) => {
const noticeFiles = files.filter(Boolean);
const intakeNos = ctx.getParsedIntakeNos?.() || [];
if (!noticeFiles.length && intakeNos.length) {
await runNoticeBatchFromIntakes(intakeNos);
return;
}
if (!noticeFiles.length) return;
const pendingNoticeTaskId = String(ctx.pendingShippingNoticeTaskId.value || '').trim().toUpperCase();
ctx.pendingShippingNoticeTaskId.value = '';
@@ -317,5 +491,6 @@ export function createShippingUploadHandlers(ctx: ShippingUploadHandlerContext)
handleShippingInventorySelected,
shippingSuggestedPrompt,
useShippingSuggestedPrompt,
isShippingNoticeBatchSubmitting,
};
}
@@ -0,0 +1,372 @@
/**
* features/chat/shipping/useShippingNoticeIntakes.ts
* 用途:发货通知选择即上传、创建 intake 与批量状态轮询编排。
* 依赖:file-assets.api、shipping.api、shipping.types、shippingNoticeAttachmentIntegrity。
* 逻辑:useChatShipping / useChatAttachments 在货代 Agent 下委托本 composable 管理预解析附件;
* 完整性判定委托 shippingNoticeAttachmentIntegrity(与后端契约对齐)。
*/
import { computed, onBeforeUnmount, ref, type Ref } from 'vue';
import { uploadFileAsset } from '@/shared/api/file-assets.api';
import type {
PendingAttachment,
ShippingDuplicateAction,
ShippingDuplicateResult,
ShippingNoticeParseSummary,
ShippingNoticePendingAttachment,
} from '../types/shipping.types';
import type { ShippingNoticeIntakeResponse } from '../types/shipping.api.types';
import {
cancelShippingNoticeIntake,
createShippingNoticeIntake,
getShippingNoticeIntakeStatuses,
listActiveShippingNoticeIntakes,
resolveShippingNoticeDuplicate,
retryShippingNoticeIntake,
} from '@/features/chat/api/shipping.api';
import { isShippingNoticeAttachmentParseIncomplete } from './shippingNoticeAttachmentIntegrity';
export { isShippingNoticeAttachmentParseIncomplete } from './shippingNoticeAttachmentIntegrity';
const TERMINAL_PARSE = new Set(['parsed', 'failed', 'parse_failed', 'consumed', 'cancelled', 'expired']);
const ACTIVE_PARSE = new Set(['waiting', 'queued', 'parsing', 'created']);
function mapServerParseStatus(status: string): ShippingNoticePendingAttachment['parseStatus'] {
const normalized = String(status || '').trim().toLowerCase();
if (normalized === 'parsed') return 'parsed';
if (normalized === 'queued' || normalized === 'created') return 'queued';
if (normalized === 'parsing') return 'parsing';
if (normalized === 'parse_failed') return 'failed';
if (normalized === 'consumed') return 'consumed';
if (normalized === 'cancelled') return 'cancelled';
if (normalized === 'expired') return 'expired';
return 'waiting';
}
/**
* 将服务端 duplicate 结果映射为前端附件状态。
*/
function mapServerDuplicate(remote: ShippingNoticeIntakeResponse): {
duplicate?: ShippingDuplicateResult;
duplicateResolution?: ShippingNoticePendingAttachment['duplicateResolution'];
} {
const dup = remote.duplicate;
if (!dup) return {};
const duplicate: ShippingDuplicateResult = {
status: dup.status,
blocking: Boolean(dup.blocking),
fingerprintStrength: dup.fingerprint_strength,
matches: (dup.matches || []).map((item) => ({
taskNo: item.task_no,
processStatus: item.process_status,
documentVersion: Number(item.document_version || 1),
matchType: item.match_type,
matchedFields: listSafe(item.matched_fields),
createdAt: item.created_at,
})),
allowedActions: (dup.allowed_actions || []) as ShippingDuplicateAction[],
};
const resolution = remote.duplicate_resolution;
return {
duplicate,
duplicateResolution: resolution
? {
action: resolution.action,
targetTaskNo: resolution.target_task_no || undefined,
reason: resolution.reason || undefined,
}
: undefined,
};
}
function listSafe(value: unknown): string[] {
return Array.isArray(value) ? value.map((item) => String(item)) : [];
}
function createPendingAttachment(file: File): ShippingNoticePendingAttachment {
return {
id: `${Date.now()}_${Math.random().toString(36).slice(2, 8)}`,
kind: 'shipping_notice',
file,
type: 'document',
uploadStatus: 'waiting',
parseStatus: 'waiting',
uploadProgress: 0,
originalFilename: file.name,
fileSize: file.size,
};
}
export interface UseShippingNoticeIntakesOptions {
attachments: Ref<PendingAttachment[]>;
conversationId: Ref<string | null>;
msg: { warning: (text: string) => void };
t: (key: string, params?: Record<string, unknown>) => string;
}
export function useShippingNoticeIntakes(options: UseShippingNoticeIntakesOptions) {
const pollTimer = ref<ReturnType<typeof setTimeout> | null>(null);
const pollRound = ref(0);
const noticeAttachments = computed(() =>
options.attachments.value.filter(
(item): item is ShippingNoticePendingAttachment => item.kind === 'shipping_notice',
),
);
const hasBlockingUploadOrParse = computed(() =>
noticeAttachments.value.some((item) =>
item.uploadStatus === 'uploading'
|| item.uploadStatus === 'waiting'
|| ACTIVE_PARSE.has(item.parseStatus)
|| item.parseStatus === 'queued'
|| item.parseStatus === 'parsing',
),
);
const hasParseFailures = computed(() =>
noticeAttachments.value.some(
(item) =>
item.parseStatus === 'failed'
|| isShippingNoticeAttachmentParseIncomplete(item.parseSummary),
),
);
const allParsedReady = computed(() =>
noticeAttachments.value.length > 0
&& noticeAttachments.value.every(
(item) =>
item.parseStatus === 'parsed'
&& !isShippingNoticeAttachmentParseIncomplete(item.parseSummary),
),
);
const hasBlockingDuplicates = computed(() =>
noticeAttachments.value.some(
(item) => item.duplicate?.blocking && !item.duplicateResolution?.action,
),
);
const allReadyForConfirmation = computed(() =>
allParsedReady.value && !hasBlockingDuplicates.value && !hasParseFailures.value,
);
const stopPolling = () => {
if (pollTimer.value) {
clearTimeout(pollTimer.value);
pollTimer.value = null;
}
pollRound.value = 0;
};
const schedulePoll = () => {
stopPolling();
const intakeNos = noticeAttachments.value
.map((item) => item.intakeNo)
.filter((item): item is string => Boolean(item));
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;
}
const delayMs = pollRound.value >= 8 ? 5000 : 2000;
pollTimer.value = setTimeout(() => {
void refreshStatuses().finally(() => {
pollRound.value += 1;
schedulePoll();
});
}, delayMs);
};
const patchAttachment = (id: string, patch: Partial<ShippingNoticePendingAttachment>) => {
options.attachments.value = options.attachments.value.map((item) =>
item.id === id && item.kind === 'shipping_notice'
? { ...item, ...patch }
: item,
);
};
const refreshStatuses = async () => {
const intakeNos = noticeAttachments.value
.map((item) => item.intakeNo)
.filter((item): item is string => Boolean(item));
if (!intakeNos.length) return;
const { items } = await getShippingNoticeIntakeStatuses(intakeNos);
for (const remote of items) {
const local = noticeAttachments.value.find((item) => item.intakeNo === remote.intake_no);
if (!local) continue;
patchAttachment(local.id, {
parseStatus: mapServerParseStatus(remote.parse_status),
parseSummary: (remote.parse_summary || undefined) as ShippingNoticeParseSummary | undefined,
errorCode: remote.error_code || undefined,
errorMessage: remote.error_message || undefined,
expiresAt: remote.expires_at || undefined,
assetNo: remote.asset_no || local.assetNo,
...mapServerDuplicate(remote),
});
}
};
const processSingleFile = async (attachment: ShippingNoticePendingAttachment) => {
if (!attachment.file) return;
patchAttachment(attachment.id, { uploadStatus: 'uploading', uploadProgress: 10 });
try {
const asset = await uploadFileAsset(attachment.file);
patchAttachment(attachment.id, {
assetNo: asset.asset_no,
uploadStatus: 'uploaded',
uploadProgress: 100,
parseStatus: 'queued',
});
const intake = await createShippingNoticeIntake(
asset.asset_no,
options.conversationId.value,
);
patchAttachment(attachment.id, {
intakeNo: intake.intake_no,
parseStatus: mapServerParseStatus(intake.parse_status),
parseSummary: (intake.parse_summary || undefined) as ShippingNoticeParseSummary | undefined,
errorCode: intake.error_code || undefined,
errorMessage: intake.error_message || undefined,
expiresAt: intake.expires_at || undefined,
});
schedulePoll();
} catch (error) {
const message = error instanceof Error ? error.message : options.t('chat.shippingNoticeUploadFailed');
patchAttachment(attachment.id, {
uploadStatus: 'failed',
parseStatus: 'failed',
errorMessage: message,
});
options.msg.warning(message);
}
};
const enqueueNoticeFiles = async (files: File[]) => {
for (const file of files) {
const attachment = createPendingAttachment(file);
options.attachments.value = [...options.attachments.value, attachment];
await processSingleFile(attachment);
}
};
/**
* 移除待建单附件:先从 UI 删除,再取消后端未消费的 intake(含已 parsed)。
* @param id - 本地附件临时 ID
*/
const removeNoticeAttachment = async (id: string) => {
const target = noticeAttachments.value.find((item) => item.id === id);
options.attachments.value = options.attachments.value.filter((item) => item.id !== id);
// parsed 且未建单的 intake 也应取消,否则刷新后会经 listActive 再次出现
if (target?.intakeNo && target.parseStatus !== 'consumed') {
try {
await cancelShippingNoticeIntake(target.intakeNo);
} catch {
// 移除 UI 优先,取消失败由后端 TTL 兜底
}
}
if (!noticeAttachments.value.length) stopPolling();
};
const retryNoticeAttachment = async (id: string) => {
const target = noticeAttachments.value.find((item) => item.id === id);
if (!target?.intakeNo) return;
patchAttachment(id, { parseStatus: 'queued', errorCode: undefined, errorMessage: undefined });
const intake = await retryShippingNoticeIntake(target.intakeNo);
patchAttachment(id, {
parseStatus: mapServerParseStatus(intake.parse_status),
parseSummary: (intake.parse_summary || undefined) as ShippingNoticeParseSummary | undefined,
errorCode: intake.error_code || undefined,
errorMessage: intake.error_message || undefined,
});
schedulePoll();
};
const getParsedIntakeNos = () =>
noticeAttachments.value
.filter(
(item) =>
item.parseStatus === 'parsed'
&& item.intakeNo
&& !isShippingNoticeAttachmentParseIncomplete(item.parseSummary),
)
.map((item) => String(item.intakeNo));
const clearConsumedAttachments = () => {
options.attachments.value = options.attachments.value.filter((item) => item.kind !== 'shipping_notice');
stopPolling();
};
const restoreForConversation = async (conversationId?: string | null) => {
const { items } = await listActiveShippingNoticeIntakes(conversationId);
const restored: ShippingNoticePendingAttachment[] = items
.filter((item) => !TERMINAL_PARSE.has(String(item.parse_status || '').toLowerCase()) || item.parse_status === 'parsed')
.filter((item) => item.parse_status !== 'consumed')
.map((item) => ({
id: `restored_${item.intake_no}`,
kind: 'shipping_notice' as const,
type: 'document' as const,
assetNo: item.asset_no || undefined,
intakeNo: item.intake_no,
uploadStatus: 'uploaded' as const,
parseStatus: mapServerParseStatus(item.parse_status),
uploadProgress: 100,
originalFilename: item.original_filename || item.intake_no,
fileSize: Number(item.file_size || 0),
parseSummary: (item.parse_summary || undefined) as ShippingNoticeParseSummary | undefined,
errorCode: item.error_code || undefined,
errorMessage: item.error_message || undefined,
expiresAt: item.expires_at || undefined,
...mapServerDuplicate(item),
}));
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')) {
schedulePoll();
}
};
const resolveDuplicateAttachment = async (
id: string,
action: ShippingDuplicateAction,
targetTaskNo?: string,
reason?: string,
) => {
const target = noticeAttachments.value.find((item) => item.id === id);
if (!target?.intakeNo) return;
const intake = await resolveShippingNoticeDuplicate(
target.intakeNo,
action,
targetTaskNo,
reason,
);
patchAttachment(target.id, {
parseStatus: mapServerParseStatus(intake.parse_status),
...mapServerDuplicate(intake),
});
};
onBeforeUnmount(() => {
stopPolling();
});
return {
noticeAttachments,
hasBlockingUploadOrParse,
hasParseFailures,
allParsedReady,
hasBlockingDuplicates,
allReadyForConfirmation,
enqueueNoticeFiles,
removeNoticeAttachment,
retryNoticeAttachment,
resolveDuplicateAttachment,
getParsedIntakeNos,
clearConsumedAttachments,
restoreForConversation,
stopPolling,
};
}
export type ShippingNoticeIntakesApi = ReturnType<typeof useShippingNoticeIntakes>;
@@ -4,6 +4,42 @@
* 依赖:无(纯类型模块)。
* 逻辑:shipping.api.ts 与 Chat/工作台组件统一引用本文件 DTO 类型。
*/
export type InventorySourceStatus =
| 'unresolved'
| 'ambiguous'
| 'resolved'
| 'user_confirmed'
| 'invalid'
| 'conflicted';
export type InventorySourceMethod =
| 'rule_exact'
| 'rule_combined'
| 'user_confirmed'
| 'legacy_migrated';
export interface ShippingInventorySourceCandidate {
source_code: string;
display_name?: string | null;
site_id?: string | null;
warehouse_id?: string | null;
source_type?: string | null;
match_score?: number | null;
matched_by?: string | null;
}
export interface ShippingInventorySourceResolution {
status?: InventorySourceStatus | null;
method?: InventorySourceMethod | null;
reason?: string | null;
candidates?: ShippingInventorySourceCandidate[];
destination_candidates?: string[];
evidence?: Record<string, unknown>[];
conflicts?: string[];
config_version?: string | null;
routing_fingerprint?: string | null;
}
export interface ShippingInventorySnapshot {
inventory_file_no?: string | null;
source_code?: string | null;
@@ -48,11 +84,34 @@ export interface ShippingTaskSummary {
};
rpa_runtime?: ShippingRpaRuntime | null;
rpa_inventory_source?: Record<string, unknown> | null;
inventory_source_resolution?: Record<string, unknown> | null;
inventory_source_resolution?: ShippingInventorySourceResolution | null;
destination_code?: string | null;
destination_city?: string | null;
destination_country?: string | null;
warehouse_hint?: string | null;
inventory_source_code?: string | null;
inventory_source_type?: string | null;
inventory_site_id?: string | null;
inventory_warehouse_id?: string | null;
inventory_source_status?: InventorySourceStatus | null;
inventory_source_method?: InventorySourceMethod | null;
inventory_source_config_version?: string | null;
inventory_routing_fingerprint?: string | null;
inventory_source_confirmed_at?: string | null;
inventory_source_confirmed_by?: number | null;
inventory_snapshot?: ShippingInventorySnapshot | null;
created_at?: string | null;
updated_at?: string | null;
ui_state?: ShippingTaskUiState;
/** 业务版本号;修订建单时递增 */
document_version?: number;
supersedes_task_no?: string | null;
superseded_by_task_no?: string | null;
duplicate_source_task_no?: string | null;
duplicate_resolution_type?: string | null;
duplicate_override_reason?: string | null;
business_fingerprint?: string | null;
fingerprint_version?: string | null;
}
export interface ShippingTaskEvent {
@@ -155,6 +214,8 @@ export interface ShippingTaskUiState {
title?: string | null;
message?: string | null;
error_message?: string | null;
/** 文件解析阶段汇总的全部待处理问题(库存源 + 解析 warnings 等) */
issues?: string[] | null;
};
action_buttons: ShippingChatAction[];
updated_at?: string | null;
@@ -222,12 +283,28 @@ export interface ShippingTaskCreateResponse {
data?: Record<string, unknown>;
}
export interface ShippingNoticeFileSummary {
total_files: number;
accepted_count: number;
rejected_count: number;
duplicate_count: number;
accepted_files?: Array<Record<string, unknown>>;
rejected_files?: Array<Record<string, unknown>>;
duplicate_files?: Array<{
filename: string;
duplicate_of: string;
content_hash?: string;
}>;
}
export interface ShippingNoticeUploadResponse {
status: string;
message?: string;
task_id?: string;
batch_no?: string;
checkpoint?: string;
idempotent_replay?: boolean;
file_summary?: ShippingNoticeFileSummary;
data?: Record<string, unknown> & {
batch?: ShippingBatchSummary;
focus_task?: ShippingTaskSummary | null;
@@ -237,6 +314,69 @@ export interface ShippingNoticeUploadResponse {
human_options?: string[];
}
export interface ShippingNoticeIntakeResponse {
intake_no: string;
asset_no?: string | null;
conversation_id?: string | null;
parse_status: string;
parser_version?: string;
parse_summary?: Record<string, unknown> | null;
business_summary?: Record<string, unknown> | null;
business_fingerprint?: string | null;
fingerprint_strength?: ShippingDuplicateFingerprintStrength | null;
fingerprint_version?: string | null;
duplicate?: ShippingDuplicateResult | null;
duplicate_resolution?: {
action: ShippingDuplicateAction;
reason?: string | null;
resolved_by_id?: number | null;
resolved_at?: string | null;
target_task_no?: string | null;
} | null;
warnings?: string[];
error_code?: string | null;
error_message?: string | null;
expires_at?: string | null;
consumed_at?: string | null;
created_at?: string | null;
updated_at?: string | null;
original_filename?: string;
file_size?: number;
content_hash?: string;
}
export type ShippingDuplicateStatus =
| 'unchecked'
| 'none'
| 'exact_file'
| 'same_active_task'
| 'same_completed_task'
| 'possible_duplicate';
export type ShippingDuplicateAction = 'open_existing' | 'create_revision' | 'force_create';
export type ShippingDuplicateFingerprintStrength = 'strong' | 'medium' | 'weak' | 'unavailable';
export interface ShippingDuplicateMatch {
task_no: string;
process_status: string;
document_version: number;
match_type: string;
matched_fields: string[];
lifecycle?: string;
created_at?: string;
}
export interface ShippingDuplicateResult {
status: ShippingDuplicateStatus;
blocking: boolean;
fingerprint_strength: ShippingDuplicateFingerprintStrength;
matches: ShippingDuplicateMatch[];
allowed_actions: ShippingDuplicateAction[];
}
export interface ShippingCreateBatchFromIntakesResponse extends ShippingNoticeUploadResponse {}
export interface ShippingDecisionResponse {
status: string;
message?: string;
@@ -11,10 +11,120 @@ export type ShippingMenuAction = 'upload' | 'paste' | 'retry_rpa' | 'confirm' |
export type ChatUploadFileType = 'image' | 'document' | 'audio' | 'video' | 'custom';
/** 待发送附件(本地文件或远程 URL) */
export type ShippingNoticeUploadStatus = 'waiting' | 'uploading' | 'uploaded' | 'failed';
export type ShippingNoticeParseStatus =
| 'waiting'
| 'queued'
| 'parsing'
| 'parsed'
| 'failed'
| 'consumed'
| 'cancelled'
| 'expired';
export type ShippingDuplicateAction = 'open_existing' | 'create_revision' | 'force_create';
export type ShippingDuplicateFingerprintStrength = 'strong' | 'medium' | 'weak' | 'unavailable';
export type ShippingDuplicateStatus =
| 'unchecked'
| 'none'
| 'exact_file'
| 'same_active_task'
| 'same_completed_task'
| 'possible_duplicate';
export interface ShippingDuplicateMatch {
taskNo: string;
processStatus: string;
documentVersion: number;
matchType: string;
matchedFields: string[];
createdAt?: string;
}
export interface ShippingDuplicateResult {
status: ShippingDuplicateStatus;
blocking: boolean;
fingerprintStrength: ShippingDuplicateFingerprintStrength;
matches: ShippingDuplicateMatch[];
allowedActions: ShippingDuplicateAction[];
}
export interface ShippingDuplicateResolution {
action: ShippingDuplicateAction;
targetTaskNo?: string;
reason?: string;
}
export interface ShippingNoticeParseAttachmentSummary {
attachment_key?: string;
filename?: string;
mime_type?: string;
size?: number;
content_hash?: string;
parse_status?: string;
/** 详情接口才有;状态轮询为瘦身摘要不含全文 */
extracted_text?: string;
/** 原始解析文本长度 */
text_length?: number;
/** 落库/截断后长度 */
stored_text_length?: number;
warnings?: string[];
}
export interface ShippingNoticeParseEmailMeta {
message_id?: string;
subject?: string;
from?: string;
to?: string;
date?: string;
/** 详情接口才有完整正文;状态轮询通常省略 */
body_text?: string;
body_text_length?: number;
stored_body_text_length?: number;
}
export interface ShippingNoticeParseSummary {
filename?: string;
source_type?: string;
text_length?: number;
line_count?: number;
warnings?: string[];
parser_version?: string;
email?: ShippingNoticeParseEmailMeta;
/** 发现的真实附件总数(含因上限未登记的) */
attachment_count?: number;
/** 实际登记到 attachments[] 的数量 */
attachment_registered_count?: number;
attachments?: ShippingNoticeParseAttachmentSummary[];
}
export type ShippingNoticePendingAttachment = {
id: string;
kind: 'shipping_notice';
file?: File;
type: 'document';
assetNo?: string;
intakeNo?: string;
uploadStatus: ShippingNoticeUploadStatus;
parseStatus: ShippingNoticeParseStatus;
uploadProgress: number;
originalFilename: string;
fileSize: number;
parseSummary?: ShippingNoticeParseSummary;
errorCode?: string;
errorMessage?: string;
expiresAt?: string;
duplicate?: ShippingDuplicateResult;
duplicateResolution?: ShippingDuplicateResolution;
};
/** 待发送附件(本地文件、远程 URL 或货代通知预解析) */
export type PendingAttachment =
| { id: string; kind: 'local'; file: File; type: ChatUploadFileType }
| { id: string; kind: 'remote'; url: string; type: ChatUploadFileType };
| { id: string; kind: 'remote'; url: string; type: ChatUploadFileType }
| ShippingNoticePendingAttachment;
export type ChatUploadFileSpec =
| { type: ChatUploadFileType; transfer_method: 'local_file'; upload_file_id: string }
@@ -141,6 +141,31 @@ const inventorySnapshotLabel = (triggerType?: string | null) => {
return map[key] || map.on_demand;
};
const inventorySourceStatusLabel = (status?: string | null) => {
const key = String(status || '').trim();
if (!key) return '—';
const i18nKey = `workspace.shippingNotice.inventorySource.statusLabels.${key}`;
return te(i18nKey) ? t(i18nKey) : key;
};
const inventorySourceMethodLabel = (method?: string | null) => {
const key = String(method || '').trim();
if (!key) return '—';
const i18nKey = `workspace.shippingNotice.inventorySource.methodLabels.${key}`;
return te(i18nKey) ? t(i18nKey) : key;
};
const hasInventorySourceFields = computed(() => {
const item = detail.value;
if (!item) return false;
return !!(
item.inventory_source_code
|| item.inventory_site_id
|| item.inventory_warehouse_id
|| item.inventory_source_status
);
});
const loadCases = async () => {
loading.value = true;
try {
@@ -388,6 +413,45 @@ onMounted(async () => {
<div><dt class="text-muted">{{ $t('workspace.shippingNotice.fields.freightRef') }}</dt><dd>{{ detail.freight_ref_no || '—' }}</dd></div>
</dl>
<div
v-if="hasInventorySourceFields"
class="rounded-2xl border border-default/80 bg-surface px-4 py-3 text-sm"
>
<h3 class="mb-2 text-sm font-semibold text-secondary">
{{ $t('workspace.shippingNotice.inventorySource.title') }}
</h3>
<dl class="grid gap-2 sm:grid-cols-2">
<div>
<dt class="text-xs text-muted">{{ $t('workspace.shippingNotice.inventorySource.sourceCode') }}</dt>
<dd class="font-mono">{{ detail.inventory_source_code || '—' }}</dd>
</div>
<div>
<dt class="text-xs text-muted">{{ $t('workspace.shippingNotice.inventorySource.status') }}</dt>
<dd>{{ inventorySourceStatusLabel(detail.inventory_source_status) }}</dd>
</div>
<div>
<dt class="text-xs text-muted">{{ $t('workspace.shippingNotice.inventorySource.siteId') }}</dt>
<dd class="font-mono">{{ detail.inventory_site_id || '—' }}</dd>
</div>
<div>
<dt class="text-xs text-muted">{{ $t('workspace.shippingNotice.inventorySource.warehouseId') }}</dt>
<dd class="font-mono">{{ detail.inventory_warehouse_id || '—' }}</dd>
</div>
<div>
<dt class="text-xs text-muted">{{ $t('workspace.shippingNotice.inventorySource.method') }}</dt>
<dd>{{ inventorySourceMethodLabel(detail.inventory_source_method) }}</dd>
</div>
<div>
<dt class="text-xs text-muted">{{ $t('workspace.shippingNotice.inventorySource.configVersion') }}</dt>
<dd class="font-mono text-xs">{{ detail.inventory_source_config_version || '—' }}</dd>
</div>
<div>
<dt class="text-xs text-muted">{{ $t('workspace.shippingNotice.inventorySource.confirmedBy') }}</dt>
<dd class="font-mono">{{ detail.inventory_source_confirmed_by ?? '—' }}</dd>
</div>
</dl>
</div>
<div
v-if="detail.inventory_snapshot"
class="rounded-2xl border border-default/80 bg-surface px-4 py-3 text-sm"