Files
SupplierSystem/server/tests/manualAssignReleaseSelfPurchase.test.ts
Ubuntu deb3e72750
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
chore: 以 AI 生鲜配送系统 当前版本作为 SupplierSystem 起点
来源仓库:jxc/ai-fresh-delivery
来源提交:f0b1a180e2deb7e4673b9d1c8542619f7bc0f73d
快照树:  09f679334ff38f0ff25e907961c94a8223bcaedd(与来源 HEAD 工作树逐字节一致,3801 个文件)

按约定本仓库不带任何历史提交:来源仓库的历史中含真实凭据
(生产 SSH 私钥 deploy/id_rsa_tencent、server/.env、.env.tencent/.env.production/.env.gitea、
deploy/小程序AppSecret.txt,其中 MP_APPSECRET / S3 AccessKey 经哈希比对与线上同值),
整包推送会把这些凭据永久带入本仓库,故只取「当前版本」的单提交快照。
供应商系统后续开发自本提交开始。
2026-10-08 17:35:43 +08:00

298 lines
12 KiB
TypeScript

import { readFileSync } from 'fs';
import path from 'path';
import { describe, expect, it, vi } from 'vitest';
vi.mock('../src/db', () => ({
pool: { query: vi.fn(), connect: vi.fn() },
getRawPoolQuery: () => vi.fn(),
}));
import {
finalizeOpenPendingPurchasesForItem,
keepFulfilledItemPendingForSupplierSwitch,
partitionLinkedPurchasesForSupplierAssign,
planOpenPendingPurchasesForItem,
shouldVoidPurchaseAfterItemUnlink,
} from '../src/services/orderAllocationService';
import { orderLineDisplaysAsSelfPurchase } from '../../src/utils/orderItemSelfPurchaseDisplay';
function sqlKey(sql: string): string {
return String(sql || '').replace(/\s+/g, ' ').trim();
}
function makeDb(handlers: {
found: Array<{ purchase_code: string | null; purchase_status: number }>;
remaining?: number;
sumQty?: number;
inbound?: boolean;
}) {
const seen: string[] = [];
const db = {
query: vi.fn(async (sql: string) => {
const key = sqlKey(sql);
seen.push(key);
if (key.includes('SELECT DISTINCT po.purchase_code')) {
return { rows: handlers.found, rowCount: handlers.found.length };
}
if (key.includes('SELECT sku_code FROM order_items')) {
return { rows: [{ sku_code: 'SKU1' }], rowCount: 1 };
}
if (key.includes("operation_type = 'inspection_in'")) {
return { rows: handlers.inbound ? [{}] : [], rowCount: handlers.inbound ? 1 : 0 };
}
if (key.includes('inbound_batch_no')) {
return { rows: [], rowCount: 0 };
}
if (key.includes('SELECT COUNT(*)::int AS cnt FROM order_item_fulfillments')) {
return { rows: [{ cnt: handlers.remaining ?? 0 }], rowCount: 1 };
}
if (key.includes('SET purchase_status = 40')) {
return { rows: [], rowCount: 1 };
}
if (key.includes('DELETE FROM inspections')) {
return { rows: [{ id: 'insp-1' }], rowCount: 1 };
}
if (key.includes('COALESCE(SUM(GREATEST(0, oi.quantity')) {
return { rows: [{ qty: handlers.sumQty ?? 0 }], rowCount: 1 };
}
if (key.includes('SET purchase_qty = $2')) {
return { rows: [], rowCount: 1 };
}
throw new Error(`unexpected sql: ${key}`);
}),
};
return { db, seen };
}
describe('手选改派供应商:本行待采作废边界', () => {
it('待采/待审可解绑;已入库 20/30 keep,未入库 20/30 可解绑', () => {
expect(
partitionLinkedPurchasesForSupplierAssign([
{ purchase_code: 'PO1', purchase_status: 10 },
{ purchase_code: 'PO2', purchase_status: 32 },
])
).toEqual({ keep: false, detachCodes: ['PO1', 'PO2'] });
expect(
partitionLinkedPurchasesForSupplierAssign(
[{ purchase_code: 'PO3', purchase_status: 20 }],
{ itemInbound: true }
)
).toEqual({ keep: true, detachCodes: [] });
expect(
partitionLinkedPurchasesForSupplierAssign(
[{ purchase_code: 'PO4', purchase_status: 30 }],
{ itemInbound: true }
)
).toEqual({ keep: true, detachCodes: [] });
expect(
partitionLinkedPurchasesForSupplierAssign(
[
{ purchase_code: null, purchase_status: 20 },
{ purchase_code: 'PO5', purchase_status: 10 },
],
{ itemInbound: true }
)
).toEqual({ keep: true, detachCodes: ['PO5'] });
expect(
partitionLinkedPurchasesForSupplierAssign(
[{ purchase_code: 'PO3', purchase_status: 20 }],
{ itemInbound: false }
)
).toEqual({ keep: false, detachCodes: ['PO3'] });
});
it('无其它履约才作废合单', () => {
expect(shouldVoidPurchaseAfterItemUnlink(0)).toBe(true);
expect(shouldVoidPurchaseAfterItemUnlink(1)).toBe(false);
});
it('待采单无其它履约:解绑后作废 40', async () => {
const { db, seen } = makeDb({
found: [{ purchase_code: 'PO-A', purchase_status: 10 }],
remaining: 0,
});
const plan = await planOpenPendingPurchasesForItem('ORD1', 'item-1', db);
expect(plan).toEqual({ kept: false, detachCodes: ['PO-A'] });
const result = await finalizeOpenPendingPurchasesForItem(
'item-1',
plan.detachCodes,
db,
'改派供应商,取消原自采单'
);
expect(result).toEqual({ voided: 1, recalc: 0 });
expect(seen.some((s) => s.includes('SET purchase_code = NULL'))).toBe(false);
expect(seen.some((s) => s.includes('SET purchase_status = 40'))).toBe(true);
expect(seen.some((s) => s.includes('processing_details') && s.includes('DELETE FROM inspections'))).toBe(
true
);
expect(seen.some((s) => s.includes('SET purchase_qty = $2'))).toBe(false);
expect(
orderLineDisplaysAsSelfPurchase({
itemId: 'item-1',
purchases: [
{
purchase_code: 'PO-A',
source_id: 'item-1',
source_type: 'order_no_supplier',
purchase_status: 40,
},
],
})
).toBe(false);
});
it('合单另一行仍挂着:不解作废,只重算数量', async () => {
const { db, seen } = makeDb({
found: [{ purchase_code: 'PO-COMBO', purchase_status: 10 }],
remaining: 1,
sumQty: 4,
});
const plan = await planOpenPendingPurchasesForItem('ORD1', 'item-1', db);
const result = await finalizeOpenPendingPurchasesForItem('item-1', plan.detachCodes, db);
expect(result).toEqual({ voided: 0, recalc: 1 });
expect(seen.some((s) => s.includes('SET purchase_status = 40'))).toBe(false);
expect(seen.some((s) => s.includes('DELETE FROM inspections'))).toBe(false);
expect(seen.some((s) => s.includes('SET purchase_qty = $2'))).toBe(true);
});
it('已入库待验收/已完成自采 keep,不作废不重算', async () => {
const { db, seen } = makeDb({
found: [{ purchase_code: 'PO-DONE', purchase_status: 30 }],
inbound: true,
});
const result = await planOpenPendingPurchasesForItem('ORD1', 'item-1', db);
expect(result).toEqual({ kept: true, detachCodes: [] });
expect(seen.some((s) => s.includes('SET purchase_status = 40'))).toBe(false);
});
it('未入库待验收/已完成自采可作废', async () => {
const { db, seen } = makeDb({
found: [{ purchase_code: 'PO-DONE', purchase_status: 30 }],
remaining: 0,
inbound: false,
});
const plan = await planOpenPendingPurchasesForItem('ORD1', 'item-1', db);
expect(plan).toEqual({ kept: false, detachCodes: ['PO-DONE'] });
const result = await finalizeOpenPendingPurchasesForItem('item-1', plan.detachCodes, db);
expect(result).toEqual({ voided: 1, recalc: 0 });
expect(seen.some((s) => s.includes('SET purchase_status = 40'))).toBe(true);
expect(seen.some((s) => s.includes('purchase_status IN (10, 20, 30, 32)'))).toBe(true);
expect(seen.some((s) => s.includes('DELETE FROM inspections'))).toBe(true);
});
it('手选圈先判定 keep,原子换履约后再收尾自采;订单管理仍 preferItemSuppliers', () => {
const allocSrc = readFileSync(
path.join(__dirname, '../src/services/orderAllocationService.ts'),
'utf8'
);
const pageSrc = readFileSync(
path.join(__dirname, '../../src/pages/orders/orderManagement/OrderManagementPage.tsx'),
'utf8'
);
const useStart = allocSrc.indexOf('if (useItemSuppliers) {');
const firstFor = allocSrc.indexOf('for (const item of withSku)', useStart);
const secondFor = allocSrc.indexOf('for (const item of withSku)', firstFor + 1);
const firstLoop = allocSrc.slice(firstFor, secondFor);
expect(firstLoop).toContain('ensureSupplierPreparationReplacingPurchases');
expect(firstLoop).toContain('if (switched.kept) continue');
expect(firstLoop.indexOf('isUnassignedSupplier')).toBeLessThan(
firstLoop.indexOf('ensureSupplierPreparationReplacingPurchases')
);
expect(firstLoop).toContain('dropStalePrepsAfterSelfPurchaseAssign');
expect(firstLoop).toContain('INTERNAL_PURCHASER_CODE');
expect(firstLoop).toContain('supplierSwitchItemIds');
expect(firstLoop).toContain('shouldCancelOpenPurchases');
const replacementStart = allocSrc.indexOf(
'async function ensureSupplierPreparationReplacingPurchases'
);
const replacementEnd = allocSrc.indexOf('function toAllocationInput', replacementStart);
const replacementBody = allocSrc.slice(replacementStart, replacementEnd);
expect(replacementBody.indexOf('planOpenPendingPurchasesForItem')).toBeLessThan(
replacementBody.indexOf('ensureSupplierPreparation(params, client)')
);
expect(replacementBody.indexOf('ensureSupplierPreparation(params, client)')).toBeLessThan(
replacementBody.indexOf('finalizeOpenPendingPurchasesForItem')
);
expect(replacementBody).toContain('supplier_preparation_id IS NOT NULL');
const manageSrc = readFileSync(
path.join(__dirname, '../src/services/orderManageItemsService.ts'),
'utf8'
);
expect(manageSrc).toContain('collectSupplierSwitchItemIds');
expect(manageSrc).not.toContain('Boolean(row.from_supplier_code)');
expect(pageSrc).toContain('preferItemSuppliers: true');
const ensureStart = allocSrc.indexOf('async function ensureSupplierPreparation');
const ensureBody = allocSrc.slice(ensureStart, allocSrc.indexOf('function toAllocationInput'));
expect(ensureBody.indexOf('dropStalePendingPreparationsForSku')).toBeLessThan(
ensureBody.indexOf('if (stock.coveredFully)')
);
expect((ensureBody.match(/dropStalePendingPreparationsForSku/g) || []).length).toBe(3);
expect(ensureBody.indexOf('await linkOrderItemToPreparation')).toBeLessThan(
ensureBody.lastIndexOf('dropStalePendingPreparationsForSku')
);
expect(pageSrc).toContain("t('orders.detail.inboundReattributeMsg')");
});
it('已有自采履约仍因改派名单进入 pending;仅改数量不进', () => {
expect(keepFulfilledItemPendingForSupplierSwitch(true, 'item-1', ['item-1'])).toBe(true);
expect(keepFulfilledItemPendingForSupplierSwitch(true, 'item-1', ['item-2'])).toBe(false);
expect(keepFulfilledItemPendingForSupplierSwitch(true, 'item-1', [])).toBe(false);
expect(keepFulfilledItemPendingForSupplierSwitch(true, 'item-1', undefined)).toBe(false);
expect(keepFulfilledItemPendingForSupplierSwitch(false, 'item-1', [])).toBe(true);
const allocSrc = readFileSync(
path.join(__dirname, '../src/services/orderAllocationService.ts'),
'utf8'
);
const pendingStart = allocSrc.indexOf('const pendingItemsRaw');
const pendingEnd = allocSrc.indexOf('const pendingItems =', pendingStart);
const pendingBlock = allocSrc.slice(pendingStart, pendingEnd);
expect(pendingBlock).toContain('keepFulfilledItemPendingForSupplierSwitch');
expect(pendingBlock).toContain('options.supplierSwitchItemIds');
expect(allocSrc).toContain('if (!pendingItems.length)');
expect(allocSrc.indexOf('keepFulfilledItemPendingForSupplierSwitch')).toBeLessThan(
allocSrc.indexOf('if (!pendingItems.length)')
);
});
it('供应商改回自采时复用状态 40 原单,避免 order+source 唯一键冲突', () => {
const allocSrc = readFileSync(
path.join(__dirname, '../src/services/orderAllocationService.ts'),
'utf8'
);
const createStart = allocSrc.indexOf('async function createPurchaseOrderForItem');
const createEnd = allocSrc.indexOf(
'/** 配送后加菜的自采履约凭证',
createStart
);
const createBody = allocSrc.slice(createStart, createEnd);
expect(createBody).toContain('purchase_status < 80');
expect(createBody).toContain('if (purchaseStatus === 40)');
expect(createBody).toContain('SET purchase_status = 10');
expect(createBody).toContain('supplier_code = NULL');
expect(createBody).toContain('actual_qty = NULL');
expect(createBody.indexOf('SET purchase_status = 10')).toBeLessThan(
createBody.indexOf('await linkOrderItemToPurchase')
);
expect(createBody.indexOf('await linkOrderItemToPurchase')).toBeLessThan(
createBody.indexOf('await dropStalePrepsAfterSelfPurchaseAssign')
);
});
it('建自采单不把分配原因或库存抵扣量写入 remark', () => {
const allocSrc = readFileSync(
path.join(__dirname, '../src/services/orderAllocationService.ts'),
'utf8'
);
const createStart = allocSrc.indexOf('async function createPurchaseOrderForItem');
const createEnd = allocSrc.indexOf('/** 配送后加菜的自采履约凭证', createStart);
const createBody = allocSrc.slice(createStart, createEnd);
expect(createBody).not.toContain('库存抵扣 ${coverQty}');
expect(createBody).not.toContain('[${purchaserLabel}]');
expect(createBody).toMatch(/params\.item\.id,\s*null,/);
});
});