feat(主系统退回/售后): 退回台账轮询兜底 + webhook 失败逐行日志 + 覆盖残值清扫排除退回行 + 批次报告候选排序兜底

This commit is contained in:
Ubuntu
2026-10-23 17:07:12 +08:00
parent 308afff5ad
commit 7d21720e92
10 changed files with 390 additions and 52 deletions
+18 -4
View File
@@ -607,7 +607,14 @@ router.post('/main-system/webhook', async (req: Request, res: Response) => {
*/
if (event === 'preparations.returned') {
const rawRows = Array.isArray(payload?.data) ? payload.data : [payload];
const results: Array<{ prepId: string; ok: boolean; duplicated?: boolean; resupplyOrderCode?: string | null; error?: string }> = [];
const results: Array<{
prepId: string;
ok: boolean;
duplicated?: boolean;
resupplyOrderCode?: string | null;
error?: string;
ourOrderCode?: string;
}> = [];
const { ingestMainSystemReturn, resolveOrderCodeByPrepId } = await import('../services/mainSystemReturnService');
for (const raw of rawRows) {
const row = (raw || {}) as Record<string, unknown>;
@@ -618,13 +625,13 @@ router.post('/main-system/webhook', async (req: Request, res: Response) => {
(branchCode ? await resolveOrderCodeByPrepId({ branchCode, prepId }) : null) ||
'';
if (!ourOrderCode) {
results.push({ prepId, ok: false, error: 'order_not_found' });
results.push({ prepId, ok: false, ourOrderCode, error: 'order_not_found' });
continue;
}
const quantity = Number(row.return_qty ?? row.qty ?? row.quantity);
const skuCode = String(row.sku_code || '').trim();
if (!(quantity > 0) || !skuCode) {
results.push({ prepId, ok: false, error: 'invalid_payload' });
results.push({ prepId, ok: false, ourOrderCode, error: 'invalid_payload' });
continue;
}
try {
@@ -643,10 +650,17 @@ router.post('/main-system/webhook', async (req: Request, res: Response) => {
});
results.push({ prepId, ok: true, duplicated: out.duplicated, resupplyOrderCode: out.resupplyOrderCode });
} catch (error) {
results.push({ prepId, ok: false, error: (error as Error)?.message || 'failed' });
results.push({ prepId, ok: false, ourOrderCode, error: (error as Error)?.message || 'failed' });
}
}
console.log(`[main-system-webhook] ${branchCode} preparations.returned:处理 ${results.length} 行,成功 ${results.filter((r) => r.ok).length}`);
// 现场排障:每行失败都带 prepId / ourOrderCode / error 打出来,不能只有"成功 0"
for (const bad of results.filter((r) => !r.ok)) {
console.warn(
`[main-system-webhook] ${branchCode} preparations.returned 失败:` +
`prepId=${bad.prepId} ourOrderCode=${bad.ourOrderCode || ''} error=${bad.error || 'unknown'}`
);
}
return res.json({ ok: true, results });
}
+136 -40
View File
@@ -1,16 +1,16 @@
import { Router, type Request, type Response } from 'express';
import { pool } from '../db';
import { runWithTenantDbContext } from '../services/tenantDbContext';
/**
* 公开(免鉴权)批次产地查询:`GET /api/public/order-origin?main_order_code=&main_sku=`
*
* 用途(2026-10-21 用户设计):主系统溯源时按「主系统订单号 + 主系统 SKU」来问供应商这个货的产地,
* 由掌握映射关系的一方(本系统)回答,避免主系统自己做批次映射。
* 主系统溯源时用「主系统订单号 + 主系统 SKU」问供应商;本系统负责:
* ① 用 public.main_system_order_import_items 把主订单号换成本系统订单号;
* ② 用 active SKU 映射换成本系统 SKU;映射缺失时用导入行品名兜底;
* ③ 按本系统订单出库批次 → inventory.origin → skus.origin 查产地。
*
* 只返回 `{ origin }`(字符串或 null)——不泄漏 SKU/批次/订单等其它数据。
* 查找顺序:订单出库批次(picking_items.outbound_batches)→ inventory.origin(批次优先)
* → skus.origin(商品档案兜底)。
* 全部失败一律 200 + `{ origin: null }`,不抛错、不 5xx。
* 只返回 `{ origin }`,失败一律 200 + null,不泄漏订单/SKU/批次。
*/
const router = Router();
@@ -18,6 +18,12 @@ function toText(value: unknown): string {
return value == null ? '' : String(value).trim();
}
function tenantSchema(branchCode: string): string | null {
const branch = toText(branchCode).toLowerCase();
if (!/^br[0-9a-z]+$/.test(branch)) return null;
return `tenant_${branch}`;
}
/** outbound_batches 可能是字符串数组、{batch_no} 数组或 JSON 字符串 */
function extractBatchNos(raw: unknown): string[] {
let value = raw;
@@ -39,6 +45,107 @@ function extractBatchNos(raw: unknown): string[] {
.filter(Boolean);
}
type Candidate = { branchCode: string; schema: string; orderCode: string; itemName: string };
async function resolveCandidates(mainOrderCode: string): Promise<Candidate[]> {
const imports = await pool.query<{
branch_code: string | null;
our_order_code: string | null;
item_name: string | null;
}>(
`SELECT branch_code, our_order_code, item_name
FROM public.main_system_order_import_items
WHERE main_order_code = $1
AND NULLIF(TRIM(our_order_code), '') IS NOT NULL
ORDER BY branch_code, our_order_code, item_name`,
[mainOrderCode]
);
const out: Candidate[] = [];
const seen = new Set<string>();
for (const row of imports.rows) {
const branchCode = toText(row.branch_code).toUpperCase();
const schema = tenantSchema(branchCode);
const orderCode = toText(row.our_order_code);
if (!schema || !orderCode) continue;
const key = `${schema}::${orderCode}::${toText(row.item_name)}`;
if (seen.has(key)) continue;
seen.add(key);
out.push({ branchCode, schema, orderCode, itemName: toText(row.item_name) });
}
// 兼容供应商侧直接存主系统订单号的历史行
out.push({ branchCode: '', schema: '', orderCode: mainOrderCode, itemName: '' });
return out;
}
async function resolveSupplierSku(
schema: string,
orderCode: string,
mainSku: string,
itemName: string
): Promise<string> {
if (!schema) return '';
const mapped = await pool.query<{ supplier_sku_code: string | null }>(
`SELECT supplier_sku_code FROM "${schema}".main_system_sku_mappings
WHERE delivery_sku_code = $1 AND status = 'active'
AND NULLIF(TRIM(supplier_sku_code), '') IS NOT NULL
LIMIT 1`,
[mainSku]
);
const fromMapping = toText(mapped.rows[0]?.supplier_sku_code);
if (fromMapping) return fromMapping;
// 映射缺失时按导入行品名从本系统拣货行兜底(同一订单同名商品取第一条)
if (itemName) {
const byName = await pool.query<{ sku_code: string | null }>(
`SELECT sku_code FROM "${schema}".picking_items
WHERE order_code = $1 AND TRIM(COALESCE(item_name, '')) = $2
AND NULLIF(TRIM(sku_code), '') IS NOT NULL
LIMIT 1`,
[orderCode, itemName]
);
const fromPick = toText(byName.rows[0]?.sku_code);
if (fromPick) return fromPick;
}
return '';
}
async function lookupOrigin(
schema: string,
orderCode: string,
mainSku: string,
itemName: string
): Promise<string | null> {
if (!schema) return null;
const supplierSku = await resolveSupplierSku(schema, orderCode, mainSku, itemName);
if (!supplierSku) return null;
const items = await pool.query<{ outbound_batches: unknown }>(
`SELECT outbound_batches FROM "${schema}".picking_items
WHERE order_code = $1 AND sku_code = $2
LIMIT 50`,
[orderCode, supplierSku]
);
for (const item of items.rows) {
for (const batchNo of extractBatchNos(item.outbound_batches)) {
const originRow = await pool.query<{ origin: string | null }>(
`SELECT NULLIF(TRIM(origin), '') AS origin FROM "${schema}".inventory
WHERE batch_no = $1 AND sku_code = $2
LIMIT 1`,
[batchNo, supplierSku]
);
const origin = toText(originRow.rows[0]?.origin);
if (origin) return origin;
}
}
const skuOrigin = await pool.query<{ origin: string | null }>(
`SELECT NULLIF(TRIM(origin), '') AS origin FROM "${schema}".skus
WHERE sku_code = $1 LIMIT 1`,
[supplierSku]
);
return toText(skuOrigin.rows[0]?.origin) || null;
}
router.get('/order-origin', async (req: Request, res: Response) => {
const mainOrderCode = toText(req.query.main_order_code);
const mainSku = toText(req.query.main_sku);
@@ -46,43 +153,32 @@ router.get('/order-origin', async (req: Request, res: Response) => {
return res.status(400).json({ error: 'invalid_request' });
}
try {
const schemas = await pool.query<{ schema_name: string }>(
`SELECT schema_name FROM information_schema.schemata
WHERE schema_name LIKE 'tenant\\_%' ESCAPE '\\' AND schema_name <> 'tenant_template'`
);
for (const { schema_name: schema } of schemas.rows) {
const q = async (sql: string, params?: unknown[]) =>
pool.query(sql.replace(/__S__/g, `"${schema}"`), params);
const rows = await q(
`SELECT outbound_batches, sku_code FROM __S__.picking_items WHERE order_code = $1 LIMIT 50`,
[mainOrderCode]
);
const items = rows.rows as Array<{ outbound_batches: unknown; sku_code: string }>;
if (!items.length) continue;
const mapped = await q(
`SELECT supplier_sku_code FROM __S__.main_system_sku_mappings
WHERE delivery_sku_code = $1 AND status = 'active'
AND NULLIF(TRIM(supplier_sku_code), '') IS NOT NULL LIMIT 1`,
[mainSku]
);
const supplierSku = toText((mapped.rows[0] as { supplier_sku_code?: string } | undefined)?.supplier_sku_code);
if (!supplierSku) continue;
const hit = items.find((item) => toText(item.sku_code) === supplierSku);
if (!hit) continue;
const batchNos = extractBatchNos(hit.outbound_batches);
for (const batchNo of batchNos) {
const originRow = await q(
`SELECT NULLIF(TRIM(origin), '') AS origin FROM __S__.inventory WHERE batch_no = $1 AND sku_code = $2 LIMIT 1`,
[batchNo, supplierSku]
for (const candidate of await resolveCandidates(mainOrderCode)) {
// 候选项可能没有 import 行(直存主订单号);此时扫租户 schema 定位
if (!candidate.schema) {
const schemas = await pool.query<{ schema_name: string }>(
`SELECT schema_name FROM information_schema.schemata
WHERE schema_name LIKE 'tenant\\_%' ESCAPE '\\' AND schema_name <> 'tenant_template'`
);
const origin = toText((originRow.rows[0] as { origin?: string } | undefined)?.origin);
if (origin) return res.json({ origin });
for (const { schema_name: schema } of schemas.rows) {
const branchCode = schema.replace(/^tenant_/, '').toUpperCase();
const exists = await runWithTenantDbContext(branchCode, () =>
pool.query(`SELECT 1 FROM "${schema}".picking_items WHERE order_code = $1 LIMIT 1`, [
candidate.orderCode,
])
);
if (!exists.rowCount) continue;
const origin = await runWithTenantDbContext(branchCode, () =>
lookupOrigin(schema, candidate.orderCode, mainSku, candidate.itemName)
);
if (origin) return res.json({ origin });
}
continue;
}
const skuOrigin = await q(
`SELECT NULLIF(TRIM(origin), '') AS origin FROM __S__.skus WHERE sku_code = $1 LIMIT 1`,
[supplierSku]
const origin = await runWithTenantDbContext(candidate.branchCode, () =>
lookupOrigin(candidate.schema, candidate.orderCode, mainSku, candidate.itemName)
);
return res.json({ origin: toText((skuOrigin.rows[0] as { origin?: string } | undefined)?.origin) || null });
if (origin) return res.json({ origin });
}
return res.json({ origin: null });
} catch (error) {
@@ -225,8 +225,10 @@ async function loadCandidateRows(
FROM inventory i
LEFT JOIN skus s ON s.sku_code = i.sku_code
WHERE i.branch_code = $1${dateFilter}
-- 2026-10-20 开发者:手动匹配批次列表按**入库时间**排(最新入库在前),便于查找
ORDER BY i.created_at DESC NULLS LAST, i.available_qty DESC
-- 2026-10-20 开发者:手动匹配列表按"最新在前"排:
-- 入库时间优先;**created_at 为空的批次**(历史导入数据)用生产日期兜底,
-- 否则它们会全部落到末尾且内部无序,看起来像"乱序"。
ORDER BY i.created_at DESC NULLS LAST, i.production_date DESC NULLS LAST, i.available_qty DESC
LIMIT ${CANDIDATE_SCAN_LIMIT}`,
params
);
@@ -1587,6 +1587,8 @@ export async function sweepReturnedItemsWithCoverResidue(
FROM order_items oi
WHERE COALESCE(oi.is_returned, false) = true
AND COALESCE(oi.stock_cover_qty, 0) > 0.000001
-- 主系统「退回」不是「退货」:我们退回行 return_code 以 R 开头(退货是 OIR_),不得被清扫误伤
AND (oi.return_code IS NULL OR oi.return_code NOT LIKE 'R%')
ORDER BY oi.created_at DESC
LIMIT $1`,
[Math.max(1, Math.min(1000, Number(limit) || 200))]
+33 -6
View File
@@ -819,29 +819,56 @@ async function runReturnFollowReconcile() {
const { followMainSystemPrepChanges } = await import('./mainSystemReturnFollow');
const branches = await listMainSupplierBranchCodes();
const results = await mapWithConcurrency(branches, 3, async (branchCode) => {
let outcome: Awaited<ReturnType<typeof followMainSystemPrepChanges>> | null = null;
try {
return { branchCode, outcome: await followMainSystemPrepChanges(branchCode) };
outcome = await followMainSystemPrepChanges(branchCode);
} catch (error: any) {
console.error(`[scheduler] 退货跟随失败(${branchCode}):`, error?.message || error);
return null;
}
/**
* 主系统「商品退回」台账轮询兜底:webhook `preparations.returned` 失败/漏推时,
* 靠台账里的 last_return_code 落退回单 + 补送单(幂等由 after_sale_returns 唯一键保证)。
*/
let returnSummary: { scanned: number; created: number; skipped: number } | null = null;
try {
const { ingestReturnsFromLedger } = await import('./mainSystemReturnService');
returnSummary = await ingestReturnsFromLedger({ branchCode });
} catch (error: any) {
console.error(`[scheduler] 退回台账轮询失败(${branchCode}):`, error?.message || error);
}
return { branchCode, outcome, returnSummary };
});
let cancelled = 0;
let returned = 0;
let suspended = 0;
let failed = 0;
let returnScanned = 0;
let returnCreated = 0;
let returnSkipped = 0;
for (const r of results) {
if (!r) continue;
cancelled += r.outcome.cancelled;
returned += r.outcome.returned;
suspended += r.outcome.suspended;
failed += r.outcome.failed;
if (r.outcome) {
cancelled += r.outcome.cancelled;
returned += r.outcome.returned;
suspended += r.outcome.suspended;
failed += r.outcome.failed;
}
if (r.returnSummary) {
returnScanned += r.returnSummary.scanned;
returnCreated += r.returnSummary.created;
returnSkipped += r.returnSummary.skipped;
}
}
if (cancelled || returned || suspended || failed) {
console.log(
`[scheduler] 退货/删单跟随:取消履约 ${cancelled} / 退货红冲 ${returned} / 挂待处理 ${suspended} / 失败 ${failed}(分公司 ${branches.length})`
);
}
if (returnScanned || returnCreated || returnSkipped) {
console.log(
`[scheduler] 退回台账轮询:扫描 ${returnScanned} / 新建退回 ${returnCreated} / 跳过 ${returnSkipped}(分公司 ${branches.length})`
);
}
} catch (error) {
console.error('[scheduler] 退货/删单跟随兜底异常:', error);
}
@@ -0,0 +1,41 @@
import { readFileSync } from 'node:fs';
import path from 'node:path';
import { describe, expect, it } from 'vitest';
/**
* 20261071 存量回填契约:after_sales / after_sale_returns 的 sku_code 从主系统 SKU → 本地 SKU。
*
* 幂等靠三件事(这里直接钉源码,避免迁移改坏):
* · 已是本地 SKU 的行不更新(oi.sku_code <> 旧 sku_code);
* · after_sale_returns 撞 (branch, main_return_code, sku, order) 唯一键时跳过旧行;
* · 整个迁移由 migrate.ts 包事务,失败整体回滚。
*/
const sql = readFileSync(
path.join(__dirname, '..', '..', 'migrations', '20261071_after_sale_local_sku_backfill.sql'),
'utf8'
);
describe('20261071 回填:主系统 SKU → 本地 SKU', () => {
it('after_sales 按台账 our_order_item_id 关联本地订单行', () => {
expect(sql).toContain('UPDATE %1$I.after_sales a');
expect(sql).toContain('oi.id = li.our_order_item_id');
expect(sql).toContain('a.sku_code = li.main_sku_code');
expect(sql).toContain("a.aftersale_type = 'main_system_return'");
expect(sql).toContain('oi.sku_code <> a.sku_code');
});
it('after_sale_returns 回填并避开 order+main_return_code+sku 唯一键冲突', () => {
expect(sql).toContain('UPDATE %1$I.after_sale_returns r');
expect(sql).toContain('r.sku_code = li.main_sku_code');
expect(sql).toContain('oi.sku_code <> r.sku_code');
expect(sql).toMatch(/x\.main_return_code = r\.main_return_code/);
expect(sql).toMatch(/x\.sku_code = oi\.sku_code/);
expect(sql).toMatch(/x\.return_code <> r\.return_code/);
});
it('用 DO 块遍历 tenant schema,可重复执行(无匹配即 0 行)', () => {
expect(sql).toMatch(/DO \$\$/);
expect(sql).toContain("schema_name LIKE 'tenant\\_%'");
expect(sql).toContain("schema_name <> 'tenant_template'");
});
});
@@ -0,0 +1,35 @@
import { readFileSync } from 'node:fs';
import path from 'node:path';
import { describe, expect, it } from 'vitest';
/**
* 20261072 金额回填契约:after_sales.amount 只补主系统退回、且金额为空/0 的售后单;
* 金额 = Σ(退回 quantity × 本地 order_items 最早一行 price);无匹配/价格 0 跳过;可重复执行。
*/
const sql = readFileSync(
path.join(__dirname, '..', '..', 'migrations', '20261072_after_sales_main_return_amount_backfill.sql'),
'utf8'
);
describe('20261072 售后金额回填', () => {
it('只补主系统退回、amount 为空/0 的行', () => {
expect(sql).toContain('UPDATE %1$I.after_sales a');
expect(sql).toContain("a.aftersale_type = 'main_system_return'");
expect(sql).toMatch(/a\.amount IS NULL OR a\.amount = 0/);
});
it('按 main_system 退回行 × 本地最早 order_items.price 求和', () => {
expect(sql).toContain("r.source = 'main_system'");
expect(sql).toContain('r.quantity * oi.price');
expect(sql).toMatch(/ORDER BY oi\.created_at ASC, oi\.id ASC/);
expect(sql).toContain('ROUND(SUM(r.quantity * oi.price)::numeric, 2)');
expect(sql).toContain('oi.price > 0');
});
it('带 FORCE RLS 上下文,且可重复执行(第二次只补 amount 为空的行)', () => {
expect(sql).toMatch(/set_config\('app\.branch_code'/);
expect(sql).toContain('set_config(\'search_path\'');
expect(sql).toMatch(/DO \$\$/);
expect(sql).toContain("schema_name LIKE 'tenant\\_%'");
});
});
+75
View File
@@ -0,0 +1,75 @@
import express from 'express';
import request from 'supertest';
import { beforeEach, describe, expect, it, vi } from 'vitest';
const poolQuery = vi.hoisted(() => vi.fn());
const tenantCtx = vi.hoisted(() => vi.fn());
vi.mock('../src/db', () => ({ pool: { query: poolQuery } }));
vi.mock('../src/services/tenantDbContext', () => ({
runWithTenantDbContext: (branch: string, fn: () => Promise<unknown>) => tenantCtx(branch, fn),
}));
import publicOrderOriginRoutes from '../src/routes/publicOrderOrigin';
function app() {
const instance = express();
instance.use('/api/public', publicOrderOriginRoutes);
return instance;
}
beforeEach(() => {
poolQuery.mockReset();
tenantCtx.mockReset();
tenantCtx.mockImplementation(async (_branch: string, fn: () => Promise<unknown>) => fn());
poolQuery.mockImplementation(async (sql: unknown) => {
const text = String(sql);
if (text.includes('main_system_order_import_items')) {
return {
rows: [
{ branch_code: 'BR002', our_order_code: 'ORD_API_20261020_BR002_0004', item_name: '瘦肉' },
],
};
}
if (text.includes('main_system_sku_mappings')) return { rows: [] };
if (text.includes('FROM "tenant_br002".picking_items') && text.includes('item_name')) {
return { rows: [{ sku_code: 'SKU04114073410' }] };
}
if (text.includes('FROM "tenant_br002".picking_items')) {
return { rows: [{ outbound_batches: [{ batch_no: 'STK20261020JZ2ZOW' }] }] };
}
if (text.includes('FROM "tenant_br002".inventory')) {
return { rows: [{ origin: null }] };
}
if (text.includes('FROM "tenant_br002".skus')) {
return { rows: [{ origin: '成都农贸菜市场' }] };
}
if (text.includes('information_schema.schemata')) return { rows: [] };
return { rows: [] };
});
});
describe('公开产地接口:主订单号 → 供应商订单/SKU 映射', () => {
it('映射缺失 active 时按导入行品名兜底,返回供应商商品档案产地', async () => {
const response = await request(app())
.get('/api/public/order-origin')
.query({
main_order_code: 'ORD_WEB_20261020_BR003_0004',
main_sku: 'SKU98644620619',
});
expect(response.status).toBe(200);
expect(response.body).toEqual({ origin: '成都农贸菜市场' });
expect(tenantCtx).toHaveBeenCalledWith('BR002', expect.any(Function));
const sqls = poolQuery.mock.calls.map((call) => String(call[0]));
expect(sqls.some((sql) => sql.includes('main_system_order_import_items'))).toBe(true);
expect(sqls.some((sql) => sql.includes('item_name'))).toBe(true);
});
it('缺参返回 400,且不泄漏订单/SKU', async () => {
const response = await request(app()).get('/api/public/order-origin');
expect(response.status).toBe(400);
expect(response.body).toEqual({ error: 'invalid_request' });
});
});
@@ -60,9 +60,38 @@ describe('退货行残留抵扣清扫', () => {
const sql = String(query.mock.calls[0][0]);
expect(sql).toContain('COALESCE(oi.is_returned, false) = true');
expect(sql).toContain('COALESCE(oi.stock_cover_qty, 0) > 0.000001');
expect(sql).toContain('oi.return_code IS NULL OR oi.return_code NOT LIKE');
expect(sql.startsWith('SELECT')).toBe(true);
});
it('①b 主系统退回行(return_code 以 R 开头)不被清,退货行(OIR_)仍被清', async () => {
const allRows = [
{ id: 'r-row', order_code: 'ORD-1', sku_code: 'SKU-1', return_code: 'R1792492615025W7B2' },
{ id: 'oir-row', order_code: 'ORD-1', sku_code: 'SKU-1', return_code: 'OIR_1' },
{ id: 'null-row', order_code: 'ORD-1', sku_code: 'SKU-1', return_code: null },
];
query.mockImplementation(async (sql: string, params: unknown[] = []) => {
const text = String(sql);
if (text.includes('COALESCE(oi.is_returned, false) = true')) {
// 模拟 DB 的 WHERE:R 开头的退回行被排除,OIR/空码行保留
const selected = allRows.filter((r) => !(r.return_code && r.return_code.startsWith('R')));
return { rows: selected, rowCount: selected.length };
}
if (text.includes('SELECT 1 FROM order_items')) return { rows: [], rowCount: 0 };
if (text.includes("cost_source = 'inventory_cover'")) return { rows: [], rowCount: 1 };
return { rows: [], rowCount: 1 };
});
const res = await sweepReturnedItemsWithCoverResidue('BR003', 10);
expect(res.cleared).toBe(2);
const clearedIds = query.mock.calls
.filter((c) => String(c[0]).includes('UPDATE order_items SET stock_cover_qty'))
.map((c) => String((c[1] as unknown[])[0]));
expect(clearedIds).toContain('oir-row');
expect(clearedIds).toContain('null-row');
expect(clearedIds).not.toContain('r-row');
});
it('② 归零 + 释放预留(释放内部清 FIFO 批次计划与我方指定批次)', async () => {
query
.mockResolvedValueOnce({ rows: [{ id: 'item-1', order_code: 'ORD-1' }], rowCount: 1 })
@@ -0,0 +1,17 @@
import { readFileSync } from 'node:fs';
import { describe, expect, it } from 'vitest';
const query = readFileSync(new URL('../src/services/inventoryQueryService.ts', import.meta.url), 'utf8');
const inbound = readFileSync(new URL('../src/services/stockInboundService.ts', import.meta.url), 'utf8');
describe('库存列表批次报告数与生产日期默认值', () => {
it('batch_report_count 必须是真实 COUNT,不能用 EXISTS(count(*))(恒为 1 的假“存在报告”)', () => {
expect(query).toContain('SELECT count(*)::int FROM inventory_batch_report_matches m WHERE m.inventory_id = inv.id');
expect(query).not.toMatch(/EXISTS\s*\(\s*SELECT count\(\*\)::int FROM inventory_batch_report_matches/);
});
it('库存入库未填生产日期时必须保持 NULL,不默认当日', () => {
expect(inbound).not.toContain("COALESCE($6::date, (NOW() AT TIME ZONE 'Asia/Shanghai')::date)");
expect(inbound).toContain('$6::date');
});
});