Files
SupplierSystem/server/src/services/missingPurchaseCostBackfill.ts
T
Ubuntu bf94aa0a1f
CI / server typecheck + tests (push) Canceled after 0s
CI / web typecheck + tests + miniprogram syntax (push) Canceled after 0s
CI / eslint (观察项,C7 骨架) (push) Canceled after 0s
CI / npm audit (critical 硬拦) (push) Canceled after 0s
feat(订单成本口径): C 块 —— 供应商第三个分类「库存抵扣」(写入点+8处归零+第三张表+全域非厂商守卫)
开发者 2026-10-14:「开始做 C 块;文案你自己编写;布局自行调整」,并确认
「独立进货就是一个客户、这个客户就是他自己、相当于补充库存」、
「订单管理列表就可以不用隐藏独立进货单了」(后者本轮未动)。
设计文 docs/design/20261014-订单成本排除独立进货与库存成本分类.md §6.1(本轮新增)。

## 取值与写入
- 新增 `STOCK_COVER_SUPPLIER_CODE='STOCK_COVER'` / 名称「库存抵扣」(服务端 + 前端 allocationRules 同名常量)。
- `applyStockCoverForOrderItem`(唯一把 stock_cover_qty 写大的入口)在**同一条 UPDATE**里维护标记:
  全额抵扣 ⇒ `supplier_code='STOCK_COVER'`;部分抵扣 ⇒ **不动**(缺口仍要厂商/自采,§5.1);
  释放/归零且原标记是 STOCK_COVER ⇒ 回退 `UNASSIGNED`。片段 `STOCK_COVER_SUPPLIER_SQL` 与
  **8 处归零点**共用(本文件 7 处 + inventoryReservationReplenishService 1 处),漏一处即留脏标记。

## 商品成本第三张表(页面 + 导出)
- 分桶取「或」:写入点打的标记 **或** 全额抵扣事实(`stock_cover_qty >= quantity`),且要求 `stock_cover_qty > 0`
  ⇒ **历史全额抵扣行无需回填**即进第三桶;释放后残留标记落自采表。
- `SkuCostSourceFilter` / 路由 / 列表与导出两个接口都放行 `stock_cover`;第三张表 `xl:grid-cols-3`、
  标题「库存抵扣」、表头「库存成本合计 ¥x · n 个商品」(该表采购成本恒 0)。
- 订单详情供应商下拉新增第三项「库存抵扣」;订单列表/订单导出/打印供货清单都不再出现裸码或空白。

## 全域「非厂商」守卫(R1 排查,新增 hasRealSupplierCode + NON_VENDOR_SUPPLIER_SQL_LIST)
- 会**静默造脏数据/抹掉标记**的三处最要命:`orderAllocationService` 结果落库安全网与 pending 过滤、
  `purchaseSupplierAssignService` 转供应商黑名单(原本不传 supplier_code 会静默建 STOCK_COVER 备货)、
  `orderManageItemsService` 加菜裸 INSERT 备货与 `isAssignedExternalSupplier`(否则保存会取消在途自采+删分拣行)。
- 其余 A 清单:竞价 `isRealBidSupplier` + 回写额外再挡一次、结算/应付×3、成本来源标签、退货红冲、
  验收单/再归属、备货成本回填、待备货/采购列表、商品指定供应商(后端拒 + 前端候选滤)。
- **B 类一行不动**(`isUnassignedSupplier` 系列):对"是否还要再分配"而言「已有供应商」就是对的。

## 实测(真库 BR002/BR003,服务函数直调,见 §6.1.5)
| 分支/周期 | 供应采购 | 自采采购 | 库存抵扣 |
| BR002 202610 | 0 行 ¥0 | 0 行 ¥0 | **3 行 / ¥137** |
| BR002 MOBILE | 0 行 ¥0 | 6 行 / ¥187 | **3 行 / ¥54** |
| BR003 MOBILE | 0 行 ¥0 | 4 行 / ¥61.8 | **8 行 / ¥942.2** |
三张表行数 = 表头合计,逐项对账相等;导出按来源筛同样落第三桶。
标记 SQL 语义在真库事务内验证并 ROLLBACK:全额→STOCK_COVER;部分(原标记)→UNASSIGNED;
部分(原厂商)→不动;释放归零→UNASSIGNED。

## 回归
- 后端 25 failed / 407 passed(干净 HEAD 890c055 为 27/396)⇒ **无新增失败**,另 2 个文件转好;
- 前端 2 failed / 163 passed(与基线同集合:SystemConfig.allowZeroCost、PickingManagement.outboundPhotoPreview);
- `tsc --noEmit`(前端)与 `tsc --noEmit -p server/tsconfig.json --module esnext` 均 0 错;
- 门禁 8 通过 / 1 已知红(check-ai-cost) / 1 未执行(verify-facts)。

## 未做(需裁决,见 §8 D 组)
D1 实时采购成本分桶(财务冻结)、D2 发车/入库照 skip_inbound(配送冻结)、
D3 改派真厂商的取消在途(分拣冻结)、D4 退货改派批次对齐、D5 小程序订单详情同改。
2026-10-14 17:32:29 +08:00

162 lines
6.7 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { pool } from '../db';
import type { PoolClient } from 'pg';
// 「非厂商」取值列表(含库存抵扣 STOCK_COVER):幽灵厂商备货不得当采购成本回填依据
import { NON_VENDOR_SUPPLIER_SQL_LIST } from './allocationRules';
type Db = Pick<PoolClient, 'query'>;
/**
* 备货已完成但采购账本缺行 的补写(存量漏账 + 结案兜底)。
*
* 背景:2026-08-31 ~ 09-10 22:00 的线上构建里,备货「确认完成」大面积为 0 写入采购账本,
* 241 行 / 38,422.98 元;链路本身有 4 处静默 return,且失败被 SAVEPOINT 软跳过、路由不返回 failures。
* 见 docs/design/20260911-backfill-missing-prep-purchase-cost.md。
*
* 口径:每 order_item 一行 `purchase/order_goods/unit_cost_sync`,
* amount = order_items.quantity × supplier_preparations.purchase_price
* (与备货完成时本应写入的公式一致;结案后 order_items.quantity 即实拣量)。
*/
export interface PrepCostGapRow {
order_item_id: string;
order_code: string;
sku_code: string;
item_name: string | null;
unit: string | null;
quantity: number;
purchase_price: number;
prepare_qty: number;
amount: number;
cycle_code: string | null;
branch_code: string | null;
prepare_time: string | null;
}
export interface PrepCostGapOptions {
/** 只处理该订单 */
orderCode?: string | null;
/** 备货完成时间下界(含),ISO/带时区字符串 */
since?: string | null;
/** 备货完成时间上界(不含) */
until?: string | null;
limit?: number | null;
}
function gapSql(opts: PrepCostGapOptions, params: unknown[]): string {
const conds: string[] = [];
if (opts.orderCode) {
params.push(String(opts.orderCode).trim());
conds.push(`oi.order_code = $${params.length}`);
}
if (opts.since) {
params.push(String(opts.since));
conds.push(`sp.prepare_time >= $${params.length}::timestamptz`);
}
if (opts.until) {
params.push(String(opts.until));
conds.push(`sp.prepare_time < $${params.length}::timestamptz`);
}
const limit = Number(opts.limit);
const limitSql = Number.isFinite(limit) && limit > 0 ? `LIMIT ${Math.floor(limit)}` : '';
return `SELECT oi.id::text AS order_item_id,
oi.order_code,
oi.sku_code,
oi.item_name,
oi.unit,
COALESCE(oi.quantity, 0)::numeric AS quantity,
COALESCE(sp.purchase_price, 0)::numeric AS purchase_price,
COALESCE(sp.prepare_qty, 0)::numeric AS prepare_qty,
ROUND((COALESCE(oi.quantity, 0) * COALESCE(sp.purchase_price, 0))::numeric, 2) AS amount,
o.cycle_code,
COALESCE(oi.branch_code, o.branch_code) AS branch_code,
sp.prepare_time::text AS prepare_time
FROM order_items oi
JOIN orders o ON o.order_code = oi.order_code AND o.deleted_at IS NULL
JOIN supplier_preparations sp
ON sp.order_code = oi.order_code AND sp.sku_code = oi.sku_code
WHERE COALESCE(oi.is_returned, false) = false
AND COALESCE(oi.is_extra_dish, false) = false
AND COALESCE(oi.quantity, 0) > 0
AND COALESCE(sp.prepare_status, 10) >= 30
AND COALESCE(sp.is_stockout, false) = false
AND COALESCE(sp.transferred_to_purchase, false) = false
AND COALESCE(sp.purchase_price, 0) > 0
AND NULLIF(TRIM(COALESCE(sp.supplier_code, '')), '') IS NOT NULL
AND UPPER(TRIM(COALESCE(sp.supplier_code, ''))) NOT IN ${NON_VENDOR_SUPPLIER_SQL_LIST}
-- 缺账本:该 order+sku 无任何采购行
AND NOT EXISTS (
SELECT 1 FROM cost_details cd
WHERE cd.order_code = oi.order_code
AND cd.sku_code IS NOT DISTINCT FROM oi.sku_code
AND cd.cost_type IN ('purchase', 'purchase_applied')
)
-- 未走验收入账(有验收则由验收/结算链路负责,不在此补)
AND NOT EXISTS (
SELECT 1 FROM inspections i
WHERE i.order_code = oi.order_code AND i.sku_code = oi.sku_code
)
${conds.length ? 'AND ' + conds.join(' AND ') : ''}
ORDER BY oi.order_code, oi.sort_order NULLS LAST, oi.id
${limitSql}`;
}
/** 只读:列出缺账本的备货行 */
export async function listMissingPrepPurchaseCostGaps(
db: Db = pool,
opts: PrepCostGapOptions = {}
): Promise<PrepCostGapRow[]> {
const params: unknown[] = [];
const result = await db.query(gapSql(opts, params), params);
return result.rows.map((row: Record<string, unknown>) => ({
order_item_id: String(row.order_item_id),
order_code: String(row.order_code),
sku_code: String(row.sku_code ?? ''),
item_name: row.item_name == null ? null : String(row.item_name),
unit: row.unit == null ? null : String(row.unit),
quantity: Number(row.quantity) || 0,
purchase_price: Number(row.purchase_price) || 0,
prepare_qty: Number(row.prepare_qty) || 0,
amount: Number(row.amount) || 0,
cycle_code: row.cycle_code == null ? null : String(row.cycle_code),
branch_code: row.branch_code == null ? null : String(row.branch_code),
prepare_time: row.prepare_time == null ? null : String(row.prepare_time),
}));
}
/**
* 补写缺账本的备货行。
* - 默认只统计(apply=false),不写库;
* - apply=true 逐行 INSERT … ON CONFLICT DO NOTHING,唯一索引兜幂等;
* - 返回实际插入行数与金额,供日志/审计。
*/
export async function backfillMissingPrepPurchaseCosts(
db: Db = pool,
opts: PrepCostGapOptions & { apply?: boolean } = {}
): Promise<{ candidates: number; inserted: number; amount: number; rows: PrepCostGapRow[] }> {
const rows = await listMissingPrepPurchaseCostGaps(db, opts);
const amount = Math.round(rows.reduce((sum, r) => sum + r.amount, 0) * 100) / 100;
if (!opts.apply) {
return { candidates: rows.length, inserted: 0, amount, rows };
}
let inserted = 0;
for (const row of rows) {
if (!(row.amount > 0)) continue;
const result = await db.query(
`INSERT INTO cost_details (
cycle_code, cost_type, cost_subtype, amount, order_code, sku_code,
allocation_method, allocated_amount, status, branch_code, cost_source,
reference_type, reference_id, order_item_id, remark
) VALUES (
$1, 'purchase', 'order_goods', $2, $3, $4,
'sku', $2, 20, $5, 'supplier',
'order_item', $6::text, $6::uuid, 'unit_cost_sync'
)
ON CONFLICT DO NOTHING
RETURNING id`,
[row.cycle_code, row.amount, row.order_code, row.sku_code, row.branch_code, row.order_item_id]
);
inserted += result.rowCount || 0;
}
return { candidates: rows.length, inserted, amount, rows };
}