feat(订单实收): 持久化实收数量/单位并接入各履约环节
移植配送系统 68555db7:demand_* 留档、received_* 单一字段、stage 防倒序;下单/采购/验收/分拣/配送/完结/管理员修正接入,订单详情优先读持久实收。
This commit is contained in:
@@ -0,0 +1,30 @@
|
||||
-- 2026-11-03:订单行实收/客户计划持久化(移植主系统 68555db7)
|
||||
-- demand_*:下单时客户计划留档,只记录,不参与计算
|
||||
-- received_*:采购/验收/分拣/配送/完结/管理员修正依次写入
|
||||
-- received_stage:10采购/20验收/30分拣/40配送/50完结/60管理员,防倒序覆盖
|
||||
DO $$
|
||||
DECLARE
|
||||
sch text;
|
||||
BEGIN
|
||||
FOR sch IN
|
||||
SELECT nspname FROM pg_namespace
|
||||
WHERE nspname = 'legacy_public' OR nspname = 'tenant_template' OR nspname LIKE 'tenant\_%'
|
||||
ORDER BY nspname
|
||||
LOOP
|
||||
IF to_regclass(format('%I.order_items', sch)) IS NULL THEN
|
||||
CONTINUE;
|
||||
END IF;
|
||||
EXECUTE format('ALTER TABLE %I.order_items ADD COLUMN IF NOT EXISTS demand_qty numeric(14,3)', sch);
|
||||
EXECUTE format('ALTER TABLE %I.order_items ADD COLUMN IF NOT EXISTS demand_unit varchar(20)', sch);
|
||||
EXECUTE format('ALTER TABLE %I.order_items ADD COLUMN IF NOT EXISTS received_qty numeric(14,3)', sch);
|
||||
EXECUTE format('ALTER TABLE %I.order_items ADD COLUMN IF NOT EXISTS received_unit varchar(20)', sch);
|
||||
EXECUTE format('ALTER TABLE %I.order_items ADD COLUMN IF NOT EXISTS received_stage smallint', sch);
|
||||
EXECUTE format('ALTER TABLE %I.order_items ADD COLUMN IF NOT EXISTS received_at timestamptz', sch);
|
||||
EXECUTE format('COMMENT ON COLUMN %I.order_items.demand_qty IS %L', sch, '客户下单计划数量留档(只记录,不参与计算)');
|
||||
EXECUTE format('COMMENT ON COLUMN %I.order_items.demand_unit IS %L', sch, '客户下单计划单位留档(只记录)');
|
||||
EXECUTE format('COMMENT ON COLUMN %I.order_items.received_qty IS %L', sch, '当前实收数量(采购/验收/分拣/配送/完结/管理员依次覆盖)');
|
||||
EXECUTE format('COMMENT ON COLUMN %I.order_items.received_unit IS %L', sch, '当前实收单位');
|
||||
EXECUTE format('COMMENT ON COLUMN %I.order_items.received_stage IS %L', sch, '实收来源阶段:10采购/20验收/30分拣/40配送/50完结/60管理员;防倒序');
|
||||
EXECUTE format('COMMENT ON COLUMN %I.order_items.received_at IS %L', sch, '实收字段最近写入时间');
|
||||
END LOOP;
|
||||
END $$;
|
||||
@@ -0,0 +1,77 @@
|
||||
/**
|
||||
* 回填 order_items 的客户计划留档与实收字段(供应商侧,移植主系统 68555db7)。
|
||||
*
|
||||
* 只补 NULL,不覆盖已有值:
|
||||
* demand_* = COALESCE(demand, ordered_*, quantity/unit)
|
||||
* received_* = COALESCE(received, actual_received_*, quantity/unit)
|
||||
* received_stage = 有 actual_received 时 30(分拣称重),否则 0(历史值)
|
||||
*
|
||||
* 用法:
|
||||
* npx tsx --env-file=.env server/scripts/backfill-order-item-received-qty.ts --dry-run
|
||||
* npx tsx --env-file=.env server/scripts/backfill-order-item-received-qty.ts
|
||||
*/
|
||||
import { pool } from '../src/db';
|
||||
|
||||
function quoteIdent(name: string): string {
|
||||
return `"${name.replace(/"/g, '""')}"`;
|
||||
}
|
||||
|
||||
async function hasColumn(schema: string, table: string, column: string): Promise<boolean> {
|
||||
const r = await pool.query(
|
||||
`SELECT 1 FROM information_schema.columns WHERE table_schema=$1 AND table_name=$2 AND column_name=$3`,
|
||||
[schema, table, column]
|
||||
);
|
||||
return Boolean(r.rowCount);
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const dryRun = process.argv.includes('--dry-run');
|
||||
const schemas = await pool.query<{ nspname: string }>(
|
||||
`SELECT nspname FROM pg_namespace
|
||||
WHERE nspname IN ('legacy_public','tenant_template') OR nspname LIKE 'tenant\\_%'
|
||||
ORDER BY nspname`
|
||||
);
|
||||
let total = 0;
|
||||
for (const { nspname } of schemas.rows) {
|
||||
if (!(await hasColumn(nspname, 'order_items', 'received_qty'))) {
|
||||
console.log(`skip ${nspname}: 缺少 received_qty(先迁移)`);
|
||||
continue;
|
||||
}
|
||||
const hasActual = await hasColumn(nspname, 'order_items', 'actual_received_qty');
|
||||
const table = `${quoteIdent(nspname)}.order_items`;
|
||||
const actualExpr = hasActual ? 'COALESCE(actual_received_qty, 0) > 0' : 'FALSE';
|
||||
const actualQty = hasActual ? 'actual_received_qty' : 'NULL';
|
||||
const actualUnit = hasActual ? 'actual_received_unit' : 'NULL';
|
||||
if (dryRun) {
|
||||
const r = await pool.query(
|
||||
`SELECT COUNT(*)::int AS n FROM ${table}
|
||||
WHERE demand_qty IS NULL OR demand_unit IS NULL OR received_qty IS NULL
|
||||
OR received_unit IS NULL OR received_stage IS NULL`
|
||||
);
|
||||
const n = Number(r.rows[0]?.n) || 0;
|
||||
total += n;
|
||||
console.log(`${nspname}: 待回填 ${n} 行(dry-run)`);
|
||||
continue;
|
||||
}
|
||||
const r = await pool.query(
|
||||
`UPDATE ${table}
|
||||
SET demand_qty = COALESCE(demand_qty, ordered_quantity, quantity),
|
||||
demand_unit = COALESCE(demand_unit, ordered_unit, unit),
|
||||
received_qty = COALESCE(received_qty, CASE WHEN ${actualExpr} THEN ${actualQty} ELSE quantity END),
|
||||
received_unit = COALESCE(received_unit, CASE WHEN ${actualExpr} THEN COALESCE(${actualUnit}, unit) ELSE unit END),
|
||||
received_stage = COALESCE(received_stage, CASE WHEN ${actualExpr} THEN 30 ELSE 0 END)
|
||||
WHERE demand_qty IS NULL OR demand_unit IS NULL OR received_qty IS NULL
|
||||
OR received_unit IS NULL OR received_stage IS NULL`
|
||||
);
|
||||
const n = Number(r.rowCount || 0);
|
||||
total += n;
|
||||
console.log(`${nspname}: 回填 ${n} 行`);
|
||||
}
|
||||
console.log(`[backfill-order-item-received-qty] done rows=${total}`);
|
||||
await pool.end();
|
||||
}
|
||||
|
||||
main().catch((error) => {
|
||||
console.error('[backfill-order-item-received-qty] failed', error);
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -8,6 +8,7 @@ import { loadDirectDeliverySkuSetForOrder } from './skuDirectDelivery';
|
||||
import { isSupplierSkipInbound } from './supplierSkipInbound';
|
||||
import { adjustInboundInspectionQty } from './inspectionInboundQtyAdjust';
|
||||
import { resolveGapSlotQty } from './receivedQtySlot';
|
||||
import { orderReceivedQtyDb, writeOrderReceivedQtyBySku } from './orderItemReceivedQtyService';
|
||||
import {
|
||||
closeOrCreateInspectionForSku,
|
||||
fillPickingForOrder,
|
||||
@@ -364,6 +365,12 @@ export async function saveAdminOrderReceivedQty(input: {
|
||||
});
|
||||
}
|
||||
|
||||
await writeOrderReceivedQtyBySku(orderReceivedQtyDb(), {
|
||||
orderCode,
|
||||
quantities: qtyBySku,
|
||||
stage: 60,
|
||||
operatorId: input.ctx?.userId ? String(input.ctx.userId) : null,
|
||||
});
|
||||
await fillPickingForOrder({ orderCode, qtyByItemId, qtyBySku, ctx: input.ctx });
|
||||
if (meta.orderStatus >= 90) {
|
||||
// 已完成单:改实收会改动 picking_items.loaded_qty(结算量取值来源),
|
||||
|
||||
@@ -240,8 +240,10 @@ async function insertOrderWithItems(
|
||||
order_code, sku_code, item_name, quantity, unit, price, amount, item_status, sort_order,
|
||||
branch_code, processing_method, processing_owner, category_code, category_name,
|
||||
needs_customer_price, price_source, unit_cost, remark, quality_report_id, quality_report_ids,
|
||||
process_unit_price, spec
|
||||
) VALUES ($1, $2, $3, $4, $5, $6, $7, 10, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19::uuid[], $20, $21)
|
||||
process_unit_price, spec,
|
||||
demand_qty, demand_unit, received_qty, received_unit, received_stage
|
||||
) VALUES ($1, $2, $3, $4, $5, $6, $7, 10, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19::uuid[], $20, $21,
|
||||
$4, $5, $4, $5, 0)
|
||||
RETURNING id::text AS id`,
|
||||
[
|
||||
params.orderCode,
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { itemDisplayNameSql } from './itemDisplayNameSql';
|
||||
import type { PoolClient } from 'pg';
|
||||
import { pool } from '../db';
|
||||
import { orderReceivedQtyDb, writeOrderItemReceivedQty } from './orderItemReceivedQtyService';
|
||||
import { fetchSortedOrderItemsForPicking } from './pickingRouteSortService';
|
||||
import { upsertActiveReservation } from './inventoryStockCoverService';
|
||||
import { isDeliveryLoadingScaleEnabled } from './pickingScaleService';
|
||||
@@ -1053,6 +1054,17 @@ export async function confirmDeliveryLoadingItem(input: {
|
||||
// 分拣称重也只保存在 picking_items;订单计划量不在**核货事务内**被覆盖 ——
|
||||
// 事务提交后由 `freezeOrderSettlementQtyOnComplete` 统一对齐(出库/核货/结案同一函数、同一口径)。
|
||||
|
||||
if (nextLoaded > 0 && orderCode && (item.order_item_id || skuCode)) {
|
||||
await writeOrderItemReceivedQty(orderReceivedQtyDb(client), {
|
||||
orderCode,
|
||||
orderItemId: item.order_item_id ? String(item.order_item_id) : null,
|
||||
skuCode: skuCode || null,
|
||||
qty: nextLoaded,
|
||||
unit: (nextUnit || item.unit || item.order_unit || null) as string | null,
|
||||
stage: 40,
|
||||
operatorId: input.operatorId || null,
|
||||
}).catch((error) => console.error('[delivery-loading] 写订单行实收失败', error));
|
||||
}
|
||||
await client.query('COMMIT');
|
||||
} catch (error) {
|
||||
await client.query('ROLLBACK').catch(() => undefined);
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { PoolClient } from 'pg';
|
||||
import { isZeroSupplyCostAllowed } from './zeroSupplyCostConfigService';
|
||||
import { pool } from '../db';
|
||||
import { orderReceivedQtyDb, writeOrderItemReceivedQty } from './orderItemReceivedQtyService';
|
||||
import { deriveExpiryDate } from '../utils/shelfLife';
|
||||
import { applyArchiveWriteback } from './stockInboundService';
|
||||
import type { ArchiveWritebackInput } from './stockInboundService';
|
||||
@@ -2131,6 +2132,16 @@ export async function submitInspectionCompliance(
|
||||
);
|
||||
}
|
||||
|
||||
if (!isRejected && actualQty > 0 && row.order_code) {
|
||||
await writeOrderItemReceivedQty(orderReceivedQtyDb(client), {
|
||||
orderCode: String(row.order_code),
|
||||
skuCode: row.sku_code ? String(row.sku_code) : null,
|
||||
qty: actualQty,
|
||||
unit,
|
||||
stage: 20,
|
||||
operatorId: input.inspector_id || null,
|
||||
}).catch((error) => console.error('[inspection] 写订单行实收失败', error));
|
||||
}
|
||||
await client.query('COMMIT');
|
||||
|
||||
if (isRejected) {
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
import type { PoolClient } from 'pg';
|
||||
import { pool } from '../db';
|
||||
|
||||
/**
|
||||
* 订单行实收数量/单位的唯一写入口(2026-11-02)。
|
||||
*
|
||||
* 设计:docs/design/20261102-order-received-qty-persistence.md
|
||||
*
|
||||
* - 采购 10 / 验收入库 20 / 分拣 30 / 配送 40 / 完结 50 / 管理员修正 60;
|
||||
* - 只允许 qty > 0,禁止用 0 或空值清空已有实收;
|
||||
* - received_stage 单调递增,防止采购/验收等旧事件晚到覆盖更晚阶段的实收;
|
||||
* - 管理员修正(60)可以覆盖任何阶段。
|
||||
*/
|
||||
|
||||
export type ReceivedStage = 10 | 20 | 30 | 40 | 50 | 60;
|
||||
|
||||
export interface WriteOrderItemReceivedQtyInput {
|
||||
orderCode: string;
|
||||
orderItemId?: string | null;
|
||||
skuCode?: string | null;
|
||||
qty: number;
|
||||
unit?: string | null;
|
||||
stage: ReceivedStage;
|
||||
operatorId?: string | null;
|
||||
/** 显式允许低阶段覆盖,仅用于数据修复,不要在日常流程使用 */
|
||||
allowLowerStage?: boolean;
|
||||
}
|
||||
|
||||
type Db = {
|
||||
query: (
|
||||
text: string,
|
||||
params?: unknown[]
|
||||
) => Promise<{ rows: Array<Record<string, unknown>>; rowCount?: number | null }>;
|
||||
};
|
||||
|
||||
function trimText(v: unknown): string {
|
||||
return String(v ?? '').trim();
|
||||
}
|
||||
|
||||
export async function writeOrderItemReceivedQty(
|
||||
db: Db,
|
||||
input: WriteOrderItemReceivedQtyInput
|
||||
): Promise<number> {
|
||||
const orderCode = trimText(input.orderCode);
|
||||
const orderItemId = trimText(input.orderItemId);
|
||||
const skuCode = trimText(input.skuCode);
|
||||
const qty = Number(input.qty);
|
||||
const unit = trimText(input.unit).slice(0, 20) || null;
|
||||
const stage = Number(input.stage);
|
||||
|
||||
if (!orderCode) return 0;
|
||||
if (!orderItemId && !skuCode) return 0;
|
||||
if (!Number.isFinite(qty) || qty <= 0) return 0;
|
||||
if (![10, 20, 30, 40, 50, 60].includes(stage)) return 0;
|
||||
|
||||
const conditions: string[] = [
|
||||
`order_code = $1`,
|
||||
`COALESCE(is_returned, false) = false`,
|
||||
// $2/$3 在分支中可能只有一个被实际引用;这里显式确定 text 类型,避免 PostgreSQL 42P18。
|
||||
`($2::text IS NULL OR $2::text = $2::text)`,
|
||||
`($3::text IS NULL OR $3::text = $3::text)`,
|
||||
];
|
||||
const params: unknown[] = [orderCode, orderItemId || null, skuCode || null, qty, unit, stage];
|
||||
if (orderItemId) {
|
||||
conditions.push(`id::text = $2::text`);
|
||||
} else {
|
||||
conditions.push(`sku_code IS NOT DISTINCT FROM $3`);
|
||||
}
|
||||
if (!input.allowLowerStage) {
|
||||
conditions.push(`(received_stage IS NULL OR received_stage <= $6::int OR $6::int = 60)`);
|
||||
}
|
||||
|
||||
const result = await db.query(
|
||||
`UPDATE order_items
|
||||
SET received_qty = $4::numeric,
|
||||
received_unit = COALESCE($5::varchar, received_unit),
|
||||
received_stage = $6::smallint,
|
||||
received_at = NOW()
|
||||
WHERE ${conditions.join(' AND ')}`,
|
||||
params
|
||||
);
|
||||
return Number(result.rowCount || 0);
|
||||
}
|
||||
|
||||
/** 按订单 SKU 批量写实收;unit 缺省时用订单行单位。返回写入行数。 */
|
||||
export async function writeOrderReceivedQtyBySku(
|
||||
db: Db,
|
||||
input: {
|
||||
orderCode: string;
|
||||
quantities: Map<string, number>;
|
||||
stage: ReceivedStage;
|
||||
operatorId?: string | null;
|
||||
}
|
||||
): Promise<number> {
|
||||
const orderCode = trimText(input.orderCode);
|
||||
if (!orderCode || !input.quantities.size) return 0;
|
||||
let written = 0;
|
||||
for (const [skuCode, qty] of input.quantities) {
|
||||
const sku = trimText(skuCode);
|
||||
if (!sku || !(Number(qty) > 0)) continue;
|
||||
const unitRow = await db.query(
|
||||
`SELECT COALESCE(NULLIF(TRIM(received_unit), ''), NULLIF(TRIM(unit), '')) AS unit
|
||||
FROM order_items
|
||||
WHERE order_code = $1 AND sku_code IS NOT DISTINCT FROM $2
|
||||
AND COALESCE(is_returned, false) = false
|
||||
ORDER BY sort_order ASC NULLS LAST, id ASC
|
||||
LIMIT 1`,
|
||||
[orderCode, sku]
|
||||
);
|
||||
const unit = trimText(unitRow.rows[0]?.unit) || null;
|
||||
written += await writeOrderItemReceivedQty(db, {
|
||||
orderCode,
|
||||
skuCode: sku,
|
||||
qty: Number(qty),
|
||||
unit,
|
||||
stage: input.stage,
|
||||
operatorId: input.operatorId,
|
||||
});
|
||||
}
|
||||
return written;
|
||||
}
|
||||
|
||||
/** 从池或事务客户端取连接;调用方已有事务时直接传 client。 */
|
||||
export function orderReceivedQtyDb(client?: PoolClient | null): Db {
|
||||
return (client || pool) as unknown as Db;
|
||||
}
|
||||
@@ -568,6 +568,9 @@ export async function freezeOrderSettlementQtyOnComplete(
|
||||
const items = await db.query(
|
||||
`SELECT oi.id::text AS order_item_id,
|
||||
oi.quantity::float8 AS quantity,
|
||||
oi.received_qty::float8 AS received_qty,
|
||||
oi.received_unit,
|
||||
COALESCE(oi.received_stage, 0)::int AS received_stage,
|
||||
(
|
||||
SELECT pi.picked_weight::float8
|
||||
FROM picking_items pi
|
||||
@@ -610,20 +613,33 @@ export async function freezeOrderSettlementQtyOnComplete(
|
||||
);
|
||||
|
||||
for (const row of items.rows) {
|
||||
const settlementQty = resolveCompleteReceivedSettlementQty(
|
||||
row.picked_weight,
|
||||
row.loaded_qty,
|
||||
row.pick_unit,
|
||||
row.picked_qty,
|
||||
row.required_qty
|
||||
);
|
||||
/**
|
||||
* 2026-11-03:持久实收字段是权威来源;stage>=10 才使用,
|
||||
* 避免新订单初始 stage=0 的计划值被当成实收冻结。
|
||||
*/
|
||||
const storedReceivedQty = Number(row.received_qty) || 0;
|
||||
const useStored = storedReceivedQty > 0 && Number(row.received_stage) >= 10;
|
||||
const settlementQty = useStored
|
||||
? storedReceivedQty
|
||||
: resolveCompleteReceivedSettlementQty(
|
||||
row.picked_weight,
|
||||
row.loaded_qty,
|
||||
row.pick_unit,
|
||||
row.picked_qty,
|
||||
row.required_qty
|
||||
);
|
||||
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;
|
||||
const current = Number(row.quantity) || 0;
|
||||
if (Math.abs(settlementQty - current) <= 0.0001) continue;
|
||||
await syncOrderItemFromPickingComplete(db, {
|
||||
orderItemId: String(row.order_item_id),
|
||||
settlementQty,
|
||||
settlementUnit: row.pick_unit ? String(row.pick_unit) : null,
|
||||
settlementUnit,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1447,6 +1447,11 @@ export async function syncOrderManageItems(params: {
|
||||
`UPDATE order_items
|
||||
SET item_name = $1, quantity = $2::numeric, unit = $3, price = $4::numeric, amount = $5::numeric,
|
||||
ordered_quantity = $2::numeric,
|
||||
demand_qty = COALESCE(demand_qty, $2::numeric),
|
||||
demand_unit = COALESCE(demand_unit, $3),
|
||||
received_qty = COALESCE(received_qty, $2::numeric),
|
||||
received_unit = COALESCE(received_unit, $3),
|
||||
received_stage = COALESCE(received_stage, 0),
|
||||
processing_method = $6, processing_owner = $7,
|
||||
category_code = $8, category_name = $9,
|
||||
sku_code = $10,
|
||||
@@ -1536,8 +1541,10 @@ export async function syncOrderManageItems(params: {
|
||||
id, order_code, sku_code, item_name, quantity, unit, price, amount, item_status, sort_order,
|
||||
branch_code, processing_method, processing_owner, category_code, category_name, supplier_code,
|
||||
locked_price, price_locked_at, is_extra_dish, unit_cost, remark, quality_report_id, quality_report_ids,
|
||||
ordered_quantity, spec
|
||||
) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, 10, $9, $10, $11, $12, $13, $14, $15, $7, NOW(), $20, $16, $17, $18::uuid, $19::uuid[], $5, $21)`,
|
||||
ordered_quantity, spec,
|
||||
demand_qty, demand_unit, received_qty, received_unit, received_stage
|
||||
) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, 10, $9, $10, $11, $12, $13, $14, $15, $7, NOW(), $20, $16, $17, $18::uuid, $19::uuid[], $5, $21,
|
||||
$5, $6, $5, $6, 0)`,
|
||||
[
|
||||
newId,
|
||||
orderCode,
|
||||
|
||||
@@ -53,6 +53,7 @@ import {
|
||||
} from './orderItemLabelBarcodeSql';
|
||||
import { resolvePickingScanRow } from './labelScanResolver';
|
||||
import { isPickingScaleRequired } from './pickingScaleService';
|
||||
import { orderReceivedQtyDb, writeOrderItemReceivedQty } from './orderItemReceivedQtyService';
|
||||
import { salesVisibleOrderSql } from './independentInbound';
|
||||
import { buildSignedStoragePathForCtxChecked } from './storageObjectOwnership';
|
||||
|
||||
@@ -1087,6 +1088,51 @@ export async function savePickingReview(input: {
|
||||
* 已完成(30) 仍可改量并保持 30;已出库(≥40) 拒绝。
|
||||
* 见 docs/design/20260829-completed-picking-editable.md
|
||||
*/
|
||||
/**
|
||||
* 分拣保存/完成之后写订单行持久实收(stage=30)。
|
||||
* 与订单详情/完结冻结共用同一字段;库存出库仍由出库服务负责,本函数不扣库。
|
||||
*/
|
||||
async function syncPickingReceivedQty(
|
||||
client: PoolClient,
|
||||
itemIds: string[]
|
||||
): Promise<void> {
|
||||
const ids = [...new Set(itemIds.map((id) => String(id || '').trim()).filter(Boolean))];
|
||||
if (!ids.length) return;
|
||||
const rows = await client.query(
|
||||
`SELECT pi.id, pi.order_code, pi.order_item_id,
|
||||
pi.picked_qty::float8 AS picked_qty,
|
||||
pi.picked_weight::float8 AS picked_weight,
|
||||
pi.settlement_mode, pi.unit,
|
||||
sku.unit AS inventory_unit, oi.sku_code
|
||||
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 = ANY($1::uuid[])`,
|
||||
[ids]
|
||||
);
|
||||
for (const row of rows.rows) {
|
||||
const orderCode = String(row.order_code || '').trim();
|
||||
const qty =
|
||||
resolvePickingSettlementQtyByMode(
|
||||
row.settlement_mode,
|
||||
row.picked_qty,
|
||||
row.picked_weight,
|
||||
String(row.inventory_unit || row.unit || '')
|
||||
) || 0;
|
||||
if (!orderCode || qty <= 0) continue;
|
||||
await writeOrderItemReceivedQty(orderReceivedQtyDb(client), {
|
||||
orderCode,
|
||||
orderItemId: row.order_item_id ? String(row.order_item_id) : null,
|
||||
skuCode: row.sku_code ? String(row.sku_code) : null,
|
||||
qty,
|
||||
unit: (row.inventory_unit || row.unit) ? String(row.inventory_unit || row.unit) : null,
|
||||
stage: 30,
|
||||
}).catch((error) => {
|
||||
console.error('[picking] 写订单行实收失败', error);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export async function updatePickingItemProgress(input: {
|
||||
pickCode: string;
|
||||
rows: PickingProgressRow[];
|
||||
@@ -1220,6 +1266,7 @@ export async function updatePickingItemProgress(input: {
|
||||
[nextStatus, input.pickCode]
|
||||
);
|
||||
}
|
||||
await syncPickingReceivedQty(client, input.rows.map((row) => String(row.id)));
|
||||
await client.query('COMMIT');
|
||||
// 分拣改量审计:失败只告警,不阻断正常分拣保存。
|
||||
for (const change of qtyChanges) {
|
||||
@@ -1787,6 +1834,7 @@ export async function confirmPickingComplete(input: {
|
||||
)
|
||||
);
|
||||
|
||||
await syncPickingReceivedQty(client, items.rows.map((row) => String(row.id)));
|
||||
await client.query('COMMIT');
|
||||
|
||||
// 订单单位与库存单位不一致(如订单 70 个 / 库存斤):分拣称重后,
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { PoolClient } from 'pg';
|
||||
import { pool } from '../db';
|
||||
import { orderReceivedQtyDb, writeOrderItemReceivedQty } from './orderItemReceivedQtyService';
|
||||
import { assertPurchaseOrderInBranch } from './purchaserBranchScope';
|
||||
import { writeAuditLog } from './auditService';
|
||||
import { syncOrderItemsFromSupplyCompletion } from './orderItemSupplyUnitSync';
|
||||
@@ -541,6 +542,16 @@ export async function amendPurchaseActual(
|
||||
actionCategory: 'purchase',
|
||||
});
|
||||
|
||||
if (nextQty > 0 && row.order_code && row.sku_code) {
|
||||
await writeOrderItemReceivedQty(orderReceivedQtyDb(ownsClient ? null : client), {
|
||||
orderCode: String(row.order_code),
|
||||
skuCode: String(row.sku_code),
|
||||
qty: nextQty,
|
||||
unit: nextUnit,
|
||||
stage: 10,
|
||||
}).catch((error) => console.error('[purchase-amend] 写订单行实收失败', error));
|
||||
}
|
||||
|
||||
if (ownsClient) await client.query('COMMIT');
|
||||
return {
|
||||
success: true,
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { PoolClient } from 'pg';
|
||||
import { pool } from '../db';
|
||||
import { orderReceivedQtyDb, writeOrderItemReceivedQty } from './orderItemReceivedQtyService';
|
||||
import { assertPurchaseOrderInBranch } from './purchaserBranchScope';
|
||||
import { PURCHASE_STATUS_QUALITY_REJECTED } from './purchaseInboundService';
|
||||
import { ensurePurchaseInspectionForCompletedPurchase } from './inspectionComplianceService';
|
||||
@@ -227,6 +228,25 @@ export async function updatePurchaseOrderStatus(
|
||||
);
|
||||
}
|
||||
|
||||
// 自采实收(stage=10):后续验收/分拣/配送会按阶段覆盖。
|
||||
if (status === 20 && actualQty != null && Number(actualQty) > 0) {
|
||||
const link = await client.query(
|
||||
`SELECT order_code, sku_code FROM purchase_orders WHERE purchase_code = $1 LIMIT 1`,
|
||||
[purchaseCode]
|
||||
);
|
||||
const orderCode = String(link.rows[0]?.order_code || '').trim();
|
||||
const skuCode = String(link.rows[0]?.sku_code || currentRow.sku_code || '').trim();
|
||||
if (orderCode && skuCode) {
|
||||
await writeOrderItemReceivedQty(orderReceivedQtyDb(client), {
|
||||
orderCode,
|
||||
skuCode,
|
||||
qty: Number(actualQty),
|
||||
unit: input.unit || null,
|
||||
stage: 10,
|
||||
}).catch((error) => console.error('[purchase] 写订单行实收失败', error));
|
||||
}
|
||||
}
|
||||
|
||||
// 实采价为 0:把「下单采购价」与金额一并清零,避免各处读取点
|
||||
// (`COALESCE(NULLIF(actual_price,0), purchase_price)`:金额重算 / 倒挂判定 / 列表展示)
|
||||
// 把真实的 0 成本静默回退成下单价。适用两种情形:
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
writeOrderItemReceivedQty,
|
||||
writeOrderReceivedQtyBySku,
|
||||
} from '../src/services/orderItemReceivedQtyService';
|
||||
|
||||
function fakeDb(rows: Record<string, unknown>[] = [], rowCount = rows.length) {
|
||||
const calls: Array<{ text: string; params?: unknown[] }> = [];
|
||||
return {
|
||||
calls,
|
||||
db: {
|
||||
query: async (text: string, params?: unknown[]) => {
|
||||
calls.push({ text, params });
|
||||
return { rows, rowCount };
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe('orderItemReceivedQtyService', () => {
|
||||
it('只接受正数量,不接受 0 清空', async () => {
|
||||
const { db, calls } = fakeDb();
|
||||
expect(
|
||||
await writeOrderItemReceivedQty(db, {
|
||||
orderCode: 'ORD1',
|
||||
skuCode: 'SKU1',
|
||||
qty: 0,
|
||||
stage: 20,
|
||||
})
|
||||
).toBe(0);
|
||||
expect(calls).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('写入 received 字段并带阶段防倒序条件', async () => {
|
||||
const { db, calls } = fakeDb([], 1);
|
||||
const written = await writeOrderItemReceivedQty(db, {
|
||||
orderCode: 'ORD1',
|
||||
orderItemId: 'item-1',
|
||||
skuCode: 'SKU1',
|
||||
qty: 30,
|
||||
unit: '斤',
|
||||
stage: 60,
|
||||
});
|
||||
expect(written).toBe(1);
|
||||
expect(calls[0].text).toContain('received_qty = $4::numeric');
|
||||
expect(calls[0].text).toContain('received_stage IS NULL OR received_stage <= $6::int');
|
||||
expect(calls[0].params).toEqual(['ORD1', 'item-1', 'SKU1', 30, '斤', 60]);
|
||||
});
|
||||
|
||||
it('按 SKU 批量写时取订单行单位', async () => {
|
||||
const { db, calls } = fakeDb([{ unit: '斤' }], 1);
|
||||
const written = await writeOrderReceivedQtyBySku(db, {
|
||||
orderCode: 'ORD1',
|
||||
quantities: new Map([['SKU1', 30]]),
|
||||
stage: 40,
|
||||
});
|
||||
expect(written).toBe(1);
|
||||
expect(calls.some((call) => call.params?.[4] === '斤')).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -16,6 +16,7 @@ import type {
|
||||
} from '../../pages/orders/orderManagement/orderManagementHelpers';
|
||||
import {
|
||||
planDisplayQty,
|
||||
planDisplayUnit,
|
||||
resolveStockCoverOptionVisible,
|
||||
type OrderDetailItemGroup,
|
||||
} from '../../pages/orders/orderManagement/orderManagementHelpers';
|
||||
@@ -1125,7 +1126,7 @@ export const OrderDetailDeliveryNotePanel: React.FC<OrderDetailDeliveryNotePanel
|
||||
className="app-input w-full px-1 py-1 border rounded text-sm text-center"
|
||||
/>
|
||||
) : (
|
||||
item.unit || ''
|
||||
planDisplayUnit(item)
|
||||
)}
|
||||
</td>
|
||||
{showCostPrice ? (
|
||||
@@ -1211,22 +1212,27 @@ export const OrderDetailDeliveryNotePanel: React.FC<OrderDetailDeliveryNotePanel
|
||||
<td className="border border-slate-700 dark:border-slate-500 px-2 py-1.5 text-center tabular-nums font-medium w-24">
|
||||
{formatOrderAmount(item.amount)}
|
||||
</td>
|
||||
<td className="border border-slate-700 dark:border-slate-500 px-2 py-1.5 text-center tabular-nums w-20">
|
||||
{canEditReceivedQty && !item.is_returned ? (
|
||||
<DecimalInput
|
||||
value={
|
||||
Number(item.received_qty) > 0
|
||||
? Number(item.received_qty)
|
||||
: Number(item.quantity) || 0
|
||||
}
|
||||
min={0}
|
||||
onChange={(received_qty) => onUpdateItem(item.id, { received_qty })}
|
||||
className="w-full px-1.5 py-1 text-sm border rounded text-center focus:outline-none focus:ring-1"
|
||||
normalClassName="app-input focus:ring-slate-500"
|
||||
/>
|
||||
) : (
|
||||
formatReceivedQty(item.received_qty)
|
||||
)}
|
||||
<td className="border border-slate-700 dark:border-slate-500 px-2 py-1.5 text-center tabular-nums w-28">
|
||||
<div className="flex items-center justify-center gap-1">
|
||||
{canEditReceivedQty && !item.is_returned ? (
|
||||
<DecimalInput
|
||||
value={
|
||||
Number(item.received_qty) > 0
|
||||
? Number(item.received_qty)
|
||||
: Number(item.quantity) || 0
|
||||
}
|
||||
min={0}
|
||||
onChange={(received_qty) => onUpdateItem(item.id, { received_qty })}
|
||||
className="w-full min-w-0 px-1.5 py-1 text-sm border rounded text-center focus:outline-none focus:ring-1"
|
||||
normalClassName="app-input focus:ring-slate-500"
|
||||
/>
|
||||
) : (
|
||||
formatReceivedQty(item.received_qty)
|
||||
)}
|
||||
<span className="shrink-0 text-xs app-foreground-muted">
|
||||
{item.received_unit || item.unit || ''}
|
||||
</span>
|
||||
</div>
|
||||
</td>
|
||||
<td className="border border-slate-700 dark:border-slate-500 px-2 py-1.5 min-w-0 text-center">
|
||||
{rowEditable ? (
|
||||
|
||||
@@ -1034,18 +1034,26 @@ export const OrderManagement: React.FC = () => {
|
||||
purchaseByItemId.get(String(item.id)) ?? (sku ? purchaseBySku.get(sku) : undefined) ?? null;
|
||||
const skipInbound = skipInboundBySupplier.get(itemSupplier) === true;
|
||||
const directDelivery = Boolean(sku && directSkuSet.has(sku));
|
||||
const received_qty = resolveOrderItemReceivedQty({
|
||||
directDelivery,
|
||||
purchaseReceivedQty: purchaseReceived,
|
||||
loadedQty: loaded ?? null,
|
||||
inspectionReceivedQty: received ?? null,
|
||||
pickedWeight: loadedRow?.pickedWeight ?? null,
|
||||
pickedQty: loadedRow?.pickedQty ?? null,
|
||||
unit: loadedRow?.unit || item.unit || null,
|
||||
loadingQtyEditable: skipInbound,
|
||||
// 仓库抵扣的那部分也要计入实收(开发者 2026-10-14 D2:入库只入自采/厂商备货的缺口)
|
||||
stockCoverQty: Number(item.stock_cover_qty) || 0,
|
||||
});
|
||||
// 2026-11-03:持久实收优先;老订单/未产生实收时回退动态取数。
|
||||
const storedReceivedQty = Number(item.received_qty) || 0;
|
||||
const storedStage = Number(item.received_stage) || 0;
|
||||
const storedReceived =
|
||||
storedReceivedQty > 0 &&
|
||||
(storedStage >= 10 || Number(selectedOrder?.order_status) >= 90);
|
||||
const received_qty = storedReceived
|
||||
? storedReceivedQty
|
||||
: resolveOrderItemReceivedQty({
|
||||
directDelivery,
|
||||
purchaseReceivedQty: purchaseReceived,
|
||||
loadedQty: loaded ?? null,
|
||||
inspectionReceivedQty: received ?? null,
|
||||
pickedWeight: loadedRow?.pickedWeight ?? null,
|
||||
pickedQty: loadedRow?.pickedQty ?? null,
|
||||
unit: loadedRow?.unit || item.unit || null,
|
||||
loadingQtyEditable: skipInbound,
|
||||
// 仓库抵扣的那部分也要计入实收(开发者 2026-10-14 D2:入库只入自采/厂商备货的缺口)
|
||||
stockCoverQty: Number(item.stock_cover_qty) || 0,
|
||||
});
|
||||
const inspection_failed =
|
||||
Boolean(sku && failMarks.skuCodes.has(sku)) ||
|
||||
Boolean(itemName && failMarks.itemNames.has(itemName));
|
||||
@@ -1060,6 +1068,10 @@ export const OrderManagement: React.FC = () => {
|
||||
is_returned: Boolean(item.is_returned),
|
||||
inbound_done: inboundDone,
|
||||
received_qty,
|
||||
received_unit: item.received_unit || item.unit || null,
|
||||
demand_qty: item.demand_qty ?? null,
|
||||
demand_unit: item.demand_unit ?? null,
|
||||
received_stage: item.received_stage ?? null,
|
||||
picked_weight: loadedRow?.pickedWeight ?? null,
|
||||
pick_done: pickDone,
|
||||
inbound_photos: pickInboundPhotosForLine(inboundPhotosBySkuSupplier, sku, itemSupplier),
|
||||
|
||||
@@ -125,6 +125,13 @@ export interface OrderItem {
|
||||
can_hard_delete?: boolean;
|
||||
/** 验收合格入库实收合计;未验为空,仅展示不落明细保存 */
|
||||
received_qty?: number | null;
|
||||
/** 持久实收单位(received_qty 配套) */
|
||||
received_unit?: string | null;
|
||||
/** 下单客户计划留档(只读,不参与计算) */
|
||||
demand_qty?: number | null;
|
||||
demand_unit?: string | null;
|
||||
/** 实收来源阶段,仅用于判断持久实收是否可用 */
|
||||
received_stage?: number | null;
|
||||
/** 分拣称重实重;仅展示 */
|
||||
picked_weight?: number | null;
|
||||
stock_cover_qty?: number | null;
|
||||
@@ -296,13 +303,33 @@ export function resolveCoverUnitCost(input: {
|
||||
return Math.round((coverCost / coverQty) * 10000) / 10000;
|
||||
}
|
||||
|
||||
/** 订单详情「计划数量」展示:用下单量快照,避免履约后把结算量当计划 */
|
||||
export function planDisplayQty(item: { quantity?: unknown; ordered_quantity?: unknown }): number {
|
||||
/** 订单详情「计划数量」展示:客户下单计划优先,其次旧订货快照,再回退当前数量 */
|
||||
export function planDisplayQty(item: {
|
||||
quantity?: unknown;
|
||||
ordered_quantity?: unknown;
|
||||
demand_qty?: unknown;
|
||||
}): number {
|
||||
const demand = Number(item.demand_qty);
|
||||
if (Number.isFinite(demand) && demand > 0) return demand;
|
||||
const ordered = Number(item.ordered_quantity);
|
||||
if (Number.isFinite(ordered) && ordered > 0) return ordered;
|
||||
return Number(item.quantity) || 0;
|
||||
}
|
||||
|
||||
/** 订单详情「计划单位」展示:客户下单计划单位优先 */
|
||||
export function planDisplayUnit(item: {
|
||||
unit?: unknown;
|
||||
ordered_unit?: unknown;
|
||||
demand_unit?: unknown;
|
||||
}): string {
|
||||
return (
|
||||
String(item.demand_unit || '').trim() ||
|
||||
String(item.ordered_unit || '').trim() ||
|
||||
String(item.unit || '').trim() ||
|
||||
''
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* **「验收实收」按 (SKU, 供应商) 归集的取键归一化**(2026-10-14 审核整改 D3)。
|
||||
*
|
||||
|
||||
Reference in New Issue
Block a user