632 lines
26 KiB
TypeScript
632 lines
26 KiB
TypeScript
import { describe, expect, it, vi, beforeEach } from 'vitest';
|
||
|
||
/**
|
||
* 主系统分配单的三条新口径(开发者 2026-10-10):
|
||
* ① 按**配送日**合并:同一配送日的多张主系统单 ⇒ 一张本系统订单;
|
||
* ② 明细备注带**主系统单号**(主系统暂不回传客户,先用单号区分);
|
||
* ③ 「缺货」= 报主系统 `status=40`(转自采)⇒ 成功后才收口我方(明细标缺货 + 未完成采购作废),
|
||
* 主系统不可用时**一律不动本地**(否则会出现"我方已剔除、主系统还在等我们供货")。
|
||
*/
|
||
|
||
const query = vi.hoisted(() => vi.fn());
|
||
const submit = vi.hoisted(() => vi.fn());
|
||
const enrich = vi.hoisted(() => vi.fn());
|
||
const withTenant = vi.hoisted(() => vi.fn());
|
||
const writeback = vi.hoisted(() => vi.fn());
|
||
const lookup = vi.hoisted(() => vi.fn());
|
||
const removeItem = vi.hoisted(() => vi.fn());
|
||
const hasInbound = vi.hoisted(() => vi.fn());
|
||
const hasPrepDone = vi.hoisted(() => vi.fn());
|
||
const hasPurchaseDone = vi.hoisted(() => vi.fn());
|
||
|
||
vi.mock('../src/db', () => ({
|
||
pool: { query: (...args: unknown[]) => query(...args), connect: vi.fn() },
|
||
getRawPoolQuery: () => query,
|
||
}));
|
||
vi.mock('../src/services/customerOrderSubmitService', () => ({
|
||
submitMobileCustomerOrder: (...args: unknown[]) => submit(...args),
|
||
}));
|
||
vi.mock('../src/services/customerOrderEnrichService', () => ({
|
||
enrichCustomerOrderItems: (...args: unknown[]) => enrich(...args),
|
||
}));
|
||
vi.mock('../src/services/tenantSchemaService', async (importOriginal) => {
|
||
const actual = await importOriginal<typeof import('../src/services/tenantSchemaService')>();
|
||
return {
|
||
...actual,
|
||
runWithTenantDataAccess: (...args: unknown[]) => withTenant(...args),
|
||
resolveActiveTenantSchema: async () => 'tenant_br001',
|
||
};
|
||
});
|
||
// 2026-10-27:出站 supplier_code 由行级台账解析 ⇒ 本文件固定为 branchCode(等价改造前行为)
|
||
vi.mock('../src/services/branchAccessCode', () => ({
|
||
resolveSupplierCodeForPrep: async (params: { branchCode: string }) => params.branchCode,
|
||
}));
|
||
vi.mock('../src/services/orderManageItemsService', () => ({
|
||
removeOrderItemForMainSystemReturn: (...args: unknown[]) => removeItem(...args),
|
||
}));
|
||
vi.mock('../src/services/orderItemReturnService', async (importOriginal) => {
|
||
const actual = await importOriginal<typeof import('../src/services/orderItemReturnService')>();
|
||
return {
|
||
...actual,
|
||
orderItemHasInspectionInbound: (...args: unknown[]) => hasInbound(...args),
|
||
orderItemHasCompletedPreparation: (...args: unknown[]) => hasPrepDone(...args),
|
||
orderItemHasCompletedPurchase: (...args: unknown[]) => hasPurchaseDone(...args),
|
||
};
|
||
});
|
||
/**
|
||
* 按分公司的包装器(2026-10-10 接入编码收尾):本文件钉的是缺货/合并语义,
|
||
* 与"用哪个 supplier_code"无关 ⇒ 这里把它转接回本文件既有的 `lookup` mock。
|
||
* 分组/多绑定逻辑本身在 `mainSystemBranchApi` 侧由真实实现 + 调用点守卫覆盖。
|
||
*/
|
||
vi.mock('../src/services/mainSystemBranchApi', () => ({
|
||
// 与旧调用同形(第一参数=分公司,第二=items)⇒ 原样透传
|
||
lookupPreparationStatesForBranch: (...args: unknown[]) => lookup(...args),
|
||
fetchArchivedPreparationsForBranch: vi.fn(),
|
||
listRequestsForBranch: vi.fn(),
|
||
listSupplierCodesForBranch: vi.fn(async () => []),
|
||
groupItemsBySupplierCode: vi.fn(async () => new Map()),
|
||
}));
|
||
|
||
vi.mock('../src/services/mainSystemPreparations', async (importOriginal) => {
|
||
const actual = await importOriginal<typeof import('../src/services/mainSystemPreparations')>();
|
||
return {
|
||
...actual,
|
||
writebackMainSystemPreparationStatus: (...args: unknown[]) => writeback(...args),
|
||
lookupMainSystemPreparationStates: (...args: unknown[]) => lookup(...args),
|
||
};
|
||
});
|
||
|
||
import { bucketGroupsByDeliveryDate, isPreparationNoLongerOurs } from '../src/services/mainSystemOrderImport';
|
||
import { reportMainSystemStockout } from '../src/services/mainSystemStockout';
|
||
import type { MainOrderGroup } from '../src/services/mainSystemPreparations';
|
||
|
||
function row(over: Record<string, unknown>) {
|
||
return {
|
||
orderCode: 'MO-1',
|
||
skuCode: null,
|
||
displayName: null,
|
||
prepareQty: 1,
|
||
unit: '斤',
|
||
orderQty: null,
|
||
orderUnit: null,
|
||
purchasePrice: 0,
|
||
suggestedPrice: null,
|
||
prepareStatus: 10,
|
||
deliveryDate: '2026-10-09',
|
||
taskDay: '2026-10-09',
|
||
isStockout: false,
|
||
processingMethod: null,
|
||
returnCode: null,
|
||
returnReason: null,
|
||
requiresQualityReport: false,
|
||
orderItemRemark: null,
|
||
skipInbound: false,
|
||
isDirectDelivery: false,
|
||
...over,
|
||
} as never;
|
||
}
|
||
|
||
function group(
|
||
orderCode: string,
|
||
deliveryDate: string | null,
|
||
names: string[],
|
||
/** 主系统分公司(行的 `branch_code`);不传 = 行里没带(走主系统单号兜底/空键) */
|
||
mainBranchCode?: string
|
||
): MainOrderGroup {
|
||
return {
|
||
orderCode,
|
||
deliveryDate,
|
||
taskDay: deliveryDate,
|
||
rows: names.map((itemName, index) =>
|
||
row({
|
||
id: `${orderCode}-${index}`,
|
||
orderCode,
|
||
itemName,
|
||
deliveryDate,
|
||
prepareQty: index + 1,
|
||
...(mainBranchCode ? { branchCode: mainBranchCode } : {}),
|
||
})
|
||
),
|
||
} as MainOrderGroup;
|
||
}
|
||
|
||
function sqlOf(call: unknown[]): string {
|
||
return String(call[0] || '');
|
||
}
|
||
|
||
describe('按配送日合并', () => {
|
||
it('同一配送日的多张主系统单归到一个桶,跨配送日分开', () => {
|
||
const buckets = bucketGroupsByDeliveryDate([
|
||
group('MO-A', '2026-10-09', ['土豆']),
|
||
group('MO-B', '2026-10-09', ['白菜', '黄瓜']),
|
||
group('MO-C', '2026-10-10', ['番茄']),
|
||
]);
|
||
expect(buckets.map((b) => b.deliveryDate)).toEqual(['2026-10-09', '2026-10-10']);
|
||
expect(buckets[0].groups.map((g) => g.orderCode)).toEqual(['MO-A', 'MO-B']);
|
||
expect(buckets[1].groups.map((g) => g.orderCode)).toEqual(['MO-C']);
|
||
});
|
||
|
||
/**
|
||
* 2026-10-27 裁决(接入编码设计 §5.1):合并键加上**主系统分公司**。
|
||
* 为什么必须加:一个接入编码可被主系统 A/B/C 三行授权绑定 ⇒ 同一家我方分公司同一天会收到
|
||
* 多个主系统分公司的货,而它们的**送达地址(各自分公司仓库)不同** ⇒ 并成一张单就会出现
|
||
* "一张单两个送达地址",派车/送达/免入库取货全错。
|
||
*/
|
||
it('同一天但**主系统分公司不同** ⇒ 拆成两个桶(不得并单)', () => {
|
||
const buckets = bucketGroupsByDeliveryDate([
|
||
group('MO-A1', '2026-10-09', ['土豆'], 'BR002'),
|
||
group('MO-B1', '2026-10-09', ['白菜'], 'BR003'),
|
||
]);
|
||
expect(buckets).toHaveLength(2);
|
||
expect(buckets.map((b) => `${b.mainBranchCode}@${b.deliveryDate}`)).toEqual([
|
||
'BR002@2026-10-09',
|
||
'BR003@2026-10-09',
|
||
]);
|
||
expect(buckets[0].groups.map((g) => g.orderCode)).toEqual(['MO-A1']);
|
||
expect(buckets[1].groups.map((g) => g.orderCode)).toEqual(['MO-B1']);
|
||
});
|
||
|
||
it('同一天 + 同一主系统分公司 ⇒ 仍并成一张单(原口径不回退)', () => {
|
||
const buckets = bucketGroupsByDeliveryDate([
|
||
group('MO-A1', '2026-10-09', ['土豆'], 'BR002'),
|
||
group('MO-A2', '2026-10-09', ['白菜'], 'BR002'),
|
||
]);
|
||
expect(buckets).toHaveLength(1);
|
||
expect(buckets[0].mainBranchCode).toBe('BR002');
|
||
expect(buckets[0].groups.map((g) => g.orderCode)).toEqual(['MO-A1', 'MO-A2']);
|
||
});
|
||
|
||
it('行里没有主系统分公司 ⇒ 归到空键(与存量占坑行同口径)', () => {
|
||
const buckets = bucketGroupsByDeliveryDate([
|
||
group('MO-X', '2026-10-09', ['土豆']),
|
||
group('MO-Y', '2026-10-09', ['白菜'], 'BR002'),
|
||
]);
|
||
expect(buckets).toHaveLength(2);
|
||
expect(buckets.map((b) => b.mainBranchCode)).toEqual(['', 'BR002']);
|
||
});
|
||
|
||
it('配送日缺失时用哨兵日兜底(不丢行)', () => {
|
||
const buckets = bucketGroupsByDeliveryDate([group('MO-D', null, ['土豆'])]);
|
||
expect(buckets).toHaveLength(1);
|
||
expect(buckets[0].deliveryDate).toBe('1970-01-01');
|
||
});
|
||
});
|
||
|
||
describe('建日单:一次建单承接该配送日全部主系统单', () => {
|
||
/** 租户连接上跑过的 (SQL, 参数),用于断言"来源主系统单号落列" */
|
||
let tenantCalls: Array<{ sql: string; params: unknown[] }> = [];
|
||
|
||
beforeEach(() => {
|
||
query.mockReset();
|
||
submit.mockReset();
|
||
enrich.mockReset();
|
||
withTenant.mockReset();
|
||
tenantCalls = [];
|
||
enrich.mockImplementation(async (_c: string, items: unknown[]) => items);
|
||
submit.mockResolvedValue({ order_code: 'ORD_API_DAY_1', zero_price_count: 0, new_products_created: 0 });
|
||
withTenant.mockImplementation(async (_b: string, fn: (c: unknown) => Promise<unknown>) =>
|
||
fn({
|
||
query: async (...args: unknown[]) => {
|
||
tenantCalls.push({ sql: String(args[0] || ''), params: (args[1] as unknown[]) || [] });
|
||
return { rowCount: 0, rows: [] };
|
||
},
|
||
})
|
||
);
|
||
query.mockImplementation(async (...args: unknown[]) => {
|
||
const sql = sqlOf(args);
|
||
if (sql.includes('INSERT INTO public.main_system_daily_order_imports')) {
|
||
return { rowCount: 1, rows: [{ id: 'day-claim-1' }] };
|
||
}
|
||
if (sql.includes('SELECT id::text AS id, item_name')) {
|
||
return { rowCount: 2, rows: [{ id: 'i1', item_name: '土豆' }, { id: 'i2', item_name: '白菜' }] };
|
||
}
|
||
return { rowCount: 0, rows: [] };
|
||
});
|
||
});
|
||
|
||
it('只建一张单;来源主系统单号落到 main_order_code,**不写备注**', async () => {
|
||
const { importMainSystemGroups } = await import('../src/services/mainSystemOrderImport');
|
||
const outcome = await importMainSystemGroups({
|
||
supplierCode: 'SUP001',
|
||
branchCode: 'SUP001',
|
||
userId: null,
|
||
groups: [group('MO-A', '2026-10-09', ['土豆']), group('MO-B', '2026-10-09', ['白菜'])],
|
||
});
|
||
|
||
expect(submit).toHaveBeenCalledTimes(1);
|
||
const items = (submit.mock.calls[0][0] as { items: Array<Record<string, unknown>> }).items;
|
||
expect(items).toHaveLength(2);
|
||
// 备注是业务字段:不得被来源单号占用(开发者 2026-10-10 明确)
|
||
expect(items[0].remark ?? null).toBeNull();
|
||
expect(items[1].remark ?? null).toBeNull();
|
||
|
||
// 来源单号落在 order_items.main_order_code(详情表按它做一级分组)
|
||
const stamps = tenantCalls.filter((c) => c.sql.includes('SET main_order_code'));
|
||
expect(stamps).toHaveLength(2);
|
||
const byOrder = new Map(stamps.map((c) => [String(c.params[2]), c.params[1] as string[]]));
|
||
expect(byOrder.get('MO-A')).toEqual(['i1']);
|
||
expect(byOrder.get('MO-B')).toEqual(['i2']);
|
||
|
||
// 两个主系统订单各出一条 created 结果,指向同一张日单
|
||
expect(outcome.results).toHaveLength(2);
|
||
expect(new Set(outcome.results.map((r) => r.ourOrderCode))).toEqual(new Set(['ORD_API_DAY_1']));
|
||
expect(outcome.created).toBe(2);
|
||
});
|
||
});
|
||
|
||
describe('报缺货:先主系统、后本地', () => {
|
||
const ORDER = 'ORD_API_DAY_1';
|
||
const ITEM = '11111111-1111-4111-8111-111111111111';
|
||
const PREP = '22222222-2222-4222-8222-222222222222';
|
||
/** 租户连接上真正跑过的 SQL(本地收口走 runWithTenantDataAccess,不在 pool 上) */
|
||
let tenantSql: string[] = [];
|
||
/** 同上,保留参数(断言作废备注等) */
|
||
let tenantCalls: Array<{ sql: string; params: unknown[] }> = [];
|
||
/** 明细查询返回的订单状态(默认 null;用例可覆盖以验证 order_status ≥ 50 闸门) */
|
||
let itemOrderStatus: number | null = null;
|
||
|
||
beforeEach(() => {
|
||
tenantSql = [];
|
||
tenantCalls = [];
|
||
itemOrderStatus = null;
|
||
query.mockReset();
|
||
withTenant.mockReset();
|
||
writeback.mockReset();
|
||
lookup.mockReset();
|
||
removeItem.mockReset();
|
||
hasInbound.mockReset();
|
||
hasPrepDone.mockReset();
|
||
hasPurchaseDone.mockReset();
|
||
removeItem.mockResolvedValue('deleted');
|
||
hasInbound.mockResolvedValue(false);
|
||
hasPrepDone.mockResolvedValue(false);
|
||
hasPurchaseDone.mockResolvedValue(false);
|
||
withTenant.mockImplementation(async (_b: string, fn: (c: unknown) => Promise<unknown>) =>
|
||
fn({
|
||
query: async (...args: unknown[]) => {
|
||
const sql = sqlOf(args);
|
||
tenantSql.push(sql);
|
||
tenantCalls.push({ sql, params: (args[1] as unknown[]) || [] });
|
||
if (sql.includes('BEGIN') || sql.includes('COMMIT') || sql.includes('ROLLBACK')) {
|
||
return { rowCount: 0, rows: [] };
|
||
}
|
||
if (sql.includes('FROM order_items') && sql.includes('COALESCE(is_returned, false) AS is_returned')) {
|
||
// 报缺货前的状态查询 / 剔除前的行查询(两个都读 is_returned)
|
||
return {
|
||
rowCount: 1,
|
||
rows: [
|
||
{
|
||
id: ITEM,
|
||
item_name: '土豆',
|
||
sku_code: 'SKU1',
|
||
is_returned: false,
|
||
is_stockout: false,
|
||
stockout_reported_at: null,
|
||
order_status: itemOrderStatus,
|
||
},
|
||
],
|
||
};
|
||
}
|
||
// 订单头重算:读剩余明细(这里给一行)后 UPDATE orders
|
||
if (sql.includes('SELECT quantity, unit, amount')) {
|
||
return { rowCount: 1, rows: [{ quantity: '1', unit: '斤', amount: '10.00' }] };
|
||
}
|
||
if (sql.includes('UPDATE orders SET total_amount')) return { rowCount: 1, rows: [] };
|
||
return { rowCount: 0, rows: [] };
|
||
},
|
||
})
|
||
);
|
||
query.mockImplementation(async (...args: unknown[]) => {
|
||
const sql = sqlOf(args);
|
||
// 主系统订单台账存在 ⇒ 是主系统分配单
|
||
if (sql.includes('FROM public.main_system_order_imports')) return { rowCount: 1, rows: [] };
|
||
// 行级台账:这一行有对照
|
||
if (sql.includes('our_order_item_id = $2::uuid')) {
|
||
return {
|
||
rowCount: 1,
|
||
rows: [
|
||
{
|
||
id: 'l1',
|
||
branch_code: 'SUP001',
|
||
main_order_code: 'MO-A',
|
||
prep_id: PREP,
|
||
our_order_code: ORDER,
|
||
our_order_item_id: ITEM,
|
||
main_supplier_code: 'SUP001',
|
||
main_sku_code: 'SKU1',
|
||
item_name: '土豆',
|
||
last_prepare_qty: 1,
|
||
last_prepare_status: 10,
|
||
last_return_code: null,
|
||
disposition: 'imported',
|
||
disposition_reason: null,
|
||
writeback_status: null,
|
||
last_seen_active_at: null,
|
||
payload: null,
|
||
},
|
||
],
|
||
};
|
||
}
|
||
return { rowCount: 0, rows: [] };
|
||
});
|
||
writeback.mockResolvedValue({ kind: 'ok', updated: 1, skipped: [], needsCustomerPrice: false });
|
||
});
|
||
|
||
it('主系统确认后:报 status=40,并把这一行从本地清掉(订单行 + 自采/备货)', async () => {
|
||
const outcome = await reportMainSystemStockout({
|
||
branchCode: 'SUP001',
|
||
orderCode: ORDER,
|
||
itemId: ITEM,
|
||
reason: '产地断货',
|
||
});
|
||
|
||
expect(outcome.kind).toBe('ok');
|
||
expect(writeback).toHaveBeenCalledTimes(1);
|
||
const params = writeback.mock.calls[0][0] as Record<string, unknown>;
|
||
expect(params.status).toBe(40);
|
||
expect(params.stockoutReason).toBe('产地断货');
|
||
expect(params.preparationId).toBe(PREP);
|
||
|
||
// 先按既有"取消履约"判据确认还能硬删,再调删除原语(它连待处理采购/备货一起清)
|
||
expect(hasInbound).toHaveBeenCalledTimes(2); // 预检 + 删除原语内部复检
|
||
expect(hasPrepDone).toHaveBeenCalledTimes(2); // 预检 + 删除原语内部复检
|
||
expect(hasPurchaseDone).toHaveBeenCalledTimes(2); // 预检 + 删除原语内部复检
|
||
expect(removeItem).toHaveBeenCalledTimes(1);
|
||
expect((removeItem.mock.calls[0][0] as Record<string, unknown>).itemId).toBe(ITEM);
|
||
|
||
const all = tenantSql.join('\n');
|
||
// 行被删掉了 ⇒ 不再写 is_stockout 标签;也不再需要作废采购(行整体清掉)
|
||
expect(all).not.toContain('SET is_stockout = true');
|
||
expect(all).not.toContain('UPDATE purchase_orders');
|
||
// ⚠️ 转的是**主系统自采**:本地绝不允许新建任何采购单
|
||
expect(all).not.toContain('INSERT INTO purchase_orders');
|
||
// 删行后订单头金额必须跟着走
|
||
expect(all).toContain('UPDATE orders SET total_amount');
|
||
|
||
// 台账处置:本系统已无此行 ⇒ 清对照 + skipped_stockout
|
||
// (清对照是为了"主系统又分配回来"时能重新建行;skipped_stockout 让退货跟随不再处理它)
|
||
const disposition = query.mock.calls.find((c) => sqlOf(c).includes("disposition = 'skipped_stockout'"));
|
||
expect(disposition).toBeTruthy();
|
||
expect(sqlOf(disposition!)).toContain('our_order_item_id = NULL');
|
||
expect(removeItem).toHaveBeenCalledTimes(1);
|
||
});
|
||
|
||
it('已有货物事实(已入库/备货完成/采购完成)→ 拒绝缺货,不动本地', async () => {
|
||
hasInbound.mockResolvedValue(true);
|
||
const outcome = await reportMainSystemStockout({
|
||
branchCode: 'SUP001',
|
||
orderCode: ORDER,
|
||
itemId: ITEM,
|
||
});
|
||
expect(outcome.kind).toBe('invalid_state');
|
||
expect(removeItem).not.toHaveBeenCalled();
|
||
const all = tenantSql.join('\n');
|
||
expect(all).not.toContain('UPDATE orders SET total_amount');
|
||
});
|
||
|
||
it('订单已分拣出库(order_status ≥ 50)→ 拒绝缺货,不发 HTTP、不动本地', async () => {
|
||
itemOrderStatus = 50;
|
||
const outcome = await reportMainSystemStockout({
|
||
branchCode: 'SUP001',
|
||
orderCode: ORDER,
|
||
itemId: ITEM,
|
||
});
|
||
expect(outcome.kind).toBe('invalid_state');
|
||
expect(writeback).not.toHaveBeenCalled();
|
||
expect(removeItem).not.toHaveBeenCalled();
|
||
const all = tenantSql.join('\n');
|
||
expect(all).not.toContain('UPDATE orders SET total_amount');
|
||
});
|
||
|
||
it('主系统不可用 → 本地一动不动(不得先剔除再报)', async () => {
|
||
writeback.mockResolvedValue({ kind: 'unavailable', reason: 'timeout' });
|
||
lookup.mockResolvedValue({ kind: 'unavailable', reason: 'timeout' });
|
||
|
||
const outcome = await reportMainSystemStockout({ branchCode: 'SUP001', orderCode: ORDER, itemId: ITEM });
|
||
expect(outcome.kind).toBe('unavailable');
|
||
|
||
const localWrites = tenantSql.filter(
|
||
(sql) => sql.includes('SET is_stockout = true') || sql.includes('UPDATE purchase_orders')
|
||
);
|
||
expect(localWrites).toHaveLength(0);
|
||
});
|
||
|
||
it('主系统侧已经是 40(缺货)→ 视为已达成,仍收口本地', async () => {
|
||
writeback.mockResolvedValue({ kind: 'unavailable', reason: 'conflict 该备货已流转自采,不可修改' });
|
||
lookup.mockResolvedValue({
|
||
kind: 'ok',
|
||
results: [{ id: PREP, found: true, prepareStatus: 40 }],
|
||
});
|
||
|
||
const outcome = await reportMainSystemStockout({ branchCode: 'SUP001', orderCode: ORDER, itemId: ITEM });
|
||
expect(outcome.kind).toBe('ok');
|
||
expect((outcome as { alreadyReported: boolean }).alreadyReported).toBe(true);
|
||
});
|
||
|
||
it('非主系统订单 → 拒绝,且不发 HTTP', async () => {
|
||
query.mockImplementation(async (...args: unknown[]) => {
|
||
const sql = sqlOf(args);
|
||
if (sql.includes('FROM public.main_system_order_imports')) return { rowCount: 0, rows: [] };
|
||
return { rowCount: 0, rows: [] };
|
||
});
|
||
|
||
const outcome = await reportMainSystemStockout({ branchCode: 'SUP001', orderCode: 'ORD_NATIVE', itemId: ITEM });
|
||
expect(outcome.kind).toBe('not_main_system_item');
|
||
expect(writeback).not.toHaveBeenCalled();
|
||
});
|
||
});
|
||
|
||
describe('缺货跟随判据:主系统"已经不属于我们了"(2026-10-10)', () => {
|
||
const ours = 'SUP37831443';
|
||
const state = (over: Partial<{ found: boolean; prepareStatus: number | null; reassigned: boolean; currentSupplierCode: string | null }>) => ({
|
||
found: true,
|
||
prepareStatus: 10,
|
||
reassigned: false,
|
||
currentSupplierCode: ours,
|
||
...over,
|
||
});
|
||
|
||
it('转自采(prepare_status=40)⇒ 是"不再属于我们"', () => {
|
||
expect(
|
||
isPreparationNoLongerOurs({
|
||
state: state({ prepareStatus: 40, reassigned: true, currentSupplierCode: 'INTERNAL' }),
|
||
ourBranchCode: ours,
|
||
})
|
||
).toBe(true);
|
||
});
|
||
|
||
it('改派给了别人 ⇒ 也是"不再属于我们"', () => {
|
||
expect(
|
||
isPreparationNoLongerOurs({
|
||
state: state({ prepareStatus: 10, reassigned: true, currentSupplierCode: 'SUP_OTHER' }),
|
||
ourBranchCode: ours,
|
||
})
|
||
).toBe(true);
|
||
});
|
||
|
||
it('还在我们名下(准备中/已完成)⇒ 不动', () => {
|
||
for (const status of [10, 20, 30]) {
|
||
expect(
|
||
isPreparationNoLongerOurs({ state: state({ prepareStatus: status }), ourBranchCode: ours })
|
||
).toBe(false);
|
||
}
|
||
});
|
||
|
||
it('查不到该行且**没有改派信号**(found=false + 供应商空)⇒ 不认(退货/取消留给开关控制的退货跟随判)', () => {
|
||
expect(
|
||
isPreparationNoLongerOurs({
|
||
state: state({ found: false, prepareStatus: null, reassigned: false, currentSupplierCode: null }),
|
||
ourBranchCode: ours,
|
||
})
|
||
).toBe(false);
|
||
});
|
||
|
||
it('⚠️ 改派 = "删旧行 + 建新行"(found=false 但订单行当前供应商是别人)⇒ **认**(2026-10-10 真库漏判修复)', () => {
|
||
// 实测:抄手皮/精瘦肉/苹果 被改派给 SUP41472132,lookup 返回
|
||
// found=false + current_supplier_code=SUP41472132 + reassigned=true ⇒ 旧实现永远不剔除
|
||
expect(
|
||
isPreparationNoLongerOurs({
|
||
state: state({ found: false, prepareStatus: null, reassigned: true, currentSupplierCode: 'SUP41472132' }),
|
||
ourBranchCode: ours,
|
||
})
|
||
).toBe(true);
|
||
});
|
||
|
||
it('found=false 但当前供应商仍是我们 / 字段缺失 ⇒ 仍不认(不可凭猜删本地行)', () => {
|
||
expect(
|
||
isPreparationNoLongerOurs({
|
||
state: state({ found: false, prepareStatus: null, reassigned: true, currentSupplierCode: ours }),
|
||
ourBranchCode: ours,
|
||
})
|
||
).toBe(false);
|
||
expect(
|
||
isPreparationNoLongerOurs({
|
||
state: state({ found: false, prepareStatus: null, reassigned: false, currentSupplierCode: 'SUP_OTHER' }),
|
||
ourBranchCode: ours,
|
||
})
|
||
).toBe(false);
|
||
});
|
||
|
||
it('reassigned 但当前供应商仍是我们(脏数据)⇒ 不认', () => {
|
||
expect(
|
||
isPreparationNoLongerOurs({
|
||
state: state({ reassigned: true, currentSupplierCode: ours }),
|
||
ourBranchCode: ours,
|
||
})
|
||
).toBe(false);
|
||
});
|
||
});
|
||
|
||
describe('占位客户状态自愈(2026-10-10 白屏事故)', () => {
|
||
/** 客户状态域只认 10/20/30/40/50;写 1 会让前端客户管理页读 statusMap[1].bgColor 抛错、整页白屏 */
|
||
let calls: Array<{ sql: string; params: unknown[] }> = [];
|
||
let customerStatus: number | null = null;
|
||
let customerSource: string | null = null;
|
||
|
||
beforeEach(() => {
|
||
calls = [];
|
||
customerStatus = null;
|
||
customerSource = null;
|
||
query.mockReset();
|
||
submit.mockReset();
|
||
enrich.mockReset();
|
||
withTenant.mockReset();
|
||
enrich.mockImplementation(async (_c: string, items: unknown[]) => items);
|
||
submit.mockResolvedValue({ order_code: 'ORD_API_DAY_1', zero_price_count: 0, new_products_created: 0 });
|
||
withTenant.mockImplementation(async (_b: string, fn: (c: unknown) => Promise<unknown>) =>
|
||
fn({
|
||
query: async (...args: unknown[]) => {
|
||
const sql = String(args[0] || '');
|
||
calls.push({ sql, params: (args[1] as unknown[]) || [] });
|
||
if (sql.includes('FROM customers') && sql.includes('WHERE customer_code = $1')) {
|
||
// 2026-10-11:客户口径升级为「一个主系统下单分公司一个客户」,
|
||
// 自愈查询多了 company_name(用于把客户名对齐成分公司名)⇒ 桩同步补该列。
|
||
return customerStatus == null
|
||
? { rowCount: 0, rows: [] }
|
||
: {
|
||
rowCount: 1,
|
||
rows: [{ status: customerStatus, source: customerSource, company_name: '主系统订单(SUP001)' }],
|
||
};
|
||
}
|
||
return { rowCount: 0, rows: [] };
|
||
},
|
||
})
|
||
);
|
||
query.mockImplementation(async (...args: unknown[]) => {
|
||
const sql = sqlOf(args);
|
||
if (sql.includes('INSERT INTO public.main_system_daily_order_imports')) {
|
||
return { rowCount: 1, rows: [{ id: 'day-claim-1' }] };
|
||
}
|
||
if (sql.includes('SELECT id::text AS id, item_name')) {
|
||
return { rowCount: 1, rows: [{ id: 'i1', item_name: '土豆' }] };
|
||
}
|
||
if (sql.includes('INSERT INTO public.main_system_order_import_items')) return { rowCount: 1, rows: [] };
|
||
return { rowCount: 0, rows: [] };
|
||
});
|
||
});
|
||
|
||
it('新建占位客户用 status=10(不是 1)', async () => {
|
||
const { importMainSystemGroups } = await import('../src/services/mainSystemOrderImport');
|
||
await importMainSystemGroups({
|
||
supplierCode: 'SUP001',
|
||
branchCode: 'SUP001',
|
||
userId: null,
|
||
groups: [group('MO-A', '2026-10-09', ['土豆'])],
|
||
});
|
||
const insert = calls.find((c) => c.sql.includes('INSERT INTO customers'));
|
||
expect(insert).toBeTruthy();
|
||
expect(insert!.params[3]).toBe(10);
|
||
// 来源标记(只作区分,不用于隐藏:主系统就是子系统的客户)
|
||
expect(insert!.params[4]).toBe('main_system');
|
||
});
|
||
|
||
it('已存在的占位客户状态不在域内 ⇒ 自愈为 10(即使本轮没有新行)', async () => {
|
||
customerStatus = 1;
|
||
const { importMainSystemGroups } = await import('../src/services/mainSystemOrderImport');
|
||
await importMainSystemGroups({
|
||
supplierCode: 'SUP001',
|
||
branchCode: 'SUP001',
|
||
userId: null,
|
||
groups: [group('MO-A', '2026-10-09', ['土豆'])],
|
||
});
|
||
const heal = calls.find((c) => c.sql.includes('UPDATE customers SET status'));
|
||
expect(heal).toBeTruthy();
|
||
// 同一轮把 status 与 source 一起补上
|
||
expect(heal!.params[0]).toBe('MAIN_SUP001');
|
||
expect(heal!.params).toContain(10);
|
||
});
|
||
|
||
it('状态已在域内且来源已标记 ⇒ 不发多余 UPDATE', async () => {
|
||
customerStatus = 10;
|
||
customerSource = 'main_system';
|
||
const { importMainSystemGroups } = await import('../src/services/mainSystemOrderImport');
|
||
await importMainSystemGroups({
|
||
supplierCode: 'SUP001',
|
||
branchCode: 'SUP001',
|
||
userId: null,
|
||
groups: [group('MO-A', '2026-10-09', ['土豆'])],
|
||
});
|
||
expect(calls.find((c) => c.sql.includes('UPDATE customers SET status'))).toBeFalsy();
|
||
});
|
||
});
|