主系统回执指出「跳过 ≠ 排队」:某行有待审改量时改单位,我方本次不上报 (避免顶掉待审改量),但那条待审若最终被驳回,这次单位变更就永久丢失。 开发者裁决选 A:跳过时留一条意图,改量审核落定后定向补发一次。 - migrations/20261043:新表 public.main_system_price_qty_unit_deferred (waiting 部分唯一索引 (branch_code, prep_id) ⇒ 同一行只留最新意图) - mainSystemUnitDeferredResend.ts:recordDeferredUnitResend(跳过时 upsert 意图) + flushDeferredUnitResendForPrep(补发,三个前提:无任何 pending / 行仍在且单位未改回 / 开关仍开) + sweepDeferredUnitResends(15 分钟清扫,兜住无决策事件的情形) - mainSystemPriceQtyRequest.ts:跳过分支留意图;handlePriceQtyDecidedEvent 尾部补发 (webhook 与 Q6 对账共用该处理器 ⇒ 两条路径都覆盖) - scheduledJobs.ts:15 分钟 tick 挂清扫(内部限流 10 分钟) - 幂等:client_request_id = unit-deferred-<意图行 id>(确定性)⇒ 重复触发只上报一次 真机 E2E(本地栈 × 真库 × 主系统管理员真驳回,靶 c66d867e…/酸菜/BR002): 造待审改量(10→12) ⇒ 改单位 斤→箱 ⇒ 不上报但留意图(主系统仍 斤)⇒ 清扫被挡 ⇒ 真驳回(HTTP 200,webhook 落定) ⇒ 补发一次 ⇒ 主系统备货行单位 斤→箱、数量/价格未动 ⇒ 收尾还原。你们那条驳回事件实际投了 2 次,确定性幂等键让只发出 1 条载体。 测试:unitDeferredResend.test.ts(10 例)+ mainSystemPriceQtyRequest.test.ts 用例 ⑥⑦(共 53 例); 服务端 tsc 0 错;设计文 §11.8;对接清单新增 §2.15(我方后续回执)。
1671 lines
71 KiB
TypeScript
1671 lines
71 KiB
TypeScript
import { describe, expect, it, vi, beforeEach } from 'vitest';
|
||
import { readFileSync } from 'node:fs';
|
||
import path from 'node:path';
|
||
|
||
/**
|
||
* 跨系统改价 / 改量审核(我方实现,2026-10-11;**2026-10-12 口径翻转为"先改后通知"**)。
|
||
*
|
||
* ⚠️ 本文件默认跑**旧口径(先审后改)**:那是仍保留、可回退的实现路径(`mode: review_gated`),
|
||
* 也是"主系统主动改它的东西"时的正常通道,A1–A8 的既有断言全部继续有效。
|
||
* 新口径(**自己只能改自己的 / 本地先生效 + 异步通知**)在文件末尾的
|
||
* `先改后通知(local-first)` describe 里单独钉住,两套语义互不掩盖。
|
||
*
|
||
* 覆盖设计文档 docs/design/20261011-跨系统改价改量审核.md 的 A1–A8:
|
||
* · 免审(applied)⇒ 台账 applied + **立即落地** + 留日志;
|
||
* · 要审(pending)⇒ 台账 pending、**不落地**、留日志;
|
||
* · 审核通过/驳回回传 ⇒ 以主系统最终值落地 / 不落地;重复回传幂等;
|
||
* · 写路径守卫:主系统行的价/量改动必须走申请(开关打开时),内部落地路径放行;
|
||
* · 开关关闭 ⇒ 与改造前逐字节一致(守卫放行、入口停用)。
|
||
*/
|
||
|
||
const query = vi.hoisted(() => vi.fn());
|
||
const submit = vi.hoisted(() => vi.fn());
|
||
const fetchAmend = vi.hoisted(() => vi.fn());
|
||
const syncItems = vi.hoisted(() => vi.fn());
|
||
const audit = vi.hoisted(() => vi.fn());
|
||
const withTenantData = vi.hoisted(() => vi.fn());
|
||
const withTenantCtx = vi.hoisted(() => vi.fn());
|
||
const isEnabledFlag = vi.hoisted(() => ({ value: true }));
|
||
|
||
vi.mock('../src/db', () => ({
|
||
pool: { query: (...args: unknown[]) => query(...args), connect: vi.fn() },
|
||
getRawPoolQuery: () => query,
|
||
}));
|
||
vi.mock('../src/services/mainSystem', () => ({
|
||
isPriceQtyRequestEnabled: () => isEnabledFlag.value,
|
||
submitMainSystemPriceQtyRequest: (...args: unknown[]) => submit(...args),
|
||
fetchMainSystemPriceAmendRows: (...args: unknown[]) => fetchAmend(...args),
|
||
MAIN_SYSTEM_AMEND_STATUS: { pending: 10, approved: 20, rejected: 30 },
|
||
}));
|
||
/**
|
||
* 2026-10-27:出站 `supplier_code` 改由**行级台账**解析(接入编码 ≠ 对方 supplier_code)。
|
||
* 本文件钉的是"提交/回传的业务语义",与"用谁的 supplier_code"无关 ⇒ 这里把它固定成
|
||
* `= branchCode`(等价于改造前的行为),解析逻辑本身在 `branchAccessCode.test.ts` 单独钉。
|
||
*/
|
||
vi.mock('../src/services/branchAccessCode', () => ({
|
||
resolveSupplierCodeForPrep: async (params: { branchCode: string }) => params.branchCode,
|
||
}));
|
||
vi.mock('../src/services/orderManageItemsService', () => ({
|
||
syncOrderManageItems: (...args: unknown[]) => syncItems(...args),
|
||
}));
|
||
vi.mock('../src/services/auditService', () => ({
|
||
writeAuditLog: (...args: unknown[]) => audit(...args),
|
||
}));
|
||
vi.mock('../src/services/tenantSchemaService', async (importOriginal) => {
|
||
const actual = await importOriginal<typeof import('../src/services/tenantSchemaService')>();
|
||
return { ...actual, runWithTenantDataAccess: (...args: unknown[]) => withTenantData(...args) };
|
||
});
|
||
vi.mock('../src/services/tenantDbContext', async (importOriginal) => {
|
||
const actual = await importOriginal<typeof import('../src/services/tenantDbContext')>();
|
||
return { ...actual, runWithTenantDbContext: (...args: unknown[]) => withTenantCtx(...args) };
|
||
});
|
||
|
||
import {
|
||
__setPriceQtyLocalFirstForTests,
|
||
assertMainSystemPriceQtyReviewed,
|
||
handlePriceQtyDecidedEvent,
|
||
notifyMainSystemPriceQtyChanges,
|
||
submitPriceQtyRequest,
|
||
} from '../src/services/mainSystemPriceQtyRequest';
|
||
|
||
const BRANCH = 'SUP37831443';
|
||
const ORDER = 'ORD_API_20261009_SUP37831443_0001';
|
||
const ITEM = '11111111-2222-3333-4444-555555555555';
|
||
|
||
function ledgerRow(overrides: Record<string, unknown> = {}) {
|
||
return {
|
||
id: 'req-row-1',
|
||
branch_code: BRANCH,
|
||
request_id: 'MS-REQ-1',
|
||
client_request_id: 'c-1',
|
||
prep_id: 'prep-1',
|
||
main_order_code: 'ORD_WEB_20261008_BR002_0007',
|
||
our_order_code: ORDER,
|
||
our_order_item_id: ITEM,
|
||
kind: 'price',
|
||
before_price: 5,
|
||
before_qty: 10,
|
||
proposed_price: 6.5,
|
||
proposed_qty: 10,
|
||
final_price: null,
|
||
final_qty: null,
|
||
unit: '斤',
|
||
status: 'pending',
|
||
review_required: true,
|
||
reason: null,
|
||
decision_reason: null,
|
||
requested_by: 'SUP37831443:admin:u1',
|
||
decided_by: null,
|
||
decided_at: null,
|
||
payload: {},
|
||
created_at: '2026-10-11T02:00:00.000Z',
|
||
updated_at: '2026-10-11T02:00:00.000Z',
|
||
...overrides,
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 无 request_id 的历史行只能落在「刚提交、还没拿到主系统申请号」的 30 分钟窗口内才可能被
|
||
* 旧 amend 视图补齐 —— 窗口外会被 `STALE_PENDING_MS` 闸门判为幽灵 pending 直接标 failed。
|
||
* 用"当前时刻"而不是写死日期,避免用例随墙钟推移由绿变红。
|
||
*/
|
||
function freshLegacyRowTimestamps() {
|
||
const now = new Date().toISOString();
|
||
return { created_at: now, updated_at: now };
|
||
}
|
||
|
||
beforeEach(() => {
|
||
// ⚠️ 默认跑**旧口径(先审后改)**:保住既有 32 条断言的语义(可回退路径不能变成"没人跑的死码")。
|
||
// 新口径(先改后通知)的用例在文件末尾的 describe 里显式切回 true。
|
||
__setPriceQtyLocalFirstForTests(false);
|
||
query.mockReset();
|
||
submit.mockReset();
|
||
fetchAmend.mockReset();
|
||
syncItems.mockReset();
|
||
audit.mockReset();
|
||
withTenantData.mockReset();
|
||
withTenantCtx.mockReset();
|
||
isEnabledFlag.value = true;
|
||
|
||
withTenantData.mockImplementation(async (_branch: string, fn: (client: unknown) => unknown) =>
|
||
fn({ query: (...args: unknown[]) => query(...args) })
|
||
);
|
||
withTenantCtx.mockImplementation(async (_branch: string, fn: () => unknown) => fn());
|
||
syncItems.mockResolvedValue({ total_amount: 100 });
|
||
audit.mockResolvedValue(undefined);
|
||
});
|
||
|
||
/** 造一次 submit 的 pool 应答:订单行读、台账 INSERT、旧 pending DELETE、台账 UPDATE */
|
||
function stubSubmitQueries(options: { existingPending?: number } = {}) {
|
||
query.mockImplementation(async (sql: string) => {
|
||
const text = String(sql);
|
||
if (text.includes('FROM order_items') && text.includes('SELECT price')) {
|
||
return { rowCount: 1, rows: [{ price: 5, quantity: 10, unit: '斤', item_name: '土豆' }] };
|
||
}
|
||
if (text.includes('FROM public.main_system_order_imports')) {
|
||
return { rowCount: 1, rows: [{ main_order_code: 'ORD_WEB_20261008_BR002_0007' }] };
|
||
}
|
||
if (text.includes('FROM public.main_system_order_import_items')) {
|
||
return { rowCount: 1, rows: [{ prep_id: 'prep-1', main_order_code: 'ORD_WEB_20261008_BR002_0007' }] };
|
||
}
|
||
if (text.startsWith('INSERT INTO public.main_system_price_qty_requests')) {
|
||
return { rowCount: 1, rows: [ledgerRow()] };
|
||
}
|
||
if (text.startsWith('DELETE FROM public.main_system_price_qty_requests')) {
|
||
return { rowCount: options.existingPending ?? 0, rows: [] };
|
||
}
|
||
if (text.startsWith('UPDATE public.main_system_price_qty_requests')) {
|
||
return { rowCount: 1, rows: [ledgerRow()] };
|
||
}
|
||
if (text.includes('FROM order_items')) {
|
||
return {
|
||
rowCount: 1,
|
||
rows: [
|
||
{
|
||
id: ITEM,
|
||
item_name: '土豆',
|
||
sku_code: 'SKU1',
|
||
quantity: 10,
|
||
unit: '斤',
|
||
price: 5,
|
||
amount: 50,
|
||
cost_price: 3,
|
||
supplier_code: null,
|
||
processing_method: '原材料',
|
||
processing_owner: null,
|
||
category_code: null,
|
||
category_name: null,
|
||
sort_order: 1,
|
||
remark: null,
|
||
is_extra_dish: false,
|
||
quality_report_id: null,
|
||
},
|
||
],
|
||
};
|
||
}
|
||
return { rowCount: 0, rows: [] };
|
||
});
|
||
}
|
||
|
||
describe('写路径守卫(A8 / C2)', () => {
|
||
it('主系统订单 + 改价 ⇒ 409 main_system_price_qty_requires_review', () => {
|
||
expect(() =>
|
||
assertMainSystemPriceQtyReviewed({
|
||
isMainSystemOrder: true,
|
||
changes: [{ itemId: ITEM, itemName: '土豆', field: 'price', from: 5, to: 6.5 }],
|
||
})
|
||
).toThrowError(/需要提交申请/);
|
||
try {
|
||
assertMainSystemPriceQtyReviewed({
|
||
isMainSystemOrder: true,
|
||
changes: [{ itemId: ITEM, itemName: '土豆', field: 'quantity', from: 10, to: 12 }],
|
||
});
|
||
} catch (error: any) {
|
||
expect(error.status).toBe(409);
|
||
expect(error.code).toBe('main_system_price_qty_requires_review');
|
||
}
|
||
});
|
||
|
||
it('非主系统订单 / 无变更 / 已审核落地 ⇒ 放行', () => {
|
||
expect(() =>
|
||
assertMainSystemPriceQtyReviewed({
|
||
isMainSystemOrder: false,
|
||
changes: [{ itemId: ITEM, itemName: '土豆', field: 'price', from: 5, to: 9 }],
|
||
})
|
||
).not.toThrow();
|
||
expect(() => assertMainSystemPriceQtyReviewed({ isMainSystemOrder: true, changes: [] })).not.toThrow();
|
||
expect(() =>
|
||
assertMainSystemPriceQtyReviewed({
|
||
isMainSystemOrder: true,
|
||
approved: true,
|
||
changes: [{ itemId: ITEM, itemName: '土豆', field: 'price', from: 5, to: 9 }],
|
||
})
|
||
).not.toThrow();
|
||
});
|
||
|
||
it('开关关闭 ⇒ 守卫放行(与改造前逐字节一致)', () => {
|
||
isEnabledFlag.value = false;
|
||
expect(() =>
|
||
assertMainSystemPriceQtyReviewed({
|
||
isMainSystemOrder: true,
|
||
changes: [{ itemId: ITEM, itemName: '土豆', field: 'price', from: 5, to: 9 }],
|
||
})
|
||
).not.toThrow();
|
||
});
|
||
});
|
||
|
||
describe('提交申请(A1 / A2 / A3 / A4)', () => {
|
||
it('开关关闭 ⇒ disabled,且不调用主系统', async () => {
|
||
isEnabledFlag.value = false;
|
||
const outcome = await submitPriceQtyRequest({
|
||
branchCode: BRANCH,
|
||
ourOrderCode: ORDER,
|
||
ourOrderItemId: ITEM,
|
||
proposedPrice: 6.5,
|
||
actor: { userId: 'u1' },
|
||
});
|
||
expect(outcome.kind).toBe('disabled');
|
||
expect(submit).not.toHaveBeenCalled();
|
||
});
|
||
|
||
it('值没变 ⇒ no_change(不提交、不落台账)', async () => {
|
||
stubSubmitQueries();
|
||
const outcome = await submitPriceQtyRequest({
|
||
branchCode: BRANCH,
|
||
ourOrderCode: ORDER,
|
||
ourOrderItemId: ITEM,
|
||
proposedPrice: 5,
|
||
proposedQty: 10,
|
||
actor: { userId: 'u1' },
|
||
});
|
||
expect(outcome.kind).toBe('no_change');
|
||
expect(submit).not.toHaveBeenCalled();
|
||
});
|
||
|
||
it('免审(applied)⇒ 台账 applied + **立即落地** + 写 auto_applied 日志', async () => {
|
||
stubSubmitQueries();
|
||
submit.mockResolvedValue({
|
||
kind: 'ok',
|
||
requestId: 'MS-REQ-1',
|
||
status: 'applied',
|
||
reviewRequired: false,
|
||
finalPrice: 6.5,
|
||
finalQty: 10,
|
||
message: '已生效(低于原价,免审)',
|
||
raw: { data: { status: 'applied' } },
|
||
});
|
||
const outcome = await submitPriceQtyRequest({
|
||
branchCode: BRANCH,
|
||
ourOrderCode: ORDER,
|
||
ourOrderItemId: ITEM,
|
||
proposedPrice: 6.5,
|
||
unit: '斤',
|
||
actor: { userId: 'u1', roles: 'admin' },
|
||
});
|
||
expect(outcome.kind).toBe('ok');
|
||
if (outcome.kind !== 'ok') return;
|
||
expect(outcome.status).toBe('applied');
|
||
expect(outcome.appliedLocally).toBe(true);
|
||
// 落地走既有改明细链路,并带"已审核"标记
|
||
expect(syncItems).toHaveBeenCalledTimes(1);
|
||
const call = syncItems.mock.calls[0][0] as any;
|
||
expect(call.mainSystemPriceQtyApproved).toBe(true);
|
||
expect(call.allowUnpriced).toBe(true);
|
||
expect(call.items[0].price).toBe(6.5);
|
||
// 免审也要留日志(开发者:两边都留详细日志)
|
||
expect(audit).toHaveBeenCalledTimes(1);
|
||
expect((audit.mock.calls[0][0] as any).operationType).toBe('main_system_price_qty_auto_applied');
|
||
});
|
||
|
||
it('要审(pending)⇒ 台账 pending、**不落地**、写 requested 日志', async () => {
|
||
stubSubmitQueries();
|
||
submit.mockResolvedValue({
|
||
kind: 'ok',
|
||
requestId: 'MS-REQ-1',
|
||
status: 'pending',
|
||
reviewRequired: true,
|
||
finalPrice: null,
|
||
finalQty: null,
|
||
message: '已提交,等待管理员确认',
|
||
raw: { data: { status: 'pending' } },
|
||
});
|
||
const outcome = await submitPriceQtyRequest({
|
||
branchCode: BRANCH,
|
||
ourOrderCode: ORDER,
|
||
ourOrderItemId: ITEM,
|
||
proposedPrice: 8,
|
||
actor: { userId: 'u1' },
|
||
});
|
||
expect(outcome.kind).toBe('ok');
|
||
if (outcome.kind !== 'ok') return;
|
||
expect(outcome.status).toBe('pending');
|
||
expect(outcome.reviewRequired).toBe(true);
|
||
expect(syncItems).not.toHaveBeenCalled();
|
||
expect((audit.mock.calls[0][0] as any).operationType).toBe('main_system_price_qty_requested');
|
||
});
|
||
|
||
it('旧的同类型 pending 申请必须**先删后插**(部分唯一索引:否则新申请撞唯一键)', async () => {
|
||
stubSubmitQueries({ existingPending: 1 });
|
||
submit.mockResolvedValue({
|
||
kind: 'ok',
|
||
requestId: 'MS-REQ-1',
|
||
status: 'pending',
|
||
reviewRequired: true,
|
||
finalPrice: null,
|
||
finalQty: null,
|
||
message: null,
|
||
raw: {},
|
||
});
|
||
await submitPriceQtyRequest({
|
||
branchCode: BRANCH,
|
||
ourOrderCode: ORDER,
|
||
ourOrderItemId: ITEM,
|
||
proposedPrice: 8,
|
||
actor: { userId: 'u1' },
|
||
});
|
||
const sqls = query.mock.calls.map((c) => String(c[0]));
|
||
const deleteAt = sqls.findIndex((sql) => sql.startsWith('DELETE FROM public.main_system_price_qty_requests'));
|
||
const insertAt = sqls.findIndex((sql) => sql.startsWith('INSERT INTO public.main_system_price_qty_requests'));
|
||
expect(deleteAt).toBeGreaterThanOrEqual(0);
|
||
expect(insertAt).toBeGreaterThanOrEqual(0);
|
||
expect(deleteAt).toBeLessThan(insertAt);
|
||
});
|
||
|
||
it('同一 client_request_id 重放(唯一键冲突)⇒ 返回既有申请,不重复上报', async () => {
|
||
query.mockImplementation(async (sql: string) => {
|
||
const text = String(sql);
|
||
if (text.includes('SELECT price')) {
|
||
return { rowCount: 1, rows: [{ price: 5, quantity: 10, unit: '斤', item_name: '土豆' }] };
|
||
}
|
||
if (text.includes('main_system_order_imports')) {
|
||
return { rowCount: 1, rows: [{ main_order_code: 'ORD_WEB_1' }] };
|
||
}
|
||
if (text.includes('main_system_order_import_items')) {
|
||
return { rowCount: 1, rows: [{ prep_id: 'prep-1', main_order_code: 'ORD_WEB_1' }] };
|
||
}
|
||
if (text.startsWith('DELETE FROM public.main_system_price_qty_requests')) return { rowCount: 0, rows: [] };
|
||
if (text.startsWith('INSERT INTO public.main_system_price_qty_requests')) {
|
||
throw Object.assign(new Error('duplicate key value violates unique constraint'), { code: '23505' });
|
||
}
|
||
if (text.includes('client_request_id = $2')) {
|
||
return { rowCount: 1, rows: [ledgerRow({ status: 'applied', review_required: false, final_price: 6.5 })] };
|
||
}
|
||
return { rowCount: 0, rows: [] };
|
||
});
|
||
const outcome = await submitPriceQtyRequest({
|
||
branchCode: BRANCH,
|
||
ourOrderCode: ORDER,
|
||
ourOrderItemId: ITEM,
|
||
proposedPrice: 6.5,
|
||
actor: { userId: 'u1' },
|
||
clientRequestId: 'c-1',
|
||
});
|
||
expect(outcome.kind).toBe('ok');
|
||
if (outcome.kind !== 'ok') return;
|
||
expect(outcome.status).toBe('applied');
|
||
expect(outcome.appliedLocally).toBe(false);
|
||
expect(submit).not.toHaveBeenCalled();
|
||
});
|
||
|
||
it('主系统接口未就绪(404)⇒ main_system_not_ready,台账标 failed', async () => {
|
||
stubSubmitQueries();
|
||
submit.mockResolvedValue({ kind: 'not_supported', reason: 'HTTP 404' });
|
||
const outcome = await submitPriceQtyRequest({
|
||
branchCode: BRANCH,
|
||
ourOrderCode: ORDER,
|
||
ourOrderItemId: ITEM,
|
||
proposedPrice: 8,
|
||
actor: { userId: 'u1' },
|
||
});
|
||
expect(outcome.kind).toBe('main_system_not_ready');
|
||
expect(syncItems).not.toHaveBeenCalled();
|
||
const statuses = query.mock.calls
|
||
.map((c) => String(c[0]))
|
||
.filter((sql) => sql.includes("SET status = 'failed'"));
|
||
expect(statuses.length).toBeGreaterThanOrEqual(1);
|
||
});
|
||
|
||
it('找不到主系统备货行(台账缺 prep_id)⇒ not_main_system_order,不提交', async () => {
|
||
query.mockImplementation(async (sql: string) => {
|
||
const text = String(sql);
|
||
if (text.includes('SELECT price')) {
|
||
return { rowCount: 1, rows: [{ price: 5, quantity: 10, unit: '斤', item_name: '土豆' }] };
|
||
}
|
||
if (text.includes('main_system_order_imports')) return { rowCount: 0, rows: [] };
|
||
if (text.includes('main_system_order_import_items')) return { rowCount: 0, rows: [] };
|
||
return { rowCount: 0, rows: [] };
|
||
});
|
||
const outcome = await submitPriceQtyRequest({
|
||
branchCode: BRANCH,
|
||
ourOrderCode: ORDER,
|
||
ourOrderItemId: ITEM,
|
||
proposedPrice: 8,
|
||
actor: { userId: 'u1' },
|
||
});
|
||
expect(outcome.kind).toBe('not_main_system_order');
|
||
expect(submit).not.toHaveBeenCalled();
|
||
});
|
||
});
|
||
|
||
describe('结果回传(A5 / A7)', () => {
|
||
function stubDecideQueries(row: Record<string, unknown>) {
|
||
query.mockImplementation(async (sql: string) => {
|
||
const text = String(sql);
|
||
if (text.includes('FROM public.main_system_price_qty_requests') && text.includes('request_id = $1')) {
|
||
return { rowCount: 1, rows: [row] };
|
||
}
|
||
if (text.startsWith('UPDATE public.main_system_price_qty_requests')) return { rowCount: 1, rows: [row] };
|
||
if (text.includes('FROM order_items')) {
|
||
return {
|
||
rowCount: 1,
|
||
rows: [
|
||
{
|
||
id: ITEM,
|
||
item_name: '土豆',
|
||
sku_code: 'SKU1',
|
||
quantity: 10,
|
||
unit: '斤',
|
||
price: 5,
|
||
amount: 50,
|
||
cost_price: 3,
|
||
supplier_order: null,
|
||
processing_method: '原材料',
|
||
processing_owner: null,
|
||
category_code: null,
|
||
category_name: null,
|
||
sort_order: 1,
|
||
remark: null,
|
||
is_extra_dish: false,
|
||
quality_report_id: null,
|
||
},
|
||
],
|
||
};
|
||
}
|
||
return { rowCount: 0, rows: [] };
|
||
});
|
||
}
|
||
|
||
it('审核通过 ⇒ 以主系统最终值落地 + approved 日志', async () => {
|
||
stubDecideQueries(ledgerRow());
|
||
const outcome = await handlePriceQtyDecidedEvent({
|
||
branchCode: BRANCH,
|
||
payload: {
|
||
event: 'preparations.price_qty_decided',
|
||
request_id: 'MS-REQ-1',
|
||
prep_id: 'prep-1',
|
||
decision: 'approved',
|
||
final_price: 7.25,
|
||
reviewer: '主系统管理员',
|
||
},
|
||
});
|
||
expect(outcome.status).toBe('done');
|
||
expect(outcome.duplicate).toBe(false);
|
||
expect(syncItems).toHaveBeenCalledTimes(1);
|
||
const call = syncItems.mock.calls[0][0] as any;
|
||
expect(call.items[0].price).toBe(7.25);
|
||
expect((audit.mock.calls[0][0] as any).operationType).toBe('main_system_price_qty_approved');
|
||
});
|
||
|
||
it('重复回传 ⇒ duplicate=true,不二次改账', async () => {
|
||
stubDecideQueries(ledgerRow({ status: 'approved', final_price: 7.25 }));
|
||
const outcome = await handlePriceQtyDecidedEvent({
|
||
branchCode: BRANCH,
|
||
payload: { event: 'preparations.price_qty_decided', request_id: 'MS-REQ-1', decision: 'approved', final_price: 7.25 },
|
||
});
|
||
expect(outcome.duplicate).toBe(true);
|
||
expect(syncItems).not.toHaveBeenCalled();
|
||
expect(audit).not.toHaveBeenCalled();
|
||
});
|
||
|
||
it('驳回 ⇒ 状态 rejected、**不落地**、留 rejected 日志', async () => {
|
||
stubDecideQueries(ledgerRow());
|
||
const outcome = await handlePriceQtyDecidedEvent({
|
||
branchCode: BRANCH,
|
||
payload: {
|
||
event: 'preparations.price_qty_decided',
|
||
request_id: 'MS-REQ-1',
|
||
decision: 'rejected',
|
||
reason: '价格过高',
|
||
reviewer: '主系统管理员',
|
||
},
|
||
});
|
||
expect(outcome.status).toBe('done');
|
||
expect(syncItems).not.toHaveBeenCalled();
|
||
expect((audit.mock.calls[0][0] as any).operationType).toBe('main_system_price_qty_rejected');
|
||
});
|
||
|
||
it('找不到申请的 request_id ⇒ ignored(不外抛、不误改数据)', async () => {
|
||
query.mockResolvedValue({ rowCount: 0, rows: [] });
|
||
const outcome = await handlePriceQtyDecidedEvent({
|
||
branchCode: BRANCH,
|
||
payload: { event: 'preparations.price_qty_decided', request_id: 'UNKNOWN', decision: 'approved' },
|
||
});
|
||
expect(outcome.status).toBe('ignored');
|
||
expect(syncItems).not.toHaveBeenCalled();
|
||
});
|
||
});
|
||
|
||
describe('轮询兜底(A6)', () => {
|
||
it('开关关闭 ⇒ 不拉主系统', async () => {
|
||
isEnabledFlag.value = false;
|
||
const { reconcileMainSystemPriceQtyRequests } = await import('../src/services/mainSystemPriceQtyRequest');
|
||
const result = await reconcileMainSystemPriceQtyRequests({ branchCode: BRANCH });
|
||
expect(result.reason).toBe('disabled');
|
||
expect(fetchAmend).not.toHaveBeenCalled();
|
||
});
|
||
|
||
it('主系统已通过 ⇒ 按最终值补齐落地(仅限**无 request_id 的历史行**,走旧 amend 视图)', async () => {
|
||
// ⚠️ 无 request_id 的行有 30 分钟"幽灵 pending"闸门(超过即标 failed 请重提),
|
||
// 所以这行必须落在这个窗口内 —— 写死日期会随墙钟推移让本用例变红(2026-10-11 已发生过一次)。
|
||
const pending = ledgerRow({ request_id: null, ...freshLegacyRowTimestamps() });
|
||
query.mockImplementation(async (sql: string) => {
|
||
const text = String(sql);
|
||
if (text.includes("status = 'pending'") && text.includes('FROM public.main_system_price_qty_requests')) {
|
||
return { rowCount: 1, rows: [pending] };
|
||
}
|
||
if (text.startsWith('UPDATE public.main_system_price_qty_requests')) return { rowCount: 1, rows: [pending] };
|
||
if (text.includes('FROM order_items')) {
|
||
return {
|
||
rowCount: 1,
|
||
rows: [
|
||
{
|
||
id: ITEM,
|
||
item_name: '土豆',
|
||
sku_code: 'SKU1',
|
||
quantity: 10,
|
||
unit: '斤',
|
||
price: 5,
|
||
amount: 50,
|
||
cost_price: 3,
|
||
supplier_code: null,
|
||
processing_method: '原材料',
|
||
processing_owner: null,
|
||
category_code: null,
|
||
category_name: null,
|
||
sort_order: 1,
|
||
remark: null,
|
||
is_extra_dish: false,
|
||
quality_report_id: null,
|
||
},
|
||
],
|
||
};
|
||
}
|
||
return { rowCount: 0, rows: [] };
|
||
});
|
||
fetchAmend.mockResolvedValue({
|
||
kind: 'ok',
|
||
rows: [
|
||
{
|
||
prepId: 'prep-1',
|
||
orderCode: ORDER,
|
||
prepareQty: 10,
|
||
purchasePrice: 5,
|
||
unit: '斤',
|
||
amendRequest: { id: 'MS-REQ-1', status: 20, statusLabel: '已确认', proposedPrice: 6.8, proposedQty: null, proposedUnit: null, reviewRemark: null, requestedAt: null },
|
||
},
|
||
],
|
||
});
|
||
const { reconcileMainSystemPriceQtyRequests } = await import('../src/services/mainSystemPriceQtyRequest');
|
||
const result = await reconcileMainSystemPriceQtyRequests({ branchCode: BRANCH });
|
||
expect(result.checked).toBe(1);
|
||
expect(result.closed).toBe(1);
|
||
expect(syncItems).toHaveBeenCalledTimes(1);
|
||
expect((syncItems.mock.calls[0][0] as any).items[0].price).toBe(6.8);
|
||
});
|
||
});
|
||
|
||
describe('一致性红线:三条错位场景必须被挡住 / 可自愈(开发者核查要求)', () => {
|
||
it('场景② 主系统已生效但本地落地失败 ⇒ 台账**退回 pending 等重试**(不留在终态)', async () => {
|
||
stubSubmitQueries();
|
||
submit.mockResolvedValue({
|
||
kind: 'ok',
|
||
requestId: 'MS-REQ-1',
|
||
status: 'applied',
|
||
reviewRequired: false,
|
||
finalPrice: 6.5,
|
||
finalQty: 10,
|
||
message: '已生效(低于原价,免审)',
|
||
raw: {},
|
||
});
|
||
syncItems.mockRejectedValue(new Error('订单已结案,不可改明细'));
|
||
const outcome = await submitPriceQtyRequest({
|
||
branchCode: BRANCH,
|
||
ourOrderCode: ORDER,
|
||
ourOrderItemId: ITEM,
|
||
proposedPrice: 6.5,
|
||
actor: { userId: 'u1' },
|
||
});
|
||
expect(outcome.kind).toBe('ok');
|
||
if (outcome.kind !== 'ok') return;
|
||
expect(outcome.status).toBe('applied');
|
||
expect(outcome.appliedLocally).toBe(false);
|
||
expect(outcome.applyNote).toMatch(/本地落地失败/);
|
||
// 台账必须退回 pending(否则对账不再重试 = 主系统变了、我方没变永久存在)
|
||
const revert = query.mock.calls
|
||
.map((c) => String(c[0]))
|
||
.find((sql) => sql.includes("SET status = 'pending'") && sql.includes('main_system_price_qty_requests'));
|
||
expect(revert, '未把台账退回 pending').toBeTruthy();
|
||
expect((audit.mock.calls[0][0] as any).operationType).toBe('main_system_price_qty_apply_failed');
|
||
});
|
||
|
||
it('场景② webhook 审核通过但落地失败 ⇒ 退回 pending 且记 retryable', async () => {
|
||
const row = ledgerRow();
|
||
query.mockImplementation(async (sql: string) => {
|
||
const text = String(sql);
|
||
if (text.includes('FROM public.main_system_price_qty_requests') && text.includes('request_id = $1')) {
|
||
return { rowCount: 1, rows: [row] };
|
||
}
|
||
if (text.startsWith('UPDATE public.main_system_price_qty_requests')) return { rowCount: 1, rows: [row] };
|
||
if (text.includes('FROM order_items')) {
|
||
return {
|
||
rowCount: 1,
|
||
rows: [
|
||
{
|
||
id: ITEM, item_name: '土豆', sku_code: 'SKU1', quantity: 10, unit: '斤', price: 5, amount: 50,
|
||
cost_price: 3, supplier_code: null, processing_method: '原材料', processing_owner: null,
|
||
category_code: null, category_name: null, sort_order: 1, remark: null, is_extra_dish: false,
|
||
quality_report_id: null,
|
||
},
|
||
],
|
||
};
|
||
}
|
||
return { rowCount: 0, rows: [] };
|
||
});
|
||
syncItems.mockRejectedValue(new Error('订单状态已变更,请刷新后重试'));
|
||
const outcome = await handlePriceQtyDecidedEvent({
|
||
branchCode: BRANCH,
|
||
payload: { event: 'preparations.price_qty_decided', request_id: 'MS-REQ-1', decision: 'approved', final_price: 7 },
|
||
});
|
||
expect(outcome.status).toBe('suspended');
|
||
expect(outcome.reason).toMatch(/将自动重试/);
|
||
const revertCall = query.mock.calls.find(
|
||
(c) => String(c[0]).includes('SET status = $2') && !String(c[0]).includes('final_price')
|
||
);
|
||
expect(revertCall, '未写回退/计数 SQL').toBeTruthy();
|
||
expect((revertCall?.[1] as unknown[])?.[1]).toBe('pending');
|
||
expect((audit.mock.calls[0][0] as any).operationType).toBe('main_system_price_qty_apply_failed');
|
||
});
|
||
|
||
it('场景② 连续落地失败到上限 ⇒ 标 failed 交人工(不无限重试)', async () => {
|
||
const row = ledgerRow({ payload: { apply_attempts: 4 } });
|
||
query.mockImplementation(async (sql: string) => {
|
||
const text = String(sql);
|
||
if (text.includes('FROM public.main_system_price_qty_requests') && text.includes('request_id = $1')) {
|
||
return { rowCount: 1, rows: [row] };
|
||
}
|
||
if (text.startsWith('UPDATE public.main_system_price_qty_requests')) return { rowCount: 1, rows: [row] };
|
||
if (text.includes('FROM order_items')) {
|
||
return {
|
||
rowCount: 1,
|
||
rows: [
|
||
{
|
||
id: ITEM, item_name: '土豆', sku_code: 'SKU1', quantity: 10, unit: '斤', price: 5, amount: 50,
|
||
cost_price: 3, supplier_code: null, processing_method: '原材料', processing_owner: null,
|
||
category_code: null, category_name: null, sort_order: 1, remark: null, is_extra_dish: false,
|
||
quality_report_id: null,
|
||
},
|
||
],
|
||
};
|
||
}
|
||
return { rowCount: 0, rows: [] };
|
||
});
|
||
syncItems.mockRejectedValue(new Error('仍然失败'));
|
||
const outcome = await handlePriceQtyDecidedEvent({
|
||
branchCode: BRANCH,
|
||
payload: { event: 'preparations.price_qty_decided', request_id: 'MS-REQ-1', decision: 'approved', final_price: 7 },
|
||
});
|
||
expect(outcome.status).toBe('suspended');
|
||
expect(outcome.reason).toMatch(/停止自动重试/);
|
||
const revertCall = query.mock.calls.find(
|
||
(c) => String(c[0]).includes('SET status = $2') && !String(c[0]).includes('final_price')
|
||
);
|
||
expect(revertCall, '未写回退 SQL').toBeTruthy();
|
||
expect((revertCall?.[1] as unknown[])?.[1]).toBe('failed');
|
||
expect(String((revertCall?.[1] as unknown[])?.[2])).toMatch(/连续失败 5 次/);
|
||
});
|
||
|
||
it('场景③ 未审核不得改本地:pending 提交不动本地数据(不调用落地)', async () => {
|
||
stubSubmitQueries();
|
||
submit.mockResolvedValue({
|
||
kind: 'ok', requestId: 'MS-REQ-1', status: 'pending', reviewRequired: true,
|
||
finalPrice: null, finalQty: null, message: null, raw: {},
|
||
});
|
||
const outcome = await submitPriceQtyRequest({
|
||
branchCode: BRANCH, ourOrderCode: ORDER, ourOrderItemId: ITEM, proposedPrice: 99, actor: { userId: 'u1' },
|
||
});
|
||
expect(outcome.kind).toBe('ok');
|
||
expect(syncItems).not.toHaveBeenCalled();
|
||
});
|
||
|
||
it('守卫范围:主系统单里的**本系统自建行**(无对照、非同名)不得被拦(正常业务不受影响)', async () => {
|
||
const { isMainSystemAllocatedLines } = await import('../src/services/mainSystemPriceQtyRequest');
|
||
const queryStub = vi.fn(async (sql: string) => {
|
||
const text = String(sql);
|
||
if (text.includes('main_system_order_imports')) return { rowCount: 1, rows: [{}] };
|
||
if (text.includes('FROM public.main_system_order_import_items')) {
|
||
return {
|
||
rowCount: 1,
|
||
rows: [{ prep_id: 'prep-1', item_name: '土豆', main_sku_code: 'SKU1', our_order_item_id: ITEM }],
|
||
};
|
||
}
|
||
return { rowCount: 0, rows: [] };
|
||
});
|
||
const { guarded } = await isMainSystemAllocatedLines({
|
||
branchCode: BRANCH,
|
||
ourOrderCode: ORDER,
|
||
query: queryStub as any,
|
||
candidates: [
|
||
{ itemId: ITEM, itemName: '土豆', skuCode: 'SKU1', mainOrderCode: null }, // 已对照 ⇒ 拦
|
||
{ itemId: 'native-1', itemName: '本店加菜-矿泉水', skuCode: 'SKU9', mainOrderCode: null }, // 自建 ⇒ 放行
|
||
],
|
||
});
|
||
expect(guarded.has(ITEM)).toBe(true);
|
||
expect(guarded.has('native-1')).toBe(false);
|
||
});
|
||
|
||
it('守卫范围:同名同 SKU 的**未回填**台账行 ⇒ 视为主系统行并顺手补对照(自愈)', async () => {
|
||
const { isMainSystemAllocatedLines } = await import('../src/services/mainSystemPriceQtyRequest');
|
||
const updates: unknown[][] = [];
|
||
const queryStub = vi.fn(async (sql: string, values?: unknown[]) => {
|
||
const text = String(sql);
|
||
if (text.includes('main_system_order_imports')) return { rowCount: 1, rows: [{}] };
|
||
if (text.includes('FROM public.main_system_order_import_items')) {
|
||
return {
|
||
rowCount: 1,
|
||
rows: [{ prep_id: 'prep-9', item_name: '桔皮', main_sku_code: 'SKU7', our_order_item_id: null }],
|
||
};
|
||
}
|
||
if (text.startsWith('UPDATE public.main_system_order_import_items')) {
|
||
updates.push(values || []);
|
||
return { rowCount: 1, rows: [] };
|
||
}
|
||
return { rowCount: 0, rows: [] };
|
||
});
|
||
const { guarded } = await isMainSystemAllocatedLines({
|
||
branchCode: BRANCH,
|
||
ourOrderCode: ORDER,
|
||
query: queryStub as any,
|
||
candidates: [{ itemId: 'legacy-1', itemName: '桔皮', skuCode: 'SKU7', mainOrderCode: null }],
|
||
});
|
||
expect(guarded.has('legacy-1')).toBe(true);
|
||
expect(updates.length).toBe(1);
|
||
expect(updates[0]?.[2]).toBe('legacy-1');
|
||
});
|
||
});
|
||
|
||
describe('按主系统回执校正:一次提交含免审+需审 & 按 kind 拆两条事件', () => {
|
||
it('混合提交(补价=免审 + 加量=需审)⇒ 免审那部分**立即落地**,未决字段不动', async () => {
|
||
stubSubmitQueries();
|
||
submit.mockResolvedValue({
|
||
kind: 'ok',
|
||
requestId: 'MS-REQ-PRICE',
|
||
status: 'pending', // 有需审项 ⇒ 整体 pending
|
||
reviewRequired: true,
|
||
finalPrice: null, // 顶层只反映已生效部分;此处用分解对象
|
||
finalQty: null,
|
||
applied: { price: 7.5 },
|
||
pending: { qty: 12 },
|
||
message: '价格已生效(改低免审);数量已提交,等待管理员确认',
|
||
raw: { data: { status: 'pending', applied: { price: 7.5 }, pending: { qty: 12 } } },
|
||
});
|
||
const outcome = await submitPriceQtyRequest({
|
||
branchCode: BRANCH,
|
||
ourOrderCode: ORDER,
|
||
ourOrderItemId: ITEM,
|
||
proposedPrice: 7.5,
|
||
proposedQty: 12,
|
||
actor: { userId: 'u1' },
|
||
});
|
||
expect(outcome.kind).toBe('ok');
|
||
if (outcome.kind !== 'ok') return;
|
||
expect(outcome.status).toBe('pending');
|
||
// 免审的价必须当场落地,且**只**动价、不动量
|
||
expect(syncItems).toHaveBeenCalledTimes(1);
|
||
const call = syncItems.mock.calls[0][0] as any;
|
||
expect(call.items[0].price).toBe(7.5);
|
||
expect(call.items[0].quantity).toBe(10); // 原值,未被 proposed 覆盖
|
||
expect(outcome.finalPrice).toBe(7.5);
|
||
expect(outcome.finalQty).toBeNull();
|
||
expect(outcome.pendingFields).toEqual({ qty: 12 });
|
||
// 两条日志:免审生效 + 进队列
|
||
const types = audit.mock.calls.map((c) => (c[0] as any).operationType);
|
||
expect(types).toContain('main_system_price_qty_auto_applied');
|
||
expect(types).toContain('main_system_price_qty_requested');
|
||
});
|
||
|
||
it('价+量各一条事件(request_id 不同,按 client_request_id 归行)⇒ 两项都落地、状态最后才终态', async () => {
|
||
const row = ledgerRow({ kind: 'both', request_id: 'MS-REQ-PRICE', client_request_id: 'c-1' });
|
||
const updates: Array<{ status: string; final_price: unknown; final_qty: unknown }> = [];
|
||
query.mockImplementation(async (sql: string, values?: unknown[]) => {
|
||
const text = String(sql);
|
||
if (text.includes('FROM public.main_system_price_qty_requests') && text.includes('client_request_id = $1')) {
|
||
return { rowCount: 1, rows: [row] };
|
||
}
|
||
if (text.startsWith('UPDATE public.main_system_price_qty_requests')) {
|
||
updates.push({ status: String(values?.[1]), final_price: values?.[2], final_qty: values?.[3] });
|
||
return { rowCount: 1, rows: [row] };
|
||
}
|
||
if (text.includes('FROM order_items')) {
|
||
return {
|
||
rowCount: 1,
|
||
rows: [
|
||
{
|
||
id: ITEM, item_name: '土豆', sku_code: 'SKU1', quantity: 10, unit: '斤', price: 5, amount: 50,
|
||
cost_price: 3, supplier_code: null, processing_method: '原材料', processing_owner: null,
|
||
category_code: null, category_name: null, sort_order: 1, remark: null, is_extra_dish: false,
|
||
quality_report_id: null,
|
||
},
|
||
],
|
||
};
|
||
}
|
||
return { rowCount: 0, rows: [] };
|
||
});
|
||
|
||
// ① 主系统的第一条事件:只决定价(request_id 是"价"那条申请行的 id)
|
||
const first = await handlePriceQtyDecidedEvent({
|
||
branchCode: BRANCH,
|
||
payload: {
|
||
event: 'preparations.price_qty_decided',
|
||
decision: 'approved',
|
||
request_id: 'MS-REQ-PRICE',
|
||
client_request_id: 'c-1',
|
||
prep_id: 'prep-1',
|
||
kind: 'price',
|
||
final_value: 7,
|
||
final_price: 7,
|
||
final_qty: null,
|
||
reviewer: 'admin-1',
|
||
},
|
||
});
|
||
expect(first.status).toBe('done');
|
||
// 只落了价,量必须保持未决(null)——**不得**用 proposed 兜底
|
||
expect(updates[0]).toMatchObject({ status: 'pending', final_price: 7, final_qty: null });
|
||
const firstApply = syncItems.mock.calls[0][0] as any;
|
||
expect(firstApply.items[0].price).toBe(7);
|
||
expect(firstApply.items[0].quantity).toBe(10);
|
||
|
||
// ② 第二条事件:只决定量(另一条申请行 id,但 client_request_id 相同 ⇒ 归到同一行)
|
||
syncItems.mockClear();
|
||
const second = await handlePriceQtyDecidedEvent({
|
||
branchCode: BRANCH,
|
||
payload: {
|
||
event: 'preparations.price_qty_decided',
|
||
decision: 'approved',
|
||
request_id: 'MS-REQ-QTY',
|
||
client_request_id: 'c-1',
|
||
prep_id: 'prep-1',
|
||
kind: 'qty',
|
||
final_value: 12,
|
||
final_price: null,
|
||
final_qty: 12,
|
||
},
|
||
});
|
||
expect(second.status).toBe('done');
|
||
expect(updates[1]).toMatchObject({ status: 'approved', final_price: 7, final_qty: 12 });
|
||
const secondApply = syncItems.mock.calls[0][0] as any;
|
||
expect(secondApply.items[0].quantity).toBe(12);
|
||
expect(secondApply.items[0].price).toBe(7); // 价保持已决值
|
||
});
|
||
|
||
it('同字段重复回传(同一 kind 二次投递)⇒ duplicate,不再落地', async () => {
|
||
const row = ledgerRow({
|
||
kind: 'both',
|
||
payload: { decided_kinds: ['price'] },
|
||
final_price: 7,
|
||
client_request_id: 'c-1',
|
||
});
|
||
query.mockImplementation(async (sql: string) => {
|
||
const text = String(sql);
|
||
if (text.includes('client_request_id = $1')) return { rowCount: 1, rows: [row] };
|
||
return { rowCount: 0, rows: [] };
|
||
});
|
||
const outcome = await handlePriceQtyDecidedEvent({
|
||
branchCode: BRANCH,
|
||
payload: {
|
||
event: 'preparations.price_qty_decided',
|
||
decision: 'approved',
|
||
request_id: 'MS-REQ-PRICE',
|
||
client_request_id: 'c-1',
|
||
kind: 'price',
|
||
final_value: 7,
|
||
},
|
||
});
|
||
expect(outcome.duplicate).toBe(true);
|
||
expect(syncItems).not.toHaveBeenCalled();
|
||
});
|
||
|
||
it('价通过、量被驳回 ⇒ 只落价,量保持原值,最终状态 rejected', async () => {
|
||
const row = ledgerRow({ kind: 'both', payload: { decided_kinds: ['price'] }, final_price: 7 });
|
||
const updates: Array<{ status: string }> = [];
|
||
query.mockImplementation(async (sql: string, values?: unknown[]) => {
|
||
const text = String(sql);
|
||
if (text.includes('client_request_id = $1')) return { rowCount: 1, rows: [row] };
|
||
if (text.startsWith('UPDATE public.main_system_price_qty_requests')) {
|
||
updates.push({ status: String(values?.[1]) });
|
||
return { rowCount: 1, rows: [row] };
|
||
}
|
||
if (text.includes('FROM order_items')) {
|
||
return {
|
||
rowCount: 1,
|
||
rows: [
|
||
{
|
||
id: ITEM, item_name: '土豆', sku_code: 'SKU1', quantity: 10, unit: '斤', price: 7, amount: 70,
|
||
cost_price: 3, supplier_code: null, processing_method: '原材料', processing_owner: null,
|
||
category_code: null, category_name: null, sort_order: 1, remark: null, is_extra_dish: false,
|
||
quality_report_id: null,
|
||
},
|
||
],
|
||
};
|
||
}
|
||
return { rowCount: 0, rows: [] };
|
||
});
|
||
const outcome = await handlePriceQtyDecidedEvent({
|
||
branchCode: BRANCH,
|
||
payload: {
|
||
event: 'preparations.price_qty_decided',
|
||
decision: 'rejected',
|
||
client_request_id: 'c-2',
|
||
request_id: 'MS-REQ-QTY',
|
||
kind: 'qty',
|
||
final_price: null,
|
||
final_qty: null,
|
||
reason: '加量不予通过',
|
||
},
|
||
});
|
||
expect(outcome.status).toBe('done');
|
||
expect(updates[0].status).toBe('rejected');
|
||
// 驳回不落地:没有调用改明细
|
||
expect(syncItems).not.toHaveBeenCalled();
|
||
const types = audit.mock.calls.map((c) => (c[0] as any).operationType);
|
||
expect(types).toContain('main_system_price_qty_rejected');
|
||
});
|
||
it('新流程行(有 request_id)不再拉旧 amend 视图(主系统已明确新流程未并入该视图)', async () => {
|
||
query.mockImplementation(async (sql: string) => {
|
||
const text = String(sql);
|
||
if (text.includes("status = 'pending'") && text.includes('FROM public.main_system_price_qty_requests')) {
|
||
return { rowCount: 1, rows: [ledgerRow({ request_id: 'MS-REQ-1' })] };
|
||
}
|
||
return { rowCount: 0, rows: [] };
|
||
});
|
||
const { reconcileMainSystemPriceQtyRequests } = await import('../src/services/mainSystemPriceQtyRequest');
|
||
const result = await reconcileMainSystemPriceQtyRequests({ branchCode: BRANCH });
|
||
expect(result.checked).toBe(1);
|
||
expect(result.closed).toBe(0);
|
||
expect(fetchAmend).not.toHaveBeenCalled();
|
||
});
|
||
});
|
||
|
||
describe('SQL 源级钉子:同一占位符既赋值又比较必须显式定型(联调实测踩过)', () => {
|
||
const src = readFileSync(path.join(__dirname, '../src/services/mainSystemPriceQtyRequest.ts'), 'utf8');
|
||
|
||
it('status 占位符在 UPDATE 里必须带 ::varchar 强制定型', () => {
|
||
// 背景:`SET status = $3 ... CASE WHEN $3 = 'applied'` 会让 PG 报
|
||
// "inconsistent types deduced for parameter $3"(单测 mock 掉 pool 时**看不见**,
|
||
// 2026-10-11 首次真连库联调才炸:提交与 webhook 接收端同时 500)。
|
||
expect(src).toMatch(/SET status = \$\d::varchar/);
|
||
expect(src).not.toMatch(/CASE WHEN \$\d = '(applied|pending)'/);
|
||
});
|
||
});
|
||
|
||
describe('申请列表:必须给出「商品名」', () => {
|
||
it('优先用本方订单行的**实时**商品名(改名后仍准)', async () => {
|
||
const row = ledgerRow({ item_name: '旧名(台账里的)', our_order_item_id: ITEM });
|
||
query.mockImplementation(async (sql: string) => {
|
||
const text = String(sql);
|
||
if (text.includes('FROM public.main_system_price_qty_requests')) return { rowCount: 1, rows: [row] };
|
||
if (text.includes('FROM order_items') && text.includes('ANY($1::uuid[])')) {
|
||
return { rowCount: 1, rows: [{ id: ITEM, item_name: '思丰牌面粉(现名)' }] };
|
||
}
|
||
return { rowCount: 0, rows: [] };
|
||
});
|
||
const { listPriceQtyRequests, toPriceQtyRequestDto } = await import('../src/services/mainSystemPriceQtyRequest');
|
||
const rows = await listPriceQtyRequests({ branchCode: BRANCH });
|
||
expect(toPriceQtyRequestDto(rows[0]).item_name).toBe('思丰牌面粉(现名)');
|
||
});
|
||
|
||
it('订单行已删(查不到实时值)⇒ 退回台账落库的商品名', async () => {
|
||
const row = ledgerRow({ item_name: '台账里的名字', our_order_item_id: ITEM });
|
||
query.mockImplementation(async (sql: string) => {
|
||
const text = String(sql);
|
||
if (text.includes('FROM public.main_system_price_qty_requests')) return { rowCount: 1, rows: [row] };
|
||
return { rowCount: 0, rows: [] };
|
||
});
|
||
const { listPriceQtyRequests, toPriceQtyRequestDto } = await import('../src/services/mainSystemPriceQtyRequest');
|
||
const rows = await listPriceQtyRequests({ branchCode: BRANCH });
|
||
expect(toPriceQtyRequestDto(rows[0]).item_name).toBe('台账里的名字');
|
||
});
|
||
|
||
it('提交时把商品名/SKU 落库(列表不必回表也能读)', async () => {
|
||
stubSubmitQueries();
|
||
submit.mockResolvedValue({
|
||
kind: 'ok',
|
||
requestId: 'MS-REQ-1',
|
||
status: 'pending',
|
||
reviewRequired: true,
|
||
finalPrice: null,
|
||
finalQty: null,
|
||
applied: {},
|
||
pending: { price: 8 },
|
||
message: null,
|
||
raw: {},
|
||
});
|
||
await submitPriceQtyRequest({
|
||
branchCode: BRANCH,
|
||
ourOrderCode: ORDER,
|
||
ourOrderItemId: ITEM,
|
||
proposedPrice: 8,
|
||
actor: { userId: 'u1' },
|
||
});
|
||
const insert = query.mock.calls.find((c) => String(c[0]).startsWith('INSERT INTO public.main_system_price_qty_requests'));
|
||
expect(insert, '没有 INSERT').toBeTruthy();
|
||
const values = insert?.[1] as unknown[];
|
||
expect(values).toContain('土豆'); // 商品名(stub 的 order_items.item_name)
|
||
expect(String(insert?.[0])).toContain('item_name, main_sku_code');
|
||
});
|
||
});
|
||
|
||
/* ══════════════════════════════════════════════════════════════════════════════
|
||
* 先改后通知(local-first)—— 开发者 2026-10-12 定稿,取代上面那套"先审后改"。
|
||
*
|
||
* 三条铁律(本 describe 逐条钉住):
|
||
* ① 我方改**我方**字段(销售价 / 数量)⇒ **本地立即生效**,谁都不许拦(守卫直接放行);
|
||
* ② 只**通知**主系统(异步、逐条、失败只记日志);对方同意/驳回**都不回改我方值**;
|
||
* ③ 主系统的结论只记台账 + 留痕;与我方值不同 ⇒ 记 `divergence`,**只留痕不提醒**。
|
||
* ══════════════════════════════════════════════════════════════════════════════ */
|
||
describe('先改后通知(local-first)', () => {
|
||
beforeEach(() => {
|
||
__setPriceQtyLocalFirstForTests(true);
|
||
});
|
||
|
||
/**
|
||
* local-first 的 `decide` 会**读我方订单行现值**(用于算 divergence),
|
||
* 所以桩里必须有一条 `SELECT price, quantity FROM order_items ... id = $2::uuid`。
|
||
*/
|
||
function stubDecideLocalFirst(row: Record<string, unknown>, our: { price: number | null; quantity: number | null }) {
|
||
query.mockImplementation(async (sql: string) => {
|
||
const text = String(sql);
|
||
if (text.includes('FROM public.main_system_price_qty_requests') && text.includes('request_id = $1')) {
|
||
return { rowCount: 1, rows: [row] };
|
||
}
|
||
if (text.startsWith('UPDATE public.main_system_price_qty_requests')) return { rowCount: 1, rows: [row] };
|
||
if (text.includes('FROM order_items') && text.includes('SELECT price, quantity')) {
|
||
return { rowCount: 1, rows: [our] };
|
||
}
|
||
return { rowCount: 0, rows: [] };
|
||
});
|
||
}
|
||
|
||
it('① 守卫直接放行:改价/改量都不再抛 409("改了就是改了")', () => {
|
||
expect(() =>
|
||
assertMainSystemPriceQtyReviewed({
|
||
isMainSystemOrder: true,
|
||
changes: [{ itemId: ITEM, itemName: '土豆', field: 'price', from: 5, to: 6.5 }],
|
||
})
|
||
).not.toThrow();
|
||
expect(() =>
|
||
assertMainSystemPriceQtyReviewed({
|
||
isMainSystemOrder: true,
|
||
changes: [{ itemId: ITEM, itemName: '土豆', field: 'quantity', from: 10, to: 12 }],
|
||
})
|
||
).not.toThrow();
|
||
});
|
||
|
||
it('② 通知是逐条独立的:价/量各提交一次,且失败只吞不抛、不回滚', async () => {
|
||
stubSubmitQueries();
|
||
submit.mockImplementation(async (params: { proposedPrice?: unknown }) =>
|
||
params.proposedPrice != null
|
||
? { kind: 'ok', requestId: 'MS-REQ-PRICE', status: 'pending', reviewRequired: true, finalPrice: null, finalQty: null, message: null, raw: {} }
|
||
: { kind: 'failed', reason: '网络超时' }
|
||
);
|
||
// 不 await:通知是**异步**的(本地写入早已提交,绝不让它拖住请求)
|
||
notifyMainSystemPriceQtyChanges({
|
||
branchCode: BRANCH,
|
||
ourOrderCode: ORDER,
|
||
changes: [
|
||
{ itemId: ITEM, itemName: '土豆', field: 'price', from: 5, to: 6.5 },
|
||
{ itemId: ITEM, itemName: '土豆', field: 'quantity', from: 10, to: 12 },
|
||
],
|
||
actor: { userId: 'u1' },
|
||
});
|
||
await vi.waitFor(() => expect(submit).toHaveBeenCalledTimes(2));
|
||
const priceCall = submit.mock.calls[0][0] as any;
|
||
const qtyCall = submit.mock.calls[1][0] as any;
|
||
expect(priceCall.proposedPrice).toBe(6.5);
|
||
expect(priceCall.proposedQty).toBeNull();
|
||
expect(qtyCall.proposedQty).toBe(12);
|
||
expect(qtyCall.proposedPrice).toBeNull();
|
||
// 两条同源同一备货行,只差被改的字段(一条失败不影响另一条)
|
||
expect(priceCall.prepId).toBe('prep-1');
|
||
expect(qtyCall.prepId).toBe('prep-1');
|
||
expect((audit.mock.calls.map((c) => (c[0] as any).operationType))).toContain('main_system_price_qty_requested');
|
||
});
|
||
|
||
it('② 【实测回归】COMMIT 后再通知:必须用调用方给的"改动前"值,否则被判 no_change 静默不发', async () => {
|
||
// 真库 E2E 复现过:调用方先把 8.30 写成 9.10 并 COMMIT,再通知;
|
||
// 此时回表读到的是 9.10 ⇒ 与 proposed 相同 ⇒ no_change ⇒ **主系统端完全收不到**(我方值却已变)。
|
||
stubSubmitQueries(); // 桩里 order_items.price = 5(模拟"库里已是新值")
|
||
submit.mockResolvedValue({
|
||
kind: 'ok',
|
||
requestId: 'MS-REQ-1',
|
||
status: 'pending',
|
||
reviewRequired: true,
|
||
finalPrice: null,
|
||
finalQty: null,
|
||
message: null,
|
||
raw: {},
|
||
});
|
||
await submitPriceQtyRequest({
|
||
branchCode: BRANCH,
|
||
ourOrderCode: ORDER,
|
||
ourOrderItemId: ITEM,
|
||
proposedPrice: 5, // 与"库里当前值"相同 —— 若不带 beforePrice 就会被判 no_change
|
||
beforePrice: 3, // 真实的改动前值
|
||
actor: { userId: 'u1' },
|
||
});
|
||
expect(submit, '未带 beforePrice 时会静默判 no_change、根本不通知').toHaveBeenCalledTimes(1);
|
||
// 台账 before_* 与发给主系统的 before_value 都必须是**旧值**
|
||
const insert = query.mock.calls.find((c) => String(c[0]).startsWith('INSERT INTO public.main_system_price_qty_requests'));
|
||
const values = insert?.[1] as unknown[];
|
||
expect(values[7]).toBe(3); // before_price
|
||
expect(values[9]).toBe(5); // proposed_price
|
||
});
|
||
|
||
it('② 通知兜异常:submit 直接 reject 也不冒泡(本地值已生效)', async () => {
|
||
stubSubmitQueries();
|
||
submit.mockRejectedValue(new Error('connect ECONNREFUSED'));
|
||
expect(() =>
|
||
notifyMainSystemPriceQtyChanges({
|
||
branchCode: BRANCH,
|
||
ourOrderCode: ORDER,
|
||
changes: [{ itemId: ITEM, itemName: '土豆', field: 'price', from: 5, to: 6.5 }],
|
||
actor: { userId: 'u1' },
|
||
})
|
||
).not.toThrow();
|
||
await vi.waitFor(() => expect(submit).toHaveBeenCalledTimes(1));
|
||
// 让它把 catch 里的日志也走完,避免未处理拒绝泄漏到下一个用例
|
||
await new Promise((r) => setTimeout(r, 0));
|
||
});
|
||
|
||
it('② 开关关闭 / 无变更 / 旧口径 ⇒ 不通知(与改造前逐字节一致)', () => {
|
||
isEnabledFlag.value = false;
|
||
notifyMainSystemPriceQtyChanges({
|
||
branchCode: BRANCH,
|
||
ourOrderCode: ORDER,
|
||
changes: [{ itemId: ITEM, itemName: '土豆', field: 'price', from: 5, to: 6.5 }],
|
||
actor: { userId: 'u1' },
|
||
});
|
||
isEnabledFlag.value = true;
|
||
notifyMainSystemPriceQtyChanges({ branchCode: BRANCH, ourOrderCode: ORDER, changes: [], actor: { userId: 'u1' } });
|
||
__setPriceQtyLocalFirstForTests(false);
|
||
notifyMainSystemPriceQtyChanges({
|
||
branchCode: BRANCH,
|
||
ourOrderCode: ORDER,
|
||
changes: [{ itemId: ITEM, itemName: '土豆', field: 'price', from: 5, to: 6.5 }],
|
||
actor: { userId: 'u1' },
|
||
});
|
||
expect(submit).not.toHaveBeenCalled();
|
||
});
|
||
|
||
it('① 提交只上报、**不**替我改本地(本地值由发起入口写,避免两个写入者)', async () => {
|
||
stubSubmitQueries();
|
||
submit.mockResolvedValue({
|
||
kind: 'ok',
|
||
requestId: 'MS-REQ-1',
|
||
status: 'applied',
|
||
reviewRequired: false,
|
||
finalPrice: 6.5,
|
||
finalQty: 10,
|
||
message: '已生效(低于原价,免审)',
|
||
raw: {},
|
||
});
|
||
const outcome = await submitPriceQtyRequest({
|
||
branchCode: BRANCH,
|
||
ourOrderCode: ORDER,
|
||
ourOrderItemId: ITEM,
|
||
proposedPrice: 6.5,
|
||
unit: '斤',
|
||
actor: { userId: 'u1', roles: 'admin' },
|
||
});
|
||
expect(outcome.kind).toBe('ok');
|
||
if (outcome.kind !== 'ok') return;
|
||
// 对方"免审已生效"仍然照记台账,但**不落本地**
|
||
expect(outcome.status).toBe('applied');
|
||
expect(outcome.appliedLocally).toBe(false);
|
||
expect(syncItems).not.toHaveBeenCalled();
|
||
// 台账 payload 标 notify_only:排障时一眼看出这不是"先审后改"
|
||
const update = query.mock.calls.find((c) => String(c[0]).includes("mode: JSON.stringify") || String(c[0]).includes('payload = $8::jsonb'));
|
||
expect(JSON.stringify(update?.[1] ?? [])).toContain('notify_only');
|
||
// 且**不得**写 auto_applied 那种"本地已落地"的日志
|
||
const types = audit.mock.calls.map((c) => (c[0] as any).operationType);
|
||
expect(types).not.toContain('main_system_price_qty_auto_applied');
|
||
});
|
||
|
||
it('① 需审(pending)在 local-first 下同样不落本地、只留 requested 日志', async () => {
|
||
stubSubmitQueries();
|
||
submit.mockResolvedValue({
|
||
kind: 'ok',
|
||
requestId: 'MS-REQ-1',
|
||
status: 'pending',
|
||
reviewRequired: true,
|
||
finalPrice: null,
|
||
finalQty: null,
|
||
message: '已提交,等待管理员确认',
|
||
raw: {},
|
||
});
|
||
const outcome = await submitPriceQtyRequest({
|
||
branchCode: BRANCH,
|
||
ourOrderCode: ORDER,
|
||
ourOrderItemId: ITEM,
|
||
proposedPrice: 8,
|
||
actor: { userId: 'u1' },
|
||
});
|
||
expect(outcome.kind).toBe('ok');
|
||
if (outcome.kind !== 'ok') return;
|
||
expect(outcome.appliedLocally).toBe(false);
|
||
expect(syncItems).not.toHaveBeenCalled();
|
||
expect((audit.mock.calls.map((c) => (c[0] as any).operationType))).toContain('main_system_price_qty_requested');
|
||
});
|
||
|
||
it('③ 主系统"通过"⇒ 不覆盖我方值:只记台账 + 留痕(值不同 ⇒ divergence)', async () => {
|
||
// 台账里我方现值已被改成 9(先改后通知),主系统给的最终值是 7.25
|
||
stubDecideLocalFirst(ledgerRow({ proposed_price: 9, payload: {} }), { price: 9, quantity: 10 });
|
||
const outcome = await handlePriceQtyDecidedEvent({
|
||
branchCode: BRANCH,
|
||
payload: {
|
||
event: 'preparations.price_qty_decided',
|
||
request_id: 'MS-REQ-1',
|
||
prep_id: 'prep-1',
|
||
decision: 'approved',
|
||
final_price: 7.25,
|
||
reviewer: '主系统管理员',
|
||
},
|
||
});
|
||
expect(outcome.status).toBe('done');
|
||
expect(outcome.reason).toMatch(/不覆盖我方值/);
|
||
// 核心:**没有**改我方库
|
||
expect(syncItems).not.toHaveBeenCalled();
|
||
// 终态照常写(否则对账永远重试)
|
||
const statusUpdate = query.mock.calls.find((c) => String(c[0]).includes('SET status = $2::varchar'));
|
||
expect(statusUpdate).toBeTruthy();
|
||
expect((statusUpdate?.[1] as unknown[])?.[1]).toBe('approved');
|
||
// 差异留痕:local_first.divergence + 一条 diverged 日志
|
||
const trace = query.mock.calls.find((c) => String(c[0]).includes("'local_first'"));
|
||
expect(trace, '没有写 local_first 留痕').toBeTruthy();
|
||
expect((trace?.[1] as unknown[])?.[6]).toBe(true);
|
||
expect((audit.mock.calls.map((c) => (c[0] as any).operationType))).toContain('main_system_price_qty_decision_diverged');
|
||
});
|
||
|
||
it('③ 主系统结论与我方值一致 ⇒ 只记 recorded,不留 divergence', async () => {
|
||
stubDecideLocalFirst(ledgerRow({ proposed_price: 6.5 }), { price: 6.5, quantity: 10 });
|
||
const outcome = await handlePriceQtyDecidedEvent({
|
||
branchCode: BRANCH,
|
||
payload: {
|
||
event: 'preparations.price_qty_decided',
|
||
request_id: 'MS-REQ-1',
|
||
decision: 'approved',
|
||
final_price: 6.5,
|
||
reviewer: '主系统管理员',
|
||
},
|
||
});
|
||
expect(outcome.status).toBe('done');
|
||
expect(outcome.reason).toMatch(/与我方当前值一致/);
|
||
expect(syncItems).not.toHaveBeenCalled();
|
||
const trace = query.mock.calls.find((c) => String(c[0]).includes("'local_first'"));
|
||
expect((trace?.[1] as unknown[])?.[6]).toBe(false);
|
||
expect((audit.mock.calls.map((c) => (c[0] as any).operationType))).toContain('main_system_price_qty_decision_recorded');
|
||
});
|
||
|
||
it('③ 主系统"驳回"⇒ 我方值同样不动(驳回 ≠ 回滚)', async () => {
|
||
stubDecideLocalFirst(ledgerRow({ proposed_price: 9 }), { price: 9, quantity: 10 });
|
||
const outcome = await handlePriceQtyDecidedEvent({
|
||
branchCode: BRANCH,
|
||
payload: {
|
||
event: 'preparations.price_qty_decided',
|
||
request_id: 'MS-REQ-1',
|
||
decision: 'rejected',
|
||
reason: '价格过高',
|
||
reviewer: '主系统管理员',
|
||
},
|
||
});
|
||
expect(outcome.status).toBe('done');
|
||
expect(syncItems).not.toHaveBeenCalled();
|
||
expect((audit.mock.calls.map((c) => (c[0] as any).operationType))).toContain('main_system_price_qty_rejected');
|
||
});
|
||
|
||
it('③ 旧 amend 轮询补齐路径同样受 local-first 管:只记录、不覆盖', async () => {
|
||
const pending = ledgerRow({ request_id: null, ...freshLegacyRowTimestamps() });
|
||
query.mockImplementation(async (sql: string) => {
|
||
const text = String(sql);
|
||
if (text.includes("status = 'pending'") && text.includes('FROM public.main_system_price_qty_requests')) {
|
||
return { rowCount: 1, rows: [pending] };
|
||
}
|
||
if (text.startsWith('UPDATE public.main_system_price_qty_requests')) return { rowCount: 1, rows: [pending] };
|
||
if (text.includes('FROM order_items')) {
|
||
return { rowCount: 1, rows: [{ price: 5, quantity: 10 }] };
|
||
}
|
||
return { rowCount: 0, rows: [] };
|
||
});
|
||
fetchAmend.mockResolvedValue({
|
||
kind: 'ok',
|
||
rows: [
|
||
{
|
||
prepId: 'prep-1',
|
||
orderCode: ORDER,
|
||
prepareQty: 10,
|
||
purchasePrice: 5,
|
||
unit: '斤',
|
||
amendRequest: { id: 'MS-REQ-1', status: 20, statusLabel: '已确认', proposedPrice: 6.8, proposedQty: null, proposedUnit: null, reviewRemark: null, requestedAt: null },
|
||
},
|
||
],
|
||
});
|
||
const { reconcileMainSystemPriceQtyRequests } = await import('../src/services/mainSystemPriceQtyRequest');
|
||
const result = await reconcileMainSystemPriceQtyRequests({ branchCode: BRANCH });
|
||
expect(result.checked).toBe(1);
|
||
expect(result.closed).toBe(1); // 终态照常写(不再重复拉取)
|
||
expect(syncItems).not.toHaveBeenCalled(); // 但不覆盖我方值
|
||
});
|
||
});
|
||
|
||
/* ══════════════════════════════════════════════════════════════════════════════
|
||
* 接线钉子:口径对了,但**接错位置**照样会出事故(本项目踩过:
|
||
* `tryAdvanceOrderToDelivery` 把 (branchCode, orderCode) 传反 ⇒ 回写静默不生效)。
|
||
* 这里用源码级断言把两个调用点的**位置**钉住。
|
||
* ══════════════════════════════════════════════════════════════════════════════ */
|
||
describe('调用点接线:必须"写库 COMMIT 之后"才通知,且通知不阻塞', () => {
|
||
const manageSrc = readFileSync(path.join(__dirname, '../src/services/orderManageItemsService.ts'), 'utf8');
|
||
const saleSrc = readFileSync(path.join(__dirname, '../src/services/purchaseLinkedSalePriceService.ts'), 'utf8');
|
||
|
||
it('订单明细:守卫保留(不删)+ 变更收集保留 + 通知在 COMMIT 之后', () => {
|
||
expect(manageSrc).toContain('assertMainSystemPriceQtyReviewed({');
|
||
expect(manageSrc).toContain('collectMainSystemPriceQtyChanges(existingMap, incoming)');
|
||
/**
|
||
* 2026-10-10:主系统分配行的**数量**改为服务层 409(`main_system_qty_locked`)⇒
|
||
* 通知只带**价格**改动(变量改名 `guardedChanges`)。
|
||
*/
|
||
expect(manageSrc).toContain('const guardedChanges = changes.filter((change) => guarded.has(change.itemId));');
|
||
expect(manageSrc).toContain('priceQtyNotices = guardedChanges;');
|
||
expect(manageSrc).toContain("code: 'main_system_qty_locked'");
|
||
const notifyAt = manageSrc.indexOf('notifyMainSystemPriceQtyChanges({');
|
||
expect(notifyAt).toBeGreaterThan(0);
|
||
// 通知必须在 `await client.query('COMMIT')` 之后(否则回滚了还去通知对方"我改了")
|
||
const commitAt = manageSrc.indexOf("await client.query('COMMIT')");
|
||
expect(commitAt).toBeGreaterThan(0);
|
||
expect(notifyAt).toBeGreaterThan(commitAt);
|
||
// 且必须在 try/catch/finally 之外(不占用请求级连接、不被 ROLLBACK 分支吞掉)
|
||
expect(manageSrc.slice(commitAt, notifyAt)).toContain('finally');
|
||
// 不 await:通知是"发出去就算",绝不拖住明细保存
|
||
expect(manageSrc.slice(notifyAt - 60, notifyAt)).not.toContain('await');
|
||
});
|
||
|
||
it('自采列表改价:通知在本地 UPDATE 之前发出,且之后没有任何 return/throw 拦写入', () => {
|
||
const guardStart = saleSrc.indexOf('跨系统改价通知');
|
||
const guardEnd = saleSrc.indexOf('const quantity = Number(before.rows[0].quantity)');
|
||
const guard = saleSrc.slice(guardStart, guardEnd);
|
||
expect(guard).toContain('await submitPriceQtyRequest(');
|
||
expect(guard).not.toMatch(/\bthrow\b/);
|
||
expect(guard).not.toMatch(/\breturn\b/);
|
||
});
|
||
|
||
it('两条链的通知都只走 submitPriceQtyRequest(不各自发明上报格式)', () => {
|
||
expect(saleSrc).toContain("import { submitPriceQtyRequest } from './mainSystemPriceQtyRequest'");
|
||
expect(manageSrc).toContain('notifyMainSystemPriceQtyChanges');
|
||
});
|
||
});
|
||
|
||
/**
|
||
* **单位变更**(2026-10-13 追加,开发者确认要上报)。
|
||
*
|
||
* 起因:运营给一张**已完成**的主系统单改了单位,主系统那边毫无动静。
|
||
* 真机反证(本地栈 × 真 HTTP):同一张单、同一行 ——
|
||
* · 只改单位 ⇒ 我方与主系统两侧申请 **0 条**(`collectMainSystemPriceQtyChanges` 只比 price/quantity);
|
||
* · 改价 6.5 → 6.51 ⇒ 我方 1 条 pending + 主系统 1 条 pending,链路本身是通的。
|
||
*
|
||
* 落地口径:单位不在主系统 `kind`(price/qty)里 ⇒ 走「**数量不变的改量载体**」:
|
||
* 主系统看到 `proposed_qty === 它的当前值` ⇒ `no_change ⇒ 免审 applied`,并在生效分支里把 `unit`
|
||
* 写进它的备货行(真机实测:备货行 `unit: 斤 → 件 → 斤`,价/量分毫未动)⇒ **不需要主系统改代码**。
|
||
*/
|
||
describe('单位变更(改单位也要上报主系统)', () => {
|
||
const orderManageSrc = readFileSync(
|
||
path.join(__dirname, '../src/services/orderManageItemsService.ts'),
|
||
'utf8'
|
||
);
|
||
|
||
beforeEach(() => {
|
||
__setPriceQtyLocalFirstForTests(true);
|
||
});
|
||
|
||
it('① 通知:单位变更按"数量不变的载体"提交,台账记 kind=qty + unit=新单位', async () => {
|
||
stubSubmitQueries();
|
||
submit.mockResolvedValue({
|
||
kind: 'ok',
|
||
requestId: 'MS-REQ-U',
|
||
status: 'applied',
|
||
reviewRequired: false,
|
||
finalPrice: null,
|
||
finalQty: 10,
|
||
message: '值与当前一致,无需审核',
|
||
raw: {},
|
||
});
|
||
notifyMainSystemPriceQtyChanges({
|
||
branchCode: BRANCH,
|
||
ourOrderCode: ORDER,
|
||
changes: [{ itemId: ITEM, itemName: '土豆', field: 'unit', fromUnit: '斤', toUnit: '件' }],
|
||
actor: { userId: 'u1' },
|
||
});
|
||
await vi.waitFor(() => expect(submit).toHaveBeenCalledTimes(1));
|
||
const call = submit.mock.calls[0][0] as any;
|
||
expect(call.proposedQty, '载体=当前数量(不变)').toBe(10);
|
||
expect(call.proposedPrice).toBeNull();
|
||
expect(call.unit).toBe('件');
|
||
expect(String(call.reason)).toContain('改单位');
|
||
const insert = query.mock.calls.find((c) =>
|
||
String(c[0]).startsWith('INSERT INTO public.main_system_price_qty_requests')
|
||
);
|
||
const values = insert?.[1] as unknown[];
|
||
expect(values?.[6]).toBe('qty');
|
||
expect(Number(values?.[8]), 'before_qty').toBe(10);
|
||
expect(Number(values?.[10]), 'proposed_qty').toBe(10);
|
||
expect(values?.[11], 'unit=新单位').toBe('件');
|
||
});
|
||
|
||
it('② local-first 陷阱:before 必须取调用方给的旧单位(库里已是新值)—— 首版因此静默漏发', async () => {
|
||
stubSubmitQueries(); // 桩里 order_items.unit = '斤',模拟"库里已是新值"
|
||
submit.mockResolvedValue({
|
||
kind: 'ok',
|
||
requestId: 'MS-REQ-U2',
|
||
status: 'applied',
|
||
reviewRequired: false,
|
||
finalPrice: null,
|
||
finalQty: 10,
|
||
message: null,
|
||
raw: {},
|
||
});
|
||
// proposedUnit 与库里现值相同(都是"斤")但**与调用方给的旧值不同** ⇒ 仍必须判为"变了"并上报
|
||
const outcome = await submitPriceQtyRequest({
|
||
branchCode: BRANCH,
|
||
ourOrderCode: ORDER,
|
||
ourOrderItemId: ITEM,
|
||
proposedUnit: '斤',
|
||
beforeUnit: '件',
|
||
actor: { userId: 'u1' },
|
||
});
|
||
expect(outcome.kind).toBe('ok');
|
||
expect(submit).toHaveBeenCalledTimes(1);
|
||
});
|
||
|
||
it('③ 单位没变 ⇒ 不提交(no_change,不发 HTTP)', async () => {
|
||
stubSubmitQueries();
|
||
const outcome = await submitPriceQtyRequest({
|
||
branchCode: BRANCH,
|
||
ourOrderCode: ORDER,
|
||
ourOrderItemId: ITEM,
|
||
proposedUnit: '斤',
|
||
beforeUnit: '斤',
|
||
actor: { userId: 'u1' },
|
||
});
|
||
expect(outcome.kind).toBe('no_change');
|
||
expect(submit).not.toHaveBeenCalled();
|
||
});
|
||
|
||
it('④ 该行有"待审改量"时,单位变更不上报(避免顶掉等待审核的改量)', async () => {
|
||
query.mockImplementation(async (sql: string) => {
|
||
const text = String(sql);
|
||
if (text.includes('FROM order_items') && text.includes('SELECT price')) {
|
||
return { rowCount: 1, rows: [{ price: 5, quantity: 10, unit: '件', item_name: '土豆' }] };
|
||
}
|
||
if (text.includes('FROM public.main_system_order_imports')) {
|
||
return { rowCount: 1, rows: [{ main_order_code: 'ORD_WEB_X' }] };
|
||
}
|
||
if (text.includes('FROM public.main_system_order_import_items')) {
|
||
return { rowCount: 1, rows: [{ prep_id: 'prep-1', main_order_code: 'ORD_WEB_X' }] };
|
||
}
|
||
if (text.includes("kind = 'qty' AND status = 'pending'")) {
|
||
return { rowCount: 1, rows: [{}] };
|
||
}
|
||
return { rowCount: 0, rows: [] };
|
||
});
|
||
const outcome = await submitPriceQtyRequest({
|
||
branchCode: BRANCH,
|
||
ourOrderCode: ORDER,
|
||
ourOrderItemId: ITEM,
|
||
proposedUnit: '件',
|
||
beforeUnit: '斤',
|
||
actor: { userId: 'u1' },
|
||
});
|
||
expect(outcome.kind).toBe('no_change');
|
||
expect(String((outcome as { reason?: string }).reason)).toContain('待审核的改量');
|
||
expect(submit).not.toHaveBeenCalled();
|
||
});
|
||
|
||
it('⑤ 采集口径(源码钉):改明细的变更采集必须比较 unit,否则改单位永远不通知', () => {
|
||
expect(orderManageSrc).toContain("field: 'unit'");
|
||
expect(orderManageSrc).toContain('fromUnit');
|
||
expect(orderManageSrc).toContain('toUnit');
|
||
// 只在请求明确带了非空单位且与库里不同时才记(没传 unit 的入口不受影响)
|
||
expect(orderManageSrc).toContain('if (newUnit && oldUnit !== newUnit)');
|
||
});
|
||
|
||
/**
|
||
* ⑥⑦ = 主系统回执 §10.2-3「跳过 ≠ 排队」的收口(开发者选 A:定向补发,设计文 §11.8)。
|
||
* 补发**不改**触发条件与文案:跳过照旧跳过,只是多留一条"待补发意图",等改量落定后补报。
|
||
*/
|
||
it('⑥ 跳过时留下"待补发意图"(before/target 单位 + 本行标识),返回文案不变', async () => {
|
||
const intentInserts: unknown[][] = [];
|
||
query.mockImplementation(async (sql: string, values?: unknown[]) => {
|
||
const text = String(sql);
|
||
if (text.includes('FROM order_items') && text.includes('SELECT price')) {
|
||
return { rowCount: 1, rows: [{ price: 5, quantity: 10, unit: '件', item_name: '土豆', sku_code: 'SKU1' }] };
|
||
}
|
||
if (text.includes('FROM public.main_system_order_imports')) {
|
||
return { rowCount: 1, rows: [{ main_order_code: 'ORD_WEB_X' }] };
|
||
}
|
||
if (text.includes('FROM public.main_system_order_import_items')) {
|
||
return { rowCount: 1, rows: [{ prep_id: 'prep-1', main_order_code: 'ORD_WEB_X' }] };
|
||
}
|
||
if (text.includes("kind = 'qty' AND status = 'pending'")) {
|
||
return { rowCount: 1, rows: [{}] };
|
||
}
|
||
if (text.startsWith('INSERT INTO public.main_system_price_qty_unit_deferred')) {
|
||
intentInserts.push(values || []);
|
||
return { rowCount: 1, rows: [{ id: 'intent-1' }] };
|
||
}
|
||
return { rowCount: 0, rows: [] };
|
||
});
|
||
const outcome = await submitPriceQtyRequest({
|
||
branchCode: BRANCH,
|
||
ourOrderCode: ORDER,
|
||
ourOrderItemId: ITEM,
|
||
proposedUnit: '件',
|
||
beforeUnit: '斤',
|
||
actor: { userId: 'u1' },
|
||
});
|
||
expect(outcome.kind).toBe('no_change');
|
||
expect(String((outcome as { reason?: string }).reason), '文案不变(运营看到的仍是"本次未上报")').toContain(
|
||
'待审核的改量'
|
||
);
|
||
expect(submit, '本次仍然不上报').not.toHaveBeenCalled();
|
||
expect(intentInserts, '留一条意图,等改量落定后补发').toHaveLength(1);
|
||
const values = intentInserts[0];
|
||
expect(values[0], 'branch_code').toBe(BRANCH);
|
||
expect(values[1], 'prep_id').toBe('prep-1');
|
||
expect(values[3], 'our_order_code').toBe(ORDER);
|
||
expect(values[4], 'our_order_item_id').toBe(ITEM);
|
||
expect(values[5], 'before_unit').toBe('斤');
|
||
expect(values[6], 'target_unit').toBe('件');
|
||
});
|
||
|
||
it('⑦ 改量被驳回 ⇒ 落定后自动补发一次单位载体(幂等键 = 意图行 id)', async () => {
|
||
__setPriceQtyLocalFirstForTests(true);
|
||
const intent = {
|
||
id: 'intent-9',
|
||
branch_code: BRANCH,
|
||
prep_id: 'prep-1',
|
||
main_order_code: 'ORD_WEB_X',
|
||
our_order_code: ORDER,
|
||
our_order_item_id: ITEM,
|
||
before_unit: '斤',
|
||
target_unit: '件',
|
||
status: 'waiting',
|
||
attempts: 0,
|
||
last_error: null,
|
||
deferred_at: '2026-10-13T05:00:00.000Z',
|
||
resolved_at: null,
|
||
updated_at: '2026-10-13T05:00:00.000Z',
|
||
payload: {},
|
||
};
|
||
const intentStatuses: unknown[] = [];
|
||
const ledgerInserts: unknown[][] = [];
|
||
query.mockImplementation(async (sql: string, values?: unknown[]) => {
|
||
const text = String(sql);
|
||
if (text.startsWith('UPDATE public.main_system_price_qty_unit_deferred')) {
|
||
intentStatuses.push(values?.[1]);
|
||
return { rowCount: 1, rows: [] };
|
||
}
|
||
if (text.includes('FROM public.main_system_price_qty_unit_deferred')) {
|
||
return { rowCount: 1, rows: [intent] };
|
||
}
|
||
// 事件处理器按 request_id 找到那条**待审改量**台账行
|
||
if (text.includes('FROM public.main_system_price_qty_requests') && text.includes('request_id = $2')) {
|
||
return { rowCount: 1, rows: [ledgerRow({ kind: 'qty', proposed_qty: 12, unit: null, status: 'pending' })] };
|
||
}
|
||
if (text.includes('SELECT 1 FROM public.main_system_price_qty_requests')) {
|
||
return { rowCount: 0, rows: [] }; // 补发前提①:此刻已无 pending
|
||
}
|
||
if (text.startsWith('DELETE FROM public.main_system_price_qty_requests')) {
|
||
return { rowCount: 0, rows: [] };
|
||
}
|
||
if (text.startsWith('INSERT INTO public.main_system_price_qty_requests')) {
|
||
ledgerInserts.push(values || []);
|
||
return { rowCount: 1, rows: [ledgerRow({ kind: 'qty', unit: '件' })] };
|
||
}
|
||
if (text.startsWith('UPDATE public.main_system_price_qty_requests')) {
|
||
return { rowCount: 1, rows: [ledgerRow({ kind: 'qty' })] };
|
||
}
|
||
if (text.includes('FROM order_items')) {
|
||
// 提交路径(带 SELECT price)与补发读单位路径都返回"库里已是新单位件"
|
||
return { rowCount: 1, rows: [{ price: 5, quantity: 10, unit: '件', item_name: '土豆', sku_code: 'SKU1' }] };
|
||
}
|
||
if (text.includes('FROM public.main_system_order_imports')) {
|
||
return { rowCount: 1, rows: [{ main_order_code: 'ORD_WEB_X' }] };
|
||
}
|
||
if (text.includes('FROM public.main_system_order_import_items')) {
|
||
return { rowCount: 1, rows: [{ prep_id: 'prep-1', main_order_code: 'ORD_WEB_X' }] };
|
||
}
|
||
return { rowCount: 0, rows: [] };
|
||
});
|
||
submit.mockResolvedValue({
|
||
kind: 'ok',
|
||
requestId: 'MS-REQ-RESEND',
|
||
status: 'applied',
|
||
reviewRequired: false,
|
||
finalPrice: null,
|
||
finalQty: 10,
|
||
message: '值与当前一致,无需审核',
|
||
raw: {},
|
||
});
|
||
|
||
const handled = await handlePriceQtyDecidedEvent({
|
||
branchCode: BRANCH,
|
||
payload: { request_id: 'MS-REQ-1', kind: 'qty', decision: 'rejected', reason: '审核不通过', final_value: null },
|
||
});
|
||
expect(handled.status).toBe('done');
|
||
expect(String(handled.reason)).toContain('驳回');
|
||
|
||
// ① 补发:仍走"数量不变的载体",只报单位
|
||
await vi.waitFor(() => expect(submit).toHaveBeenCalledTimes(1));
|
||
const call = submit.mock.calls[0][0] as any;
|
||
expect(call.proposedQty, '载体 = 该行当前数量(不变)').toBe(10);
|
||
expect(call.proposedPrice).toBeNull();
|
||
expect(call.unit).toBe('件');
|
||
expect(String(call.reason)).toContain('单位变更补报');
|
||
// ② 幂等键确定性(同一意图重复触发 ⇒ 命中台账唯一键,不重复上报)
|
||
const inserted = ledgerInserts[0];
|
||
expect(inserted?.[1], 'client_request_id').toBe('unit-deferred-intent-9');
|
||
expect(inserted?.[6], 'kind').toBe('qty');
|
||
expect(Number(inserted?.[10]), 'proposed_qty').toBe(10);
|
||
expect(inserted?.[11], 'unit').toBe('件');
|
||
// ③ 意图收敛为 sent
|
||
expect(intentStatuses).toContain('sent');
|
||
});
|
||
});
|