来源仓库: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 经哈希比对与线上同值), 整包推送会把这些凭据永久带入本仓库,故只取「当前版本」的单提交快照。 供应商系统后续开发自本提交开始。
298 lines
12 KiB
TypeScript
298 lines
12 KiB
TypeScript
/**
|
||
* 订单侧改成本价 → 回写自采单 / 备货行(`orderEnteredCostWritebackService`)契约测试。
|
||
*
|
||
* 要点(对应 docs/design/20260922-order-cost-writeback-to-supply.md):
|
||
* - 已结算(statement_lines 供应商行)/ 已验收(inspections 有实收)**必须跳过**,
|
||
* 否则供应商结算金额会与备货价对不上;
|
||
* - 备货行只改未作废/非历史修复/未转自采的行;
|
||
* - 自采单按状态分写:10 → purchase_price;20/30 → amendPurchaseActual(只改价);
|
||
* 40 作废单不碰;
|
||
* - ⚠️ 回归钉子:`purchase_orders` **没有 unit 列**,本服务不得从它 SELECT/传 unit
|
||
* (否则 `column "unit" does not exist`,且会被上层 try/catch 静默吞掉)。
|
||
*/
|
||
import { describe, expect, it, vi, beforeEach } from 'vitest';
|
||
import { readFileSync } from 'node:fs';
|
||
import type { PoolClient } from 'pg';
|
||
|
||
const writeAuditLog = vi.fn(async () => undefined);
|
||
const amendPurchaseActual = vi.fn(async () => ({ success: true as const }));
|
||
const linkedToWarehouseDemand = vi.fn(async () => false);
|
||
|
||
vi.mock('../src/services/auditService', () => ({
|
||
writeAuditLog: (...args: unknown[]) => writeAuditLog(...args),
|
||
}));
|
||
vi.mock('../src/services/purchaseAmendService', () => ({
|
||
amendPurchaseActual: (...args: unknown[]) => amendPurchaseActual(...args),
|
||
}));
|
||
vi.mock('../src/services/processingDemandSheetService', () => ({
|
||
purchaseLinkedToWarehouseDemand: (...args: unknown[]) => linkedToWarehouseDemand(...args),
|
||
}));
|
||
|
||
import { writeOrderEnteredCostToSupply } from '../src/services/orderEnteredCostWritebackService';
|
||
|
||
type MockOptions = {
|
||
settled?: boolean;
|
||
inspected?: boolean;
|
||
prepRowCount?: number;
|
||
purchaseOrders?: Array<{ purchase_code: string; purchase_status: number; self_processed?: boolean }>;
|
||
};
|
||
|
||
function mockClient(options: MockOptions = {}) {
|
||
const query = vi.fn(async (sql: string, _params?: unknown[]) => {
|
||
const text = String(sql);
|
||
if (text.includes('FROM statement_lines')) {
|
||
return { rows: options.settled ? [{ '?column?': 1 }] : [], rowCount: options.settled ? 1 : 0 };
|
||
}
|
||
if (text.includes('FROM inspections')) {
|
||
return { rows: options.inspected ? [{ '?column?': 1 }] : [], rowCount: options.inspected ? 1 : 0 };
|
||
}
|
||
if (text.includes('UPDATE supplier_preparations')) {
|
||
const n = options.prepRowCount ?? 0;
|
||
return { rows: [], rowCount: n };
|
||
}
|
||
if (text.includes('FROM purchase_orders')) {
|
||
const rows = options.purchaseOrders || [];
|
||
return { rows, rowCount: rows.length };
|
||
}
|
||
if (text.includes('UPDATE purchase_orders')) {
|
||
return { rows: [], rowCount: 1 };
|
||
}
|
||
return { rows: [], rowCount: 0 };
|
||
});
|
||
return { query } as unknown as PoolClient & { query: typeof query };
|
||
}
|
||
|
||
const input = {
|
||
orderCode: 'ORD_WEB_20260922_BR004_0002',
|
||
skuCode: 'SKU04297298787',
|
||
supplierCode: 'SUP58009628',
|
||
branchCode: 'BR004',
|
||
unitCost: 12,
|
||
operatorId: 'u-1',
|
||
operatorRole: 'admin',
|
||
};
|
||
|
||
const sqlOf = (client: ReturnType<typeof mockClient>) =>
|
||
client.query.mock.calls.map(([sql]) => String(sql));
|
||
|
||
beforeEach(() => {
|
||
writeAuditLog.mockClear();
|
||
amendPurchaseActual.mockClear();
|
||
linkedToWarehouseDemand.mockClear();
|
||
linkedToWarehouseDemand.mockImplementation(async () => false);
|
||
});
|
||
|
||
describe('writeOrderEnteredCostToSupply 守卫', () => {
|
||
it('缺少 SKU 或成本价时直接返回,不查库', async () => {
|
||
const client = mockClient();
|
||
await expect(writeOrderEnteredCostToSupply(client, { ...input, skuCode: ' ' })).resolves.toEqual({
|
||
prep_updated: 0,
|
||
purchase_updated: 0,
|
||
skipped: 'no_sku',
|
||
});
|
||
await expect(writeOrderEnteredCostToSupply(client, { ...input, unitCost: 0 })).resolves.toEqual({
|
||
prep_updated: 0,
|
||
purchase_updated: 0,
|
||
skipped: 'no_cost',
|
||
});
|
||
await expect(writeOrderEnteredCostToSupply(client, { ...input, unitCost: null })).resolves.toEqual({
|
||
prep_updated: 0,
|
||
purchase_updated: 0,
|
||
skipped: 'no_cost',
|
||
});
|
||
expect(client.query).not.toHaveBeenCalled();
|
||
});
|
||
|
||
it('已结算的订单行被跳过:一列都不改(结算金额口径保护)', async () => {
|
||
const client = mockClient({ settled: true, prepRowCount: 1 });
|
||
const result = await writeOrderEnteredCostToSupply(client, input);
|
||
expect(result).toEqual({ prep_updated: 0, purchase_updated: 0, skipped: 'settled' });
|
||
const sql = sqlOf(client);
|
||
expect(sql.some((s) => s.includes('UPDATE supplier_preparations'))).toBe(false);
|
||
expect(sql.some((s) => s.includes('UPDATE purchase_orders'))).toBe(false);
|
||
expect(writeAuditLog).not.toHaveBeenCalled();
|
||
});
|
||
|
||
it('已验收(有实收)的订单行被跳过', async () => {
|
||
const client = mockClient({ inspected: true, prepRowCount: 1 });
|
||
await expect(writeOrderEnteredCostToSupply(client, input)).resolves.toEqual({
|
||
prep_updated: 0,
|
||
purchase_updated: 0,
|
||
skipped: 'inspected',
|
||
});
|
||
expect(sqlOf(client).some((s) => s.includes('UPDATE supplier_preparations'))).toBe(false);
|
||
// 验收谓词必须限定供应商来源且实收 > 0
|
||
const inspSql = sqlOf(client).find((s) => s.includes('FROM inspections')) || '';
|
||
expect(inspSql).toContain("COALESCE(NULLIF(TRIM(source_type), ''), 'supplier') = 'supplier'");
|
||
expect(inspSql).toContain('COALESCE(actual_qty, 0) > 0');
|
||
});
|
||
});
|
||
|
||
describe('writeOrderEnteredCostToSupply 回写', () => {
|
||
it('备货行:写入订单侧成本价并留审计', async () => {
|
||
const client = mockClient({ prepRowCount: 1 });
|
||
const result = await writeOrderEnteredCostToSupply(client, input);
|
||
expect(result).toEqual({ prep_updated: 1, purchase_updated: 0 });
|
||
|
||
const prepCall = client.query.mock.calls.find(([sql]) =>
|
||
String(sql).includes('UPDATE supplier_preparations')
|
||
);
|
||
expect(String(prepCall?.[0])).toContain('SET purchase_price = $3::numeric');
|
||
expect(prepCall?.[1]).toEqual([input.orderCode, input.skuCode, 12, input.supplierCode]);
|
||
// 未作废 / 非历史修复 / 未转自采 三条保护都要在
|
||
expect(String(prepCall?.[0])).toContain('COALESCE(prepare_status, 0) < 40');
|
||
expect(String(prepCall?.[0])).toContain('COALESCE(is_history_repair, false) = false');
|
||
expect(String(prepCall?.[0])).toContain('COALESCE(transferred_to_purchase, false) = false');
|
||
|
||
expect(writeAuditLog).toHaveBeenCalledTimes(1);
|
||
expect(writeAuditLog.mock.calls[0][0]).toMatchObject({
|
||
operationType: 'order_cost_writeback',
|
||
targetTable: 'supplier_preparations',
|
||
targetId: `${input.orderCode}:${input.skuCode}`,
|
||
branchCode: 'BR004',
|
||
newValue: { unit_cost: 12, prep_updated: 1, purchase_updated: 0 },
|
||
});
|
||
});
|
||
|
||
it('备货行未命中且无自采单时不写审计', async () => {
|
||
const client = mockClient({ prepRowCount: 0, purchaseOrders: [] });
|
||
await expect(writeOrderEnteredCostToSupply(client, input)).resolves.toEqual({
|
||
prep_updated: 0,
|
||
purchase_updated: 0,
|
||
});
|
||
expect(writeAuditLog).not.toHaveBeenCalled();
|
||
});
|
||
|
||
it('自采单 status=10:改 purchase_price', async () => {
|
||
const client = mockClient({
|
||
prepRowCount: 0,
|
||
purchaseOrders: [{ purchase_code: 'PUR001', purchase_status: 10 }],
|
||
});
|
||
await expect(writeOrderEnteredCostToSupply(client, input)).resolves.toEqual({
|
||
prep_updated: 0,
|
||
purchase_updated: 1,
|
||
});
|
||
const update = client.query.mock.calls.find(([sql]) =>
|
||
String(sql).includes('UPDATE purchase_orders')
|
||
);
|
||
expect(String(update?.[0])).toContain('SET purchase_price = $2::numeric');
|
||
expect(String(update?.[0])).toContain('purchase_status = 10');
|
||
expect(update?.[1]).toEqual(['PUR001', 12]);
|
||
expect(amendPurchaseActual).not.toHaveBeenCalled();
|
||
});
|
||
|
||
it('自采单 status=20/30:走 amendPurchaseActual 只改价,不动实收数量', async () => {
|
||
for (const status of [20, 30]) {
|
||
amendPurchaseActual.mockClear();
|
||
const client = mockClient({
|
||
prepRowCount: 0,
|
||
purchaseOrders: [{ purchase_code: 'PUR002', purchase_status: status }],
|
||
});
|
||
await expect(writeOrderEnteredCostToSupply(client, input)).resolves.toEqual({
|
||
prep_updated: 0,
|
||
purchase_updated: 1,
|
||
});
|
||
expect(amendPurchaseActual).toHaveBeenCalledTimes(1);
|
||
const [payload, passedClient] = amendPurchaseActual.mock.calls[0] as unknown as [
|
||
Record<string, unknown>,
|
||
unknown,
|
||
];
|
||
expect(payload).toMatchObject({
|
||
purchaseCode: 'PUR002',
|
||
branchCode: 'BR004',
|
||
actualPrice: 12,
|
||
operatorId: 'u-1',
|
||
operatorRole: 'admin',
|
||
skipOrderItemSync: true,
|
||
preserveOrderEnteredCost: true,
|
||
preserveActualQty: true,
|
||
});
|
||
expect(passedClient).toBe(client);
|
||
// 不传 unit:单位交给 amendPurchaseActual 按订单行推导
|
||
expect('unit' in payload).toBe(false);
|
||
expect('actualQty' in payload).toBe(false);
|
||
}
|
||
});
|
||
|
||
it('回归:不得从 purchase_orders 取 unit 列(该表没有 unit)', async () => {
|
||
const client = mockClient({
|
||
prepRowCount: 0,
|
||
purchaseOrders: [{ purchase_code: 'PUR003', purchase_status: 20 }],
|
||
});
|
||
await writeOrderEnteredCostToSupply(client, input);
|
||
const select = client.query.mock.calls.find(([sql]) =>
|
||
String(sql).includes('FROM purchase_orders')
|
||
);
|
||
expect(String(select?.[0])).toContain('SELECT purchase_code, purchase_status, self_processed');
|
||
expect(String(select?.[0])).not.toMatch(/\bunit\b/);
|
||
expect(String(select?.[0])).toContain('COALESCE(purchase_status, 0) <> 40');
|
||
});
|
||
|
||
it('status=10 的仓内加工成品自采单不改价(与 amendPurchaseActual 的 0 成本守卫对齐)', async () => {
|
||
const client = mockClient({
|
||
prepRowCount: 0,
|
||
purchaseOrders: [{ purchase_code: 'PUR004', purchase_status: 10, self_processed: true }],
|
||
});
|
||
await expect(writeOrderEnteredCostToSupply(client, input)).resolves.toEqual({
|
||
prep_updated: 0,
|
||
purchase_updated: 0,
|
||
});
|
||
expect(sqlOf(client).some((s) => s.includes('UPDATE purchase_orders'))).toBe(false);
|
||
expect(writeAuditLog).not.toHaveBeenCalled();
|
||
});
|
||
|
||
it('status=10 且挂仓库需求单的自采单不改价', async () => {
|
||
linkedToWarehouseDemand.mockImplementation(async () => true);
|
||
const client = mockClient({
|
||
prepRowCount: 0,
|
||
purchaseOrders: [{ purchase_code: 'PUR005', purchase_status: 10, self_processed: false }],
|
||
});
|
||
await expect(writeOrderEnteredCostToSupply(client, input)).resolves.toEqual({
|
||
prep_updated: 0,
|
||
purchase_updated: 0,
|
||
});
|
||
expect(linkedToWarehouseDemand).toHaveBeenCalledWith('PUR005', client);
|
||
expect(sqlOf(client).some((s) => s.includes('UPDATE purchase_orders'))).toBe(false);
|
||
});
|
||
|
||
it('作废单(status=40)由 SQL 排除,不进循环', async () => {
|
||
const client = mockClient({ prepRowCount: 0, purchaseOrders: [] });
|
||
await writeOrderEnteredCostToSupply(client, input);
|
||
const select = client.query.mock.calls.find(([sql]) =>
|
||
String(sql).includes('FROM purchase_orders')
|
||
);
|
||
expect(select?.[1]).toEqual([input.orderCode, input.skuCode]);
|
||
expect(amendPurchaseActual).not.toHaveBeenCalled();
|
||
});
|
||
});
|
||
|
||
/**
|
||
* 集成点接线(`syncOrderManageItems` 写完成本价之后):改动成本价才回写;
|
||
* 必须复用**同一个事务 client**(否则订单保存回滚后回写还在);回写失败不得阻断保存。
|
||
*/
|
||
describe('orderManageItemsService 集成点', () => {
|
||
const src = readFileSync(
|
||
new URL('../src/services/orderManageItemsService.ts', import.meta.url),
|
||
'utf8'
|
||
);
|
||
const idx = src.indexOf('writeOrderEnteredCostToSupply(client');
|
||
|
||
it('改动成本价后才回写,且复用事务 client', () => {
|
||
expect(idx).toBeGreaterThan(-1);
|
||
const around = src.slice(Math.max(0, idx - 900), idx + 200);
|
||
expect(around).toContain("await import(\n './orderEnteredCostWritebackService'\n )");
|
||
expect(around).toContain('const costChanged =');
|
||
// 2026-09-24 裁决:调用点不再用 `> 0` 提前挡掉 0(0 是否回写由服务按「允许成本价为 0」开关判定)
|
||
expect(around).toContain('if (costChanged) {');
|
||
expect(around).not.toContain('if (costChanged && Number(unitCost) > 0)');
|
||
expect(around).toContain('branchCode: order.branch_code || null');
|
||
});
|
||
|
||
it('回写失败被 try/catch 吞掉并打日志(不阻断订单保存)', () => {
|
||
const around = src.slice(Math.max(0, idx - 400), idx + 900);
|
||
expect(around).toContain("console.error('[order-cost-writeback] 回写自采单/备货价失败'");
|
||
// 不得把回写错误再抛出去
|
||
expect(around).not.toMatch(/throw\s+(err|error)\b/);
|
||
});
|
||
});
|