来源仓库: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 经哈希比对与线上同值), 整包推送会把这些凭据永久带入本仓库,故只取「当前版本」的单提交快照。 供应商系统后续开发自本提交开始。
239 lines
9.4 KiB
TypeScript
239 lines
9.4 KiB
TypeScript
import { readFileSync } from 'node:fs';
|
|
import path from 'path';
|
|
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
|
|
|
const { query, connect, writeAuditLog } = vi.hoisted(() => ({
|
|
query: vi.fn(async () => ({ rows: [], rowCount: 0 })),
|
|
connect: vi.fn(),
|
|
writeAuditLog: vi.fn(async () => undefined),
|
|
}));
|
|
|
|
vi.mock('../src/db', () => ({
|
|
pool: { query, connect },
|
|
getRawPoolQuery: () => vi.fn(),
|
|
}));
|
|
|
|
vi.mock('../src/services/auditService', () => ({
|
|
writeAuditLog,
|
|
resolveOperatorProfile: vi.fn(async () => ({ name: '管理员甲', roles: 'admin' })),
|
|
}));
|
|
|
|
import {
|
|
PRICE_INVERT_AUDIT_TYPE,
|
|
PRICE_INVERT_OPERATOR_NAME,
|
|
recordPriceInvertOnOrderComplete,
|
|
recordPriceInvertOnPrepPriceApply,
|
|
} from '../src/services/priceInvertEventService';
|
|
|
|
const invertRow = {
|
|
branch_code: 'BR002',
|
|
order_code: 'ORD1',
|
|
order_item_id: '33333333-3333-3333-3333-333333333333',
|
|
sku_code: 'SKU1',
|
|
item_name: '青菜',
|
|
source_kind: 'self_purchase',
|
|
supplier_code: null,
|
|
purchaser_code: 'P001',
|
|
cost_price: 12,
|
|
sale_price: 10,
|
|
prep_id: null,
|
|
purchase_code: 'PO1',
|
|
};
|
|
|
|
function sqlOf(call: unknown[]) {
|
|
return String(call[0] || '');
|
|
}
|
|
|
|
describe('recordPriceInvertOnOrderComplete', () => {
|
|
beforeEach(() => {
|
|
query.mockReset();
|
|
writeAuditLog.mockReset();
|
|
query.mockImplementation(async () => ({ rows: [], rowCount: 0 }));
|
|
});
|
|
|
|
it('uses SAVEPOINT, complete unique conflict, cost>sale, then 系统 audit', async () => {
|
|
query.mockImplementation(async (sql: string) => {
|
|
const text = String(sql);
|
|
if (text.includes('SAVEPOINT')) return { rows: [], rowCount: 0 };
|
|
if (text.includes('RELEASE SAVEPOINT')) return { rows: [], rowCount: 0 };
|
|
if (text.includes('INSERT INTO price_invert_events')) {
|
|
return { rows: [{ id: 'e1' }], rowCount: 1 };
|
|
}
|
|
if (text.includes('invert_src') || text.includes('UNION ALL')) {
|
|
return { rows: [invertRow], rowCount: 1 };
|
|
}
|
|
return { rows: [], rowCount: 0 };
|
|
});
|
|
const client = { query } as never;
|
|
await recordPriceInvertOnOrderComplete('ORD1', client);
|
|
const sqls = query.mock.calls.map((call) => sqlOf(call as unknown[]));
|
|
expect(sqls.some((sql) => sql.includes('SAVEPOINT price_invert'))).toBe(true);
|
|
expect(sqls.some((sql) => sql.includes('RELEASE SAVEPOINT price_invert'))).toBe(true);
|
|
expect(sqls.some((sql) => sql.includes('ON CONFLICT (complete_dedupe_key)'))).toBe(true);
|
|
expect(sqls.some((sql) => sql.includes("trigger_kind = 'order_complete'"))).toBe(true);
|
|
expect(sqls.some((sql) => sql.includes('UNION ALL'))).toBe(true);
|
|
expect(sqls.join('\n')).toMatch(/\) > \(/);
|
|
expect(writeAuditLog).toHaveBeenCalledTimes(1);
|
|
expect(writeAuditLog.mock.calls[0][0]).toMatchObject({
|
|
operatorId: null,
|
|
operatorName: PRICE_INVERT_OPERATOR_NAME,
|
|
operationType: PRICE_INVERT_AUDIT_TYPE,
|
|
targetTable: 'price_invert_events',
|
|
targetId: 'ORD1',
|
|
});
|
|
expect(writeAuditLog.mock.calls[0][0].newValue).toMatchObject({
|
|
trigger_kind: 'order_complete',
|
|
order_code: 'ORD1',
|
|
items: [expect.objectContaining({ item_name: '青菜', cost_price: 12, sale_price: 10 })],
|
|
});
|
|
});
|
|
|
|
it('INSERT failure rolls back savepoint and does not throw', async () => {
|
|
query.mockImplementation(async (sql: string) => {
|
|
const text = String(sql);
|
|
if (text.includes('INSERT INTO price_invert_events')) {
|
|
throw Object.assign(new Error('boom'), { code: '42P01' });
|
|
}
|
|
if (text.includes('invert_src') || text.includes('UNION ALL')) {
|
|
return { rows: [invertRow], rowCount: 1 };
|
|
}
|
|
return { rows: [], rowCount: 0 };
|
|
});
|
|
await expect(
|
|
recordPriceInvertOnOrderComplete('ORD1', { query } as never)
|
|
).resolves.toBeUndefined();
|
|
const sqls = query.mock.calls.map((call) => sqlOf(call as unknown[]));
|
|
expect(sqls.some((sql) => sql.includes('ROLLBACK TO SAVEPOINT price_invert'))).toBe(true);
|
|
expect(writeAuditLog).not.toHaveBeenCalled();
|
|
});
|
|
});
|
|
|
|
describe('recordPriceInvertOnPrepPriceApply', () => {
|
|
beforeEach(() => {
|
|
query.mockReset();
|
|
connect.mockReset();
|
|
writeAuditLog.mockReset();
|
|
});
|
|
|
|
it('empty ids skip sql', async () => {
|
|
await recordPriceInvertOnPrepPriceApply([]);
|
|
expect(query).not.toHaveBeenCalled();
|
|
expect(connect).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it('without client opens own BEGIN after caller COMMIT', async () => {
|
|
const ownQuery = vi.fn(async (sql: string) => {
|
|
const text = String(sql);
|
|
if (text.includes('FROM supplier_preparations')) {
|
|
return {
|
|
rows: [
|
|
{
|
|
...invertRow,
|
|
source_kind: 'supplier_prep',
|
|
prep_id: '44444444-4444-4444-4444-444444444444',
|
|
purchase_code: null,
|
|
purchaser_code: null,
|
|
supplier_code: 'S1',
|
|
},
|
|
],
|
|
rowCount: 1,
|
|
};
|
|
}
|
|
if (text.includes('INSERT INTO price_invert_events')) {
|
|
return { rows: [{ id: 'e2' }], rowCount: 1 };
|
|
}
|
|
return { rows: [], rowCount: 0 };
|
|
});
|
|
connect.mockResolvedValue({ query: ownQuery, release: vi.fn() });
|
|
await recordPriceInvertOnPrepPriceApply(
|
|
['44444444-4444-4444-4444-444444444444'],
|
|
undefined,
|
|
{ operatorId: 'user-1', operatorRole: 'admin' }
|
|
);
|
|
const sqls = ownQuery.mock.calls.map((call) => sqlOf(call as unknown[]));
|
|
expect(sqls[0]).toBe('BEGIN');
|
|
const insertCall = ownQuery.mock.calls.find((call) =>
|
|
String(call[0] || '').includes('INSERT INTO price_invert_events')
|
|
);
|
|
expect(insertCall?.[1]).toEqual(expect.arrayContaining(['prep_price_apply']));
|
|
expect(sqls.some((sql) => sql === 'COMMIT')).toBe(true);
|
|
expect(writeAuditLog).toHaveBeenCalledTimes(1);
|
|
expect(writeAuditLog.mock.calls[0][0]).toMatchObject({
|
|
operatorId: 'user-1',
|
|
operatorName: '管理员甲',
|
|
operatorRole: 'admin',
|
|
});
|
|
expect(writeAuditLog.mock.calls[0][0].newValue).toMatchObject({
|
|
trigger_kind: 'prep_price_apply',
|
|
});
|
|
});
|
|
});
|
|
|
|
describe('源码合同:旁路不进结案主 UPDATE、改价仅落价后、申请不写', () => {
|
|
const root = path.join(__dirname, '..');
|
|
|
|
it('finalize core records invert after SET 90, not in the same SQL', () => {
|
|
const src = readFileSync(
|
|
path.join(root, 'src/services/orderWorkflowFulfillmentService.ts'),
|
|
'utf8'
|
|
);
|
|
const coreStart = src.indexOf('async function finalizeOrderFulfillmentCore');
|
|
const core = src.slice(coreStart, src.indexOf('export async function finalizeOrderFulfillment'));
|
|
const set90 = core.indexOf('SET order_status = 90');
|
|
const invertAt = core.indexOf('recordPriceInvertOnOrderComplete');
|
|
expect(set90).toBeGreaterThan(0);
|
|
expect(invertAt).toBeGreaterThan(set90);
|
|
expect(core).toContain('ensureSupplierStatementsForOrder');
|
|
expect(invertAt).toBeGreaterThan(core.indexOf('ensureSupplierStatementsForOrder'));
|
|
const updateSql = core.slice(core.indexOf('UPDATE orders SET order_status = 90'), core.indexOf('return true'));
|
|
expect(updateSql).not.toContain('price_invert_events');
|
|
expect(src).toContain('priceInvertEventService');
|
|
});
|
|
|
|
it('event service never throws past SAVEPOINT rollback', () => {
|
|
const src = readFileSync(path.join(root, 'src/services/priceInvertEventService.ts'), 'utf8');
|
|
expect(src).toContain('SAVEPOINT ${SAVEPOINT}');
|
|
expect(src).toContain('ROLLBACK TO SAVEPOINT');
|
|
expect(src).toContain('resolveInvertActor');
|
|
expect(src).toContain('actor.operatorName');
|
|
expect(src).toContain("'order_complete'");
|
|
expect(src).toContain("'prep_price_apply'");
|
|
expect(src).not.toContain('throw err');
|
|
});
|
|
|
|
it('prep price apply is after COMMIT; submit amend request does not record', () => {
|
|
const prep = readFileSync(
|
|
path.join(root, 'src/services/supplierPreparationStatusService.ts'),
|
|
'utf8'
|
|
);
|
|
const fnStart = prep.indexOf('export async function updatePreparationPurchasePrice');
|
|
const fn = prep.slice(fnStart, prep.indexOf('export async function updateSupplierPreparationStatus'));
|
|
expect(fn.indexOf("await client.query('COMMIT')")).toBeGreaterThan(0);
|
|
expect(fn.indexOf('recordPriceInvertOnPrepPriceApply')).toBeGreaterThan(
|
|
fn.indexOf("await client.query('COMMIT')")
|
|
);
|
|
expect(fn).toContain('operatorId: options?.operatorId');
|
|
const submit = readFileSync(path.join(root, 'src/services/prepAmendRequestService.ts'), 'utf8');
|
|
const submitStart = submit.indexOf('export async function submitPrepAmendRequest');
|
|
const submitFn = submit.slice(submitStart, submit.indexOf('export async function', submitStart + 10));
|
|
expect(submitFn).not.toContain('recordPriceInvert');
|
|
expect(submit).toContain('updatePreparationPurchasePrice');
|
|
});
|
|
|
|
it('migration registers tenant table and is not in ALLOWED_TABLES', () => {
|
|
const mig = readFileSync(
|
|
path.join(root, '../migrations/20260921_price_invert_events.sql'),
|
|
'utf8'
|
|
);
|
|
expect(mig).toContain("'price_invert_events'");
|
|
expect(mig).toContain("'assistant_conversations'");
|
|
expect(mig).toContain("'assistant_messages'");
|
|
expect(mig).toContain('tenant_business_tables');
|
|
expect(mig).toContain('complete_dedupe_key');
|
|
const policy = readFileSync(path.join(root, 'src/services/accessPolicy.ts'), 'utf8');
|
|
expect(policy).not.toContain('price_invert_events');
|
|
const rating = readFileSync(path.join(root, 'src/services/supplierRatingService.ts'), 'utf8');
|
|
expect(rating).not.toContain('price_invert_events');
|
|
});
|
|
});
|