Files
SupplierSystem/server/src/services/orderCostPostingService.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

852 lines
30 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 { hasRealSupplierCode } from './allocationRules';
import type { PoolClient } from 'pg';
import type { TenantContext } from './tenantScope';
export const EXTRA_DISH_COST_SOURCE = 'extra_dish';
export const EXTRA_DISH_COST_SUBTYPE = 'extra_dish';
export const EXTRA_DISH_COST_REMARK_PREFIX = '订单加菜';
function extraDishRemark(orderCode: string): string {
const code = String(orderCode || '').trim();
return code ? `${EXTRA_DISH_COST_REMARK_PREFIX} · ${code}` : EXTRA_DISH_COST_REMARK_PREFIX;
}
function nowCycleCode() {
const d = new Date();
return `${d.getFullYear()}${String(d.getMonth() + 1).padStart(2, '0')}`;
}
type SkuAmountRow = { sku_code: string; amount: number; cost_source: 'supplier' | 'self_purchase' };
/** B2: 备货与自采分别归集,不再互斥 */
async function resolveSkuPurchaseAmounts(orderCode: string): Promise<SkuAmountRow[]> {
const [prep, po] = await Promise.all([
pool.query(
`SELECT sp.sku_code,
ROUND(SUM(COALESCE(sp.prepare_qty, 0) * COALESCE(sp.purchase_price, 0))::numeric, 2) AS amt
FROM supplier_preparations sp
WHERE sp.order_code = $1
AND COALESCE(sp.is_stockout, false) = false
AND COALESCE(sp.transferred_to_purchase, false) = false
AND COALESCE(sp.is_history_repair, false) = false
AND sp.sku_code IS NOT NULL
AND TRIM(sp.sku_code) <> ''
GROUP BY sp.sku_code
HAVING SUM(COALESCE(sp.prepare_qty, 0) * COALESCE(sp.purchase_price, 0)) > 0`,
[orderCode]
),
pool.query(
`SELECT po.sku_code,
ROUND(SUM(COALESCE(po.actual_qty, po.purchase_qty, 0) * COALESCE(po.actual_price, po.purchase_price, 0))::numeric, 2) AS amt
FROM purchase_orders po
WHERE po.order_code = $1
AND po.sku_code IS NOT NULL
AND TRIM(po.sku_code) <> ''
GROUP BY po.sku_code
HAVING SUM(COALESCE(po.actual_qty, po.purchase_qty, 0) * COALESCE(po.actual_price, po.purchase_price, 0)) > 0`,
[orderCode]
),
]);
const rows: SkuAmountRow[] = [];
for (const r of prep.rows) {
rows.push({
sku_code: String(r.sku_code),
amount: Math.round(Number(r.amt || 0) * 100) / 100,
cost_source: 'supplier',
});
}
for (const r of po.rows) {
rows.push({
sku_code: String(r.sku_code),
amount: Math.round(Number(r.amt || 0) * 100) / 100,
cost_source: 'self_purchase',
});
}
return rows;
}
/** 已完成订单:按当前备货/自采数量×单价更新已过账采购行金额(不改公式、不改客户结算) */
export async function resyncPostedPurchaseCostAmounts(orderCode: string): Promise<number> {
const code = String(orderCode || '').trim();
if (!code) return 0;
const status = await pool.query(
`SELECT order_status FROM orders WHERE order_code = $1 AND deleted_at IS NULL LIMIT 1`,
[code]
);
if (Number(status.rows[0]?.order_status) < 90) return 0;
const skuAmounts = await resolveSkuPurchaseAmounts(code);
let updated = 0;
for (const row of skuAmounts) {
const result = await pool.query(
`UPDATE cost_details
SET amount = $4,
allocated_amount = $4
WHERE order_code = $1
AND sku_code = $2
AND cost_type = 'purchase'
AND cost_source IS NOT DISTINCT FROM $3
AND COALESCE(remark, '') IS DISTINCT FROM 'unit_cost_sync'`,
[code, row.sku_code, row.cost_source, row.amount]
);
updated += result.rowCount || 0;
}
return updated;
}
/**
* 待配送起/已完成加菜:按明细成本价写入采购成本账(不建自采)。
* 仅处理无备货/自采挂载的加菜行;按 order_item id 幂等。
*/
export async function reconcileExtraDishPurchaseCosts(
client: PoolClient,
orderCode: string,
opts?: {
branchCode?: string | null;
/** sku → 单价(本次保存明细成本价) */
costBySku?: Map<string, number> | Record<string, number>;
}
): Promise<{ posted: number; amount: number }> {
const code = String(orderCode || '').trim();
if (!code) return { posted: 0, amount: 0 };
const orderMeta = await client.query(
`SELECT cycle_code, branch_code, order_status FROM orders WHERE order_code = $1 LIMIT 1`,
[code]
);
if (!orderMeta.rowCount) return { posted: 0, amount: 0 };
const orderStatus = Number(orderMeta.rows[0].order_status) || 0;
if (orderStatus < 60) return { posted: 0, amount: 0 };
const cycleCode =
String(orderMeta.rows[0]?.cycle_code || '').trim() || nowCycleCode();
const branchCode = opts?.branchCode || orderMeta.rows[0]?.branch_code || null;
const costBySku = new Map<string, number>();
if (opts?.costBySku instanceof Map) {
for (const [k, v] of opts.costBySku) {
const sku = String(k || '').trim();
const price = Number(v);
if (sku && Number.isFinite(price) && price > 0) costBySku.set(sku, price);
}
} else if (opts?.costBySku) {
for (const [k, v] of Object.entries(opts.costBySku)) {
const sku = String(k || '').trim();
const price = Number(v);
if (sku && Number.isFinite(price) && price > 0) costBySku.set(sku, price);
}
}
// 报价兜底:保存未带 cost 的加菜 SKU
const quoteCosts = await client.query(
`SELECT DISTINCT ON (cqi.sku_code) cqi.sku_code, cqi.cost_price::float AS cost_price
FROM orders o
JOIN customer_quote_sheet_customers qsc ON qsc.customer_code = o.customer_code
JOIN customer_quote_sheets qs
ON qs.quote_sheet_code = qsc.quote_sheet_code
AND qs.status = 1
AND qs.approval_status = 30
AND (qs.expires_at IS NULL OR qs.expires_at > NOW())
AND (qs.branch_code IS NULL OR qs.branch_code = o.branch_code)
JOIN customer_quote_sheet_items cqi ON cqi.quote_sheet_code = qs.quote_sheet_code
WHERE o.order_code = $1
AND cqi.sku_code IS NOT NULL AND TRIM(cqi.sku_code) <> ''
AND COALESCE(cqi.cost_price, 0) > 0
ORDER BY cqi.sku_code, qs.updated_at DESC NULLS LAST`,
[code]
);
for (const row of quoteCosts.rows) {
const sku = String(row.sku_code || '').trim();
if (!sku || costBySku.has(sku)) continue;
const price = Number(row.cost_price);
if (Number.isFinite(price) && price > 0) costBySku.set(sku, price);
}
const items = await client.query(
`SELECT oi.id::text AS id,
oi.sku_code,
COALESCE(oi.quantity, 0)::float AS quantity,
f.purchase_code,
f.supplier_preparation_id
FROM order_items oi
LEFT JOIN order_item_fulfillments f ON f.order_item_id = oi.id
WHERE oi.order_code = $1
AND COALESCE(oi.is_extra_dish, false) = true
AND COALESCE(oi.is_returned, false) = false`,
[code]
);
const keepRefIds: string[] = [];
let posted = 0;
let totalAmount = 0;
for (const row of items.rows) {
const itemId = String(row.id || '').trim();
const sku = String(row.sku_code || '').trim();
const qty = Number(row.quantity) || 0;
const hasPurchase = Boolean(row.purchase_code && String(row.purchase_code).trim());
const hasPrep = Boolean(row.supplier_preparation_id);
if (!itemId || !sku || qty <= 0 || hasPurchase || hasPrep) continue;
const unitCost = costBySku.get(sku) || 0;
if (!(unitCost > 0)) continue;
const amount = Math.round(qty * unitCost * 100) / 100;
if (!(amount > 0)) continue;
keepRefIds.push(itemId);
const remark = extraDishRemark(code);
const existing = await client.query(
`SELECT id FROM cost_details
WHERE order_code = $1 AND cost_type = 'purchase'
AND cost_source = $2
AND reference_type = 'order_item'
AND reference_id = $3
LIMIT 1`,
[code, EXTRA_DISH_COST_SOURCE, itemId]
);
if (existing.rowCount) {
await client.query(
`UPDATE cost_details
SET amount = $2,
allocated_amount = $2,
cycle_code = $3,
branch_code = COALESCE($4, branch_code),
sku_code = $5,
cost_subtype = $6,
remark = $7,
status = 20
WHERE id = $1`,
[existing.rows[0].id, amount, cycleCode, branchCode, sku, EXTRA_DISH_COST_SUBTYPE, remark]
);
} else {
try {
await client.query('SAVEPOINT extra_dish_cost_ins');
await client.query(
`INSERT INTO cost_details (
cycle_code, order_code, cost_type, cost_subtype, amount, allocated_amount,
allocation_method, status, branch_code, sku_code,
reference_type, reference_id, cost_source, remark
) VALUES (
$1, $2, 'purchase', $3, $4, $4, 'sku', 20, $5, $6,
'order_item', $7, $8, $9
)`,
[
cycleCode,
code,
EXTRA_DISH_COST_SUBTYPE,
amount,
branchCode,
sku,
itemId,
EXTRA_DISH_COST_SOURCE,
remark,
]
);
await client.query('RELEASE SAVEPOINT extra_dish_cost_ins');
} catch (error: any) {
await client.query('ROLLBACK TO SAVEPOINT extra_dish_cost_ins').catch(() => undefined);
if (error?.code !== '23505') throw error;
await client.query(
`UPDATE cost_details
SET amount = $3, allocated_amount = $3, cycle_code = $4,
sku_code = $5, cost_subtype = $6, status = 20,
branch_code = COALESCE($7, branch_code),
remark = $9
WHERE order_code = $1 AND cost_type = 'purchase'
AND cost_source = $8 AND reference_id = $2`,
[
code,
itemId,
amount,
cycleCode,
sku,
EXTRA_DISH_COST_SUBTYPE,
branchCode,
EXTRA_DISH_COST_SOURCE,
remark,
]
);
}
}
posted += 1;
totalAmount += amount;
}
if (keepRefIds.length > 0) {
await client.query(
`DELETE FROM cost_details
WHERE order_code = $1 AND cost_type = 'purchase' AND cost_source = $2
AND NOT (reference_id = ANY($3::text[]))`,
[code, EXTRA_DISH_COST_SOURCE, keepRefIds]
);
} else {
await client.query(
`DELETE FROM cost_details
WHERE order_code = $1 AND cost_type = 'purchase' AND cost_source = $2`,
[code, EXTRA_DISH_COST_SOURCE]
);
}
// 清理历史误记:仅加菜 SKU 上的 unit_cost_sync 供应行(无非加菜同行、无自采/备货挂载)
await client.query(
`DELETE FROM cost_details cd
WHERE cd.order_code = $1
AND cd.cost_type = 'purchase'
AND cd.cost_source = 'supplier'
AND COALESCE(cd.remark, '') = 'unit_cost_sync'
AND cd.sku_code IS NOT NULL
AND EXISTS (
SELECT 1 FROM order_items oi
WHERE oi.order_code = cd.order_code
AND oi.sku_code IS NOT DISTINCT FROM cd.sku_code
AND COALESCE(oi.is_extra_dish, false) = true
)
AND NOT EXISTS (
SELECT 1 FROM order_items oi
WHERE oi.order_code = cd.order_code
AND oi.sku_code IS NOT DISTINCT FROM cd.sku_code
AND COALESCE(oi.is_extra_dish, false) = false
)
AND NOT EXISTS (
SELECT 1
FROM order_items oi
JOIN order_item_fulfillments f ON f.order_item_id = oi.id
WHERE oi.order_code = cd.order_code
AND oi.sku_code IS NOT DISTINCT FROM cd.sku_code
AND (
NULLIF(TRIM(f.purchase_code), '') IS NOT NULL
OR f.supplier_preparation_id IS NOT NULL
)
)`,
[code]
);
return { posted, amount: Math.round(totalAmount * 100) / 100 };
}
/** 为单笔已完成订单按 SKU+来源 生成采购成本明细(幂等) */
export async function postOrderPurchaseCost(
orderCode: string,
branchCode?: string | null,
cycleCode?: string
): Promise<{ generated: boolean; amount: number }> {
const orderMeta = await pool.query(
`SELECT cycle_code, branch_code FROM orders WHERE order_code = $1 LIMIT 1`,
[orderCode]
);
if (!orderMeta.rowCount) {
return { generated: false, amount: 0 };
}
const skuAmounts = await resolveSkuPurchaseAmounts(orderCode);
const totalAmount = Math.round(skuAmounts.reduce((s, r) => s + r.amount, 0) * 100) / 100;
if (totalAmount <= 0 || skuAmounts.length === 0) {
return { generated: false, amount: 0 };
}
const cycle =
String(cycleCode || '').trim() ||
String(orderMeta.rows[0]?.cycle_code || '').trim() ||
nowCycleCode();
const resolvedBranch = branchCode || orderMeta.rows[0]?.branch_code || null;
let insertedAmount = 0;
let insertedAny = false;
for (const row of skuAmounts) {
try {
const inserted = await pool.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
)
SELECT $1, 'purchase', 'order_goods', $2, $3, $4, 'sku', $2, 20, $5, $6
WHERE NOT EXISTS (
SELECT 1 FROM cost_details
WHERE order_code = $3 AND cost_type = 'purchase' AND sku_code = $4
AND cost_source IS NOT DISTINCT FROM $6
)
RETURNING id, amount`,
[cycle, row.amount, orderCode, row.sku_code, resolvedBranch, row.cost_source]
);
if (inserted.rowCount) {
insertedAny = true;
insertedAmount += Number(inserted.rows[0].amount) || row.amount;
}
} catch (error: any) {
if (error?.code === '23505') continue;
throw error;
}
}
if (!insertedAny) {
return { generated: false, amount: 0 };
}
return { generated: true, amount: Math.round(insertedAmount * 100) / 100 };
}
/** 批量为已完成且未入账的订单生成采购成本(财务模块) */
export async function postPurchaseCostsForCompletedOrders(
ctx: TenantContext | null | undefined,
options?: { cycleCode?: string; orderCodes?: string[]; limit?: number; operatingBranchCode?: string | null }
): Promise<{ posted: number; skipped: number; totalAmount: number }> {
const params: unknown[] = [];
let sql = `
SELECT o.order_code, o.branch_code
FROM orders o
WHERE o.order_status >= 90
AND o.deleted_at IS NULL
AND NOT EXISTS (
SELECT 1 FROM cost_details cd
WHERE cd.order_code = o.order_code AND cd.cost_type = 'purchase'
)`;
const effectiveBranch = ctx?.isSuperAdmin
? options?.operatingBranchCode || null
: ctx?.branchCode || null;
if (effectiveBranch) {
params.push(effectiveBranch);
sql += ` AND o.branch_code = $${params.length}`;
}
if (options?.orderCodes?.length) {
params.push(options.orderCodes);
sql += ` AND o.order_code = ANY($${params.length}::text[])`;
}
params.push(Math.min(options?.limit || 200, 500));
sql += ` ORDER BY o.updated_at DESC LIMIT $${params.length}`;
const rows = await pool.query(sql, params);
let posted = 0;
let skipped = 0;
let totalAmount = 0;
for (const row of rows.rows) {
const result = await postOrderPurchaseCost(
String(row.order_code),
row.branch_code,
options?.cycleCode
);
if (result.generated) {
posted += 1;
totalAmount += result.amount;
} else {
skipped += 1;
}
}
return { posted, skipped, totalAmount: Math.round(totalAmount * 100) / 100 };
}
type DbClient = Pick<PoolClient, 'query'> | typeof pool;
/**
* 补偿:遍历订单中 unit_cost>0 的非加菜商品,确保 cost_details 存在。
* 用于分配完成后(供应商备货已创建)补建之前遗漏的采购成本行。
*/
export async function compensateOrderItemCostDetails(
db: DbClient,
orderCode: string
): Promise<{ created: number; skipped: number }> {
const code = String(orderCode || '').trim();
if (!code) return { created: 0, skipped: 0 };
const items = await db.query(
`SELECT oi.id::text AS order_item_id, oi.sku_code, oi.unit_cost, oi.quantity,
COALESCE(oi.is_extra_dish, false) AS is_extra_dish,
COALESCE(oi.is_returned, false) AS is_returned
FROM order_items oi
WHERE oi.order_code = $1
AND oi.sku_code IS NOT NULL AND TRIM(oi.sku_code) <> ''
ORDER BY oi.sku_code`,
[code]
);
let created = 0;
let skipped = 0;
for (const item of items.rows) {
const sku = String(item.sku_code || '').trim();
const unitCost = Number(item.unit_cost) || 0;
const isExtra = item.is_extra_dish === true || item.is_extra_dish === 't' || item.is_extra_dish === 1;
const isReturned = item.is_returned === true || item.is_returned === 't' || item.is_returned === 1;
if (!sku || isExtra || isReturned || !(unitCost > 0)) {
skipped += 1;
continue;
}
// 检查是否已有 cost_details(任意 cost_source)
const existing = await db.query(
`SELECT 1 FROM cost_details
WHERE order_code = $1 AND cost_type = 'purchase' AND sku_code = $2
LIMIT 1`,
[code, sku]
);
if (existing.rowCount && existing.rowCount > 0) {
skipped += 1;
continue;
}
// 缺失 cost_details,调用 upsert 补建
try {
await upsertOrderSkuPurchaseCostFromUnitCost(db, code, sku, unitCost, {
orderItemId: String(item.order_item_id || ''),
});
created += 1;
} catch (err: any) {
console.error(
`[costPosting] compensateOrderItemCostDetails 补建失败: order=${code}, sku=${sku}, unitCost=${unitCost}, error=${err?.message || err}`
);
skipped += 1;
}
}
if (created > 0) {
console.log(
`[costPosting] compensateOrderItemCostDetails: order=${code}, created=${created}, skipped=${skipped}`
);
}
return { created, skipped };
}
/**
* 一套账 1B:按订单+SKU 用当前单价×数量 upsert 采购账本行(非加菜)。
* 与验收覆盖同一唯一键语义(order_code + sku_code + cost_source)。
*/
export async function upsertOrderSkuPurchaseCostFromUnitCost(
db: DbClient,
orderCode: string,
skuCode: string,
unitCost: unknown,
opts?: {
costSource?: 'supplier' | 'self_purchase' | null;
/** 新账按订单明细记账;未传时保留历史订单+SKU兼容路径。 */
orderItemId?: string | null;
}
): Promise<void> {
const code = String(orderCode || '').trim();
const sku = String(skuCode || '').trim();
if (!code || !sku) return;
const price = Number(unitCost);
const unit = Number.isFinite(price) && price >= 0 ? Math.round(price * 10000) / 10000 : 0;
const orderMeta = await db.query(
`SELECT cycle_code, branch_code FROM orders WHERE order_code = $1 AND deleted_at IS NULL LIMIT 1`,
[code]
);
if (!orderMeta.rowCount) return;
const orderItemId = String(opts?.orderItemId || '').trim();
if (orderItemId) {
const item = await db.query(
`SELECT COALESCE(quantity, 0)::numeric AS quantity,
COALESCE(stock_cover_qty, 0)::numeric AS stock_cover_qty,
COALESCE(is_extra_dish, false) AS is_extra_dish,
COALESCE(is_returned, false) AS is_returned,
supplier_code
FROM order_items
WHERE id = $1::uuid AND order_code = $2 AND sku_code = $3
LIMIT 1`,
[orderItemId, code, sku]
);
if (!item.rowCount) {
// 静默漏账高危点:明细不存在(含 sku_code 不一致)时不会写账本,必须留痕。
// 见 docs/design/20260911-backfill-missing-prep-purchase-cost.md
console.warn(
`[costPosting] upsertOrderSkuPurchaseCostFromUnitCost 未匹配到明细,跳过账本写入: order=${code}, sku=${sku}, item=${orderItemId}`
);
return;
}
const row = item.rows[0];
if (row.is_extra_dish === true || row.is_extra_dish === 't' || row.is_returned === true || row.is_returned === 't') {
return;
}
/**
* **只记「缺口部分」的成本**(2026-10-14 口径变更,开发者批准):
* 被库存抵扣的部分,其成本在**进货时**就已入账(`inventory_holding`,且被净利当期间费用扣掉),
* 不再计到订单上;只有需要自采/厂商备货的缺口才按本行的成本价计。
* 见 docs/design/20261014-抵扣部分不计订单成本.md
*/
const qty = Math.max(0, (Number(row.quantity) || 0) - (Number(row.stock_cover_qty) || 0));
const amount = Math.round(qty * unit * 100) / 100;
const supplierCode = String(row.supplier_code || '').trim().toUpperCase();
const costSource =
opts?.costSource || (!hasRealSupplierCode(supplierCode) ? 'self_purchase' : 'supplier');
const cycleCode = String(orderMeta.rows[0]?.cycle_code || '').trim() || nowCycleCode();
const branchCode = orderMeta.rows[0]?.branch_code || null;
// 改派供应商/自采时,清掉本明细旧的同步占位,避免同一商品行双来源累计。
await db.query(
`DELETE FROM cost_details
WHERE order_item_id = $1::uuid
AND cost_type = 'purchase'
AND COALESCE(remark, '') = 'unit_cost_sync'
AND cost_source IS DISTINCT FROM $2`,
[orderItemId, costSource]
);
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, $6, 'order_item', $7::text, $7::uuid, 'unit_cost_sync'
)
ON CONFLICT (order_item_id, COALESCE(cost_source, ''))
WHERE cost_type = 'purchase' AND order_item_id IS NOT NULL
DO UPDATE SET amount = EXCLUDED.amount,
allocated_amount = EXCLUDED.allocated_amount,
cycle_code = EXCLUDED.cycle_code,
branch_code = COALESCE(EXCLUDED.branch_code, cost_details.branch_code),
sku_code = EXCLUDED.sku_code,
status = 20,
cost_subtype = 'order_goods',
reference_type = 'order_item',
reference_id = EXCLUDED.reference_id,
remark = 'unit_cost_sync'`,
[cycleCode, amount, code, sku, branchCode, costSource, orderItemId]
);
return;
}
// 加菜数量不进供应侧 unit_cost 汇总(加菜走 cost_source=extra_dish)
const qtyRow = await db.query(
// 同上:只汇总**缺口部分**(quantity − stock_cover_qty),抵扣部分不计订单成本
`SELECT COALESCE(SUM(GREATEST(0, COALESCE(quantity, 0) - COALESCE(stock_cover_qty, 0))), 0)::numeric AS qty
FROM order_items
WHERE order_code = $1 AND sku_code = $2
AND COALESCE(is_extra_dish, false) = false
AND COALESCE(is_returned, false) = false`,
[code, sku]
);
const qty = Number(qtyRow.rows[0]?.qty) || 0;
const amount = Math.round(qty * unit * 100) / 100;
const cycleCode =
String(orderMeta.rows[0]?.cycle_code || '').trim() || nowCycleCode();
const branchCode = orderMeta.rows[0]?.branch_code || null;
// 已有正式采购入账:unit_cost_sync 仅为占位,禁止覆盖正式金额、禁止叠插
const formal = await db.query(
`SELECT id FROM cost_details
WHERE order_code = $1 AND cost_type = 'purchase' AND sku_code = $2
AND cost_source IS DISTINCT FROM $3
AND COALESCE(remark, '') IS DISTINCT FROM 'unit_cost_sync'
LIMIT 1`,
[code, sku, EXTRA_DISH_COST_SOURCE]
);
if (formal.rowCount) return;
// 仅更新已有 unit_cost_sync 占位行
const existingSync = await db.query(
`SELECT id FROM cost_details
WHERE order_code = $1 AND cost_type = 'purchase' AND sku_code = $2
AND COALESCE(remark, '') = 'unit_cost_sync'
ORDER BY created_at DESC NULLS LAST
LIMIT 1`,
[code, sku]
);
if (existingSync.rowCount) {
await db.query(
`UPDATE cost_details
SET amount = $2,
allocated_amount = $2,
cycle_code = $3,
branch_code = COALESCE($4, branch_code),
status = 20,
cost_subtype = COALESCE(NULLIF(TRIM(cost_subtype), ''), 'order_goods')
WHERE id = $1`,
[existingSync.rows[0].id, amount, cycleCode, branchCode]
);
return;
}
if (!(amount > 0) && !(unit > 0)) {
console.warn(
`[costPosting] upsertOrderSkuPurchaseCostFromUnitCost 跳过: amount=${amount} unit=${unit}, order=${code}, sku=${sku}`
);
return;
}
let costSource = opts?.costSource || null;
if (!costSource) {
const po = await db.query(
`SELECT 1 FROM purchase_orders WHERE order_code = $1 AND sku_code = $2 LIMIT 1`,
[code, sku]
);
if (po.rowCount) {
costSource = 'self_purchase';
} else {
// 无供应商备货则归自采,避免无供应商行误入供应采购成本
const prep = await db.query(
`SELECT 1 FROM supplier_preparations
WHERE order_code = $1 AND sku_code = $2
AND NULLIF(TRIM(supplier_code), '') IS NOT NULL
AND COALESCE(is_stockout, false) = false
AND COALESCE(transferred_to_purchase, false) = false
LIMIT 1`,
[code, sku]
);
costSource = prep.rowCount ? 'supplier' : 'self_purchase';
}
}
// 外层若已在事务中:INSERT 冲突必须用 SAVEPOINT,否则整单被 abort
let savepointOk = false;
try {
await db.query('SAVEPOINT upsert_purchase_unit_cost');
savepointOk = true;
} catch {
// 非事务连接:无 SAVEPOINT,依赖下方 23505 catch
}
try {
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, remark
) VALUES (
$1, 'purchase', 'order_goods', $2, $3, $4, 'sku', $2, 20, $5, $6, 'unit_cost_sync'
)`,
[cycleCode, amount, code, sku, branchCode, costSource]
);
if (savepointOk) await db.query('RELEASE SAVEPOINT upsert_purchase_unit_cost');
} catch (error: any) {
if (savepointOk) {
await db.query('ROLLBACK TO SAVEPOINT upsert_purchase_unit_cost').catch(() => undefined);
}
if (error?.code !== '23505') {
console.error(
`[costPosting] upsertOrderSkuPurchaseCostFromUnitCost INSERT 失败: order=${code}, sku=${sku}, costSource=${costSource}, error=${error?.message || error}`
);
throw error;
}
// 冲突时优先更新已有 unit_cost_sync 占位行
const updateResult = await db.query(
`UPDATE cost_details
SET amount = $3,
allocated_amount = $3,
cycle_code = $4,
branch_code = COALESCE($5, branch_code),
status = 20,
cost_subtype = COALESCE(NULLIF(TRIM(cost_subtype), ''), 'order_goods')
WHERE id = (
SELECT id FROM cost_details
WHERE order_code = $1 AND cost_type = 'purchase' AND sku_code = $2
AND COALESCE(remark, '') = 'unit_cost_sync'
ORDER BY created_at DESC NULLS LAST
LIMIT 1
)`,
[code, sku, amount, cycleCode, branchCode]
);
if (updateResult.rowCount === 0) {
// 冲突行不是 unit_cost_sync(可能是正式采购行),回退为按 (order_code, sku_code, cost_source) 更新
const fallbackUpdate = await db.query(
`UPDATE cost_details
SET amount = $3,
allocated_amount = $3,
cycle_code = $4,
branch_code = COALESCE($5, branch_code),
status = 20,
cost_subtype = COALESCE(NULLIF(TRIM(cost_subtype), ''), 'order_goods')
WHERE order_code = $1 AND cost_type = 'purchase' AND sku_code = $2
AND cost_source IS NOT DISTINCT FROM $6
ORDER BY created_at DESC NULLS LAST
LIMIT 1`,
[code, sku, amount, cycleCode, branchCode, costSource]
);
if (fallbackUpdate.rowCount === 0) {
console.error(
`[costPosting] upsertOrderSkuPurchaseCostFromUnitCost 23505 冲突但无法更新任何行: order=${code}, sku=${sku}, costSource=${costSource}, amount=${amount}`
);
}
}
}
}
/**
* 商品直送自采完成:用实采价×量写入正式自采采购账(清掉 unit_cost_sync 占位)。
* 见 docs/design/20260830-cost-bucket-processing-direct-delivery.md
*/
export async function upsertSkuDirectDeliverySelfPurchaseCost(
db: DbClient,
input: {
orderCode: string;
skuCode: string;
qty: number;
unitPrice: number;
branchCode?: string | null;
purchaseCode?: string | null;
}
): Promise<void> {
const orderCode = String(input.orderCode || '').trim();
const skuCode = String(input.skuCode || '').trim();
const qty = Number(input.qty) || 0;
const unitPrice = Number(input.unitPrice) || 0;
if (!orderCode || !skuCode) return;
if (!(qty > 0) || !(unitPrice > 0)) return;
const amount = Math.round(qty * unitPrice * 100) / 100;
if (!(amount > 0)) return;
const orderMeta = await db.query(
`SELECT cycle_code, branch_code FROM orders WHERE order_code = $1 AND deleted_at IS NULL LIMIT 1`,
[orderCode]
);
if (!orderMeta.rowCount) return;
const cycleCode =
String(orderMeta.rows[0]?.cycle_code || '').trim() || nowCycleCode();
const branchCode = input.branchCode || orderMeta.rows[0]?.branch_code || null;
const purchaseCode = String(input.purchaseCode || '').trim() || null;
const remark = purchaseCode
? `sku_direct_delivery:${purchaseCode}`
: 'sku_direct_delivery';
const existing = await db.query(
`SELECT id, remark FROM cost_details
WHERE order_code = $1 AND cost_type = 'purchase' AND sku_code = $2
AND cost_source IS NOT DISTINCT FROM 'self_purchase'
ORDER BY
CASE WHEN COALESCE(remark, '') = 'unit_cost_sync' THEN 0 ELSE 1 END,
created_at DESC NULLS LAST
LIMIT 1`,
[orderCode, skuCode]
);
if (existing.rowCount) {
await db.query(
`UPDATE cost_details
SET amount = $2,
allocated_amount = $2,
cycle_code = $3,
branch_code = COALESCE($4, branch_code),
cost_subtype = 'direct_delivery_purchase',
cost_source = 'self_purchase',
reference_type = CASE WHEN $5::text IS NULL THEN reference_type ELSE 'purchase_order' END,
reference_id = COALESCE($5::text, reference_id),
remark = $6,
status = 20
WHERE id = $1`,
[existing.rows[0].id, amount, cycleCode, branchCode, purchaseCode, remark]
);
return;
}
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, remark
) VALUES (
$1, 'purchase', 'direct_delivery_purchase', $2, $3, $4,
'sku', $2, 20, $5, 'self_purchase',
'purchase_order', $6, $7
)`,
[cycleCode, amount, orderCode, skuCode, branchCode, purchaseCode, remark]
);
}