Files
SupplierSystem/server/src/services/customerOrderSubmitService.ts
T
Ubuntu 9005c096b2
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(状态推进): 抵扣完毕必须由代码当次推进 —— 判据收口为一份 + 三条写入路径都补推进
开发者 2026-10-13:「都抵扣完了为什么订单还是卡在待分配……代码层面存在问题 核查一下,
不能光靠脚本,我需要后续不能出现类似的情况……这个待分拣应该是定时器兜底机制推进过去的」。

核查结论(operation_logs 真库时间线):
  09:48:06 点「库存抵扣」→ 抵 46.064 斤、**仍有缺口**(苹果 13.784 / 抄手皮 3.152)
           ⇒ 路由内推进器给「尚有未履约明细」、**状态保持 20** ✅ 这是正确的;
  09:51:22 `order_status_reconcile` 与同一次按钮请求同毫秒(.661 / 响应 .694)
           ⇒ 当时的 45 是**这次请求内**推进的,不是 15 分钟调度器。
所以截图「还写待分配」是有缺口时的正确表现;真正要补的是"有些写入路径只有定时器兜底"。

代码层收口(两件,均由测试钉住):
① 「该行已履约」判据只留**一份** —— `orderItemFulfillmentService.FULFILLED_BRANCHES_SQL`,
   分配侧 `isOrderItemFulfillmentValid` 与推进器 `listUncoveredOrderItems` 共用。
   此前两条查询各写一遍(文件里自己写着「必须同改」)——一次漂移就会出现
   「分配侧认为已履约 ⇒ 推到 30/45,推进器却认为有缺口」的自相矛盾;现在结构上不可能漂移。
   库存履约分支仍要求**足额**(stock_cover_qty ≥ quantity),缺口一律不推进。
② 三条写入路径都在**当次请求内**推进(幂等、失败只告警):
   · 主系统导入(建单/追加)→ `advanceImportedOrders()`(推送与拉取两条通道)
   · 订单详情/小程序改明细保存 → `syncOrderManageItems()` 提交后
   · Web/小程序下单提交 → `customerOrderSubmitService` COMMIT 后
   · 「库存抵扣」按钮 → 路由 reconcileOrderWorkflowStatus(原本就有)
   触发条件统一「本次没建备货也没建自采且状态刚被置 30」,推进器内部按
   uncovered / pendingPreps / pendingPurchases 严格判断。

真库实测(同一个调用内完成,与定时器无关;验证单已删、账外余额已回补):
  A 部分抵扣(米块 10 斤,账外只够 6)⇒ 状态 **20 待分配**、无备货/自采 ✅ 不推进
  B 全额抵扣(米块 6 斤)           ⇒ 状态 **45 待分拣** ✅ 当次完成

回归:server 套件 26 failed files = 基线(无新增;33 failed / 2707 passed);
更新 3 个按"判据两份"写的旧断言(directToDeliveryMode / stockCoverGuard / inventoryFullCoverFulfillment)
为"单份共享常量";root+server tsc exit 0;门禁 8 通过/1 已知红/1 未执行。
2026-10-13 18:03:13 +08:00

800 lines
32 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 { PoolClient } from 'pg';
import { isIndependentInboundCustomer } from './independentInbound';
import { pool } from '../db';
import { assertCustomerCredit } from './customerBudgetService';
import { enrichCustomerOrderItems } from './customerOrderEnrichService';
import { calcItemAmount, enrichOrderItemsWithPrices } from './orderPricingService';
import { compensateOrderItemCostDetails } from './orderCostPostingService';
import { learnAlias, syncCustomerMappings } from './orderParseService';
import { reprocessOrderAllocation } from './orderAllocationService';
import { applyDirectToDeliveryAfterAllocation } from './directToDeliveryService';
import {
syncWarehouseProcessingDemandForOrder,
syncWarehouseProcessingDemandForOrderAfterCommit,
} from './processingDemandSheetService';
import { withAllocationSlot } from './allocationConcurrency';
import {
assertDeliveryDateOnOrAfterOrderDate,
formatChinaDate,
getDefaultDeliveryDate,
normalizeDateOnly,
} from './orderDeliveryDate';
import { assertBranchAllowsOrders } from './platformBranch';
import {
normalizeProcessingOwner,
resolveProcessUnitPriceForOrderItem,
seedOrderItemUnitCost,
} from './processingMethodUtils';
import {
applyEnsuredSkuCodes,
ensureOrderProductsInCatalog,
type EnsuredOrderProductCatalog,
} from './orderProductCatalogService';
import { allocateOrderCode, type OrderEntryChannel } from './orderCodeService';
function tomorrowChinaDate() {
return getDefaultDeliveryDate();
}
/** 录单弱引用:支持单 id 或多 id(多供应商报告) */
function normalizeQualityReportIds(item: Record<string, unknown>): string[] {
const fromArr = Array.isArray(item.quality_report_ids)
? item.quality_report_ids.map((x) => String(x || '').trim()).filter(Boolean)
: [];
const single = String(item.quality_report_id || '').trim();
const ids = fromArr.length ? fromArr : single ? [single] : [];
return [...new Set(ids)];
}
export interface SubmitMobileCustomerOrderInput {
customerCode: string;
branchCode: string | null;
userId: string | null;
items: Array<Record<string, unknown>>;
remark?: string | null;
deliveryDate?: string | null;
deliveryTimeSlot?: string | null;
deliveryAddress?: string | null;
cycleCode?: string;
bidCode?: string;
smartClassifyEnabled?: boolean;
/** 录单分类写入商品主数据;未指定时,用户手动改分类的明细会自动同步 */
syncToProductCatalog?: boolean;
/**
* 确认将缺失商品写入基础商品库。
* 未确认且存在需新建商品时,事务回滚并抛出 needs_confirm_new_products。
*/
confirmNewProducts?: boolean;
/** 录单入口:WEB / MP / CP / API,影响订单号前缀 */
entryChannel?: OrderEntryChannel | string | null;
/** 解析会话ID,用于关联导入解析结果 */
parseSessionId?: string | null;
/**
* 放行零价明细(提交 + 分配两处闸门)。
* 仅「主系统分配任务导入建单」传 true:主系统给的就是成本价,那边未定价时为 0。
* 人工录单不要传,保持"售价为 0 禁止提交"的既有约束。
*/
allowUnpriced?: boolean;
/**
* **主系统分配任务导入建单专用**:本单明细**不自动分配**(先库存抵扣,缺口留「未分配」等人工选择)。
*
* 开发者 2026-10-13:主系统分配过来的应该是**先库存抵扣**,缺少的部分才由人选择「分配给供应商 / 自采」,
* 不能替他直接分配好给谁(替分配会连带产生厂商应付,并让库存抵扣永远轮不到)。
* 实现=给 `reprocessOrderAllocation` 传既有语义 `preferItemSuppliers: true`:
* 只按明细已有供应商落履约,未指定行保持待分配;抵扣仍在分配入口**先**跑。
* 人工录单 / 小程序下单不要传。
* 见 docs/design/20261013-主系统导入单默认未分配(先抵扣后人工选择供应商或自采).md §2
*/
keepItemsUnassigned?: boolean;
}
export interface SubmitMobileCustomerOrderResult {
success: true;
order_code: string;
order_status: number;
budget: Awaited<ReturnType<typeof assertCustomerCredit>>;
allocation?: Awaited<ReturnType<typeof reprocessOrderAllocation>>;
allocation_message?: string;
new_products_created?: number;
new_product_names?: string[];
ensured_products?: EnsuredOrderProductCatalog[];
/** 未匹配到报价的零价明细(前端据此提示补价) */
zero_price_items?: Array<{ item_name: string; sku_code: string | null; quantity: number; unit: string }>;
zero_price_count?: number;
}
async function insertOrderWithItems(
client: PoolClient,
params: {
orderCode: string;
customerCode: string;
branchCode: string | null;
userId: string | null;
pricedItems: any[];
totalAmount: number;
totalWeight: number;
/** 备注:仅用户显式填写时有值,否则 null(不再自动填来源标记) */
remark: string | null;
deliveryDate: string | null;
deliveryTimeSlot: string | null;
deliveryAddress: string | null;
cycleCode: string;
bidCode: string;
}
) {
await client.query(
`INSERT INTO orders (
order_code, cycle_code, bid_code, customer_code, order_status, total_amount, total_weight,
remark, created_by, branch_code, delivery_date, delivery_time_slot, delivery_address
) VALUES ($1, $2, $3, $4, 20, $5, $6, $7, $8, $9, $10, $11, $12)`,
[
params.orderCode,
params.cycleCode,
params.bidCode,
params.customerCode,
params.totalAmount,
params.totalWeight,
params.remark,
params.userId,
params.branchCode,
params.deliveryDate,
params.deliveryTimeSlot,
params.deliveryAddress,
]
);
const skuCodes = params.pricedItems
.map((item) => (item.sku_code ? String(item.sku_code) : ''))
.filter(Boolean);
const { resolveActiveQuoteSheetCostPrices } = await import('./orderItemUnitCostService');
const quoteCostBySku = await resolveActiveQuoteSheetCostPrices(
params.customerCode,
skuCodes,
params.branchCode,
client
);
for (let index = 0; index < params.pricedItems.length; index += 1) {
const item = params.pricedItems[index];
const quantity = Number(item.quantity || 0) || 1;
const unit = String(item.unit || '斤');
const name = String(
item.original_name || item.originalName || item.item_name || item.sku_name || ''
).trim();
const skuCode = item.sku_code ? String(item.sku_code) : null;
const price = Number(item.price) || 0;
const amount = calcItemAmount(quantity, price);
const computedCost =
skuCode && quoteCostBySku.has(skuCode)
? Number(quoteCostBySku.get(skuCode)) || 0
: Math.max(0, Number((item as { cost_price?: number }).cost_price) || 0);
const processingMethod = String(item.processing_method || item.processingMethod || '').trim() || null;
const processingOwner = normalizeProcessingOwner(
processingMethod,
item.processing_owner || item.processingOwner
);
const unitCost = seedOrderItemUnitCost({
processingMethod,
processingOwner,
computedCost,
});
const processUnitPrice = resolveProcessUnitPriceForOrderItem(
processingOwner,
item.process_unit_price ?? item.processUnitPrice
);
const categoryCode = item.category_code ? String(item.category_code) : null;
const categoryName = item.category_name ? String(item.category_name) : null;
const remarkRaw = String(item.remark || '').trim();
const remark = remarkRaw ? remarkRaw.slice(0, 500) : null;
const qualityReportIds = normalizeQualityReportIds(item);
const qualityReportId = qualityReportIds[0] || null;
if (!name) continue;
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)));
const missing = qualityReportIds.filter((id) => !found.has(id));
if (missing.length) {
throw Object.assign(new Error(`明细「${name}」选用的质检报告不存在或已作废`), {
status: 400,
code: 'invalid_quality_report',
});
}
}
/**
* 「独立进货」单(哨兵客户,2026-10-12):**没有销售价** —— 进货单不卖给客户,
* 销售价/金额一律写 0 ⇒ 所有"销售额"公式(订单金额、行销售额、返利、毛利)天然算 0,
* 而成本(`unit_cost`)与供应商应付照常。见 docs/design/20261012-独立进货(自用哨兵客户).md §6
*/
const independentInbound = isIndependentInboundCustomer(params.customerCode);
const revenuePrice = independentInbound ? 0 : price;
const revenueAmount = independentInbound ? 0 : amount;
const insertedItem = await client.query(
`INSERT INTO order_items (
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
) VALUES ($1, $2, $3, $4, $5, $6, $7, 10, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19::uuid[], $20)
RETURNING id::text AS id`,
[
params.orderCode,
skuCode,
name,
quantity,
unit,
revenuePrice,
revenueAmount,
index + 1,
params.branchCode,
processingMethod,
processingOwner,
categoryCode,
categoryName,
independentInbound ? false : price <= 0 ? true : (item.needs_customer_price ?? false),
independentInbound ? 'independent_inbound' : price <= 0 ? 'missing' : (item.price_source ?? null),
unitCost,
remark,
qualityReportId,
qualityReportIds,
processUnitPrice,
]
);
if (skuCode && unitCost > 0) {
const { upsertOrderSkuPurchaseCostFromUnitCost } = await import('./orderCostPostingService');
const itemId = insertedItem.rows[0]?.id ? String(insertedItem.rows[0].id) : null;
await upsertOrderSkuPurchaseCostFromUnitCost(client, params.orderCode, skuCode, unitCost, {
orderItemId: itemId,
});
}
}
try {
const { upsertOrderItemRemarksSafe } = await import('./customerSkuRemarkService');
await upsertOrderItemRemarksSafe(
client,
params.customerCode,
params.pricedItems.map((item) => ({
sku_code: item.sku_code ? String(item.sku_code) : item.skuCode ? String(item.skuCode) : null,
remark: item.remark != null ? String(item.remark) : null,
}))
);
} catch (error) {
console.warn('[customerSkuRemarks] batch after insert failed:', error);
}
}
type PreparedCustomerOrderSubmit = {
pricedItems: any[];
estimatedAmount: number;
credit: Awaited<ReturnType<typeof assertCustomerCredit>>;
totalWeight: number;
deliveryDate: string;
deliveryTimeSlot: string | null;
deliveryAddress: string | null;
remark: string | null;
};
/** 事务外:分类、报价、信用、零价开关、配送日。不写 orders。 */
async function prepareCustomerOrderSubmit(
input: SubmitMobileCustomerOrderInput
): Promise<PreparedCustomerOrderSubmit> {
const smartClassifyEnabled = input.smartClassifyEnabled !== false;
const enrichedItems = await enrichCustomerOrderItems(input.customerCode, input.items as any, input.branchCode, {
smartClassifyEnabled,
preferCustomerMapping: true,
});
const pricedItems = await enrichOrderItemsWithPrices(
input.customerCode,
enrichedItems as any,
input.branchCode
);
const estimatedAmount = pricedItems.reduce(
(sum: number, item: any) => sum + (Number(item.amount) || Number(item.price || 0) * Number(item.quantity || 0) || 0),
0
);
/**
* 「独立进货」哨兵客户(2026-10-12):它不是真实客户、也不产生应收 ⇒ 跳过"客户必须存在"的信用检查。
* 普通客户仍走原有校验(信用本身不拦单,唯一 block 是客户不存在 —— 那是冻结口径,这里不动)。
*/
const credit = isIndependentInboundCustomer(input.customerCode)
? {
allowed: true,
level: 'ok' as const,
message: '',
creditFrozen: false,
creditLimit: 0,
usedBudget: 0,
orderAmount: Math.max(0, Number(estimatedAmount) || 0),
projectedUsed: Math.max(0, Number(estimatedAmount) || 0),
}
: await assertCustomerCredit(input.customerCode, estimatedAmount);
const { isBlockZeroSaleOnSubmitEnabled } = await import('./blockZeroSaleConfigService');
/**
* 「独立进货」单(哨兵客户)**没有销售价**(价/额写 0)⇒ 不适用"售价为 0 禁止提交"这道闸门。
* 与 `allowUnpriced` 同效,但只对本类单生效,人工录普通单的既有约束不变。
*/
const independentInboundOrder = isIndependentInboundCustomer(input.customerCode);
const blockZeroSale =
input.allowUnpriced === true || independentInboundOrder
? false
: await isBlockZeroSaleOnSubmitEnabled(input.branchCode);
if (blockZeroSale) {
const zeroPricePreview = pricedItems.filter(
(item: any) => (Number(item.price) || 0) <= 0 || item.needs_customer_price === true
);
if (zeroPricePreview.length > 0) {
throw Object.assign(
new Error(
`有 ${zeroPricePreview.length} 条明细售价为 0 或未匹配报价,请先补价后再提交,无法创建订单`
),
{
status: 400,
code: 'zero_price_blocked',
zero_price_items: zeroPricePreview.map((item: any) => ({
item_name: String(
item.original_name || item.originalName || item.item_name || item.sku_name || ''
),
sku_code: item.sku_code ? String(item.sku_code) : null,
quantity: Number(item.quantity) || 0,
unit: String(item.unit || ''),
})),
zero_price_count: zeroPricePreview.length,
}
);
}
}
const totalWeight = pricedItems.reduce((sum: number, item: any) => sum + (Number(item.quantity || 0) || 0), 0);
const deliveryDate = normalizeDateOnly(input.deliveryDate) || tomorrowChinaDate();
const orderDate = formatChinaDate();
assertDeliveryDateOnOrAfterOrderDate(deliveryDate, orderDate);
return {
pricedItems,
estimatedAmount,
credit,
totalWeight,
deliveryDate,
deliveryTimeSlot: String(input.deliveryTimeSlot || '').trim() || null,
deliveryAddress: String(input.deliveryAddress || '').trim() || null,
// 备注不再自动填「小程序客户下单」等来源标记(用户 2026-09-15):
// 只保留显式传入的内容,空则存 null(orders.remark 可空),由用户自行填写。
remark: String(input.remark || '').trim() || null,
};
}
type AllocationResult = Awaited<ReturnType<typeof reprocessOrderAllocation>>;
/** COMMIT 后竞价 defer 跟进:后续分配不传事务 client。 */
async function runDeferredBidFollowUp(params: {
allocation: AllocationResult;
orderCode: string;
customerCode: string;
branchCode: string | null;
userId: string | null;
}): Promise<AllocationResult> {
let allocation = params.allocation;
if (!allocation.deferredForBid) return allocation;
const excludeSkuCodes = allocation.deferredBidSkuCodes || [];
try {
if (allocation.needsAutoBidStart) {
const { runPerOrderAutoBidAfterDefer } = await import('./bidRoundService');
const started = await runPerOrderAutoBidAfterDefer({
orderCode: params.orderCode,
branchCode: params.branchCode,
createdBy: params.userId,
});
if (!started.ok) {
const { resolvePerOrderBidSkipGateAllocOptions } = await import('./bidRoundService');
const skipOpts = await resolvePerOrderBidSkipGateAllocOptions({
orderCode: params.orderCode,
excludeSkuCodes,
started,
});
const followUp = await reprocessOrderAllocation(
params.orderCode,
params.customerCode,
params.branchCode,
undefined,
skipOpts
);
allocation = followUp;
if (skipOpts.excludeSkuCodes?.length) {
allocation.deferredForBid = true;
allocation.deferredBidSkuCodes = skipOpts.excludeSkuCodes;
}
} else if (excludeSkuCodes.length > 0) {
const partial = await reprocessOrderAllocation(
params.orderCode,
params.customerCode,
params.branchCode,
undefined,
{ skipPerOrderAutoBidGate: true, excludeSkuCodes }
);
partial.deferredForBid = true;
partial.deferredBidSkuCodes = excludeSkuCodes;
partial.bidGateMessage = allocation.bidGateMessage;
allocation = partial;
}
} else if (excludeSkuCodes.length > 0) {
const partial = await reprocessOrderAllocation(
params.orderCode,
params.customerCode,
params.branchCode,
undefined,
{ skipPerOrderAutoBidGate: true, excludeSkuCodes }
);
partial.deferredForBid = true;
partial.deferredBidSkuCodes = excludeSkuCodes;
partial.bidGateMessage = allocation.bidGateMessage;
allocation = partial;
}
} catch (followUpError) {
console.warn('[customerOrderSubmit] deferred bid follow-up failed', {
orderCode: params.orderCode,
message: followUpError instanceof Error ? followUpError.message : String(followUpError),
});
try {
const { resolvePerOrderBidSkipGateAllocOptions } = await import('./bidRoundService');
const skipOpts = await resolvePerOrderBidSkipGateAllocOptions({
orderCode: params.orderCode,
excludeSkuCodes,
});
const followUp = await reprocessOrderAllocation(
params.orderCode,
params.customerCode,
params.branchCode,
undefined,
skipOpts
);
allocation = followUp;
if (skipOpts.excludeSkuCodes?.length) {
allocation.deferredForBid = true;
allocation.deferredBidSkuCodes = skipOpts.excludeSkuCodes;
}
} catch {
// 带排除仍失败则停,禁止第三次无排除整单覆盖竞价 SKU
}
}
return allocation;
}
async function buildSubmitAllocationMessage(params: {
allocation: AllocationResult | undefined;
orderStatus: number;
branchCode: string | null;
orderCode: string;
}): Promise<string> {
const { allocation, orderStatus } = params;
let allocationMessage = '';
if (allocation?.deferredForBid && allocation.bidGateMessage) {
allocationMessage = allocation.bidGateMessage;
} else if ((!allocation || allocation.deferredForBid) && orderStatus === 20) {
try {
const { getBidSettings } = await import('./bidConfigService');
const { hasOpenPerOrderBid } = await import('./bidAwardService');
const settings = await getBidSettings(params.branchCode);
if (settings.enabled && settings.per_order_mode === 'auto' && (await hasOpenPerOrderBid(params.orderCode))) {
allocationMessage = '已自动发起竞价,确认中标后将强制分配中标供应商';
}
} catch {
// ignore
}
}
if (!allocationMessage && allocation?.orderStatusUpdated === 30) {
allocationMessage = `已自动分配供应商:备货 ${allocation.preparationsCreated} 项,采购 ${allocation.purchaseOrdersCreated} 项。请等待供应商完成备货后继续流转`;
} else if (!allocationMessage && allocation && allocation.smartAllocationEnabled === false) {
allocationMessage = '智能分配已关闭,订单待手动分配供应商后确认分配';
} else if (
!allocationMessage &&
allocation &&
(allocation.preparationsCreated > 0 || allocation.purchaseOrdersCreated > 0)
) {
allocationMessage = `分配处理 ${allocation.itemsProcessed} 项,备货 ${allocation.preparationsCreated} 项,采购 ${allocation.purchaseOrdersCreated} 项`;
} else if (!allocationMessage && allocation) {
allocationMessage = `分配处理 ${allocation.itemsProcessed} 项,订单待分配(状态 ${allocation.orderStatusUpdated ?? 20})`;
}
return allocationMessage;
}
export async function submitMobileCustomerOrder(
input: SubmitMobileCustomerOrderInput
): Promise<SubmitMobileCustomerOrderResult> {
const items = Array.isArray(input.items) ? input.items : [];
if (!items.length) {
throw Object.assign(new Error('请填写商品'), { status: 400, code: 'invalid_request' });
}
assertBranchAllowsOrders(input.branchCode);
const prepared = await prepareCustomerOrderSubmit({ ...input, items });
const { pricedItems, estimatedAmount, credit, totalWeight, deliveryDate, deliveryTimeSlot, deliveryAddress, remark } =
prepared;
let orderCode = '';
let pricedForInsert = pricedItems;
let newProductNames: string[] = [];
let ensuredProducts: EnsuredOrderProductCatalog[] = [];
let allocation: AllocationResult | undefined;
await withAllocationSlot(async () => {
const client = await pool.connect();
try {
await client.query('BEGIN');
const catalogInputs = pricedItems.map((item: any, index: number) => ({
key: String(item.id || item.key || `line-${index}`),
name: String(
item.original_name || item.originalName || item.item_name || item.sku_name || ''
).trim(),
skuCode: item.sku_code ? String(item.sku_code) : null,
categoryCode: String(item.category_code || item.categoryCode || '').trim(),
unit: item.unit ? String(item.unit) : '斤',
price: Number(item.price) || 0,
}));
const catalogPlan = await ensureOrderProductsInCatalog(client, catalogInputs, input.branchCode);
ensuredProducts = catalogPlan.ensured;
newProductNames = catalogPlan.newProducts.map((row) => row.name);
if (catalogPlan.newProducts.length > 0 && !input.confirmNewProducts) {
await client.query('ROLLBACK');
throw Object.assign(
new Error(
`有 ${catalogPlan.newProducts.length} 个商品不在基础商品库,确认后将自动创建:${newProductNames.slice(0, 8).join('、')}${newProductNames.length > 8 ? '…' : ''}`
),
{
status: 409,
code: 'needs_confirm_new_products',
new_products: catalogPlan.newProducts,
}
);
}
pricedForInsert = applyEnsuredSkuCodes(
pricedItems,
catalogPlan.ensured,
(item: any, index: number) => String(item.id || item.key || `line-${index}`)
);
orderCode = await allocateOrderCode(client, {
channel: input.entryChannel,
branchCode: input.branchCode,
});
await insertOrderWithItems(client, {
orderCode,
customerCode: input.customerCode,
branchCode: input.branchCode,
userId: input.userId,
pricedItems: pricedForInsert,
/**
* 「独立进货」单(哨兵客户):**销售价锁死为 0** ⇒ 订单头金额也必须是 0。
* ⚠️ 2026-10-12 真库实测踩到:只锁明细价/额时,订单头仍按前端传的价算
* (传 99 ⇒ 明细 0 但 `orders.total_amount = 99`),会从订单列表/其它聚合漏成"销售额"。
*/
totalAmount: isIndependentInboundCustomer(input.customerCode) ? 0 : estimatedAmount,
totalWeight,
remark,
deliveryDate,
deliveryTimeSlot,
deliveryAddress,
cycleCode: input.cycleCode || 'MOBILE',
bidCode: input.bidCode || 'MOBILE',
});
// 分配入口内含 per_order 自动竞价闸门(Web /orders/submit 与小程序共用本函数)
allocation = await reprocessOrderAllocation(
orderCode,
input.customerCode,
input.branchCode,
client,
{
bidCreatedBy: input.userId,
allowUnpriced:
input.allowUnpriced === true || isIndependentInboundCustomer(input.customerCode),
/**
* 主系统导入:不跑规则引擎 ⇒ 未指定供应商的行保持「未分配」(抵扣已在入口先跑)。
* 别的入口一律不带 ⇒ 行为不变。
*/
...(input.keepItemsUnassigned === true ? { preferItemSuppliers: true } : {}),
}
);
if (allocation.errors.length && !allocation.deferredForBid) {
throw Object.assign(new Error(allocation.errors.join(';')), {
status: 409,
code: 'order_allocation_incomplete',
});
}
// 补偿:分配完成后,供应商备货已创建,为之前因缺备货而归入 self_purchase 或未成功写入的商品补建 cost_details
await compensateOrderItemCostDetails(client, orderCode);
await syncWarehouseProcessingDemandForOrder(orderCode, client);
// 方案 B(下单即挂应付):下单即按订单行生成/更新供应商结算单。失败不阻断下单(与其它结算同步同款处理)。
try {
const { ensureSupplierStatementsForOrder } = await import('./financeReconciliationService');
await ensureSupplierStatementsForOrder(orderCode, client);
} catch (err) {
console.error('[finance] 下单后同步供应商结算失败', orderCode, err);
}
// 过账扣点:下单时把「客户配置的比例」快照到 order_items.rebate_ratio(只写这一列;
// 客户未开启则全为 NULL)。比例改动只影响此后的新单,历史不追溯。
try {
const { attachOrderRebateSnapshots } = await import('./customerRebateService');
// 这里**故意不传 rowIds**:订单与全部明细都是本事务刚建的(allocateOrderCode 给的新单号),
// 整单即「新建行」。改单路径必须传 rowIds,否则会重刷历史行。
await attachOrderRebateSnapshots({
orderCode,
customerCode: (input as { customerCode?: string }).customerCode || null,
db: client,
});
} catch (error) {
console.error('[rebate] 下单快照失败(不阻断下单):', (error as Error)?.message);
}
await client.query('COMMIT');
/**
* 「全额库存抵扣、没有采购义务」的单:**当次提交内**推进到待分拣(不靠 15 分钟兜底)。
* 本函数用外部事务连接,分配模块的 after-commit 副作用不会跑;推进器自身严格判断,
* 有缺口不会硬推。失败只告警,不影响下单结果。
*/
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-submit] 全额抵扣后推进状态失败(不影响下单)order=${orderCode}:`,
(error as Error)?.message || error
);
}
}
// 嵌套事务场景:闸门仅标记 needsAutoBidStart,提交后再发标;失败回退普通分配 await client.query('COMMIT');
// 嵌套事务场景:闸门仅标记 needsAutoBidStart,提交后再发标;失败回退普通分配
// 发标成功后立刻分配「非竞价范围」商品,避免白菜等被整单卡住
if (allocation) {
allocation = await runDeferredBidFollowUp({
allocation,
orderCode,
customerCode: input.customerCode,
branchCode: input.branchCode,
userId: input.userId,
});
}
await syncWarehouseProcessingDemandForOrderAfterCommit(orderCode);
// 极简流转(按分公司开关,**默认关闭**):录单提交是**外部传入事务**(ownsTransaction=false),
// 分配函数里的后置钩子在这种调用下不会执行 —— 所以提交后再触发一次,保证
// 「录单 → 智能分配 → 直接待配送」在 Web 与小程序(共用本函数)都生效。
// 函数自身幂等 + 状态门槛(只处理状态 30 的单),且失败绝不影响下单。
// 见 docs/design/20261007-direct-to-delivery-mode.md
let directToDeliveryHandled = false;
try {
const direct = await applyDirectToDeliveryAfterAllocation(orderCode, input.branchCode);
directToDeliveryHandled = direct.advanced === true;
} catch (err) {
console.error('[customerOrderSubmit] 极简流转失败(不影响下单)', orderCode, err);
}
// 厂商备货行「分配即供货完成」:录单是外部事务、分配内的后置钩子不执行,提交后补一次
//(建待验入库、回写订单行成本、免入库/直送结算桶、推进订单)。幂等,失败不影响下单。
if (!directToDeliveryHandled) {
try {
const { finalizeAutoCompletedSupplierPreparations } = await import(
'./supplierPreparationStatusService'
);
await finalizeAutoCompletedSupplierPreparations(orderCode, { branchCode: input.branchCode });
} catch (err) {
console.error('[customerOrderSubmit] 自动完成厂商备货失败(不影响下单)', orderCode, err);
}
}
} catch (error: any) {
// needs_confirm 路径已在事务内 ROLLBACK;其它错误再尝试回滚
if (error?.code !== 'needs_confirm_new_products') {
await client.query('ROLLBACK').catch(() => undefined);
}
throw error;
} finally {
client.release();
}
});
try {
await learnAlias({
customerCode: input.customerCode,
items: pricedForInsert
.filter((item: any) => item.sku_code && item.item_name)
.map((item: any) => ({
originalName: String(item.item_name),
skuCode: String(item.sku_code),
skuName: String(item.item_name),
})),
});
} catch (err) {
// 不阻断下单;必须可观测,避免静默丢学习
console.warn('[customerOrderSubmit] learnAlias failed (non-blocking)', {
orderCode,
customerCode: input.customerCode,
message: err instanceof Error ? err.message : String(err),
});
}
const syncCatalogExplicit = input.syncToProductCatalog;
const syncToProductCatalog =
syncCatalogExplicit === true ||
(syncCatalogExplicit !== false &&
pricedForInsert.some((item: any) =>
Boolean(item.category_manually_set || item.categoryManuallySet)
));
/**
* 「独立进货」哨兵客户(2026-10-12)**跳过「客户×商品」映射学习**:
* 它不在 customers 里,学出来的映射没有主人(真库实测会撞 RLS:customer_skus 写不进去)。
*/
try {
if (isIndependentInboundCustomer(input.customerCode)) throw { __skip: true };
await syncCustomerMappings({
customerCode: input.customerCode,
updateProductCatalog: syncToProductCatalog,
items: pricedForInsert.map((item: any) => ({
originalName: String(item.item_name || ''),
skuName: String(item.item_name || ''),
skuCode: item.sku_code ? String(item.sku_code) : undefined,
unit: item.unit,
categoryCode: item.category_code || undefined,
processingMethod: item.processing_method || undefined,
processingOwner: item.processing_owner || undefined,
categoryManuallySet: Boolean(item.category_manually_set || item.categoryManuallySet),
libraryCategoryCode: item.library_category_code || item.libraryCategoryCode || undefined,
})),
});
} catch (err) {
if ((err as { __skip?: boolean })?.__skip) {
// 独立进货单:无客户可学,静默跳过(不是错误)
} else {
console.warn('[customerOrderSubmit] syncCustomerMappings failed (non-blocking)', {
orderCode,
customerCode: input.customerCode,
message: err instanceof Error ? err.message : String(err),
});
}
}
const statusResult = await pool.query(`SELECT order_status FROM orders WHERE order_code = $1`, [orderCode]);
const orderStatus = Number(statusResult.rows[0]?.order_status || 20);
const allocationMessage = await buildSubmitAllocationMessage({
allocation,
orderStatus,
branchCode: input.branchCode,
orderCode,
});
// 录单已硬拦零价,成功路径不应再有零价明细;字段保留兼容前端
return {
success: true,
order_code: orderCode,
order_status: orderStatus,
budget: credit,
new_products_created: newProductNames.length,
new_product_names: newProductNames,
ensured_products: ensuredProducts,
allocation,
allocation_message: allocationMessage,
zero_price_items: [],
zero_price_count: 0,
};
}