Files
Ubuntu 5a54480bdc
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
feat(产地): 上报带主系统订单号 + 主系统 SKU(可注入解析器)
- 供应商 SKU → 主系统 SKU:默认读本地只读镜像 main_system_sku_mappings(active),
  抽成可注入 resolveMainSku(测试用纯函数,避免依赖租户上下文)
- 未映射 ⇒ 跳过不上报(仅日志),不影响取货/到仓主流程
- preparations/status body 增 order_code + sku_code(主系统可据此直接定位订单行)
- 测试:16 passed(注入解析器后原两条用例恢复)
2026-10-20 13:13:14 +08:00

327 lines
14 KiB
TypeScript
Raw Permalink 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.
import { beforeEach, describe, expect, it, vi } from 'vitest';
/**
* 批次级产地(2026-10-21)增量测试。
*
* 冻结口径:产地 = **批次级 + 商品档案默认值**;批次报告与「取货完成/配送上仓库完成」两个节点都发;
* 有产地才发;发送失败 fire-and-forget(日志,不影响主流程);主系统只落库 + 溯源显示文本。
*/
const poolQuery = vi.hoisted(() => vi.fn());
const clientQuery = vi.hoisted(() => vi.fn());
const clientRelease = vi.hoisted(() => vi.fn());
vi.mock('../src/db', () => ({
pool: {
query: (...args: unknown[]) => poolQuery(...args),
connect: async () => ({
query: (...args: unknown[]) => clientQuery(...args),
release: () => clientRelease(),
}),
},
getRawPoolQuery: () => poolQuery,
}));
const writeAuditLog = vi.hoisted(() => vi.fn());
vi.mock('../src/services/auditService', () => ({
writeAuditLog: (...args: unknown[]) => writeAuditLog(...args),
}));
// 出站:token / http 全 mock(零网络)
const requestMainSystem = vi.hoisted(() => vi.fn());
const getMainSystemToken = vi.hoisted(() => vi.fn());
vi.mock('../src/services/mainSystem/http', () => ({
requestMainSystem: (...args: unknown[]) => requestMainSystem(...args),
}));
vi.mock('../src/services/mainSystem/token', () => ({
getMainSystemToken: (...args: unknown[]) => getMainSystemToken(...args),
}));
// 节点上报:配置开关 + 备货行供应商编码 + 状态回写全 mock
const isMainSystemIntegrationEnabled = vi.hoisted(() => vi.fn(() => true));
vi.mock('../src/services/mainSystem/config', async (importOriginal) => {
const actual = await importOriginal<typeof import('../src/services/mainSystem/config')>();
return { ...actual, isMainSystemIntegrationEnabled: () => isMainSystemIntegrationEnabled() };
});
const resolveSupplierCodeForPrep = vi.hoisted(() => vi.fn());
vi.mock('../src/services/branchAccessCode', () => ({
resolveSupplierCodeForPrep: (...args: unknown[]) => resolveSupplierCodeForPrep(...args),
}));
const writebackMainSystemPreparationStatus = vi.hoisted(() => vi.fn());
vi.mock('../src/services/mainSystemPreparations', () => ({
writebackMainSystemPreparationStatus: (...args: unknown[]) => writebackMainSystemPreparationStatus(...args),
}));
const tenantCtx = vi.hoisted(() => vi.fn());
vi.mock('../src/services/tenantDbContext', () => ({
runWithTenantDbContext: (...args: unknown[]) => tenantCtx(...args),
}));
import { updateInventoryBatchAttributes } from '../src/services/inventoryBatchEditService';
import { registerBatchReportOnPreparation } from '../src/services/mainSystem/api/qualityReports';
import { reportBatchOriginsToMainSystem } from '../src/services/batchOriginReportService';
import { readFileSync } from 'node:fs';
const read = (rel: string) => readFileSync(new URL(rel, import.meta.url), 'utf8');
type DbState = {
inventory: Record<string, unknown>;
sql: string[];
updates: Array<{ sql: string; params: unknown[] }>;
};
function installDb(state: DbState): void {
const handler = async (sql: string, params: unknown[] = []) => {
const text = String(sql);
state.sql.push(text);
if (text.includes('FROM inventory') && text.includes('FOR UPDATE')) {
return { rows: [state.inventory], rowCount: 1 };
}
if (text.startsWith('UPDATE inventory SET')) {
state.updates.push({ sql: text, params: [...params] });
return { rows: [], rowCount: 1 };
}
if (text.includes('FROM skus WHERE sku_code')) {
return { rows: [{ sku_name: '草鱼', category_code: 'C1', spec: '1斤', unit: '斤', origin: '旧档案产地' }], rowCount: 1 };
}
return { rows: [], rowCount: 0 };
};
clientQuery.mockImplementation((sql: string, params?: unknown[]) => handler(sql, params || []));
poolQuery.mockImplementation((sql: string, params?: unknown[]) => handler(sql, params || []));
}
function makeState(): DbState {
return {
inventory: {
id: 'inv-1',
batch_no: 'STK001',
sku_code: 'SKU1',
storage_zone: 'A1',
shelf_life: '7天',
expiry_date: '2026-10-28',
production_date: '2026-10-21',
cost_price: '10.00',
origin: null,
},
sql: [],
updates: [],
};
}
beforeEach(() => {
clientQuery.mockReset();
poolQuery.mockReset();
clientRelease.mockReset();
writeAuditLog.mockReset();
writeAuditLog.mockResolvedValue(undefined);
requestMainSystem.mockReset();
getMainSystemToken.mockReset();
getMainSystemToken.mockResolvedValue({ kind: 'ok', token: 't' });
resolveSupplierCodeForPrep.mockReset();
resolveSupplierCodeForPrep.mockResolvedValue('SUP1');
writebackMainSystemPreparationStatus.mockReset();
writebackMainSystemPreparationStatus.mockResolvedValue({ kind: 'ok', updated: 1, skipped: [], needsCustomerPrice: false });
isMainSystemIntegrationEnabled.mockReturnValue(true);
tenantCtx.mockReset();
tenantCtx.mockImplementation(async (_branch: string, fn: () => Promise<unknown>) => fn());
});
describe('批次级产地:写入 / 清空 / 超长拒绝', () => {
it('写入批次产地 ⇒ UPDATE inventory 带 origin,changed 含 origin,审计留痕', async () => {
const state = makeState();
installDb(state);
const result = await updateInventoryBatchAttributes({
inventoryId: 'inv-1',
branchCode: 'BR002',
operatorId: 'u1',
remark: '',
batchOrigin: '四川雅安',
});
expect(result.changed).toContain('origin');
const update = state.updates.find((u) => u.sql.includes('origin = $'));
expect(update, state.updates.map((u) => u.sql).join('\n')).toBeTruthy();
expect(update!.sql).toContain('origin = $');
expect(update!.params).toContain('四川雅安');
await new Promise((r) => setTimeout(r, 0));
expect(writeAuditLog).toHaveBeenCalled();
});
it('清空批次产地(空串)⇒ origin 写 NULL', async () => {
const state = makeState();
state.inventory.origin = '四川雅安';
installDb(state);
const result = await updateInventoryBatchAttributes({
inventoryId: 'inv-1',
branchCode: 'BR002',
remark: '',
batchOrigin: '',
});
expect(result.changed).toContain('origin');
const update = state.updates.find((u) => u.sql.includes('origin = $'));
expect(update).toBeTruthy();
expect(update!.params[0]).toBeNull(); // 清空落 NULL(不是空串)
});
it('同值不改 ⇒ 不产生 UPDATE(无变化不写、不审计)', async () => {
const state = makeState();
state.inventory.origin = '四川雅安';
installDb(state);
const result = await updateInventoryBatchAttributes({
inventoryId: 'inv-1',
branchCode: 'BR002',
remark: '',
batchOrigin: '四川雅安 ',
});
expect(result.changed).not.toContain('origin');
expect(state.updates.filter((u) => u.sql.includes('origin = $'))).toHaveLength(0);
});
it('超长(>200)⇒ 400 invalid_origin,且零 UPDATE', async () => {
const state = makeState();
installDb(state);
await expect(
updateInventoryBatchAttributes({
inventoryId: 'inv-1',
branchCode: 'BR002',
remark: '',
batchOrigin: '四'.repeat(201),
})
).rejects.toMatchObject({ status: 400, code: 'invalid_origin' });
expect(state.updates).toHaveLength(0);
});
});
describe('批次报告登记:origin 批次优先,空则回退商品档案', () => {
const base = {
supplierCode: 'SUP1',
preparationId: 'prep-1',
files: ['a.pdf'],
reportType: 'batch',
};
it('带 origin ⇒ body.origin(≤200)', async () => {
requestMainSystem.mockResolvedValue({ kind: 'ok', status: 200, data: {}, payload: { data: { id: 'r1' } } });
await registerBatchReportOnPreparation({ ...base, origin: '四川雅安' });
const body = (requestMainSystem.mock.calls[0][0] as any).body;
expect(body.origin).toBe('四川雅安');
});
it('空 origin ⇒ 不带该字段(旧行为不变)', async () => {
requestMainSystem.mockResolvedValue({ kind: 'ok', status: 200, data: {}, payload: { data: { id: 'r1' } } });
await registerBatchReportOnPreparation({ ...base, origin: '' });
const body = (requestMainSystem.mock.calls[0][0] as any).body;
expect('origin' in body).toBe(false);
});
it('超长 origin ⇒ 截断到 200(主系统只落文本,不校验)', async () => {
requestMainSystem.mockResolvedValue({ kind: 'ok', status: 200, data: {}, payload: { data: { id: 'r1' } } });
await registerBatchReportOnPreparation({ ...base, origin: '四'.repeat(260) });
const body = (requestMainSystem.mock.calls[0][0] as any).body;
expect(String(body.origin)).toHaveLength(200);
});
it('候选 SQL:批次产地优先、商品档案 origin 兜底', () => {
const pushService = read('../src/services/mainSystemReportPushService.ts');
expect(pushService).toContain('inv.origin AS batch_origin');
expect(pushService).toContain('sk.origin AS sku_origin');
expect(pushService).toContain('NULLIF(TRIM(h.batch_origin)');
expect(pushService).toContain('NULLIF(TRIM(h.sku_origin)');
expect(pushService).toContain('origin: candidate.origin');
});
});
describe('取货完成 / 配送上仓库完成:有产地才报、失败不影响主流程', () => {
const batchRows = [
{
sku_code: 'SKU1',
batch_no: 'STK001',
origin: '四川雅安',
prep_ids: ['prep-1'],
main_supplier_code: 'SUP1',
},
];
it('有产地 ⇒ 调既有 preparations/status 回写(status=30 + batch_no + origin)', async () => {
poolQuery.mockImplementation(async (sql: string) => {
if (String(sql).includes('main_system_order_imports')) return { rows: [{ branch_code: 'BR002' }] };
return { rows: [], rowCount: 0 };
});
clientQuery.mockImplementation(async (sql: string) => {
if (String(sql).includes('WITH consumed')) return { rows: batchRows, rowCount: 1 };
return { rows: [], rowCount: 0 };
});
// 该方法用 pool.query 查询 consumed(runWithTenantDbContext 内)
poolQuery.mockImplementation(async (sql: string) => {
if (String(sql).includes('WITH consumed')) return { rows: batchRows, rowCount: 1 };
if (String(sql).includes('main_system_order_imports')) return { rows: [{ branch_code: 'BR002' }] };
return { rows: [], rowCount: 0 };
});
const result = await reportBatchOriginsToMainSystem({ orderCode: 'ORD1', node: 'pickup_complete', resolveMainSku: async () => 'MAIN_SKU_1' });
expect(result.sent).toBe(1);
expect(writebackMainSystemPreparationStatus).toHaveBeenCalledWith(
expect.objectContaining({ preparationId: 'prep-1', status: 30, batchNo: 'STK001', origin: '四川雅安' })
);
});
it('没有产地 ⇒ 零出站(不上报)', async () => {
poolQuery.mockImplementation(async (sql: string) => {
if (String(sql).includes('WITH consumed')) return { rows: [], rowCount: 0 };
if (String(sql).includes('main_system_order_imports')) return { rows: [{ branch_code: 'BR002' }] };
return { rows: [], rowCount: 0 };
});
const result = await reportBatchOriginsToMainSystem({ orderCode: 'ORD1', node: 'inbound_complete', resolveMainSku: async () => 'MAIN_SKU_1' });
expect(result.sent).toBe(0);
expect(writebackMainSystemPreparationStatus).not.toHaveBeenCalled();
});
it('上报异常 ⇒ 吞掉并记 failed,**绝不抛错**(不阻塞/不回滚主流程)', async () => {
poolQuery.mockRejectedValue(new Error('db down'));
const result = await reportBatchOriginsToMainSystem({ orderCode: 'ORD1', node: 'pickup_complete', resolveMainSku: async () => 'MAIN_SKU_1' });
expect(result.failed).toBeGreaterThan(0);
await expect(Promise.resolve(result)).resolves.toBeTruthy();
});
it('回写返回失败 ⇒ 记 failed,不抛错', async () => {
poolQuery.mockImplementation(async (sql: string) => {
if (String(sql).includes('WITH consumed')) return { rows: batchRows, rowCount: 1 };
if (String(sql).includes('main_system_order_imports')) return { rows: [{ branch_code: 'BR002' }] };
return { rows: [], rowCount: 0 };
});
writebackMainSystemPreparationStatus.mockResolvedValue({ kind: 'rejected', reason: 'locked' });
const result = await reportBatchOriginsToMainSystem({ orderCode: 'ORD1', node: 'pickup_complete', resolveMainSku: async () => 'MAIN_SKU_1' });
expect(result.failed).toBe(1);
});
it('两个节点在结案成功后 fire-and-forget 调用(源码接线)', () => {
const fulfillment = read('../src/services/orderWorkflowFulfillmentService.ts');
const pickupIdx = fulfillment.indexOf("node: 'pickup_complete'");
const inboundIdx = fulfillment.indexOf("node: 'inbound_complete'");
expect(pickupIdx).toBeGreaterThan(-1);
expect(inboundIdx).toBeGreaterThan(-1);
// 都在 `if (done)` 之后、且由 fireAndForgetBatchOriginReport 发起(不 await)
expect(fulfillment).toMatch(/if \(done\) fireAndForgetBatchOriginReport\(\{ orderCode, node: 'pickup_complete' \}\);/);
expect(fulfillment).toMatch(/if \(done\) fireAndForgetBatchOriginReport\(\{ orderCode, node: 'inbound_complete' \}\);/);
expect(fulfillment).not.toMatch(/await fireAndForgetBatchOriginReport/);
});
});
describe('库存列表/详情:批次产地回显字段', () => {
it('列表 SQL 显式返回 batch_origin(COALESCE(inv.origin,\'\')),行映射落 string', () => {
const queryService = read('../src/services/inventoryQueryService.ts');
expect(queryService).toContain("COALESCE(inv.origin, '') AS batch_origin");
expect(queryService).toContain("batch_origin: item.batch_origin == null ? '' : String(item.batch_origin)");
});
it('批次报告详情候选也带 batch_origin(批次优先,空回退商品档案)', () => {
const reportService = read('../src/services/inventoryBatchReportService.ts');
expect(reportService).toContain("COALESCE(i.origin, '') AS batch_origin");
expect(reportService).toContain('batch_origin: String(row.batch_origin || row.sku_origin || \'\')');
});
it('批次编辑服务把 origin 纳入前值快照(同值不写、不留假变更)', () => {
const editService = read('../src/services/inventoryBatchEditService.ts');
expect(editService).toContain('cost_price, origin');
expect(editService).toContain('origin: row.origin == null ? null : String(row.origin)');
});
});