feat(抵扣批次): 列表「库存抵扣:…」点开看已抵扣批次明细(几号入库/生产日期/保质期/区域/抵扣多少)
开发者:「还有将已经被抵扣的批次展示出来呀 —— 几号入库的、生产日期、保质期、区域、 抵扣了多少都需要展示的」。展示面当轮确认:订单列表那行点开弹窗。 - 新增只读接口 GET /orders/:orderCode/stock-cover-batches(鉴权 + 委派,路由零 SQL), 权限与 batch-reports/quality-report-files 同一套 - 批次来源①事实:picking_items.outbound_batches(抵扣写的 FIFO 计划 / 分拣选的批次) → source=plan;②无计划时按先进先出现算(ORDER BY created_at ASC, expiry_date ASC NULLS FIRST, 与 stockCoverBatchPlanService.loadFifoBatches 逐字一致,有源码级守卫)→ source=fifo - 字段:批次号 / 抵扣数量 / 入库日期 / 生产日期 / 保质期效期 / 区域;只列已抵扣且未退货的行; 批次元数据从 inventory 现查(同一 batch_no 跨 SKU 重名 ⇒ 键带 sku_code) - 前端:新弹窗 OrderStockCoverBatchesModal(加载/失败/空态齐、generation+订单号丢弃过期响应); 列表那行有权限才可点且 stopPropagation(否则连带打开详情),无权限退回原文字 - 不新增界面文案:标题与字段标签全部复用既有词条(orders.list.inventoryOffset / inventory.inboundDate / inventory.col.prodDate / inventory.col.expiry / picking.batch.noZone 等), 有契约测试逐键校验三语存在、且弹窗代码无硬编码中文 - 真库实测:纯抵扣单 ORD_API_20261013_BR003_0001 抄手皮×8 → STK202610118WEOS7 (入库 2026-10-11 · 生产 2026-10-08 · 效期 2026-10-15 · 冷库A)source=fifo; 有计划单 ORD_API_20261012_BR003_0002 三行 source=plan,批次/数量与库里逐字一致 - 设计文档:docs/design/20261013-订单抵扣批次明细.md
This commit is contained in:
@@ -1223,6 +1223,38 @@ router.get('/orders/:orderCode/batch-reports', authMiddleware, async (req: AuthR
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* 「这一单已经抵扣了哪些批次」(2026-10-13 开发者要求:列表那行「库存抵扣:…」点开看
|
||||
* 几号入库/生产日期/保质期/区域/抵扣了多少)。
|
||||
*
|
||||
* 只读接口:批次事实 = `picking_items.outbound_batches`;没有计划时按先进先出算给前端看
|
||||
* (`source: 'plan' | 'fifo'`)。权限与 `quality-report-files` / `batch-reports` 同一套,
|
||||
* 路由内不写 SQL(一律委派服务层)。
|
||||
*/
|
||||
router.get('/orders/:orderCode/stock-cover-batches', authMiddleware, async (req: AuthRequest, res: Response) => {
|
||||
try {
|
||||
const ctx = await getWorkflowCtx(req);
|
||||
requireWorkflowPermission(ctx, [
|
||||
'order_manage',
|
||||
'order_entry',
|
||||
'order_status_update',
|
||||
'allocation_manage',
|
||||
]);
|
||||
const orderCode = String(req.params.orderCode || '').trim();
|
||||
await assertOrderCodeAccess(orderCode, ctx!);
|
||||
const { listStockCoverBatches } = await import(
|
||||
'../../../services/stockCoverBatchQueryService'
|
||||
);
|
||||
const data = await listStockCoverBatches({ orderCode, branchCode: ctx?.branchCode || null });
|
||||
return res.json({ data });
|
||||
} catch (error: any) {
|
||||
return res.status(error?.status || 500).json({
|
||||
error: error?.code || 'server_error',
|
||||
error_description: error?.message || '读取抵扣批次失败',
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
router.get('/orders/:orderCode/status', authMiddleware, async (req: AuthRequest, res: Response) => {
|
||||
try {
|
||||
const ctx = await getWorkflowCtx(req);
|
||||
|
||||
@@ -0,0 +1,241 @@
|
||||
/**
|
||||
* 「这一单**已经抵扣了哪些批次**」只读查询(2026-10-13 开发者立项)。
|
||||
*
|
||||
* 开发者原话:「还有将已经被抵扣的批次展示出来呀 —— 几号入库的、生产日期、保质期、区域、
|
||||
* 抵扣了多少都需要展示的」。展示面:**订单列表那行「库存抵扣:…」点开弹窗**。
|
||||
*
|
||||
* 口径(两个来源,**优先事实、兜底口径**):
|
||||
* ① **已落库的批次事实**:`picking_items.outbound_batches`
|
||||
* (抵扣时由 `stockCoverBatchPlanService` 写的 FIFO 计划,或分拣操作员自己选的批次);
|
||||
* ② **没有计划时按先进先出算给你看**(纯只读,不写任何表):与抵扣/出库**同一套 FIFO 口径**
|
||||
* —— `ORDER BY created_at ASC, expiry_date ASC NULLS FIRST`(先入库先出,见
|
||||
* `docs/design/20261012-库存抵扣按先进先出记批次.md`)。纯抵扣单(没有分拣环节)走这条。
|
||||
* 响应里 `source` 区分二者(`plan` / `fifo`),前端不额外造词。
|
||||
*
|
||||
* ⚠️ **只读**:本模块不扣库、不写计划、不写流水、不推主系统;批次元数据从 `inventory` 现查。
|
||||
* ⚠️ FIFO 顺序**必须与 `stockCoverBatchPlanService.loadFifoBatches` 逐字一致**(两处漂移会让
|
||||
* 「显示要扣的批次」与「实际记的批次」对不上)—— 有源码级守卫
|
||||
* `server/tests/stockCoverBatchQuery.test.ts` 钉住两处的 ORDER BY。
|
||||
*/
|
||||
import { pool } from '../db';
|
||||
import { runWithTenantDbContext } from './tenantDbContext';
|
||||
|
||||
type Db = { query: typeof pool.query };
|
||||
|
||||
const round3 = (n: number) => Math.round(n * 1000) / 1000;
|
||||
|
||||
/** 与 `pickingService.toDateOnlyLocal` 同口径:按**本地日**输出 YYYY-MM-DD */
|
||||
function toDateOnlyLocal(v: unknown): string | null {
|
||||
if (v == null) return null;
|
||||
const d = v instanceof Date ? v : new Date(String(v));
|
||||
if (Number.isNaN(d.getTime())) return null;
|
||||
const y = d.getFullYear();
|
||||
const m = String(d.getMonth() + 1).padStart(2, '0');
|
||||
const day = String(d.getDate()).padStart(2, '0');
|
||||
return `${y}-${m}-${day}`;
|
||||
}
|
||||
|
||||
export type StockCoverBatchLine = {
|
||||
batch_no: string;
|
||||
/** 本行从该批次抵扣的数量 */
|
||||
qty: number;
|
||||
/** **入库日期**(`inventory.created_at` 本地日)——「几号入库的」 */
|
||||
inbound_date: string | null;
|
||||
production_date: string | null;
|
||||
expiry_date: string | null;
|
||||
storage_zone: string | null;
|
||||
};
|
||||
|
||||
export type StockCoverBatchItem = {
|
||||
order_item_id: string;
|
||||
item_name: string | null;
|
||||
sku_code: string | null;
|
||||
unit: string | null;
|
||||
/** 该行已抵扣数量(`order_items.stock_cover_qty`) */
|
||||
cover_qty: number;
|
||||
/** `plan` = 库里已有批次事实;`fifo` = 无计划,按先进先出算的(只读预估) */
|
||||
source: 'plan' | 'fifo';
|
||||
batches: StockCoverBatchLine[];
|
||||
};
|
||||
|
||||
/** 已落库的批次条目(`{batch_no, qty, source?}`)→ 只留批次号与数量,防御脏 JSON */
|
||||
function normalizePlannedBatches(raw: unknown): Array<{ batch_no: string; qty: number }> {
|
||||
if (!Array.isArray(raw)) return [];
|
||||
const out: Array<{ batch_no: string; qty: number }> = [];
|
||||
for (const entry of raw) {
|
||||
if (!entry || typeof entry !== 'object') continue;
|
||||
const row = entry as { batch_no?: unknown; qty?: unknown };
|
||||
const batchNo = String(row.batch_no ?? '').trim();
|
||||
const qty = Number(row.qty) || 0;
|
||||
if (!batchNo || qty <= 1e-9) continue;
|
||||
out.push({ batch_no: batchNo, qty: round3(qty) });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** 与抵扣/出库同口径的 FIFO 候选(只读、不加锁) */
|
||||
async function loadFifoBatches(
|
||||
db: Db,
|
||||
skuCode: string,
|
||||
branchCode: string | null
|
||||
): Promise<Array<{ batch_no: string; available_qty: number }>> {
|
||||
const result = await db.query(
|
||||
`SELECT batch_no, available_qty::float AS available_qty
|
||||
FROM inventory
|
||||
WHERE sku_code = $1
|
||||
AND available_qty > 0
|
||||
AND ($2::text IS NULL OR branch_code IS NOT DISTINCT FROM $2)
|
||||
ORDER BY created_at ASC, expiry_date ASC NULLS FIRST`,
|
||||
[skuCode, branchCode]
|
||||
);
|
||||
return (result.rows as Array<{ batch_no: string; available_qty: number }>).filter(
|
||||
(row) => String(row.batch_no || '').trim() !== ''
|
||||
);
|
||||
}
|
||||
|
||||
/** 按 FIFO 顺序分配到 `qty` 为止(不够就分到没有为止,与 `allocateFifo` 同算法) */
|
||||
function allocateFifo(
|
||||
batches: Array<{ batch_no: string; available_qty: number }>,
|
||||
qty: number
|
||||
): Array<{ batch_no: string; qty: number }> {
|
||||
const out: Array<{ batch_no: string; qty: number }> = [];
|
||||
let remaining = Number(qty) || 0;
|
||||
for (const batch of batches) {
|
||||
if (remaining <= 1e-9) break;
|
||||
const take = Math.min(remaining, Number(batch.available_qty) || 0);
|
||||
if (take <= 1e-9) continue;
|
||||
out.push({ batch_no: String(batch.batch_no), qty: round3(take) });
|
||||
remaining = round3(remaining - take);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* 某订单「已抵扣行 × 批次 × 数量」+ 批次元数据(入库日期 / 生产日期 / 效期 / 区域)。
|
||||
* 只列**已抵扣且未退货**的行;没有批次可分(库存已空且无计划)的行照样返回(`batches: []`),
|
||||
* 让前端能说清"这行没有批次",而不是整行消失。
|
||||
*/
|
||||
export async function listStockCoverBatches(params: {
|
||||
orderCode: string;
|
||||
branchCode?: string | null;
|
||||
}): Promise<{ items: StockCoverBatchItem[] }> {
|
||||
const orderCode = String(params.orderCode || '').trim();
|
||||
const branch = String(params.branchCode || '').trim() || null;
|
||||
if (!orderCode) return { items: [] };
|
||||
|
||||
const load = async (): Promise<{ items: StockCoverBatchItem[] }> => {
|
||||
const covered = await pool.query(
|
||||
`SELECT id::text AS id, item_name, sku_code, unit,
|
||||
COALESCE(stock_cover_qty, 0)::float AS cover_qty
|
||||
FROM order_items
|
||||
WHERE order_code = $1
|
||||
AND COALESCE(stock_cover_qty, 0) > 0.000001
|
||||
-- 退货行不再出库 ⇒ 不展示它的批次(与计划/推送侧同一门)
|
||||
AND COALESCE(is_returned, false) = false
|
||||
ORDER BY sort_order ASC NULLS LAST, id ASC`,
|
||||
[orderCode]
|
||||
);
|
||||
if (!covered.rowCount) return { items: [] };
|
||||
|
||||
const planRows = await pool.query(
|
||||
`SELECT pi.order_item_id::text AS item_id, pi.outbound_batches
|
||||
FROM picking_items pi
|
||||
JOIN order_items oi ON oi.id = pi.order_item_id
|
||||
WHERE oi.order_code = $1`,
|
||||
[orderCode]
|
||||
);
|
||||
const planByItem = new Map<string, unknown>();
|
||||
for (const row of planRows.rows as Array<{ item_id: string; outbound_batches: unknown }>) {
|
||||
planByItem.set(String(row.item_id), row.outbound_batches);
|
||||
}
|
||||
|
||||
const items: StockCoverBatchItem[] = [];
|
||||
for (const row of covered.rows as Array<{
|
||||
id: string;
|
||||
item_name: string | null;
|
||||
sku_code: string | null;
|
||||
unit: string | null;
|
||||
cover_qty: number;
|
||||
}>) {
|
||||
const itemId = String(row.id);
|
||||
const skuCode = String(row.sku_code || '').trim();
|
||||
const coverQty = Number(row.cover_qty) || 0;
|
||||
const planned = normalizePlannedBatches(planByItem.get(itemId));
|
||||
let batches: Array<{ batch_no: string; qty: number }> = [];
|
||||
let source: 'plan' | 'fifo' = 'plan';
|
||||
if (planned.length) {
|
||||
batches = planned;
|
||||
} else {
|
||||
source = 'fifo';
|
||||
if (skuCode) {
|
||||
batches = allocateFifo(await loadFifoBatches(pool as unknown as Db, skuCode, branch), coverQty);
|
||||
}
|
||||
}
|
||||
items.push({
|
||||
order_item_id: itemId,
|
||||
item_name: row.item_name == null ? null : String(row.item_name),
|
||||
sku_code: skuCode || null,
|
||||
unit: row.unit == null ? null : String(row.unit),
|
||||
cover_qty: round3(coverQty),
|
||||
source,
|
||||
batches: batches.map((b) => ({
|
||||
batch_no: b.batch_no,
|
||||
qty: b.qty,
|
||||
inbound_date: null,
|
||||
production_date: null,
|
||||
expiry_date: null,
|
||||
storage_zone: null,
|
||||
})),
|
||||
});
|
||||
}
|
||||
|
||||
/** 批次元数据一次性取回(同一个 batch_no 在不同 SKU 下可能重名 ⇒ 键必须带 sku_code) */
|
||||
const skus = [...new Set(items.map((i) => i.sku_code).filter((v): v is string => Boolean(v)))];
|
||||
const batchNos = [...new Set(items.flatMap((i) => i.batches.map((b) => b.batch_no)))];
|
||||
const meta = new Map<
|
||||
string,
|
||||
{ created_at: unknown; production_date: unknown; expiry_date: unknown; storage_zone: unknown }
|
||||
>();
|
||||
if (skus.length && batchNos.length) {
|
||||
const inv = await pool.query(
|
||||
`SELECT DISTINCT ON (sku_code, batch_no)
|
||||
sku_code, batch_no, created_at, production_date, expiry_date, storage_zone
|
||||
FROM inventory
|
||||
WHERE sku_code = ANY($1::text[])
|
||||
AND batch_no = ANY($2::text[])
|
||||
AND ($3::text IS NULL OR branch_code IS NOT DISTINCT FROM $3)
|
||||
ORDER BY sku_code, batch_no, created_at ASC`,
|
||||
[skus, batchNos, branch]
|
||||
);
|
||||
for (const row of inv.rows as Array<{
|
||||
sku_code: string;
|
||||
batch_no: string;
|
||||
created_at: unknown;
|
||||
production_date: unknown;
|
||||
expiry_date: unknown;
|
||||
storage_zone: unknown;
|
||||
}>) {
|
||||
meta.set(`${row.sku_code}|${row.batch_no}`, row);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
items: items.map((item) => ({
|
||||
...item,
|
||||
batches: item.batches.map((batch) => {
|
||||
const m = meta.get(`${item.sku_code}|${batch.batch_no}`);
|
||||
return {
|
||||
batch_no: batch.batch_no,
|
||||
qty: batch.qty,
|
||||
inbound_date: m ? toDateOnlyLocal(m.created_at) : null,
|
||||
production_date: m ? toDateOnlyLocal(m.production_date) : null,
|
||||
expiry_date: m ? toDateOnlyLocal(m.expiry_date) : null,
|
||||
storage_zone: m?.storage_zone == null ? null : String(m.storage_zone),
|
||||
};
|
||||
}),
|
||||
})),
|
||||
};
|
||||
};
|
||||
|
||||
return branch ? runWithTenantDbContext(branch, load) : load();
|
||||
}
|
||||
Reference in New Issue
Block a user