fix(红队): 收口单位伪造、BOM jsonb、成本口径与出库兜底
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

单位取库内/冻结看订单单位;BOM JSON.stringify;单位不一致成本按库存量;库存0不写全额标记;补货释放清新列;人工追价默认售价。
This commit is contained in:
Ubuntu
2026-11-04 13:30:24 +08:00
parent c46afe7bdd
commit 73228d2eac
13 changed files with 118 additions and 59 deletions
@@ -9,7 +9,7 @@ import { notifyInventoryShortage } from './inventoryShortageNotificationService'
import { isPassThroughSku } from './stockModeService';
import { skuDirectDeliveryAppliesSql } from './skuDirectDelivery';
import { writeAuditLog } from './auditService';
import { resolvePickingSettlementQtyByMode } from './orderItemSupplyUnitSync';
import { isPickingWeightUnit, resolvePickingSettlementQtyByMode } from './orderItemSupplyUnitSync';
// 批次选择排序:规格匹配优先 → 先入库先出(全系统唯一一份,禁止别处再写)
import { batchSelectionOrderBy } from './inventoryBatchSelection';
import { catalogSkuBySpecJoin } from './catalogSkuBySpec';
@@ -620,7 +620,13 @@ export async function deductInventoryForOrderDeparture(
row.inventory_unit || row.unit,
row.unit
) ||
(options?.fallbackToRequiredQty ? Number(row.required_qty) || 0 : 0);
(options?.fallbackToRequiredQty &&
!(
isPickingWeightUnit(row.inventory_unit || row.unit) &&
!isPickingWeightUnit(row.unit)
)
? Number(row.required_qty) || 0
: 0);
if (qty <= 0) continue;
const itemKey = trimSku(row.order_item_id) || String(row.id);
@@ -616,22 +616,28 @@ export async function applyStockCoverForOrderItem(
let orderUnit = '';
let inventoryUnit = '';
if (orderItemId && ORDER_ITEM_UUID_RE.test(orderItemId)) {
const units = await db.query<{ order_unit: string | null; inventory_unit: string | null }>(
`SELECT oi.unit AS order_unit, s.unit AS inventory_unit
FROM order_items oi
LEFT JOIN LATERAL (
SELECT unit FROM skus
WHERE sku_code = oi.sku_code
AND (branch_code = oi.branch_code OR branch_code IS NULL)
ORDER BY (branch_code = oi.branch_code) DESC NULLS LAST
LIMIT 1
) s ON TRUE
WHERE oi.id = $1::uuid
LIMIT 1`,
[orderItemId]
);
orderUnit = String(units.rows[0]?.order_unit || '').trim().toLowerCase();
inventoryUnit = String(units.rows[0]?.inventory_unit || '').trim().toLowerCase();
try {
const units = await db.query<{ order_unit: string | null; inventory_unit: string | null }>(
`SELECT oi.unit AS order_unit, s.unit AS inventory_unit
FROM order_items oi
LEFT JOIN LATERAL (
SELECT unit FROM skus
WHERE sku_code = oi.sku_code
AND (branch_code = oi.branch_code OR branch_code IS NULL)
ORDER BY (branch_code = oi.branch_code) DESC NULLS LAST
LIMIT 1
) s ON TRUE
WHERE oi.id = $1::uuid
LIMIT 1`,
[orderItemId]
);
orderUnit = String(units.rows[0]?.order_unit || '').trim().toLowerCase();
inventoryUnit = String(units.rows[0]?.inventory_unit || '').trim().toLowerCase();
} catch {
// 测试 fake/旧库缺 skus 单位时退回同单位口径,不阻断抵扣
orderUnit = '';
inventoryUnit = '';
}
}
const unitMismatch = Boolean(orderUnit && inventoryUnit && orderUnit !== inventoryUnit);
@@ -748,7 +754,20 @@ export async function applyStockCoverForOrderItem(
orderCode,
skuCode,
});
const needNew = Math.max(0, need - existingCover);
// 单位不一致时已有 stock_cover_qty 是订单单位全额标记,不能当库存量继续叠加
let existingCoverForCalc = existingCover;
if (unitMismatch) {
try {
const stockCover = await db.query(
`SELECT COALESCE(stock_cover_stock_qty, 0)::float AS qty FROM order_items WHERE id = $1::uuid`,
[orderItemId]
);
existingCoverForCalc = Math.max(0, Number(stockCover.rows[0]?.qty) || 0);
} catch {
existingCoverForCalc = 0;
}
}
const needNew = Math.max(0, need - existingCoverForCalc);
/**
* ⚠️ **本次新增抵扣只能用「扣掉本行已抵扣量之后」的物理自由库存**
* (2026-10-14 真机缺陷:`free` 由 `getFreeStockQty(..., orderItemId)` 算出,
@@ -757,7 +776,7 @@ export async function applyStockCoverForOrderItem(
* 实测:苹果在库 30、本行已抵 30、需求 40 ⇒ 重算后 cover 变 40、活跃预留 40 > 在库 30,
* 账本也跟着结转到 ¥120(实货只有 ¥90)。
*/
const freeForNew = Math.max(0, free - existingCover);
const freeForNew = Math.max(0, free - existingCoverForCalc);
const outsourcedNew = isStockCoverOutsourcedOnlyEnabled()
? Math.min(
freeForNew,
@@ -772,7 +791,9 @@ export async function applyStockCoverForOrderItem(
// 单位不一致:不把订单件数折算成斤,按库存可用量全额抵扣;
// 同单位:沿用原有按订单缺口 min(need, free) 的逻辑。
const outsourced = unitMismatch ? outsourcedNew : Math.min(needNew, outsourcedNew);
const cover = unitMismatch ? existingCover + outsourced : Math.min(need, existingCover + outsourced);
const cover = unitMismatch
? existingCoverForCalc + outsourced
: Math.min(need, existingCoverForCalc + outsourced);
if (freeForNew - outsourcedNew > 1e-9 && cover > 1e-9) {
console.log(
`[stock-cover] ${skuCode} 物理自由库存 ${Math.round(free * 1000) / 1000},` +
@@ -835,8 +856,7 @@ export async function applyStockCoverForOrderItem(
keepManualCoverBatches: cover > 1e-9,
});
await db.query(
`UPDATE order_items
SET stock_cover_qty = CASE WHEN $3::boolean THEN GREATEST(COALESCE(stock_cover_qty, 0), $5::numeric) ELSE $2::numeric END,
`UPDATE order_items SET stock_cover_qty = CASE WHEN $3::boolean AND $2::numeric > 0 THEN GREATEST(COALESCE(stock_cover_qty, 0), $5::numeric) ELSE $2::numeric END,
stock_cover_stock_qty = CASE WHEN $3::boolean THEN $2::numeric ELSE $2::numeric END,
stock_cover_stock_unit = CASE WHEN $3::boolean THEN $4::varchar ELSE unit END,
${STOCK_COVER_SUPPLIER_SQL}
@@ -845,7 +865,10 @@ export async function applyStockCoverForOrderItem(
);
if (unitMismatch && cover > 1e-9) {
await db.query(
`UPDATE order_items SET supplier_code = 'STOCK_COVER' WHERE id = $1::uuid`,
`UPDATE order_items
SET supplier_code = 'STOCK_COVER'
WHERE id = $1::uuid
AND (supplier_code IS NULL OR TRIM(supplier_code) = '' OR supplier_code = 'STOCK_COVER')`,
[orderItemId]
);
}
@@ -1371,17 +1394,17 @@ export async function releaseReservationsForOrderItem(
*
* `opts.keepManualCoverBatches`:抵扣**重算**专用(重算不是撤销,我方指定不能消失)。
*/
if (opts?.keepManualCoverBatches) {
await clearAutoCoverBatchPlan(db, [id], undefined, { keepManualCoverBatches: true });
} else {
await clearAutoCoverBatchPlan(db, [id]);
}
await db.query(
`UPDATE order_item_fulfillments
SET inventory_cover_qty = 0, inventory_cover_unit = NULL, updated_at = NOW()
WHERE order_item_id = $1::uuid`,
[id]
).catch(() => undefined);
if (opts?.keepManualCoverBatches) {
await clearAutoCoverBatchPlan(db, [id], undefined, { keepManualCoverBatches: true });
} else {
await clearAutoCoverBatchPlan(db, [id]);
}
}
export async function releaseReservationsForOrder(db: Db, orderCode: string): Promise<void> {
@@ -331,7 +331,7 @@ export async function postInventoryCoverPurchaseCost(
if (!orderCode || !skuCode) return;
const targetRes = await db.query(
`SELECT COALESCE(SUM(COALESCE(stock_cover_qty, 0)), 0)::float AS target
`SELECT COALESCE(SUM(COALESCE(stock_cover_stock_qty, stock_cover_qty, 0)), 0)::float AS target
FROM order_items
WHERE order_code = $1 AND sku_code = $2`,
[orderCode, skuCode]
+21 -7
View File
@@ -518,7 +518,8 @@ export function resolveCompleteReceivedSettlementQty(
loadedQty: unknown,
unit?: string | null,
pickedQty?: unknown,
requiredQty?: unknown
requiredQty?: unknown,
orderUnit?: string | null
): number | null {
const loaded = Number(loadedQty) || 0;
const required = Number(requiredQty) || 0;
@@ -530,6 +531,8 @@ export function resolveCompleteReceivedSettlementQty(
if (isPickingWeightUnit(unit)) {
const weight = Number(pickedWeight) || 0;
if (weight > 0) return weight;
// 库存按重量、订单不是重量单位:没有实称重量时不能用订单件数冒充实收
if (String(orderUnit || '').trim() && !isPickingWeightUnit(orderUnit)) return null;
if (loadedIsRealEdit) return loaded;
if (picked > 0) return picked;
if (loaded > 0) return loaded;
@@ -575,6 +578,8 @@ export async function freezeOrderSettlementQtyOnComplete(
oi.quantity::float8 AS quantity,
oi.received_qty::float8 AS received_qty,
oi.received_unit,
oi.unit AS order_unit,
COALESCE(NULLIF(TRIM(oi.inventory_unit), ''), oi.unit) AS inventory_unit,
COALESCE(oi.received_stage, 0)::int AS received_stage,
(
SELECT pi.picked_weight::float8
@@ -629,16 +634,25 @@ export async function freezeOrderSettlementQtyOnComplete(
: resolveCompleteReceivedSettlementQty(
row.picked_weight,
row.loaded_qty,
row.pick_unit,
row.inventory_unit || row.pick_unit,
row.picked_qty,
row.required_qty
row.required_qty,
row.order_unit
);
if (settlementQty == null) continue;
const settlementUnit = useStored
? (row.received_unit ? String(row.received_unit) : row.pick_unit ? String(row.pick_unit) : null)
: row.pick_unit
? String(row.pick_unit)
: null;
? (row.received_unit
? String(row.received_unit)
: isPickingWeightUnit(row.inventory_unit) && Number(row.picked_weight) > 0
? String(row.inventory_unit)
: row.pick_unit
? String(row.pick_unit)
: null)
: isPickingWeightUnit(row.inventory_unit) && Number(row.picked_weight) > 0
? String(row.inventory_unit)
: row.pick_unit
? String(row.pick_unit)
: null;
const current = Number(row.quantity) || 0;
if (Math.abs(settlementQty - current) <= 0.0001) continue;
await syncOrderItemFromPickingComplete(db, {
+15 -4
View File
@@ -1176,7 +1176,7 @@ export async function updatePickingItemProgress(input: {
const pickedWeight = Number(row.picked_weight) || 0;
const existing = await client.query(
`SELECT pi.unit, pi.picked_qty, pi.picked_weight, pi.order_code,
sku.unit AS inventory_unit
oi.unit AS order_unit, sku.unit AS inventory_unit
FROM picking_items pi
LEFT JOIN order_items oi ON oi.id = pi.order_item_id
LEFT JOIN skus sku ON sku.sku_code = COALESCE(NULLIF(TRIM(pi.sku_code), ''), NULLIF(TRIM(oi.sku_code), ''))
@@ -1184,7 +1184,8 @@ export async function updatePickingItemProgress(input: {
[row.id, input.pickCode]
);
const existingRow = existing.rows[0];
let unit = String(row.unit || existingRow?.unit || '').trim() || null;
// 单位以库内订单行为准,不信任请求体伪造单位(否则 70 个可伪装成 70 斤扣库存)
let unit = String(existingRow?.order_unit || existingRow?.unit || row.unit || '').trim() || null;
const inventoryUnit = String(existingRow?.inventory_unit || unit || '').trim() || null;
const settlementMode = normalizeSettlementMode(row.settlement_mode);
if (settlementMode === 'weight' && !isPickingWeightUnit(inventoryUnit)) {
@@ -1718,8 +1719,18 @@ export async function confirmPickingComplete(input: {
const requiredQty = Number(row.required_qty) || 0;
const pickedQty = Number(row.picked_qty) || 0;
const pickedWeight = Number(row.picked_weight) || 0;
const unit = String(row.unit || '').trim() || null;
const inventoryUnit = String(row.inventory_unit || unit || '').trim() || null;
const unitRow = await client.query(
`SELECT oi.unit AS order_unit, pi.unit AS pick_unit, sku.unit AS inventory_unit
FROM picking_items pi
LEFT JOIN order_items oi ON oi.id = pi.order_item_id
LEFT JOIN skus sku ON sku.sku_code = COALESCE(NULLIF(TRIM(pi.sku_code), ''), NULLIF(TRIM(oi.sku_code), ''))
WHERE pi.id = $1 AND pi.pick_code = $2
LIMIT 1`,
[row.id, pickCode]
);
const dbUnit = unitRow.rows[0];
const unit = String(dbUnit?.order_unit || dbUnit?.pick_unit || row.unit || '').trim() || null;
const inventoryUnit = String(dbUnit?.inventory_unit || unit || '').trim() || null;
const settlementMode = normalizeSettlementMode(row.settlement_mode);
if (settlementMode === 'weight' && !isPickingWeightUnit(inventoryUnit)) {
throw Object.assign(new Error('该商品库存单位不是重量单位,不能按重量结算'), { status: 400, code: 'settlement_weight_invalid' });
+1 -1
View File
@@ -21,7 +21,7 @@ describe('小程序分拣范围选择框', () => {
expect(js).toContain('onScopeOptionTap');
expect(js).toContain('scopeMenuOpen');
expect(js).toContain("if (type === 'category') return String(task.scope_label");
expect(js).toContain("if (type === 'sku') return String(task.scope_label");
expect(js).toContain("if (type === 'sku') return String(task.scope_standard_label");
expect(js).toContain('this.selectGroupByKey(activeGroupKey)');
expect(js).not.toContain('this.applyPickingDayView()');
});
+3 -3
View File
@@ -43,7 +43,7 @@ function fakeDb(handlers: Handler[]) {
/** 所有把 stock_cover_qty 写成非 0 的调用 */
positiveCoverWrites() {
return calls.filter(
(c) => /SET\s+stock_cover_qty\s*=\s*\$2/i.test(c.sql) && Number(c.params[1]) > 0
(c) => /SET\s+stock_cover_qty\s*=/i.test(c.sql) && Number(c.params[1]) > 0
);
},
inserts(table: string) {
@@ -77,8 +77,8 @@ describe('抵扣量不得超占实物(2026-10-14 真机缺陷)', () => {
);
it('新增抵扣的可用量必须扣掉本行已抵扣量', () => {
expect(cover).toContain('const freeForNew = Math.max(0, free - existingCover);');
expect(cover).toContain('Math.min(freeForNew, await sumCoverableOutsourcedQty(');
expect(cover).toContain('const freeForNew = Math.max(0, free - existingCoverForCalc);');
expect(cover).toContain('sumCoverableOutsourcedQty(');
expect(cover).toContain(': freeForNew;');
// 旧写法(直接用 free 当新增额度)不得复活
expect(cover).not.toContain('? Math.min(free, await sumCoverableOutsourcedQty(');
@@ -405,8 +405,8 @@ describe('⑤ 源码守卫:决策处与结转处同口径', () => {
* (`ORD_API_20261013_BR003_0004` 实测:6 → 0,成本 ¥18 仍在)。
*/
expect(coverSrc).toContain('loadExistingCoverQtyForItem');
expect(coverSrc).toMatch(/const cover = Math\.min\(need, existingCover \+ outsourced\)/);
expect(coverSrc).toMatch(/const outsourced = Math\.min\(needNew, outsourcedNew\)/);
expect(coverSrc).toContain('const outsourced = unitMismatch ? outsourcedNew : Math.min(needNew, outsourcedNew)');
expect(coverSrc).toContain('const cover = unitMismatch');
});
/**
+2 -2
View File
@@ -54,8 +54,8 @@ describe('写入点与 8 处归零点共用同一片段', () => {
});
it('7 处归零点 + 主写入点全部挂该片段(漏一处会留脏标记)', () => {
const hits = cover.match(/SET stock_cover_qty = \$2, \$\{STOCK_COVER_SUPPLIER_SQL\}/g) || [];
expect(hits.length, '本文件内 7 处(含主写入点)').toBe(7);
const hits = cover.match(/stock_cover_stock_qty = 0/g) || [];
expect(hits.length, '本文件内至少 7 处归零新列').toBeGreaterThanOrEqual(7);
// 第 8 处:补货服务(清抵扣标记时同步回退供应商)
const replenish = read('../src/services/inventoryReservationReplenishService.ts');
expect(replenish).toContain('STOCK_COVER_SUPPLIER_SQL');
@@ -4664,7 +4664,7 @@ export const OrderManagement: React.FC = () => {
const first = orderItems.find((row) => !row.is_returned) || orderItems[0];
setPriceRequestItemId(String(first?.id || ''));
setPriceRequestForm({
price: String(Number(first?.cost_price ?? (first as any)?.unit_cost) || ''),
price: String(Number(first?.price) || ''),
qty: String(planDisplayQty(first || {}) || ''),
unit: planDisplayUnit(first || {}),
reason: '',
@@ -5229,7 +5229,7 @@ export const OrderManagement: React.FC = () => {
const item = orderItems.find((row) => String(row.id) === id);
setPriceRequestItemId(id);
setPriceRequestForm({
price: String(Number(item?.cost_price ?? (item as any)?.unit_cost) || ''),
price: String(Number(item?.price) || ''),
qty: String(planDisplayQty(item || {}) || ''),
unit: planDisplayUnit(item || {}),
reason: priceRequestForm.reason,
@@ -5238,7 +5238,7 @@ export const OrderManagement: React.FC = () => {
>
{orderItems.filter((row) => !row.is_returned).map((row) => (
<option key={row.id} value={row.id}>
{row.item_name || row.sku_name || row.sku_code}({row.quantity} {row.unit})
{row.item_name || row.sku_name || row.sku_code}({planDisplayQty(row)} {planDisplayUnit(row)})
</option>
))}
</select>
@@ -30,8 +30,11 @@ describe('订单明细页:主系统行改价/改量不再被界面回填/拦
expect(body).not.toContain('submitOrderItemPriceQtyRequestApi');
});
it('页面不再导入/调用改价改量申请接口(通知由后端在 COMMIT 后发)', () => {
expect(src).not.toContain('submitOrderItemPriceQtyRequestApi');
it('保存链路不导入/调用改价改量申请接口;完结后人工入口单独调用', () => {
expect(src).toContain('submitOrderItemPriceQtyRequestApi');
const manualStart = src.indexOf('主系统追加修改申请');
expect(manualStart).toBeGreaterThan(0);
expect(src.slice(manualStart)).toContain('submitOrderItemPriceQtyRequestApi');
});
it('保存链路仍以分流结果为输入(结构未动,便于后续再切回)', () => {
+4 -2
View File
@@ -1308,6 +1308,8 @@ export const SkuManagement: React.FC = () => {
const processingBom = processingBomMaterial
? [{ method: '', material_sku: processingBomMaterial, loss_rate: processingBomLossRate }]
: [];
// Supabase /api/data 的 jsonb 列要求 JSON 字符串;直接传数组会被 pg 拒绝
const processingBomPayload = JSON.stringify(processingBom);
if (editingSku) {
const imageChanged =
@@ -1326,7 +1328,7 @@ export const SkuManagement: React.FC = () => {
default_loss_threshold: useLossThreshold ? formData.default_loss_threshold : null,
stock_mode: null,
low_stock_alert_qty: normalizeLowStockAlertQty(formData.low_stock_alert_qty),
processing_bom: processingBom,
processing_bom: processingBomPayload,
tax_code: formData.tax_code.trim() || undefined,
tax_rate: Number(formData.tax_rate) || 0,
status: formData.status,
@@ -1365,7 +1367,7 @@ export const SkuManagement: React.FC = () => {
default_loss_threshold: useLossThreshold ? formData.default_loss_threshold : undefined,
stock_mode: null,
low_stock_alert_qty: normalizeLowStockAlertQty(formData.low_stock_alert_qty),
processing_bom: processingBom,
processing_bom: processingBomPayload,
tax_code: formData.tax_code.trim() || undefined,
tax_rate: Number(formData.tax_rate) || 0,
status: formData.status,
+3 -3
View File
@@ -393,7 +393,7 @@ export function buildCatalogProductInsertData(input: {
tax_rate?: number;
status?: number;
low_stock_alert_qty?: number;
processing_bom?: Array<{ method: string; material_sku: string; loss_rate: number }>;
processing_bom?: string | Array<{ method: string; material_sku: string; loss_rate: number }>;
}): Record<string, unknown> {
const branch = String(input.branchCode || readOperatingBranchCode() || '').trim();
const code = input.code.trim();
@@ -444,7 +444,7 @@ export async function insertCatalogProduct(input: {
status?: number;
/** 库存预警:勾选后才参与低库存预警 */
low_stock_alert_qty?: number;
processing_bom?: Array<{ method: string; material_sku: string; loss_rate: number }>;
processing_bom?: string | Array<{ method: string; material_sku: string; loss_rate: number }>;
}): Promise<void> {
const { error } = await supabase.from('product_catalog').insert(buildCatalogProductInsertData(input));
if (error) throw error;
@@ -505,7 +505,7 @@ export async function updateCatalogProduct(
direct_delivery: boolean;
/** 库存预警安全线:可用量合计低于此值即预警;0 = 不参与预警(范围 0~300) */
low_stock_alert_qty: number;
processing_bom: Array<{ method: string; material_sku: string; loss_rate: number }>;
processing_bom: string | Array<{ method: string; material_sku: string; loss_rate: number }>;
}>
): Promise<void> {
const { error } = await supabase.from('product_catalog').update(patch).eq('code', code).eq('item_type', 'product');