Files
SupplierSystem/server/tests/amendActualPreservePrepareQty.test.ts
T
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

190 lines
7.9 KiB
TypeScript
Raw 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.
/**
* 改价接口 `preserveActualQty=true` 时不得覆盖待验行 `prepare_qty` 契约测试。
*
* 背景(docs/design/20260929-amend-actual-preserve-prepare-qty.md):
* 自采 UI 改价(`PATCH /purchase/:code/amend-actual`,固定 `preserveActualQty: true`)
* 曾无条件执行 `UPDATE inspections SET prepare_qty = $2`,在 PO 未验收
* (`actual_qty = null`)时 `nextQty = 0`,把建好的 `prepare_qty` 清成 0,
* 导致后续合并入库超量兜底落到无照片行、照片闸门拦死。
* 方案 C 设计意图是「本接口只改价格/单位/备注」,故 `preserveActualQty=true`
* 时应保持 `prepare_qty` 不变。
*/
import { describe, expect, it, vi, beforeEach } from 'vitest';
import type { PoolClient } from 'pg';
const assertPurchaseOrderInBranch = vi.fn(async () => undefined);
const purchaseLinkedToWarehouseDemand = vi.fn(async () => false);
const syncOrderItemsFromSupplyCompletion = vi.fn(async () => ({
needsCustomerPrice: false,
itemIds: [],
}));
const syncSkuCostFromPreparation = vi.fn(async () => undefined);
const reconcileOrderPurchaseFromLatestInspections = vi.fn(async () => undefined);
const applyInboundBatchQtyDelta = vi.fn(async () => undefined);
const assertSupplyCostPrice = vi.fn(async () => undefined);
const clearPlanPriceForZeroCost = vi.fn(async () => undefined);
const isZeroSupplyCostAllowed = vi.fn(async () => false);
const writeAuditLog = vi.fn(async () => undefined);
vi.mock('../src/services/purchaserBranchScope', () => ({
assertPurchaseOrderInBranch: (...a: unknown[]) => assertPurchaseOrderInBranch(...a),
}));
vi.mock('../src/services/processingDemandSheetService', () => ({
purchaseLinkedToWarehouseDemand: (...a: unknown[]) => purchaseLinkedToWarehouseDemand(...a),
}));
vi.mock('../src/services/orderItemSupplyUnitSync', () => ({
syncOrderItemsFromSupplyCompletion: (...a: unknown[]) => syncOrderItemsFromSupplyCompletion(...a),
}));
vi.mock('../src/services/preparationCostService', () => ({
syncSkuCostFromPreparation: (...a: unknown[]) => syncSkuCostFromPreparation(...a),
}));
vi.mock('../src/services/inspectionComplianceService', () => ({
reconcileOrderPurchaseFromLatestInspections: (...a: unknown[]) =>
reconcileOrderPurchaseFromLatestInspections(...a),
}));
vi.mock('../src/services/inventoryAdjustService', () => ({
applyInboundBatchQtyDelta: (...a: unknown[]) => applyInboundBatchQtyDelta(...a),
}));
vi.mock('../src/services/supplyCostPrice', () => ({
assertSupplyCostPrice: (...a: unknown[]) => assertSupplyCostPrice(...a),
clearPlanPriceForZeroCost: (...a: unknown[]) => clearPlanPriceForZeroCost(...a),
}));
vi.mock('../src/services/zeroSupplyCostConfigService', () => ({
isZeroSupplyCostAllowed: (...a: unknown[]) => isZeroSupplyCostAllowed(...a),
}));
vi.mock('../src/services/auditService', () => ({
writeAuditLog: (...a: unknown[]) => writeAuditLog(...a),
}));
import { amendPurchaseActual } from '../src/services/purchaseAmendService';
type PORow = {
purchase_code: string;
purchase_status: number;
branch_code: string;
sku_code: string;
order_code: string;
supplier_code: string | null;
source_id: string | null;
purchase_qty: string;
purchase_price: string;
actual_qty: string | null;
actual_price: string | null;
remark: string | null;
self_processed: boolean;
};
function mockClient(po: Partial<PORow> = {}) {
const fullPo: PORow = {
purchase_code: po.purchase_code || 'PUR_TEST_001',
purchase_status: po.purchase_status ?? 20,
branch_code: po.branch_code || 'BR002',
sku_code: po.sku_code || 'SKU_TEST',
order_code: po.order_code || 'ORD_TEST_001',
supplier_code: po.supplier_code ?? null,
source_id: po.source_id ?? null,
purchase_qty: po.purchase_qty || '15.00',
purchase_price: po.purchase_price || '2.00',
actual_qty: po.actual_qty ?? null,
actual_price: po.actual_price ?? null,
remark: po.remark ?? null,
self_processed: po.self_processed ?? false,
};
const calls: Array<{ sql: string; params: unknown[] }> = [];
const query = vi.fn(async (sql: string, params?: unknown[]) => {
const text = String(sql);
calls.push({ sql: text, params: params || [] });
if (text.includes('SELECT purchase_code, purchase_status, branch_code, sku_code, order_code')) {
return { rows: [fullPo], rowCount: 1 };
}
if (text.includes('COALESCE(NULLIF(TRIM(oi.unit)') && text.includes('FROM purchase_orders po')) {
return { rows: [{ unit: '斤' }], rowCount: 1 };
}
if (text.includes('UPDATE purchase_orders')) {
return { rows: [], rowCount: 1 };
}
if (text.includes('UPDATE inspections')) {
return { rows: [], rowCount: 1 };
}
if (text.includes('SELECT inbound_batch_no')) {
return { rows: [], rowCount: 0 };
}
return { rows: [], rowCount: 0 };
});
return { query, calls } as unknown as PoolClient & {
query: typeof query;
calls: typeof calls;
};
}
const baseInput = {
purchaseCode: 'PUR_TEST_001',
branchCode: 'BR002',
actualPrice: 3,
operatorId: 'u-1',
operatorRole: 'admin',
};
beforeEach(() => {
vi.clearAllMocks();
purchaseLinkedToWarehouseDemand.mockImplementation(async () => false);
isZeroSupplyCostAllowed.mockImplementation(async () => false);
});
describe('amendPurchaseActual preserveActualQty 不覆盖 prepare_qty', () => {
it('preserveActualQty=true + 未验收(actual_qty=null):UPDATE inspections 不写 prepare_qty', async () => {
const client = mockClient({ actual_qty: null, purchase_qty: '15.00' });
await amendPurchaseActual({ ...baseInput, preserveActualQty: true }, client);
const inspUpdate = client.calls.find((c) => c.sql.includes('UPDATE inspections'));
expect(inspUpdate).toBeTruthy();
// SQL 必须含 CASE WHEN $7::boolean THEN prepare_qty ELSE $2 守卫
expect(inspUpdate!.sql).toContain('CASE WHEN $7::boolean THEN prepare_qty ELSE $2 END');
// 不得是无条件 SET prepare_qty = $2
expect(inspUpdate!.sql).not.toMatch(/SET prepare_qty = \$2/);
// 第 7 个参数是 preserveActualQty
expect(inspUpdate!.params[6]).toBe(true);
});
it('preserveActualQty=false + 未验收(actual_qty=null):保持原行为 prepare_qty = nextQty', async () => {
const client = mockClient({ actual_qty: null, purchase_qty: '15.00' });
await amendPurchaseActual(
{ ...baseInput, preserveActualQty: false, actualQty: 12 },
client
);
const inspUpdate = client.calls.find((c) => c.sql.includes('UPDATE inspections'));
expect(inspUpdate).toBeTruthy();
// preserveActualQty=false 时走 ELSE 分支 = $2 = nextQty
expect(inspUpdate!.sql).toContain('CASE WHEN $7::boolean THEN prepare_qty ELSE $2 END');
expect(inspUpdate!.params[6]).toBe(false);
// nextQty = input.actualQty = 12
expect(inspUpdate!.params[1]).toBe(12);
});
it('preserveActualQty=true + 已验收(actual_qty>0):prepare_qty 不变(nextQty=actual_qty)', async () => {
const client = mockClient({ actual_qty: '10.00', actual_price: '2.00' });
await amendPurchaseActual({ ...baseInput, preserveActualQty: true }, client);
const inspUpdate = client.calls.find((c) => c.sql.includes('UPDATE inspections'));
expect(inspUpdate).toBeTruthy();
expect(inspUpdate!.sql).toContain('CASE WHEN $7::boolean THEN prepare_qty ELSE $2 END');
expect(inspUpdate!.params[6]).toBe(true);
});
});
describe('源码静态守卫', () => {
it('purchaseAmendService.ts 含 CASE WHEN 守卫且不再无条件写 prepare_qty', async () => {
const { readFileSync } = await import('node:fs');
const src = readFileSync(
new URL('../src/services/purchaseAmendService.ts', import.meta.url),
'utf8'
);
expect(src).toContain('CASE WHEN $7::boolean THEN prepare_qty ELSE $2 END');
// 旧的无条件写法不应残留(排除 CASE WHEN 行本身)
const lines = src.split('\n');
const bareSet = lines.find((l) => /SET prepare_qty = \$2/.test(l));
expect(bareSet).toBeUndefined();
});
});