Files
SupplierSystem/server/src/services/orderPricingService.ts
T
Ubuntu deb3e72750
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
chore: 以 AI 生鲜配送系统 当前版本作为 SupplierSystem 起点
来源仓库:jxc/ai-fresh-delivery
来源提交:f0b1a180e2deb7e4673b9d1c8542619f7bc0f73d
快照树:  09f679334ff38f0ff25e907961c94a8223bcaedd(与来源 HEAD 工作树逐字节一致,3801 个文件)

按约定本仓库不带任何历史提交:来源仓库的历史中含真实凭据
(生产 SSH 私钥 deploy/id_rsa_tencent、server/.env、.env.tencent/.env.production/.env.gitea、
deploy/小程序AppSecret.txt,其中 MP_APPSECRET / S3 AccessKey 经哈希比对与线上同值),
整包推送会把这些凭据永久带入本仓库,故只取「当前版本」的单提交快照。
供应商系统后续开发自本提交开始。
2026-10-08 17:35:43 +08:00

380 lines
14 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 type { PoolClient } from 'pg';
import { pool } from '../db';
import { applySaleDiscount } from '../utils/discountRate';
import {
resolveItemDisplayName,
resolveItemSkuCode,
resolveLastSalePriceList,
} from './lastSalePriceByNameSpecService';
import { resolveActiveQuoteSheetForCustomer } from './quoteSheetService';
type Db = Pick<PoolClient, 'query'> | typeof pool;
export function calcItemAmount(quantity: number, price: number) {
return Math.round(quantity * price * 100) / 100;
}
/** 单位规范化,便于「斤/市斤」「公斤/kg」互通匹配 */
export function normalizeUnitKey(unit: string | null | undefined): string {
const raw = String(unit || '').trim().toLowerCase();
if (!raw) return '';
if (raw === '斤' || raw === '市斤' || raw === 'jin') return '斤';
if (raw === '公斤' || raw === '千克' || raw === 'kg' || raw === 'kilo') return '公斤';
if (raw === '只' || raw === '个' || raw === '件' || raw === '条') return raw;
return String(unit || '').trim();
}
export function unitsEquivalent(a: string | null | undefined, b: string | null | undefined): boolean {
const left = normalizeUnitKey(a);
const right = normalizeUnitKey(b);
if (!left || !right) return false;
return left === right;
}
function firstPriceBySku(rows: Array<{ sku_code: string; price: unknown }>): Map<string, number> {
const map = new Map<string, number>();
for (const row of rows) {
const code = row.sku_code;
if (!code || map.has(code)) continue;
const price = Number(row.price) || 0;
if (price > 0) map.set(code, price);
}
return map;
}
async function resolveCustomerBranch(db: Db, customerCode: string): Promise<string | null> {
if (!customerCode.trim()) return null;
const customerResult = await db.query(
`SELECT branch_code FROM customers WHERE customer_code = $1 LIMIT 1`,
[customerCode.trim()]
);
return customerResult.rows[0]?.branch_code ?? null;
}
/**
* 按客户 + SKU + 可选单位解析售价。
* 有 unit 时优先匹配报价单位;无单位命中则不回退到「只」价(避免只价当斤价)。
*/
export async function resolveSkuPriceForCustomer(
customerCode: string,
skuCode: string,
unit?: string | null,
db: Db = pool
): Promise<number | null> {
const code = String(skuCode || '').trim();
const customer = String(customerCode || '').trim();
if (!code || !customer) return null;
const branchCode = await resolveCustomerBranch(db, customer);
const unitKey = normalizeUnitKey(unit);
if (unitKey) {
const quoteByUnit = await db.query(
`SELECT price, unit
FROM customer_quote_versions
WHERE customer_code = $1 AND status = 1
AND (approval_status = 30 OR approval_status IS NULL)
AND (expires_at IS NULL OR expires_at > NOW())
AND sku_code = $2
AND branch_code IS NOT DISTINCT FROM $3
ORDER BY effective_at DESC NULLS LAST`,
[customer, code, branchCode]
);
let base: number | null = null;
for (const row of quoteByUnit.rows) {
if (unitsEquivalent(String(row.unit || ''), unitKey) && Number(row.price) > 0) {
base = Number(row.price);
break;
}
}
if (base == null) {
// 单位已指定但无匹配报价:不回退只价/无单位价
return null;
}
const dr = await db.query(
`SELECT discount_rate FROM customer_skus
WHERE customer_code = $1 AND sku_code = $2 LIMIT 1`,
[customer, code]
);
return applySaleDiscount(base, dr.rows[0]?.discount_rate);
}
const map = await resolveSkuPricesForCustomer(customer, [code], db);
const price = map.get(code);
return price && price > 0 ? price : null;
}
/** 客户报价 > 中标价 > 价格偏好(商品档案已无销售价) */
export async function resolveSkuPricesForCustomer(
customerCode: string,
skuCodes: string[],
db: Db = pool,
includeQuoteVersions = true
): Promise<Map<string, number>> {
const codes = [...new Set(skuCodes.filter(Boolean))];
if (!codes.length) return new Map();
const trimmedCustomer = customerCode.trim();
const customerBranch = await resolveCustomerBranch(db, trimmedCustomer);
const [quoteResult, bidResult, customerSkuResult] = await Promise.all([
trimmedCustomer && includeQuoteVersions
? db.query(
`SELECT DISTINCT ON (sku_code) sku_code, price
FROM customer_quote_versions
WHERE customer_code = $1 AND status = 1
AND (approval_status = 30 OR approval_status IS NULL)
AND (expires_at IS NULL OR expires_at > NOW())
AND sku_code = ANY($2)
AND branch_code IS NOT DISTINCT FROM $3
ORDER BY sku_code, effective_at DESC NULLS LAST`,
[trimmedCustomer, codes, customerBranch]
)
: Promise.resolve({ rows: [] as Array<{ sku_code: string; price: unknown }> }),
db.query(
`SELECT DISTINCT ON (sku_code) sku_code, price
FROM bid_prices WHERE status = 1 AND sku_code = ANY($1)
ORDER BY sku_code, created_at DESC NULLS LAST`,
[codes]
),
trimmedCustomer
? db.query(
`SELECT sku_code, price_preference AS price, discount_rate FROM customer_skus
WHERE customer_code = $1 AND sku_code = ANY($2)`,
[trimmedCustomer, codes]
)
: Promise.resolve({
rows: [] as Array<{ sku_code: string; price: unknown; discount_rate: unknown }>,
}),
]);
const quoteMap = firstPriceBySku(quoteResult.rows);
const bidMap = firstPriceBySku(bidResult.rows);
const preferenceMap = firstPriceBySku(customerSkuResult.rows);
const discountBySku = new Map<string, unknown>();
for (const row of customerSkuResult.rows) {
const code = String(row.sku_code || '').trim();
if (code && !discountBySku.has(code)) discountBySku.set(code, row.discount_rate);
}
const result = new Map<string, number>();
for (const code of codes) {
const base = quoteMap.get(code) ?? bidMap.get(code) ?? preferenceMap.get(code) ?? 0;
if (!(base > 0)) continue;
// 报价/中标/偏好基准价 × 客户商品库折扣率
result.set(code, applySaleDiscount(base, discountBySku.get(code)));
}
return result;
}
/**
* 不按单位兜底:取该客户该 SKU 最新生效报价(status=1、未过期、按 effective_at 倒序)。
* 用于报价单位与下单单位不一致时的回退取价,避免静默 0 价。
*/
export async function resolveSkuPricesAnyUnitForCustomer(
customerCode: string,
skuCodes: string[],
db: Db = pool
): Promise<Map<string, number>> {
const codes = [...new Set(skuCodes.filter(Boolean))];
if (!codes.length) return new Map();
const trimmedCustomer = customerCode.trim();
if (!trimmedCustomer) return new Map();
const customerBranch = await resolveCustomerBranch(db, trimmedCustomer);
const r = await db.query(
`SELECT DISTINCT ON (sku_code) sku_code, price
FROM customer_quote_versions
WHERE customer_code = $1 AND status = 1
AND (expires_at IS NULL OR expires_at > NOW())
AND sku_code = ANY($2)
AND branch_code IS NOT DISTINCT FROM $3
ORDER BY sku_code, effective_at DESC NULLS LAST`,
[trimmedCustomer, codes, customerBranch]
);
const result = new Map<string, number>();
for (const row of r.rows) {
const price = Number(row.price) || 0;
if (price > 0 && !result.has(row.sku_code)) result.set(row.sku_code, price);
}
return result;
}
/** 客户执行中报价单:sku -> 销售价(约定执行价,不再乘折扣) */
async function resolveActiveQuoteSheetSalePrices(
customerCode: string,
skuCodes: string[],
branchCode?: string | null,
db: Db = pool
): Promise<Map<string, number>> {
const codes = [...new Set(skuCodes.filter(Boolean))];
const result = new Map<string, number>();
if (!codes.length || !customerCode.trim()) return result;
const sheetCode = await resolveActiveQuoteSheetForCustomer(db, customerCode.trim(), branchCode);
if (!sheetCode) return result;
const r = await db.query(
`SELECT sku_code, COALESCE(NULLIF(sale_price, 0), NULLIF(price, 0), 0)::numeric AS sale_price
FROM customer_quote_sheet_items
WHERE quote_sheet_code = $1
AND sku_code = ANY($2)`,
[sheetCode, codes]
);
for (const row of r.rows) {
const code = String(row.sku_code || '').trim();
const sale = Number(row.sale_price) || 0;
if (code && sale > 0 && !result.has(code)) result.set(code, sale);
}
return result;
}
/**
* 履约单位变更后重取客户销售价:
* **生效报价单销售价优先** → 单位精确的报价版本(含折扣) → 任意单位报价版本(含折扣)。
*
* 为什么报价单必须排第一:新报价单表(customer_quote_sheets)与旧版本表
* (customer_quote_versions)并存,而「完成自采/备货自动调价」「完成回写」「录单回写」
* 三类回写**只写新表**。若这里仍以旧版本表优先,单位一变更就会拿旧价把刚调好的销售价
* 冲回去(2026-10-07 实测:报价单 6.00、旧表 5.00 时订单行被改回 5.00)。
* 录单预填(enrichOrderItemsWithPrices)自 70ff73ff 起同样以报价单优先,两边口径必须一致。
* 见 docs/design/20261007-quote-sale-price-priority-and-writeback.md、
* docs/design/20260807-mp-picking-editable-unit.md
*/
export async function resolveSkuSalePriceForUnitChange(
customerCode: string,
skuCode: string,
settlementUnit?: string | null,
db: Db = pool
): Promise<number | null> {
const code = String(skuCode || '').trim();
const customer = String(customerCode || '').trim();
if (!code || !customer) return null;
const branchCode = await resolveCustomerBranch(db, customer);
const sheetMap = await resolveActiveQuoteSheetSalePrices(customer, [code], branchCode, db);
const sheetSale = sheetMap.get(code) ?? 0;
if (sheetSale > 0) return sheetSale;
const byUnit = await resolveSkuPriceForCustomer(customer, code, settlementUnit, db);
if (byUnit != null && byUnit > 0) return byUnit;
const anyUnitMap = await resolveSkuPricesAnyUnitForCustomer(customer, [code], db);
const base = anyUnitMap.get(code) ?? 0;
if (!(base > 0)) return null;
const dr = await db.query(
`SELECT discount_rate FROM customer_skus
WHERE customer_code = $1 AND sku_code = $2 LIMIT 1`,
[customer, code]
);
const priced = applySaleDiscount(base, dr.rows[0]?.discount_rate);
return priced > 0 ? priced : null;
}
export async function enrichPrefillRowsWithPrices(
customerCode: string,
rows: Array<{
sku_code: string;
sku_name?: string;
unit?: string;
avg_qty?: number | string;
[key: string]: unknown;
}>,
branchCode?: string | null
) {
const skuCodes = rows.map((row) => row.sku_code).filter(Boolean);
const lastSaleItems = rows.map((row) => ({
item_name: row.sku_name,
sku_name: row.sku_name,
sku_code: row.sku_code,
}));
const [sheetSaleMap, lastSalePrices, priceMap] = await Promise.all([
resolveActiveQuoteSheetSalePrices(customerCode, skuCodes, branchCode),
resolveLastSalePriceList({ customerCode, branchCode, items: lastSaleItems }),
resolveSkuPricesForCustomer(customerCode, skuCodes, pool, false),
]);
return rows.map((row, index) => {
const quantity = Math.max(1, Math.round(Number(row.avg_qty) || 1));
const lastSale = lastSalePrices[index];
const sheetSale = sheetSaleMap.get(row.sku_code) ?? 0;
const price =
sheetSale > 0
? sheetSale
: lastSale != null && lastSale > 0
? lastSale
: priceMap.get(row.sku_code) ?? 0;
return {
...row,
quantity,
price,
amount: calcItemAmount(quantity, price),
};
});
}
export async function enrichOrderItemsWithPrices<
T extends {
sku_code?: string | null;
skuCode?: string;
price?: number;
quantity?: number;
unit?: string;
item_name?: string;
sku_name?: string;
originalName?: string;
spec?: string | null;
processing_method?: string | null;
processingMethod?: string | null;
needs_customer_price?: boolean;
price_source?: string | null;
},
>(
customerCode: string,
items: T[],
branchCode?: string | null
): Promise<Array<T & { price: number; amount: number }>> {
const skuCodes = items.map((item) => resolveItemSkuCode(item)).filter(Boolean);
const needLastSale = items.some(
(item) => !(Number(item.price) > 0) && Boolean(resolveItemDisplayName(item))
);
const [sheetSaleMap, lastSalePrices, priceMap] = await Promise.all([
resolveActiveQuoteSheetSalePrices(customerCode, skuCodes, branchCode),
needLastSale
? resolveLastSalePriceList({ customerCode, branchCode, items })
: Promise.resolve(items.map(() => null as number | null)),
resolveSkuPricesForCustomer(customerCode, skuCodes, pool, false),
]);
return items.map((item, index) => {
const code = resolveItemSkuCode(item);
const quantity = Number(item.quantity) || 1;
const existing = Number(item.price) || 0;
let price = existing;
let priceSource = item.price_source ?? null;
if (!(price > 0)) {
const lastSale = lastSalePrices[index];
const sheetSale = code ? sheetSaleMap.get(code) ?? 0 : 0;
if (sheetSale > 0) {
price = sheetSale;
priceSource = 'quote_sheet';
} else if (lastSale != null && lastSale > 0) {
// 上次成交价不再乘折扣
price = lastSale;
priceSource = 'last_sale_name_spec';
} else {
price = priceMap.get(code) ?? 0;
}
}
const needsPrice = price <= 0;
return {
...item,
price,
amount: calcItemAmount(quantity, price),
needs_customer_price: needsPrice ? true : (item.needs_customer_price ?? false),
price_source: needsPrice ? 'missing' : priceSource,
};
});
}