feat: 重构追溯码及上链出库流程

This commit is contained in:
Nixevol
2026-07-16 11:49:50 +08:00
parent 5f5c158c01
commit ebc2603815
92 changed files with 7089 additions and 1615 deletions
@@ -0,0 +1,211 @@
import { JobItemStatus, JobStatus, JobType } from '@prisma/client';
import { BatchOutboundProcessor } from './batch-outbound.processor';
function code(id: bigint, outbound = false) {
return {
id,
shortCode: id.toString().padStart(12, '0'),
outbound: outbound ? { id: id + 1000n } : null,
};
}
function createHarness(codes: ReturnType<typeof code>[]) {
const items: any[] = [];
const records = new Map(codes.map((item) => [item.id, item]));
const jobRecord: any = {
id: 'job-1',
type: JobType.BATCH_OUTBOUND,
status: JobStatus.PENDING,
total: 0,
successCount: 0,
failCount: 0,
createdBy: 7,
payload: {
selection: { mode: 'IDS', ids: codes.map((item) => item.id.toString()) },
outTime: '2026-07-15T10:00:00.000Z',
remark: '批量出库',
preparing: true,
},
};
const jobItem = {
createMany: jest.fn().mockImplementation(async ({ data }: any) => {
for (const entry of data) {
if (items.some((item) => item.jobId === entry.jobId && item.selectionKey === entry.selectionKey)) continue;
items.push({ id: BigInt(items.length + 1), ...entry, result: entry.result ?? null, error: entry.error ?? null });
}
return { count: data.length };
}),
count: jest.fn().mockImplementation(async ({ where }: any) =>
items.filter((item) => item.jobId === where.jobId).length,
),
findMany: jest.fn().mockImplementation(async ({ where, take }: any) =>
items
.filter((item) => item.jobId === where.jobId && item.status === where.status)
.sort((a, b) => a.sequence - b.sequence)
.slice(0, take),
),
updateMany: jest.fn().mockImplementation(async ({ where, data }: any) => {
const item = items.find((entry) => entry.id === where.id && entry.status === where.status);
if (!item) return { count: 0 };
Object.assign(item, data);
return { count: 1 };
}),
update: jest.fn().mockImplementation(async ({ where, data }: any) => {
const item = items.find((entry) => entry.id === where.id);
if (!item) throw new Error('item not found');
Object.assign(item, data);
return item;
}),
groupBy: jest.fn().mockImplementation(async () => {
const counts = new Map<string, number>();
for (const item of items) counts.set(item.status, (counts.get(item.status) ?? 0) + 1);
return [...counts].map(([status, count]) => ({ status, _count: { _all: count } }));
}),
};
const traceCode = {
findMany: jest.fn().mockImplementation(async () => codes),
findUnique: jest.fn().mockImplementation(async ({ where }: any) => records.get(where.id) ?? null),
};
const outboundRecord = {
create: jest.fn().mockImplementation(async ({ data }: any) => {
const current = records.get(data.traceCodeId)!;
if (current.outbound) throw Object.assign(new Error('duplicate'), { code: 'P2002' });
const outbound = { id: data.traceCodeId + 2000n };
current.outbound = outbound;
return outbound;
}),
};
const prisma = {
job: {
findUnique: jest.fn().mockResolvedValue(jobRecord),
updateMany: jest.fn().mockImplementation(async ({ data }: any) => {
Object.assign(jobRecord, data);
return { count: 1 };
}),
update: jest.fn().mockImplementation(async ({ data }: any) => {
Object.assign(jobRecord, data);
return jobRecord;
}),
},
jobItem,
traceCode,
outboundRecord,
$transaction: jest.fn().mockImplementation(async (operation: any) =>
typeof operation === 'function' ? operation({ jobItem, traceCode, outboundRecord }) : Promise.all(operation),
),
};
const processor = new BatchOutboundProcessor(prisma as any);
jest.spyOn((processor as any).logger, 'log').mockImplementation(() => undefined);
return { processor, prisma, items, jobRecord, records };
}
describe('BatchOutboundProcessor', () => {
it('prepares items and records each eligible outbound without being blocked by skipped rows', async () => {
const harness = createHarness([code(1n), code(2n, true), code(3n)]);
await harness.processor.process({ data: { jobId: 'job-1' } } as any);
expect(harness.items.map((item) => item.status)).toEqual([
JobItemStatus.SUCCESS,
JobItemStatus.SKIPPED,
JobItemStatus.SUCCESS,
]);
expect(harness.prisma.outboundRecord.create).toHaveBeenCalledTimes(2);
expect(harness.jobRecord).toMatchObject({
total: 3,
status: JobStatus.SUCCESS,
successCount: 2,
failCount: 0,
});
});
it('marks a disappeared trace code failed while allowing the remaining rows to succeed', async () => {
const harness = createHarness([code(1n), code(2n)]);
harness.prisma.traceCode.findUnique.mockImplementation(async ({ where }: any) =>
where.id === 1n ? null : harness.records.get(where.id) ?? null,
);
await harness.processor.process({ data: { jobId: 'job-1' } } as any);
expect(harness.items.map((item) => item.status)).toEqual([JobItemStatus.FAILED, JobItemStatus.SUCCESS]);
expect(harness.jobRecord).toMatchObject({
status: JobStatus.PARTIAL,
successCount: 1,
failCount: 1,
});
});
it('records an ID deleted before preparation as failed and continues the remaining rows', async () => {
const harness = createHarness([code(1n), code(2n)]);
harness.prisma.traceCode.findMany.mockResolvedValue([harness.records.get(2n)]);
await harness.processor.process({ data: { jobId: 'job-1' } } as any);
expect(harness.items).toEqual([
expect.objectContaining({ traceCodeId: null, selectionKey: '1', status: JobItemStatus.FAILED }),
expect.objectContaining({ traceCodeId: 2n, selectionKey: '2', status: JobItemStatus.SUCCESS }),
]);
expect(harness.jobRecord).toMatchObject({
status: JobStatus.PARTIAL,
successCount: 1,
failCount: 1,
});
});
it('prepares FILTER selections in stable cursor pages without loading all rows at once', async () => {
const allCodes = Array.from({ length: 1001 }, (_, index) => code(BigInt(index + 1)));
const harness = createHarness(allCodes);
harness.jobRecord.payload.selection = { mode: 'FILTER', filters: {}, excludeIds: [] };
harness.jobRecord.payload.snapshotMaxId = '1001';
harness.prisma.traceCode.findMany
.mockResolvedValueOnce(allCodes.slice(0, 1000))
.mockResolvedValueOnce(allCodes.slice(1000))
.mockResolvedValueOnce([]);
await expect((harness.processor as any).prepareItems('job-1', harness.jobRecord.payload)).resolves.toBe(true);
expect(harness.prisma.traceCode.findMany).toHaveBeenCalledTimes(3);
expect(harness.prisma.jobItem.createMany).toHaveBeenCalledTimes(2);
expect(harness.items).toHaveLength(1001);
expect(harness.items[1000].sequence).toBe(1000);
expect(harness.jobRecord.total).toBe(1001);
});
it('keeps codes that became outbound after the FILTER selection cutoff as skipped results', async () => {
const harness = createHarness([code(1n, true)]);
harness.jobRecord.payload.selection = {
mode: 'FILTER',
filters: { outboundStatus: 'NOT_OUTBOUND' },
excludeIds: [],
};
harness.jobRecord.payload.selectionCutoff = '2026-07-15T10:00:00.000Z';
harness.jobRecord.payload.snapshotMaxId = '1';
harness.prisma.traceCode.findMany
.mockResolvedValueOnce([harness.records.get(1n)])
.mockResolvedValueOnce([]);
await expect((harness.processor as any).prepareItems('job-1', harness.jobRecord.payload)).resolves.toBe(true);
const where = harness.prisma.traceCode.findMany.mock.calls[0][0].where;
expect(JSON.stringify(where, (_key, value) => typeof value === 'bigint' ? value.toString() : value))
.toContain('2026-07-15T10:00:00.000Z');
expect(harness.items).toEqual([
expect.objectContaining({ traceCodeId: 1n, status: JobItemStatus.SKIPPED }),
]);
});
it('chunks explicit ID selections instead of issuing an unbounded IN query', async () => {
const allCodes = Array.from({ length: 1001 }, (_, index) => code(BigInt(index + 1)));
const harness = createHarness(allCodes);
harness.prisma.traceCode.findMany.mockImplementation(async ({ where }: any) => {
const ids = where.id.in as bigint[];
return ids.map((id) => harness.records.get(id));
});
await expect((harness.processor as any).prepareItems('job-1', harness.jobRecord.payload)).resolves.toBe(true);
expect(harness.prisma.traceCode.findMany).toHaveBeenCalledTimes(2);
expect(harness.prisma.jobItem.createMany).toHaveBeenCalledTimes(2);
expect(harness.items).toHaveLength(1001);
});
});