开发者报障:订单 ORD_WEB_20261014_BR002_0004 行内「抵扣」小字显示 抄手皮 5.63、精瘦肉 6.00、
苹果 4.03,而被抵扣批次成本价明明是 ¥3.00。
根因(两处,同一根因:**一个字段被赋予两种语义**):
1. `picking_items.outbound_batches` 原本只装「抵扣时写的 FIFO 计划」(stockCoverBatchPlanService:230),
分拣保存后被覆盖成**整行出库批次** = 抵扣批次 + 缺口自采/备货批次
(本单 8+7 / 15+15 / 30+10)。「抵扣批次」查询仍按旧语义取值(source='plan')
⇒ 缺口批次混进抵扣批次,违反设计 20261013-订单抵扣批次明细.md §5 取舍 2
("真实出库流水的批次不并进来")。
2. 前端用 `Σ(批次量×批次价) ÷ 抵扣量` 现算抵扣单价 ⇒ 被放大 `整行 ÷ 抵扣量` 倍:
45/8=5.63、90/15=6.00、121/30=4.03;真值都是 3.00。
改法(开发者 2026-10-14「一起」批准 1+2+3):
1. 服务按 `cover_qty` **截断**抵扣批次(新增纯函数 splitBatchesByCoverQty),
超出部分走新字段 `gap_batches` / `gap_qty`;
2. 抵扣**成本额改读账本**:新字段 `cover_cost_amount` = cost_details(cost_source='inventory_cover')
结转额(与成本页/C 块/改批次成本重算同源);前端优先用它,批次求和只作兜底;
3. 弹窗把这些缺口批次**单列一行**:新文案 orders.coverBatch.gapHint
「另有缺口批次(自采/备货){qty}{unit}」(三语同提交,文案按开发者原话,未加尾注)。
顺带修正:
- `settled` / `frozen_cover_cost` 两字段**从未被赋值**(前端那段是死代码)⇒ 标注 deprecated:
已结算订单的账本本就不会被改价重算(applyBatchCostChange 跳过该单),天然冻结;
- 弹窗契约测试②的判据本身写错(拿剥掉命名空间前缀的 'coverBatch.editCost' 去比,
而三语文件存的是全键 'orders.coverBatch.editCost')⇒ 该断言恒假、长期空红;改为先比全键。
验收(BR002 ORD_API_20261014_BR002_0001,本地库 + 真实数据):
- 抵扣批次:抄手皮 8斤@¥3 / 瘦肉 15斤@¥3 / 苹果 30斤@¥3(不再是 8+7 / 15+15 / 30+10)
- 抵扣成本额(账本):24 / 45 / 90 ⇒ 单价 **3.00 / 3.00 / 3.00**(改前 5.63 / 6.00 / 4.03)
- 缺口批次单列:7 / 15 / 10 斤(苹果缺口 ¥3.1 正确显示)
测试:server/tests/stockCoverBatchQuery.test.ts 13→16 例(新增截断/账本额/纯函数三例);
前端 orderManagementHelpers.coverUnitCost.test.ts 增「详情页取账本额」守卫;
弹窗契约测试 9 例全绿(含新键三语齐全)。
回归:后端 0 新增失败(2963 passed / 32 failed);前端 866 passed,剩余失败 3 项均与本轮无关
(PickingManagement.outboundPhotoPreview、SystemConfig.allowZeroCost 为既有;skuCostThirdBucket
由并发会话未提交的 CostAccountingPanel.tsx 引起)。
tsc 前后端各 0 错误;设计门禁 8 通过 / 2 既有红。**零数据变更**(只改取数与展示)。
455 lines
19 KiB
TypeScript
455 lines
19 KiB
TypeScript
/**
|
||
* 「这一单**抵扣了哪些批次**」只读查询 + 可编辑所需的候选批次(2026-10-13 开发者)。
|
||
*
|
||
* 展示面:**订单列表那行「库存抵扣:…」点开弹窗**(开发者当轮选定)。
|
||
* 开发者在同一轮追加:「这个调整出库后就只能是看了不能改;这边如果改了抵扣的批次后,
|
||
* 那么分拣时分拣的批次需要对应得上(当然分拣时分拣员也能改)」。
|
||
*
|
||
* 口径(三来源,**优先级写死**:我方指定 > 抵扣计划/分拣选定 > 先进先出现算):
|
||
* ① `order_items.cover_batches`(我方指定;写入方 `orderItemCoverBatchesService`)→ `source='manual'`
|
||
* ② `picking_items.outbound_batches`(抵扣时的 FIFO 计划 / 分拣员选的批次)→ `source='plan'`
|
||
* ③ 都没有 ⇒ 按**先进先出**现算(只读,不写库)→ `source='fifo'`
|
||
* ⚠️ **已出库**的行(出库流水 / 拣货行 `outbound_at` / 订单 ≥50)以 ②(事实)为准 ——
|
||
* 分拣员现场改过的批次就是最终事实,我方指定不再覆盖显示。
|
||
*
|
||
* ⚠️ **本模块只读**:不扣库、不写计划、不写流水、不推主系统。
|
||
* ⚠️ FIFO 顺序**必须与 `stockCoverBatchPlanService.loadFifoBatches` 逐字一致**(有源码级守卫)。
|
||
*/
|
||
import { pool } from '../db';
|
||
import { runWithTenantDbContext } from './tenantDbContext';
|
||
import {
|
||
loadCoverBatchLockState,
|
||
normalizeCoverBatchEntries,
|
||
} from './orderItemCoverBatchesService';
|
||
|
||
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;
|
||
/** 该批次**当前**可用量(库存后来变了会与抵扣量不同;实际扣库按 min(可用, 指定) 回落 FIFO) */
|
||
available_qty: number | null;
|
||
/**
|
||
* 该批次的**成本价**(`inventory.cost_price`):抵扣部分按被抵扣批次成本价计入订单成本
|
||
* (见 docs/design/20261014-抵扣成本口径(成本随货走+去重).md),界面要能看到抵的是多少钱的货。
|
||
* 批次未设成本价 ⇒ null(界面显示"未设置",不要当 0 展示)。
|
||
*/
|
||
cost_price: number | null;
|
||
};
|
||
|
||
/** 可选的候选批次(编辑时用;与 FIFO 同序) */
|
||
export type StockCoverBatchCandidate = {
|
||
batch_no: string;
|
||
available_qty: number;
|
||
inbound_date: string | null;
|
||
production_date: string | null;
|
||
expiry_date: string | null;
|
||
storage_zone: string | null;
|
||
/** 同 `StockCoverBatchLine.cost_price` */
|
||
cost_price: number | 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;
|
||
/** `manual` = 我方指定;`plan` = 库里的批次事实(抵扣计划/分拣选定);`fifo` = 现算兜底 */
|
||
source: 'manual' | 'plan' | 'fifo';
|
||
/**
|
||
* **只含被抵扣的那部分批次**(数量合计 = `cover_qty`)。
|
||
*
|
||
* ⚠️ 2026-10-14 修复:`picking_items.outbound_batches` 原本只装"抵扣计划",
|
||
* 分拣保存后会写入**整行出库批次**(抵扣批次 + 缺口自采/备货批次)⇒ 直接拿它当"抵扣批次"
|
||
* 会把缺口批次也算进去,界面「抵扣 ¥X」被放大 `整行数量 ÷ 抵扣量` 倍
|
||
* (实测 BR002:抄手皮 45/8=5.63、瘦肉 90/15=6.00、苹果 121/30=4.03,真值都是 3.00)。
|
||
* 本函数现在按 `cover_qty` 截断,`gap_batches` 另行返回(见下)。
|
||
*/
|
||
batches: StockCoverBatchLine[];
|
||
/**
|
||
* **抵扣成本额(账本权威)** = `cost_details(cost_source='inventory_cover')` 的结转额。
|
||
* 前端「抵扣 ¥X」与成本页/C 块同源;不再由批次列表现算。
|
||
* `null` = 该(订单×SKU)没有抵扣账本行。
|
||
*/
|
||
cover_cost_amount: number | null;
|
||
/** 整行出库批次里**超出抵扣量**的部分(缺口:自采/供应商备货入库的那几批) */
|
||
gap_qty: number;
|
||
/** 缺口批次(同 `batches` 的字段结构);缺口为 0 时是空数组 */
|
||
gap_batches: StockCoverBatchLine[];
|
||
/** 已出库(出库流水 / 拣货行已出库 / 订单 ≥50)⇒ 前端只读 */
|
||
read_only: boolean;
|
||
/** `order_departed` | `picking_outbound` | `inventory_outbound` | null */
|
||
read_only_reason: string | null;
|
||
/** 未出库时给候选批次(编辑用);已出库为空数组 */
|
||
candidates: StockCoverBatchCandidate[];
|
||
/**
|
||
* @deprecated 2026-10-14:改为直接读账本 `cover_cost_amount`(已结算订单的账本本就不会被改价重算
|
||
* ⇒ 天然冻结),前端不再需要这条分支;字段保留仅为兼容旧响应。
|
||
*/
|
||
settled?: boolean;
|
||
/** @deprecated 同上;见 {@link StockCoverBatchItem.cover_cost_amount} */
|
||
frozen_cover_cost?: number | null;
|
||
};
|
||
|
||
/** 已落库的批次条目(`{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;
|
||
}
|
||
|
||
/**
|
||
* 把「整行出库批次」按**抵扣量**切成两段(纯函数,可测):
|
||
* · `cover` = 前 `coverQty` 斤(**被抵扣的那几批**,顺序即批次事实顺序)
|
||
* · `gap` = 其余(**缺口那几批**:自采/供应商备货后来入库的)
|
||
*
|
||
* 为什么需要它:分拣保存会把整行出库批次写回 `picking_items.outbound_batches`(抵扣批次 + 缺口批次),
|
||
* 而「库存抵扣批次」这个面只应回答"**抵扣**用了哪些批次"(设计 `20261013-订单抵扣批次明细.md` §5.2:
|
||
* 真实出库流水的批次不并进来)⇒ 必须按抵扣量截断,否则抵扣单价会被放大 `整行 ÷ 抵扣量` 倍。
|
||
*/
|
||
export function splitBatchesByCoverQty(
|
||
batches: Array<{ batch_no: string; qty: number }>,
|
||
coverQty: number
|
||
): {
|
||
cover: Array<{ batch_no: string; qty: number }>;
|
||
gap: Array<{ batch_no: string; qty: number }>;
|
||
gapQty: number;
|
||
} {
|
||
const target = Number(coverQty) || 0;
|
||
const cover: Array<{ batch_no: string; qty: number }> = [];
|
||
const gap: Array<{ batch_no: string; qty: number }> = [];
|
||
let remaining = target;
|
||
for (const batch of batches) {
|
||
const qty = round3(Number(batch.qty) || 0);
|
||
if (qty <= 1e-9) continue;
|
||
if (remaining > 1e-9) {
|
||
const take = Math.min(remaining, qty);
|
||
if (take > 1e-9) cover.push({ batch_no: batch.batch_no, qty: round3(take) });
|
||
remaining = round3(remaining - take);
|
||
const rest = round3(qty - take);
|
||
if (rest > 1e-9) gap.push({ batch_no: batch.batch_no, qty: rest });
|
||
} else {
|
||
gap.push({ batch_no: batch.batch_no, qty });
|
||
}
|
||
}
|
||
return { cover, gap, gapQty: round3(gap.reduce((s, b) => s + b.qty, 0)) };
|
||
}
|
||
|
||
type BatchMeta = {
|
||
created_at: unknown;
|
||
production_date: unknown;
|
||
expiry_date: unknown;
|
||
storage_zone: unknown;
|
||
available_qty: unknown;
|
||
cost_price: unknown;
|
||
};
|
||
|
||
/**
|
||
* 某订单「已抵扣行 × 批次 × 数量」+ 批次元数据(入库日期 / 生产日期 / 效期 / 区域),
|
||
* 以及**是否已出库**(只读)与编辑用的候选批次。
|
||
* 只列**已抵扣且未退货**的行;没有批次可分(库存已空且无指定)的行照常返回(`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 oi.id::text AS id, oi.item_name, oi.sku_code, oi.unit,
|
||
COALESCE(oi.stock_cover_qty, 0)::float AS cover_qty,
|
||
oi.cover_batches,
|
||
COALESCE(o.order_status, 0) AS order_status
|
||
FROM order_items oi
|
||
JOIN orders o ON o.order_code = oi.order_code
|
||
WHERE oi.order_code = $1
|
||
AND COALESCE(oi.stock_cover_qty, 0) > 0.000001
|
||
-- 退货行不再出库 ⇒ 不展示它的批次(与计划/推送侧同一门)
|
||
AND COALESCE(oi.is_returned, false) = false
|
||
ORDER BY oi.sort_order ASC NULLS LAST, oi.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);
|
||
}
|
||
|
||
/**
|
||
* **抵扣成本额(账本权威)**:按 SKU 汇总 `cost_details(cost_source='inventory_cover')`。
|
||
* 前端「抵扣 ¥X」与成本页/C 块/改批次成本重算同源;**不再用批次列表现算**
|
||
* (批次列表分拣后会含缺口批次 ⇒ 现算会把缺口成本算进抵扣)。
|
||
*/
|
||
const ledgerRows = await pool.query(
|
||
`SELECT sku_code, COALESCE(SUM(amount), 0)::numeric AS amount
|
||
FROM cost_details
|
||
WHERE order_code = $1 AND cost_source = 'inventory_cover'
|
||
GROUP BY sku_code`,
|
||
[orderCode]
|
||
);
|
||
const coverCostBySku = new Map<string, number>();
|
||
for (const row of ledgerRows.rows as Array<{ sku_code: string | null; amount: unknown }>) {
|
||
coverCostBySku.set(String(row.sku_code || ''), Number(row.amount) || 0);
|
||
}
|
||
|
||
const items: Array<
|
||
Omit<
|
||
StockCoverBatchItem,
|
||
'batches' | 'candidates' | 'cover_cost_amount' | 'gap_qty' | 'gap_batches'
|
||
> & {
|
||
batches: Array<{ batch_no: string; qty: number }>;
|
||
}
|
||
> = [];
|
||
/** 每行编辑用的候选(未出库才有) */
|
||
const candidatesByItem = new Map<string, Array<{ batch_no: string; available_qty: number }>>();
|
||
/** 兜底数据:我方指定里出现过期批次(换过 SKU / 批次被删)时要能退回计划或 FIFO */
|
||
const fallbackByItem = new Map<
|
||
string,
|
||
{
|
||
planned: Array<{ batch_no: string; qty: number }>;
|
||
fifo: Array<{ batch_no: string; available_qty: number }>;
|
||
coverQty: number;
|
||
locked: boolean;
|
||
}
|
||
>();
|
||
|
||
for (const row of covered.rows as Array<{
|
||
id: string;
|
||
item_name: string | null;
|
||
sku_code: string | null;
|
||
unit: string | null;
|
||
cover_qty: number;
|
||
cover_batches: unknown;
|
||
order_status: number;
|
||
}>) {
|
||
const itemId = String(row.id);
|
||
const skuCode = String(row.sku_code || '').trim();
|
||
const coverQty = Number(row.cover_qty) || 0;
|
||
const manual = normalizeCoverBatchEntries(row.cover_batches);
|
||
const planned = normalizePlannedBatches(planByItem.get(itemId));
|
||
const lock = await loadCoverBatchLockState(pool as unknown as Db, {
|
||
orderCode,
|
||
itemId,
|
||
skuCode: skuCode || null,
|
||
orderStatus: Number(row.order_status) || 0,
|
||
});
|
||
|
||
let batches: Array<{ batch_no: string; qty: number }> = [];
|
||
let source: 'manual' | 'plan' | 'fifo' = 'fifo';
|
||
let fifo: Array<{ batch_no: string; available_qty: number }> = [];
|
||
if (skuCode) {
|
||
fifo = await loadFifoBatches(pool as unknown as Db, skuCode, branch);
|
||
}
|
||
if (lock.locked && planned.length) {
|
||
// 已出库 ⇒ 事实优先(分拣员现场改过的就是最终值)
|
||
batches = planned;
|
||
source = 'plan';
|
||
} else if (manual.length) {
|
||
batches = manual;
|
||
source = 'manual';
|
||
} else if (planned.length) {
|
||
batches = planned;
|
||
source = 'plan';
|
||
} else {
|
||
batches = allocateFifo(fifo, coverQty);
|
||
source = 'fifo';
|
||
}
|
||
if (!lock.locked) candidatesByItem.set(itemId, fifo);
|
||
fallbackByItem.set(itemId, {
|
||
planned,
|
||
fifo,
|
||
coverQty,
|
||
locked: lock.locked,
|
||
});
|
||
|
||
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,
|
||
read_only: lock.locked,
|
||
read_only_reason: lock.reason,
|
||
batches,
|
||
});
|
||
}
|
||
|
||
/** 批次元数据一次性取回(同一个 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)),
|
||
...[...candidatesByItem.values()].flatMap((list) => list.map((b) => b.batch_no)),
|
||
]),
|
||
];
|
||
const meta = new Map<string, BatchMeta>();
|
||
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,
|
||
available_qty, cost_price
|
||
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<BatchMeta & { sku_code: string; batch_no: string }>) {
|
||
meta.set(`${row.sku_code}|${row.batch_no}`, row);
|
||
}
|
||
}
|
||
const lineOf = (skuCode: string | null, batch: { batch_no: string; qty: number }) => {
|
||
const m = meta.get(`${skuCode}|${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),
|
||
available_qty: m?.available_qty == null ? null : Number(m.available_qty) || 0,
|
||
cost_price: m?.cost_price == null ? null : Number(m.cost_price) || 0,
|
||
};
|
||
};
|
||
|
||
return {
|
||
items: items.map((item) => {
|
||
/**
|
||
* 防御:我方指定里若出现**当前 SKU 下已不存在**的批次(改绑过商品 / 批次被删),
|
||
* 该条目不能当真(否则会被带进分拣行并推给主系统)⇒ 丢掉;全丢则退回计划/FIFO。
|
||
* 兜底清扫(15 分钟)会把这种行彻底清掉;这里先保证**界面与对外口径不脏**。
|
||
*/
|
||
let batches = item.batches;
|
||
let source = item.source;
|
||
if (source === 'manual') {
|
||
const healthy = batches.filter((batch) => meta.has(`${item.sku_code}|${batch.batch_no}`));
|
||
if (healthy.length !== batches.length) {
|
||
const fallback = fallbackByItem.get(item.order_item_id);
|
||
if (healthy.length) {
|
||
batches = healthy;
|
||
} else if (fallback?.planned.length) {
|
||
batches = fallback.planned;
|
||
source = 'plan';
|
||
} else if (fallback) {
|
||
batches = fallback.locked
|
||
? []
|
||
: allocateFifo(fallback.fifo, fallback.coverQty);
|
||
source = 'fifo';
|
||
} else {
|
||
batches = [];
|
||
}
|
||
}
|
||
}
|
||
/**
|
||
* ⚠️ 只回**抵扣那部分**(按 `cover_qty` 截断);超出部分是缺口批次(自采/备货入库的那几批),
|
||
* 走 `gap_batches` 单独返回。见 `splitBatchesByCoverQty` 的注释。
|
||
*/
|
||
const split = splitBatchesByCoverQty(batches, item.cover_qty);
|
||
const skuKey = String(item.sku_code || '');
|
||
const ledgerAmount = coverCostBySku.has(skuKey) ? coverCostBySku.get(skuKey)! : null;
|
||
return {
|
||
...item,
|
||
source,
|
||
batches: split.cover.map((batch) => lineOf(item.sku_code, batch)),
|
||
cover_cost_amount: ledgerAmount == null ? null : Math.round(ledgerAmount * 100) / 100,
|
||
gap_qty: split.gapQty,
|
||
gap_batches: split.gap.map((batch) => lineOf(item.sku_code, batch)),
|
||
candidates: (candidatesByItem.get(item.order_item_id) || []).map((candidate) => {
|
||
const m = meta.get(`${item.sku_code}|${candidate.batch_no}`);
|
||
return {
|
||
batch_no: candidate.batch_no,
|
||
available_qty: Number(candidate.available_qty) || 0,
|
||
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),
|
||
cost_price: m?.cost_price == null ? null : Number(m.cost_price) || 0,
|
||
};
|
||
}),
|
||
};
|
||
}),
|
||
};
|
||
};
|
||
|
||
return branch ? runWithTenantDbContext(branch, load) : load();
|
||
}
|