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

379 lines
13 KiB
TypeScript

import { pool } from '../db';
import {
fetchCategoryRows,
getCategoryDisplayLabel,
} from './categoryCatalogService';
import { findSkuByFuzzyName } from './skuFuzzyMatchService';
import {
normalizeProcessingOwner,
resolveProcessingMethodFromAlias,
type ProcessingAlias,
} from './processingMethodUtils';
export interface CustomerOrderItemInput {
item_name?: string;
sku_code?: string;
sku_name?: string;
catalog_sku_name?: string;
quantity?: number | string;
unit?: string;
price?: number | string;
amount?: number | string;
processing_method?: string;
processingMethod?: string;
processing_owner?: string;
processingOwner?: string;
category_code?: string;
categoryCode?: string;
category_name?: string;
categoryName?: string;
category_manually_set?: boolean;
categoryManuallySet?: boolean;
library_category_code?: string;
libraryCategoryCode?: string;
smart_classify_enabled?: boolean;
smartClassifyEnabled?: boolean;
originalName?: string;
/** 明细备注 */
remark?: string | null;
}
export interface EnrichCustomerOrderOptions {
smartClassifyEnabled?: boolean;
/** 无分类时不读 skus 表默认分类(提交/小程序识别默认 true)。已提交的分类不被映射覆盖。 */
preferCustomerMapping?: boolean;
}
export type CustomerSkuCategoryRow = {
sku_code: string;
customer_sku_name: string | null;
category_code: string | null;
};
/**
* 录单 enrich 分类优先级:已提交编码 > 客户映射 > 智能规则;
* preferCustomerMapping 时跳过 SKU 主数据。不覆盖本次请求已有分类。
*/
export function pickCustomerOrderCategoryCode(params: {
submittedCategory: string | null;
skuCode: string;
itemName: string;
customerSkus: CustomerSkuCategoryRow[];
smartRules: Array<{ keyword: string; category_code: string }>;
smartClassifyEnabled: boolean;
preferCustomerMapping: boolean;
skuMasterCategory?: string | null;
filledCategory?: string | null;
}): string | null {
const submitted = String(params.submittedCategory || '').trim() || null;
if (submitted) return submitted;
let categoryCode = String(params.filledCategory || '').trim() || null;
if (!params.preferCustomerMapping && !categoryCode && params.skuCode) {
const master = String(params.skuMasterCategory || '').trim() || null;
if (master) categoryCode = master;
}
if (!categoryCode && params.skuCode && params.customerSkus.length) {
const bySku = params.customerSkus.find((row) => row.sku_code === params.skuCode && row.category_code);
categoryCode = bySku?.category_code ? String(bySku.category_code) : null;
}
const itemName = params.itemName.trim();
if (!categoryCode && params.smartClassifyEnabled && itemName && params.customerSkus.length) {
const normalizedItemName = itemName.toLowerCase();
const byName = params.customerSkus.find((row) => {
if (!row.category_code || !row.customer_sku_name) return false;
const mappingName = row.customer_sku_name.trim().toLowerCase();
return (
mappingName === normalizedItemName ||
normalizedItemName.includes(mappingName) ||
mappingName.includes(normalizedItemName)
);
});
categoryCode = byName?.category_code ? String(byName.category_code) : null;
}
if (!categoryCode && params.smartClassifyEnabled && itemName) {
for (const rule of params.smartRules) {
const keyword = String(rule.keyword || '').trim();
if (keyword && itemName.includes(keyword)) {
categoryCode = String(rule.category_code);
break;
}
}
}
return categoryCode;
}
async function loadProcessingAliases(customerCode: string): Promise<ProcessingAlias[]> {
const result = await pool.query(
`SELECT alias_name, processing_method
FROM customer_processing_aliases
WHERE customer_code = $1 AND COALESCE(status, 1) = 1`,
[customerCode]
).catch(() => ({ rows: [] as ProcessingAlias[] }));
return result.rows as ProcessingAlias[];
}
async function loadCustomerSkus(customerCode: string) {
const result = await pool.query(
`SELECT sku_code, customer_sku_name, customer_unit, category_code, processing_method, processing_owner
FROM customer_skus
WHERE customer_code = $1`,
[customerCode]
);
return result.rows as Array<{
sku_code: string;
customer_sku_name: string | null;
customer_unit: string | null;
category_code: string | null;
processing_method: string | null;
processing_owner: string | null;
}>;
}
function resolveProcessingOwnerForItem(
item: CustomerOrderItemInput,
method: string,
customerSkus: Awaited<ReturnType<typeof loadCustomerSkus>>
): string | null {
const raw = String(item.processing_owner || item.processingOwner || '').trim();
if (raw) return normalizeProcessingOwner(method, raw);
const itemName = String(item.item_name || item.sku_name || item.originalName || '').trim();
const skuCode = String(item.sku_code || '').trim();
if (skuCode) {
const bySku = customerSkus.find((row) => row.sku_code === skuCode && row.processing_owner);
if (bySku?.processing_owner) {
return normalizeProcessingOwner(method, bySku.processing_owner);
}
}
if (itemName) {
const normalized = itemName.toLowerCase();
const byName = customerSkus.find((row) => {
if (!row.customer_sku_name || !row.processing_owner) return false;
const name = row.customer_sku_name.trim().toLowerCase();
return name === normalized || normalized.includes(name) || name.includes(normalized);
});
if (byName?.processing_owner) {
return normalizeProcessingOwner(method, byName.processing_owner);
}
}
return normalizeProcessingOwner(method, null);
}
function resolveProcessingForItem(
item: CustomerOrderItemInput,
aliases: ProcessingAlias[],
customerSkus: Awaited<ReturnType<typeof loadCustomerSkus>>
): string {
const raw = String(item.processing_method || item.processingMethod || '').trim();
if (raw) {
return resolveProcessingMethodFromAlias(raw, aliases);
}
const itemName = String(item.item_name || item.sku_name || item.originalName || '').trim();
const skuCode = String(item.sku_code || '').trim();
if (skuCode) {
const bySku = customerSkus.find((row) => row.sku_code === skuCode && row.processing_method);
if (bySku?.processing_method) {
return resolveProcessingMethodFromAlias(bySku.processing_method, aliases);
}
}
if (itemName) {
const normalized = itemName.toLowerCase();
const byName = customerSkus.find((row) => {
if (!row.customer_sku_name || !row.processing_method) return false;
const name = row.customer_sku_name.trim().toLowerCase();
return name === normalized || normalized.includes(name) || name.includes(normalized);
});
if (byName?.processing_method) {
return resolveProcessingMethodFromAlias(byName.processing_method, aliases);
}
}
return resolveProcessingMethodFromAlias(raw, aliases);
}
function resolveSmartClassifyEnabled(
item: CustomerOrderItemInput,
options?: EnrichCustomerOrderOptions
): boolean {
if (item.smart_classify_enabled === false || item.smartClassifyEnabled === false) return false;
if (item.smart_classify_enabled === true || item.smartClassifyEnabled === true) return true;
if (options?.smartClassifyEnabled === false) return false;
return true;
}
async function resolveCategoryForItem(
item: CustomerOrderItemInput,
customerSkus: Awaited<ReturnType<typeof loadCustomerSkus>>,
categoryRows: Awaited<ReturnType<typeof fetchCategoryRows>>,
smartRules: Array<{ keyword: string; category_code: string }>,
options?: EnrichCustomerOrderOptions,
branchCode?: string | null
): Promise<{ category_code: string | null; category_name: string | null; sku_code?: string | null }> {
const smartClassifyEnabled = resolveSmartClassifyEnabled(item, options);
const preferCustomerMapping = options?.preferCustomerMapping !== false;
const manuallySet = Boolean(item.category_manually_set || item.categoryManuallySet);
const submittedCategory = String(item.category_code || item.categoryCode || '').trim() || null;
const itemName = String(item.item_name || item.sku_name || item.originalName || '').trim();
let skuCode = String(item.sku_code || '').trim();
let filledFromFuzzy: string | null = null;
if (!skuCode && itemName) {
const fuzzy = await findSkuByFuzzyName(itemName, branchCode, submittedCategory || undefined);
if (fuzzy) {
skuCode = fuzzy.skuCode;
if (!submittedCategory && fuzzy.categoryCode) {
filledFromFuzzy = String(fuzzy.categoryCode);
}
}
}
let skuMasterCategory: string | null = null;
if (!preferCustomerMapping && !submittedCategory && !filledFromFuzzy && skuCode) {
const sku = await pool.query(`SELECT category_code FROM skus WHERE sku_code = $1 LIMIT 1`, [skuCode]);
skuMasterCategory = sku.rows[0]?.category_code ? String(sku.rows[0].category_code) : null;
}
const categoryCode = pickCustomerOrderCategoryCode({
submittedCategory,
skuCode,
itemName,
customerSkus,
smartRules,
smartClassifyEnabled,
preferCustomerMapping,
skuMasterCategory,
filledCategory: filledFromFuzzy,
});
const submittedName = String(item.category_name || item.categoryName || '').trim();
const categoryName = categoryCode
? (manuallySet || submittedCategory) && submittedName
? submittedName
: getCategoryDisplayLabel(categoryRows, categoryCode) || submittedName || null
: null;
return { category_code: categoryCode, category_name: categoryName, sku_code: skuCode || null };
}
export async function enrichCustomerOrderItems(
customerCode: string,
items: CustomerOrderItemInput[],
branchCode?: string | null,
options?: EnrichCustomerOrderOptions
) {
const [aliases, customerSkus, categoryRows, smartRulesResult] = await Promise.all([
loadProcessingAliases(customerCode),
loadCustomerSkus(customerCode),
fetchCategoryRows(branchCode),
pool.query(`SELECT keyword, category_code FROM smart_classification_rules WHERE is_active = true`),
]);
const skuCodes = [...new Set(customerSkus.map((row) => row.sku_code).filter(Boolean))];
const masterNameBySku = new Map<string, string>();
if (skuCodes.length) {
const master = await pool
.query(`SELECT sku_code, sku_name FROM skus WHERE sku_code = ANY($1::text[])`, [skuCodes])
.catch(() => ({ rows: [] as Array<{ sku_code: string; sku_name: string }> }));
for (const row of master.rows) {
if (row.sku_code && row.sku_name) masterNameBySku.set(String(row.sku_code), String(row.sku_name));
}
}
const smartRules = smartRulesResult.rows as Array<{ keyword: string; category_code: string }>;
return Promise.all(
items.map(async (item) => {
const processing_method = resolveProcessingForItem(item, aliases, customerSkus);
const processing_owner = resolveProcessingOwnerForItem(item, processing_method, customerSkus);
const category = await resolveCategoryForItem(
item,
customerSkus,
categoryRows,
smartRules,
options,
branchCode
);
return {
...item,
sku_code: category.sku_code || item.sku_code || '',
// Keep the customer's wording in item_name, but expose the master name
// separately for confirmation screens and downstream consumers.
sku_name:
(category.sku_code && masterNameBySku.get(category.sku_code)) ||
item.sku_name ||
item.catalog_sku_name ||
item.item_name ||
item.originalName ||
'',
catalog_sku_name:
(category.sku_code && masterNameBySku.get(category.sku_code)) ||
item.catalog_sku_name ||
item.sku_name ||
'',
processing_method,
processing_owner,
category_code: category.category_code,
category_name: category.category_name,
};
})
);
}
export async function enrichParsedCustomerOrderItems(
customerCode: string,
parsedItems: Array<{
item_name?: string;
sku_code?: string;
skuName?: string;
sku_name?: string;
catalog_sku_name?: string;
originalName?: string;
original_name?: string;
quantity?: number;
unit?: string;
price?: number;
processingMethod?: string;
processing_method?: string;
processingOwner?: string;
processing_owner?: string;
categoryCode?: string;
category_code?: string;
categoryName?: string;
category_name?: string;
remark?: string | null;
}>,
branchCode?: string | null,
options?: EnrichCustomerOrderOptions
) {
return enrichCustomerOrderItems(
customerCode,
parsedItems.map((item) => ({
item_name: item.originalName || item.original_name || item.item_name || '',
sku_code: item.sku_code || '',
sku_name: item.sku_name || item.catalog_sku_name || item.skuName || '',
catalog_sku_name: item.catalog_sku_name || item.sku_name || item.skuName || '',
originalName: item.originalName || item.original_name || item.item_name || '',
quantity: item.quantity,
unit: item.unit,
price: item.price,
processing_method: item.processingMethod || item.processing_method,
processing_owner: item.processingOwner || item.processing_owner,
category_code: item.categoryCode || item.category_code,
category_name: item.categoryName || item.category_name,
remark: String(item.remark || '').trim().slice(0, 500) || undefined,
smart_classify_enabled: options?.smartClassifyEnabled,
})),
branchCode,
options
);
}