Merge branch 'hugo-auto-transfer' into dev

This commit is contained in:
hugo committed 2026-10-12 21:34:33 +08:00
commit d95c4dc086
88 files changed
+5345 -406

No files matched your search

@@ -236,3 +236,27 @@ export const retryTransferSourceRpa = (sourceCode: string) =>
method: 'POST',
headers: jsonHeaders(),
});
/** 批量来源重试响应:triggered=是否写了 batch trigger;results 逐来源真实结果 */
export interface TransferRetryRpaBatchResult {
ok: boolean;
triggered: boolean;
trigger_path?: string;
error_code?: string;
results: Array<{
source_code: string;
ok: boolean;
reparsed?: boolean;
file_status?: string;
error_code?: string;
}>;
}
/** 批量重试(2026-10-09):多来源合并写一个 batch trigger 文件,
* Worker 单次浏览器会话串行导出全部来源(逐来源单文件会开/关 N 次浏览器) */
export const retryTransferSourcesRpaBatch = (sourceCodes: string[]) =>
requestJson<TransferRetryRpaBatchResult>(`${BASE}/sources/retry-rpa-batch`, {
method: 'POST',
headers: jsonHeaders(),
body: JSON.stringify({ source_codes: sourceCodes }),
});
@@ -1,12 +1,14 @@
<!--
features/chat/components/messages/TransferBacklogSummaryCard.vue
用途:待处理异常卡(可恢复/已关闭/结果未知三组)——列与匹配窗口一致,
支持关键字/结果筛选、多选批量操作(重查/恢复处理/标记无需处理)与行级快捷操作。
支持关键字/结果筛选、多选批量操作(重查/恢复/关闭)与行级快捷操作。
依赖:props.items、i18n chat.transfer.*、transferBatch.deriveBatchNo、transferFormat.formatQuantity。
逻辑:仅 blocked_recoverable 可勾选与操作;result_unknown / manually_closed 只读;
可恢复行按 result_code 细分徽标(blocked_file_removed=文件已移除);
blocked_file_removed 行行内仅留「标记无需继续处理」(重查不可恢复——消失证据
blocked_file_removed 行行内仅留「关闭」(重查不可恢复——消失证据
无法由重查翻回,唯一出口=人工关闭或等文件重新同步);
批量按钮与行内按钮同用短文案键(重查/恢复/关闭,2026-10-12 文案一致化,
完整语义经 title 悬浮),勾选计数保留;
勾选集合为卡片本地态,操作经 emit 交父组件调用批量端点并刷新。
-->
<script setup lang="ts">
@@ -157,18 +159,22 @@ function resultLabelKey(item: TransferBacklogItem): string {
class="rounded-lg border border-brand-200 bg-brand-50 px-3 py-1 text-xs font-bold text-brand-700 transition hover:bg-brand-100 disabled:cursor-not-allowed disabled:opacity-40"
data-testid="transfer-backlog-batch-resume"
:disabled="busy"
:title="$t('chat.transfer.resumeAction')"
@click="emit('resume', selectedActionableIds)"
>
{{ $t('chat.transfer.resumeAction') }}({{ selectedActionableIds.length }})
<!-- [2026-10-12 文案一致化] 批量按钮与行内按钮同用短文案键(恢复/关闭),
勾选计数保留;完整语义经 title 悬浮透出(与行内按钮同模式) -->
{{ $t('chat.transfer.resumeActionShort') }}({{ selectedActionableIds.length }})
</button>
<button
type="button"
class="rounded-lg border border-red-200 bg-red-50 px-3 py-1 text-xs font-bold text-red-600 transition hover:bg-red-100 disabled:cursor-not-allowed disabled:opacity-40"
data-testid="transfer-backlog-batch-close"
:disabled="busy"
:title="$t('chat.transfer.manualClose')"
@click="emit('batchClose', selectedActionableIds)"
>
{{ $t('chat.transfer.manualClose') }}({{ selectedActionableIds.length }})
{{ $t('chat.transfer.manualCloseShort') }}({{ selectedActionableIds.length }})
</button>
<button
type="button"
@@ -10,6 +10,7 @@
import { computed, ref } from 'vue';
import { deriveBatchNo } from './transferBatch';
import { formatQuantity } from './transferFormat';
import { parseApiUtcDate } from '@/shared/utils/dateTime';
import type { TransferMatchingItem } from '../../types/transfer.types';
const props = defineProps<{
@@ -71,10 +72,11 @@ function rowKey(item: TransferMatchingItem): string {
return `${item.item_id ?? 'na'}|${item.invoice_no}`;
}
/** 查询时刻展示(HH:mm);无 checked_at 不渲染。 */
/** 查询时刻展示(HH:mm);后端 naive ISO 按 UTC 解析后转浏览器本地时区
* (仓库约定 parseApiUtcDate,2026-09-29 修复 UTC+8 展示异常);无 checked_at 不渲染。 */
function checkedTime(item: TransferMatchingItem): string {
if (!item.checked_at) return '';
const date = new Date(item.checked_at);
const date = parseApiUtcDate(item.checked_at);
return Number.isNaN(date.getTime()) ? '' : date.toTimeString().slice(0, 5);
}
</script>
@@ -10,7 +10,7 @@ import { mount } from '@vue/test-utils';
import { describe, expect, it } from 'vitest';
import i18n from '@/i18n';
import TransferMatchCard from './TransferMatchCard.vue';
import type { TransferMatchingSummary, TransferSourceProgress } from '../../types/transfer.types';
import type { TransferMatchingItem, TransferMatchingSummary, TransferSourceProgress } from '../../types/transfer.types';
/** 最小合法匹配摘要(TransferMatchingSummary 全必填字段齐备,计数为 0) */
function buildSummary(): TransferMatchingSummary {
@@ -70,3 +70,81 @@ describe('TransferMatchCard 来源失败顶栏', () => {
expect(wrapper.find('[data-testid="transfer-match-failed-sources"]').exists()).toBe(false);
});
});
/** [2026-10-12 单据数口径修正] 预计 ERP 单据数按执行建单五元组去重。
* 行分组键 = (external_org, source_code, receipt_date, from_warehouse,
* to_warehouse),与后端 execution_service.prepare_execution 同口径:
* 同组多行执行期合并一张 ERP 单,预估数不得等于可执行行数。 */
function buildItem(overrides: Partial<TransferMatchingItem>): TransferMatchingItem {
return {
item_id: 1,
source_code: 'DBS-AWSBI',
material_no: 'MAT-001',
material_name: '连接器组件',
specification: 'A 型',
invoice_no: 'HOM-001',
receipt_date: '2026-08-05',
from_warehouse: 'DBS-TRANSIT',
from_quantity: '100',
to_warehouse: 'HUB-CN01',
to_quantity: '100',
result: 'executable',
external_org: 'HX-CN01',
...overrides,
};
}
/** 计数卡第 5 格 = 预计 ERP 单据(可执行/未成熟/阻断/数量/单据/待查/失效)。 */
function estimateCardText(wrapper: ReturnType<typeof mount>): string {
const cells = wrapper.find('[data-testid="transfer-match-counts"]').findAll('div.rounded-lg');
return cells[4]?.text() ?? '';
}
describe('TransferMatchCard 预计 ERP 单据数(五元组去重)', () => {
const sameGroupA = buildItem({ item_id: 1, invoice_no: 'HOM-001' });
const sameGroupB = buildItem({ item_id: 2, invoice_no: 'HOX-002' });
const crossDate = buildItem({ item_id: 3, invoice_no: 'HOM-003', receipt_date: '2026-08-04' });
it('计数卡:同组两行 + 跨日一行 → 预估 2(不等于可执行行数 3)', () => {
// [断言意图] 锁定五元组去重口径:receipt_date 入键,同组合并、跨组拆分,
// 历史快照旧口径(=行数)持久值不再上屏。
const wrapper = mount(TransferMatchCard, {
props: {
summary: buildSummary(),
items: [sameGroupA, sameGroupB, crossDate],
selected: new Set<number>(),
},
global: { plugins: [i18n] },
});
expect(estimateCardText(wrapper).replace(/\D/g, '')).toBe('2');
});
it('生成按钮旁预估随勾选联动:勾选同组两行仍为 1,跨组勾选后为 2', async () => {
// [断言意图] 底部预估回答「点生成会出几张单」:仅统计勾选的可执行行并
// 按五元组分组;同组两行勾选=1 张(合并),追加跨日行勾选=2 张。
const wrapper = mount(TransferMatchCard, {
props: {
summary: buildSummary(),
items: [sameGroupA, sameGroupB, crossDate],
selected: new Set<number>([1, 2]),
},
global: { plugins: [i18n] },
});
expect(wrapper.find('[data-testid="transfer-estimate-selected"]').text()).toContain(':1');
await wrapper.setProps({ selected: new Set<number>([1, 2, 3]) });
expect(wrapper.find('[data-testid="transfer-estimate-selected"]').text()).toContain(':2');
});
it('阻断行不参与预估:勾选阻断行不改变单据数', () => {
const blocked = buildItem({ item_id: 4, invoice_no: 'HOM-BLOCKED', result: 'blocked_quantity_mismatch' });
const wrapper = mount(TransferMatchCard, {
props: {
summary: buildSummary(),
items: [sameGroupA, blocked],
selected: new Set<number>([1, 4]),
},
global: { plugins: [i18n] },
});
expect(wrapper.find('[data-testid="transfer-estimate-selected"]').text()).toContain(':1');
});
});
@@ -15,13 +15,19 @@
emit execute(itemIds);来源级解析/文件失败经 sources.error_code 透出
(防"安静全 0"),但路由未解析失败(TRANSFER.ROUTE_NOT_RESOLVED)不进顶栏
——路由失败保持行级(result=blocked_route_not_resolved 行内展示),
顶栏按 error_code 客户端排除,历史卡片回放同样生效。
顶栏按 error_code 客户端排除,历史卡片回放同样生效;
[2026-10-12 单据数口径修正] 预计 ERP 单据数(计数卡=全部可执行行、
生成按钮旁=勾选可执行行)按执行建单五元组 (external_org, source_code,
receipt_date, from_warehouse, to_warehouse) 去重实时计算(与后端
execution_service 同键),同组多行合并一张单——原「=可执行行数」口径
高估单据数误导用户。
-->
<script setup lang="ts">
import { computed, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { deriveBatchNo } from './transferBatch';
import { formatQuantity } from './transferFormat';
import { parseApiUtcDate } from '@/shared/utils/dateTime';
import type { TransferMatchingItem, TransferMatchingSummary, TransferSourceProgress } from '../../types/transfer.types';
const { t } = useI18n();
@@ -143,13 +149,43 @@ const executableCheckedItemIds = computed(() =>
props.items.filter((item) => isSelectable(item) && isChecked(item)).map((item) => item.item_id as number),
);
/** [2026-10-12 单据数口径修正] 执行建单五元组键(与后端 execution_service.
* prepare_execution 分组建单同键同 .trim() 规范化):(external_org, source_code,
* receipt_date, from_warehouse, to_warehouse),同组多行执行期合并一张 ERP 单。
* 老卡片行缺 external_org 按 '' 参与(分组退化为四元组,仅跨组织同仓库配置下有差异)。 */
function documentGroupKey(item: TransferMatchingItem): string {
return [
(item.external_org ?? '').trim(),
(item.source_code ?? '').trim(),
(item.receipt_date ?? '').trim(),
(item.from_warehouse ?? '').trim(),
(item.to_warehouse ?? '').trim(),
].join('\u001f');
}
/** 预计 ERP 单据数(计数卡):全部可执行行按五元组去重的组数。客户端实时计算,
* 使历史快照中旧口径(=可执行行数)的持久化估计值不再上屏误导。 */
const estimatedDocumentCountAll = computed(
() => new Set(props.items.filter((item) => item.result === 'executable').map(documentGroupKey)).size,
);
/** 预计 ERP 单据数(生成按钮旁):按当前勾选的可执行行分组计数,回答
* 「点生成会出几张单」;未勾选为 0。 */
const estimatedDocumentCountSelected = computed(
() => new Set(
props.items.filter((item) => item.result === 'executable' && isChecked(item)).map(documentGroupKey),
).size,
);
/**
* 库存查询时刻小字(HH:mm);无效/缺省 checked_at 返回 null 不渲染。
* 库存查询时刻小字(HH:mm);后端 naive ISO 按 UTC 解析后转浏览器本地时区
* (仓库约定 parseApiUtcDate,2026-09-29 修复 UTC+8 展示异常);
* 无效/缺省 checked_at 返回 null 不渲染。
* @param item 匹配明细行;checked_at 为后端 ISO 时间
*/
function checkedAtLabel(item: TransferMatchingItem): string | null {
if (!item.checked_at) return null;
const date = new Date(item.checked_at);
const date = parseApiUtcDate(item.checked_at);
if (Number.isNaN(date.getTime())) return null;
const hh = String(date.getHours()).padStart(2, '0');
const mm = String(date.getMinutes()).padStart(2, '0');
@@ -217,7 +253,9 @@ function reasonTitle(item: TransferMatchingItem): string | undefined {
<div class="text-[11px] text-muted">{{ $t('chat.transfer.estimatedQuantity') }}</div>
</div>
<div class="rounded-lg bg-surface-soft p-2 text-center">
<div class="text-lg font-black text-brand-600">{{ summary.estimated_external_write_count }}</div>
<!-- [2026-10-12 单据数口径修正] 按执行建单五元组去重(客户端计算),
不再透传旧口径持久值(=可执行行数)——同组多行合并一张 ERP 单 -->
<div class="text-lg font-black text-brand-600">{{ estimatedDocumentCountAll }}</div>
<div class="text-[11px] text-muted">{{ $t('chat.transfer.estimatedExternalWrites') }}</div>
</div>
<!-- 待查库存:文件已落地、尚未查过 ERP 库存的行数(历史回放缺省 0) -->
@@ -390,9 +428,10 @@ function reasonTitle(item: TransferMatchingItem): string | undefined {
</div>
<div class="mt-3 flex items-center justify-end gap-3 border-t border-subtle pt-3">
<span class="text-xs text-muted">
<span class="text-xs text-muted" data-testid="transfer-estimate-selected">
{{ $t('chat.transfer.selectedCount', { count: selectedCount }) }} ·
{{ $t('chat.transfer.estimatedExternalWrites') }}:{{ summary.estimated_external_write_count }}
<!-- [2026-10-12 单据数口径修正] 随勾选联动:按勾选可执行行五元组分组计数 -->
{{ $t('chat.transfer.estimatedExternalWrites') }}:{{ estimatedDocumentCountSelected }}
</span>
<button
type="button"
@@ -385,9 +385,13 @@ 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);
// 多来源一次批量端点(合并单 batch trigger,Worker 单次浏览器会话串行导出);
// 单来源沿用原接口(行级 ↻ 一源一文件语义不变)。
const [first, ...rest] = codes;
if (rest.length > 0) {
await transfer.retrySourcesRpaBatch(codes);
} else if (first !== undefined) {
await transfer.retrySourceRpa(first);
}
} catch (e) {
reportError(e);
@@ -4,8 +4,8 @@
* 确认提交、重试收料 RPA。
* 依赖:@vue/test-utils、i18n。
* 逻辑:平台 DBS/Crane 仅分组;实例为选择与执行边界(决策 2/3/4);
* 确认需至少一个 has_ready_file(兜底告警),提交范围静默过滤为 ready-only
* (无 ready 文件的勾选项不进匹配,2026-09-29 来源错误分层);
* 确认需至少一个 has_ready_file(兜底告警);混合选择(含非就绪项)先披露范围
* 再确认(知情部分确认 2026-10-09,替代历史静默剔除),提交范围 ready-only;
* 重试门禁=仅 fetching 在途不可重试(ready 亦可强制重抓,2026-09-29 去管控)。
*/
import { mount } from '@vue/test-utils';
@@ -54,18 +54,21 @@ describe('TransferSourceSelectCard', () => {
expect(wrapper.emitted('confirm')).toBeUndefined();
});
it('“全选可见”勾选全部启用实例,确认时静默剔除无 ready 文件来源', async () => {
// [断言意图] 门禁新语义:有 ready 文件的勾选项照常放行,无 ready 文件的勾选项
// (DBS-AWSSG none)静默剔除——确认范围只含可执行来源,不再整包提交。
it('“全选可见”勾选全部启用实例,混合选择先披露再确认 ready-only', async () => {
// [断言意图] 知情部分确认(2026-10-09):混合选择(2 ready + 1 none)点确认先出现
// 披露条且不提交;披露后确认只携带具备 ready 文件的来源码。
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.find('[data-testid="transfer-source-partial-confirm"]').exists()).toBe(true);
expect(wrapper.emitted('confirm')).toBeUndefined();
await wrapper.find('[data-testid="transfer-source-partial-proceed"]').trigger('click');
expect(wrapper.emitted('confirm')?.[0][0]).toEqual(['DBS-AWSBI', 'CRANE-SZ']);
});
it('勾选 ready+parse_failed 确认时只提交 ready 来源', async () => {
it('勾选 ready+parse_failed 先披露,披露后确认只提交 ready 来源', async () => {
// [断言意图] 解析失败来源(has_ready_file=false)勾选后不阻断确认,
// 但确认事件只携带具备 ready 文件的来源码。
// 但须经披露条确认,确认事件只携带具备 ready 文件的来源码。
const sources = [
{ source_code: 'DSV-OK', display_name: 'ok', platform: 'dbs', enabled: true, has_ready_file: true, file_status: 'ready' as const },
{ source_code: 'DSV-BAD', display_name: 'bad', platform: 'dbs', enabled: true, has_ready_file: false, file_status: 'parse_failed' as const },
@@ -74,9 +77,64 @@ describe('TransferSourceSelectCard', () => {
await wrapper.find('[data-testid="transfer-source-option-DSV-OK"] input').setValue(true);
await wrapper.find('[data-testid="transfer-source-option-DSV-BAD"] input').setValue(true);
await wrapper.find('[data-testid="transfer-source-confirm"]').trigger('click');
expect(wrapper.emitted('confirm')).toBeUndefined();
await wrapper.find('[data-testid="transfer-source-partial-proceed"]').trigger('click');
expect(wrapper.emitted('confirm')?.[0][0]).toEqual(['DSV-OK']);
});
it('混合选择披露条展示可匹配/暂不可匹配计数与状态分组', async () => {
// [断言意图] 披露必须让「抓取中」与「真失败」可区分:摘要含三段计数,
// 分组明细含「抓取中 1」——用户知情后再决定是否仅匹配就绪来源。
const sources = [
{ source_code: 'DSV-OK', display_name: 'ok', platform: 'dbs', enabled: true, has_ready_file: true, file_status: 'ready' as const },
{ source_code: 'DSV-FETCH', display_name: 'fetching', platform: 'dbs', enabled: true, has_ready_file: false, file_status: 'fetching' as const },
];
const wrapper = mountCard({}, sources);
await wrapper.find('[data-testid="transfer-source-option-DSV-OK"] input').setValue(true);
await wrapper.find('[data-testid="transfer-source-option-DSV-FETCH"] input').setValue(true);
await wrapper.find('[data-testid="transfer-source-confirm"]').trigger('click');
const summary = wrapper.find('[data-testid="transfer-source-partial-summary"]').text();
expect(summary).toContain('可匹配 1 个');
expect(summary).toContain('暂不可匹配 1 个');
expect(summary).toContain('抓取中 1');
});
it('披露后「取消」收回披露条且不提交,确认按钮还原', 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-DBS-AWSSG"] input').setValue(true);
await wrapper.find('[data-testid="transfer-source-confirm"]').trigger('click');
expect(wrapper.find('[data-testid="transfer-source-partial-confirm"]').exists()).toBe(true);
await wrapper.find('[data-testid="transfer-source-partial-cancel"]').trigger('click');
expect(wrapper.find('[data-testid="transfer-source-partial-confirm"]').exists()).toBe(false);
expect(wrapper.find('[data-testid="transfer-source-confirm"]').exists()).toBe(true);
expect(wrapper.emitted('confirm')).toBeUndefined();
});
it('披露展示期间调整勾选即收回披露(旧口径失效)', 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-DBS-AWSSG"] input').setValue(true);
await wrapper.find('[data-testid="transfer-source-confirm"]').trigger('click');
expect(wrapper.find('[data-testid="transfer-source-partial-confirm"]').exists()).toBe(true);
await wrapper.find('[data-testid="transfer-source-option-DBS-AWSSG"] input').setValue(false);
expect(wrapper.find('[data-testid="transfer-source-partial-confirm"]').exists()).toBe(false);
expect(wrapper.emitted('confirm')).toBeUndefined();
});
it('全就绪选择不出现披露,确认直达提交', 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.find('[data-testid="transfer-source-partial-confirm"]').exists()).toBe(false);
expect(wrapper.emitted('confirm')?.[0][0]).toEqual(['DBS-AWSBI', 'CRANE-SZ']);
});
it('parse_failed 显示解析失败徽标且可重试', async () => {
// [断言意图] 当日收料文件解析失败(file_status=parse_failed)不得误报就绪;
// 与 none/failed/expired 一样允许重新触发收料 RPA。
@@ -180,6 +238,16 @@ describe('TransferSourceSelectCard', () => {
expect(wrapper.emitted('retry')?.[0][0]).toEqual(['DBS-AWSBI', 'DBS-AWSSG', 'CRANE-SZ']);
});
it('空数据来源显示「无收料数据」徽标而非抓取失败', async () => {
// [断言意图] 抓取成功但当日无收料记录(file_status=no_data)属业务结果,
// 必须如实展示"无收料数据",不得与"抓取失败"混淆(2026-10-08 PRD01 误标事故)。
const wrapper = mountCard({}, [
{ source_code: 'CRANE-NODATA', display_name: '空数据在途仓', platform: 'crane', enabled: true, has_ready_file: false, file_status: 'no_data' },
]);
expect(wrapper.find('[data-testid="transfer-source-status-CRANE-NODATA"]').text()).toBe('无收料数据');
expect((wrapper.find('[data-testid="transfer-source-retry-CRANE-NODATA"]').element as HTMLButtonElement).disabled).toBe(false);
});
it('已过期来源显示「文件已过期」徽标且可重试', async () => {
// [断言意图] 保留期已到的来源不得误报就绪(has_ready_file=false);
// expired 状态与 none/failed 一样允许重新触发收料 RPA。
@@ -6,14 +6,15 @@
逻辑:匹配参数区(调拨类型 + 收料日期,确认时一并提交)→ 选择辅助/上下文操作条
(有选中时原位替换辅助区,承载批量重试/下载/清空选择)→ 平台分组来源列表
(平台仅分组不可直接执行)→ 底部唯一实心主按钮「确认范围并匹配」(未选禁用);
确认只提交具备 ready 文件的来源(勾选的无 ready 项如 parse_failed/none 静默剔除,
门禁「至少一 ready」保留为兜底告警);重试除抓取中(fetching)外均可触发
确认只提交具备 ready 文件的来源:混合选择(含非就绪项)先披露范围再确认
(知情部分确认 2026-10-09,替代历史静默剔除),全就绪直达;
门禁「至少一 ready」保留为兜底告警;重试除抓取中(fetching)外均可触发
(ready 亦可强制重抓,2026-09-29 去管控),徽标独立文案;
调拨类型决定收料数据范围(类型 1 仅纳入 INVOICE 前缀 HOM/HOX/WTP),
类型 2/3 一期占位(禁用,后端同样 fail-closed)。
-->
<script setup lang="ts">
import { computed, ref } from 'vue';
import { computed, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { useMessage } from '@/shared/composables/useMessage';
import { eligibleReceiptDateTo } from './transferDate';
@@ -89,6 +90,37 @@ const confirmDisabled = computed(() =>
);
const downloadDisabled = computed(() => props.busy || !selectedHasReadyFile.value);
// ---- [知情部分确认 2026-10-09] 混合选择(含非就绪项)先披露范围再确认,替代历史静默剔除 ----
/** 披露条可见性:仅在「已选含就绪 + 非就绪」混合状态点确认后出现。 */
const showPartialConfirm = ref(false);
/** 已选来源中具备 ready 文件的数量。 */
const selectedReadyCount = computed(() =>
[...selected.value].filter((code) => props.sources.find((s) => s.source_code === code)?.has_ready_file).length,
);
const selectedUnreadyCount = computed(() => selectedCount.value - selectedReadyCount.value);
/** 非就绪状态分组展示顺序:先在途(fetching)后终态。 */
const unreadyStatusOrder = ['fetching', 'failed', 'parse_failed', 'no_data', 'expired', 'none'] as const;
/** 非就绪状态 → 徽标文案 key(复用既有状态徽标词汇,披露条逐组计数)。 */
const UNREADY_STATUS_LABEL_KEYS: Record<(typeof unreadyStatusOrder)[number], string> = {
fetching: 'chat.transfer.fileFetching',
failed: 'chat.transfer.fileFailed',
parse_failed: 'chat.transfer.fileParseFailed',
no_data: 'chat.transfer.fileNoData',
expired: 'chat.transfer.fileExpired',
none: 'chat.transfer.fileNone',
};
/** 非就绪来源按状态分组计数(固定顺序),让「抓取中」与「真失败」可区分。 */
const unreadyBreakdownText = computed(() => unreadyStatusOrder
.map((status) => ({
status,
count: [...selected.value].filter(
(code) => props.sources.find((s) => s.source_code === code)?.file_status === status,
).length,
}))
.filter((item) => item.count > 0)
.map((item) => `${t(UNREADY_STATUS_LABEL_KEYS[item.status])} ${item.count}`)
.join(' · '));
function toggle(sourceCode: string, checked: boolean) {
const next = new Set(selected.value);
if (checked) next.add(sourceCode);
@@ -141,23 +173,49 @@ function downloadSelected(): void {
if (codes.length) emit('download', codes);
}
/** 确认范围并匹配:只提交具备 ready 文件的来源;无 ready 文件的勾选项(如 parse_failed/none)
* 静默剔除(历史上是「至少一 ready 则整包提交」,会把不可执行来源带进匹配);
* 「至少一 ready」门禁保留为兜底告警(全部无 ready 时拦截)。 */
/** 确认范围并匹配:只提交具备 ready 文件的来源。混合选择(含非就绪项)先展示披露条
* (知情部分确认 2026-10-09,替代历史「至少一 ready 则静默剔除整包」),用户确认后
* 才提交 ready-only;全就绪直达。「至少一 ready」门禁保留为兜底告警。 */
function confirm() {
if (selectedCount.value === 0) {
notifyWarning(t('chat.transfer.needSelectSource'), t('chat.transfer.sourceSelectTitle'));
return;
}
const readyCodes = [...selected.value].filter(
(code) => props.sources.find((s) => s.source_code === code)?.has_ready_file,
);
const readyCodes = selectedReadyCodes();
if (readyCodes.length === 0) {
notifyWarning(t('chat.transfer.needReadyFile'), t('chat.transfer.sourceSelectTitle'));
return;
}
if (selectedUnreadyCount.value > 0) {
showPartialConfirm.value = true;
return;
}
emit('confirm', readyCodes, { from: dateFrom.value || undefined, to: dateTo.value || undefined }, transferType.value);
}
/** 已选来源中的 ready 来源码(每次 emit 时现算,避免披露期间勾选变化导致口径过期)。 */
function selectedReadyCodes(): string[] {
return [...selected.value].filter(
(code) => props.sources.find((s) => s.source_code === code)?.has_ready_file,
);
}
/** 披露后确认:仅提交就绪来源(其余来源就绪后可重新匹配补入,后端增量圈行不破坏已有行)。 */
function proceedPartialConfirm() {
const readyCodes = selectedReadyCodes();
showPartialConfirm.value = false;
emit('confirm', readyCodes, { from: dateFrom.value || undefined, to: dateTo.value || undefined }, transferType.value);
}
/** 披露后取消:收回披露条,可调整勾选或等待其余来源就绪。 */
function cancelPartialConfirm() {
showPartialConfirm.value = false;
}
// 勾选变化即收回披露:用户在调整范围,旧披露口径已失效。
watch(selected, () => {
showPartialConfirm.value = false;
});
</script>
<template>
@@ -278,7 +336,10 @@ function confirm() {
</span>
</div>
<div v-for="platform in platforms" :key="platform" class="mb-3 rounded-lg border border-subtle">
<!-- [ZONE 3] 来源列表:上限随视口伸缩(60vh)而非固定值——来源多时列表尽量占满可用高度再内部滚动,
避免固定小限高把列表压成几行+卡片下方大量留白;来源少时卡片自然收缩不受影响 -->
<div class="max-h-[60vh] space-y-3 overflow-y-auto" data-testid="transfer-source-list">
<div v-for="platform in platforms" :key="platform" class="rounded-lg border border-subtle">
<div class="flex items-center justify-between rounded-t-lg bg-surface-soft px-3 py-1.5">
<b class="text-xs text-secondary">{{ platform.toUpperCase() }}</b>
<label class="text-[11px] text-muted">
@@ -329,6 +390,14 @@ function confirm() {
>
{{ t('chat.transfer.fileFailed') }}
</span>
<!-- 无收料数据(no_data):抓取成功但当日无收料记录,属业务结果而非故障;当日稍后到货可重抓补数 -->
<span
v-else-if="source.file_status === 'no_data'"
class="inline-flex items-center gap-1 rounded-full bg-sky-50 px-2 py-0.5 text-[10px] font-bold text-sky-700"
:data-testid="`transfer-source-status-${source.source_code}`"
>
{{ t('chat.transfer.fileNoData') }}
</span>
<span
v-else-if="source.file_status === 'expired'"
class="inline-flex items-center gap-1 rounded-full bg-orange-50 px-2 py-0.5 text-[10px] font-bold text-orange-700"
@@ -365,9 +434,42 @@ function confirm() {
</div>
</div>
</div>
</div>
<div class="flex items-center justify-end border-t border-subtle pt-3">
<!-- [知情部分确认] 混合状态点确认后按钮区原位替换为披露条(同槽位切换惯例):
明确本次仅纳入就绪来源、逐状态分组展示未就绪项,用户显式确认后才提交。 -->
<div
v-if="showPartialConfirm"
class="flex w-full flex-col gap-1.5 rounded-lg border border-amber-200 bg-amber-50 px-3 py-2"
data-testid="transfer-source-partial-confirm"
>
<p class="text-xs font-bold text-amber-700" data-testid="transfer-source-partial-summary">
{{ $t('chat.transfer.partialConfirmSummary', { total: selectedCount, ready: selectedReadyCount, unready: selectedUnreadyCount }) }}
<span v-if="unreadyBreakdownText" class="font-normal">{{ $t('chat.transfer.partialConfirmBreakdown', { items: unreadyBreakdownText }) }}</span>
</p>
<p class="text-xs text-amber-700">{{ $t('chat.transfer.partialConfirmHint') }}</p>
<div class="flex items-center justify-end gap-2">
<button
type="button"
class="rounded-lg border border-default px-3 py-1.5 text-xs font-bold text-secondary hover-surface-soft"
data-testid="transfer-source-partial-cancel"
@click="cancelPartialConfirm"
>
{{ $t('chat.transfer.partialConfirmCancel') }}
</button>
<button
type="button"
class="rounded-lg bg-brand-600 px-4 py-1.5 text-xs font-bold text-white hover:bg-brand-700"
data-testid="transfer-source-partial-proceed"
@click="proceedPartialConfirm"
>
{{ $t('chat.transfer.partialConfirmProceed') }}
</button>
</div>
</div>
<button
v-else
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"
@@ -5,6 +5,9 @@
逻辑:主卡内部 section = 「当前阶段/状态/正式OT → 下一步 → 动作区」;
状态文案严格绑定 user_status;blocking_reason 只作下一步问题说明;按钮显隐由后端 retryable + primary_action.parameters 决定;
主动作按钮文案 fail-closed:后端下发动作码但无受控 i18n 文案时整体隐藏该按钮(含图标),禁止渲染无文字裸按钮;
阶段能力禁用态:视图层把 preparation.capabilities 的 disabled_reason 并进动作对象
(capabilityDisabledReason),命中时按钮渲染 disabled + 原因 tooltip(capabilityDisabled 命名空间),
与 submitFormalGateAction 的点击拦截同源(展示=执行同源),禁止可点样式诱导用户点击后才被拦截;
loading 仅代表「权威投影读取中」而非系统运行态:已知阶段/状态/阻断仍照常展示
(与投影同源或后端 automation 运行态),空态自然落到「待机/状态待确认」,
禁止把读取占位误述为「系统处理中」,也不做骨架→真值的二次刷新;
@@ -45,12 +48,17 @@ const props = defineProps<{
| null;
retryable?: boolean;
blockingReason?: ShippingProcessingBlockingReason | null;
primaryAction?: ShippingProcessingPrimaryAction | null;
primaryAction?: (ShippingProcessingPrimaryAction & {
/** 阶段能力禁用原因(视图层从 preparation.capabilities 并入);非空=按钮渲染禁用态。 */
capabilityDisabledReason?: string | null;
}) | null;
recoveryActions?: Array<{
code: string;
i18nKey?: string | null;
label_key?: string | null;
parameters?: Record<string, unknown>;
/** 阶段能力禁用原因(视图层从 preparation.capabilities 并入);非空=按钮渲染禁用态。 */
capabilityDisabledReason?: string | null;
}>;
/** 正式 Gate 原始状态仅用于区分未入队、运行中与外部回执等待;不参与按钮裁决。 */
gateStatus?: string | null;
@@ -296,6 +304,11 @@ const businessActionLabel = computed(() => {
});
const businessActionTitle = computed(() => {
// 能力禁用原因优先于重试中提示:禁用态按钮的 tooltip 必须解释"为什么不可点"。
const capabilityText = capabilityDisabledText(
props.primaryAction ? capabilityDisabledReasonOf(props.primaryAction) : null,
);
if (capabilityText) return capabilityText;
const retryingFlag = Boolean(props.retrying);
if (retryingFlag) {
return t('chat.shippingOrderReview.currentTask.actionRetryRunningTooltip');
@@ -305,6 +318,29 @@ const businessActionTitle = computed(() => {
const actionIsRetry = computed(() => String(props.primaryAction?.code || '').trim().startsWith('retry_'));
const actionIsInventoryRpa = computed(() => String(props.primaryAction?.code || '').trim() === 'retry_inventory_preparation');
/**
* 阶段能力禁用态裁决:与视图层 submitFormalGateAction 的点击拦截同源(展示=执行同源)。
* 核心逻辑:视图层把 preparation.capabilities 的 disabled_reason 并进动作对象;本卡只负责
* 渲染禁用态与原因 tooltip,不自行推断业务能力。原因文案复用 capabilityDisabled 命名空间,
* 未登记的 reason fail-closed 禁用但不给 tooltip(禁止裸露内部原因码)。
*/
function capabilityDisabledReasonOf(action: { capabilityDisabledReason?: string | null }): string | null {
const reason = String(action.capabilityDisabledReason || '').trim();
return reason || null;
}
function capabilityDisabledText(reason: string | null | undefined): string {
const normalized = String(reason || '').trim();
if (!normalized) return '';
const key = `chat.shippingOrderReview.lifecycle.prepare.capabilityDisabled.${normalized}`;
return te(key) ? t(key) : '';
}
const businessActionCapabilityDisabled = computed(() => (
Boolean(props.primaryAction && capabilityDisabledReasonOf(props.primaryAction))
));
const recoveryActions = computed(() => (props.recoveryActions || []).filter((action) => {
const code = String(action.code || '').trim();
if (!code || isNonTaskCapabilityAction(code) || isInternalInventoryAction(code)) return false;
@@ -329,6 +365,8 @@ function recoveryActionLabel(action: (typeof recoveryActions.value)[number]): st
}
function handleBusinessActionClick() {
// 能力禁用态兜底:disabled 按钮通常不派发 click,此处防御键盘等旁路触发。
if (businessActionCapabilityDisabled.value) return;
const primaryActionCode = String(props.primaryAction?.code || '').trim();
if (!primaryActionCode || primaryActionCode === 'retry') return;
emit('action', primaryActionCode, props.primaryAction?.parameters ?? {});
@@ -464,9 +502,10 @@ type ReviewCurrentUserStatus =
<button
v-if="showBusinessAction"
type="button"
class="inline-flex items-center gap-1 rounded-md bg-sky-700 px-3 py-1.5 text-xs font-medium text-white shadow-sm transition hover:bg-sky-800 disabled:opacity-50 dark:bg-sky-600 dark:hover:bg-sky-500"
class="inline-flex items-center gap-1 rounded-md bg-sky-700 px-3 py-1.5 text-xs font-medium text-white shadow-sm transition hover:bg-sky-800 disabled:opacity-50 disabled:cursor-not-allowed dark:bg-sky-600 dark:hover:bg-sky-500"
:data-testid="actionIsRetry ? 'review-current-processing-retry' : 'review-current-task-primary-action'"
:disabled="retrying || locating"
:data-capability-disabled="businessActionCapabilityDisabled ? 'true' : undefined"
:disabled="retrying || locating || businessActionCapabilityDisabled"
:title="businessActionTitle"
@click="handleBusinessActionClick"
>
@@ -482,9 +521,11 @@ type ReviewCurrentUserStatus =
v-for="action in recoveryActions"
:key="action.code"
type="button"
class="inline-flex items-center gap-1 rounded-md border border-sky-300 bg-surface px-2.5 py-1.5 text-xs font-medium text-sky-800 shadow-sm transition hover:bg-sky-50 disabled:opacity-50 dark:border-sky-700 dark:bg-sky-900 dark:text-sky-100 dark:hover:bg-sky-800"
class="inline-flex items-center gap-1 rounded-md border border-sky-300 bg-surface px-2.5 py-1.5 text-xs font-medium text-sky-800 shadow-sm transition hover:bg-sky-50 disabled:opacity-50 disabled:cursor-not-allowed dark:border-sky-700 dark:bg-sky-900 dark:text-sky-100 dark:hover:bg-sky-800"
:data-testid="`review-current-task-recovery-${action.code}`"
:disabled="retrying || locating"
:data-capability-disabled="capabilityDisabledReasonOf(action) ? 'true' : undefined"
:disabled="retrying || locating || Boolean(capabilityDisabledReasonOf(action))"
:title="capabilityDisabledText(capabilityDisabledReasonOf(action))"
@click="$emit('action', action.code, action.parameters || {})"
>
{{ recoveryActionLabel(action) }}
@@ -35,6 +35,7 @@ import {
manualCloseTransferItem,
retryTransferItem,
retryTransferSourceRpa,
retryTransferSourcesRpaBatch,
} from '../api/transfer.api';
import type {
TransferBacklogItem,
@@ -458,6 +459,15 @@ export function useChatTransfer() {
return status;
}
/** 批量来源重试:一次批量端点调用(多来源合并单 batch trigger,Worker 单次浏览器
* 会话串行导出;逐来源循环会产生 N 个文件、开/关 N 次浏览器),随后刷新来源状态
* (loadSources 观察到 fetching 自动开始轮询)。 */
async function retrySourcesRpaBatch(sourceCodes: string[]) {
const result = await retryTransferSourcesRpaBatch(sourceCodes);
await loadSources();
return result;
}
/** 加载待处理异常列表与汇总 */
async function loadBacklog() {
const [items, summary] = await Promise.all([listTransferBacklog(), getTransferBacklogSummary()]);
@@ -559,6 +569,7 @@ export function useChatTransfer() {
manualClose,
loadSources,
retrySourceRpa,
retrySourcesRpaBatch,
loadBacklog,
loadBacklogSummary,
loadExecutableItems,
@@ -1529,6 +1529,8 @@ export interface ShippingTaskUiState {
part_number?: string | null;
required_qty?: string | number | null;
available_qty?: string | number | null;
/** 料号维度总可用量(忽略预约号、行允许源内汇总);无快照/未就绪为 null。 */
part_available_qty?: string | null;
shortage_qty?: string | number | null;
/** Match 正式匹配源;未匹配时为空,禁止用候选回填。 */
source_code?: string | null;
@@ -67,6 +67,9 @@ export interface TransferMatchingItem {
stale?: boolean;
/** 行评估所用收料文件版本与来源最新可用文件是否一致;false = 文件已更新需重新匹配 */
file_current?: boolean;
/** [2026-10-12 单据数口径修正] 执行建单五元组首键(路由解析所得外部组织);
* 匹配评估路径透出,历史回放缺省——预估 ERP 单据数按五元组去重的分组输入 */
external_org?: string;
}
/** 来源实例级进度(决策 18:来源隔离展示) */
@@ -246,7 +249,7 @@ export interface TransferSourceOption {
platform: string;
enabled: boolean;
/** 收料文件状态:ready / fetching / failed / parse_failed / expired / none(只读投影货代收料事实;parse_failed=当日可用收料文件解析失败) */
file_status?: 'ready' | 'fetching' | 'failed' | 'parse_failed' | 'expired' | 'none';
file_status?: 'ready' | 'fetching' | 'failed' | 'no_data' | 'parse_failed' | 'expired' | 'none';
/** 是否已有当前可用的收料文件(门禁:无 ready 文件禁止确认匹配) */
has_ready_file?: boolean;
file_no?: string | null;
@@ -256,7 +259,7 @@ export interface TransferSourceOption {
/** 来源收料文件状态(门禁 + 状态标识 + 重试返回) */
export interface TransferSourceFileStatus {
source_code: string;
file_status: 'ready' | 'fetching' | 'failed' | 'parse_failed' | 'expired' | 'none';
file_status: 'ready' | 'fetching' | 'failed' | 'no_data' | 'parse_failed' | 'expired' | 'none';
has_ready_file: boolean;
file_no?: string | null;
file_sha256?: string | null;
@@ -701,8 +701,13 @@ async function mountView(query: Record<string, string> = {}) {
releaseShortageHint: '放行后本次发货按缺口处理。',
releaseReasonPlaceholder: '可填写放行原因(选填)',
releaseConfirm: '确认放行',
reservedQty: '预约数量',
partAvailableQty: '可用数量',
shortage: '库存不足',
pending: '库存匹配或通知文件尚未生成。',
capabilityDisabled: {
no_match_result: '暂无库存匹配结果,请先重新获取库存',
},
},
uploadComplete: {
title: '通知完成',
@@ -759,6 +764,8 @@ async function mountView(query: Record<string, string> = {}) {
actionCodes: {
confirm_customer: '确认客户',
resolve_field_conflicts: '处理字段冲突',
retry_inventory_preparation: '重新获取库存',
retry_inventory_matching: '重新匹配库存',
},
},
},
@@ -1620,6 +1627,81 @@ describe('ShippingOrderReviewView layout phase 1', () => {
);
});
it('renders capability-disabled actions as disabled buttons with reason tooltip', async () => {
// 回归(展示=执行同源):A 渲染的 retry_inventory_matching 命中阶段能力 disabled
// (no_match_result)时,右卡必须直接渲染禁用态 + 原因 tooltip;
// 禁止可点样式诱导用户点击后才被 submitFormalGateAction 弹提示拦截。
activeCase.value = {
...activeCase.value,
status: 'confirmed', has_formal_ot: true, task_missing: false,
confirmed_task_id: 906, confirmed_task_no: 'SN-RPA-CAP-DISABLED',
};
shippingProcessingProjection.value = {
workItemType: 'order_task', workItemNo: 'SN-RPA-CAP-DISABLED',
status: 'failed', userStatus: 'retryable', stage: 'inventory_fetching',
progressVersion: 5, currentGate: { status: 'blocked_retryable' },
uiState: {
status: 'retryable', stage: 'inventory_fetching', lifecycleStage: 'fulfillment_prep',
primary_action: { code: 'retry_inventory_matching' },
secondary_actions: [{ code: 'retry_inventory_preparation', enabled: true }],
},
} as any;
const taskApi = await import('@/features/chat/api/shipping.api');
vi.mocked(taskApi.getWorkspaceShippingTask).mockResolvedValue({
task_no: 'SN-RPA-CAP-DISABLED', status: 'processing', lines: [], events: [],
ui_state: {
actions: { primary: null, secondary: [] },
process_gate: {
execution_no: 'EXEC-RPA-CAP-DISABLED',
current_blocking_gate: {
gate_code: 'inventory_preparation', evaluation_version: 2, status: 'blocked_retryable',
},
allowed_actions: ['retry_inventory_matching', 'retry_inventory_preparation'],
},
stage_context: {
preparation: {
status: 'blocked', source_locked: false,
source_options: [{ source_code: 'DSV' }],
failed_source_codes: ['DSV'],
capabilities: [
{
code: 'retry_inventory_matching', scope: 'task',
action_code: 'retry_inventory_matching', enabled: false,
disabled_reason: 'no_match_result',
},
{
code: 'retry_inventory_preparation', scope: 'task',
action_code: 'retry_inventory_preparation', enabled: true,
disabled_reason: null,
},
],
frozen_order_lines: [], lines: [],
},
},
summary: {}, steps: [],
},
} as any);
submitProcessGatePrimaryActionMock.mockClear();
messageMocks.info.mockClear();
const wrapper = await mountView({ lifecycle_stage: 'fulfillment_prep' });
await flushPromises();
// 主按钮:能力禁用 → disabled + 原因 tooltip(复用 capabilityDisabled.no_match_result 文案)。
const primary = wrapper.get('[data-testid="review-current-processing-retry"]');
expect(primary.attributes('disabled')).toBeDefined();
expect(primary.attributes('data-capability-disabled')).toBe('true');
expect(primary.attributes('title')).toContain('暂无库存匹配结果');
// 侧路按钮:能力 enabled → 保持可点,不受主按钮禁用影响。
const recovery = wrapper.get('[data-testid="review-current-task-recovery-retry_inventory_preparation"]');
expect(recovery.attributes('disabled')).toBeUndefined();
// 点击禁用按钮不得触发提交,也不得弹任何 info 提示(此前会弹未翻译 key)。
await primary.trigger('click');
await flushPromises();
expect(submitProcessGatePrimaryActionMock).not.toHaveBeenCalled();
expect(messageMocks.info).not.toHaveBeenCalled();
});
it('refreshes the processing projection after field-conflict adjudication refreshes the Case', async () => {
activeCase.value = {
...activeCase.value,
@@ -2022,6 +2104,65 @@ describe('ShippingOrderReviewView layout phase 1', () => {
}
});
it('does not auto-advance when switching formal-downstream files without an activeCase identity', async () => {
// 回归:正式下游(通知准备/货代上传/通知完成,选法 2)activeCase 刻意为 null,
// 切换前后 activeCase 身份(case_no/document_id)恒为空值;自动推进守卫若用
// activeCase 做“同一文件”判据,会把目标文件更晚的阶段误判成当前文件被推进,
// 弹出“已自动推进到货代上传”。文件身份必须用 requestedCaseNo(与阶段解析同源,
// selectCase/beginCrossRunSwitch 同步块内更新):切换必变更 → 静默;真实推进
// 不触碰 requestedCaseNo → 提示行为不变。
const originalQueue = reviewQueue.value;
try {
reviewQueue.value = {
...reviewQueue.value,
summary: { total: 2, needs_action: 2, processing: 0, completed: 0 },
items: [
{
...reviewQueue.value.items[0],
has_formal_ot: true,
lifecycle_stage: 'fulfillment_prep',
lifecycle_entries: [
{ code: 'order_review', state: 'available', targetSurface: 'order_lifecycle_workbench' },
{ code: 'fulfillment_prep', state: 'current', targetSurface: 'order_lifecycle_workbench' },
{ code: 'freight_upload', state: 'unavailable', targetSurface: 'order_lifecycle_workbench' },
{ code: 'upload_complete', state: 'unavailable', targetSurface: 'order_lifecycle_workbench' },
],
},
{
case_no: 'CASE-2', source_run_no: 'RUN-1', document_id: 2, file_name: 'po-2.pdf',
status: 'confirmed', has_formal_ot: true, issue_count: 0,
lifecycle_stage: 'freight_upload',
lifecycle_entries: [
{ code: 'order_review', state: 'available', targetSurface: 'order_lifecycle_workbench' },
{ code: 'fulfillment_prep', state: 'available', targetSurface: 'order_lifecycle_workbench' },
{ code: 'freight_upload', state: 'current', targetSurface: 'order_lifecycle_workbench' },
{ code: 'upload_complete', state: 'unavailable', targetSurface: 'order_lifecycle_workbench' },
],
},
],
};
// 选法 2 盲区:源文件无复核 Case 快照(懒加载失败/未完成时生产即如此),
// 此刻文件身份只剩 requestedCaseNo。
activeCase.value = null;
requestedCaseNo.value = 'CASE-1';
const wrapper = await mountView({ case_no: 'CASE-1', lifecycle_stage: 'fulfillment_prep' });
await flushPromises();
messageMocks.success.mockClear();
// 模拟真实 selectCase 正式下游分支的同步块:更新 requestedCaseNo + activeCase 保持 null。
requestedCaseNo.value = 'CASE-2';
await nextTick();
await flushPromises();
expect(messageMocks.success).not.toHaveBeenCalledWith('已自动推进到货代上传');
// 守卫不得替用户改写深链:切文件是展示上下文切换,不是流程推进。
expect((wrapper.vm as any).$route.query.lifecycle_stage).toBe('fulfillment_prep');
} finally {
reviewQueue.value = originalQueue;
}
});
it('does not open a lifecycle stage before the backend authorizes lifecycle entries', async () => {
// 未收到正式 ui_state.lifecycle_entries 时,前端只能等待实时裁决,
// 不能因页面默认值自行开放订单复核或其他生命周期阶段。
@@ -2686,7 +2827,7 @@ describe('ShippingOrderReviewView layout phase 1', () => {
lines: [{
snapshot_line_id: 1001, line_no: 1,
reservation_id: 'RSV-FROZEN', part_number: 'PN-FROZEN',
required_qty: '6', available_qty: null, shortage_qty: null, source_code: 'DBS',
required_qty: '6', available_qty: null, part_available_qty: '9', shortage_qty: null, source_code: 'DBS',
inventory_file_no: 'SIF-LINE-DBS', status: 'shortage',
draft_line_id: 'line-frozen',
inventory_allowed_actions: ['retry_inventory_preparation', 'retry_inventory_matching'],
@@ -2719,6 +2860,12 @@ describe('ShippingOrderReviewView layout phase 1', () => {
expect(workspace.text()).toContain('RSV-FROZEN');
expect(workspace.text()).toContain('PN-FROZEN');
expect(workspace.text()).toContain('DBS');
// 断言意图:原可用数量列头改由 reservedQty 键渲染(预约数量),
// 新增料号总库存列紧随其后,值来自 part_available_qty。
const headers = workspace.findAll('thead th').map((th) => th.text());
expect(headers).toContain('预约数量');
expect(headers.indexOf('可用数量')).toBe(headers.indexOf('预约数量') + 1);
expect(workspace.text()).toContain('9');
expect(wrapper.find('[data-testid="review-fulfillment-frozen-order"]').exists()).toBe(false);
// 展示态行级动作收纳进更多菜单(⋯):逐项断言授权动作入口存在,不再有常显按钮。
await openLineOverflowMenu(wrapper, 1001);
@@ -817,6 +817,33 @@ const LINE_SCOPE_INVENTORY_ACTIONS = new Set([
'override_line_inventory_source',
]);
/**
* 阶段能力按执行动作码索引(preparation.capabilities)。
* 核心逻辑:右卡按钮的禁用态渲染必须与 submitFormalGateAction 的点击拦截消费同一份
* 能力投影,保证「展示=执行同源」——禁止按钮渲染成可点、点击才被能力门禁弹提示。
*/
const stageCapabilityByActionCode = computed(() => {
const map = new Map<string, { enabled: boolean; disabled_reason?: string | null }>();
for (const cap of formalPreparationContext.value?.capabilities || []) {
const code = String(cap.action_code || '').trim();
if (code) map.set(code, cap);
}
return map;
});
/**
* 给右卡动作附加阶段能力禁用原因。
* @param action - 已统一到卡片域的动作对象(须含 code)
* @returns 原对象浅拷贝;能力禁用时带 capabilityDisabledReason,否则该字段为 null
*/
function withStageCapabilityState<T extends { code: string }>(
action: T,
): T & { capabilityDisabledReason?: string | null } {
const cap = stageCapabilityByActionCode.value.get(String(action.code || '').trim());
if (!cap || cap.enabled) return { ...action, capabilityDisabledReason: null };
return { ...action, capabilityDisabledReason: String(cap.disabled_reason || '').trim() || null };
}
const currentTaskPrimaryAction = computed(() => {
if (formalTaskProjectionPending.value) return null;
if (hasFormalOt.value) {
@@ -828,10 +855,10 @@ const currentTaskPrimaryAction = computed(() => {
// 故必须统一映射到卡片域,否则按钮会因 businessActionLabel 为空而 fail-closed 消失。
const action = currentTaskUiState.value?.primary_action ?? null;
if (!action?.code || LINE_SCOPE_INVENTORY_ACTIONS.has(action.code)) return null;
return {
return withStageCapabilityState({
code: String(action.code).trim(),
i18nKey: `workspace.shippingNotice.processGate.actionCodes.${action.code}`,
};
});
}
const projection = shippingProcessingProjection.value;
if (projection) {
@@ -914,6 +941,8 @@ const currentTaskRecoveryActions = computed(() => {
// [§2.4 单源] 任务级恢复按钮只读 A.secondary_actions;不再叠加 B.capabilities。
// capabilities 仍可作点击执行的 stageCapabilityBypass 查找(见 handleCurrentTaskAction),
// 但不得单独渲成右卡按钮——能力要展示须先并进 A。行级选源禁止出现在右卡。
// [展示=执行同源] A 已渲染的按钮若命中阶段能力 disabled(capabilityDisabledReason
// 非空),右卡必须渲染禁用态 + 原因 tooltip,禁止可点样式诱导用户点击后才被拦截。
return (currentTaskUiState.value?.secondary_actions || [])
.filter((action) => action.enabled
&& String(action.code || '').trim() !== 'download_excel'
@@ -923,7 +952,8 @@ const currentTaskRecoveryActions = computed(() => {
// 统一右卡 domain:actionCodes.<code>(见 currentTaskPrimaryAction 注;A 的 i18nKey 可能是 chat 域)。
i18nKey: `workspace.shippingNotice.processGate.actionCodes.${String(action.code || '').trim()}`,
}))
.filter((action): action is { code: string; i18nKey: string } => {
.map((action) => withStageCapabilityState(action))
.filter((action): action is { code: string; i18nKey: string; capabilityDisabledReason?: string | null } => {
const code = String(action.code || '').trim();
return Boolean(code) && !LINE_SCOPE_INVENTORY_ACTIONS.has(code);
});
@@ -2568,8 +2598,12 @@ const formalPreparationLines = computed(() => {
...line,
required_qty: displayDecimalQty(line.required_qty),
available_qty: displayDecimalQty(line.available_qty),
// available_qty 语义为「预约匹配量」(列头:预约数量);part_available_qty 为料号总库存
// (列头:可用数量)。null 透传,由模板渲染待确认占位,避免把「无快照」误显示为 0。
part_available_qty:
line.part_available_qty == null ? null : displayDecimalQty(line.part_available_qty),
shortage_qty: displayDecimalQty(line.shortage_qty),
})) as Array<typeof rows[number] & { snapshot_line_id?: number | null; required_qty: string; available_qty: string; shortage_qty: string }>;
})) as Array<typeof rows[number] & { snapshot_line_id?: number | null; required_qty: string; available_qty: string; shortage_qty: string; part_available_qty: string | null }>;
});
/** 通知准备固定展示冻结订单明细;库存匹配结果只作为附加事实合并。 */
@@ -4875,20 +4909,21 @@ watch(
watch(
() => [
lifecycleCurrentStageCode.value,
String(activeCase.value?.case_no || '').trim(),
activeReviewDocumentId(),
// 文件身份必须用 requestedCaseNo(与 lifecycleUiState 解析阶段同源):正式下游
// (通知准备/货代上传/通知完成,选法 2)activeCase 刻意为 null,其 case_no/document_id
// 在这些文件之间恒为空值,用 activeCase 做身份会让"切换文件"被误判成"同一文件的
// 阶段推进"而弹出"已自动推进"。requestedCaseNo 在 selectCase/beginCrossRunSwitch/
// load 里与阶段重算同一同步块内更新,切换文件时本 watcher 必然看到变化而静默;
// 真正的自动推进只改队列投影、不触碰 requestedCaseNo,提示行为不变。
String(requestedCaseNo.value || activeCase.value?.case_no || '').trim(),
] as const,
async (current, previous) => {
const [currentStage, currentCaseNo, currentDocumentId] = current;
const [previousStage, previousCaseNo, previousDocumentId] = previous || [];
const [currentStage, currentFileKey] = current;
const [previousStage, previousFileKey] = previous || [];
if (await syncPendingReleaseAutoAdvance()) return;
// 切换文件时生命周期阶段会随新 Case 一起变更;这不是当前文件的自动推进,
// 切换文件时生命周期阶段会随新文件身份一起变更;这不是当前文件的自动推进,
// 不能跳转或弹出“已自动推进”提示。
if (
!previous
|| currentCaseNo !== previousCaseNo
|| currentDocumentId !== previousDocumentId
) return;
if (!previous || currentFileKey !== previousFileKey) return;
if (!currentStage || !previousStage || currentStage === previousStage) return;
const pendingReparse = pendingReparseNavigation.value;
if (
@@ -5329,8 +5364,8 @@ watch(
</div>
<div class="overflow-x-auto overscroll-x-contain" data-testid="review-fulfillment-prep-table-scroll">
<table class="review-fulfillment-prep-table min-w-[1060px] text-xs">
<thead class="border-b border-default bg-surface-muted/50 text-left"><tr><th v-if="preparationEditable" class="w-10 px-3 py-2"><input type="checkbox" class="rounded border-default" :checked="allPreparationWaveSelected" :disabled="!preparationWaveSelectableLines.length || preparationWaveBusy" :aria-label="t('chat.shippingOrderReview.fulfillmentDecision.selectReady')" @change="toggleAllPreparationLineSelection(($event.target as HTMLInputElement).checked)"></th><th v-if="preparationCustomerPoLineVisible" class="whitespace-nowrap px-3 py-2">{{ preparationCustomerPoLineLabel() }}</th><th class="whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.workbench.resultReservation') }}</th><th class="px-3 py-2">{{ t('chat.shippingOrderReview.workbench.resultPartNumber') }}</th><th class="whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.lifecycle.prepare.requiredQty') }}</th><th class="px-3 py-2">{{ t('chat.shippingOrderReview.lifecycle.prepare.inventorySource') }}</th><th v-if="formalPreparationOdmColumnVisible" class="whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.odmConflict.column') }}</th><th class="whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.fulfillmentDecision.availableQty') }}</th><th class="whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.fulfillmentDecision.shortage') }}</th><th class="whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.lifecycle.prepare.lineStatus') }}</th><th class="review-fulfillment-sticky-action-head whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.lineOps.moreActions') }}</th></tr></thead>
<tbody><template v-for="(line, lineIndex) in formalPreparationDisplayLines" :key="line.snapshot_line_id || `${line.reservation_id}-${line.part_number}`"><tr :class="Number(line.shortage_qty || 0) > 0 ? 'border-b border-amber-100 bg-amber-50/40 last:border-0 dark:border-amber-950 dark:bg-amber-950/10' : 'border-b border-default last:border-0'"><td v-if="preparationEditable" class="w-10 px-3 py-2"><input type="checkbox" class="rounded border-default" :checked="selectedPreparationSnapshotLineIds.includes(String(line.snapshot_line_id))" :disabled="preparationWaveBusy || !preparationWaveSelectableLines.some((item) => String(item.snapshot_line_id) === String(line.snapshot_line_id))" :aria-label="`${t('chat.shippingOrderReview.fulfillmentDecision.selectReady')}: ${preparationLineCustomerPoLine(line)}`" :data-testid="`review-fulfillment-line-select-${line.snapshot_line_id || lineIndex}`" @change="togglePreparationLineSelection(String(line.snapshot_line_id || lineIndex), ($event.target as HTMLInputElement).checked)"></td><td v-if="preparationCustomerPoLineVisible" class="whitespace-nowrap px-3 py-2">{{ preparationLineCustomerPoLine(line) }}</td><td class="whitespace-nowrap px-3 py-2 font-medium text-primary"><template v-if="editingLine && isInlineEditing(line)"><input v-model="editingLine.reservation_id" type="text" class="w-28 rounded border border-default bg-surface px-1.5 py-1 text-xs" :disabled="inlineEditSaving" :aria-label="t('chat.shippingOrderReview.workbench.resultReservation')" :data-testid="`review-fulfillment-line-edit-reservation-${line.snapshot_line_id}`" @keyup.enter="saveInlineEdit(line)" @keyup.esc="cancelInlineEdit" /></template><span v-else>{{ line.reservation_id || '—' }}</span></td><td class="max-w-[220px] px-3 py-2"><template v-if="editingLine && isInlineEditing(line)"><input v-model="editingLine.part_number" type="text" class="w-full min-w-0 rounded border border-default bg-surface px-1.5 py-1 text-xs" :disabled="inlineEditSaving" :aria-label="t('chat.shippingOrderReview.workbench.resultPartNumber')" :data-testid="`review-fulfillment-line-edit-part-${line.snapshot_line_id}`" @keyup.enter="saveInlineEdit(line)" @keyup.esc="cancelInlineEdit" /></template><span v-else class="block max-w-[220px] truncate" :title="line.part_number || '—'">{{ line.part_number || '—' }}</span></td><td class="whitespace-nowrap px-3 py-2"><template v-if="editingLine && isInlineEditing(line)"><input :value="editingLine.required_qty" type="number" min="0" step="any" class="w-20 rounded border border-default bg-surface px-1.5 py-1 text-xs" :disabled="inlineEditSaving" :aria-label="t('chat.shippingOrderReview.lifecycle.prepare.requiredQty')" :data-testid="`review-fulfillment-line-edit-qty-${line.snapshot_line_id}`" @input="updateInlineEditQty(($event.target as HTMLInputElement).value)" @keyup.enter="saveInlineEdit(line)" @keyup.esc="cancelInlineEdit" /></template><span v-else>{{ line.required_qty ?? '—' }}</span></td><td class="max-w-[220px] px-3 py-2"><template v-if="isInlineEditing(line) && inlineSourceOptions(line).length"><select class="w-full min-w-0 rounded border border-default bg-surface px-1.5 py-1 text-xs" :data-testid="`review-fulfillment-line-edit-source-${line.snapshot_line_id}`" :aria-label="t('chat.shippingOrderReview.lifecycle.prepare.selectSource')" :value="editingLine?.source_code" :disabled="inlineEditSaving" @change="updateInlineEditSource(($event.target as HTMLSelectElement).value)"><option v-for="option in inlineSourceOptions(line)" :key="option.value" :value="option.value">{{ option.label }}</option></select></template><span v-else class="block max-w-[220px] truncate" :title="formalPreparationLineSource(line)">{{ formalPreparationLineSource(line) || '—' }}</span></td><td v-if="formalPreparationOdmColumnVisible" class="whitespace-nowrap px-3 py-2"><div v-if="(line.odm_values?.length || 0) > 1 && !formalPreparationSourceLocked" class="flex items-center gap-1" :data-testid="`review-line-odm-${line.snapshot_line_id || lineIndex}`"><select class="min-w-0 flex-1 rounded border border-default bg-surface px-1.5 py-1 text-xs" :data-testid="`review-line-odm-select-${line.snapshot_line_id || lineIndex}`" :aria-label="t('chat.shippingOrderReview.odmConflict.title')" :value="lineOdmSelections[String(line.snapshot_line_id || lineIndex)] || line.chosen_odm_id || ''" @change="lineOdmSelections[String(line.snapshot_line_id || lineIndex)] = ($event.target as HTMLSelectElement).value"><option value="" disabled>{{ t('chat.shippingOrderReview.odmConflict.placeholder') }}</option><option v-for="value in line.odm_values" :key="value" :value="value">{{ value }}</option></select><button type="button" class="rounded bg-brand-600 px-2 py-1 text-xs font-medium text-white disabled:opacity-50" :data-testid="`review-line-odm-confirm-${line.snapshot_line_id || lineIndex}`" :disabled="!lineOdmSelections[String(line.snapshot_line_id || lineIndex)] || lineOdmBusy" :aria-label="t('chat.shippingOrderReLine truncated
<thead class="border-b border-default bg-surface-muted/50 text-left"><tr><th v-if="preparationEditable" class="w-10 px-3 py-2"><input type="checkbox" class="rounded border-default" :checked="allPreparationWaveSelected" :disabled="!preparationWaveSelectableLines.length || preparationWaveBusy" :aria-label="t('chat.shippingOrderReview.fulfillmentDecision.selectReady')" @change="toggleAllPreparationLineSelection(($event.target as HTMLInputElement).checked)"></th><th v-if="preparationCustomerPoLineVisible" class="whitespace-nowrap px-3 py-2">{{ preparationCustomerPoLineLabel() }}</th><th class="whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.workbench.resultReservation') }}</th><th class="px-3 py-2">{{ t('chat.shippingOrderReview.workbench.resultPartNumber') }}</th><th class="whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.lifecycle.prepare.requiredQty') }}</th><th class="px-3 py-2">{{ t('chat.shippingOrderReview.lifecycle.prepare.inventorySource') }}</th><th v-if="formalPreparationOdmColumnVisible" class="whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.odmConflict.column') }}</th><th class="whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.lifecycle.prepare.reservedQty') }}</th><th class="whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.lifecycle.prepare.partAvailableQty') }}</th><th class="whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.fulfillmentDecision.shortage') }}</th><th class="whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.lifecycle.prepare.lineStatus') }}</th><th class="review-fulfillment-sticky-action-head whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.lineOps.moreActions') }}</th></tr></thead>
<tbody><template v-for="(line, lineIndex) in formalPreparationDisplayLines" :key="line.snapshot_line_id || `${line.reservation_id}-${line.part_number}`"><tr :class="Number(line.shortage_qty || 0) > 0 ? 'border-b border-amber-100 bg-amber-50/40 last:border-0 dark:border-amber-950 dark:bg-amber-950/10' : 'border-b border-default last:border-0'"><td v-if="preparationEditable" class="w-10 px-3 py-2"><input type="checkbox" class="rounded border-default" :checked="selectedPreparationSnapshotLineIds.includes(String(line.snapshot_line_id))" :disabled="preparationWaveBusy || !preparationWaveSelectableLines.some((item) => String(item.snapshot_line_id) === String(line.snapshot_line_id))" :aria-label="`${t('chat.shippingOrderReview.fulfillmentDecision.selectReady')}: ${preparationLineCustomerPoLine(line)}`" :data-testid="`review-fulfillment-line-select-${line.snapshot_line_id || lineIndex}`" @change="togglePreparationLineSelection(String(line.snapshot_line_id || lineIndex), ($event.target as HTMLInputElement).checked)"></td><td v-if="preparationCustomerPoLineVisible" class="whitespace-nowrap px-3 py-2">{{ preparationLineCustomerPoLine(line) }}</td><td class="whitespace-nowrap px-3 py-2 font-medium text-primary"><template v-if="editingLine && isInlineEditing(line)"><input v-model="editingLine.reservation_id" type="text" class="w-28 rounded border border-default bg-surface px-1.5 py-1 text-xs" :disabled="inlineEditSaving" :aria-label="t('chat.shippingOrderReview.workbench.resultReservation')" :data-testid="`review-fulfillment-line-edit-reservation-${line.snapshot_line_id}`" @keyup.enter="saveInlineEdit(line)" @keyup.esc="cancelInlineEdit" /></template><span v-else>{{ line.reservation_id || '—' }}</span></td><td class="max-w-[220px] px-3 py-2"><template v-if="editingLine && isInlineEditing(line)"><input v-model="editingLine.part_number" type="text" class="w-full min-w-0 rounded border border-default bg-surface px-1.5 py-1 text-xs" :disabled="inlineEditSaving" :aria-label="t('chat.shippingOrderReview.workbench.resultPartNumber')" :data-testid="`review-fulfillment-line-edit-part-${line.snapshot_line_id}`" @keyup.enter="saveInlineEdit(line)" @keyup.esc="cancelInlineEdit" /></template><span v-else class="block max-w-[220px] truncate" :title="line.part_number || '—'">{{ line.part_number || '—' }}</span></td><td class="whitespace-nowrap px-3 py-2"><template v-if="editingLine && isInlineEditing(line)"><input :value="editingLine.required_qty" type="number" min="0" step="any" class="w-20 rounded border border-default bg-surface px-1.5 py-1 text-xs" :disabled="inlineEditSaving" :aria-label="t('chat.shippingOrderReview.lifecycle.prepare.requiredQty')" :data-testid="`review-fulfillment-line-edit-qty-${line.snapshot_line_id}`" @input="updateInlineEditQty(($event.target as HTMLInputElement).value)" @keyup.enter="saveInlineEdit(line)" @keyup.esc="cancelInlineEdit" /></template><span v-else>{{ line.required_qty ?? '—' }}</span></td><td class="max-w-[220px] px-3 py-2"><template v-if="isInlineEditing(line) && inlineSourceOptions(line).length"><select class="w-full min-w-0 rounded border border-default bg-surface px-1.5 py-1 text-xs" :data-testid="`review-fulfillment-line-edit-source-${line.snapshot_line_id}`" :aria-label="t('chat.shippingOrderReview.lifecycle.prepare.selectSource')" :value="editingLine?.source_code" :disabled="inlineEditSaving" @change="updateInlineEditSource(($event.target as HTMLSelectElement).value)"><option v-for="option in inlineSourceOptions(line)" :key="option.value" :value="option.value">{{ option.label }}</option></select></template><span v-else class="block max-w-[220px] truncate" :title="formalPreparationLineSource(line)">{{ formalPreparationLineSource(line) || '—' }}</span></td><td v-if="formalPreparationOdmColumnVisible" class="whitespace-nowrap px-3 py-2"><div v-if="(line.odm_values?.length || 0) > 1 && !formalPreparationSourceLocked" class="flex items-center gap-1" :data-testid="`review-line-odm-${line.snapshot_line_id || lineIndex}`"><select class="min-w-0 flex-1 rounded border border-default bg-surface px-1.5 py-1 text-xs" :data-testid="`review-line-odm-select-${line.snapshot_line_id || lineIndex}`" :aria-label="t('chat.shippingOrderReview.odmConflict.title')" :value="lineOdmSelections[String(line.snapshot_line_id || lineIndex)] || line.chosen_odm_id || ''" @change="lineOdmSelections[String(line.snapshot_line_id || lineIndex)] = ($event.target as HTMLSelectElement).value"><option value="" disabled>{{ t('chat.shippingOrderReview.odmConflict.placeholder') }}</option><option v-for="value in line.odm_values" :key="value" :value="value">{{ value }}</option></select><button type="button" class="rounded bg-brand-600 px-2 py-1 text-xs font-medium text-white disabled:opacity-50" :data-testid="`review-line-odm-confirm-${line.snapshot_line_id || lineIndex}`" :disabled="!lineOdmSelections[String(line.snapshot_line_id || lineIndex)] || lineOdmBusy" :aria-label="t('chat.shippingOrderReLine truncated
</table>
</div>
</div>