Files
SupplierSystem/server/src/services/orderManageItemsService.ts
T
Ubuntu 83825fa2df
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
fix(主系统同步单): 修「标着库存抵扣但抵扣为 0」的卡行 + 放开「同步行可删」(删单仍禁)
开发者 2026-10-17 报障:「订单管理,从配送系统同步过来的订单商品行可以删除,同步过来的商品无法处理」。

生产只读排查(BR005 / ORD_API_20261017_BR005_0001):香蕉 500 斤这一行
supplier_code='STOCK_COVER'、stock_cover_qty=0、履约行 inventory_cover_qty=0,
既没有采购单也没有备货单 ⇒ 既不走库存抵扣也不进采购/备货 ⇒ 验收/分拣拿不到货。
全生产扫一遍只有这 1 行(br005 1 行,其余租户 0 行)。

A)卡行修复
· 迁移 20261056:三条边界**同时**成立才把 supplier_code 改回 'UNASSIGNED'
  (① stock_cover_qty≤0 ② 履约行也没有手动抵扣量 ③ 未退货)——只纠正标记、不删行、
  不误伤"真抵扣"和"手动选择抵扣商品"的行;遍历所有 tenant_* + tenant_template,幂等。
· 增量自愈:inventoryStockCoverService.normalizeStockCoverSupplierFlags(),在整单抵扣收尾
  (补完 FIFO 批次计划之后)调用;失败只记日志、不影响本次抵扣结果。

B)同步行可删(口径变更,开发者 2026-10-17 授权,覆盖 2026-10-10 的"禁删")
· 服务层不再对主系统单抛 409 main_system_item_locked;
· 删除时**同一事务**把该行行级台账(main_system_order_import_items,按 our_order_item_id 反查)
  置 disposition='cancelled' ⇒ needsAppendToOrder 不再追加、台账 upsert 的处置是粘性的
  ⇒ 下一轮对账/主系统 webhook 追加不会把它塞回来;
· markPrepDisposition 增加可选 client,保证处置与删除同事务提交(失败只记日志,巡检兜底);
· 界面:主系统行也出现删除按钮(复用既有 title 文案,无新增文案);
· **删单仍然禁止**(orderDeleteService.assertNotMainSystemOrder 未动),缺货按钮保留。

验证:
· 本地真库(事务内造 3 行 + ROLLBACK):假标记行 STOCK_COVER/0 → UNASSIGNED;
  STOCK_COVER/500 与"履约行 manual cover 500"两行保持 STOCK_COVER(不误伤)
· cd server && npx tsc --noEmit → 0 错;npm run typecheck(web)→ 0 错
· 新增用例:stockCoverSupplierFlagRepair 5 条、mainSystemItemDeletable 9 条,全过;
  相关后端子集 35 文件 / 536 用例通过(independentInbound 有 1 条既有失败,与基线同)
· 前端 order 相关 42 文件 / 245 用例全过
· 设计门禁:8 通过 / 1 已知红 check-ai-cost / verify-facts 因本地缺 tenant_br003 红(均基线)
2026-10-17 16:51:09 +08:00

2703 lines
112 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 { randomUUID } from 'crypto';
import type { PoolClient } from 'pg';
import { getRawPoolConnect, pool } from '../db';
import { INTERNAL_PURCHASER_CODE } from './allocationRules';
import { INDEPENDENT_INBOUND_CUSTOMER_CODE } from './independentInbound';
import { isStockCoverSupplierCode } from './allocationRules';
import { ensureSupplierStatementsForOrder, upsertCustomerStatementForOrder } from './financeReconciliationService';
import { reconcileOrderPurchaseFromLatestInspections } from './inspectionComplianceService';
import { reconcileExtraDishPurchaseCosts } from './orderCostPostingService';
import { syncInspectionFulfillmentIdentityForOrder } from './inspectionDisplayService';
import { normalizeProcessingOwner, requiresWarehouseProcessing, seedOrderItemUnitCost } from './processingMethodUtils';
import { isSupplierSkipInbound, supplierSkipInboundExistsSql } from './supplierSkipInbound';
import { amendPurchaseActual } from './purchaseAmendService';
import { releaseReservationsForOrderItem } from './inventoryStockCoverService';
import {
syncWarehouseProcessingDemandForOrder,
syncWarehouseProcessingDemandForOrderAfterCommit,
listCompletedWarehouseDemandItemIds,
} from './processingDemandSheetService';
import {
purchaserDirectAllocation,
ensureCompletedExtraDishPurchase,
reprocessOrderAllocation,
syncOpenPurchaseQtyForOrder,
syncPurchaseQtyFromFulfillments,
type ReprocessAllocationOptions,
} from './orderAllocationService';
import { withAllocationSlot } from './allocationConcurrency';
import { deleteUnworkedPickingRowsForItems } from './pickingService';
import { markPrepDisposition } from './mainSystemPrepLedger';
import {
countPreparationLinks,
linkOrderItemToInventoryCover,
listUncoveredOrderItems,
recalcPreparationQty,
} from './orderItemFulfillmentService';
import { syncSkuCostFromPreparation } from './preparationCostService';
import { upsertCustomerQuoteItemCosts } from './quoteSheetService';
import { getTenantDbStore } from './tenantDbContext';
import { loadWeightUnitFactors, sumWeightInJin } from './unitConversionService';
import { writeAuditLog } from './auditService';
import {
assertMainSystemPriceQtyReviewed,
isEnabled as isPriceQtyRequestEnabled,
notifyMainSystemPriceQtyChanges,
isMainSystemAllocatedLines,
type PriceQtyChange,
} from './mainSystemPriceQtyRequest';
import {
buildOrderItemsEditAuditPayload,
type ExistingOrderItemForAudit,
} from './orderItemsEditAudit';
import {
assertDeliveryDateOnOrAfterOrderDate,
getOrderDateFromCreatedAt,
normalizeDateOnly,
} from './orderDeliveryDate';
import { calcItemAmount } from './orderPricingService';
import { inventoryLogVoidedByReturnSql, notVoidedByLineReturnSql } from './inboundCoverageSql';
import { ensureCatalogSkuForPurchaserOrder } from './skuProvisioningService';
import {
markOrderItemReturned,
orderItemHasInspectionInbound,
removeOrReturnOrderItem,
} from './orderItemReturnService';
import {
orderItemHasInspectionInboundForSupplier,
reattributeInboundFulfillment,
} from './inboundFulfillmentReattributeService';
import { findSupplierSwitchLock, supplierSwitchLockError } from './preparationSwitchLock';
import { assertNoPendingManualAfterSaleForOrderItem } from './afterSaleLifecycleService';
/**
* 新增明细是否计加菜:
* - 配送中起(≥60):算加菜(司机自买,不入库)
* - 待配送及之前(<60):正常修改;50 只对新行走分配入库
*/
export function resolveNewRowIsExtraDish(
orderStatus: number
): boolean {
const status = Number(orderStatus) || 0;
return status >= 60;
}
const TENANT_SCHEMA_RE = /^tenant_[a-z0-9_-]{2,30}$/;
/** 明细保存事务:独立连接,避免 TENANT_REQUEST_CLIENT 复用连接时被嵌套 BEGIN/ROLLBACK 冲掉 */
async function connectExclusiveTenantClient(): Promise<PoolClient> {
const rawConnect = getRawPoolConnect();
const client = await rawConnect();
const store = getTenantDbStore();
const schemaName = String(store?.schemaName || '').trim();
const branchCode = String(store?.branchCode || '').trim();
// FORCE RLS 下 owner 也依赖 app.branch_code;只切 search_path 会导致 FOR UPDATE 看不到本分公司订单
if (schemaName && TENANT_SCHEMA_RE.test(schemaName)) {
await client.query(`SELECT set_config('search_path', $1, false)`, [`${schemaName}, public`]);
}
if (branchCode) {
await client.query(`SELECT set_config('app.branch_code', $1, false)`, [branchCode]);
}
return client;
}
async function resetExclusiveTenantClient(client: PoolClient): Promise<void> {
await client.query(`SELECT set_config('search_path', 'public', false)`);
await client.query(`SELECT set_config('app.branch_code', '', false)`);
}
/** 待验收(40)起非管理员不可改明细(与 Web OrderManagement 对齐) */
export const ORDER_ITEMS_LOCKED_FROM_STATUS = 40;
const ORDER_COMPLETED_STATUS = 90;
/** 配送中起:加菜成本可直接入账(不建自采) */
const EXTRA_DISH_COST_FROM_STATUS = 60;
export function isPurchaseFulfillmentLockedForOrderItemEdit(status: unknown): boolean {
const normalized = Number(status) || 0;
return normalized === 20 || normalized === 30;
}
export type OrderManageItemInput = {
id?: string | null;
item_name?: string | null;
sku_code?: string | null;
quantity?: number | string | null;
unit?: string | null;
price?: number | string | null;
/** 订单列表展示/编辑的成本价;保存时写入客户生效报价单 */
cost_price?: number | string | null;
amount?: number | string | null;
processing_method?: string | null;
processing_owner?: string | null;
category_code?: string | null;
category_name?: string | null;
supplier_code?: string | null;
sku_name?: string | null;
is_extra_dish?: boolean | string | null;
/** 小程序采购员加单:确认保存时在同一事务建品 */
create_product?: boolean | string | null;
/** 录单明细备注;展示用 */
remark?: string | null;
/**
* 商品规格(`order_items.spec`;2026-10-16 起可在订单详情直接改)。
* ⚠️ **区分「没传」与「传了空」**:本服务用 `hasOwnProperty('spec')` 判断是否要写,
* 没传的入口(小程序/MCP)保存时保持原值,不会把已存规格抹掉。
*/
spec?: string | null;
/** 弱引用质检报告库;MVP 不计硬门禁 */
quality_report_id?: string | null;
/** 可挂多份(多供应商) */
quality_report_ids?: string[] | null;
is_returned?: boolean | string | null;
};
function trimText(value: unknown): string {
return String(value || '').trim();
}
function isTempId(id: string): boolean {
return !id || id.startsWith('new-') || id.startsWith('tmp-');
}
function isTruthyFlag(value: unknown): boolean {
return value === true || value === 'true' || value === 1 || value === '1';
}
/**
* 加菜(含新增行)销售价为 0 的商品名,供保存前硬拦。
*
* `allowUnpriced=true` 时直接放行 —— 与 `orderZeroPriceGuard.assertNoZeroPriceItems` 同一口径。
* 谁传它:**主系统导入的系统追加路径**(`mainSystemOrderImport` 已传,见其 `allowUnpriced` 注释)。
*
* ⚠️ 为什么必须让这道门读这个开关(2026-10-14 真库实测):
* 主系统**先分配、后定价**(实测同一批 14 行在 11 分钟后才补价),这批追加行售价 0。
* 本判据把所有**新行**都当加菜 ⇒ 抛 `zero_price_blocked` ⇒ **整批追加回滚**。
* webhook 重试与定时对账走同一条路径 ⇒ 不自愈,只能等主系统补价;
* 期间现象就是「主系统分过来的商品在子系统静默丢失」(`ORD_API_20261014_BR002_0001` 只落了 1/15 行)。
* 该路径本来就传了 `allowUnpriced: true` 并写明「不能被既有零价行挡住」,是本判据没有遵守。
*/
export function listZeroSaleExtraDishNames(
items: OrderManageItemInput[],
existingExtraDishIds: Set<string> = new Set(),
opts: { allowUnpriced?: boolean; independentInbound?: boolean } = {}
): string[] {
// 主系统未定价 ⇒ 售价 0 是正常口径,硬拦会让整批分配行丢失(见上)
if (opts.allowUnpriced === true) return [];
/**
* **独立进货单**(哨兵客户 `__INDEPENDENT_INBOUND__`)不销售 ⇒ 售价恒为 0 是设计如此,
* 这条门对它不成立(2026-10-16 开发者报障:独立进货加菜被「销售价为 0,请先补价后再保存」拦下,
* 前端放开后后端必须同口径,否则照样 400)。
* 与录单页既有口径一致(`CustomerOrder.tsx` 的零价拦截排除独立进货客户)。
*/
if (opts.independentInbound === true) return [];
const names: string[] = [];
for (const row of items) {
const id = trimText(row.id);
const isNew = isTempId(id);
const isExtra =
isNew || isTruthyFlag(row.is_extra_dish) || (Boolean(id) && existingExtraDishIds.has(id));
if (!isExtra) continue;
if (isTruthyFlag(row.is_returned)) continue;
if ((Number(row.price) || 0) > 0) continue;
names.push(trimText(row.item_name) || trimText(row.sku_name) || '未命名商品');
}
return names;
}
function isUnassignedSupplier(supplierCode?: string | null): boolean {
const code = String(supplierCode || '').trim();
return !code || code === INTERNAL_PURCHASER_CODE || code === 'UNASSIGNED' || code === 'INTERNAL';
}
/** 保留 INTERNAL 表示采购员明确选择了"自采",不转为 null 以避免被智能分配覆盖 */
function normalizeSupplierCode(supplierCode?: string | null): string | null {
const code = String(supplierCode || '').trim();
if (!code) return null;
if (code === 'UNASSIGNED') return null;
// INTERNAL 保留,表示采购员明确选择了自采
return code;
}
function isSelfPurchaseSupplier(supplierCode?: string | null): boolean {
const code = String(supplierCode || '').trim();
return code === INTERNAL_PURCHASER_CODE || code === 'INTERNAL';
}
/** 已选外部供应商(非空 / 未分配 / 自采) */
/**
* 已选**外部厂商**(非空 / 未分配 / 自采 / 库存抵扣)。
* 2026-10-14:库存抵扣(STOCK_COVER)**不是**外部厂商 —— 否则保存明细会
* 取消在途自采单、删分拣明细(分拣出库冻结面),见设计文 §6.1.4。
*/
export function isAssignedExternalSupplier(supplierCode?: string | null): boolean {
const code = normalizeSupplierCode(supplierCode);
return Boolean(code) && !isSelfPurchaseSupplier(code) && !isStockCoverSupplierCode(code);
}
/**
* 手选保存时要作废本行未入库自采的明细。
* 含库供应商列未变(详情盖成自采)以及 from 为空。提交仍为自采的不在此列。
*/
export function collectSupplierSwitchItemIds(input: {
changes: Array<{
item_id: string;
to_supplier_code: string | null;
is_extra_dish?: boolean;
}>;
openSelfPurchaseItemIds: string[];
}): string[] {
const ids = new Set<string>();
for (const row of input.changes) {
if (row.is_extra_dish) continue;
const id = String(row.item_id || '').trim();
if (!id || !isAssignedExternalSupplier(row.to_supplier_code)) continue;
ids.add(id);
}
for (const raw of input.openSelfPurchaseItemIds) {
const id = String(raw || '').trim();
if (id) ids.add(id);
}
return [...ids];
}
/**
* 「本次写明细要不要跑分配规则引擎」的判定(**纯函数**,便于单测)。
*
* - `preferItemSuppliers`:手动分配页保存 —— 按明细已有供应商落履约,不跑规则改写;
* - `keepNewItemsUnassigned`:**主系统导入** —— 同上「只认已有供应商」语义,
* 但**新插入的行也不许进规则引擎**(不许替人分配好给谁),抵扣后缺口保持「未分配」。
*
* 两个标志都**不**影响整单抵扣:`reprocessOrderAllocation` 入口处无条件先跑
* `applyStockCoverForOrder`(「先抵扣」永远发生在分配之前)。
* 见 docs/design/20261013-主系统导入单默认未分配(先抵扣后人工选择供应商或自采).md §2.1/§2.2
*/
export function resolveWriteAllocationIntent(params: {
preferItemSuppliers?: boolean;
keepNewItemsUnassigned?: boolean;
}): { useItemSuppliers: boolean; autoAllocateNewItems: boolean } {
const keepUnassigned = params.keepNewItemsUnassigned === true;
return {
useItemSuppliers: keepUnassigned || params.preferItemSuppliers === true,
autoAllocateNewItems: !keepUnassigned,
};
}
/** 与 cancelOpenPendingPurchasesForItem 同一关联:source_id 本行或履约 purchase_code */
async function listOpenSelfPurchaseItemIds(
db: PoolClient,
orderCode: string,
itemIds: string[]
): Promise<string[]> {
const ids = [...new Set(itemIds.map((id) => String(id || '').trim()).filter(Boolean))];
if (!ids.length) return [];
const found = await db.query(
`SELECT DISTINCT item_id FROM (
SELECT po.source_id AS item_id
FROM purchase_orders po
WHERE po.order_code = $1
AND po.purchase_status <> 40
AND po.source_id::text = ANY($2::text[])
UNION
SELECT f.order_item_id::text
FROM order_item_fulfillments f
INNER JOIN purchase_orders po ON po.purchase_code = f.purchase_code
WHERE po.order_code = $1
AND po.purchase_status <> 40
AND f.order_item_id = ANY($3::uuid[])
) open_po
WHERE item_id IS NOT NULL AND TRIM(item_id) <> ''`,
[orderCode, ids, ids]
);
return found.rows.map((row) => String(row.item_id || '').trim()).filter(Boolean);
}
function normalizeQualityReportIds(row: OrderManageItemInput): string[] {
const fromArr = Array.isArray(row.quality_report_ids)
? row.quality_report_ids.map((x) => String(x || '').trim()).filter(Boolean)
: [];
const single = trimText(row.quality_report_id);
const ids = fromArr.length ? fromArr : single ? [single] : [];
return [...new Set(ids)];
}
/**
* 明细可编辑矩阵(与 Web OrderManagement 对齐):
* - ≥90:管理员或调用方 canEditCompleted(采购员改单)
* - 40–89:须 canForceEdit(order_force_edit;内置 admin/super_admin 默认具备)
* - <40:有订单写权限即可(由路由鉴权)
*/
export function canEditOrderItemsForStatus(
orderStatus: number,
isAdmin = false,
canEditCompleted = false,
canForceEdit = false
): boolean {
const status = Number(orderStatus) || 0;
if (status >= ORDER_COMPLETED_STATUS) return Boolean(isAdmin || canEditCompleted);
if (status >= ORDER_ITEMS_LOCKED_FROM_STATUS) return Boolean(canForceEdit);
return true;
}
/**
* 完成单保存时:用本单已填备货/自采价补空报价成本,使财务报价成本有数。
*/
async function fillMissingQuoteCostsFromOrderSupply(
client: PoolClient,
orderCode: string,
branchCode?: string | null
): Promise<void> {
const rows = await client.query(
`SELECT sku_code, MAX(price)::float AS price, MAX(sale_price)::float AS sale_price FROM (
SELECT sp.sku_code, sp.purchase_price AS price, oi.price AS sale_price
FROM supplier_preparations sp
LEFT JOIN order_items oi ON oi.order_code = sp.order_code AND oi.sku_code = sp.sku_code
WHERE sp.order_code = $1
AND sp.sku_code IS NOT NULL AND TRIM(sp.sku_code) <> ''
AND COALESCE(sp.purchase_price, 0) > 0
AND COALESCE(sp.is_stockout, false) = false
UNION ALL
SELECT po.sku_code, COALESCE(NULLIF(po.actual_price, 0), po.purchase_price) AS price, oi.price AS sale_price
FROM purchase_orders po
LEFT JOIN order_items oi ON oi.order_code = po.order_code AND oi.sku_code = po.sku_code
WHERE po.order_code = $1
AND po.sku_code IS NOT NULL AND TRIM(po.sku_code) <> ''
AND COALESCE(po.actual_price, po.purchase_price, 0) > 0
AND po.purchase_status >= 20
) t
GROUP BY sku_code`,
[orderCode]
);
for (const row of rows.rows) {
const sku = String(row.sku_code || '').trim();
const price = Number(row.price);
const salePrice = Number(row.sale_price);
if (!sku || !(price > 0)) continue;
await syncSkuCostFromPreparation(sku, price, client, branchCode || null, {
syncQuoteSheet: true,
onlyIfQuoteCostZero: true,
salePrice,
onlyIfQuoteSalePriceZero: true,
});
}
}
/** 加菜未履约:用库存覆盖挂履约,避免断言失败且不新建采购。完成单可覆盖全部未履约行。 */
async function coverUnfulfilledItemsAsInventoryForCompleted(
client: PoolClient,
orderCode: string,
opts?: { onlyExtraDish?: boolean }
): Promise<void> {
const uncovered = await listUncoveredOrderItems(client, orderCode, { includeHistoryRepair: true });
for (const row of uncovered) {
const qtyResult = await client.query(
`SELECT COALESCE(quantity, 0)::float AS quantity, COALESCE(is_extra_dish, false) AS is_extra_dish
FROM order_items WHERE id = $1::uuid`,
[row.id]
);
const meta = qtyResult.rows[0];
if (opts?.onlyExtraDish && !isTruthyFlag(meta?.is_extra_dish)) continue;
const qty = Math.max(0, Number(meta?.quantity) || 0);
if (qty <= 0) continue;
// 只挂履约(写 order_item_fulfillments.inventory_cover_qty),**不写** order_items.stock_cover_qty。
//
// 为什么不写 stock_cover_qty:stock_cover_qty 的语义是「已被可用库存抵扣」,
// 正规路径(inventoryStockCoverService.applyStockCoverForOrderItem)写它时必定同时
// 建 inventory_reservations(status=10) 并写一条 stock_cover 成本行。
// 本函数发生在订单状态 >=60 的重新保存路径,既不建预留也不写成本,
// 若在此抬高 stock_cover_qty,就会让「有抵扣」与「库存真被占用」脱钩:
// - pendingBackfillQtyService:341/358、orderAutoAdvanceService:410 用
// GREATEST(stock_cover_qty, inventory_cover_qty) → 待回填/强推被判为已满足;
// - recalcPreparationQty 把 prepare_qty 重算为 0;备货量聚合认为已覆盖;不进竞价候选;
// - 而库存实际未被占用(无预留即无出库)→ 账面库存虚高。
//
// 断言 side 不需要 stock_cover_qty:listUncoveredOrderItems 的判据是
// COALESCE(oi.stock_cover_qty, f.inventory_cover_qty, 0) >= quantity
// 本函数已把 inventory_cover_qty 写成整行量,断言即可通过,目的已达。
// 见 docs/todo/20260915-模块流转总图与设计对照.md §4.3 第 3 项
await linkOrderItemToInventoryCover(client, {
orderItemId: row.id,
orderCode,
inventoryCoverQty: qty,
});
}
}
async function deleteOrderItemWithDependencies(
client: PoolClient,
orderCode: string,
item: {
id: string;
sku_code?: string | null;
item_name?: string | null;
supplier_code?: string | null;
},
options?: { keepItem?: boolean; preserveFulfilledHistory?: boolean }
): Promise<void> {
const itemId = String(item.id || '');
if (!itemId || isTempId(itemId)) return;
const itemLabel = trimText(item.item_name || item.sku_code) || '商品';
const sku = trimText(item.sku_code);
const itemName = trimText(item.item_name);
const supplierCode = trimText(item.supplier_code);
const fulfillment = await client.query(
`SELECT supplier_preparation_id, purchase_code
FROM order_item_fulfillments
WHERE order_item_id = $1::uuid
LIMIT 1`,
[itemId]
);
const linkedPreparationId = fulfillment.rows[0]?.supplier_preparation_id
? String(fulfillment.rows[0].supplier_preparation_id)
: null;
const linkedPurchaseCode = fulfillment.rows[0]?.purchase_code
? String(fulfillment.rows[0].purchase_code)
: null;
// 仓内加工会把成品自采单挂到 processing_demand_items。删除订单行时,
// 需求单随后会重算,但该采购单不会再被普通履约清理逻辑命中,容易
// 残留在入库/自采列表。先记录这类采购单,解除履约后按引用数定向清理。
const warehouseDemandPurchases = await client.query(
`SELECT DISTINCT po.purchase_code, po.purchase_status, po.self_processed
FROM purchase_orders po
LEFT JOIN order_item_fulfillments f ON f.purchase_code = po.purchase_code
JOIN processing_demand_items di ON (
di.order_item_id = $2::uuid
AND (di.order_item_id = f.order_item_id OR po.source_id = di.order_item_id::text)
)
JOIN processing_tasks pt ON pt.id = di.task_id
AND pt.source_type = 'demand'
WHERE po.order_code = $1
AND ($3::text IS NULL OR po.purchase_code = $3)` ,
[orderCode, itemId, linkedPurchaseCode]
);
const purchases = await client.query(
`SELECT purchase_code, purchase_status, source_id, sku_code
FROM purchase_orders
WHERE order_code = $1
AND (
($2::text IS NOT NULL AND purchase_code = $2)
OR source_id = $3
OR (
$4::text <> '' AND sku_code = $4
AND NOT EXISTS (
SELECT 1 FROM order_item_fulfillments f
WHERE f.purchase_code = purchase_orders.purchase_code
AND f.order_item_id IS DISTINCT FROM $5::uuid
)
)
)`,
[orderCode, linkedPurchaseCode, itemId, sku || '', itemId]
);
const relatedPurchases = purchases.rows;
const inbound = await orderItemHasInspectionInbound(client, orderCode, item);
for (const row of relatedPurchases) {
const status = Number(row.purchase_status ?? 10);
if (
isPurchaseFulfillmentLockedForOrderItemEdit(status) &&
inbound &&
!options?.preserveFulfilledHistory
) {
throw Object.assign(new Error(`「${itemLabel}」已验收入库,无法删除(请走退货)`), {
status: 409,
code: 'fulfillment_conflict',
});
}
}
// 履约挂载的备货 + 同单同 SKU/名称且未被其它明细引用的备货(无挂载时的孤儿)
const preps = await client.query(
`SELECT sp.id, sp.prepare_status, sp.sku_code, sp.item_name, sp.supplier_code
FROM supplier_preparations sp
WHERE sp.order_code = $1
AND COALESCE(sp.is_history_repair, false) = false
AND (
($2::uuid IS NOT NULL AND sp.id = $2::uuid)
OR (
(
($3::text <> '' AND sp.sku_code = $3)
OR ($3::text = '' AND $4::text <> '' AND TRIM(COALESCE(sp.item_name, '')) = $4)
)
AND ($5::text = '' OR COALESCE(sp.supplier_code, '') = $5)
AND NOT EXISTS (
SELECT 1 FROM order_item_fulfillments f
WHERE f.supplier_preparation_id = sp.id
AND f.order_item_id IS DISTINCT FROM $6::uuid
)
)
)`,
[
orderCode,
linkedPreparationId,
sku || '',
itemName || '',
supplierCode || '',
itemId,
]
);
const relatedPreps = preps.rows;
for (const row of relatedPreps) {
if (
Number(row.prepare_status ?? 10) === 30 &&
inbound &&
!options?.preserveFulfilledHistory
) {
throw Object.assign(new Error(`「${itemLabel}」已验收入库,无法删除(请走退货)`), {
status: 409,
code: 'fulfillment_conflict',
});
}
}
await releaseReservationsForOrderItem(client, itemId);
// 删履约链接会触发 trg_cleanup_orphan_fulfillments;采购员改单须保留完成态自采单(status 20/30)
await client.query(
`SELECT set_config('app.preserve_fulfilled_history', $1, true)`,
[options?.preserveFulfilledHistory ? 'true' : 'false']
);
await client.query(`DELETE FROM order_item_fulfillments WHERE order_item_id = $1::uuid`, [itemId]);
// 直送免入库的核货行随明细删除,避免配送核货列表残留孤儿行(真实分拣行不动)
await client.query(
`DELETE FROM picking_items pi
WHERE pi.order_item_id = $1::uuid
AND EXISTS (
SELECT 1 FROM order_items oi
WHERE oi.id = pi.order_item_id
AND ${supplierSkipInboundExistsSql('oi.supplier_code')}
)`,
[itemId]
);
/**
* 取消履约(删行)后清掉**还没动过**的拣货行(2026-10-12 真库事故 `ORD_API_20261012_BR003_0002`):
* 此前只清「直送/免入库」行 ⇒ 删掉的明细在拣货单里留下孤儿行(`order_items` 都没了,
* 分拣对话框照样显示、还带 FIFO 出库批次,并让完成分拣报「项未确认」)。
* 已拣/已核货的行保留(真实分拣行不动)。
*/
await deleteUnworkedPickingRowsForItems(client, [itemId]);
if (!options?.preserveFulfilledHistory && sku) {
await client.query(
`DELETE FROM inspections
WHERE order_code = $1
AND sku_code IS NOT DISTINCT FROM $2
AND NULLIF(TRIM(inbound_batch_no), '') IS NULL`,
[orderCode, sku]
);
}
for (const row of relatedPurchases) {
if (
options?.preserveFulfilledHistory &&
isPurchaseFulfillmentLockedForOrderItemEdit(row.purchase_status)
) {
continue;
}
const refs = await client.query(
`SELECT COUNT(*)::int AS count FROM order_item_fulfillments WHERE purchase_code = $1`,
[row.purchase_code]
);
if (Number(refs.rows[0]?.count) === 0) {
await client.query(`DELETE FROM purchase_orders WHERE purchase_code = $1`, [row.purchase_code]);
} else {
await syncPurchaseQtyFromFulfillments(String(row.purchase_code), client);
}
}
for (const row of relatedPreps) {
if (options?.preserveFulfilledHistory && Number(row.prepare_status ?? 10) === 30) {
continue;
}
if ((await countPreparationLinks(client, String(row.id))) === 0) {
await client.query(`DELETE FROM supplier_preparations WHERE id = $1`, [row.id]);
}
}
if (sku && supplierCode) {
await client.query(
`DELETE FROM allocation_tasks
WHERE order_code = $1 AND sku_code = $2 AND supplier_code = $3`,
[orderCode, sku, supplierCode]
);
}
// 删除仅由当前订单行持有、且尚未形成实际入库的仓内加工成品采购单。
// 已有实采/入库语义的单据不自动删除,交由退货/来源更正流程处理。
for (const row of warehouseDemandPurchases.rows) {
const purchaseCode = String(row.purchase_code || '').trim();
if (!purchaseCode) continue;
const refs = await client.query(
`SELECT COUNT(*)::int AS count
FROM order_item_fulfillments
WHERE purchase_code = $1`,
[purchaseCode]
);
if (Number(refs.rows[0]?.count) > 0) continue;
const status = Number(row.purchase_status) || 0;
const selfProcessed = Boolean(row.self_processed);
if (![10, 20, 32].includes(status)) continue;
if (status === 20 && !selfProcessed) continue;
const inbound = await client.query(
`SELECT 1 FROM inspections
WHERE COALESCE(actual_qty, 0) > 0
AND (
processing_details->>'purchase_code' = $1
OR processing_details->'purchase_codes' ? $1
)
LIMIT 1`,
[purchaseCode]
);
if (inbound.rowCount) continue;
await client.query(`DELETE FROM purchase_orders WHERE purchase_code = $1`, [purchaseCode]);
}
if (!options?.keepItem) {
await client.query(`DELETE FROM order_items WHERE id = $1 AND order_code = $2`, [
itemId,
orderCode,
]);
}
}
/**
* 采购员改单:自采计划随订单需求更新;已产生实采语义的单据同时更新实采量。
* 采购价/实采价保持不变,金额仅按原价与新实采量重算。
*/
async function syncPurchaserLinkedPurchaseSnapshots(
client: PoolClient,
orderCode: string,
branchCode: string | null,
operatorId?: string | null,
operatorRole?: string | null
): Promise<void> {
const linkedResult = await client.query(
`WITH target_purchase AS (
SELECT DISTINCT f.purchase_code
FROM order_item_fulfillments f
JOIN order_items oi ON oi.id = f.order_item_id
WHERE oi.order_code = $1
AND f.purchase_code IS NOT NULL
),
linked AS (
SELECT
f.purchase_code,
COALESCE(
SUM(GREATEST(0, oi.quantity - COALESCE(oi.stock_cover_qty, 0))),
0
)::numeric AS quantity,
CASE
WHEN COUNT(DISTINCT NULLIF(TRIM(oi.unit), '')) = 1
THEN MAX(NULLIF(TRIM(oi.unit), ''))
ELSE NULL
END AS unit
FROM order_item_fulfillments f
JOIN order_items oi ON oi.id = f.order_item_id
JOIN target_purchase target ON target.purchase_code = f.purchase_code
GROUP BY f.purchase_code
)
SELECT po.purchase_code, po.purchase_status, po.actual_qty,
po.actual_price, po.purchase_price, linked.quantity, linked.unit
FROM linked
JOIN purchase_orders po ON po.purchase_code = linked.purchase_code
WHERE po.purchase_status <> 40`,
[orderCode]
);
for (const row of linkedResult.rows) {
const purchaseCode = String(row.purchase_code || '');
const quantity = Number(row.quantity) || 0;
const unit = trimText(row.unit) || null;
await client.query(
`UPDATE purchase_orders
SET purchase_qty = $2::numeric
WHERE purchase_code = $1 AND purchase_status <> 40`,
[purchaseCode, quantity]
);
const status = Number(row.purchase_status) || 0;
const actualPrice =
Number(row.actual_price) > 0
? Number(row.actual_price)
: Number(row.purchase_price) > 0
? Number(row.purchase_price)
: 0;
if ((status === 20 || status === 30) && actualPrice > 0 && branchCode) {
await amendPurchaseActual(
{
purchaseCode,
branchCode,
actualQty: quantity,
actualPrice,
unit,
operatorId,
operatorRole,
skipOrderItemSync: true,
preserveOrderEnteredCost: true,
},
client
);
} else if (row.actual_qty != null) {
await client.query(
`UPDATE purchase_orders
SET actual_qty = $2::numeric,
total_amount = CASE
WHEN COALESCE(NULLIF(actual_price, 0), NULLIF(purchase_price, 0)) IS NOT NULL
THEN ROUND(
$2::numeric * COALESCE(NULLIF(actual_price, 0), NULLIF(purchase_price, 0)),
2
)
ELSE total_amount
END
WHERE purchase_code = $1 AND purchase_status <> 40`,
[purchaseCode, quantity]
);
}
}
}
/**
* 比对「已存在的订单行」的价格/数量是否被本次改明细改动(供主系统行的改价改量守卫使用)。
* 只比较已存在的行(新增行不算改价改量);已退货行跳过。
*
* ⚠️ 2026-10-14 开发者令「这块需要解封,当前加工方式是自己设置了」:
* **加工方式/加工方已从"受管字段"移出**(原 `collectMainSystemProcessingChanges` +
* `main_system_processing_locked` 409 已删除)。口径来源:
* docs/design/20261014-主系统加工需求与我方加工决策.md §6.3 D2''、§7 验收 5 ——
* 主系统的 `processingMethod` 只作**提示**(并入行备注),加工方式由**我方**设置。
* 仍保留的锁只有两个:**计划数量**(本节下方)与**配送时间**(`orders.delivery_date` 另一路径)。
*/
function collectMainSystemPriceQtyChanges(
existingMap: Map<
string,
{
id: string;
item_name?: string | null;
price?: number | null;
quantity?: number | null;
unit?: string | null;
is_returned?: boolean | null;
}
>,
incoming: OrderManageItemInput[]
): PriceQtyChange[] {
const EPS = 1e-6;
const changes: PriceQtyChange[] = [];
const normUnit = (value: unknown) => String(value ?? '').trim();
for (const row of incoming) {
const id = trimText(row.id);
if (!id || isTempId(id)) continue;
const existing = existingMap.get(id);
if (!existing || existing.is_returned) continue;
const name = trimText(existing.item_name) || trimText(row.item_name) || id;
const oldPrice = Number(existing.price) || 0;
const newPrice = Number(row.price) || 0;
if (Math.abs(oldPrice - newPrice) > EPS) {
changes.push({ itemId: id, itemName: name, field: 'price', from: oldPrice, to: newPrice });
}
const oldQty = Number(existing.quantity) || 0;
const newQty = Number(row.quantity) || 0;
if (Math.abs(oldQty - newQty) > EPS) {
changes.push({ itemId: id, itemName: name, field: 'quantity', from: oldQty, to: newQty });
}
/**
* **单位**(2026-10-13 开发者确认要上报):此前只比价与量 ⇒ 改单位完全不上报
* (真机反证:只改单位时我方与主系统两侧申请都是 0 条)。只在请求**明确带了非空单位**
* 且与库里不同时才记变更 —— 调用方没传 unit 的入口(小程序部分入口)不受影响。
*/
const oldUnit = normUnit(existing.unit);
const newUnit = normUnit(row.unit);
if (newUnit && oldUnit !== newUnit) {
changes.push({ itemId: id, itemName: name, field: 'unit', fromUnit: oldUnit, toUnit: newUnit });
}
}
return changes;
}
export async function syncOrderManageItems(params: {
orderCode: string;
items: OrderManageItemInput[];
isAdmin?: boolean;
/** 已完成订单可改(admin 或采购员专用通道) */
canEditCompleted?: boolean;
/** 履约中(40–89)强制改明细:order_force_edit */
canForceEdit?: boolean;
/** 手动分配页:保存时按明细供应商落履约,不跑规则改写 */
preferItemSuppliers?: boolean;
/**
* **主系统导入专用**:本次写入的新行**不自动分配**(先库存抵扣,缺口留「未分配」等人工选择)。
*
* 开发者 2026-10-13(真库 BR003 土豆单 `ORD_API_20261013_BR003_0003`):
* 「主系统分配过来的应该是先库存抵扣,然后缺少的部分才是进行选择分配给供应商还是自采去采购,
* **不能替他直接分配好给谁**;而且分配给供应商的默认是直接供应完成,导致库存抵扣也无法生效。」
*
* 不传 ⇒ 维持原行为(规则引擎定供应商 / 转自采)。只有主系统导入的建单与追加两条路径传 true,
* Web 改明细、小程序下单、手动分配页一律不传。
* 见 docs/design/20261013-主系统导入单默认未分配(先抵扣后人工选择供应商或自采).md §2
*/
keepNewItemsUnassigned?: boolean;
/** 订单详情/小程序改单须校验创建后可修改时限;手动分配页可关闭 */
enforceEditWindow?: boolean;
/** 采购员专用改单:已履约删行保留历史采购/验收/已完成备货 */
preserveFulfilledHistory?: boolean;
/** 采购员专用改单:同步关联自采计划、单位及已有实采数量 */
syncPurchaserPurchaseSnapshots?: boolean;
/** 小程序采购员加单直接分配:仅处理本次新增行,不走 Web 智能分配引擎 */
purchaserDirectAllocation?: { purchaserCode: string };
/** 小程序采购员加单可在保存事务内新建/复用商品档案 */
provisionPurchaserOrderSkus?: boolean;
/**
* 主系统导入的**系统追加**路径专用:放行「向主系统单新增行」。
* 开发者 2026-10-12:主系统分配单**子系统不能新增商品**(只能主系统添加后分配);
* 但导入本身就是要追加主系统新分配的行 ⇒ 只有它带这个标志。
*/
allowMainSystemAppend?: boolean;
/**
* 放行订单内的零价明细(透传给分配)。默认 false(硬拦)。
* 追加行专用:主系统分配过来的备货任务,其成本价=我们的销售价,那边没定价时就是 0;
* 这类订单再追加新分配的行时,不能被已有零价行挡住(用户 2026-10-08 明确允许零价)。
*/
allowUnpriced?: boolean;
/**
* 内部路径专用:本次改价/改量是「跨系统改价改量申请」的**已生效/已审核**落地
* (`mainSystemPriceQtyRequest.applyFinalPriceQtyToOurOrderItem`),跳过"必须走申请"的守卫。
* ⚠️ 除该申请落地外不得传 true —— 传了就等于绕过主系统审核改它的成本价。
*/
mainSystemPriceQtyApproved?: boolean;
operatorId?: string | null;
operatorRoles?: string | null;
/** Web 详情:与明细同一 PATCH 写订单头,避免先走 /api/data */
orderPatch?: {
delivery_date?: string | null;
delivery_time_slot?: string | null;
delivery_address?: string | null;
remark?: string | null;
} | null;
}): Promise<{
total_amount: number;
total_weight: number;
items: Array<Record<string, unknown>>;
allocation?: Awaited<ReturnType<typeof reprocessOrderAllocation>>;
allocation_soft_warnings?: string[];
statement_sync?: 'created' | 'updated' | 'skipped' | 'empty';
cost_reconciled?: boolean;
extra_dish_cost_posted?: boolean;
quote_cost_sync?: {
quote_sheet_code: string | null;
updated: number;
inserted: number;
requested: number;
};
}> {
const orderCode = trimText(params.orderCode);
const incoming = Array.isArray(params.items) ? params.items : [];
if (!orderCode) {
throw Object.assign(new Error('缺少订单号'), { status: 400, code: 'invalid_request' });
}
if (!incoming.length) {
throw Object.assign(new Error('订单至少保留一项商品'), { status: 400, code: 'invalid_request' });
}
/** 透传给分配:放行订单内既有零价行(默认不放行,保持原硬拦口径) */
const unpricedOpt: ReprocessAllocationOptions = params.allowUnpriced === true
? { allowUnpriced: true }
: {};
const orderResult = await pool.query(
`SELECT order_code, order_status, customer_code, branch_code, created_at, delivery_date
FROM orders WHERE order_code = $1 LIMIT 1`,
[orderCode]
);
const order = orderResult.rows[0];
if (!order) {
throw Object.assign(new Error('订单不存在'), { status: 404, code: 'not_found' });
}
const orderStatus = Number(order.order_status) || 0;
const orderCompleted = orderStatus >= ORDER_COMPLETED_STATUS;
const canPostExtraDishCost = orderStatus >= EXTRA_DISH_COST_FROM_STATUS;
if (
!canEditOrderItemsForStatus(
orderStatus,
Boolean(params.isAdmin),
Boolean(params.canEditCompleted),
Boolean(params.canForceEdit)
)
) {
throw Object.assign(new Error('当前状态不可修改商品明细(履约中须持「强制改单」权限)'), {
status: 400,
code: 'invalid_state',
});
}
let totalAmount = 0;
let totalWeight = 0;
const weightItems: Array<{ quantity: number; unit: string }> = [];
let allocation: Awaited<ReturnType<typeof reprocessOrderAllocation>> | undefined;
let allocationSoftWarnings: string[] = [];
let statementSync: 'created' | 'updated' | 'skipped' | 'empty' | undefined;
let costReconciled = false;
let extraDishCostPosted = false;
let quoteCostSync:
| { quote_sheet_code: string | null; updated: number; inserted: number; requested: number }
| undefined;
const manualSupplierChanges: Array<{
item_id: string;
item_name: string;
sku_code: string | null;
from_supplier_code: string | null;
to_supplier_code: string | null;
is_extra_dish?: boolean;
}> = [];
const realSupplierSavedItemIds: string[] = [];
let previousItemCount = 0;
const autoAllocateItemIds: string[] = [];
/** 分配意图(导入=不跑规则引擎、新行也不许自动分配;其它入口维持原行为) */
const allocationIntent = resolveWriteAllocationIntent({
preferItemSuppliers: params.preferItemSuppliers,
keepNewItemsUnassigned: params.keepNewItemsUnassigned,
});
const newlyInsertedNonExtraIds: string[] = [];
/** 本次新建的**全部**行(含加菜):过账扣点快照只允许写这些行,历史行绝不重刷 */
const newlyInsertedItemIds: string[] = [];
const purchaserDirectAllocationItemIds: string[] = [];
const forceSelfPurchaseItemIds: string[] = [];
let supplierSwitchItemIds: string[] = [];
const inboundFulfillmentReattributes: Array<{
itemId: string;
skuCode: string | null;
itemName: string;
unit: string;
quantity: number;
unitCost: number;
previousSupplierCode: string | null;
nextSupplierCode: string | null;
}> = [];
const inboundReattributeItemIds = new Set<string>();
let existingItemsForAudit: ExistingOrderItemForAudit[] = [];
const client = await connectExclusiveTenantClient();
/** 先改后通知:本次明细保存中被改动的"主系统行"价/量变更(COMMIT 后异步通知主系统) */
let priceQtyNotices: ReturnType<typeof collectMainSystemPriceQtyChanges> = [];
try {
await client.query('BEGIN');
const lockedOrder = await client.query(
`SELECT order_status, branch_code, created_at
FROM orders WHERE order_code = $1 FOR UPDATE`,
[orderCode]
);
if (!lockedOrder.rowCount) {
throw Object.assign(new Error('订单不存在'), { status: 404, code: 'not_found' });
}
const lockedStatus = Number(lockedOrder.rows[0].order_status) || 0;
if (lockedStatus !== orderStatus) {
throw Object.assign(new Error('订单状态已变更,请刷新后重试'), {
status: 409,
code: 'conflict',
});
}
const existingResult = await client.query(
`SELECT id, sku_code, item_name, supplier_code, is_extra_dish, quantity, price, amount, unit_cost,
unit, remark, main_order_code, processing_method, processing_owner,
COALESCE(is_returned, false) AS is_returned, return_code
FROM order_items WHERE order_code = $1`,
[orderCode]
);
previousItemCount = existingResult.rows.length;
existingItemsForAudit = existingResult.rows;
const existingMap = new Map(
existingResult.rows.map((row) => [String(row.id), row as {
id: string;
sku_code: string | null;
item_name: string | null;
supplier_code: string | null;
is_extra_dish?: boolean | null;
is_returned?: boolean | null;
quantity?: number | null;
price?: number | null;
amount?: number | null;
unit_cost?: number | null;
unit?: string | null;
remark?: string | null;
/** 主系统订单号(迁移 20261015 的行级来源标记;可能为 NULL) */
main_order_code?: string | null;
processing_method?: string | null;
processing_owner?: string | null;
}])
);
const existingExtraDishIds = new Set(
existingResult.rows
.filter((row) => Boolean(row.is_extra_dish))
.map((row) => String(row.id))
);
const incomingExistingIds = incoming
.map((row) => trimText(row.id))
.filter((id): id is string => Boolean(id) && !isTempId(id) && existingMap.has(id));
const completedDemandItemIds = await listCompletedWarehouseDemandItemIds(
client,
incomingExistingIds
);
const zeroSaleExtraNames = listZeroSaleExtraDishNames(incoming, existingExtraDishIds, {
// 主系统导入的系统追加:未定价时售价 0 是正常口径,不得整批回滚(见该函数注释)
allowUnpriced: params.allowUnpriced === true,
// 独立进货单:不销售 ⇒ 售价恒为 0(本单客户即哨兵客户,见独立进货设计)
independentInbound:
String(order.customer_code || '').trim() === INDEPENDENT_INBOUND_CUSTOMER_CODE,
});
if (zeroSaleExtraNames.length > 0) {
const shown = zeroSaleExtraNames.slice(0, 5).join('、');
throw Object.assign(
new Error(
`加菜「${shown}${zeroSaleExtraNames.length > 5 ? '…' : ''}」销售价为 0,请先补价后再保存`
),
{
status: 400,
code: 'zero_price_blocked',
zero_price_count: zeroSaleExtraNames.length,
zero_price_items: zeroSaleExtraNames,
}
);
}
const newRowIsExtraDish = resolveNewRowIsExtraDish(orderStatus);
/**
* 主系统分配过来的订单:**子系统不能新增商品行**(只能主系统自己添加后分配过来)—— 开发者 2026-10-12。
*
* 第二道门(界面已隐藏「添加」按钮;改明细另有小程序/MCP 入口,只锁界面会被绕过)。
* 边界(勿错伤):
* · 只对**已存在**的主系统单生效(`existingMap.size > 0`)⇒ 新建单/录单建档不受影响;
* · 加菜(`newRowIsExtraDish`,>=60 的新增行)是本系统合法履约动作 ⇒ 放行;
* · 主系统导入的系统追加路径传 `allowMainSystemAppend` ⇒ 放行;
* · 同理也认 `allowUnpriced`(与上一道零价闸门同一开关,勿只认一个 —— 2026-10-14:
* 两个开关本该同源,只认一个会出现"一道门放行、另一道门照样拦"的半放行状态)。
*/
if (
!params.allowMainSystemAppend &&
!params.allowUnpriced &&
!newRowIsExtraDish &&
existingMap.size > 0
) {
const addingNewRows = params.items.some((row) => {
const id = trimText(row.id);
return !id || isTempId(id) || !existingMap.has(id);
});
if (addingNewRows) {
const ledger = await pool.query(
`SELECT 1 FROM public.main_system_order_imports
WHERE branch_code = $1 AND our_order_code = $2 LIMIT 1`,
[order.branch_code || '', orderCode]
);
if ((ledger.rowCount || 0) > 0) {
throw Object.assign(
new Error('主系统分配过来的订单,子系统不能新增商品(只能由主系统添加后分配过来)'),
{ status: 400, code: 'main_system_order_no_manual_append' }
);
}
}
}
const keptIds = new Set<string>();
for (const row of incoming) {
const id = trimText(row.id);
if (id && !isTempId(id)) keptIds.add(id);
}
/**
* 主系统分配过来的订单:**允许删行**(开发者 2026-10-17 裁决,覆盖 2026-10-10 的"禁删")。
*
* 口径变化的原因:同步过来的行有时确实是废行(例如「标着库存抵扣但抵扣为 0」、或者主系统发错商品),
* 只给「缺货」一条路会让人无路可走。**删单仍然禁止**(`orderDeleteService.assertNotMainSystemOrder` 不动),
* 缺货按钮也保留(那是报给主系统的正规通道)。
*
* ⚠️ 防复发:删掉的行不能在下一轮对账/主系统 webhook 追加里被塞回来 —— 必须**同时**
* 把它这一行的行级台账(`public.main_system_order_import_items`,按 `our_order_item_id` 反查)
* 置 `disposition='cancelled'`;`needsAppendToOrder()` 已把 `cancelled` 列为不再追加,
* 且台账 upsert 只在原值 `pending`/`skipped_stockout` 时才覆盖处置 ⇒ 该处置是粘性的。
*/
const removedIds = [...existingMap.entries()]
.filter(([id, row]) => !keptIds.has(id) && !row.is_returned)
.map(([id]) => id);
if (removedIds.length) {
const mainSystemOrder = await client.query(
`SELECT 1 FROM public.main_system_order_imports
WHERE branch_code = $1 AND our_order_code = $2
LIMIT 1`,
[order.branch_code || null, orderCode]
);
if (mainSystemOrder.rowCount) {
for (const removedId of removedIds) {
try {
const links = await client.query(
`SELECT prep_id FROM public.main_system_order_import_items
WHERE branch_code = $1 AND our_order_item_id = $2::uuid`,
[order.branch_code || null, removedId]
);
for (const link of links.rows as Array<{ prep_id: string | null }>) {
const prepId = String(link?.prep_id || '').trim();
if (!prepId) continue;
await markPrepDisposition({
branchCode: order.branch_code || '',
prepId,
disposition: 'cancelled',
reason: '子系统删除明细(操作员)',
client,
});
}
} catch (error) {
// 台账处置失败**不阻断**删除(否则又变回"删不掉");只记日志,由巡检兜底
console.error(
`[order_items_edit] 主系统行处置落账失败(继续删除)${orderCode} ${removedId}:`,
(error as Error)?.message || error
);
}
}
}
}
// 主系统分配过来的订单:**改价/改量统一"先改后通知"**(开发者 2026-10-12 口径)。
// 为什么放在服务层:改明细有 5 个入口(Web / 小程序 ×3 / MCP),只在界面处理会被绕过;
// 这里的职责是"收集变更 → 照常写库 → COMMIT 之后异步通知主系统",不拦人。
// 开关关闭时(默认)直接放行 ⇒ 与改造前逐字节一致(也不通知)。
/**
* ⚠️ 2026-10-12 口径:**先改后通知** —— 守卫已改为"放行"(`assertMainSystemPriceQtyReviewed`
* 在 local-first 下直接 return),真正的动作变成**写完库之后异步通知主系统**(见下方 notify)。
* 这里保留收集逻辑:既用于通知,也用于审计留痕。
*/
if (!params.mainSystemPriceQtyApproved && isPriceQtyRequestEnabled()) {
const changes = collectMainSystemPriceQtyChanges(existingMap, incoming);
/**
* ⚠️ 2026-10-14:加工方式**已解封**(开发者:「这块需要解封 当前加工方式是自己设置了」)——
* 原"只改加工方式也要进这道门"的并集判据随 `collectMainSystemProcessingChanges` 一起删除,
* 这里只判价格/数量。加工方式/加工方的改动**照常落库**,不通知主系统(他们没有这个反向通道)。
*/
if (changes.length) {
// ⚠️ 必须按**行**判:主系统单是按配送日合并的一张单,上面允许加本系统自建行/加菜行,
// 那些行在主系统没有备货行(提交申请必然失败)⇒ 按整单判会把它们的正常改价堵死。
const { guarded } = await isMainSystemAllocatedLines({
branchCode: order.branch_code || '',
ourOrderCode: orderCode,
candidates: changes.map((change) => ({
itemId: change.itemId,
itemName: change.itemName,
skuCode: existingMap.get(change.itemId)?.sku_code ?? null,
mainOrderCode: existingMap.get(change.itemId)?.main_order_code ?? null,
})),
query: (sql, values) => client.query(sql, values as unknown[]),
});
const guardedChanges = changes.filter((change) => guarded.has(change.itemId));
assertMainSystemPriceQtyReviewed({
isMainSystemOrder: true,
changes: guardedChanges,
});
/**
* ⚠️ 2026-10-10 口径(开发者):「主系统给子系统的订单,这个**计划数量**取消可以编辑的权限
* (子系统正常录单的不要被影响)」⇒ 主系统分配行的**数量**改动在这里**直接拒绝**。
*
* 为什么放服务层而不是只在界面禁用:改明细有 5 个入口(Web / 小程序 ×3 / MCP),
* 界面锁住但接口仍可改 ⇒ 界面锁等于摆设(本条是开发者明确要求的第二道门)。
* 只拦 `quantity`:**价格**仍走"先改后通知"(2026-10-12 口径不变);
* 我方自建行(加菜/自录)不在 `guarded` 里 ⇒ 完全不受影响。
*/
const qtyLocked = guardedChanges.filter(
(change): change is Extract<PriceQtyChange, { field: 'quantity' }> =>
change.field === 'quantity'
);
if (qtyLocked.length) {
const names = qtyLocked
.map((change) => `${change.itemName}(${change.from} → ${change.to})`)
.slice(0, 5)
.join('、');
throw Object.assign(
new Error(
`分发订单的数量无法修改(${names});` +
`数量与实际不符请联系主系统重新分配,或用「缺货」上报`
),
{ status: 409, code: 'main_system_qty_locked', changes: qtyLocked }
);
}
/**
* ⚠️ 2026-10-14 已删除「加工方式无法修改」这道门(开发者:「这块需要解封 当前加工方式是自己设置了」)。
*
* 原 2026-10-10 口径是"分配来的订单加工方式只能主系统改";但 2026-10-14 我方改为
* **加工方式由我方设置**(主系统的 `processingMethod` 只作提示并入行备注),
* 于是这道门只会拦住我们自己——详情页/小程序都能改、保存却 409。
* 现口径与落点:docs/design/20261014-主系统加工需求与我方加工决策.md §6.3 D2''、§7 验收 5;
* 前端(Web 详情 / 小程序加工格与加工方 chip)同步解禁。
* **计划数量锁(上面)与配送时间锁保持不变**。
*/
// local-first:价格改动不拦,改为"写库后通知主系统"
priceQtyNotices = guardedChanges;
}
}
for (const [id, row] of existingMap) {
if (!keptIds.has(id)) {
if (row.is_returned) continue;
await assertNoPendingManualAfterSaleForOrderItem(client, id);
await removeOrReturnOrderItem(client, {
orderCode,
branchCode: order.branch_code || null,
item: row,
hardDelete: async (target) => {
await deleteOrderItemWithDependencies(client, orderCode, target, {
preserveFulfilledHistory: params.preserveFulfilledHistory,
});
},
});
}
}
for (let index = 0; index < incoming.length; index += 1) {
const row = incoming[index];
const itemName = trimText(row.item_name);
if (!itemName) {
throw Object.assign(new Error('商品名称不能为空'), { status: 400, code: 'invalid_request' });
}
const id = trimText(row.id);
const existingRow = id && !isTempId(id) ? existingMap.get(id) : undefined;
const markReturnedNow =
isTruthyFlag(row.is_returned) || Boolean(existingRow?.is_returned);
if (markReturnedNow && existingRow && !existingRow.is_returned) {
await assertNoPendingManualAfterSaleForOrderItem(client, id);
await markOrderItemReturned(client, {
orderCode,
branchCode: order.branch_code || null,
item: existingRow,
});
existingRow.is_returned = true;
}
if (markReturnedNow || existingRow?.is_returned) {
continue;
}
const quantity = Number(row.quantity) || 0;
const price = Number(row.price) || 0;
// 服务端强制重算:忽略客户端 body.amount,防篡改
const amount = calcItemAmount(quantity, price);
totalAmount += amount;
const processingMethod = trimText(row.processing_method) || '原材料';
const processingOwner = normalizeProcessingOwner(processingMethod, row.processing_owner);
const unit = trimText(row.unit) || '斤';
weightItems.push({ quantity, unit });
const categoryCode = trimText(row.category_code) || null;
const categoryName = trimText(row.category_name) || null;
const supplierRaw = trimText(row.supplier_code) || null;
let supplierCode = normalizeSupplierCode(supplierRaw);
if (
requiresWarehouseProcessing(processingMethod, processingOwner) &&
(await isSupplierSkipInbound(supplierCode, client))
) {
throw Object.assign(new Error(`「${itemName}」供应商已开启不入仓,不能指定仓内加工`), {
status: 400,
code: 'skip_inbound_no_warehouse_processing',
});
}
if (requiresWarehouseProcessing(processingMethod, processingOwner)) {
if (
params.preferItemSuppliers &&
supplierCode &&
!isUnassignedSupplier(supplierCode) &&
// 库存抵扣(STOCK_COVER)也不是「改派供应商」:与自采/未分配一样强制成 INTERNAL(2026-10-14)
!isStockCoverSupplierCode(supplierCode)
) {
throw Object.assign(new Error(`「${itemName}」为仓内加工,不能改派供应商`), {
status: 409,
code: 'warehouse_processing_self_purchase_only',
});
}
supplierCode = INTERNAL_PURCHASER_CODE;
}
const isNewRow = !id || isTempId(id) || !existingMap.has(id);
let persistedItemId = !isNewRow ? id : '';
let skuCode = trimText(row.sku_code) || null;
if (
isNewRow &&
params.provisionPurchaserOrderSkus &&
isTruthyFlag(row.create_product) &&
!skuCode
) {
const provisioned = await ensureCatalogSkuForPurchaserOrder(client, {
name: itemName,
parentCode: categoryCode || '',
branchCode: order.branch_code || null,
unit,
});
skuCode = provisioned.skuCode;
row.sku_code = skuCode;
}
const rowIsExtraDish = isNewRow
? newRowIsExtraDish
: isTruthyFlag(row.is_extra_dish) || Boolean(existingMap.get(id)?.is_extra_dish);
const remarkRaw = trimText(row.remark);
const remark = remarkRaw ? remarkRaw.slice(0, 500) : null;
/**
* 规格(`order_items.spec`,2026-10-16 起可在订单详情直接改)。
*
* ⚠️ **只有载荷真的带了这个字段才动它**:改明细有 5 个入口(Web / 小程序 ×3 / MCP),
* 别的入口不带 spec ⇒ 若无条件 `spec = $N`,保存一次就会把已存规格**抹成 NULL**。
* 故用 `hasSpec` 标志位(UPDATE 里走 CASE),新行则直接取值(本来就是空)。
*/
const hasSpec = Object.prototype.hasOwnProperty.call(row, 'spec');
const spec = hasSpec ? trimText(row.spec).slice(0, 60) || null : null;
const qualityReportIds = normalizeQualityReportIds(row);
const qualityReportId = qualityReportIds[0] || null;
if (qualityReportIds.length) {
const qr = await client.query(
`SELECT id::text AS id FROM quality_reports WHERE id = ANY($1::uuid[]) AND status = 10`,
[qualityReportIds]
);
const found = new Set(qr.rows.map((r) => String(r.id)));
if (qualityReportIds.some((id) => !found.has(id))) {
throw Object.assign(new Error(`明细「${itemName}」选用的质检报告不存在或已作废`), {
status: 400,
code: 'invalid_quality_report',
});
}
}
const warehouseForced = requiresWarehouseProcessing(processingMethod, processingOwner);
const unitCost = seedOrderItemUnitCost({
processingMethod,
processingOwner,
computedCost: Math.max(0, Number(row.cost_price) || 0),
demandCompleted: Boolean(id && !isTempId(id) && completedDemandItemIds.has(id)),
existingUnitCost: id && existingMap.has(id) ? existingMap.get(id)?.unit_cost : undefined,
});
if (id && !isTempId(id) && existingMap.has(id)) {
const previous = existingMap.get(id)!;
const previousSku = trimText(previous.sku_code);
const identityChanged = previousSku
? previousSku !== trimText(skuCode)
: trimText(previous.item_name) !== itemName;
if (identityChanged && !params.syncPurchaserPurchaseSnapshots) {
await deleteOrderItemWithDependencies(client, orderCode, previous, {
keepItem: true,
});
}
if (params.preferItemSuppliers) {
if (!rowIsExtraDish && isAssignedExternalSupplier(supplierCode)) {
realSupplierSavedItemIds.push(id);
}
const fromCode = normalizeSupplierCode(previous.supplier_code);
if (fromCode !== supplierCode) {
manualSupplierChanges.push({
item_id: id,
item_name: itemName,
sku_code: skuCode || previousSku || null,
from_supplier_code: fromCode,
to_supplier_code: supplierCode,
is_extra_dish: rowIsExtraDish,
});
if (!rowIsExtraDish) {
const inbound = await orderItemHasInspectionInboundForSupplier(
client,
orderCode,
skuCode || previousSku,
fromCode
);
if (inbound) {
inboundReattributeItemIds.add(id);
inboundFulfillmentReattributes.push({
itemId: id,
skuCode: skuCode || previousSku || null,
itemName,
unit,
quantity,
unitCost,
previousSupplierCode: fromCode,
nextSupplierCode: supplierCode,
});
} else {
// 免入库 / 商品直送:实物交付方式不可逆(直送=供应商自送、免入库=配送员上门取),
// 完成供货后再改归属会让旧供应商那条已完成备货继续计费 → 两家重复结算。
// 有入库记录的行不走这里(由上面的"已入库改挂"按数据源变更处理)。
// 见 docs/design/20260924-supplier-switch-lock-after-prep.md
const lock = await findSupplierSwitchLock(client, {
orderCode,
itemId: id,
skuCode: skuCode || previousSku || null,
currentSupplierCode: fromCode,
orderStatus,
});
if (lock) throw supplierSwitchLockError(lock, itemName);
}
}
}
}
}
// 软落只对 forceSelfPurchaseItemIds 建自采。INTERNAL 行不进智能分配,
// 若名单还要求「这次才从供应商改成自采」,改数量会永远漏单(小苹果即此)。
// 已落库的非加菜自采行一律列入;createPurchaseOrderForItem 去重,完结单拒绝建待采。
// 已入库转挂行由 reattributeInboundFulfillment 写成完成自采,禁止再开待采。
if (
params.preferItemSuppliers &&
isSelfPurchaseSupplier(supplierCode) &&
!rowIsExtraDish &&
!isNewRow &&
id &&
!inboundReattributeItemIds.has(id)
) {
forceSelfPurchaseItemIds.push(id);
}
if (id && !isTempId(id) && existingMap.has(id)) {
const updated = await client.query(
`UPDATE order_items
SET item_name = $1, quantity = $2::numeric, unit = $3, price = $4::numeric, amount = $5::numeric,
ordered_quantity = $2::numeric,
processing_method = $6, processing_owner = $7,
category_code = $8, category_name = $9,
sku_code = $10,
supplier_code = $11,
sort_order = $12,
locked_price = $4::numeric, price_locked_at = NOW(),
needs_customer_price = CASE WHEN $4::numeric > 0 THEN false ELSE needs_customer_price END,
unit_cost = $15::numeric,
remark = $16,
quality_report_id = $17::uuid,
quality_report_ids = $18::uuid[],
-- 规格:仅当载荷带 spec 时才写(否则保持原值,见 hasSpec 注释)
spec = CASE WHEN $20::boolean THEN $19 ELSE spec END
WHERE id = $13::uuid AND order_code = $14`,
[
itemName,
quantity,
unit,
price,
amount,
processingMethod,
processingOwner,
categoryCode,
categoryName,
skuCode,
supplierCode,
index + 1,
id,
orderCode,
unitCost,
remark,
qualityReportId,
qualityReportIds,
spec,
hasSpec,
]
);
if (!updated.rowCount) {
throw Object.assign(new Error(`明细「${itemName}」更新失败,请刷新后重试`), {
status: 409,
code: 'conflict',
});
}
// 订单侧改了成本价 → 回写自采单 / 备货行(补齐与「备货/自采→订单」不对称的方向)。
// 已**确认**结算(≥20)/ 已验收 / 已作废 由服务内部排除;0 是否回写也由服务按
// 「允许成本价为 0」开关判定(此前这里还有一道 `> 0`,会把 0 提前挡掉)。
// 回写失败不阻断订单保存。
const previousUnitCost = Number(existingMap.get(id)?.unit_cost);
const costChanged = Number.isFinite(previousUnitCost)
? Math.abs(Number(unitCost) - previousUnitCost) > 1e-9
: Number(unitCost) > 0;
if (costChanged) {
try {
const { writeOrderEnteredCostToSupply } = await import(
'./orderEnteredCostWritebackService'
);
await writeOrderEnteredCostToSupply(client, {
orderCode,
skuCode: skuCode || '',
supplierCode,
branchCode: order.branch_code || null,
unitCost,
operatorId: params.operatorId || null,
operatorRole: params.operatorRoles || null,
});
} catch (err) {
console.error('[order-cost-writeback] 回写自采单/备货价失败', orderCode, skuCode, err);
}
}
// 直送免入库:核货行申报量随改单同步(实配以司机核货/称重为准)
const previousQty = Number(existingMap.get(id)?.quantity);
if (
previousQty !== quantity &&
(await isSupplierSkipInbound(supplierCode, client))
) {
await client.query(
`UPDATE picking_items SET required_qty = $2::numeric, picked_qty = $2::numeric
WHERE order_item_id = $1::uuid`,
[id, quantity]
);
}
} else {
const newId = randomUUID();
persistedItemId = newId;
await client.query(
`INSERT INTO order_items (
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)`,
[
newId,
orderCode,
skuCode,
itemName,
quantity,
unit,
price,
amount,
index + 1,
order.branch_code || null,
processingMethod,
processingOwner,
categoryCode,
categoryName,
supplierCode,
unitCost,
remark,
qualityReportId,
qualityReportIds,
rowIsExtraDish,
spec,
]
);
if (params.purchaserDirectAllocation) {
purchaserDirectAllocationItemIds.push(newId);
}
newlyInsertedItemIds.push(newId);
if (!rowIsExtraDish) newlyInsertedNonExtraIds.push(newId);
// 主系统导入(keepNewItemsUnassigned):新行**不许**进规则引擎 ⇒ 保持「未分配」等人工选择
if (
allocationIntent.autoAllocateNewItems &&
!rowIsExtraDish &&
supplierCode !== INTERNAL_PURCHASER_CODE
) {
autoAllocateItemIds.push(newId);
}
if (params.preferItemSuppliers && supplierCode) {
manualSupplierChanges.push({
item_id: newId,
item_name: itemName,
sku_code: skuCode,
from_supplier_code: null,
to_supplier_code: supplierCode,
is_extra_dish: rowIsExtraDish,
});
}
if (
params.preferItemSuppliers &&
isSelfPurchaseSupplier(supplierCode) &&
!rowIsExtraDish
) {
forceSelfPurchaseItemIds.push(newId);
}
}
// 加菜成本由 reconcileExtraDishPurchaseCosts 入自采侧(extra_dish),禁止走 unit_cost_sync 误记供应
if (skuCode && !rowIsExtraDish && unitCost > 0 && !warehouseForced) {
const { upsertOrderSkuPurchaseCostFromUnitCost } = await import('./orderCostPostingService');
await upsertOrderSkuPurchaseCostFromUnitCost(
client,
orderCode,
skuCode,
unitCost,
{ orderItemId: persistedItemId }
);
}
}
try {
const { upsertOrderItemRemarksSafe } = await import('./customerSkuRemarkService');
await upsertOrderItemRemarksSafe(
client,
String(order.customer_code || ''),
incoming.map((row) => ({
sku_code: row.sku_code,
remark: row.remark,
}))
);
} catch (error) {
console.warn('[customerSkuRemarks] batch after sync failed:', error);
}
for (const row of inboundFulfillmentReattributes) {
await reattributeInboundFulfillment(client, {
orderCode,
itemId: row.itemId,
skuCode: row.skuCode,
itemName: row.itemName,
unit: row.unit,
previousSupplierCode: row.previousSupplierCode,
nextSupplierCode: row.nextSupplierCode,
quantity: row.quantity,
unitCost: row.unitCost,
branchCode: order.branch_code || null,
});
}
const openSelfPurchaseItemIds = params.preferItemSuppliers
? await listOpenSelfPurchaseItemIds(client, orderCode, realSupplierSavedItemIds)
: [];
supplierSwitchItemIds = params.preferItemSuppliers
? collectSupplierSwitchItemIds({
changes: manualSupplierChanges.filter((row) => !inboundReattributeItemIds.has(row.item_id)),
openSelfPurchaseItemIds: openSelfPurchaseItemIds.filter(
(id) => !inboundReattributeItemIds.has(id)
),
})
: [];
const switchIdSet = new Set(supplierSwitchItemIds);
const skuBySwitchItemId = new Map<string, string | null>();
for (const row of manualSupplierChanges) {
if (switchIdSet.has(row.item_id)) skuBySwitchItemId.set(row.item_id, row.sku_code);
}
for (const itemId of supplierSwitchItemIds) {
if (skuBySwitchItemId.has(itemId)) continue;
const prev = existingMap.get(itemId);
if (prev) skuBySwitchItemId.set(itemId, trimText(prev.sku_code) || null);
}
for (const itemId of supplierSwitchItemIds) {
if (orderStatus >= 50) continue;
const inbound = await orderItemHasInspectionInbound(client, orderCode, {
id: itemId,
sku_code: skuBySwitchItemId.get(itemId) || undefined,
});
if (inbound) continue;
await client.query(`DELETE FROM picking_items WHERE order_item_id = $1::uuid`, [
itemId,
]);
}
// 配送后加菜不再经过分配器;选择真实供应商时补建一条已完成备货记录,
// 使供应商结算与订单明细保持可追溯。自采(INTERNAL/UNASSIGNED)仍由采购单链路处理。
if (orderStatus >= 60) {
const extraRows = await client.query(
`SELECT id, sku_code, item_name, quantity, unit, supplier_code, unit_cost
FROM order_items
WHERE order_code = $1 AND COALESCE(is_extra_dish, false) = true
AND COALESCE(is_returned, false) = false`,
[orderCode]
);
for (const row of extraRows.rows) {
// 库存抵扣的行也走自采侧:否则会裸 INSERT 一张 supplier_code='STOCK_COVER' 的
// 「已完成备货」(幽灵厂商备货 → 待验/结算/成本回填全以它为依据,2026-10-14)
if (isSelfPurchaseSupplier(row.supplier_code) || isStockCoverSupplierCode(row.supplier_code)) {
if (row.id) await ensureCompletedExtraDishPurchase({
orderCode, itemId: String(row.id), skuCode: row.sku_code,
itemName: row.item_name, quantity: Number(row.quantity) || 0,
unitCost: Number(row.unit_cost) || 0, branchCode: order.branch_code || null,
}, client);
continue;
}
const supplierCode = normalizeSupplierCode(row.supplier_code);
const sku = trimText(row.sku_code);
if (!supplierCode || !sku) continue;
const qty = Math.max(0, Number(row.quantity) || 0);
if (!(qty > 0)) continue;
const price = Math.max(0, Number(row.unit_cost) || 0);
await client.query(
`INSERT INTO supplier_preparations
(order_code, supplier_code, sku_code, item_name, prepare_qty, purchase_price,
prepare_status, prepare_time, branch_code, unit)
VALUES ($1, $2, $3, $4, $5, $6, 30, NOW(), $7, $8)
ON CONFLICT (order_code, sku_code, supplier_code)
WHERE sku_code IS NOT NULL AND TRIM(sku_code) <> ''
AND COALESCE(is_stockout, false) = false
AND COALESCE(transferred_to_purchase, false) = false
DO UPDATE
SET prepare_qty = EXCLUDED.prepare_qty,
purchase_price = EXCLUDED.purchase_price,
prepare_status = 30,
prepare_time = COALESCE(supplier_preparations.prepare_time, NOW())`,
[orderCode, supplierCode, sku, trimText(row.item_name) || sku, qty, price, order.branch_code || null, trimText(row.unit) || null]
);
}
}
// 方案 B(下单即挂应付):订单保存/明细变更后**无条件**按订单行重建该单的(供应商 × 下单日)结算单。
// 原实现只在免入库分支里同步,新口径下所有供应商都要即时同步。
await ensureSupplierStatementsForOrder(orderCode, client);
if (params.syncPurchaserPurchaseSnapshots) {
await syncPurchaserLinkedPurchaseSnapshots(
client,
orderCode,
order.branch_code || null,
params.operatorId,
params.operatorRoles
);
}
totalAmount = Math.round(totalAmount * 100) / 100;
// total_weight 统一折算到「斤」;箱/件/个等非重量单位无可靠系数,不计入重量合计
const weightFactors = await loadWeightUnitFactors(client);
totalWeight = sumWeightInJin(weightItems, weightFactors);
const orderPatch = params.orderPatch;
if (orderPatch) {
const deliveryDate = normalizeDateOnly(orderPatch.delivery_date);
/**
* ⚠️ **主系统分配单的配送日,任何通道都不许改**(2026-10-16 开发者批准补锁)。
* 该值现在由「我们收到/导入那一单的当日」决定(见
* docs/design/20261016-主系统派单配送日按导入当日.md),与主系统给的配送日**刻意解耦**。
*
* 判据与行内单字段通道**逐字同源**:该单存在**主系统分配行**(行级 `main_order_code` 非空)。
* 我方自建单(含加菜行)没有这个标记 ⇒ 完全不受影响。
*
* ⚠️ **只在"配送日真的变了"时才拦**:Web 保存明细会把当前配送日**原样回传**,
* 无条件拦会把主系统单的正常保存整体打挂(这是补这道锁时最容易犯的错)。
*/
const previousDeliveryDate = normalizeDateOnly(order.delivery_date);
if (deliveryDate !== previousDeliveryDate) {
const mainRows = await client.query<{ n: number }>(
`SELECT count(*)::int AS n FROM order_items
WHERE order_code = $1 AND NULLIF(TRIM(main_order_code), '') IS NOT NULL`,
[orderCode]
);
if (Number(mainRows.rows[0]?.n || 0) > 0) {
throw Object.assign(new Error('分发订单的配送时间由导入当日确定,无法修改'), {
status: 409,
code: 'main_system_delivery_date_locked',
});
}
}
if (deliveryDate) {
try {
assertDeliveryDateOnOrAfterOrderDate(
deliveryDate,
getOrderDateFromCreatedAt(order.created_at)
);
} catch (dateError) {
throw Object.assign(
dateError instanceof Error ? dateError : new Error(String(dateError)),
{ status: 400, code: 'invalid_request' }
);
}
}
await client.query(
`UPDATE orders
SET total_amount = $1, total_weight = $2, updated_at = NOW(),
delivery_date = $4, delivery_time_slot = $5, delivery_address = $6, remark = $7
WHERE order_code = $3`,
[
totalAmount,
totalWeight,
orderCode,
deliveryDate,
orderPatch.delivery_time_slot ?? null,
orderPatch.delivery_address ?? null,
orderPatch.remark ?? null,
]
);
} else {
await client.query(
`UPDATE orders
SET total_amount = $1, total_weight = $2, updated_at = NOW()
WHERE order_code = $3`,
[totalAmount, totalWeight, orderCode]
);
}
// 过账扣点:明细保存后重打比例快照(新增行按当前客户配置写入;只写 rebate_ratio 一列)
try {
const { attachOrderRebateSnapshots } = await import('./customerRebateService');
await attachOrderRebateSnapshots({
orderCode,
customerCode: order.customer_code || null,
// 只给本次新建的行打快照:客户改比例/关开关都不得重刷已存在的行(历史成本不追溯)
rowIds: newlyInsertedItemIds,
db: client,
});
} catch (error) {
console.error('[rebate] 明细快照失败(不阻断保存):', (error as Error)?.message);
}
// 明细携带的成本价写入客户生效报价(含已完成单改价;须在「补空」之前,避免被跳过)
const costUpserts = new Map<
string,
{ sku_code: string; cost_price: number; sale_price: number; sku_name: string; unit: string }
>();
for (const row of incoming) {
if (isTruthyFlag(row.is_returned)) continue;
const sku = trimText(row.sku_code);
const cost = Math.max(0, Number(row.cost_price) || 0);
const sale = Math.max(0, Number(row.price) || 0);
if (!sku || (!(cost > 0) && !(sale > 0))) continue;
// 仓内加工行不参与报价单回写:该类行成本须为 0(完工后才分摊),
// 与 inspectionAmendService「仓内加工行不在此改」及既有录单不种子报价成本的约定一致。
// 2026-10-07 用户确认:「仓内加工的不需要回写」。原判定行保持原样,勿改写法(有测试钉住)。
const method = trimText(row.processing_method) || '原材料';
const owner = normalizeProcessingOwner(method, row.processing_owner);
if (requiresWarehouseProcessing(method, owner)) continue;
costUpserts.set(sku, {
sku_code: sku,
cost_price: cost,
sale_price: sale,
sku_name: trimText(row.item_name || row.sku_name),
unit: trimText(row.unit) || '斤',
});
}
if (costUpserts.size > 0 && order.customer_code) {
const sync = await upsertCustomerQuoteItemCosts(client, {
customerCode: String(order.customer_code),
branchCode: order.branch_code || null,
items: [...costUpserts.values()],
});
quoteCostSync = {
quote_sheet_code: sync.quote_sheet_code,
updated: sync.updated,
inserted: sync.inserted,
requested: costUpserts.size,
};
}
if (orderStatus >= 60) {
// 配送中起:不重跑分配;仅加菜行库存覆盖。完成单仍覆盖全部未履约行并重算验收采购账。
await coverUnfulfilledItemsAsInventoryForCompleted(client, orderCode, {
onlyExtraDish: !orderCompleted,
});
}
if (orderStatus >= 50) {
statementSync = await upsertCustomerStatementForOrder(orderCode, client);
if (orderCompleted) {
await fillMissingQuoteCostsFromOrderSupply(client, orderCode, order.branch_code || null);
await reconcileOrderPurchaseFromLatestInspections(client, orderCode, {
branchCode: order.branch_code || null,
});
costReconciled = true;
}
if (canPostExtraDishCost) {
const costBySku = new Map<string, number>();
for (const [sku, row] of costUpserts) {
costBySku.set(sku, row.cost_price);
}
const extra = await reconcileExtraDishPurchaseCosts(client, orderCode, {
branchCode: order.branch_code || null,
costBySku,
});
extraDishCostPosted = extra.posted > 0;
}
}
await client.query('COMMIT');
} catch (error) {
await client.query('ROLLBACK').catch(() => undefined);
throw error;
} finally {
try {
await resetExclusiveTenantClient(client);
} catch {
/* ignore */
}
client.release();
}
/**
* **先改后通知**(2026-10-12 口径):明细写入已 COMMIT ⇒ 现在**异步通知**主系统我方改了价/量。
* 非阻塞、失败不改我方值;主系统的同意/驳回都不回改我方(只留痕)。
*/
if (priceQtyNotices.length) {
notifyMainSystemPriceQtyChanges({
branchCode: order.branch_code || '',
ourOrderCode: orderCode,
changes: priceQtyNotices,
actor: {
userId: params.operatorId ?? null,
roles: params.operatorRoles ?? null,
requestedBy: params.operatorId ?? null,
},
reason: '订单明细改价/改量(先改后通知)',
});
}
const allocateNewRowsAtStatus50 =
orderStatus === 50 &&
(params.purchaserDirectAllocation
? purchaserDirectAllocationItemIds.length > 0
: newlyInsertedNonExtraIds.length > 0);
if (orderStatus < 50 || allocateNewRowsAtStatus50) {
await withAllocationSlot(async () => {
const follow = await connectExclusiveTenantClient();
try {
await follow.query('BEGIN');
if (params.purchaserDirectAllocation) {
const directResult = await purchaserDirectAllocation(
{
orderCode,
branchCode: order.branch_code,
customerCode: order.customer_code,
purchaserCode: params.purchaserDirectAllocation.purchaserCode,
itemIds: purchaserDirectAllocationItemIds,
},
follow
);
if (directResult.errors.length) {
allocationSoftWarnings = [...directResult.errors];
}
allocation = {
orderCode,
itemsProcessed: directResult.purchaseOrdersCreated + directResult.preparationsCreated,
purchaseOrdersCreated: directResult.purchaseOrdersCreated,
preparationsCreated: directResult.preparationsCreated,
skipped: 0,
errors: directResult.errors,
};
} else {
allocation = await reprocessOrderAllocation(
orderCode,
order.customer_code,
order.branch_code,
follow,
allocationIntent.useItemSuppliers
? {
preferItemSuppliers: true,
autoAllocateItemIds,
forceSelfPurchaseItemIds,
supplierSwitchItemIds,
...unpricedOpt,
...(orderStatus === 50
? {
onlyItemIds: newlyInsertedNonExtraIds,
skipPerOrderAutoBidGate: true,
}
: {}),
}
: orderStatus === 50
? {
onlyItemIds: newlyInsertedNonExtraIds,
skipPerOrderAutoBidGate: true,
...unpricedOpt,
}
: (Object.keys(unpricedOpt).length ? unpricedOpt : undefined)
);
const softAllocationWarnings = (allocation.errors || []).filter((msg) =>
/未配置(?:主)?采购员|待人工处理/.test(String(msg || ''))
);
const hardAllocationErrors = (allocation.errors || []).filter(
(msg) => !softAllocationWarnings.includes(msg)
);
allocationSoftWarnings = [...softAllocationWarnings];
if (hardAllocationErrors.length && !allocation.deferredForBid) {
allocationSoftWarnings.push(...hardAllocationErrors);
}
if (!allocation.deferredForBid) {
await recalcPreparationQty(follow, orderCode);
}
}
if (forceSelfPurchaseItemIds.length) {
const skuRows = await follow.query(
`SELECT DISTINCT NULLIF(TRIM(sku_code), '') AS sku_code
FROM order_items
WHERE order_code = $1 AND id = ANY($2::uuid[])`,
[orderCode, forceSelfPurchaseItemIds]
);
const skuCodes = skuRows.rows
.map((row) => String(row.sku_code || '').trim())
.filter(Boolean);
const { dropSkusFromActivePerOrderBidRoundsIfNoUnassignedRemain } = await import(
'./bidRoundService'
);
await dropSkusFromActivePerOrderBidRoundsIfNoUnassignedRemain({
orderCode,
skuCodes,
client: follow,
});
}
await syncInspectionFulfillmentIdentityForOrder(follow, orderCode);
await syncWarehouseProcessingDemandForOrder(orderCode, follow);
await syncOpenPurchaseQtyForOrder(follow, orderCode);
const { ensureSkipInboundLoadingLines } = await import('./skipInboundLoadingService');
await ensureSkipInboundLoadingLines(orderCode, follow);
await follow.query('COMMIT');
} catch (fulfillError) {
await follow.query('ROLLBACK').catch(() => undefined);
const msg =
fulfillError instanceof Error ? fulfillError.message : String(fulfillError || '履约同步失败');
allocationSoftWarnings.push(msg);
} finally {
try {
await resetExclusiveTenantClient(follow);
} catch {
/* ignore */
}
follow.release();
}
});
} else {
const follow = await connectExclusiveTenantClient();
try {
await syncInspectionFulfillmentIdentityForOrder(follow, orderCode);
await syncOpenPurchaseQtyForOrder(follow, orderCode);
const { ensureSkipInboundLoadingLines } = await import('./skipInboundLoadingService');
await ensureSkipInboundLoadingLines(orderCode, follow);
} catch (syncError) {
const msg =
syncError instanceof Error ? syncError.message : String(syncError || '履约对齐失败');
allocationSoftWarnings.push(msg);
} finally {
try {
await resetExclusiveTenantClient(follow);
} catch {
/* ignore */
}
follow.release();
}
}
/**
* 「全额库存抵扣、没有采购义务」的单:**在本次请求内**推进到待分拣
* (开发者 2026-10-13:「不能只靠定时器兜底」)。
*
* 这条路径(订单详情/小程序改明细保存)跑在**外部事务连接**上,不触发分配模块的
* `runAllocationAfterCommitSideEffects`,此前只能等 15 分钟调度器 —— 用户看到的就是
* 「明明抵扣完了,状态还停在待分配/待备货」。这里在自身事务提交后补一次推进;
* 推进器内部按 uncovered / pendingPreps / pendingPurchases 严格判断,
* **有缺口绝不会硬推**(只留下 steps 说明)。幂等。
*/
if (
allocation &&
allocation.orderStatusUpdated === 30 &&
allocation.preparationsCreated === 0 &&
allocation.purchaseOrdersCreated === 0
) {
try {
const { reconcileOrderWorkflowStatus } = await import('./orderStatusReconcileService');
await reconcileOrderWorkflowStatus(orderCode);
} catch (error) {
console.warn(
`[order-items] 全额抵扣后推进状态失败(不影响保存)order=${orderCode}:`,
(error as Error)?.message || error
);
}
}
if (params.enforceEditWindow !== false) {
const editAudit = buildOrderItemsEditAuditPayload({
orderCode,
orderStatus,
existing: existingItemsForAudit,
incoming,
});
await writeAuditLog({
operatorId: params.operatorId || null,
operatorRole: params.operatorRoles || null,
operationType: 'order_items_edit',
targetTable: 'orders',
targetId: orderCode,
oldValue: {
order_code: orderCode,
item_count: previousItemCount,
},
newValue: {
...editAudit,
allocation_reprocessed: orderStatus < 50 || allocateNewRowsAtStatus50,
},
branchCode: order.branch_code || null,
actionCategory: 'order',
}).catch((auditError) => {
console.error('[order_items_edit] writeAuditLog failed:', auditError);
});
}
if (params.preferItemSuppliers && manualSupplierChanges.length > 0) {
await writeAuditLog({
operatorId: params.operatorId || null,
operatorRole: params.operatorRoles || null,
operationType: 'manual_allocation_supplier_change',
targetTable: 'order_items',
targetId: orderCode,
oldValue: {
order_code: orderCode,
changes: manualSupplierChanges.map((c) => ({
item_id: c.item_id,
item_name: c.item_name,
sku_code: c.sku_code,
supplier_code: c.from_supplier_code,
})),
},
newValue: {
source: 'manual_allocation',
order_code: orderCode,
order_status: orderStatus,
change_count: manualSupplierChanges.length,
changes: manualSupplierChanges.map((c) => ({
item_id: c.item_id,
item_name: c.item_name,
sku_code: c.sku_code,
from_supplier_code: c.from_supplier_code,
to_supplier_code: c.to_supplier_code,
})),
},
branchCode: order.branch_code || null,
actionCategory: 'order',
}).catch((auditError) => {
console.error('[manual_allocation] writeAuditLog failed:', auditError);
});
}
// 改明细若触发 per_order 自动竞价闸门:事务外发标;失败回退普通分配
// 发标成功后立刻分配非竞价范围商品
if (allocation?.deferredForBid) {
const excludeSkuCodes = allocation.deferredBidSkuCodes || [];
try {
if (allocation.needsAutoBidStart) {
const { runPerOrderAutoBidAfterDefer } = await import('./bidRoundService');
const started = await runPerOrderAutoBidAfterDefer({
orderCode,
branchCode: order.branch_code,
});
if (!started.ok) {
const { resolvePerOrderBidSkipGateAllocOptions } = await import('./bidRoundService');
const skipOpts = await resolvePerOrderBidSkipGateAllocOptions({
orderCode,
excludeSkuCodes,
started,
});
allocation = await reprocessOrderAllocation(
orderCode,
order.customer_code,
order.branch_code,
undefined,
{ ...skipOpts, ...unpricedOpt }
);
if (skipOpts.excludeSkuCodes?.length) {
allocation.deferredForBid = true;
allocation.deferredBidSkuCodes = skipOpts.excludeSkuCodes;
}
} else if (excludeSkuCodes.length > 0) {
const partial = await reprocessOrderAllocation(
orderCode,
order.customer_code,
order.branch_code,
undefined,
{ skipPerOrderAutoBidGate: true, excludeSkuCodes, ...unpricedOpt }
);
partial.deferredForBid = true;
partial.deferredBidSkuCodes = excludeSkuCodes;
partial.bidGateMessage = allocation.bidGateMessage;
allocation = partial;
}
} else if (excludeSkuCodes.length > 0) {
const partial = await reprocessOrderAllocation(
orderCode,
order.customer_code,
order.branch_code,
undefined,
{ skipPerOrderAutoBidGate: true, excludeSkuCodes, ...unpricedOpt }
);
partial.deferredForBid = true;
partial.deferredBidSkuCodes = excludeSkuCodes;
partial.bidGateMessage = allocation.bidGateMessage;
allocation = partial;
}
} catch (followUpError) {
console.warn('[orderManageItems] deferred bid follow-up failed', {
orderCode,
message: followUpError instanceof Error ? followUpError.message : String(followUpError),
});
try {
const { resolvePerOrderBidSkipGateAllocOptions } = await import('./bidRoundService');
const skipOpts = await resolvePerOrderBidSkipGateAllocOptions({
orderCode,
excludeSkuCodes,
});
allocation = await reprocessOrderAllocation(
orderCode,
order.customer_code,
order.branch_code,
undefined,
{ ...skipOpts, ...unpricedOpt }
);
if (skipOpts.excludeSkuCodes?.length) {
allocation.deferredForBid = true;
allocation.deferredBidSkuCodes = skipOpts.excludeSkuCodes;
}
} catch {
// 带排除仍失败则停,禁止第三次无排除整单覆盖竞价 SKU
}
}
}
await syncWarehouseProcessingDemandForOrderAfterCommit(orderCode);
// 厂商备货行「分配即供货完成」:改单走外部事务(分配内后置钩子不执行),提交后补一次
//(建待验入库、回写订单行成本、免入库/直送结算桶、推进订单)。幂等,失败不影响改单。
try {
const { finalizeAutoCompletedSupplierPreparations } = await import(
'./supplierPreparationStatusService'
);
await finalizeAutoCompletedSupplierPreparations(orderCode);
} catch (err) {
console.error('[orderManageItems] 自动完成厂商备货失败', orderCode, err);
}
// 提交后再读:走当前请求租户 path,与列表/详情回读一致
const items = await pool.query(
`SELECT oi.id, oi.item_name, oi.sku_code, oi.quantity, oi.unit, oi.price, oi.amount,
oi.supplier_code, oi.processing_method, oi.processing_owner,
oi.category_code, oi.category_name, oi.sort_order, oi.is_extra_dish, oi.remark,
oi.quality_report_id, oi.quality_report_ids,
COALESCE(oi.is_returned, false) AS is_returned, oi.return_code,
(EXISTS (
SELECT 1 FROM inventory_logs il
WHERE il.related_order_code = oi.order_code
AND il.operation_type = 'inspection_in'
AND COALESCE(il.quantity, 0) > 0
AND il.sku_code IS NOT DISTINCT FROM oi.sku_code
AND NOT ${inventoryLogVoidedByReturnSql('il')}
) OR EXISTS (
SELECT 1 FROM inspections insp
WHERE insp.order_code = oi.order_code
AND insp.sku_code IS NOT DISTINCT FROM oi.sku_code
AND NULLIF(TRIM(insp.inbound_batch_no), '') IS NOT NULL
AND ${notVoidedByLineReturnSql('insp')}
)) AS inbound_done,
s.company_name AS supplier_name
FROM order_items oi
LEFT JOIN suppliers s ON s.supplier_code = oi.supplier_code
WHERE oi.order_code = $1
AND COALESCE(oi.is_returned, false) = false
ORDER BY oi.sort_order ASC NULLS LAST, oi.id ASC`,
[orderCode]
);
return {
total_amount: totalAmount,
total_weight: totalWeight,
items: items.rows.map((row) => ({
...row,
can_hard_delete: !row.is_returned && !row.inbound_done,
})),
allocation,
...(allocationSoftWarnings.length
? { allocation_soft_warnings: allocationSoftWarnings }
: {}),
...(statementSync ? { statement_sync: statementSync } : {}),
...(costReconciled ? { cost_reconciled: true } : {}),
...(extraDishCostPosted ? { extra_dish_cost_posted: true } : {}),
...(quoteCostSync ? { quote_cost_sync: quoteCostSync } : {}),
};
}
/**
* 第三方订单(主系统分配)**退货跟随**专用入口(2026-10-08)。
*
* 走的是与「订单改明细删行」**完全相同**的删行/红冲路径(同一个 removeOrReturnOrderItem +
* 同一个 deleteOrderItemWithDependencies),不新造任何红冲语义:
* · 未采购、未备货完成 ⇒ 取消履约(删行 + 清孤儿备货/待采)
* · 已采购 / 已备货完成 / 已验收入库 ⇒ OIR_ 退货单 + 销售/成本红冲 + 应付冲回 + 结算重算
*
* 与人工改单的差别只有两点,都是刻意的:
* 1. 不受 `canEditOrderItemsForStatus` 的权限闸门约束(这是主系统发起的被动跟随,不是人改单);
* **状态闸门由调用方负责**(设计文档 §3.3:已发车 ≥60 必须挂起、不得自动红冲)。
* 2. 只处理**这一行**,不动同单其他明细。
* 见 docs/design/20261008-第三方订单退货跟随与发车回写方案.md §3.3。
*/
export async function removeOrderItemForMainSystemReturn(params: {
orderCode: string;
branchCode?: string | null;
itemId: string;
/**
* 在同一事务内、红冲/删行**之前**执行(第三方退货跟随的库存抵扣补丁用)。
* 设计文档 §3.6 要求补丁与红冲同事务:否则红冲失败时会留下
* 「成本已作废、库存预留已释放,但销售行还在」的不一致状态(对抗式复查 #5)。
*/
beforeRemove?: (client: PoolClient) => Promise<void>;
}): Promise<'deleted' | 'returned' | 'already_returned'> {
const orderCode = trimText(params.orderCode);
const itemId = trimText(params.itemId);
if (!orderCode || !itemId) {
throw Object.assign(new Error('缺少订单号或明细 id'), { status: 400, code: 'invalid_request' });
}
// 上下文要求:必须在**租户上下文**里调用(`runWithTenantDbContext(branchCode, …)`)——
// 那时 `pool.connect()` 拿到的是带租户 search_path + app.branch_code 的连接(会话级或新借),
// 未加限定名的 order_items / cost_details 才找得到。没有租户上下文时不要调用。
const client = await pool.connect();
try {
await client.query('BEGIN');
const itemResult = await client.query(
`SELECT id, sku_code, item_name, supplier_code, is_extra_dish, quantity, price, amount, unit_cost,
COALESCE(is_returned, false) AS is_returned, return_code
FROM order_items
WHERE id = $1::uuid AND order_code = $2
LIMIT 1`,
[itemId, orderCode]
);
if (!itemResult.rowCount) {
await client.query('ROLLBACK');
throw Object.assign(new Error('订单明细不存在或不属于该订单'), { status: 404, code: 'not_found' });
}
const row = itemResult.rows[0];
if (row.is_returned) {
await client.query('ROLLBACK');
return 'already_returned';
}
await assertNoPendingManualAfterSaleForOrderItem(client, itemId);
if (params.beforeRemove) await params.beforeRemove(client);
const outcome = await removeOrReturnOrderItem(client, {
orderCode,
branchCode: params.branchCode ?? null,
item: {
id: String(row.id),
sku_code: row.sku_code,
item_name: row.item_name,
supplier_code: row.supplier_code,
is_extra_dish: row.is_extra_dish,
quantity: row.quantity,
price: row.price,
amount: row.amount,
unit_cost: row.unit_cost,
is_returned: row.is_returned,
return_code: row.return_code,
},
hardDelete: async (target) => {
await deleteOrderItemWithDependencies(client, orderCode, target, {});
},
});
await client.query('COMMIT');
return outcome;
} catch (error) {
await client.query('ROLLBACK').catch(() => undefined);
throw error;
} finally {
client.release();
}
}
/** 售后处理确认:走与订单删除相同的硬删/红冲,但不新建 OIR_/取消履约单。 */
export async function applyAfterSaleHandleOrderItem(
client: PoolClient,
args: {
orderCode: string;
branchCode?: string | null;
itemId: string;
}
): Promise<'deleted' | 'returned' | 'already_returned'> {
const itemId = String(args.itemId || '').trim();
const orderCode = String(args.orderCode || '').trim();
if (!itemId || !orderCode) {
throw Object.assign(new Error('处理前须绑定订单明细'), { status: 400, code: 'invalid_request' });
}
const item = await client.query(
`SELECT id, sku_code, item_name, supplier_code, is_extra_dish, quantity, price, amount, unit_cost,
COALESCE(is_returned, false) AS is_returned, return_code
FROM order_items WHERE id = $1::uuid AND order_code = $2 LIMIT 1`,
[itemId, orderCode]
);
if (!item.rowCount) {
throw Object.assign(new Error('订单明细不存在或不属于该订单'), {
status: 400,
code: 'invalid_request',
});
}
const row = item.rows[0];
return removeOrReturnOrderItem(client, {
orderCode,
branchCode: args.branchCode,
item: {
id: String(row.id),
sku_code: row.sku_code,
item_name: row.item_name,
supplier_code: row.supplier_code,
is_extra_dish: row.is_extra_dish,
quantity: row.quantity,
price: row.price,
amount: row.amount,
unit_cost: row.unit_cost,
is_returned: row.is_returned,
return_code: row.return_code,
},
skipNewAfterSaleTicket: true,
hardDelete: async (target) => {
await deleteOrderItemWithDependencies(client, orderCode, target);
},
});
}
/* ────────────────────────────────────────────────────────────────────────────
* 订单列表「配送日」双击行内编辑(用户 2026-10-08)
*
* 为什么并入本文件而不是新开服务:`server/tests/routeLayerBoundary.test.ts` 把
* `getRawPoolConnect` 的消费方固定成只允许收紧的白名单(本文件在名单内);
* 新开文件会被判为「新增绕过 ALS 租户上下文的 raw pool 调用方」。
* 本文件本就是「订单明细 / 头信息保存」的领域服务,配送日属头信息,归此最自然。
* ──────────────────────────────────────────────────────────────────────────── */
/** 配送中:列表行内改配送日的上界(与前端 orderManagementHelpers 同口径) */
export const DELIVERY_DATE_EDIT_MAX_STATUS = 60;
/** 待处理组上界:< 50 视为「待处理」(与后端 pending 统计口径一致) */
const DELIVERY_DATE_EDIT_PENDING_MAX = 50;
export function canEditDeliveryDateByStatus(status: unknown): boolean {
const n = Number(status);
if (!Number.isFinite(n)) return false;
if (n === DELIVERY_DATE_EDIT_MAX_STATUS) return true;
return n >= 20 && n < DELIVERY_DATE_EDIT_PENDING_MAX;
}
export interface OrderDeliveryDatePatchResult {
order_code: string;
delivery_date: string;
/** 是否真的写入(同日不改 → false,避免无意义 updated_at 变化) */
changed: boolean;
previous_delivery_date: string | null;
}
/**
* 只改 `orders.delivery_date` 一列:不动明细、金额、状态,也不重排已生成的
* 分拣/配送任务(任务自带 delivery_date;已发车单改日会出现「订单显示 X 日、
* 司机端任务仍是 Y 日」的不一致——本次需求已知边界,见设计说明)。
*
* 闸门:仅管理员;仅「待处理组(<50)」与「配送中(60)」;配送日不得早于下单日。
*/
export async function updateOrderDeliveryDate(params: {
orderCode: string;
deliveryDate: unknown;
operatorId?: string | null;
operatorRoles?: string | null;
operatorIsAdmin: boolean;
}): Promise<OrderDeliveryDatePatchResult> {
const orderCode = String(params.orderCode || '').trim();
if (!orderCode) {
throw Object.assign(new Error('缺少订单号'), { status: 400, code: 'invalid_request' });
}
if (!params.operatorIsAdmin) {
throw Object.assign(new Error('仅管理员可修改配送日期'), { status: 403, code: 'forbidden' });
}
const deliveryDate = normalizeDateOnly(params.deliveryDate);
if (!deliveryDate) {
throw Object.assign(new Error('配送日期无效'), { status: 400, code: 'invalid_request' });
}
const client = await connectExclusiveTenantClient();
try {
await client.query('BEGIN');
const found = await client.query(
`SELECT order_code, order_status, created_at, delivery_date, branch_code
FROM orders WHERE order_code = $1 LIMIT 1`,
[orderCode]
);
const order = found.rows[0];
if (!order) {
throw Object.assign(new Error('订单不存在'), { status: 404, code: 'not_found' });
}
/**
* ⚠️ 2026-10-10 口径(开发者):「**分配来的订单不能修改配送时间** —— 只能是主系统那边改了我们这边同步」。
* 与数量/加工方式同款(服务层是第二道门,界面禁用之外还必须拦接口)。
* 判据与列表页 `is_main_system_order` 同源:该单存在**主系统分配行**(行级 `main_order_code`)。
* 我方自建单(含加菜行)没有这个标记 ⇒ 完全不受影响。
*/
const mainRows = await client.query<{ n: number }>(
`SELECT count(*)::int AS n FROM order_items
WHERE order_code = $1 AND NULLIF(TRIM(main_order_code), '') IS NOT NULL`,
[orderCode]
);
if (Number(mainRows.rows[0]?.n || 0) > 0) {
throw Object.assign(new Error('分发订单的配送时间由导入当日确定,无法修改'), {
status: 409,
code: 'main_system_delivery_date_locked',
});
}
if (!canEditDeliveryDateByStatus(order.order_status)) {
throw Object.assign(new Error('当前订单状态不允许修改配送日期(仅待处理与配送中可改)'), {
status: 400,
code: 'invalid_status',
});
}
try {
assertDeliveryDateOnOrAfterOrderDate(
deliveryDate,
getOrderDateFromCreatedAt(order.created_at)
);
} catch (dateError) {
// 守卫抛普通 Error,不映射会被兜底成 500;这是用户输入问题,应为 400。
throw Object.assign(
dateError instanceof Error ? dateError : new Error(String(dateError)),
{ status: 400, code: 'invalid_request' }
);
}
const previous = normalizeDateOnly(order.delivery_date);
let changed = false;
if (previous !== deliveryDate) {
await client.query(
`UPDATE orders SET delivery_date = $1, updated_at = NOW() WHERE order_code = $2`,
[deliveryDate, orderCode]
);
changed = true;
}
await client.query('COMMIT');
if (changed) {
await writeAuditLog({
operatorId: params.operatorId || null,
operatorRole: params.operatorRoles || null,
operationType: 'order_delivery_date_edit',
targetTable: 'orders',
targetId: orderCode,
oldValue: { order_code: orderCode, delivery_date: previous },
newValue: {
order_code: orderCode,
delivery_date: deliveryDate,
order_status: Number(order.order_status),
via: 'order_list_inline',
},
branchCode: order.branch_code || null,
actionCategory: 'order',
}).catch(() => undefined);
}
return {
order_code: orderCode,
delivery_date: deliveryDate,
changed,
previous_delivery_date: previous,
};
} catch (error) {
await client.query('ROLLBACK').catch(() => undefined);
throw error;
} finally {
await resetExclusiveTenantClient(client).catch(() => undefined);
client.release();
}
}
export type OrderDeliveryAddressPatchResult = {
order_code: string;
delivery_address: string | null;
previous_delivery_address: string | null;
changed: boolean;
};
/**
* 单独改「收货地址」(表头字段,**不带明细**)。
*
* 为什么需要它(2026-10-11 开发者提出):
* 详情页原来只有一个可编辑的地址输入框,它随 `canEditOrderForStatus` 一起失效
* ⇒ 订单一到 **40/45/50(待配送)** 地址就再也改不了,而"改地址"恰恰是发车前最常见的动作。
* 明细保存(`PATCH /orders/:code/items`)在 40+ 被明细锁挡住,所以这里给一条只写表头的通道:
* **不碰明细、不动状态链**,只 `UPDATE orders.delivery_address`。
*
* 门槛:订单存在、未进垃圾桶、`order_status < 90`(已结案不再改地址,避免与结算单/配送单不一致)。
* 留痕:`operation_logs` 写 `order_delivery_address_edit`(含改前/改后),与配送日修改同口径。
*/
export async function updateOrderDeliveryAddress(params: {
orderCode: string;
deliveryAddress: unknown;
operatorId?: string | null;
operatorRoles?: string | null;
}): Promise<OrderDeliveryAddressPatchResult> {
const orderCode = String(params.orderCode || '').trim();
if (!orderCode) {
throw Object.assign(new Error('缺少订单号'), { status: 400, code: 'invalid_request' });
}
const nextAddress =
params.deliveryAddress === null || params.deliveryAddress === undefined
? ''
: String(params.deliveryAddress).trim();
if (nextAddress.length > 500) {
throw Object.assign(new Error('收货地址过长(最多 500 字)'), {
status: 400,
code: 'invalid_request',
});
}
const client = await connectExclusiveTenantClient();
try {
await client.query('BEGIN');
const found = await client.query(
`SELECT order_code, order_status, delivery_address, deleted_at, branch_code, customer_code
FROM orders WHERE order_code = $1 LIMIT 1`,
[orderCode]
);
const order = found.rows[0];
if (!order) {
throw Object.assign(new Error('订单不存在'), { status: 404, code: 'not_found' });
}
if (order.deleted_at) {
throw Object.assign(new Error('订单在垃圾桶中,不可修改收货地址'), {
status: 409,
code: 'order_trashed',
});
}
const status = Number(order.order_status) || 0;
/**
* 1A(开发者 2026-10-13):**只有未发车(<60)可改** —— 车已经在路上还改地址,
* 骑手按旧路线跑、地址却是新的。原实现只拦 >=90,现收到 60。
*/
if (status >= 60) {
throw Object.assign(
new Error(`订单已发车/完成(状态 ${status}),不可修改收货地址`),
{ status: 409, code: 'delivery_address_too_late' }
);
}
const previous = order.delivery_address ? String(order.delivery_address) : null;
let changed = false;
if ((previous || '') !== nextAddress) {
/**
* `delivery_address_overridden = true`:**以我方改为准** ——
* 主系统后续回写(改量/改供等)不得覆盖这个地址。
*/
await client.query(
`UPDATE orders
SET delivery_address = $1,
delivery_address_overridden = true,
updated_at = NOW()
WHERE order_code = $2`,
[nextAddress || null, orderCode]
);
/**
* 客户档案地址同步(开发者追加要求):客户列表/客户详情随之显示新地址,
* 以后给该客户录单默认带出;**该客户的历史订单地址不动**(各自是取证信息)。
*/
const customerCode = String(order.customer_code || '').trim();
if (customerCode && nextAddress) {
await client.query(`UPDATE customers SET address = $2 WHERE customer_code = $1`, [
customerCode,
nextAddress,
]);
}
changed = true;
}
await client.query('COMMIT');
// 2A:重新地理编码 + 重排该骑手未完成站点(失败不影响地址已保存;在事务提交之后做)
try {
const { applyDeliveryAddressSideEffects } = await import('./orderDeliveryAddressService');
const effects = await applyDeliveryAddressSideEffects({
orderCode,
branchCode: order.branch_code || null,
address: nextAddress,
customerCode: order.customer_code || null,
});
void effects;
} catch (error: unknown) {
console.error('[delivery-address] 副作用失败:', (error as Error)?.message || error);
}
if (changed) {
await writeAuditLog({
operatorId: params.operatorId || null,
operatorRole: params.operatorRoles || null,
operationType: 'order_delivery_address_edit',
targetTable: 'orders',
targetId: orderCode,
oldValue: { order_code: orderCode, delivery_address: previous },
newValue: {
order_code: orderCode,
delivery_address: nextAddress || null,
order_status: status,
via: 'order_detail_header',
},
branchCode: order.branch_code || null,
actionCategory: 'order',
}).catch(() => undefined);
}
return {
order_code: orderCode,
delivery_address: nextAddress || null,
previous_delivery_address: previous,
changed,
};
} catch (error) {
await client.query('ROLLBACK').catch(() => undefined);
throw error;
} finally {
await resetExclusiveTenantClient(client).catch(() => undefined);
client.release();
}
}