order_items 原本无 spec 列,录单填的规格被丢弃(建单 INSERT 不含该列)。本轮加列 + 建单写入 + 详情表商品名后加只读「规格」列(三语)。
- 迁移 20261050:各 schema 给 order_items 加 spec VARCHAR(60)(可空、不回溯)
- 建单 INSERT 落 spec(trim / 60 字上限)
- 详情表 colCount 15/12→16/13、合计行 colSpan 6→7,契约测试钉住手写列对齐
- 详情读数 select('*') 已带出 spec,无需改查询
另入库「订单入库补字段」设计草案(待拍板,未实现)。
819 lines
33 KiB
TypeScript
819 lines
33 KiB
TypeScript
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(
|
||
/**
|
||
* `self_pickup`:**录单时从客户主数据快照**(2026-10-15「是否取货」需求)。
|
||
* 用子查询而不是让调用方透传:一处收口、原子读同一事务;客户开关事后改了**不影响已有单**。
|
||
* 客户不存在/未设置 ⇒ false(存量行为完全不变)。
|
||
*
|
||
* ⚠️ **必须用独立参数 `$13` 传客户编码**(不能复用 `$4`):PG 会把 `$4` 在 VALUES 里推断为
|
||
* `text`、在 `customers.customer_code = $4` 里推断为 `character varying` ⇒ 直接报
|
||
* `inconsistent types deduced for parameter $4`(本地实测;`::text` 显式转换也救不了)。
|
||
*/
|
||
`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,
|
||
self_pickup
|
||
) VALUES (
|
||
$1, $2, $3, $4, 20, $5, $6, $7, $8, $9, $10, $11, $12,
|
||
COALESCE((SELECT c.is_self_pickup FROM customers c WHERE c.customer_code = $13 LIMIT 1), false)
|
||
)`,
|
||
[
|
||
params.orderCode,
|
||
params.cycleCode,
|
||
params.bidCode,
|
||
params.customerCode,
|
||
params.totalAmount,
|
||
params.totalWeight,
|
||
params.remark,
|
||
params.userId,
|
||
params.branchCode,
|
||
params.deliveryDate,
|
||
params.deliveryTimeSlot,
|
||
params.deliveryAddress,
|
||
// $13:只给子查询用(避免与 VALUES 里的 $4 参数类型推断冲突,见上)
|
||
params.customerCode,
|
||
]
|
||
);
|
||
|
||
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;
|
||
// 订单行商品规格(录单录入/人工修正的原文;60 字上限,与录单一致)
|
||
const spec =
|
||
String(item.spec ?? item.specification ?? '').trim().slice(0, 60) || 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, spec
|
||
) VALUES ($1, $2, $3, $4, $5, $6, $7, 10, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19::uuid[], $20, $21)
|
||
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,
|
||
spec,
|
||
]
|
||
);
|
||
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,
|
||
};
|
||
}
|