Files
SupplierSystem/server/src/services/prepPriceNormalizeService.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

592 lines
19 KiB
TypeScript

import type { PoolClient } from 'pg';
import { pool } from '../db';
type Db = Pick<PoolClient, 'query'>;
export type PackFactors = Record<string, number>;
export type ResolvedPricingFactor = {
pricingUnit: string;
factor: number;
prepUnitNorm: string;
pricingUnitNorm: string;
};
export type NormalizedPrepPrice = {
purchasePrice: number;
purchasePriceNormalized: number;
normalizedPricingUnit: string;
packFactorApplied: number;
prepUnit: string;
};
/** 单位规范化:散装/斤 → 斤;避免混单位均价 */
export function normalizePrepUnit(raw: unknown): string {
const s = String(raw || '')
.trim()
.toLowerCase()
.replace(/\s+/g, '');
if (!s) return '';
if (s.includes('斤')) return '斤';
if (s.includes('公斤') || s === 'kg') return '公斤';
if (s.includes('件')) return '件';
if (s.includes('箱')) return '箱';
if (s.includes('袋')) return '袋';
return s;
}
export function parsePackFactors(raw: unknown): PackFactors {
if (!raw) return {};
let obj: unknown = raw;
if (typeof raw === 'string') {
try {
obj = JSON.parse(raw);
} catch {
return {};
}
}
if (!obj || typeof obj !== 'object' || Array.isArray(obj)) return {};
const out: PackFactors = {};
for (const [k, v] of Object.entries(obj as Record<string, unknown>)) {
const key = normalizePrepUnit(k) || String(k || '').trim();
const n = Number(v);
if (!key || !Number.isFinite(n) || n <= 0) continue;
out[key] = n;
}
return out;
}
export function computeNormalizedPrice(purchasePrice: number, factor: number): number {
const price = Number(purchasePrice);
const f = Number(factor);
if (!Number.isFinite(price) || price < 0) return 0;
if (!Number.isFinite(f) || f <= 0) return 0;
return Math.round((price / f) * 10000) / 10000;
}
/**
* 解析备货单位相对 SKU 计价单位的折算系数。
* 等价单位(含散装/斤→斤)系数为 1;否则查 pack_factors。
*/
export function resolvePricingFactor(input: {
pricingUnit?: string | null;
fallbackUnit?: string | null;
packFactors?: unknown;
prepUnit?: string | null;
}): ResolvedPricingFactor | null {
const pricingUnitRaw =
String(input.pricingUnit || '').trim() || String(input.fallbackUnit || '').trim() || '斤';
const pricingUnitNorm = normalizePrepUnit(pricingUnitRaw) || pricingUnitRaw;
const prepUnitNorm = normalizePrepUnit(input.prepUnit);
if (!prepUnitNorm) return null;
if (prepUnitNorm === pricingUnitNorm) {
return {
pricingUnit: pricingUnitRaw,
factor: 1,
prepUnitNorm,
pricingUnitNorm,
};
}
const factors = parsePackFactors(input.packFactors);
const factor = factors[prepUnitNorm];
if (!Number.isFinite(factor) || factor <= 0) return null;
return {
pricingUnit: pricingUnitRaw,
factor,
prepUnitNorm,
pricingUnitNorm,
};
}
export async function loadSkuPricingMeta(
db: Db,
skuCode: string
): Promise<{ pricingUnit: string; unit: string; packFactors: PackFactors }> {
const code = String(skuCode || '').trim();
if (!code) {
return { pricingUnit: '斤', unit: '斤', packFactors: {} };
}
const catalog = await db.query(
`SELECT unit, pricing_unit, pack_factors
FROM product_catalog
WHERE item_type = 'product' AND code = $1
LIMIT 1`,
[code]
);
if (catalog.rowCount) {
const row = catalog.rows[0];
const unit = String(row.unit || '斤').trim() || '斤';
const pricingUnit = String(row.pricing_unit || unit).trim() || unit;
return {
unit,
pricingUnit,
packFactors: parsePackFactors(row.pack_factors),
};
}
const sku = await db.query(
`SELECT unit, pricing_unit, pack_factors FROM skus WHERE sku_code = $1 LIMIT 1`,
[code]
);
const row = sku.rows[0] || {};
const unit = String(row.unit || '斤').trim() || '斤';
const pricingUnit = String(row.pricing_unit || unit).trim() || unit;
return {
unit,
pricingUnit,
packFactors: parsePackFactors(row.pack_factors),
};
}
export type TryNormalizePrepPriceResult =
| { ok: true; normalized: NormalizedPrepPrice; warning?: undefined }
| { ok: false; normalized?: undefined; warning: string; code: 'prep_price_not_normalizable' };
/**
* 尝试归一;折算失败只返回 warning,不抛(完成/改价不拦截)。
* 缺 sku / 价无效 / 缺单位仍抛 400(必填项)。
*/
export async function tryNormalizePrepPrice(
db: Db,
input: {
skuCode: string | null | undefined;
prepUnit: string | null | undefined;
purchasePrice: number;
/** 「允许成本价为 0」开关(分公司级):开启后 0 可归一(归一价同样为 0) */
allowZero?: boolean;
}
): Promise<TryNormalizePrepPriceResult> {
const skuCode = String(input.skuCode || '').trim();
const prepUnit = String(input.prepUnit || '').trim();
const purchasePrice = Number(input.purchasePrice);
if (!skuCode) {
throw Object.assign(new Error('缺少商品编码,无法归一采购价'), {
status: 400,
code: 'invalid_request',
});
}
if (!Number.isFinite(purchasePrice) || (input.allowZero === true ? purchasePrice < 0 : purchasePrice <= 0)) {
throw Object.assign(new Error('采购价无效'), { status: 400, code: 'invalid_request' });
}
if (!prepUnit) {
throw Object.assign(new Error('缺少备货单位,无法归一采购价'), {
status: 400,
code: 'invalid_request',
});
}
const meta = await loadSkuPricingMeta(db, skuCode);
const resolved = resolvePricingFactor({
pricingUnit: meta.pricingUnit,
fallbackUnit: meta.unit,
packFactors: meta.packFactors,
prepUnit,
});
if (!resolved) {
const pricingLabel = meta.pricingUnit || meta.unit || '斤';
return {
ok: false,
code: 'prep_price_not_normalizable',
warning: `备货单位「${prepUnit}」无法折算到计价单位「${pricingLabel}」。建议在商品档案补充 pack_factors(例如 1${prepUnit}=N${pricingLabel}),以便行情均价与异常价准确`,
};
}
return {
ok: true,
normalized: {
purchasePrice,
purchasePriceNormalized: computeNormalizedPrice(purchasePrice, resolved.factor),
normalizedPricingUnit: resolved.pricingUnit,
packFactorApplied: resolved.factor,
prepUnit,
},
};
}
/** @deprecated 完成/改价请用 tryNormalizePrepPrice;清洗回填等仍可硬校验 */
export async function assertPrepPriceNormalizable(
db: Db,
input: { skuCode: string | null | undefined; prepUnit: string | null | undefined; purchasePrice: number }
): Promise<NormalizedPrepPrice> {
const result = await tryNormalizePrepPrice(db, input);
if (!result.ok) {
throw Object.assign(new Error(result.warning), {
status: 400,
code: result.code,
});
}
return result.normalized;
}
export async function clearPrepNormalizedPrice(db: Db, prepId: string): Promise<void> {
await db.query(
`UPDATE supplier_preparations
SET purchase_price_normalized = NULL,
normalized_pricing_unit = NULL,
pack_factor_applied = NULL,
price_outlier = FALSE
WHERE id = $1::uuid`,
[prepId]
);
}
export async function applyNormalizedPriceToPrep(
db: Db,
prepId: string,
normalized: NormalizedPrepPrice
): Promise<void> {
await db.query(
`UPDATE supplier_preparations
SET purchase_price_normalized = $2,
normalized_pricing_unit = $3,
pack_factor_applied = $4
WHERE id = $1::uuid`,
[
prepId,
normalized.purchasePriceNormalized,
normalized.normalizedPricingUnit,
normalized.packFactorApplied,
]
);
}
/** 同 SKU 已完成归一价中,> max(5×中位, 中位+阈值) 标 price_outlier */
export async function markOutliersForSku(
db: Db,
skuCode: string,
branchCode?: string | null
): Promise<{ marked: number; cleared: number }> {
const code = String(skuCode || '').trim();
if (!code) return { marked: 0, cleared: 0 };
const params: unknown[] = [code];
let branchSql = '';
if (branchCode) {
params.push(branchCode);
branchSql = ` AND branch_code = $${params.length}`;
}
const rows = await db.query(
`SELECT id, purchase_price_normalized
FROM supplier_preparations
WHERE sku_code = $1
AND prepare_status >= 30
AND purchase_price_normalized IS NOT NULL
AND purchase_price_normalized > 0
${branchSql}`,
params
);
const prices = rows.rows
.map((r) => Number(r.purchase_price_normalized))
.filter((n) => Number.isFinite(n) && n > 0)
.sort((a, b) => a - b);
if (prices.length < 3) {
const cleared = await db.query(
`UPDATE supplier_preparations
SET price_outlier = false
WHERE sku_code = $1
AND prepare_status >= 30
${branchSql}
AND price_outlier = true`,
params
);
return { marked: 0, cleared: cleared.rowCount || 0 };
}
const mid = Math.floor(prices.length / 2);
const median =
prices.length % 2 === 1 ? prices[mid] : (prices[mid - 1] + prices[mid]) / 2;
const threshold = Math.max(median * 5, median + Math.max(50, median));
let marked = 0;
let cleared = 0;
for (const row of rows.rows) {
const n = Number(row.purchase_price_normalized);
const isOutlier = Number.isFinite(n) && n > threshold;
const upd = await db.query(
`UPDATE supplier_preparations
SET price_outlier = $2
WHERE id = $1::uuid AND price_outlier IS DISTINCT FROM $2`,
[row.id, isOutlier]
);
if (upd.rowCount) {
if (isOutlier) marked += 1;
else cleared += 1;
}
}
return { marked, cleared };
}
export type PriceNormalizeIssue = {
issue_type: 'missing_factor' | 'mixed_units' | 'suspected_outlier' | 'unnormalized';
sku_code: string;
sku_name?: string | null;
pricing_unit?: string | null;
pack_factors?: PackFactors;
units?: string[];
prep_id?: string;
purchase_price?: number | null;
purchase_price_normalized?: number | null;
unit?: string | null;
message: string;
};
export async function listPriceNormalizeIssues(input?: {
branchCode?: string | null;
limit?: number;
}): Promise<PriceNormalizeIssue[]> {
const branchCode = String(input?.branchCode || '').trim() || null;
const limit = Math.min(Math.max(Number(input?.limit) || 200, 1), 500);
const params: unknown[] = [];
let branchSql = '';
if (branchCode) {
params.push(branchCode);
branchSql = ` AND sp.branch_code = $${params.length}`;
}
const issues: PriceNormalizeIssue[] = [];
const mixed = await pool.query(
`SELECT sp.sku_code,
MAX(COALESCE(pc.name, s.sku_name, sp.item_name, sp.sku_code)) AS sku_name,
MAX(COALESCE(pc.pricing_unit, s.pricing_unit, pc.unit, s.unit, '斤')) AS pricing_unit,
COALESCE(MAX(pc.pack_factors::text), MAX(s.pack_factors::text), '{}') AS pack_factors,
array_agg(DISTINCT NULLIF(TRIM(sp.unit), '') ) FILTER (WHERE NULLIF(TRIM(sp.unit), '') IS NOT NULL) AS units
FROM supplier_preparations sp
LEFT JOIN product_catalog pc ON pc.item_type = 'product' AND pc.code = sp.sku_code
LEFT JOIN skus s ON s.sku_code = sp.sku_code
WHERE sp.prepare_status >= 30
AND sp.created_at >= NOW() - INTERVAL '180 days'
${branchSql}
GROUP BY sp.sku_code
HAVING COUNT(DISTINCT NULLIF(TRIM(sp.unit), '')) > 1
ORDER BY sp.sku_code
LIMIT ${limit}`,
params
);
for (const row of mixed.rows) {
const units = (row.units || []).filter(Boolean).map(String);
const pricingUnit = String(row.pricing_unit || '斤');
const factors = parsePackFactors(row.pack_factors);
const pricingNorm = normalizePrepUnit(pricingUnit) || pricingUnit;
const missing = units.filter((u: string) => {
const n = normalizePrepUnit(u);
if (!n || n === pricingNorm) return false;
return !(factors[n] > 0);
});
if (missing.length) {
issues.push({
issue_type: 'missing_factor',
sku_code: String(row.sku_code),
sku_name: row.sku_name ? String(row.sku_name) : null,
pricing_unit: pricingUnit,
pack_factors: factors,
units,
message: `混单位 ${units.join('/')},缺折算:${missing.join('、')} → ${pricingUnit}`,
});
} else {
issues.push({
issue_type: 'mixed_units',
sku_code: String(row.sku_code),
sku_name: row.sku_name ? String(row.sku_name) : null,
pricing_unit: pricingUnit,
pack_factors: factors,
units,
message: `历史混单位 ${units.join('/')}(系数已齐全,可回填归一)`,
});
}
}
const unnormParams: unknown[] = [];
let unnormBranch = '';
if (branchCode) {
unnormParams.push(branchCode);
unnormBranch = ` AND sp.branch_code = $${unnormParams.length}`;
}
const unnormalized = await pool.query(
`SELECT sp.id, sp.sku_code, sp.unit, sp.purchase_price, sp.purchase_price_normalized,
COALESCE(pc.name, s.sku_name, sp.item_name, sp.sku_code) AS sku_name
FROM supplier_preparations sp
LEFT JOIN product_catalog pc ON pc.item_type = 'product' AND pc.code = sp.sku_code
LEFT JOIN skus s ON s.sku_code = sp.sku_code
WHERE sp.prepare_status >= 30
AND COALESCE(sp.purchase_price, 0) > 0
AND (sp.purchase_price_normalized IS NULL OR sp.purchase_price_normalized <= 0)
AND sp.created_at >= NOW() - INTERVAL '180 days'
${unnormBranch}
ORDER BY sp.created_at DESC
LIMIT ${Math.min(limit, 100)}`,
unnormParams
);
for (const row of unnormalized.rows) {
issues.push({
issue_type: 'unnormalized',
sku_code: String(row.sku_code),
sku_name: row.sku_name ? String(row.sku_name) : null,
prep_id: String(row.id),
unit: row.unit != null ? String(row.unit) : null,
purchase_price: Number(row.purchase_price) || 0,
purchase_price_normalized: row.purchase_price_normalized != null ? Number(row.purchase_price_normalized) : null,
message: `已完成但未归一:¥${Number(row.purchase_price) || 0}/${row.unit || '?'}`,
});
}
const outlierParams: unknown[] = [];
let outlierBranch = '';
if (branchCode) {
outlierParams.push(branchCode);
outlierBranch = ` AND sp.branch_code = $${outlierParams.length}`;
}
const outliers = await pool.query(
`SELECT sp.id, sp.sku_code, sp.unit, sp.purchase_price, sp.purchase_price_normalized,
COALESCE(pc.name, s.sku_name, sp.item_name, sp.sku_code) AS sku_name
FROM supplier_preparations sp
LEFT JOIN product_catalog pc ON pc.item_type = 'product' AND pc.code = sp.sku_code
LEFT JOIN skus s ON s.sku_code = sp.sku_code
WHERE sp.price_outlier = true
AND sp.prepare_status >= 30
${outlierBranch}
ORDER BY sp.created_at DESC
LIMIT ${Math.min(limit, 100)}`,
outlierParams
);
for (const row of outliers.rows) {
issues.push({
issue_type: 'suspected_outlier',
sku_code: String(row.sku_code),
sku_name: row.sku_name ? String(row.sku_name) : null,
prep_id: String(row.id),
unit: row.unit != null ? String(row.unit) : null,
purchase_price: Number(row.purchase_price) || 0,
purchase_price_normalized: row.purchase_price_normalized != null ? Number(row.purchase_price_normalized) : null,
message: `已标记脏价隔离:归一 ¥${Number(row.purchase_price_normalized) || 0}`,
});
}
return issues.slice(0, limit);
}
export async function backfillPrepPriceNormalized(input?: {
branchCode?: string | null;
skuCodes?: string[] | null;
syncDownstream?: boolean;
client?: PoolClient;
}): Promise<{
scanned: number;
updated: number;
skipped: number;
outliersMarked: number;
downstreamSynced: number;
}> {
const ownClient = input?.client ? null : await pool.connect();
const db = input?.client || ownClient!;
const branchCode = String(input?.branchCode || '').trim() || null;
const skuFilter = (input?.skuCodes || []).map((c) => String(c || '').trim()).filter(Boolean);
const syncDownstream = Boolean(input?.syncDownstream);
try {
const params: unknown[] = [];
const conds: string[] = [
'prepare_status >= 30',
'COALESCE(purchase_price, 0) > 0',
`created_at >= NOW() - INTERVAL '365 days'`,
];
if (branchCode) {
params.push(branchCode);
conds.push(`branch_code = $${params.length}`);
}
if (skuFilter.length) {
params.push(skuFilter);
conds.push(`sku_code = ANY($${params.length}::text[])`);
}
const rows = await db.query(
`SELECT id, sku_code, unit, purchase_price, order_code, supplier_code, branch_code
FROM supplier_preparations
WHERE ${conds.join(' AND ')}
ORDER BY created_at DESC
LIMIT 5000`,
params
);
let updated = 0;
let skipped = 0;
let downstreamSynced = 0;
const touchedSkus = new Set<string>();
for (const row of rows.rows) {
try {
const normalized = await assertPrepPriceNormalizable(db, {
skuCode: row.sku_code,
prepUnit: row.unit,
purchasePrice: Number(row.purchase_price),
});
await applyNormalizedPriceToPrep(db, String(row.id), normalized);
updated += 1;
if (row.sku_code) touchedSkus.add(String(row.sku_code));
if (syncDownstream && row.order_code && row.sku_code) {
const { setOrderItemUnitCostByOrderSku } = await import('./orderItemUnitCostService');
await setOrderItemUnitCostByOrderSku(
db,
String(row.order_code),
String(row.sku_code),
normalized.purchasePriceNormalized
);
downstreamSynced += 1;
}
} catch {
skipped += 1;
}
}
let outliersMarked = 0;
for (const sku of touchedSkus) {
const r = await markOutliersForSku(db, sku, branchCode);
outliersMarked += r.marked;
}
return {
scanned: rows.rowCount || 0,
updated,
skipped,
outliersMarked,
downstreamSynced,
};
} finally {
if (ownClient) ownClient.release();
}
}
export async function setPrepPriceOutlier(
prepId: string,
outlier: boolean,
opts?: { branchCode?: string | null }
): Promise<{ id: string; price_outlier: boolean }> {
const params: unknown[] = [prepId, Boolean(outlier)];
let branchSql = '';
if (opts?.branchCode) {
params.push(opts.branchCode);
branchSql = ` AND branch_code = $${params.length}`;
}
const result = await pool.query(
`UPDATE supplier_preparations
SET price_outlier = $2
WHERE id = $1::uuid${branchSql}
RETURNING id, price_outlier`,
params
);
if (!result.rowCount) {
throw Object.assign(new Error('备货单不存在或无权操作'), { status: 404, code: 'not_found' });
}
return {
id: String(result.rows[0].id),
price_outlier: Boolean(result.rows[0].price_outlier),
};
}