feat(shipping-notice): 增强发货通知与订单抽取功能,支持多进程处理与紧急停止

- 移除不再使用的 SHIPPING_NOTICE_LAYOUT_PARSER_REVISION 配置
- 在环境配置中新增 SHIPPING_NOTICE_WORKER_CONCURRENCY 和 SHIPPING_NOTICE_JOB_RUNNING_TIMEOUT_SECONDS
- 实现发货通知 worker 进程,支持并发处理订单抽取任务
- 引入紧急停止功能,允许管理员在运行中控制订单解析状态
- 更新相关 API,支持读取与设置紧急停止状态
- 增强文档与代码注释,反映新的业务逻辑与功能要求
This commit is contained in:
hugo committed 2026-07-31 18:00:49 +08:00
1 parent d0fe084999
commit b352c281d5
149 files changed
+12550 -1874

No files matched your search

@@ -187,6 +187,43 @@ describe('useChatShippingSendHandler', () => {
);
});
it('submits ready intakes from separate upload selections in one run', async () => {
const attachments = ref([
{
id: 'notice-first', kind: 'shipping_notice' as const, type: 'document' as const,
uploadStatus: 'uploaded' as const, parseStatus: 'parsed' as const,
orderExtractionStatus: 'not_started' as const, uploadProgress: 100,
originalFilename: 'first.eml', fileSize: 100, intakeNo: 'SNI-FIRST', uploadBatchId: 'batch-first',
},
{
id: 'notice-second', kind: 'shipping_notice' as const, type: 'document' as const,
uploadStatus: 'uploaded' as const, parseStatus: 'parsed' as const,
orderExtractionStatus: 'not_started' as const, uploadProgress: 100,
originalFilename: 'second.eml', fileSize: 120, intakeNo: 'SNI-SECOND', uploadBatchId: 'batch-second',
},
]);
const startOrderExtractionRun = vi.fn(async () => true);
const ctx = createContext({
attachments,
getParsedIntakeNos: () => ['SNI-FIRST', 'SNI-SECOND'],
startOrderExtractionRun,
});
const { tryHandleShippingAttachmentAutoFlow } = createShippingSendHandlers(ctx);
const consumed = await tryHandleShippingAttachmentAutoFlow(undefined, '', '');
expect(consumed).toBe(true);
expect(startOrderExtractionRun).toHaveBeenCalledWith(
'chat.shippingOrderExtractionDefaultUserMessage',
['SNI-FIRST', 'SNI-SECOND'],
[
{ name: 'first.eml', size: 100, extension: 'eml', type: 'document', source: 'shipping_notice' },
{ name: 'second.eml', size: 120, extension: 'eml', type: 'document', source: 'shipping_notice' },
],
);
expect(attachments.value).toEqual([]);
});
it('keeps attachments in the input when starting the run fails', async () => {
const attachment = {
id: 'notice-start-failed',
@@ -226,10 +226,6 @@ export function createShippingSendHandlers(ctx: ShippingSendHandlerContext) {
.map((item) => String(item.uploadBatchId || '').trim())
.filter(Boolean),
);
if (batchIds.size > 1) {
ctx.msg.warning('当前发送批次不一致,请重新上传需要一起识别的文件');
return true;
}
const userAttachments = createChatMessageAttachmentSnapshots(
noticeItems.filter((item) =>
item.intakeNo
@@ -241,7 +237,8 @@ export function createShippingSendHandlers(ctx: ShippingSendHandlerContext) {
ctx.shippingAutoFlowRequested.value = false;
if (typeof textOrEvent !== 'string') ctx.input.value = '';
try {
const uploadBatchId = [...batchIds][0];
// 多次文件选择可以共同进入一个 Run;仅单一上传批次时携带该幂等提示。
const uploadBatchId = batchIds.size === 1 ? [...batchIds][0] : undefined;
const started = uploadBatchId
? await ctx.startOrderExtractionRun?.(query, intakeNos, userAttachments, uploadBatchId)
: await ctx.startOrderExtractionRun?.(query, intakeNos, userAttachments);
@@ -1,18 +1,132 @@
/**
* features/chat/shipping/useShippingNoticeIntakes.spec.ts
* 用途:验证订单抽取阶段的轮询与本地即时状态合并规则。
* 依赖:Vitest、useShippingNoticeIntakes 纯函数导出。
* 逻辑:确保 parsed 不会提前停止 extracting 轮询,且服务端 not_started 不覆盖刚点击发送的本地状态。
* 用途:验证发货通知批量入队、订单抽取轮询与本地即时状态合并规则。
* 依赖:Vitest、Vue ref、useShippingNoticeIntakes、文件资产与 Intake API mock。
* 逻辑:确保同批附件一次进入输入区并并发预处理;parsed 不提前停止 extracting 轮询,服务端 not_started 不覆盖本地状态。
*/
import { describe, expect, it } from 'vitest';
import { ref } from 'vue';
import { describe, expect, it, vi } from 'vitest';
import type { PendingAttachment } from '../types/shipping.types';
const apiMocks = vi.hoisted(() => ({
uploadFileAsset: vi.fn(),
createShippingNoticeIntake: vi.fn(),
}));
vi.mock('@/shared/api/file-assets.api', () => ({
uploadFileAsset: apiMocks.uploadFileAsset,
}));
vi.mock('@/features/chat/api/shipping.api', () => ({
cancelShippingNoticeIntake: vi.fn(),
createShippingNoticeIntake: apiMocks.createShippingNoticeIntake,
getShippingNoticeIntakeStatuses: vi.fn(),
listActiveShippingNoticeIntakes: vi.fn(),
promoteShippingNoticeCandidate: vi.fn(),
rejectShippingNoticeCandidate: vi.fn(),
resolveShippingNoticeCandidateDuplicate: vi.fn(),
resolveShippingNoticeDuplicate: vi.fn(),
retryShippingNoticeIntake: vi.fn(),
updateShippingNoticeCandidate: vi.fn(),
}));
import {
isOrderExtractionEligibleIntake,
resolveShippingOrderExtractionStatus,
shouldRestoreShippingNoticeIntake,
shouldPollShippingNoticeIntake,
useShippingNoticeIntakes,
} from './useShippingNoticeIntakes';
/** 创建可手动完成的 Promise,用于断言多个附件上传是否在同一轮启动。 */
function createDeferred<T>() {
let resolve!: (value: T) => void;
const promise = new Promise<T>((done) => {
resolve = done;
});
return { promise, resolve };
}
describe('shipping notice order extraction state', () => {
it('adds the whole selected batch before starting concurrent preprocessing', async () => {
const firstUpload = createDeferred<{ asset_no: string }>();
const secondUpload = createDeferred<{ asset_no: string }>();
apiMocks.uploadFileAsset
.mockReset()
.mockReturnValueOnce(firstUpload.promise)
.mockReturnValueOnce(secondUpload.promise);
apiMocks.createShippingNoticeIntake
.mockReset()
.mockImplementation(async (assetNo: string, _conversationId: string | null, uploadBatchId: string) => ({
intake_no: `SNI-${assetNo}`,
upload_batch_id: uploadBatchId,
parse_status: 'parsed',
candidates: [],
}));
const attachments = ref<PendingAttachment[]>([]);
const intakes = useShippingNoticeIntakes({
attachments,
conversationId: ref(null),
msg: { warning: vi.fn() },
t: (key) => key,
});
const files = [
new File(['first'], 'first.eml', { type: 'message/rfc822' }),
new File(['second'], 'second.eml', { type: 'message/rfc822' }),
];
const enqueuePromise = intakes.enqueueNoticeFiles(files);
expect(attachments.value).toHaveLength(2);
expect(new Set(attachments.value.map((item) => item.kind === 'shipping_notice' ? item.uploadBatchId : undefined)).size).toBe(1);
expect(apiMocks.uploadFileAsset).toHaveBeenCalledTimes(2);
firstUpload.resolve({ asset_no: 'ASSET-1' });
secondUpload.resolve({ asset_no: 'ASSET-2' });
await enqueuePromise;
expect(apiMocks.createShippingNoticeIntake).toHaveBeenCalledTimes(2);
});
it('submits all ready attachments even when users selected them in separate batches', async () => {
apiMocks.uploadFileAsset
.mockReset()
.mockResolvedValueOnce({ asset_no: 'ASSET-1' })
.mockResolvedValueOnce({ asset_no: 'ASSET-2' });
apiMocks.createShippingNoticeIntake
.mockReset()
.mockImplementation(async (assetNo: string, _conversationId: string | null, uploadBatchId: string) => ({
intake_no: `SNI-${assetNo}`,
upload_batch_id: uploadBatchId,
parse_status: 'parsed',
parse_summary: {
preview_status: 'ready_for_extraction',
ready_for_extraction: true,
attachment_directory_complete: true,
},
order_extraction_status: 'not_started',
candidates: [],
}));
const attachments = ref<PendingAttachment[]>([]);
const intakes = useShippingNoticeIntakes({
attachments,
conversationId: ref(null),
msg: { warning: vi.fn() },
t: (key) => key,
});
await intakes.enqueueNoticeFiles([
new File(['first'], 'first.eml', { type: 'message/rfc822' }),
]);
await intakes.enqueueNoticeFiles([
new File(['second'], 'second.eml', { type: 'message/rfc822' }),
]);
// 两次选择具有不同 uploadBatchId,但同在当前输入框时必须进入同一个订单抽取 Run。
expect(new Set(attachments.value.map((item) => item.kind === 'shipping_notice' ? item.uploadBatchId : undefined)).size).toBe(2);
expect(intakes.getParsedIntakeNos()).toEqual(['SNI-ASSET-1', 'SNI-ASSET-2']);
});
it('does not resubmit consumed intakes for a new order extraction turn', () => {
expect(isOrderExtractionEligibleIntake({
intakeNo: 'SNI-CONSUMED',
@@ -2,7 +2,8 @@
* features/chat/shipping/useShippingNoticeIntakes.ts
* 用途:发货通知选择即上传、创建 intake 与批量状态轮询编排。
* 依赖:file-assets.api、shipping.api、shipping.types、shippingNoticeAttachmentIntegrity、后端布局状态汇总。
* 逻辑:useChatShipping / useChatAttachments 在货代 Agent 下委托本 composable 管理预解析附件;
* 逻辑:useChatShipping / useChatAttachments 在货代 Agent 下委托本 composable 原子加入附件并并发预解析;
* 点击发送时汇集输入框内全部合格附件,不以某次文件选择生成的 uploadBatchId 截断;
* 完整性判定委托 shippingNoticeAttachmentIntegrity(与后端契约对齐);会话刷新仅恢复未提交的处理中或解析失败附件。
*/
import { computed, onBeforeUnmount, ref, type Ref } from 'vue';
@@ -247,8 +248,6 @@ export interface UseShippingNoticeIntakesOptions {
export function useShippingNoticeIntakes(options: UseShippingNoticeIntakesOptions) {
const pollTimer = ref<ReturnType<typeof setTimeout> | null>(null);
const pollRound = ref(0);
// 新文件选择显式推进当前批次;恢复历史卡片不能覆盖它。
const currentUploadBatchId = ref<string | null>(null);
const noticeAttachments = computed(() =>
options.attachments.value.filter(
@@ -256,12 +255,8 @@ export function useShippingNoticeIntakes(options: UseShippingNoticeIntakesOption
),
);
const currentBatchAttachments = computed(() => {
const batchId = currentUploadBatchId.value;
return batchId
? noticeAttachments.value.filter((item) => item.uploadBatchId === batchId)
: noticeAttachments.value;
});
// 输入框就是本次提交边界;多次选择加入的附件必须一起校验和发送。
const currentBatchAttachments = noticeAttachments;
const hasBlockingUploadOrParse = computed(() =>
currentBatchAttachments.value.some((item) =>
@@ -422,16 +417,19 @@ export function useShippingNoticeIntakes(options: UseShippingNoticeIntakesOption
}
};
/**
* 将同一次选择的发货通知作为一个批次加入输入区,并并发完成资产上传与 Intake 创建。
* 核心逻辑:先原子追加全部附件,确保 UI 立即展示完整批次;再并发预处理,单文件失败由 processSingleFile 独立记录。
* @param files - 用户同一次选择的本地附件;所有文件共享同一个 uploadBatchId
* @returns 全部附件的预处理任务结束后完成;单文件失败不会拒绝整个批次
*/
const enqueueNoticeFiles = async (files: File[]) => {
// 同一次选择共享一个持久化批次;后续发送只会自动取这个最新批次。
// 同一次选择共享批次 ID,用于上传幂等和状态关联;发送范围由当前输入框决定。
const uploadBatchId = globalThis.crypto?.randomUUID?.()
|| `${Date.now()}-${Math.random().toString(36).slice(2, 12)}`;
currentUploadBatchId.value = uploadBatchId;
for (const file of files) {
const attachment = createPendingAttachment(file, uploadBatchId);
options.attachments.value = [...options.attachments.value, attachment];
await processSingleFile(attachment);
}
const batchAttachments = files.map((file) => createPendingAttachment(file, uploadBatchId));
options.attachments.value = [...options.attachments.value, ...batchAttachments];
await Promise.all(batchAttachments.map((attachment) => processSingleFile(attachment)));
};
/**
@@ -468,12 +466,15 @@ export function useShippingNoticeIntakes(options: UseShippingNoticeIntakesOption
};
const getParsedIntakeNos = () => {
const eligible = noticeAttachments.value.filter(isOrderExtractionEligibleIntake);
const currentBatchId = currentUploadBatchId.value
|| [...noticeAttachments.value].reverse().find((item) => item.uploadBatchId)?.uploadBatchId;
return eligible
.filter((item) => item.uploadBatchId === currentBatchId)
.map((item) => String(item.intakeNo));
const seen = new Set<string>();
return noticeAttachments.value
.filter(isOrderExtractionEligibleIntake)
.map((item) => String(item.intakeNo || '').trim().toUpperCase())
.filter((intakeNo) => {
if (!intakeNo || seen.has(intakeNo)) return false;
seen.add(intakeNo);
return true;
});
};
/** 点击发送后立即展示订单识别阶段,并启动 Intake 状态轮询。 */