import { readFileSync } from 'node:fs'; import { describe, expect, it } from 'vitest'; /** * 「实收/单位申请」接收端(对方发起 → 我方审核)契约。 * 主系统 Q8/Q9 已交付(提交 b8519fbb);我方按 §4.9/§4.10/§4.11 的口径实现。 */ const inbox = readFileSync(new URL('../src/services/mainSystemActualQtyInbox.ts', import.meta.url), 'utf8'); const route = readFileSync(new URL('../src/routes/mainSystemIntegration.ts', import.meta.url), 'utf8'); const api = readFileSync(new URL('../src/services/mainSystem/api/preparations.ts', import.meta.url), 'utf8'); const cfg = readFileSync(new URL('../src/services/mainSystem/config.ts', import.meta.url), 'utf8'); describe('"同一商品只留最新一条待审"(开发者 2026-10-12)', () => { it('用**一次确定性收敛**(最新一条留下、其余 superseded),不得"谁后到谁关掉对方"', () => { expect(inbox).toContain('async function convergeLatestPending'); const idx = inbox.indexOf('async function convergeLatestPending'); const body = inbox.slice(idx, idx + 2600); // 排序键:最终生效时间 → 落库时间 → 有真 request_id 优先 → id(顺序与到达顺序无关 ⇒ 幂等) expect(body).toContain('ORDER BY COALESCE(applied_at, created_at) DESC'); expect(body).toContain("(payload->>'local_only' IS NULL) DESC"); expect(body).toContain("SET status = 'superseded'"); expect(body).toContain('prep_id IS NOT DISTINCT FROM $2::uuid'); expect(body).toContain("AND field = $3"); expect(body).toContain('AND id <> $6::uuid'); // 可回溯:谁取代了它 expect(body).toContain("'superseded_by'"); // ⚠️ 2026-10-12 真库实测的坑:旧实现"各写各的"会让两条**互相取代、全废** expect(inbox).not.toContain('supersedeOlderPending'); expect(inbox.match(/await convergeLatestPending\(/g)?.length ?? 0).toBeGreaterThanOrEqual(3); }); }); describe('preparations.price_changed 事实接收端(2026-10-12 新增)', () => { const routeHasBranch = route.includes("event === 'preparations.price_changed'"); it('事件已接线(此前一律 200 ignored ⇒ 主系统以为我们没收到)', () => { expect(routeHasBranch).toBe(true); expect(route).toContain('recordPriceChangedFact'); }); it('有可审申请时只附事实、**不新建**第二条待审', () => { const idx = inbox.indexOf('export async function recordPriceChangedFact'); const body = inbox.slice(idx, idx + 4000); expect(body).toContain("'price_changed_fact'"); expect(body).toMatch(/该商品已有待审的价格申请/); // 幂等键派生确定性 UUID(重推不产生第二行) expect(inbox).toContain("from '../utils/deterministicUuid'"); }); it('无对应申请时补一条**本地待审**(审核页照常出现,由我方决定跟不跟)', () => { const idx = inbox.indexOf('export async function recordPriceChangedFact'); const body = inbox.slice(idx, idx + 9000); expect(body).toContain("local_only: true"); expect(body).toContain("'post_complete_price'"); // 本地事实行不回传主系统(对方已生效;驳回 = 我方自己不改而已) expect(inbox).toContain('const isLocalOnly = Boolean'); expect(inbox).toContain('本地事实行(对方已生效),无需回执'); }); }); describe('驳回 = 我方自己不改而已(两个方向都不越界)', () => { it('驳回不写终值:台账 final_value 必须留空(原来会存入对方 proposed,被历史列表当"我方最终值")', () => { expect(inbox).toContain("params.decision === 'approved' ? appliedValue : null"); // 且落值只在 approved 时调用 expect(inbox).toMatch(/if \(params\.decision === 'approved' && row\.our_order_code\)/); }); it('审核**不外传** final_value("不能自己修改对方想要的值")', () => { // 开发者 2026-10-12:「关闭了,不能自己修改对方想要的值,相当于就是自己只能改自己的」 expect(inbox).toContain('finalValue: null,'); // 手填的值只影响我方落值 ⇒ 取值优先级里 requestedFinalValue 排第一 expect(inbox).toMatch(/const appliedValue =\s*requestedFinalValue \?\?/); // 传输层:空值一律**不放进请求体**(否则等于给对方一个"按此值改写"的指令) expect(api).toMatch(/params\.finalValue === null \|\| params\.finalValue === undefined \? \{\} : \{ final_value: params\.finalValue \}/); }); it('对方对我方申请的结论(actual_qty_decided)只改台账,**绝不**碰我方业务数据', () => { const idx = inbox.indexOf('export async function handleActualQtyDecidedEvent'); const body = inbox.slice(idx, idx + 6000); expect(body).toContain('UPDATE public.main_system_actual_qty_requests'); for (const tbl of ['order_items', 'picking_items', 'inspections', 'applyActualQtySyncValue']) { expect(body, `该处理器不得写 ${tbl}`).not.toContain(tbl); } }); }); describe('审核页状态下拉的服务端过滤(2026-10-12 界面重构)', () => { it('status 支持逗号多值("已失效"= withdrawn,superseded),且非法值**返回空集**而不是放行全部', () => { expect(inbox).toContain('const INBOX_STATUSES = new Set('); const idx = inbox.indexOf('const statusList = status'); const body = inbox.slice(idx, idx + 900); expect(body).toContain("r.status = ANY($${args.length}::text[])"); expect(body).toContain("where.push('FALSE')"); // 只有一个合法值时仍走等值(走索引) expect(body).toContain('r.status = $'); }); }); describe('确定性 UUID(事实事件的幂等键 → request_id)', () => { it('同一 seed 恒定、不同 seed 不同,且形态合规(能被 UUID 校验放行)', async () => { const { deterministicUuid } = await import('../src/utils/deterministicUuid'); const a = deterministicUuid('pc_prep-1_3_4'); const b = deterministicUuid('pc_prep-1_3_4'); const c = deterministicUuid('pc_prep-1_3_5'); expect(a).toBe(b); expect(a).not.toBe(c); expect(a).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-5[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/); }); }); describe('乐观并发校验(主系统第七批 §12.3 / 我方 §4.5.6-A)', () => { const migration = readFileSync( new URL('../../migrations/20261025_main_system_actual_qty_request_version.sql', import.meta.url), 'utf8' ); it('迁移加 request_version / request_updated_at(NULL = 对方未提供,行为与旧版一致)', () => { expect(migration).toMatch(/ADD COLUMN IF NOT EXISTS request_version INTEGER/); expect(migration).toMatch(/ADD COLUMN IF NOT EXISTS request_updated_at TIMESTAMPTZ/); }); it('事件/Q6 都映射版本,回执带 decided_basis_version,409 单独分类并自动刷新', () => { expect(inbox).toMatch(/requestVersion: num\(payload\?\.request_version\)/); expect(inbox).toContain('decidedBasisVersion: row.request_version ?? null'); expect(api).toContain('decided_basis_version: params.decidedBasisVersion'); expect(api).toContain("kind: 'stale'"); expect(api).toMatch(/stale_request_version/); expect(inbox).toContain('该申请已被主系统更新为最新值,已刷新,请重新确认'); }); it('成本价同意落值:写我方销售价 + 重算金额 + 重建结算投影(不再静默无操作)', () => { const apply = readFileSync( new URL('../src/services/mainSystemActualQtyApply.ts', import.meta.url), 'utf8' ); expect(apply).toMatch(/params\.field === 'price' \? params\.finalValue : null/); expect(apply).toContain('syncStatementsForOrderSafe(orderCode, null)'); }); }); describe('实收申请接收端', () => { it('事件已接线且幂等键用对方 request_id', () => { expect(route).toContain("preparations.actual_qty_request"); expect(route).toContain('recordActualQtyRequest'); expect(inbox).toContain('WHERE branch_code = $1 AND request_id = $2'); expect(inbox).toContain('ON CONFLICT (branch_code, request_id) DO NOTHING'); }); it('事实登记节点 = 核货 + 撤销核货 + 入库 + ≥60 修正 + 成本价(全部"先改后审",驳回不回滚)', () => { // 2026-10-12 终态:主系统**所有**节点都是"先改自己的值再发请求" ⇒ 全部事实登记。 // 成本价 `post_complete_price` 于主系统第七批 `3e90deb9`(其设计文档 §12.1)从 ≥90"先审后改" // 翻转为"写库后通知" ⇒ 2026-10-12 起我方也必须把它算作事实登记(否则驳回文案会谎称"双方均不改值")。 expect(inbox).toMatch( /const FACT_NODES = new Set\(\[[^\]]*'post_complete_price'[^\]]*\]\)/ ); for (const node of ['picking_check', 'picking_check_revert', 'inbound', 'admin_received_qty', 'post_complete_price']) { expect(inbox).toContain(`'${node}'`); } // 不得再有"成本价先审后改"的过期断言/注释 expect(inbox).not.toMatch(/`post_complete_price` 不在其列/); expect(inbox).toContain('fact_registered'); // 驳回:不回传 final_value,且文案明确"对方不回滚、我方只留痕" expect(inbox).toContain("params.decision === 'approved'"); expect(inbox).toContain('事实登记,不回滚'); // 2026-10-12 口径:审核人没手填值时**回传 null**(让主系统按它当前值落地), // 本地落值改用**回执返回的 final_value** —— 不再用我方台账里的(可能是旧的)proposed_value 兜底, // 否则在"同一 request_id 被原地刷新"的情况下会把旧值覆盖回去。 expect(inbox).toContain('const requestedFinalValue ='); expect(inbox).toContain('const appliedValue ='); expect(inbox).not.toContain('params.finalValue ?? num(row.proposed_value)'); }); it('决策回传打到主系统的 actual-qty-decision(路径只在 endpoints/config 定义)', () => { expect(api).toContain('export async function postMainSystemActualQtyDecision'); expect(api).toContain("mainSystemPath('actualQtyDecision')"); expect(cfg).toContain("actualQtyDecision: '/api/supplier/preparations/actual-qty-decision'"); expect(api).toContain('request_id: params.requestId'); expect(api).toContain('decision: params.decision'); }); it('request_id 必须 UUID(非 UUID 直接忽略,不入待审队列)', () => { expect(inbox).toContain('const UUID_RE ='); expect(inbox).toContain('request_id 非 UUID,已忽略'); const start = inbox.indexOf('export async function recordActualQtyRequest'); const fn = inbox.slice(start, start + 1200); expect(fn).toContain('if (!UUID_RE.test(mapped.requestId))'); }); it('回传失败不落本地结论(避免两边不一致)', () => { expect(inbox).toContain("if (sent.kind !== 'ok')"); expect(inbox).toContain('回传主系统失败,未改本地结论'); }); });