Files
SupplierSystem/server/tests/mainSystemQuantityChange.test.ts
Ubuntu 521e1ae13d
CI / server typecheck + tests (push) Canceled after 0s
CI / web typecheck + tests + miniprogram syntax (push) Canceled after 0s
CI / eslint (观察项,C7 骨架) (push) Canceled after 0s
CI / npm audit (critical 硬拦) (push) Canceled after 0s
feat(main-system): 消费 preparations.quantity_changed 同步订单计划数量
- webhook 消费:event_id+prep_id 幂等、revision 防乱序,业务失败 200 靠对账兜底
- 未出库:订单数量/金额/分拣 required_qty/库存抵扣差额/已分配备货/自采/结算同步
- 已出库/备货完成竞态/共享行缺订单行 id:不覆盖,落冲突台账 + 站内通知
- 定时对账兜底:mainSystemReturnFollow + 事件消费者 quantity_sync
- 迁移两张台账表;新增 13 条单测
2026-10-28 10:37:52 +08:00

530 lines
24 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { readFileSync } from 'node:fs';
import path from 'node:path';
import { beforeEach, describe, expect, it, vi } from 'vitest';
/**
* 供应商侧:主系统 `preparations.quantity_changed` 消费(2026-10-28)
*
* 验收要点:
* · 未出库:更新本地订单数量/金额、分拣计划 required_qty、库存抵扣(差额)、
* 已分配备货/自采数量、客户/供应商结算;
* · 已出库/发车/备货完成竞态:不静默覆盖,落冲突台账 + 站内通知;
* · event_id+prep_id 幂等、revision 防乱序;事件丢失由定时对账补(reconcile)。
*/
const poolQuery = vi.hoisted(() => vi.fn());
vi.mock('../src/db', () => ({
pool: { query: (...args: unknown[]) => poolQuery(...args), connect: vi.fn() },
query: (...args: unknown[]) => poolQuery(...args),
getRawPoolQuery: () => poolQuery,
getRawPoolConnect: () => vi.fn(),
acquireTenantSessionClient: vi.fn(),
releaseTenantSessionClient: vi.fn(),
attachSerializedQuery: (c: unknown) => c,
isRlsRoleAvailable: async () => false,
warmRlsRoleCache: async () => undefined,
allowRlsFailOpen: () => true,
runWithBranchRls: async (_code: string, fn: () => Promise<unknown>) => fn(),
applyBranchRlsToClient: async () => true,
}));
const tenantRun = vi.hoisted(() => vi.fn());
vi.mock('../src/services/tenantSchemaService', () => ({
runWithTenantDataAccess: (code: string, fn: (client: unknown) => Promise<unknown>) =>
tenantRun(code, fn),
}));
const lockState = vi.hoisted(() => vi.fn());
vi.mock('../src/services/orderItemCoverBatchesService', () => ({
loadCoverBatchLockState: (...args: unknown[]) => lockState(...args),
}));
const applyCover = vi.hoisted(() => vi.fn());
vi.mock('../src/services/inventoryStockCoverService', () => ({
applyStockCoverForOrder: (...args: unknown[]) => applyCover(...args),
}));
const recalcPrep = vi.hoisted(() => vi.fn());
vi.mock('../src/services/orderItemFulfillmentService', () => ({
recalcPreparationQty: (...args: unknown[]) => recalcPrep(...args),
}));
const syncOpenPurchase = vi.hoisted(() => vi.fn());
vi.mock('../src/services/orderAllocationService', () => ({
syncOpenPurchaseQtyForOrder: (...args: unknown[]) => syncOpenPurchase(...args),
}));
const syncStatements = vi.hoisted(() => vi.fn());
vi.mock('../src/services/financeReconciliationService', () => ({
syncStatementsForOrderSafe: (...args: unknown[]) => syncStatements(...args),
}));
const recalcHeader = vi.hoisted(() => vi.fn());
vi.mock('../src/services/mainSystemStockout', () => ({
recalcOrderHeaderTotals: (...args: unknown[]) => recalcHeader(...args),
}));
const updateSnapshot = vi.hoisted(() => vi.fn());
vi.mock('../src/services/mainSystemPrepLedger', () => ({
updatePrepSnapshot: (...args: unknown[]) => updateSnapshot(...args),
}));
const recordFailure = vi.hoisted(() => vi.fn());
vi.mock('../src/services/mainSystemImportFailureService', () => ({
recordMainSystemImportFailure: (...args: unknown[]) => recordFailure(...args),
}));
const notifyRoleUsers = vi.hoisted(() => vi.fn());
vi.mock('../src/services/notificationService', () => ({
notifyRoleUsers: (...args: unknown[]) => notifyRoleUsers(...args),
}));
const auditLog = vi.hoisted(() => vi.fn());
vi.mock('../src/services/auditService', () => ({
writeAuditLog: (...args: unknown[]) => auditLog(...args),
}));
const fetchActive = vi.hoisted(() => vi.fn());
vi.mock('../src/services/mainSystemPreparations', () => ({
fetchActivePreparationsForOrder: (...args: unknown[]) => fetchActive(...args),
}));
const {
applyOneQuantityChange,
applyQuantityChangedPayload,
reconcileQuantityChangedForOrder,
} = await import('../src/services/mainSystemQuantityChange');
const { classifyEvent } = await import('../src/services/mainSystemEventConsumer');
const read = (rel: string) => readFileSync(path.join(__dirname, '..', rel), 'utf8');
const PREP_ID = '036d60e9-1e31-434e-86f4-e0870909d652';
const ITEM_ID = 'd494daef-2282-420d-80cf-da3b71681586';
const OUR_ORDER = 'ORD_API_20261028_BR002_0001';
const MAIN_ORDER = 'ORD_WEB_20261028_BR002_0001';
type ClientResult = { rows: Array<Record<string, any>>; rowCount: number };
function makeFakeClient(handler: (text: string, params?: unknown[]) => ClientResult) {
const calls: Array<{ text: string; params?: unknown[] }> = [];
const client = {
query: vi.fn(async (text: string, params?: unknown[]) => {
calls.push({ text, params });
return handler(text, params);
}),
};
return { client, calls };
}
function ledgerRow(overrides: Record<string, unknown> = {}) {
return {
prep_id: PREP_ID,
our_order_code: OUR_ORDER,
our_order_item_id: ITEM_ID,
last_prepare_qty: '25',
last_prepare_status: 10,
disposition: 'imported',
payload: { main_order_code: MAIN_ORDER },
...overrides,
};
}
beforeEach(() => {
poolQuery.mockReset();
tenantRun.mockReset();
lockState.mockReset();
lockState.mockResolvedValue({ locked: false, reason: null });
applyCover.mockReset();
applyCover.mockResolvedValue({ itemCount: 1, coveredQty: 30 });
recalcPrep.mockReset();
recalcPrep.mockResolvedValue({ qtyUpdated: 1, completedOrphans: 0 });
syncOpenPurchase.mockReset();
syncOpenPurchase.mockResolvedValue(undefined);
syncStatements.mockReset();
syncStatements.mockResolvedValue(undefined);
recalcHeader.mockReset();
recalcHeader.mockResolvedValue(undefined);
updateSnapshot.mockReset();
updateSnapshot.mockResolvedValue(undefined);
recordFailure.mockReset();
recordFailure.mockResolvedValue({ attempts: 1, isFirst: true });
notifyRoleUsers.mockReset();
notifyRoleUsers.mockResolvedValue(true);
auditLog.mockReset();
auditLog.mockResolvedValue(undefined);
fetchActive.mockReset();
});
describe('未出库应用(applied)', () => {
it('25→30:更新订单数量/金额、分拣 required_qty、抵扣/备货/自采/结算同步', async () => {
const { client, calls } = makeFakeClient((text) => {
if (text.includes('FROM orders') && text.includes('FOR UPDATE')) {
return { rows: [{ order_code: OUR_ORDER, order_status: 30, delivery_date: '2026-10-28', branch_code: 'BR002' }], rowCount: 1 };
}
if (text.includes('FROM order_items') && text.includes('WHERE id = $1::uuid AND order_code = $2')) {
return {
rows: [{ id: ITEM_ID, quantity: 25, ordered_quantity: 25, price: 12, amount: 300, sku_code: 'SKU78659582524', item_name: '二刀肉', unit: '斤', stock_cover_qty: 0 }],
rowCount: 1,
};
}
if (text.includes('FROM picking_items') && text.includes('MAX(picked_qty)')) {
return { rows: [{ rows: 1, picked_qty: 0 }], rowCount: 1 };
}
if (text.includes('UPDATE order_items')) return { rows: [], rowCount: 1 };
if (text.includes('UPDATE picking_items')) return { rows: [], rowCount: 1 };
if (text.includes('SELECT COALESCE(stock_cover_qty')) return { rows: [{ cover: 30 }], rowCount: 1 };
return { rows: [], rowCount: 0 };
});
tenantRun.mockImplementation(async (_code: string, fn: (c: unknown) => Promise<unknown>) => fn(client));
poolQuery.mockImplementation(async (text: string) => {
if (text.includes('INSERT INTO public.main_system_quantity_event_applies')) {
return { rows: [{ event_id: 'evt-1' }], rowCount: 1 };
}
if (text.includes('MAX(revision)')) return { rows: [{ max_revision: 0 }], rowCount: 1 };
if (text.includes('FROM public.main_system_order_import_items')) return { rows: [ledgerRow()], rowCount: 1 };
return { rows: [], rowCount: 0 };
});
const result = await applyOneQuantityChange({
branchCode: 'BR002',
eventId: '11111111-1111-4111-8111-111111111111',
revision: 4,
source: 'webhook',
row: {
prep_id: PREP_ID,
main_order_item_id: ITEM_ID,
sku_code: 'SKU78659582524',
item_name: '二刀肉',
unit: '斤',
old_quantity: 25,
new_quantity: 30,
prep_old_qty: 25,
prep_new_qty: 30,
prepare_status: 10,
order_code: MAIN_ORDER,
},
});
expect(result.status).toBe('applied');
const orderUpdate = calls.find((c) => c.text.includes('UPDATE order_items'));
expect(orderUpdate?.params).toEqual([ITEM_ID, 30, 360]);
const pickingUpdate = calls.find((c) => c.text.includes('UPDATE picking_items'));
expect(pickingUpdate?.params).toEqual([ITEM_ID, 30]);
expect(applyCover).toHaveBeenCalledTimes(1);
expect(recalcPrep).toHaveBeenCalledTimes(1);
expect(syncOpenPurchase).toHaveBeenCalledTimes(1);
expect(syncStatements).toHaveBeenCalledTimes(1);
expect(updateSnapshot).toHaveBeenCalledWith(
expect.objectContaining({ branchCode: 'BR002', prepId: PREP_ID, prepareQty: 30 })
);
expect(recalcHeader).toHaveBeenCalledTimes(1);
// 事件台账 applied
const applyStatusCall = poolQuery.mock.calls.find(
(c) => String(c[0]).includes('UPDATE public.main_system_quantity_event_applies')
);
expect(applyStatusCall?.[1]?.[2]).toBe('applied');
});
it('重复事件(event_id+prep_id 已存在)⇒ duplicate,不写业务', async () => {
poolQuery.mockImplementation(async (text: string) => {
if (text.includes('INSERT INTO public.main_system_quantity_event_applies')) {
return { rows: [], rowCount: 0 };
}
return { rows: [], rowCount: 0 };
});
const result = await applyOneQuantityChange({
branchCode: 'BR002',
eventId: '11111111-1111-4111-8111-111111111111',
revision: 4,
source: 'webhook',
row: { prep_id: PREP_ID, new_quantity: 30, old_quantity: 25 },
});
expect(result.status).toBe('duplicate');
expect(tenantRun).not.toHaveBeenCalled();
});
it('旧 revision ⇒ stale_revision,不写业务', async () => {
poolQuery.mockImplementation(async (text: string) => {
if (text.includes('INSERT INTO public.main_system_quantity_event_applies')) return { rows: [{ event_id: 'e' }], rowCount: 1 };
if (text.includes('MAX(revision)')) return { rows: [{ max_revision: 9 }], rowCount: 1 };
if (text.includes('FROM public.main_system_order_import_items')) return { rows: [ledgerRow()], rowCount: 1 };
return { rows: [], rowCount: 0 };
});
const result = await applyOneQuantityChange({
branchCode: 'BR002',
eventId: '22222222-2222-4222-8222-222222222222',
revision: 8,
source: 'webhook',
row: { prep_id: PREP_ID, new_quantity: 30, old_quantity: 25 },
});
expect(result.status).toBe('stale_revision');
expect(tenantRun).not.toHaveBeenCalled();
});
it('共享备货行缺 main_order_item_id ⇒ 明确拒绝(shared_prep_missing_main_item),不按聚合量覆盖', async () => {
poolQuery.mockImplementation(async (text: string) => {
if (text.includes('INSERT INTO public.main_system_quantity_event_applies')) return { rows: [{ event_id: 'e' }], rowCount: 1 };
if (text.includes('MAX(revision)')) return { rows: [{ max_revision: 0 }], rowCount: 1 };
if (text.includes('FROM public.main_system_order_import_items')) return { rows: [ledgerRow()], rowCount: 1 };
if (text.includes('FROM orders WHERE order_code = $1 LIMIT 1')) return { rows: [{ delivery_date: '2026-10-28' }], rowCount: 1 };
return { rows: [], rowCount: 0 };
});
const result = await applyOneQuantityChange({
branchCode: 'BR002',
eventId: '66666666-6666-4666-8666-666666666666',
revision: 2,
source: 'webhook',
row: { prep_id: PREP_ID, shared_prep: true, old_quantity: 10, new_quantity: 12, prep_new_qty: 30 },
});
expect(result.status).toBe('conflict');
expect(result.reason).toBe('shared_prep_missing_main_item');
expect(tenantRun).not.toHaveBeenCalled();
});
it('共享备货行用订单行新量(不是聚合量)作为目标数量', async () => {
const { client, calls } = makeFakeClient((text) => {
if (text.includes('FROM orders') && text.includes('FOR UPDATE')) {
return { rows: [{ order_code: OUR_ORDER, order_status: 30, delivery_date: '2026-10-28', branch_code: 'BR002' }], rowCount: 1 };
}
if (text.includes('FROM order_items') && text.includes('WHERE id = $1::uuid AND order_code = $2')) {
return { rows: [{ id: ITEM_ID, quantity: 10, price: 5, sku_code: 'SKU1', item_name: '共享菜', unit: '斤', stock_cover_qty: 0 }], rowCount: 1 };
}
if (text.includes('FROM picking_items') && text.includes('MAX(picked_qty)')) return { rows: [{ rows: 0, picked_qty: 0 }], rowCount: 1 };
if (text.includes('UPDATE ')) return { rows: [], rowCount: 1 };
if (text.includes('SELECT COALESCE(stock_cover_qty')) return { rows: [{ cover: 0 }], rowCount: 1 };
return { rows: [], rowCount: 0 };
});
tenantRun.mockImplementation(async (_code: string, fn: (c: unknown) => Promise<unknown>) => fn(client));
poolQuery.mockImplementation(async (text: string) => {
if (text.includes('INSERT INTO public.main_system_quantity_event_applies')) return { rows: [{ event_id: 'e' }], rowCount: 1 };
if (text.includes('MAX(revision)')) return { rows: [{ max_revision: 0 }], rowCount: 1 };
if (text.includes('FROM public.main_system_order_import_items')) return { rows: [ledgerRow()], rowCount: 1 };
return { rows: [], rowCount: 0 };
});
const result = await applyOneQuantityChange({
branchCode: 'BR002',
eventId: '77777777-7777-4777-8777-777777777777',
revision: 3,
source: 'webhook',
row: {
prep_id: PREP_ID,
main_order_item_id: ITEM_ID,
shared_prep: true,
old_quantity: 10,
new_quantity: 12,
prep_old_qty: 28,
prep_new_qty: 30,
},
});
expect(result.status).toBe('applied');
const orderUpdate = calls.find((c) => c.text.includes('UPDATE order_items'));
expect(orderUpdate?.params).toEqual([ITEM_ID, 12, 60]);
});
it('未知 prep ⇒ ignored_unknown_prep(落失败台账,等导入/对账)', async () => {
poolQuery.mockImplementation(async (text: string) => {
if (text.includes('INSERT INTO public.main_system_quantity_event_applies')) return { rows: [{ event_id: 'e' }], rowCount: 1 };
if (text.includes('MAX(revision)')) return { rows: [{ max_revision: 0 }], rowCount: 1 };
return { rows: [], rowCount: 0 };
});
const result = await applyOneQuantityChange({
branchCode: 'BR002',
eventId: '33333333-3333-4333-8333-333333333333',
revision: 1,
source: 'webhook',
row: { prep_id: PREP_ID, new_quantity: 30, old_quantity: 25 },
});
expect(result.status).toBe('ignored_unknown_prep');
expect(recordFailure).toHaveBeenCalled();
expect(tenantRun).not.toHaveBeenCalled();
});
});
describe('已出库 / 备货完成竞态 ⇒ 冲突不覆盖', () => {
it('order_departed:不写订单数量,落冲突台账 + 通知', async () => {
lockState.mockResolvedValue({ locked: true, reason: 'order_departed' });
const { client, calls } = makeFakeClient((text) => {
if (text.includes('FROM orders') && text.includes('FOR UPDATE')) {
return { rows: [{ order_code: OUR_ORDER, order_status: 50, delivery_date: '2026-10-28', branch_code: 'BR002' }], rowCount: 1 };
}
if (text.includes('FROM order_items')) {
return { rows: [{ id: ITEM_ID, quantity: 25, price: 12, sku_code: 'SKU1', item_name: '二刀肉', unit: '斤', stock_cover_qty: 0 }], rowCount: 1 };
}
return { rows: [], rowCount: 0 };
});
tenantRun.mockImplementation(async (_code: string, fn: (c: unknown) => Promise<unknown>) => fn(client));
poolQuery.mockImplementation(async (text: string) => {
if (text.includes('INSERT INTO public.main_system_quantity_event_applies')) return { rows: [{ event_id: 'e' }], rowCount: 1 };
if (text.includes('MAX(revision)')) return { rows: [{ max_revision: 0 }], rowCount: 1 };
if (text.includes('FROM public.main_system_order_import_items')) return { rows: [ledgerRow()], rowCount: 1 };
if (text.includes('FROM orders WHERE order_code = $1 LIMIT 1')) return { rows: [{ delivery_date: '2026-10-28' }], rowCount: 1 };
return { rows: [], rowCount: 0 };
});
const result = await applyOneQuantityChange({
branchCode: 'BR002',
eventId: '44444444-4444-4444-8444-444444444444',
revision: 3,
source: 'webhook',
row: { prep_id: PREP_ID, main_order_item_id: ITEM_ID, new_quantity: 30, old_quantity: 25, sku_code: 'SKU1', item_name: '二刀肉' },
});
expect(result.status).toBe('conflict');
expect(result.reason).toBe('order_departed');
expect(calls.some((c) => c.text.includes('UPDATE order_items'))).toBe(false);
const conflictInsert = poolQuery.mock.calls.find((c) =>
String(c[0]).includes('INSERT INTO public.main_system_quantity_conflicts')
);
expect(conflictInsert).toBeTruthy();
expect(notifyRoleUsers).toHaveBeenCalled();
// 冲突也同步台账快照,避免对账每轮重复告警
expect(updateSnapshot).toHaveBeenCalled();
});
it('prep_completed_race:备货已完成 ⇒ 冲突', async () => {
lockState.mockResolvedValue({ locked: false, reason: null });
const { client } = makeFakeClient((text) => {
if (text.includes('FROM orders') && text.includes('FOR UPDATE')) {
return { rows: [{ order_code: OUR_ORDER, order_status: 30, delivery_date: '2026-10-28', branch_code: 'BR002' }], rowCount: 1 };
}
if (text.includes('FROM order_items')) {
return { rows: [{ id: ITEM_ID, quantity: 25, price: 12, sku_code: 'SKU1', item_name: '二刀肉', unit: '斤', stock_cover_qty: 0 }], rowCount: 1 };
}
return { rows: [], rowCount: 0 };
});
tenantRun.mockImplementation(async (_code: string, fn: (c: unknown) => Promise<unknown>) => fn(client));
poolQuery.mockImplementation(async (text: string) => {
if (text.includes('INSERT INTO public.main_system_quantity_event_applies')) return { rows: [{ event_id: 'e' }], rowCount: 1 };
if (text.includes('MAX(revision)')) return { rows: [{ max_revision: 0 }], rowCount: 1 };
if (text.includes('FROM public.main_system_order_import_items')) {
return { rows: [ledgerRow({ last_prepare_status: 30 })], rowCount: 1 };
}
if (text.includes('FROM orders WHERE order_code = $1 LIMIT 1')) return { rows: [{ delivery_date: '2026-10-28' }], rowCount: 1 };
return { rows: [], rowCount: 0 };
});
const result = await applyOneQuantityChange({
branchCode: 'BR002',
eventId: '55555555-5555-4555-8555-555555555555',
revision: 2,
source: 'webhook',
row: { prep_id: PREP_ID, main_order_item_id: ITEM_ID, new_quantity: 30, old_quantity: 25 },
});
expect(result.status).toBe('conflict');
expect(result.reason).toBe('prep_completed_race');
});
});
describe('webhook payload 解析 / 消费端接线', () => {
it('data[] 与 items[] 都接受;revision 从信封取', async () => {
poolQuery.mockImplementation(async (text: string) => {
if (text.includes('INSERT INTO public.main_system_quantity_event_applies')) return { rows: [], rowCount: 0 };
return { rows: [], rowCount: 0 };
});
const dataPayload = await applyQuantityChangedPayload({
branchCode: 'BR002',
payload: { revision: 7, request_id: 'req-1', data: [{ prep_id: PREP_ID }] },
});
expect(dataPayload.revision).toBe(7);
expect(dataPayload.results).toHaveLength(1);
expect(dataPayload.results[0].status).toBe('duplicate');
const itemsPayload = await applyQuantityChangedPayload({
branchCode: 'BR002',
payload: { revision: 8, event_id: 'req-2', items: [{ prep_id: PREP_ID }, { prep_id: PREP_ID }] },
});
expect(itemsPayload.revision).toBe(8);
expect(itemsPayload.results).toHaveLength(2);
});
it('事件消费者把 quantity_changed 分类为 quantity_sync', () => {
expect(classifyEvent({ event: 'preparations.quantity_changed', orderCode: MAIN_ORDER })).toBe('quantity_sync');
const consumer = read('src/services/mainSystemEventConsumer.ts');
expect(consumer).toContain("name === 'preparations.quantity_changed'");
expect(consumer).toContain('reconcileQuantityChangedForOrder');
});
it('webhook 路由处理 quantity_changed(在 E1 兜底之前);对账接入 mainSystemReturnFollow', () => {
const route = read('src/routes/mainSystemIntegration.ts');
expect(route).toContain("event === 'preparations.quantity_changed'");
expect(route).toContain('applyQuantityChangedPayload');
const routeIdx = route.indexOf("event === 'preparations.quantity_changed'");
const fallbackIdx = route.indexOf("if (event !== 'preparations.allocated')");
expect(routeIdx).toBeGreaterThan(-1);
expect(fallbackIdx).toBeGreaterThan(routeIdx);
const follow = read('src/services/mainSystemReturnFollow.ts');
expect(follow).toContain('applyOneQuantityChange');
});
});
describe('定时对账兜底(reconcileQuantityChangedForOrder)', () => {
it('active 行 prepare_qty 与台账快照不同 ⇒ 走同一应用逻辑', async () => {
fetchActive.mockResolvedValue({
kind: 'ok',
supplierCode: 'SUP76694428',
branchCode: 'BR002',
rowCount: 1,
orders: [
{
orderCode: MAIN_ORDER,
deliveryDate: '2026-10-28',
taskDay: '2026-10-28',
rows: [
{
id: PREP_ID,
orderCode: MAIN_ORDER,
skuCode: 'SKU78659582524',
itemName: '二刀肉',
prepareQty: 30,
unit: '斤',
prepareStatus: 10,
mainOrderItemId: ITEM_ID,
quantityRevision: 6,
},
],
},
],
});
const { client } = makeFakeClient((text) => {
if (text.includes('FROM orders') && text.includes('FOR UPDATE')) {
return { rows: [{ order_code: OUR_ORDER, order_status: 30, delivery_date: '2026-10-28', branch_code: 'BR002' }], rowCount: 1 };
}
if (text.includes('FROM order_items') && text.includes('WHERE id = $1::uuid AND order_code = $2')) {
return { rows: [{ id: ITEM_ID, quantity: 25, price: 12, sku_code: 'SKU78659582524', item_name: '二刀肉', unit: '斤', stock_cover_qty: 0 }], rowCount: 1 };
}
if (text.includes('FROM picking_items') && text.includes('MAX(picked_qty)')) return { rows: [{ rows: 0, picked_qty: 0 }], rowCount: 1 };
if (text.includes('UPDATE ')) return { rows: [], rowCount: 1 };
if (text.includes('SELECT COALESCE(stock_cover_qty')) return { rows: [{ cover: 30 }], rowCount: 1 };
return { rows: [], rowCount: 0 };
});
tenantRun.mockImplementation(async (_code: string, fn: (c: unknown) => Promise<unknown>) => fn(client));
poolQuery.mockImplementation(async (text: string) => {
if (text.includes('FROM public.main_system_order_import_items') && text.includes('main_order_code')) {
return { rows: [{ prep_id: PREP_ID, last_prepare_qty: '25', last_prepare_status: 10 }], rowCount: 1 };
}
if (text.includes('INSERT INTO public.main_system_quantity_event_applies')) return { rows: [{ event_id: 'e' }], rowCount: 1 };
if (text.includes('MAX(revision)')) return { rows: [{ max_revision: 0 }], rowCount: 1 };
if (text.includes('FROM public.main_system_order_import_items')) return { rows: [ledgerRow()], rowCount: 1 };
return { rows: [], rowCount: 0 };
});
const outcome = await reconcileQuantityChangedForOrder({
branchCode: 'BR002',
supplierCode: 'SUP76694428',
mainOrderCode: MAIN_ORDER,
});
expect(outcome.status).toBe('ok');
expect(outcome.applied).toBe(1);
expect(updateSnapshot).toHaveBeenCalled();
});
it('主系统接口不可用 ⇒ 不判定(下轮重试)', async () => {
fetchActive.mockResolvedValue({ kind: 'unavailable', reason: 'timeout' });
const outcome = await reconcileQuantityChangedForOrder({
branchCode: 'BR002',
supplierCode: 'SUP76694428',
mainOrderCode: MAIN_ORDER,
});
expect(outcome.status).toBe('unavailable');
expect(outcome.applied).toBe(0);
});
});