feat(in-transit-transfer): 实现在途仓自动调拨Agent一期完整功能

包含后端服务层、任务处理器与消费Worker、前端聊天组件、数据库模型与迁移脚本、测试用例,同时新增外部系统连接器框架基础能力并更新相关文档。
This commit is contained in:
hugo committed 2026-08-28 17:16:06 +08:00
1 parent f3050164d0
commit 6b53b563e7
177 files changed
+17260 -36

No files matched your search

@@ -7,6 +7,7 @@ import type { Ref } from 'vue';
import ChatWelcomePanel, { type WelcomeQuestionItem, type WelcomeQuestionSection } from './ChatWelcomePanel.vue';
import ChatThinkingBubble from './ChatThinkingBubble.vue';
import ChatMessageBubble, { type ChatMessageBubbleHandlers } from './messages/ChatMessageBubble.vue';
import TransferHomePanel from './messages/TransferHomePanel.vue';
import ToolRunProgressCard from './ToolRunProgressCard.vue';
import type { LeaveMessageHandlers } from './messages/LeaveMessageBlock.vue';
import type { ShippingMessageHandlers } from './messages/shippingMessageHandlers';
@@ -45,6 +46,8 @@ const {
toolRunProgressTitle: string;
showScrollToBottom: boolean;
hideWelcomePanel?: boolean;
/** 在途仓自动调拨 Agent:无消息时渲染专属首页入口区(替代通用欢迎面板)。 */
isInTransitTransferAgent?: boolean;
pinMessagesToBottom?: boolean;
/** 供父级滚动逻辑绑定 main 元素 */
scrollContainerHolder: { el: Ref<HTMLElement | null> };
@@ -63,6 +66,8 @@ const emit = defineEmits<{
'maintenance-view-record-history': [device: MaintenanceDevice];
'maintenance-create-record-for-device': [device: MaintenanceDevice];
'open-batch-workbench': [];
/** 在途仓自动调拨:业务流激活时向上冒泡,父级据此隐藏聊天输入框。 */
'transfer-flow-active': [active: boolean];
}>();
const bindScrollContainer = (node: unknown) => {
@@ -144,7 +149,7 @@ const isLatestAssistantMessage = (items: ChatMessage[], index: number) => {
>
<div :class="messages.length === 0 ? 'h-full' : pinMessagesToBottom === false ? 'min-h-full' : 'flex min-h-full flex-col justify-end'">
<ChatWelcomePanel
v-if="messages.length === 0 && !hideWelcomePanel"
v-if="messages.length === 0 && !hideWelcomePanel && !isInTransitTransferAgent"
:agent-name="agentName"
:suggested-questions-style="suggestedQuestionsStyle"
:styled-sections="styledSections"
@@ -153,6 +158,12 @@ const isLatestAssistantMessage = (items: ChatMessage[], index: number) => {
@select-question="emit('select-question', $event)"
/>
<TransferHomePanel
v-if="messages.length === 0 && !hideWelcomePanel && isInTransitTransferAgent"
:agent-name="agentName"
@flow-active="emit('transfer-flow-active', $event)"
/>
<template v-for="(msg, index) in messages" :key="getMessageKey(msg, index)">
<ChatMessageBubble
v-if="shouldRenderMessage(msg) && !isDuplicateShippingExtractionMessage(messages, index)"
@@ -44,7 +44,7 @@ import { useChatPageContext } from '@/features/chat/composables/chat.context';
import { matchesTrainingAgent } from '@/features/chat/training/trainingWorkspace.utils';
import { agentHasIntentUiProfile } from '@/shared/utils/agent-registry.utils';
import { agentHasIntentUiProfile, resolveAgentCode, AGENT_CODE_IN_TRANSIT_TRANSFER } from '@/shared/utils/agent-registry.utils';
import {
SHIPPING_WORKFLOW_KEY,
@@ -111,6 +111,13 @@ const isTrainingAgentPage = computed(() => matchesTrainingAgent(page.currentAgen
const isMaintenanceAgentPage = computed(() => agentHasIntentUiProfile(page.currentAgent, 'maintenance'));
/** 在途仓自动调拨 Agent:无消息时展示专属首页入口区(决策:补 Chat 首页入口 A 方案)。 */
const isInTransitTransferAgent = computed(() => resolveAgentCode(page.currentAgent) === AGENT_CODE_IN_TRANSIT_TRANSFER);
/** 在途仓自动调拨业务流激活(来源选择/待处理等子视图)时隐藏聊天输入框,模拟业务页。 */
const transferFlowActive = ref(false);
watch(isInTransitTransferAgent, (isTransfer) => { if (!isTransfer) transferFlowActive.value = false; });
/** 批次进度工作台按需打开;关闭时不占用对话区右侧布局。 */
const batchWorkbenchOpen = ref(false);
@@ -542,6 +549,8 @@ watch(() => page.currentAgentId, () => {
:hide-welcome-title="hideWelcomeTitle"
:is-in-transit-transfer-agent="isInTransitTransferAgent"
:pin-messages-to-bottom="!isTrainingAgentPage"
:scroll-container-holder="page.scrollContainerHolder"
@@ -570,13 +579,15 @@ watch(() => page.currentAgentId, () => {
@open-batch-workbench="openBatchWorkbench"
@transfer-flow-active="transferFlowActive = $event"
/>
<ChatInputBar
v-show="!isTrainingWorkspaceExpanded"
v-show="!isTrainingWorkspaceExpanded && !transferFlowActive"
:key="`${page.currentAgentId}-${page.conversationId || 'draft'}-${page.messages.length}`"
@@ -14,6 +14,7 @@ import LeaveMessageBlock, { type LeaveMessageHandlers } from './LeaveMessageBloc
import ChatMessageAttachmentList from './ChatMessageAttachmentList.vue';
import MaintenanceDeviceResultCard from './MaintenanceDeviceResultCard.vue';
import ContractReviewResultCard from './ContractReviewResultCard.vue';
import TransferMessageView from './TransferMessageView.vue';
import ShippingMatchResultCard from './ShippingMatchResultCard.vue';
import ShippingParseReviewMessage, { type ShippingParseReviewHandlers } from './ShippingParseReviewMessage.vue';
import type { ShippingMessageHandlers } from './shippingMessageHandlers';
@@ -94,6 +95,12 @@ const RESTRICTED_INLINE_DOWNLOAD_FILE_NAME = '资产明细全量导出表.csv';
/** 合同审查结果卡:自身已是完整卡片,外层只需透明容器。 */
const isContractReviewMessage = computed(() => message.type === 'procurement-contract-review');
const isTransferMessage = computed(
() =>
message.type === 'transfer-precheck'
|| message.type === 'transfer-progress'
|| message.type === 'transfer-result',
);
const isLeaveMessage = computed(() =>
message.type === 'leave-form'
@@ -770,6 +777,10 @@ function handleInlineDownload(file: InlineDownloadFile): void {
v-else-if="message.type === 'procurement-contract-review'"
:message="message"
/>
<TransferMessageView
v-else-if="isTransferMessage"
:payload="(message.payload as Record<string, unknown> | undefined)"
/>
<TrainingExamQuestionMessage
v-else-if="isTrainingExamMessage && trainingHandlers.getQuestion()"
:question="trainingHandlers.getQuestion()!"
@@ -0,0 +1,90 @@
<!--
features/chat/components/messages/TransferBacklogSummaryCard.vue
用途:待处理异常卡(可恢复/已关闭/结果未知三组)+ 人工重试/人工关闭入口。
依赖:props.items、i18n chat.transfer.*。
逻辑:result_unknown 只读(无重试/关闭按钮);人工关闭由父组件弹窗处理。
-->
<script setup lang="ts">
import type { TransferBacklogItem } from '../../types/transfer.types';
defineProps<{
items: TransferBacklogItem[];
}>();
const emit = defineEmits<{
retry: [itemId: number];
close: [item: TransferBacklogItem];
refresh: [];
}>();
function agingLabel(level: string): string {
const map: Record<string, string> = {
warn_3d: 'chat.transfer.agingWarn',
escalate_5d: 'chat.transfer.agingEscalate',
critical_7d: 'chat.transfer.agingCritical',
result_unknown: 'chat.transfer.resultUnknown',
closed: 'chat.transfer.statusClosed',
};
return map[level] ?? 'chat.transfer.agingNormal';
}
</script>
<template>
<div class="my-2 rounded-2xl border border-brand-100 bg-white p-4 shadow-sm" data-testid="transfer-backlog-card">
<div class="mb-2 flex items-center justify-between">
<h3 class="text-sm font-bold text-slate-800">{{ $t('chat.transfer.backlogTitle') }}</h3>
<button
type="button"
class="rounded-lg border border-slate-200 px-2 py-1 text-xs text-slate-600 hover:bg-slate-50"
data-testid="transfer-backlog-refresh"
@click="emit('refresh')"
>
{{ $t('chat.transfer.refreshProgress') }}
</button>
</div>
<ul v-if="items.length" class="flex flex-col gap-1.5">
<li
v-for="item in items"
:key="item.item_id"
class="flex items-center justify-between gap-2 rounded-lg border border-slate-100 px-3 py-2 text-xs"
:data-testid="`transfer-backlog-${item.invoice_no}`"
>
<div class="min-w-0">
<div class="font-semibold text-slate-700">
{{ item.invoice_no }}
<span class="ml-1 text-slate-400">{{ item.source_code }}</span>
</div>
<div class="text-[11px] text-slate-500">
{{ item.reason }} · {{ $t(agingLabel(item.aging_level)) }}
</div>
</div>
<div class="flex shrink-0 gap-1.5">
<template v-if="item.status === 'blocked_recoverable'">
<button
type="button"
class="rounded-lg border border-brand-200 px-2 py-1 font-bold text-brand-700 hover:bg-brand-50"
data-testid="transfer-backlog-retry"
@click="emit('retry', item.item_id)"
>
{{ $t('chat.transfer.retryErp') }}
</button>
<button
type="button"
class="rounded-lg border border-red-200 px-2 py-1 font-bold text-red-600 hover:bg-red-50"
data-testid="transfer-backlog-close"
@click="emit('close', item)"
>
{{ $t('chat.transfer.manualClose') }}
</button>
</template>
<span v-else-if="item.status === 'result_unknown'" class="text-[11px] text-slate-400">
{{ $t('chat.transfer.resultUnknownReadonly') }}
</span>
</div>
</li>
</ul>
<div v-else class="rounded-lg bg-slate-50 p-3 text-xs text-slate-500">
{{ $t('chat.transfer.noBacklog') }}
</div>
</div>
</template>
@@ -0,0 +1,50 @@
<!--
features/chat/components/messages/TransferFileProgressCard.vue
用途:来源实例级收料文件准备进度(决策 18:来源隔离展示,不伪造总百分比)。
依赖:props.sources、i18n chat.transfer.*。
逻辑:按来源显示 file_ready / waiting_rpa_callback / failed 阶段与文件信息。
-->
<script setup lang="ts">
import type { TransferSourceProgress } from '../../types/transfer.types';
defineProps<{
sources: TransferSourceProgress[];
}>();
</script>
<template>
<div
class="my-2 rounded-2xl border border-brand-100 bg-white p-4 shadow-sm"
data-testid="transfer-file-progress-card"
>
<h3 class="mb-3 text-sm font-bold text-slate-800">{{ $t('chat.transfer.fileProgressTitle') }}</h3>
<ul class="flex flex-col gap-2">
<li
v-for="source in sources"
:key="source.source_code"
class="flex items-center justify-between rounded-lg border border-slate-100 px-3 py-2"
:data-testid="`transfer-source-${source.source_code}`"
>
<div class="min-w-0">
<div class="text-sm font-semibold text-slate-700">{{ source.source_code }}</div>
<div v-if="source.file_no" class="truncate text-xs text-slate-400">
{{ source.file_no }}<template v-if="source.file_version"> · v{{ source.file_version }}</template>
</div>
<div v-else-if="source.error_message" class="truncate text-xs text-red-500">{{ source.error_message }}</div>
</div>
<span
class="shrink-0 rounded-full px-2 py-0.5 text-xs font-bold"
:class="{
'bg-emerald-50 text-emerald-700': source.stage === 'file_ready',
'bg-amber-50 text-amber-700': source.stage === 'waiting_rpa_callback',
'bg-red-50 text-red-700': source.stage === 'failed',
}"
>
<template v-if="source.stage === 'file_ready'">{{ $t('chat.transfer.stageFileReady') }}</template>
<template v-else-if="source.stage === 'waiting_rpa_callback'">{{ $t('chat.transfer.stageWaitingRpa') }}</template>
<template v-else>{{ $t('chat.transfer.stageFailed') }}</template>
</span>
</li>
</ul>
</div>
</template>
@@ -0,0 +1,131 @@
/**
* features/chat/components/messages/TransferHomePanel.spec.ts
* 用途:验证在途仓自动调拨 Agent 的 Chat 首页入口区——
* home 视图渲染“今日待办 + 历史待办”计数卡;点击入口独立触发
* source-select / backlog 卡片(复用自驱动的 TransferMessageView,不注入消息流)。
* 依赖:vi.mock(transfer.api)、@vue/test-utils、i18n。
* 逻辑:Mock API 断言入口切换与计数展示;对应后端 backlog/summary 契约面。
*/
import { mount, flushPromises } from '@vue/test-utils';
import { describe, expect, it, vi, beforeEach } from 'vitest';
import i18n from '@/i18n';
const api = vi.hoisted(() => ({
createTransferPrecheck: vi.fn(),
getTransferPrecheck: vi.fn(),
executeTransferPrecheck: vi.fn(),
getTransferRun: vi.fn(),
retryTransferItem: vi.fn(),
manualCloseTransferItem: vi.fn(),
downloadTransferReceiptFiles: vi.fn(),
downloadTransferErpInventory: vi.fn(),
downloadTransferExceptions: vi.fn(),
listTransferBacklog: vi.fn(),
getTransferBacklogSummary: vi.fn(),
listTransferSources: vi.fn(),
}));
vi.mock('@/features/chat/api/transfer.api', () => api);
import TransferHomePanel from './TransferHomePanel.vue';
function mountHome() {
return mount(TransferHomePanel, {
props: { agentName: '在途仓自动调拨' },
global: { plugins: [i18n] },
});
}
describe('TransferHomePanel chat home entry', () => {
beforeEach(() => {
vi.clearAllMocks();
api.getTransferBacklogSummary.mockResolvedValue({
recoverable: 6, closed: 2, unknown: 1, aging: { warn_3d: 3, escalate_5d: 2, critical_7d: 1 },
});
api.listTransferBacklog.mockResolvedValue([]);
api.listTransferSources.mockResolvedValue([
{ source_code: 'DBS-AWSBI', display_name: 'AWSBI', platform: 'dbs', enabled: true, has_ready_file: true, file_status: 'ready' },
]);
});
it('home 视图渲染标题、今日待办入口与三张历史待办计数卡', async () => {
const wrapper = mountHome();
await flushPromises();
expect(wrapper.find('[data-testid="transfer-home"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="transfer-home-today"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="transfer-home-recoverable"]').text()).toContain('6');
expect(wrapper.find('[data-testid="transfer-home-closed"]').text()).toContain('2');
expect(wrapper.find('[data-testid="transfer-home-unknown"]').text()).toContain('1');
expect(api.getTransferBacklogSummary).toHaveBeenCalled();
});
it('点击“发起今日调拨预检”独立触发来源选择卡(复用 TransferMessageView)', async () => {
api.createTransferPrecheck.mockResolvedValue({
precheck_id: 'TPC-1', status: 'ready_to_execute', business_date: '2026-08-06',
eligible_receipt_date_to: '2026-08-05', expires_at: '',
counts: { file_invoice_count: 1, not_matured_count: 0, prechecked_count: 1, executable_count: 1, blocked_count: 0 },
estimated_transfer_quantity: '1200', estimated_erp_write_count: 1, precheck_hash: 'sha256:x',
});
api.getTransferPrecheck.mockResolvedValue({
summary: {
precheck_id: 'TPC-1', status: 'ready_to_execute', business_date: '2026-08-06',
eligible_receipt_date_to: '2026-08-05', expires_at: '',
counts: { file_invoice_count: 1, not_matured_count: 0, prechecked_count: 1, executable_count: 1, blocked_count: 0 },
estimated_transfer_quantity: '1200', estimated_erp_write_count: 1, precheck_hash: 'sha256:x',
},
items: [{
source_code: 'DBS-AWSBI', material_no: 'MAT-1', material_name: '连接器组件', specification: 'A',
invoice_no: 'INV-001', from_warehouse: 'DBS-TRANSIT', from_quantity: '1200',
to_warehouse: 'HUB-CN01', to_quantity: '1200', result: 'executable',
}],
sources: [{ source_code: 'DBS-AWSBI', stage: 'file_ready', file_no: 'REC-1' }],
});
const wrapper = mountHome();
await flushPromises();
await wrapper.find('[data-testid="transfer-home-today"]').trigger('click');
await flushPromises();
expect(wrapper.find('[data-testid="transfer-source-select-card"]').exists()).toBe(true);
expect(api.listTransferSources).toHaveBeenCalled();
});
it('点击历史待办计数卡独立触发 backlog 卡片', async () => {
api.listTransferBacklog.mockResolvedValue([
{ item_id: 7, source_code: 'DBS-AWSBI', invoice_no: 'INV-001', material_no: 'MAT-1',
status: 'blocked_recoverable', reason: '收料 1200 / ERP 1000', age_days: 1, aging_level: 'normal' },
]);
const wrapper = mountHome();
await flushPromises();
await wrapper.find('[data-testid="transfer-home-recoverable"]').trigger('click');
await flushPromises();
expect(wrapper.find('[data-testid="transfer-backlog-card"]').exists()).toBe(true);
expect(api.listTransferBacklog).toHaveBeenCalled();
});
it('子视图提供“返回首页”并切回 home', async () => {
const wrapper = mountHome();
await flushPromises();
await wrapper.find('[data-testid="transfer-home-today"]').trigger('click');
await flushPromises();
expect(wrapper.find('[data-testid="transfer-source-select-card"]').exists()).toBe(true);
await wrapper.find('[data-testid="transfer-home-back"]').trigger('click');
await flushPromises();
expect(wrapper.find('[data-testid="transfer-home"]').exists()).toBe(true);
});
it('进入子流程时冒泡 flow-active=true,返回首页时 false(父级据此隐藏聊天输入框)', async () => {
const wrapper = mountHome();
await flushPromises();
expect(wrapper.emitted('flow-active')?.[0]?.[0]).toBe(false);
await wrapper.find('[data-testid="transfer-home-today"]').trigger('click');
await flushPromises();
expect(wrapper.emitted('flow-active')?.at(-1)?.[0]).toBe(true);
await wrapper.find('[data-testid="transfer-home-back"]').trigger('click');
await flushPromises();
expect(wrapper.emitted('flow-active')?.at(-1)?.[0]).toBe(false);
});
});
@@ -0,0 +1,134 @@
<!--
features/chat/components/messages/TransferHomePanel.vue
用途:在途仓自动调拨 Agent 的 Chat 首页入口区——home 视图展示标题、今日待办
入口与三张历史待办计数卡;点击入口独立触发 source-select / backlog 卡片。
依赖:TransferMessageView(复用自驱动卡片)、useChatTransfer、i18n chat.transfer.*。
逻辑:home 时只消费 backlogSummary 计数;非 home 时渲染 TransferMessageView。
卡片不注入消息流,因此无需后端 ChatLog 消息(决策:补首页入口 A 方案)。
-->
<script setup lang="ts">
import { computed, onMounted, ref, watch } from 'vue';
import TransferMessageView from './TransferMessageView.vue';
import { useChatTransfer } from '../../composables/useChatTransfer';
const props = defineProps<{
agentName?: string;
}>();
const emit = defineEmits<{
/** 业务流激活状态:true 表示进入来源选择/待处理等子视图(父级据此隐藏聊天输入框)。 */
'flow-active': [active: boolean];
}>();
type HomeView = 'home' | 'source-select' | 'backlog';
const transfer = useChatTransfer();
const view = ref<HomeView>('home');
/** 进入非 home 时通知父级隐藏聊天输入框(决策:来源选择为业务页,无对话输入区)。 */
watch(view, (value) => emit('flow-active', value !== 'home'), { immediate: true });
/** home 视图仅需要待办汇总;进入时拉取计数。 */
async function loadHomeSummary() {
if (view.value !== 'home') return;
await transfer.loadBacklog();
}
onMounted(() => { void loadHomeSummary(); });
watch(view, () => { void loadHomeSummary(); });
const displayAgentName = computed(() => props.agentName || '在途仓自动调拨');
/** 非 home 视图把当前入口透传给自驱动的 TransferMessageView(决定 source-select 或 backlog)。 */
const childPayload = computed(() => (
view.value === 'source-select'
? { kind: 'source-select' }
: { kind: 'backlog' }
));
function goBack() {
view.value = 'home';
}
</script>
<template>
<div class="flex w-full flex-col items-center px-4 pb-2 pt-6 md:pb-4">
<!-- home:标题 + 今日/历史待办入口 -->
<template v-if="view === 'home'">
<h2 data-testid="transfer-home" class="mb-8 mt-6 shrink-0 text-center text-2xl font-bold text-primary md:mt-10 md:text-3xl">
{{ $t('chat.transfer.homeWelcome') }}
<span class="mx-1 text-brand-600">{{ displayAgentName }}</span>
</h2>
<div class="w-full max-w-3xl space-y-4">
<!-- 今日待办 -->
<section aria-label="今日待办">
<p class="mb-2 text-sm font-bold text-secondary">{{ $t('chat.transfer.homeTodayLabel') }}</p>
<button
type="button"
data-testid="transfer-home-today"
class="flex w-full items-center gap-3 rounded-2xl border border-brand-200 bg-brand-50 p-4 text-left transition-colors hover:bg-brand-100"
@click="view = 'source-select'"
>
<span class="grid h-10 w-10 shrink-0 place-items-center rounded-xl bg-brand-600 text-lg font-bold text-white">+</span>
<span class="min-w-0 flex-1">
<b class="block text-sm font-bold text-brand-700">{{ $t('chat.transfer.homeTodayAction') }}</b>
<span class="mt-1 block text-xs text-brand-600/80">{{ $t('chat.transfer.homeTodayHint') }}</span>
</span>
<span class="shrink-0 text-xl text-brand-600">›</span>
</button>
</section>
<!-- 历史待办 -->
<section aria-label="历史待办">
<p class="mb-2 text-sm font-bold text-secondary">{{ $t('chat.transfer.homeHistoryLabel') }}</p>
<div class="grid grid-cols-1 gap-3 sm:grid-cols-3">
<button
type="button"
data-testid="transfer-home-recoverable"
class="rounded-2xl border border-brand-200 bg-brand-50 p-4 text-left transition-colors hover:bg-brand-100"
@click="view = 'backlog'"
>
<b class="block text-2xl leading-none text-brand-600">{{ transfer.backlogSummary.value?.recoverable ?? 0 }}</b>
<b class="mt-2 block text-sm font-bold text-primary">{{ $t('chat.transfer.homeRecoverable') }}</b>
<span class="mt-1 block text-xs text-secondary">{{ $t('chat.transfer.homeRecoverableHint') }}</span>
</button>
<button
type="button"
data-testid="transfer-home-closed"
class="rounded-2xl border border-slate-200 bg-surface p-4 text-left transition-colors hover:border-brand-200 hover:bg-brand-50"
@click="view = 'backlog'"
>
<b class="block text-2xl leading-none text-slate-600">{{ transfer.backlogSummary.value?.closed ?? 0 }}</b>
<b class="mt-2 block text-sm font-bold text-primary">{{ $t('chat.transfer.homeClosed') }}</b>
<span class="mt-1 block text-xs text-secondary">{{ $t('chat.transfer.homeClosedHint') }}</span>
</button>
<button
type="button"
data-testid="transfer-home-unknown"
class="rounded-2xl border border-amber-200 bg-amber-50 p-4 text-left transition-colors hover:bg-amber-100"
@click="view = 'backlog'"
>
<b class="block text-2xl leading-none text-amber-600">{{ transfer.backlogSummary.value?.unknown ?? 0 }}</b>
<b class="mt-2 block text-sm font-bold text-primary">{{ $t('chat.transfer.homeUnknown') }}</b>
<span class="mt-1 block text-xs text-secondary">{{ $t('chat.transfer.homeUnknownHint') }}</span>
</button>
</div>
</section>
</div>
</template>
<!-- 子流程:复用自驱动的 TransferMessageView -->
<div v-else class="w-full max-w-4xl pr-2">
<button
type="button"
data-testid="transfer-home-back"
class="mb-2 rounded-lg px-2 py-1 text-sm font-bold text-brand-600 transition-colors hover:bg-brand-50"
@click="goBack"
>
← {{ $t('chat.transfer.homeBack') }}
</button>
<TransferMessageView :payload="childPayload" />
</div>
</div>
</template>
@@ -0,0 +1,67 @@
<!--
features/chat/components/messages/TransferManualCloseDialog.vue
用途:人工关闭弹窗(原因必填;关闭后永久排除,历史保留)。
依赖:props(open/invoiceNo)、i18n chat.transfer.*。
逻辑:原因为空时确认按钮禁用;确认时 emit confirm(reason)。
-->
<script setup lang="ts">
import { ref, watch } from 'vue';
const props = defineProps<{
open: boolean;
invoiceNo: string;
}>();
const emit = defineEmits<{
confirm: [reason: string];
cancel: [];
}>();
const reason = ref('');
watch(
() => props.open,
(open) => {
if (open) reason.value = '';
},
);
</script>
<template>
<div
v-if="open"
class="fixed inset-0 z-50 flex items-center justify-center bg-slate-900/40 p-4"
data-testid="transfer-manual-close-dialog"
>
<div class="w-full max-w-md rounded-2xl bg-white p-5 shadow-xl">
<h3 class="text-base font-bold text-slate-800">{{ $t('chat.transfer.manualCloseTitle') }}</h3>
<p class="mt-1 text-xs text-slate-500">{{ invoiceNo }} · {{ $t('chat.transfer.manualCloseHint') }}</p>
<textarea
v-model="reason"
rows="3"
class="mt-3 w-full rounded-lg border border-slate-200 p-2 text-sm"
:placeholder="$t('chat.transfer.closeReasonPlaceholder')"
data-testid="transfer-close-reason"
/>
<div class="mt-4 flex justify-end gap-2">
<button
type="button"
class="rounded-lg border border-slate-200 px-4 py-1.5 text-sm text-slate-600 hover:bg-slate-50"
data-testid="transfer-close-cancel"
@click="emit('cancel')"
>
{{ $t('chat.transfer.cancel') }}
</button>
<button
type="button"
class="rounded-lg bg-brand-600 px-4 py-1.5 text-sm font-bold text-white hover:bg-brand-700 disabled:cursor-not-allowed disabled:opacity-40"
:disabled="!reason.trim()"
data-testid="transfer-close-confirm"
@click="emit('confirm', reason.trim())"
>
{{ $t('chat.transfer.confirmClose') }}
</button>
</div>
</div>
</div>
</template>
@@ -0,0 +1,173 @@
/**
* features/chat/components/messages/TransferMessageView.spec.ts
* 用途:验证卡片自驱动接线——预检卡渲染、点“直接生成调拨单”真实调 API 并切换结果卡、
* 下载按钮调 requestBlob 封装、结果页无审计入口。
* 依赖:vi.mock(transfer.api)、@vue/test-utils、i18n。
* 逻辑:Mock API 断言调用参数与状态切换(对应后端 197 项测试的契约面)。
*/
import { mount, flushPromises } from '@vue/test-utils';
import { describe, expect, it, vi, beforeEach } from 'vitest';
import i18n from '@/i18n';
const api = vi.hoisted(() => ({
createTransferPrecheck: vi.fn(),
getTransferPrecheck: vi.fn(),
executeTransferPrecheck: vi.fn(),
getTransferRun: vi.fn(),
retryTransferItem: vi.fn(),
manualCloseTransferItem: vi.fn(),
downloadTransferReceiptFiles: vi.fn(),
downloadTransferErpInventory: vi.fn(),
downloadTransferExceptions: vi.fn(),
listTransferBacklog: vi.fn(),
getTransferBacklogSummary: vi.fn(),
listTransferSources: vi.fn(),
}));
vi.mock('@/features/chat/api/transfer.api', () => api);
import TransferMessageView from './TransferMessageView.vue';
const payload = {
kind: 'precheck',
summary: {
precheck_id: 'TPC-1',
status: 'ready_to_execute',
business_date: '2026-08-06',
eligible_receipt_date_to: '2026-08-05',
expires_at: '',
counts: { file_invoice_count: 1, not_matured_count: 0, prechecked_count: 1, executable_count: 1, blocked_count: 0 },
estimated_transfer_quantity: '1200',
estimated_erp_write_count: 1,
precheck_hash: 'sha256:x',
},
items: [{
source_code: 'DBS-AWSBI', material_no: 'MAT-1', material_name: '连接器组件', specification: 'A',
invoice_no: 'INV-001', from_warehouse: 'DBS-TRANSIT', from_quantity: '1200',
to_warehouse: 'HUB-CN01', to_quantity: '1200', result: 'executable',
}],
sources: [{ source_code: 'DBS-AWSBI', stage: 'file_ready', file_no: 'REC-1' }],
};
const runPayload = {
kind: 'result',
run_no: 'RUN-1',
status: 'success',
run: {
run_no: 'RUN-1',
status: 'success',
result: {
erp_documents: [{
document_no: 'TRF-10001', from_warehouse: 'DBS-TRANSIT', to_warehouse: 'HUB-CN01',
material_count: 1, total_quantity: '1200', posting_status: 'posted',
lines: [{ material_no: 'MAT-1', material_name: '连接器组件', specification: 'A', invoice_no: 'INV-001', quantity: '1200' }],
}],
exceptions: [],
},
},
};
describe('TransferMessageView self-driving wiring', () => {
beforeEach(() => {
vi.clearAllMocks();
api.executeTransferPrecheck.mockResolvedValue({ run_no: 'RUN-1', status: 'success' });
api.getTransferRun.mockResolvedValue(runPayload.run);
api.downloadTransferReceiptFiles.mockResolvedValue({ blob: new Blob(['z']), filename: 'r.zip' });
api.downloadTransferErpInventory.mockResolvedValue({ blob: new Blob(['c']), filename: 'e.csv' });
});
it('预检 payload 渲染预检卡,且默认勾选可执行项', () => {
const wrapper = mount(TransferMessageView, {
props: { payload },
global: { plugins: [i18n] },
});
expect(wrapper.find('[data-testid="transfer-precheck-card"]').exists()).toBe(true);
expect((wrapper.find('[data-testid="transfer-check-INV-001"]').element as HTMLInputElement).checked).toBe(true);
});
it('点击“直接生成调拨单”调用 execute API 并切换为结果卡', async () => {
const wrapper = mount(TransferMessageView, {
props: { payload },
global: { plugins: [i18n] },
});
await wrapper.find('[data-testid="transfer-generate-button"]').trigger('click');
await flushPromises();
expect(api.executeTransferPrecheck).toHaveBeenCalledWith('TPC-1', ['INV-001']);
expect(wrapper.find('[data-testid="transfer-result-card"]').exists()).toBe(true);
});
it('结果卡下载按钮调用下载 API(收料来源文件 + ERP 库存表)', async () => {
const wrapper = mount(TransferMessageView, {
props: { payload: runPayload },
global: { plugins: [i18n] },
});
await wrapper.find('[data-testid="transfer-download-receipt"]').trigger('click');
await wrapper.find('[data-testid="transfer-download-erp"]').trigger('click');
await flushPromises();
expect(api.downloadTransferReceiptFiles).toHaveBeenCalledWith('RUN-1');
expect(api.downloadTransferErpInventory).toHaveBeenCalledWith('RUN-1');
});
it('结果卡不出现执行审计入口(决策 19)', () => {
const wrapper = mount(TransferMessageView, {
props: { payload: runPayload },
global: { plugins: [i18n] },
});
expect(wrapper.text()).not.toContain('审计');
});
it('backlog 视图拉取待处理列表,重试/关闭调用对应 API', async () => {
api.listTransferBacklog.mockResolvedValue([{
item_id: 7, source_code: 'DBS-AWSBI', invoice_no: 'INV-001', material_no: 'MAT-1',
status: 'blocked_recoverable', reason: '收料 1200 / ERP 1000', age_days: 1, aging_level: 'normal',
}]);
api.getTransferBacklogSummary.mockResolvedValue({
recoverable: 1, closed: 0, unknown: 0, aging: { warn_3d: 0, escalate_5d: 0, critical_7d: 0 },
});
api.retryTransferItem.mockResolvedValue({ item_id: 7, status: 'ready_to_execute', attempt_no: 2 });
api.manualCloseTransferItem.mockResolvedValue({ item_id: 7, status: 'manually_closed' });
const wrapper = mount(TransferMessageView, {
props: { payload: { kind: 'backlog' } },
global: { plugins: [i18n] },
});
await flushPromises();
expect(wrapper.find('[data-testid="transfer-backlog-card"]').exists()).toBe(true);
expect(wrapper.text()).toContain('INV-001');
await wrapper.find('[data-testid="transfer-backlog-retry"]').trigger('click');
await flushPromises();
expect(api.retryTransferItem).toHaveBeenCalledWith(7);
await wrapper.find('[data-testid="transfer-backlog-close"]').trigger('click');
await wrapper.find('[data-testid="transfer-close-reason"]').setValue('线下已处理');
await wrapper.find('[data-testid="transfer-close-confirm"]').trigger('click');
await flushPromises();
expect(api.manualCloseTransferItem).toHaveBeenCalledWith(7, '线下已处理');
});
it('来源实例选择:加载列表 → 确认范围 → 创建预检并切换预检卡', async () => {
api.listTransferSources.mockResolvedValue([
{ source_code: 'DBS-AWSBI', display_name: 'AWSBI', platform: 'dbs', enabled: true, has_ready_file: true, file_status: 'ready' },
]);
api.createTransferPrecheck.mockResolvedValue(payload.summary);
api.getTransferPrecheck.mockResolvedValue({
summary: payload.summary,
items: payload.items,
sources: payload.sources,
});
const wrapper = mount(TransferMessageView, {
props: { payload: { kind: 'source-select' } },
global: { plugins: [i18n] },
});
await flushPromises();
expect(wrapper.find('[data-testid="transfer-source-select-card"]').exists()).toBe(true);
await wrapper.find('[data-testid="transfer-source-option-DBS-AWSBI"] input').setValue(true);
await wrapper.find('[data-testid="transfer-source-confirm"]').trigger('click');
await flushPromises();
expect(api.createTransferPrecheck).toHaveBeenCalledWith({ source_codes: ['DBS-AWSBI'] });
expect(wrapper.find('[data-testid="transfer-precheck-card"]').exists()).toBe(true);
});
});
@@ -0,0 +1,243 @@
<!--
features/chat/components/messages/TransferMessageView.vue
用途:在途调拨消息卡片的自驱动挂载视图——按 payload 形态渲染卡片,并把卡片按钮
(直接生成调拨单 / 下载 / 重试 / 关闭)经 useChatTransfer 真实调用 API。
依赖:Transfer*Card、useChatTransfer、i18n chat.transfer.*。
逻辑:payload 作为初始状态(ChatLog 回放);执行后切换为结果卡;下载走 requestBlob;
不展示执行审计入口(决策 19)。
-->
<script setup lang="ts">
import { computed, onMounted, ref, watch } from 'vue';
import TransferPrecheckCard from './TransferPrecheckCard.vue';
import TransferFileProgressCard from './TransferFileProgressCard.vue';
import TransferProgressCard from './TransferProgressCard.vue';
import TransferResultCard from './TransferResultCard.vue';
import TransferBacklogSummaryCard from './TransferBacklogSummaryCard.vue';
import TransferManualCloseDialog from './TransferManualCloseDialog.vue';
import TransferSourceSelectCard from './TransferSourceSelectCard.vue';
import { useChatTransfer } from '../../composables/useChatTransfer';
import { useMessage } from '@/shared/composables/useMessage';
import type {
TransferBacklogItem,
TransferPrecheckItem,
TransferPrecheckSummary,
TransferRunResult,
TransferSourceProgress,
} from '../../types/transfer.types';
const props = defineProps<{
payload?: Record<string, unknown> | null;
}>();
const { error: notifyError } = useMessage();
/** 统一错误提示:BusinessError 带本地化 message,其余回退到 String(e)。 */
function reportError(e: unknown) {
notifyError(e instanceof Error ? e.message : String(e));
}
const kind = computed(() => String(props.payload?.kind ?? 'precheck'));
const mode = ref(kind.value);
const summaryRef = ref<TransferPrecheckSummary | null>((props.payload?.summary as TransferPrecheckSummary) ?? null);
const items = ref<TransferPrecheckItem[]>((props.payload?.items as TransferPrecheckItem[]) ?? []);
const runNo = ref(String(props.payload?.run_no ?? ''));
const status = ref(String(props.payload?.status ?? 'executing'));
const run = ref<TransferRunResult | null>((props.payload?.run as TransferRunResult) ?? null);
const busy = ref(false);
const closeTarget = ref<TransferBacklogItem | null>(null);
/** 正在重试收料 RPA 的来源编码集合(按来源独立展示重试中)。 */
const retryingSource = ref<Set<string>>(new Set());
const transfer = useChatTransfer();
/** 待处理异常视图:进入时拉取列表与汇总 */
onMounted(() => {
if (kind.value === 'backlog') {
void transfer.loadBacklog();
}
if (kind.value === 'source-select') {
void transfer.loadSources();
}
});
/** payload 更新时重置本地状态(历史回放/刷新);初始化组合式函数上下文 */
function applyPayload(payload?: Record<string, unknown> | null) {
if (!payload) return;
mode.value = String(payload.kind ?? 'precheck');
summaryRef.value = (payload.summary as TransferPrecheckSummary) ?? null;
items.value = (payload.items as TransferPrecheckItem[]) ?? [];
runNo.value = String(payload.run_no ?? '');
status.value = String(payload.status ?? 'executing');
run.value = (payload.run as TransferRunResult) ?? null;
const summaryValue = (payload.summary as TransferPrecheckSummary) ?? null;
if (summaryValue) {
transfer.precheckId.value = summaryValue.precheck_id;
transfer.selected.value = new Set(
(payload.items as TransferPrecheckItem[] ?? [])
.filter((item) => item.result === 'executable')
.map((item) => item.invoice_no),
);
}
if (runNo.value) {
transfer.runNo.value = runNo.value;
}
}
applyPayload(props.payload);
watch(() => props.payload, applyPayload);
/** 直接生成调拨单(决策 4/5:无独立确认页) */
async function onExecute(invoiceNos: string[]) {
busy.value = true;
try {
transfer.selected.value = new Set(invoiceNos);
const outcome = await transfer.execute();
if (outcome) {
mode.value = 'result';
runNo.value = outcome.run_no;
status.value = outcome.status;
run.value = transfer.run.value;
}
} catch (e) {
reportError(e);
} finally {
busy.value = false;
}
}
async function onDownloadReceipt() {
try {
await transfer.downloadReceiptFiles();
} catch (e) {
reportError(e);
}
}
async function onDownloadErp() {
try {
await transfer.downloadErpInventory();
} catch (e) {
reportError(e);
}
}
async function onDownloadExceptions() {
try {
await transfer.downloadExceptions();
} catch (e) {
reportError(e);
}
}
async function onBacklogRetry(itemId: number) {
busy.value = true;
try {
await transfer.retry(itemId);
await transfer.loadBacklog();
} catch (e) {
reportError(e);
} finally {
busy.value = false;
}
}
function onBacklogClose(item: TransferBacklogItem) {
closeTarget.value = item;
}
async function onCloseConfirm(reason: string) {
if (!closeTarget.value) return;
busy.value = true;
try {
await transfer.manualClose(closeTarget.value.item_id, reason);
closeTarget.value = null;
await transfer.loadBacklog();
} catch (e) {
reportError(e);
} finally {
busy.value = false;
}
}
/** 来源实例选择确认 → 创建预检并切换预检卡(决策 4:两步第一步) */
async function onSourceConfirm(sourceCodes: string[]) {
busy.value = true;
try {
await transfer.createPrecheck(sourceCodes);
mode.value = 'precheck';
summaryRef.value = transfer.precheck.value;
items.value = transfer.items.value;
run.value = null;
} catch (e) {
reportError(e);
} finally {
busy.value = false;
}
}
/** 对来源(单个或批量)重新触发收料 RPA 抓取,重试期间标记该来源(busy 独立于 confirm busy)。 */
async function onSourceRetry(sourceCodes: string[]) {
const codes = Array.isArray(sourceCodes) ? sourceCodes : [sourceCodes];
retryingSource.value = new Set([...retryingSource.value, ...codes]);
try {
// 逐来源触发,避免一次并发 EPR/RPA 竞态;失败中断剩余。
for (const code of codes) {
await transfer.retrySourceRpa(code);
}
} catch (e) {
reportError(e);
} finally {
const next = new Set(retryingSource.value);
for (const code of codes) next.delete(code);
retryingSource.value = next;
}
}
</script>
<template>
<div>
<TransferFileProgressCard
v-if="mode === 'file-progress'"
:sources="(props.payload?.sources as TransferSourceProgress[]) ?? []"
/>
<TransferSourceSelectCard
v-else-if="mode === 'source-select'"
:sources="transfer.sourceOptions.value"
:busy="busy"
:retrying="retryingSource"
@confirm="onSourceConfirm"
@retry="onSourceRetry"
/>
<TransferPrecheckCard
v-else-if="mode === 'precheck' && summaryRef"
:summary="summaryRef"
:items="items"
:selected="transfer.selected.value"
:busy="busy"
@toggle="(invoiceNo, checked) => transfer.toggleSelect(invoiceNo, checked)"
@execute="onExecute"
/>
<TransferProgressCard v-else-if="mode === 'progress'" :run-no="runNo" :status="status" :busy="busy" />
<TransferResultCard
v-else-if="mode === 'result' && run"
:run="run"
@download-receipt="onDownloadReceipt"
@download-erp="onDownloadErp"
@download-exceptions="onDownloadExceptions"
/>
<TransferBacklogSummaryCard
v-else-if="mode === 'backlog'"
:items="transfer.backlog.value"
@retry="onBacklogRetry"
@close="onBacklogClose"
@refresh="() => transfer.loadBacklog()"
/>
<TransferManualCloseDialog
v-if="closeTarget"
:open="Boolean(closeTarget)"
:invoice-no="closeTarget.invoice_no"
@confirm="onCloseConfirm"
@cancel="closeTarget = null"
/>
</div>
</template>
@@ -0,0 +1,157 @@
<!--
features/chat/components/messages/TransferPrecheckCard.vue
用途:预检卡——计数 + 调拨明细表(决策 6 十列)+ 勾选 + “直接生成调拨单”按钮。
依赖:props(summary/items/selected/busy)、i18n chat.transfer.*。
逻辑:阻断/未成熟项 checkbox 禁用;无选择或 busy 时生成按钮禁用;
emit execute(invoiceNos)(决策 4/5:无独立确认页)。
-->
<script setup lang="ts">
import { computed } from 'vue';
import type { TransferPrecheckItem, TransferPrecheckSummary } from '../../types/transfer.types';
const props = defineProps<{
summary: TransferPrecheckSummary;
items: TransferPrecheckItem[];
selected: Set<string>;
busy?: boolean;
}>();
const emit = defineEmits<{
toggle: [invoiceNo: string, checked: boolean];
execute: [invoiceNos: string[]];
}>();
const selectedCount = computed(() =>
props.items.filter((item) => item.result === 'executable' && props.selected.has(item.invoice_no)).length,
);
const executeDisabled = computed(() => props.busy || selectedCount.value === 0);
function isSelectable(item: TransferPrecheckItem): boolean {
return item.result === 'executable';
}
function isChecked(item: TransferPrecheckItem): boolean {
return props.selected.has(item.invoice_no);
}
function resultLabel(result: string): string {
const map: Record<string, string> = {
executable: 'chat.transfer.resultExecutable',
not_matured: 'chat.transfer.resultNotMatured',
blocked_quantity_mismatch: 'chat.transfer.resultBlocked',
blocked_inventory_not_found: 'chat.transfer.resultBlocked',
blocked_future_date: 'chat.transfer.resultBlocked',
erp_query_timeout: 'chat.transfer.resultUnknown',
result_unknown: 'chat.transfer.resultUnknown',
};
return map[result] ?? 'chat.transfer.resultBlocked';
}
</script>
<template>
<div class="my-2 rounded-2xl border border-brand-100 bg-white p-4 shadow-sm" data-testid="transfer-precheck-card">
<div class="mb-3 flex flex-wrap items-center justify-between gap-3">
<h3 class="text-sm font-bold text-slate-800">{{ $t('chat.transfer.precheckTitle') }}</h3>
<span class="text-xs text-slate-400">{{ $t('chat.transfer.businessDate') }}:{{ summary.business_date }}</span>
</div>
<div class="mb-3 grid grid-cols-2 gap-2 sm:grid-cols-5" data-testid="transfer-precheck-counts">
<div class="rounded-lg bg-slate-50 p-2 text-center">
<div class="text-lg font-black text-brand-600">{{ summary.counts.executable_count }}</div>
<div class="text-[11px] text-slate-500">{{ $t('chat.transfer.executableCount') }}</div>
</div>
<div class="rounded-lg bg-slate-50 p-2 text-center">
<div class="text-lg font-black text-slate-600">{{ summary.counts.not_matured_count }}</div>
<div class="text-[11px] text-slate-500">{{ $t('chat.transfer.notMaturedCount') }}</div>
</div>
<div class="rounded-lg bg-slate-50 p-2 text-center">
<div class="text-lg font-black text-slate-600">{{ summary.counts.blocked_count }}</div>
<div class="text-[11px] text-slate-500">{{ $t('chat.transfer.blockedCount') }}</div>
</div>
<div class="rounded-lg bg-slate-50 p-2 text-center">
<div class="text-lg font-black text-brand-600">{{ summary.estimated_transfer_quantity }}</div>
<div class="text-[11px] text-slate-500">{{ $t('chat.transfer.estimatedQuantity') }}</div>
</div>
<div class="rounded-lg bg-slate-50 p-2 text-center">
<div class="text-lg font-black text-brand-600">{{ summary.estimated_erp_write_count }}</div>
<div class="text-[11px] text-slate-500">{{ $t('chat.transfer.estimatedErpWrites') }}</div>
</div>
</div>
<div class="overflow-x-auto">
<table class="w-full min-w-[1100px] text-xs" data-testid="transfer-precheck-table">
<thead>
<tr class="border-b border-slate-200 bg-slate-50 text-left text-[11px] text-slate-500">
<th class="p-2"></th>
<th class="p-2">{{ $t('chat.transfer.colSource') }}</th>
<th class="p-2">{{ $t('chat.transfer.colMaterial') }}</th>
<th class="p-2">{{ $t('chat.transfer.colName') }}</th>
<th class="p-2">{{ $t('chat.transfer.colSpec') }}</th>
<th class="p-2">{{ $t('chat.transfer.colInvoice') }}</th>
<th class="p-2">{{ $t('chat.transfer.colFromWarehouse') }}</th>
<th class="p-2">{{ $t('chat.transfer.colFromQty') }}</th>
<th class="p-2">{{ $t('chat.transfer.colToWarehouse') }}</th>
<th class="p-2">{{ $t('chat.transfer.colToQty') }}</th>
<th class="p-2">{{ $t('chat.transfer.colResult') }}</th>
</tr>
</thead>
<tbody>
<tr
v-for="item in items"
:key="item.invoice_no"
class="border-b border-slate-100"
:class="{ 'bg-slate-50 text-slate-400': !isSelectable(item) }"
:data-testid="`transfer-item-${item.invoice_no}`"
>
<td class="p-2">
<input
type="checkbox"
:checked="isChecked(item)"
:disabled="!isSelectable(item) || busy"
:data-testid="`transfer-check-${item.invoice_no}`"
@change="emit('toggle', item.invoice_no, ($event.target as HTMLInputElement).checked)"
/>
</td>
<td class="p-2">{{ item.source_code }}</td>
<td class="p-2">{{ item.material_no }}</td>
<td class="p-2">{{ item.material_name }}</td>
<td class="p-2">{{ item.specification }}</td>
<td class="p-2 font-semibold">{{ item.invoice_no }}</td>
<td class="p-2">{{ item.from_warehouse }}</td>
<td class="p-2">{{ item.from_quantity ?? '—' }}</td>
<td class="p-2">{{ item.to_warehouse }}</td>
<td class="p-2">{{ item.to_quantity }}</td>
<td class="p-2">
<span
class="rounded-full px-2 py-0.5 font-bold"
:class="{
'bg-emerald-50 text-emerald-700': item.result === 'executable',
'bg-amber-50 text-amber-700': item.result === 'not_matured',
'bg-red-50 text-red-700': !isSelectable(item) && item.result !== 'not_matured',
}"
>
{{ $t(resultLabel(item.result)) }}
</span>
</td>
</tr>
</tbody>
</table>
</div>
<div class="mt-3 flex items-center justify-end gap-3 border-t border-slate-100 pt-3">
<span class="text-xs text-slate-500">
{{ $t('chat.transfer.selectedCount', { count: selectedCount }) }} ·
{{ $t('chat.transfer.estimatedErpWrites') }}:{{ summary.estimated_erp_write_count }}
</span>
<button
type="button"
class="rounded-lg bg-brand-600 px-4 py-1.5 text-sm font-bold text-white hover:bg-brand-700 disabled:cursor-not-allowed disabled:opacity-40"
:disabled="executeDisabled"
:data-testid="'transfer-generate-button'"
@click="emit('execute', items.filter(isSelectable).filter(isChecked).map((item) => item.invoice_no))"
>
{{ $t('chat.transfer.generateTransfer') }}
</button>
</div>
</div>
</template>
@@ -0,0 +1,60 @@
<!--
features/chat/components/messages/TransferProgressCard.vue
用途:Run 执行进度卡(页面关闭/刷新后经 run_no 恢复)。
依赖:props(runNo/status/busy)、i18n chat.transfer.*。
逻辑:展示 Run 编号与状态,提供刷新按钮;页面刷新不取消后台 Run。
-->
<script setup lang="ts">
defineProps<{
runNo: string;
status: string;
busy?: boolean;
}>();
const emit = defineEmits<{
refresh: [];
}>();
function statusLabel(status: string): string {
const map: Record<string, string> = {
executing: 'chat.transfer.runExecuting',
success: 'chat.transfer.runSuccess',
partial_failed: 'chat.transfer.runPartialFailed',
failed: 'chat.transfer.runFailed',
cancelled: 'chat.transfer.runCancelled',
};
return map[status] ?? 'chat.transfer.runExecuting';
}
</script>
<template>
<div class="my-2 rounded-2xl border border-brand-100 bg-white p-4 shadow-sm" data-testid="transfer-progress-card">
<div class="flex items-center justify-between">
<div>
<div class="text-sm font-bold text-slate-800">{{ $t('chat.transfer.runProgress') }}</div>
<div class="mt-1 text-xs text-slate-500">{{ runNo }}</div>
</div>
<span
class="rounded-full px-2 py-0.5 text-xs font-bold"
:class="{
'bg-blue-50 text-blue-700': status === 'executing',
'bg-emerald-50 text-emerald-700': status === 'success',
'bg-amber-50 text-amber-700': status === 'partial_failed',
'bg-red-50 text-red-700': status === 'failed' || status === 'cancelled',
}"
data-testid="transfer-run-status"
>
{{ $t(statusLabel(status)) }}
</span>
<button
type="button"
class="rounded-lg border border-slate-200 px-3 py-1 text-xs font-bold text-slate-600 hover:bg-slate-50"
:disabled="busy"
data-testid="transfer-run-refresh"
@click="emit('refresh')"
>
{{ $t('chat.transfer.refreshProgress') }}
</button>
</div>
</div>
</template>
@@ -0,0 +1,131 @@
<!--
features/chat/components/messages/TransferResultCard.vue
用途:结果卡——按 ERP 单号聚合(决策 20)、可展开物料明细、未生成单据异常区、
下载收料来源文件 / ERP 库存表(决策 21)。不展示执行审计入口(决策 19)。
依赖:props.run、i18n chat.transfer.*。
逻辑:<details> 展开/收起物料行;异常单独分区;两个下载按钮 + 异常 Excel。
-->
<script setup lang="ts">
import type { TransferRunResult } from '../../types/transfer.types';
defineProps<{
run: TransferRunResult;
}>();
const emit = defineEmits<{
downloadReceipt: [];
downloadErp: [];
downloadExceptions: [];
}>();
function reasonLabel(reason: string): string {
const map: Record<string, string> = {
blocked_quantity_mismatch: 'chat.transfer.resultBlocked',
blocked_inventory_not_found: 'chat.transfer.resultBlocked',
business_failed: 'chat.transfer.exceptionBusinessFailed',
technical_failed: 'chat.transfer.exceptionTechnicalFailed',
result_unknown: 'chat.transfer.resultUnknown',
precheck_expired: 'chat.transfer.exceptionPrecheckExpired',
};
return map[reason] ?? 'chat.transfer.resultBlocked';
}
</script>
<template>
<div class="my-2 rounded-2xl border border-brand-100 bg-white p-4 shadow-sm" data-testid="transfer-result-card">
<div class="mb-3 flex items-center justify-between">
<h3 class="text-sm font-bold text-slate-800">{{ $t('chat.transfer.resultTitle') }}</h3>
<span class="text-xs text-slate-400">{{ run.run_no }}</span>
</div>
<!-- 已生成 ERP 单据:按单号聚合 + 可展开物料明细 -->
<div v-if="run.result.erp_documents.length" class="flex flex-col gap-2">
<details
v-for="doc in run.result.erp_documents"
:key="doc.document_no"
class="rounded-lg border border-slate-200"
data-testid="transfer-erp-document"
>
<summary class="flex cursor-pointer flex-wrap items-center justify-between gap-2 px-3 py-2 text-xs">
<span class="font-bold text-brand-700">{{ doc.document_no }}</span>
<span class="text-slate-600">{{ doc.from_warehouse }} → {{ doc.to_warehouse }}</span>
<span class="text-slate-500">{{ $t('chat.transfer.materialCount', { count: doc.material_count }) }}</span>
<span class="font-bold text-slate-700">{{ doc.total_quantity }}</span>
<span class="rounded-full bg-emerald-50 px-2 py-0.5 font-bold text-emerald-700">
{{ $t('chat.transfer.posted') }}
</span>
</summary>
<div class="border-t border-slate-100 px-3 py-2">
<table class="w-full text-xs" data-testid="transfer-erp-document-lines">
<thead>
<tr class="text-left text-[11px] text-slate-500">
<th class="p-1">{{ $t('chat.transfer.colMaterial') }}</th>
<th class="p-1">{{ $t('chat.transfer.colName') }}</th>
<th class="p-1">{{ $t('chat.transfer.colSpec') }}</th>
<th class="p-1">{{ $t('chat.transfer.colInvoice') }}</th>
<th class="p-1">{{ $t('chat.transfer.colToQty') }}</th>
</tr>
</thead>
<tbody>
<tr v-for="line in doc.lines" :key="line.invoice_no" class="border-t border-slate-100">
<td class="p-1">{{ line.material_no }}</td>
<td class="p-1">{{ line.material_name }}</td>
<td class="p-1">{{ line.specification }}</td>
<td class="p-1">{{ line.invoice_no }}</td>
<td class="p-1">{{ line.quantity }}</td>
</tr>
</tbody>
</table>
</div>
</details>
</div>
<div v-else class="mb-3 rounded-lg bg-slate-50 p-3 text-xs text-slate-500">
{{ $t('chat.transfer.noDocuments') }}
</div>
<!-- 未生成 ERP 单据的异常区(决策 20 单独展示) -->
<div v-if="run.result.exceptions.length" class="mt-3" data-testid="transfer-exceptions-area">
<h4 class="mb-1 text-xs font-bold text-slate-600">{{ $t('chat.transfer.exceptionsTitle') }}</h4>
<ul class="flex flex-col gap-1">
<li
v-for="exc in run.result.exceptions"
:key="exc.invoice_no"
class="rounded-lg bg-red-50 px-3 py-1.5 text-xs text-red-700"
data-testid="transfer-exception-item"
>
<span class="font-bold">{{ exc.invoice_no }}</span>
<span class="mx-1 text-red-400">·</span>{{ exc.source_code }} · {{ $t(reasonLabel(exc.reason)) }}
<div class="text-[11px] text-red-500">{{ exc.facts }}</div>
</li>
</ul>
</div>
<!-- 下载:收料来源文件 + ERP 库存表(决策 21);无审计入口(决策 19) -->
<div class="mt-3 flex flex-wrap gap-2 border-t border-slate-100 pt-3" data-testid="transfer-result-downloads">
<button
type="button"
class="rounded-lg border border-brand-200 px-3 py-1.5 text-xs font-bold text-brand-700 hover:bg-brand-50"
data-testid="transfer-download-receipt"
@click="emit('downloadReceipt')"
>
{{ $t('chat.transfer.downloadReceiptFiles') }}
</button>
<button
type="button"
class="rounded-lg border border-brand-200 px-3 py-1.5 text-xs font-bold text-brand-700 hover:bg-brand-50"
data-testid="transfer-download-erp"
@click="emit('downloadErp')"
>
{{ $t('chat.transfer.downloadErpInventory') }}
</button>
<button
type="button"
class="rounded-lg border border-slate-200 px-3 py-1.5 text-xs font-bold text-slate-600 hover:bg-slate-50"
data-testid="transfer-download-exceptions"
@click="emit('downloadExceptions')"
>
{{ $t('chat.transfer.downloadExceptions') }}
</button>
</div>
</div>
</template>
@@ -0,0 +1,89 @@
/**
* features/chat/components/messages/TransferSourceSelectCard.spec.ts
* 用途:来源实例选择卡——平台分组、全选已启用、清空、按收料文件状态门禁确认、
* 确认提交、重试收料 RPA。
* 依赖:@vue/test-utils、i18n。
* 逻辑:平台 DBS/Crane 仅分组;实例为选择与执行边界(决策 2/3/4);
* 所选来源需至少一个 has_ready_file 才能确认预检(决策:无 ready 文件禁止确认)。
*/
import { mount } from '@vue/test-utils';
import { describe, expect, it } from 'vitest';
import i18n from '@/i18n';
import TransferSourceSelectCard from './TransferSourceSelectCard.vue';
const readySources = [
{ source_code: 'DBS-AWSBI', display_name: 'AWSBI 在途仓', platform: 'dbs', enabled: true, has_ready_file: true, file_status: 'ready' },
{ source_code: 'DBS-AWSSG', display_name: 'AWSSG 在途仓', platform: 'dbs', enabled: true, file_status: 'none' },
{ source_code: 'CRANE-SZ', display_name: '深圳在途仓', platform: 'crane', enabled: true, has_ready_file: true, file_status: 'ready' },
];
function mountCard(props = {}, sources = readySources) {
return mount(TransferSourceSelectCard, {
props: { sources, ...props },
global: { plugins: [i18n] },
});
}
describe('TransferSourceSelectCard', () => {
it('按平台分组展示来源实例', () => {
const wrapper = mountCard();
expect(wrapper.find('[data-testid="transfer-source-option-DBS-AWSBI"]').text()).toContain('DBS-AWSBI');
expect(wrapper.find('[data-testid="transfer-source-option-CRANE-SZ"]').text()).toContain('CRANE-SZ');
});
it('未选任何来源时确认按钮禁用(需至少一个 ready 文件来源)', () => {
const wrapper = mountCard();
expect((wrapper.find('[data-testid="transfer-source-confirm"]').element as HTMLButtonElement).disabled).toBe(true);
});
it('勾选含 ready 文件来源后确认提交所选来源', async () => {
const wrapper = mountCard();
await wrapper.find('[data-testid="transfer-source-option-DBS-AWSBI"] input').setValue(true);
await wrapper.find('[data-testid="transfer-source-option-CRANE-SZ"] input').setValue(true);
await wrapper.find('[data-testid="transfer-source-confirm"]').trigger('click');
expect(wrapper.emitted('confirm')?.[0][0]).toEqual(['DBS-AWSBI', 'CRANE-SZ']);
});
it('仅勾选无 ready 文件来源时不提交(门禁)', async () => {
const wrapper = mountCard();
await wrapper.find('[data-testid="transfer-source-option-DBS-AWSSG"] input').setValue(true);
await wrapper.find('[data-testid="transfer-source-confirm"]').trigger('click');
expect(wrapper.emitted('confirm')).toBeUndefined();
});
it('“全选可见”勾选全部启用实例', async () => {
const wrapper = mountCard();
await wrapper.find('[data-testid="transfer-source-select-visible"]').trigger('click');
await wrapper.find('[data-testid="transfer-source-confirm"]').trigger('click');
expect(wrapper.emitted('confirm')?.[0][0]).toEqual(['DBS-AWSBI', 'DBS-AWSSG', 'CRANE-SZ']);
});
it('“清空”清空已选实例', async () => {
const wrapper = mountCard();
await wrapper.find('[data-testid="transfer-source-select-visible"]').trigger('click');
await wrapper.find('[data-testid="transfer-source-clear"]').trigger('click');
await wrapper.find('[data-testid="transfer-source-confirm"]').trigger('click');
expect(wrapper.emitted('confirm')).toBeUndefined();
});
it('“只选可重试”勾选无文件/失败来源', async () => {
const wrapper = mountCard();
await wrapper.find('[data-testid="transfer-source-select-retryable"]').trigger('click');
const selected = (wrapper.find('[data-testid="transfer-source-confirm"]').element as HTMLButtonElement).disabled;
// 可重试来源为 DBS-AWSSG(none);选中它但无 ready 文件 → 确认仍禁用(门禁)。
expect(selected).toBe(true);
});
it('点击行尾重试图标 emit retry([sourceCode])', async () => {
const wrapper = mountCard();
await wrapper.find('[data-testid="transfer-source-retry-DBS-AWSSG"]').trigger('click');
expect(wrapper.emitted('retry')?.[0][0]).toEqual(['DBS-AWSSG']);
});
it('批量重试仅传可重试来源', async () => {
const wrapper = mountCard();
await wrapper.find('[data-testid="transfer-source-select-retryable"]').trigger('click');
await wrapper.find('[data-testid="transfer-source-batch-retry"]').trigger('click');
expect(wrapper.emitted('retry')?.[0][0]).toEqual(['DBS-AWSSG']);
});
});
@@ -0,0 +1,246 @@
<!--
features/chat/components/messages/TransferSourceSelectCard.vue
用途:来源实例选择卡(决策 2/3/4:手工两步第一步)——按平台 DBS/Crane 分组勾选实例,
“确认范围并预检”发起预检。
依赖:props.sources、i18n chat.transfer.*。
逻辑:平台仅分组不可直接执行;未选任何实例时确认按钮禁用。
-->
<script setup lang="ts">
import { computed, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { useMessage } from '@/shared/composables/useMessage';
import type { TransferSourceOption } from '../../types/transfer.types';
const props = defineProps<{
sources: TransferSourceOption[];
busy?: boolean;
/** 正在重试收料 RPA 的来源编码集合 */
retrying?: Set<string>;
}>();
const emit = defineEmits<{
confirm: [sourceCodes: string[]];
/** 批量重试收料 RPA:传来源编码列表 */
retry: [sourceCodes: string[]];
}>();
const { warning: notifyWarning } = useMessage();
const { t } = useI18n();
const selected = ref<Set<string>>(new Set());
const platforms = computed(() => [...new Set(props.sources.map((source) => source.platform))]);
const selectedCount = computed(() => selected.value.size);
/** 可重试判定:仅 待抓取(none) / 抓取失败(failed) 的来源可重试(ready/fetching 不重复触发)。 */
function isRetryable(source: TransferSourceOption): boolean {
return source.file_status === 'none' || source.file_status === 'failed';
}
/** 全部可重试来源。 */
const retryableSources = computed(() => props.sources.filter(isRetryable));
/** 已选来源中可重试的数量。 */
const selectedRetryableCount = computed(() =>
[...selected.value].filter((code) => props.sources.some((s) => s.source_code === code && isRetryable(s))).length,
);
const batchRetryDisabled = computed(() => props.busy || selectedRetryableCount.value === 0);
/** 已选来源中是否有具备 ready 文件的(门禁:都无 ready 文件则禁止确认预检)。 */
const selectedHasReadyFile = computed(() =>
[...selected.value].some((code) => props.sources.find((s) => s.source_code === code)?.has_ready_file),
);
const confirmDisabled = computed(() => props.busy || selectedCount.value === 0 || !selectedHasReadyFile.value);
function toggle(sourceCode: string, checked: boolean) {
const next = new Set(selected.value);
if (checked) next.add(sourceCode);
else next.delete(sourceCode);
selected.value = next;
}
function togglePlatform(platform: string, checked: boolean) {
const next = new Set(selected.value);
for (const source of props.sources) {
if (source.platform === platform) {
if (checked) next.add(source.source_code);
else next.delete(source.source_code);
}
}
selected.value = next;
}
/** 全选当前可见来源(已启用实例)。 */
function selectVisible() {
selected.value = new Set(props.sources.filter((source) => source.enabled).map((source) => source.source_code));
}
/** 只选可重试来源(待抓取/抓取失败),来源多时一键收敛。 */
function selectRetryable() {
selected.value = new Set(retryableSources.value.map((source) => source.source_code));
}
/** 清空选择。 */
function clearSelected() {
selected.value = new Set();
}
/** 批量重试收料 RPA:仅触发所选来源中可重试的那部分。 */
function batchRetry() {
const codes = [...selected.value].filter(
(code) => props.sources.some((s) => s.source_code === code && isRetryable(s)),
);
if (codes.length === 0) {
notifyWarning(t('chat.transfer.noRetryable'), t('chat.transfer.sourceSelectTitle'));
return;
}
emit('retry', codes);
}
function confirm() {
if (selectedCount.value === 0) {
notifyWarning(t('chat.transfer.needSelectSource'), t('chat.transfer.sourceSelectTitle'));
return;
}
if (!selectedHasReadyFile.value) {
notifyWarning(t('chat.transfer.needReadyFile'), t('chat.transfer.sourceSelectTitle'));
return;
}
emit('confirm', [...selected.value]);
}
</script>
<template>
<div class="my-2 rounded-2xl border border-brand-100 bg-white p-4 shadow-sm" data-testid="transfer-source-select-card">
<h3 class="mb-1 text-sm font-bold text-slate-800">{{ $t('chat.transfer.sourceSelectTitle') }}</h3>
<p class="mb-3 text-xs text-slate-500">{{ $t('chat.transfer.sourceSelectHint') }}</p>
<div class="mb-3 flex flex-wrap items-center gap-2">
<button
type="button"
class="rounded-lg border border-brand-200 px-3 py-1.5 text-xs font-bold text-brand-700 hover:bg-brand-50 disabled:opacity-50"
:disabled="busy"
data-testid="transfer-source-select-visible"
@click="selectVisible"
>
{{ $t('chat.transfer.selectVisible') }}
</button>
<button
type="button"
class="rounded-lg border border-brand-200 px-3 py-1.5 text-xs font-bold text-brand-700 hover:bg-brand-50 disabled:opacity-50"
:disabled="busy"
data-testid="transfer-source-select-retryable"
@click="selectRetryable"
>
{{ $t('chat.transfer.selectRetryable') }}
</button>
<button
type="button"
class="rounded-lg bg-brand-600 px-3 py-1.5 text-xs font-bold text-white hover:bg-brand-700 disabled:opacity-50"
:disabled="batchRetryDisabled"
data-testid="transfer-source-batch-retry"
@click="batchRetry"
>
{{ $t('chat.transfer.batchRetry') }}
</button>
<button
type="button"
class="rounded-lg border border-slate-200 px-3 py-1.5 text-xs font-bold text-slate-600 hover:bg-slate-50 disabled:opacity-50"
:disabled="busy"
data-testid="transfer-source-clear"
@click="clearSelected"
>
{{ $t('chat.transfer.clearSources') }}
</button>
<span class="ml-auto text-xs text-slate-500">
{{ $t('chat.transfer.selectedSourceCount', { count: selectedCount }) }}
<span v-if="selectedRetryableCount > 0" class="text-amber-600"> · {{ $t('chat.transfer.selectedRetryableCount', { count: selectedRetryableCount }) }}</span>
</span>
</div>
<div v-for="platform in platforms" :key="platform" class="mb-3 rounded-lg border border-slate-100">
<div class="flex items-center justify-between rounded-t-lg bg-slate-50 px-3 py-1.5">
<b class="text-xs text-slate-700">{{ platform.toUpperCase() }}</b>
<label class="text-[11px] text-slate-500">
<input
type="checkbox"
:checked="props.sources.filter((source) => source.platform === platform).every((source) => selected.has(source.source_code))"
@change="togglePlatform(platform, ($event.target as HTMLInputElement).checked)"
/>
{{ $t('chat.transfer.selectAll') }}
</label>
</div>
<div class="grid grid-cols-1 gap-1 p-2 sm:grid-cols-2">
<div
v-for="source in props.sources.filter((item) => item.platform === platform)"
:key="source.source_code"
class="flex items-center gap-2 rounded-lg px-2 py-1.5 hover:bg-slate-50"
:data-testid="`transfer-source-option-${source.source_code}`"
>
<input
type="checkbox"
:checked="selected.has(source.source_code)"
:disabled="busy"
@change="toggle(source.source_code, ($event.target as HTMLInputElement).checked)"
/>
<span class="min-w-0 flex-1">
<span class="block truncate text-xs font-semibold text-slate-700">{{ source.source_code }}</span>
<span class="block truncate text-[11px] text-slate-400">{{ source.display_name }}</span>
</span>
<span class="shrink-0">
<span
v-if="source.has_ready_file"
class="inline-flex items-center gap-1 rounded-full bg-emerald-50 px-2 py-0.5 text-[10px] font-bold text-emerald-700"
:data-testid="`transfer-source-status-${source.source_code}`"
>
{{ t('chat.transfer.fileReady') }}
</span>
<span
v-else-if="source.file_status === 'fetching'"
class="inline-flex items-center gap-1 rounded-full bg-amber-50 px-2 py-0.5 text-[10px] font-bold text-amber-700"
:data-testid="`transfer-source-status-${source.source_code}`"
>
{{ t('chat.transfer.fileFetching') }}
</span>
<span
v-else-if="source.file_status === 'failed'"
class="inline-flex items-center gap-1 rounded-full bg-red-50 px-2 py-0.5 text-[10px] font-bold text-red-700"
:data-testid="`transfer-source-status-${source.source_code}`"
>
{{ t('chat.transfer.fileFailed') }}
</span>
<span
v-else
class="inline-flex items-center gap-1 rounded-full bg-slate-100 px-2 py-0.5 text-[10px] font-bold text-slate-500"
:data-testid="`transfer-source-status-${source.source_code}`"
>
{{ t('chat.transfer.fileNone') }}
</span>
<button
type="button"
class="ml-1 inline-flex h-6 w-6 items-center justify-center rounded-md border border-slate-200 text-sm text-slate-500 hover:border-brand-200 hover:text-brand-700 disabled:cursor-not-allowed disabled:opacity-40"
:disabled="busy || !isRetryable(source) || retrying?.has(source.source_code)"
:title="t('chat.transfer.retryReceipt')"
:data-testid="`transfer-source-retry-${source.source_code}`"
@click.stop="emit('retry', [source.source_code])"
>
<span aria-hidden="true">{{ retrying?.has(source.source_code) ? '…' : '↻' }}</span>
</button>
</span>
</div>
</div>
</div>
<div class="flex items-center justify-end gap-3 border-t border-slate-100 pt-3">
<span class="text-xs text-slate-500">{{ $t('chat.transfer.selectedCount', { count: selectedCount }) }}</span>
<button
type="button"
class="rounded-lg bg-brand-600 px-4 py-1.5 text-sm font-bold text-white hover:bg-brand-700 disabled:cursor-not-allowed disabled:opacity-40"
:disabled="confirmDisabled"
data-testid="transfer-source-confirm"
@click="confirm"
>
{{ $t('chat.transfer.confirmScopeAndPrecheck') }}
</button>
</div>
</div>
</template>
@@ -0,0 +1,147 @@
/**
* features/chat/components/messages/transferCards.spec.ts
* 用途:验证在途调拨三张核心卡片(文件进度/预检/结果)+ 关闭弹窗的交互与禁用语义。
* 依赖:@vue/test-utils、i18n、transfer.types。
* 逻辑:断言按钮禁用、勾选禁用、ERP 单号展开/收起、异常展示、下载按钮与
* 结果页不出现“查看执行审计”入口(决策 19)。
*/
import { mount } from '@vue/test-utils';
import { describe, expect, it } from 'vitest';
import i18n from '@/i18n';
import TransferFileProgressCard from './TransferFileProgressCard.vue';
import TransferPrecheckCard from './TransferPrecheckCard.vue';
import TransferResultCard from './TransferResultCard.vue';
import TransferManualCloseDialog from './TransferManualCloseDialog.vue';
const mountOptions = { global: { plugins: [i18n] } };
const summary = {
precheck_id: 'TPC-1',
status: 'ready_to_execute',
business_date: '2026-08-06',
eligible_receipt_date_to: '2026-08-05',
expires_at: '',
counts: { file_invoice_count: 3, not_matured_count: 1, prechecked_count: 2, executable_count: 2, blocked_count: 0 },
estimated_transfer_quantity: '2400',
estimated_erp_write_count: 2,
precheck_hash: 'sha256:x',
};
const items = [
{ source_code: 'DBS-AWSBI', material_no: 'MAT-1', material_name: '连接器', specification: 'A', invoice_no: 'INV-001', from_warehouse: 'DBS-TRANSIT', from_quantity: '1200', to_warehouse: 'HUB-CN01', to_quantity: '1200', result: 'executable' },
{ source_code: 'DBS-AWSBI', material_no: 'MAT-2', material_name: '控制器', specification: 'B', invoice_no: 'INV-041', from_warehouse: '', from_quantity: null, to_warehouse: '', to_quantity: '400', result: 'not_matured' },
];
describe('TransferFileProgressCard', () => {
it('按来源显示阶段,不伪造总百分比', () => {
const wrapper = mount(TransferFileProgressCard, {
props: { sources: [
{ source_code: 'DBS-AWSBI', stage: 'file_ready', file_no: 'REC-1', file_version: 'v3' },
{ source_code: 'CRANE-SZ', stage: 'waiting_rpa_callback' },
] },
...mountOptions,
});
expect(wrapper.find('[data-testid="transfer-source-DBS-AWSBI"]').text()).toContain('REC-1');
expect(wrapper.find('[data-testid="transfer-source-CRANE-SZ"]').text()).toContain('RPA');
});
});
describe('TransferPrecheckCard', () => {
it('阻断/未成熟项 checkbox 禁用;可执行项可选', () => {
const wrapper = mount(TransferPrecheckCard, {
props: { summary, items, selected: new Set(['INV-001']) },
...mountOptions,
});
const executableCheck = wrapper.find('[data-testid="transfer-check-INV-001"]');
const maturedCheck = wrapper.find('[data-testid="transfer-check-INV-041"]');
expect((executableCheck.element as HTMLInputElement).disabled).toBe(false);
expect((maturedCheck.element as HTMLInputElement).disabled).toBe(true);
});
it('未选择任何项时生成按钮禁用', () => {
const wrapper = mount(TransferPrecheckCard, {
props: { summary, items, selected: new Set() },
...mountOptions,
});
expect((wrapper.find('[data-testid="transfer-generate-button"]').element as HTMLButtonElement).disabled).toBe(true);
});
it('busy 时生成按钮禁用', () => {
const wrapper = mount(TransferPrecheckCard, {
props: { summary, items, selected: new Set(['INV-001']), busy: true },
...mountOptions,
});
expect((wrapper.find('[data-testid="transfer-generate-button"]').element as HTMLButtonElement).disabled).toBe(true);
});
it('点击生成按钮仅提交可执行勾选项', async () => {
const wrapper = mount(TransferPrecheckCard, {
props: { summary, items, selected: new Set(['INV-001']) },
...mountOptions,
});
await wrapper.find('[data-testid="transfer-generate-button"]').trigger('click');
expect(wrapper.emitted('execute')?.[0][0]).toEqual(['INV-001']);
});
});
describe('TransferResultCard', () => {
const run = {
run_no: 'RUN-1',
status: 'partial_failed',
result: {
erp_documents: [{
document_no: 'TRF-10001',
from_warehouse: 'DBS-TRANSIT',
to_warehouse: 'HUB-CN01',
material_count: 1,
total_quantity: '1200',
posting_status: 'posted',
lines: [{ material_no: 'MAT-1', material_name: '连接器', specification: 'A', invoice_no: 'INV-001', quantity: '1200' }],
}],
exceptions: [{ source_code: 'DBS-AWSBI', invoice_no: 'INV-999', material_no: 'MAT-9', reason: 'business_failed', facts: '收料 300 / ERP 280' }],
},
};
it('按 ERP 单号聚合展示,物料明细可展开/收起', async () => {
const wrapper = mount(TransferResultCard, { props: { run }, ...mountOptions });
const doc = wrapper.find('[data-testid="transfer-erp-document"]');
expect(doc.text()).toContain('TRF-10001');
expect(doc.attributes('open')).toBeUndefined();
await doc.find('summary').trigger('click');
expect(doc.attributes('open')).toBeDefined();
expect(wrapper.find('[data-testid="transfer-erp-document-lines"]').text()).toContain('INV-001');
});
it('未生成单据异常单独展示', () => {
const wrapper = mount(TransferResultCard, { props: { run }, ...mountOptions });
expect(wrapper.find('[data-testid="transfer-exceptions-area"]').text()).toContain('INV-999');
});
it('提供两个下载按钮(收料来源文件 + ERP 库存表)', async () => {
const wrapper = mount(TransferResultCard, { props: { run }, ...mountOptions });
await wrapper.find('[data-testid="transfer-download-receipt"]').trigger('click');
await wrapper.find('[data-testid="transfer-download-erp"]').trigger('click');
expect(wrapper.emitted('downloadReceipt')).toBeTruthy();
expect(wrapper.emitted('downloadErp')).toBeTruthy();
});
it('结果页不出现“查看执行审计”入口(决策 19)', () => {
const wrapper = mount(TransferResultCard, { props: { run }, ...mountOptions });
expect(wrapper.text()).not.toContain('审计');
});
});
describe('TransferManualCloseDialog', () => {
it('原因为空时确认按钮禁用;填写后可提交', async () => {
const wrapper = mount(TransferManualCloseDialog, {
props: { open: true, invoiceNo: 'INV-001' },
...mountOptions,
});
const confirm = wrapper.find('[data-testid="transfer-close-confirm"]');
expect((confirm.element as HTMLButtonElement).disabled).toBe(true);
await wrapper.find('[data-testid="transfer-close-reason"]').setValue('线下已处理');
expect((confirm.element as HTMLButtonElement).disabled).toBe(false);
await confirm.trigger('click');
expect(wrapper.emitted('confirm')?.[0][0]).toBe('线下已处理');
});
});