来源仓库: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 经哈希比对与线上同值), 整包推送会把这些凭据永久带入本仓库,故只取「当前版本」的单提交快照。 供应商系统后续开发自本提交开始。
320 lines
12 KiB
TypeScript
320 lines
12 KiB
TypeScript
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||
import { readFileSync } from 'node:fs';
|
||
import path from 'node:path';
|
||
|
||
const mocks = vi.hoisted(() => ({
|
||
writeAuditLog: vi.fn(async () => undefined),
|
||
removeCustomerStatementForOrder: vi.fn(async () => undefined),
|
||
recalculateStatementsFromRefs: vi.fn(async () => 'ok'),
|
||
releaseReservationsForOrder: vi.fn(async () => undefined),
|
||
syncWarehouseProcessingDemandForOrder: vi.fn(async () => undefined),
|
||
deleteNotificationsByRelatedOrderCode: vi.fn(async () => ({ deleted: 0, userIds: [] })),
|
||
}));
|
||
|
||
vi.mock('../src/db', () => ({
|
||
pool: { connect: vi.fn(), query: vi.fn() },
|
||
getRawPoolQuery: () => vi.fn(),
|
||
}));
|
||
vi.mock('../src/services/auditService', () => ({ writeAuditLog: mocks.writeAuditLog }));
|
||
vi.mock('../src/services/financeReconciliationService', () => ({
|
||
removeCustomerStatementForOrder: mocks.removeCustomerStatementForOrder,
|
||
recalculateStatementsFromRefs: mocks.recalculateStatementsFromRefs,
|
||
recalculateStatementsAffectedByOrder: vi.fn(),
|
||
upsertCustomerStatementForOrder: vi.fn(),
|
||
}));
|
||
vi.mock('../src/services/inventoryStockCoverService', () => ({
|
||
releaseReservationsForOrder: mocks.releaseReservationsForOrder,
|
||
}));
|
||
vi.mock('../src/services/processingDemandSheetService', () => ({
|
||
syncWarehouseProcessingDemandForOrder: mocks.syncWarehouseProcessingDemandForOrder,
|
||
}));
|
||
vi.mock('../src/services/notificationService', () => ({
|
||
deleteNotificationsByRelatedOrderCode: mocks.deleteNotificationsByRelatedOrderCode,
|
||
}));
|
||
vi.mock('../src/services/notificationStreamService', () => ({
|
||
listBellNotifications: vi.fn(),
|
||
publishNotificationEvent: vi.fn(),
|
||
}));
|
||
|
||
import { deleteOrderWithDependencies, moveOrderToTrash } from '../src/services/orderDeleteService';
|
||
import { pool } from '../src/db';
|
||
|
||
describe('deleteOrderWithDependencies order tree cleanup', () => {
|
||
beforeEach(() => {
|
||
vi.clearAllMocks();
|
||
});
|
||
|
||
it('deletes item dependants before the order when tenant FKs are absent', async () => {
|
||
const statements: string[] = [];
|
||
const client = {
|
||
query: vi.fn(async (sql: string) => {
|
||
statements.push(sql.replace(/\s+/g, ' ').trim());
|
||
if (sql.includes('FROM orders o') && sql.includes('FOR UPDATE')) {
|
||
return {
|
||
rowCount: 1,
|
||
rows: [{
|
||
order_code: 'ORD-PURGE',
|
||
branch_code: 'BR001',
|
||
order_status: 20,
|
||
customer_code: 'C001',
|
||
total_amount: 10,
|
||
delivery_date: '2026-09-08',
|
||
cycle_code: null,
|
||
deleted_at: new Date().toISOString(),
|
||
item_count: 1,
|
||
}],
|
||
};
|
||
}
|
||
if (sql.includes('FROM order_items') && sql.includes('LIMIT')) {
|
||
return {
|
||
rowCount: 1,
|
||
rows: [{
|
||
sku_code: 'SKU1',
|
||
item_name: '青菜',
|
||
quantity: 2,
|
||
unit: '斤',
|
||
price: 1,
|
||
locked_price: 3.5,
|
||
unit_cost: 2,
|
||
}],
|
||
};
|
||
}
|
||
if (sql.includes('SELECT DISTINCT statement_no')) return { rowCount: 0, rows: [] };
|
||
if (sql.includes('SELECT task_code FROM delivery_tasks')) return { rowCount: 0, rows: [] };
|
||
if (sql.includes('SELECT to_regclass')) return { rowCount: 1, rows: [{ reg: 'present' }] };
|
||
if (sql.includes('information_schema.columns')) return { rowCount: 1, rows: [{ '?column?': 1 }] };
|
||
if (sql.includes('FROM profiles WHERE id')) return { rowCount: 1, rows: [{ operator_name: 'Admin' }] };
|
||
if (sql.startsWith('DELETE FROM orders')) {
|
||
return { rowCount: 1, rows: [{ order_code: 'ORD-PURGE' }] };
|
||
}
|
||
if (sql.startsWith('DELETE')) return { rowCount: 1, rows: [] };
|
||
return { rowCount: 0, rows: [] };
|
||
}),
|
||
release: vi.fn(),
|
||
};
|
||
|
||
const result = await deleteOrderWithDependencies(
|
||
'ORD-PURGE',
|
||
{
|
||
userId: '00000000-0000-0000-0000-000000000001',
|
||
roles: ['admin'],
|
||
permissions: [],
|
||
branchCode: 'BR001',
|
||
isSuperAdmin: true,
|
||
isBranchAdmin: false,
|
||
},
|
||
client as never
|
||
);
|
||
|
||
expect(result.deleted_related).toMatchObject({
|
||
picking_items: 1,
|
||
order_item_fulfillments: 1,
|
||
order_item_returns: 1,
|
||
order_items: 1,
|
||
});
|
||
const indexOfDelete = (table: string) =>
|
||
statements.findIndex((sql) => sql.startsWith(`DELETE FROM ${table} `));
|
||
expect(indexOfDelete('picking_items')).toBeLessThan(indexOfDelete('order_item_fulfillments'));
|
||
expect(indexOfDelete('order_item_fulfillments')).toBeLessThan(indexOfDelete('order_item_returns'));
|
||
expect(indexOfDelete('order_item_returns')).toBeLessThan(indexOfDelete('order_items'));
|
||
expect(indexOfDelete('order_items')).toBeLessThan(indexOfDelete('orders'));
|
||
expect(mocks.writeAuditLog).toHaveBeenCalledWith(
|
||
expect.objectContaining({
|
||
operationType: 'order_purge',
|
||
oldValue: expect.objectContaining({
|
||
items: [
|
||
expect.objectContaining({
|
||
sku_code: 'SKU1',
|
||
item_name: '青菜',
|
||
quantity: 2,
|
||
sale_price: 3.5,
|
||
unit_cost: 2,
|
||
}),
|
||
],
|
||
items_truncated: false,
|
||
}),
|
||
})
|
||
);
|
||
});
|
||
|
||
it('清干净分拣/预留/竞价等子表,但绝不动库存流水台账', async () => {
|
||
const statements: string[] = [];
|
||
const client = {
|
||
query: vi.fn(async (sql: string) => {
|
||
statements.push(sql.replace(/\s+/g, ' ').trim());
|
||
if (sql.includes('FROM orders o') && sql.includes('FOR UPDATE')) {
|
||
return {
|
||
rowCount: 1,
|
||
rows: [{
|
||
order_code: 'ORD-PURGE',
|
||
branch_code: 'BR001',
|
||
order_status: 20,
|
||
customer_code: 'C001',
|
||
total_amount: 10,
|
||
delivery_date: '2026-09-08',
|
||
cycle_code: null,
|
||
deleted_at: new Date().toISOString(),
|
||
item_count: 1,
|
||
}],
|
||
};
|
||
}
|
||
if (sql.includes('FROM order_items') && sql.includes('LIMIT')) {
|
||
return { rowCount: 1, rows: [{ sku_code: 'SKU1', item_name: '青菜', quantity: 2, unit: '斤', price: 1, locked_price: 3.5, unit_cost: 2 }] };
|
||
}
|
||
if (sql.includes('SELECT DISTINCT statement_no')) return { rowCount: 0, rows: [] };
|
||
if (sql.includes('SELECT task_code FROM delivery_tasks')) return { rowCount: 0, rows: [] };
|
||
if (sql.includes('SELECT to_regclass')) return { rowCount: 1, rows: [{ reg: 'present' }] };
|
||
if (sql.includes('information_schema.columns')) return { rowCount: 1, rows: [{ '?column?': 1 }] };
|
||
if (sql.includes('FROM profiles WHERE id')) return { rowCount: 1, rows: [{ operator_name: 'Admin' }] };
|
||
if (sql.startsWith('DELETE FROM orders')) return { rowCount: 1, rows: [{ order_code: 'ORD-PURGE' }] };
|
||
if (sql.startsWith('DELETE')) return { rowCount: 1, rows: [] };
|
||
return { rowCount: 0, rows: [] };
|
||
}),
|
||
release: vi.fn(),
|
||
};
|
||
|
||
const result = await deleteOrderWithDependencies(
|
||
'ORD-PURGE',
|
||
{
|
||
userId: '00000000-0000-0000-0000-000000000001',
|
||
roles: ['admin'],
|
||
permissions: [],
|
||
branchCode: 'BR001',
|
||
isSuperAdmin: true,
|
||
isBranchAdmin: false,
|
||
},
|
||
client as never
|
||
);
|
||
|
||
// 2026-09-23 补齐的 5 张(原先漏清 → 实测 br003 留 49/29/312/11/2 行孤儿)
|
||
expect(result.deleted_related).toMatchObject({
|
||
picking_containers: 1,
|
||
picking_tasks: 1,
|
||
inventory_reservations: 1,
|
||
bid_rounds: 1,
|
||
supplier_prep_amend_requests: 1,
|
||
});
|
||
|
||
const indexOfDelete = (table: string) =>
|
||
statements.findIndex((sql) => sql.startsWith(`DELETE FROM ${table} `));
|
||
// 子表先于父表:picking_items → picking_containers/picking_tasks → order_items → orders
|
||
expect(indexOfDelete('picking_items')).toBeLessThan(indexOfDelete('picking_containers'));
|
||
expect(indexOfDelete('picking_containers')).toBeLessThan(indexOfDelete('picking_tasks'));
|
||
expect(indexOfDelete('picking_tasks')).toBeLessThan(indexOfDelete('order_items'));
|
||
expect(indexOfDelete('order_items')).toBeLessThan(indexOfDelete('orders'));
|
||
|
||
// 台账/通知不得走裸 DELETE:
|
||
// - inventory_logs 是库存流水台账,硬删订单不回滚 inventory,删流水会造成「有库存无流水」
|
||
// (定性见 docs/design/20260920-inventory-freeze.md §11)
|
||
// - notifications 由 deleteNotificationsByRelatedOrderCode 清理(其 related_order_code
|
||
// 混存 UUID 形态,通用 NOT EXISTS 模板会误删非订单通知)
|
||
expect(statements.filter((sql) => /\bFROM\s+inventory_logs\b/i.test(sql))).toEqual([]);
|
||
expect(statements.filter((sql) => /\bFROM\s+notifications\b/i.test(sql))).toEqual([]);
|
||
expect(mocks.deleteNotificationsByRelatedOrderCode).toHaveBeenCalledWith('ORD-PURGE', expect.anything());
|
||
});
|
||
|
||
it('孤儿清理清单与硬删清单口径一致,且不得含库存流水台账 / 通知', () => {
|
||
const src = readFileSync(path.join(__dirname, '../src/services/orderDeleteService.ts'), 'utf8');
|
||
const block = src.match(
|
||
/const targets: Array<\{ table: string; column: string \}> = \[([\s\S]*?)\n {2}\];/
|
||
);
|
||
expect(block, '未找到 cleanupOrphanOrderDependencies 的 targets 清单,结构可能已变更').toBeTruthy();
|
||
const tables = [...block![1].matchAll(/table: '([a-z_]+)'/g)].map((m) => m[1]);
|
||
|
||
// 台账与通知**不得**进通用清理清单:
|
||
// - inventory_logs:库存流水台账,随订单硬删保留(见 20260920-inventory-freeze.md §11)
|
||
// - notifications:related_order_code 混存 UUID 形态,通用 NOT EXISTS 模板会误删非订单通知
|
||
expect(tables).not.toContain('inventory_logs');
|
||
expect(tables).not.toContain('notifications');
|
||
|
||
// 2026-09-23 补齐的 5 张 + 订单树子表必须在内(防回退)
|
||
for (const table of [
|
||
'picking_items',
|
||
'order_item_fulfillments',
|
||
'order_item_returns',
|
||
'picking_containers',
|
||
'picking_tasks',
|
||
'inventory_reservations',
|
||
'bid_rounds',
|
||
'supplier_prep_amend_requests',
|
||
'order_items',
|
||
]) {
|
||
expect(tables, `孤儿清理清单缺少 ${table}`).toContain(table);
|
||
}
|
||
});
|
||
|
||
it('writes item snapshot on trash audit', async () => {
|
||
const client = {
|
||
query: vi.fn(async (sql: string) => {
|
||
const text = sql.replace(/\s+/g, ' ').trim();
|
||
if (text.includes('FROM orders o') && text.includes('FOR UPDATE')) {
|
||
return {
|
||
rowCount: 1,
|
||
rows: [{
|
||
order_code: 'ORD-TRASH',
|
||
branch_code: 'BR001',
|
||
order_status: 20,
|
||
customer_code: 'C001',
|
||
total_amount: 10,
|
||
delivery_date: '2026-09-08',
|
||
cycle_code: null,
|
||
deleted_at: null,
|
||
item_count: 1,
|
||
}],
|
||
};
|
||
}
|
||
if (text.includes('FROM order_items') && text.includes('LIMIT')) {
|
||
return {
|
||
rowCount: 1,
|
||
rows: [{
|
||
sku_code: 'SKU1',
|
||
item_name: '豆腐',
|
||
quantity: 1,
|
||
unit: '块',
|
||
price: 4,
|
||
locked_price: 0,
|
||
unit_cost: 2,
|
||
}],
|
||
};
|
||
}
|
||
if (text.includes('FROM profiles WHERE id')) {
|
||
return { rowCount: 1, rows: [{ operator_name: 'Admin' }] };
|
||
}
|
||
if (text.startsWith('UPDATE orders')) {
|
||
return { rowCount: 1, rows: [{ order_code: 'ORD-TRASH' }] };
|
||
}
|
||
return { rowCount: 0, rows: [] };
|
||
}),
|
||
release: vi.fn(),
|
||
};
|
||
vi.mocked(pool.connect).mockResolvedValue(client as never);
|
||
|
||
await moveOrderToTrash(
|
||
'ORD-TRASH',
|
||
{
|
||
userId: '00000000-0000-0000-0000-000000000001',
|
||
roles: ['admin'],
|
||
permissions: [],
|
||
branchCode: 'BR001',
|
||
isSuperAdmin: true,
|
||
isBranchAdmin: false,
|
||
}
|
||
);
|
||
|
||
expect(mocks.writeAuditLog).toHaveBeenCalledWith(
|
||
expect.objectContaining({
|
||
operationType: 'order_trash',
|
||
oldValue: expect.objectContaining({
|
||
items: [
|
||
expect.objectContaining({
|
||
item_name: '豆腐',
|
||
quantity: 1,
|
||
sale_price: 4,
|
||
}),
|
||
],
|
||
}),
|
||
})
|
||
);
|
||
});
|
||
});
|