独立红队子代理推翻了我上一轮「已完成」的自述,逐条复现后确认属实,本提交全部修复。
## HIGH ①:P4 验收路径实际是死的(路由漏字段)
`/inspection/submit` 与小程序 `/mobile/inspection/.../complete` 都是**逐字段枚举** body,唯独没有 `spec`
⇒ 服务层 `NULLIF(TRIM($12),'')` 恒拿 NULL ⇒ Web/小程序验收建的批次 `inventory.spec` 永远是 NULL。
我上一轮只测了服务层 INSERT 就写「已实测」,是验证方法错误。两条路由现已补 `spec: req.body?.spec`。
## HIGH ②:实扣取错订单行的规格(真扣错批次)
`fifoDeductInventory` 第一条取批次 SQL 按「订单+SKU」取规格且 `LIMIT 1` 无 ORDER BY,按行取规格只是兜底
⇒ 同单同 SKU 两行规格不同时(行1 1箱12瓶 / 行2 1箱24瓶),行2 实扣会拿到行1 的规格、扣错批次。
改为:有 `pickItemId` 时**先走行级**路径;兜底的「订单+SKU」表达式也给 `pickItemId` 让路(COALESCE 按行取)+ 加 ORDER BY。
真跑验证:行1 ⇒ 实扣 ZZ_B12,行2 ⇒ 实扣 ZZ_B24(修复前行2 会扣 ZZ_B12)。
## MEDIUM-HIGH ③:「匹配不到 ⇒ 与改前纯 FIFO 一致」曾经不成立
三段 CASE 把「规格未知」排到「明确不匹配」之前 ⇒ 一个都不命中时会插队、偏离改前 FIFO。
改为**两档**(0 命中 / 1 其余)⇒ 无命中时所有行同级 ⇒ 直接退化为纯 FIFO。
⚠️ 我第一次用窗口函数 `MIN() OVER ()` 修,真跑发现 PG **不允许 `FOR UPDATE` 与窗口函数同用**
(抛 `FOR UPDATE is not allowed with window functions`)⇒ 等于把分拣出库/发车扣库打挂,已改掉并加断言禁止。
验证:无规格 / 无匹配(1箱48瓶) 两种输入顺序完全相同(纯 FIFO:BLEGACY→B24→B12→B12B);1箱12瓶 命中批置顶。
## 踩坑 ④:我打红了 13 个既有测试(改共享服务没跑它的既有测试)
`stockCoverBatchQuery.test.ts` 12 个(P2c 新增 SQL 让假匹配器抛「未预期的 SQL」)+ `stockCoverBatchPlan.test.ts` 1 个
(FIFO 字面量守卫)。已补 mock 规则并把守卫改成更强的两段断言(无规格时唯一实现产物逐字等于改前 FIFO;
两处 loader 必须都调它;不许再把字面量写回)。
现状:stockCoverBatchQuery 17 / stockCoverBatchPlan 12 / inventoryBatchSpecSelection 12 全绿;
出库扣库相关 9 个文件 98 通过。
## 归一化第三批:迁移 20261053
JS `\s` 还含 U+1680 / U+2000–200A / U+2028 / U+2029 / U+202F / U+205F,其中 **U+2007(Excel 数字对齐空格)**
与 U+202F 实测会让「录单认得出、实扣认不出」⇒ 静默退 FIFO。新迁移把这 19 个码点折成空格并逐条守卫;
JS 侧把 U+0130 显式折 `i`(PG `lower('İ')='i'`,JS `toLowerCase()` 是 i+U+0307)。
## 另外修正我自己提交的一处类型错误
`new Map<string, string, Array<...>>` 多写一个类型参数(`tsc` 报 `Expected 2 type arguments, but got 3`)——
上轮「server tsc 干净」是在该编辑之前跑的、之后没复跑就提交了。现已修正:`npx tsc --noEmit` 仅剩既有
`src/prompts/defaults.ts(465)` 一处红(他人面,非本次);web `tsc --noEmit` 0 错。
## 证据与已知红(均已用 stash / 对照证明与本次无关)
- 契约测试 ⑫ 新增:验收路由必须透传 spec + 实扣必须按该行自己的规格
- 既有红:`bidInventoryCover`(5s 超时)、`completedPickingEditable`(`保存修改` 在 HEAD 亦为 0 处)、
web `PickingManagement.outboundPhotoPreview` 3 例 + `SystemConfig.allowZeroCost` 2 例 + `skuCostThirdBucket` 1 例
- 门禁快档 8 通过 / `check-ai-cost` 既有红(不许调绿)
2210 lines
76 KiB
TypeScript
2210 lines
76 KiB
TypeScript
import { pool } from '../db';
|
||
import { syncProductCategoryToMasterData } from './productCategorySyncService';
|
||
import { fetchCategoryRows } from './categoryCatalogService';
|
||
import { findSkuByFuzzyName, isSafeLooseNameContain, spokenNameWindowScore } from './skuFuzzyMatchService';
|
||
import { normalizeProcessingOwner } from './processingMethodUtils';
|
||
import {
|
||
callWithImage as callArkWithImage,
|
||
callWithText as callArkWithText,
|
||
hasRuntimeConfig as hasArkRuntimeConfig,
|
||
type LlmCallOptions as ArkCallOptions,
|
||
} from './llmService';
|
||
import { resolvePrompt } from './promptRegistryService';
|
||
import { transcribeAudioBase64, type AudioFormat } from './speechService';
|
||
|
||
export interface ParsedItem {
|
||
originalName: string;
|
||
skuName: string;
|
||
skuCode: string;
|
||
quantity: number;
|
||
unit: string;
|
||
matchLayer: 0 | 1 | 3 | null;
|
||
confidence: number;
|
||
categoryCode?: string;
|
||
categoryName?: string;
|
||
processingMethod?: string;
|
||
/** 行备注(来自 OCR/文本第 5 字段) */
|
||
remark?: string;
|
||
/**
|
||
* 规格(来自 OCR/文本**第 7 字段**,2026-10-16 新增)。
|
||
*
|
||
* 客户单据把包装规格写在品名里(`燕子酵母粉500g/袋`、`川光醪糟600g*12瓶`…),
|
||
* 原先 6 字段口径 + 「品名只写商品本体」的规则 ⇒ **规格必然丢失**,
|
||
* 导致录单员看不出该选哪条 SKU、库存抵扣容易拿错包装。
|
||
* 追加在**末尾**(索引 6)以保持对旧 6 字段输出的向后兼容。
|
||
*/
|
||
spec?: string;
|
||
/** Web 拆条建议分类名(尚未落库) */
|
||
suggestedCategoryName?: string;
|
||
inCustomerLibrary?: boolean;
|
||
/** B6: 口语约数/范围数量,须人工确认 */
|
||
quantityNeedsConfirm?: boolean;
|
||
quantityHint?: string;
|
||
/** 消歧候选列表:同名模糊匹配到多个 SKU 时返回,供录单员选择 */
|
||
candidates?: SkuCandidate[];
|
||
}
|
||
|
||
export interface SkuCandidate {
|
||
skuCode: string;
|
||
skuName: string;
|
||
unit: string;
|
||
categoryCode: string;
|
||
categoryName: string;
|
||
/**
|
||
* 该候选 SKU 的规格(`skus.spec`)——用于"同名多规格"时**按规格消歧**
|
||
* (2026-10-16:客户单据上写了 `600g*12瓶`,就该落到 12 瓶那条 SKU,而不是靠猜)。
|
||
*/
|
||
spec?: string | null;
|
||
/** 该客户历史下单次数 */
|
||
orderCount: number;
|
||
/** 模糊匹配的置信度 */
|
||
confidence: number;
|
||
}
|
||
|
||
export interface ParseResult {
|
||
items: ParsedItem[];
|
||
unmatched: string[];
|
||
demoMode?: boolean;
|
||
message?: string;
|
||
/** 图片 OCR 合并统计(便于前端提示「共识别 N 项」) */
|
||
extractedStats?: {
|
||
parallelCount: number;
|
||
requestItemCounts: number[];
|
||
mergedItemCount: number;
|
||
};
|
||
}
|
||
|
||
export interface ExtractedItem {
|
||
originalName: string;
|
||
quantity: number;
|
||
unit: string;
|
||
processingMethod?: string;
|
||
remark?: string;
|
||
/** 规格(模型第 7 字段;旧 6 字段输出时为空) */
|
||
spec?: string;
|
||
categoryCode?: string;
|
||
/** 模型原文分类(编码或名称),解析后再归一 */
|
||
categoryLabel?: string;
|
||
suggestedCategoryName?: string;
|
||
quantityNeedsConfirm?: boolean;
|
||
quantityHint?: string;
|
||
}
|
||
|
||
/** 明细备注:trim + 上限 500,空则 undefined */
|
||
function normalizeExtractedRemark(raw: unknown): string | undefined {
|
||
const text = String(raw ?? '')
|
||
.trim()
|
||
.replace(/\s+/g, ' ')
|
||
.slice(0, 500);
|
||
return text || undefined;
|
||
}
|
||
|
||
/**
|
||
* 规格(第 7 字段):**原样保留**客户单据写法(`500g/袋`、`600g*12瓶`、`25kg/袋`、`1箱24瓶`…)。
|
||
* 只做 trim / 折叠空白 / 上限 60 —— 不做归一化(口径未定:归一化规则一旦写偏,
|
||
* 同一种货会出现多种 spec 写法反而更乱;见设计文档,等开发者裁决)。
|
||
*/
|
||
function normalizeExtractedSpec(raw: unknown): string | undefined {
|
||
const text = String(raw ?? '')
|
||
.trim()
|
||
.replace(/\s+/g, ' ')
|
||
.slice(0, 60);
|
||
return text || undefined;
|
||
}
|
||
|
||
const PROCESSING_METHODS = ['砍', '去皮', '切片', '切块', '切丝', '切段', '切丁', '清洗', '洗净', '打包', '分装', '净菜', '剁碎', '去根', '去叶'];
|
||
|
||
/** 常见订货单位(含语音/OCR 易出现的写法) */
|
||
const QTY_UNIT_PATTERN =
|
||
'斤|公斤|千克|kg|KG|Kg|个|箱|袋|盒|包|把|根|条|份|瓶|桶|件|只|克|g|G|板|提|串|排|卷|听|罐|捆|箩|筐|朵|颗|枚|支|块|片';
|
||
|
||
const CN_DIGIT_MAP: Record<string, number> = {
|
||
零: 0,
|
||
〇: 0,
|
||
一: 1,
|
||
壹: 1,
|
||
二: 2,
|
||
贰: 2,
|
||
两: 2,
|
||
俩: 2,
|
||
三: 3,
|
||
叁: 3,
|
||
四: 4,
|
||
肆: 4,
|
||
五: 5,
|
||
伍: 5,
|
||
六: 6,
|
||
陆: 6,
|
||
七: 7,
|
||
柒: 7,
|
||
八: 8,
|
||
捌: 8,
|
||
九: 9,
|
||
玖: 9,
|
||
};
|
||
|
||
/** 全角数字/小数点 → 半角;中文逗号当小数点;去掉空白 */
|
||
export function normalizeQuantityText(raw: unknown): string {
|
||
return String(raw ?? '')
|
||
.trim()
|
||
.replace(/[\uFF10-\uFF19]/g, (ch) => String.fromCharCode(ch.charCodeAt(0) - 0xfee0))
|
||
.replace(/[\uFF0E\u3002.]/g, '.')
|
||
.replace(/,/g, '.')
|
||
.replace(/\s+/g, '');
|
||
}
|
||
|
||
/** 解析中文数量词:半/两/十一/二十三 等常见订货说法 */
|
||
export function parseChineseNumeral(raw: string): number | null {
|
||
const text = String(raw || '').trim();
|
||
if (!text) return null;
|
||
if (text === '半') return 0.5;
|
||
if (text === '两' || text === '俩') return 2;
|
||
|
||
if (/^[点\.]\d+$/.test(text) === false && /^[零〇一二两三四五六七八九十百千万半点]+$/.test(text)) {
|
||
if (text.includes('点')) {
|
||
const [intPart, decPart = ''] = text.split('点');
|
||
const intVal = parseChineseNumeral(intPart || '零');
|
||
if (intVal == null) return null;
|
||
let dec = 0;
|
||
for (let i = 0; i < decPart.length; i++) {
|
||
const d = CN_DIGIT_MAP[decPart[i]];
|
||
if (d == null) return null;
|
||
dec += d * Math.pow(10, -(i + 1));
|
||
}
|
||
return Math.round((intVal + dec) * 1000) / 1000;
|
||
}
|
||
|
||
if (text === '十') return 10;
|
||
if (text.startsWith('十')) {
|
||
const ones = CN_DIGIT_MAP[text.slice(1)];
|
||
return ones == null ? null : 10 + ones;
|
||
}
|
||
if (text.endsWith('十') && text.length === 2) {
|
||
const tens = CN_DIGIT_MAP[text[0]];
|
||
return tens == null ? null : tens * 10;
|
||
}
|
||
if (text.includes('十')) {
|
||
const [tensPart, onesPart = ''] = text.split('十');
|
||
const tens = tensPart ? CN_DIGIT_MAP[tensPart] : 1;
|
||
const ones = onesPart ? CN_DIGIT_MAP[onesPart] : 0;
|
||
if (tens == null || ones == null) return null;
|
||
return tens * 10 + ones;
|
||
}
|
||
if (text.length === 1 && CN_DIGIT_MAP[text] != null) return CN_DIGIT_MAP[text];
|
||
}
|
||
return null;
|
||
}
|
||
|
||
const QTY_FUZZY_RE =
|
||
/十来|大概|左右|上下|约|差不多|将近|几|七八|五六|两三|三两|\d+\s*[-~~到至]\s*\d+/;
|
||
|
||
/**
|
||
* 统一解析数量字段:支持半角/全角数字、带单位字符串、中文量词。
|
||
* 解析失败返回 null(由调用方决定是否回退为 1 或从品名剥离)。
|
||
* B6: 口语范围/约数打 needsConfirm,避免静默当精确量。
|
||
*/
|
||
export function parseQuantityValue(raw: unknown): {
|
||
quantity: number | null;
|
||
unitFromQty: string;
|
||
needsConfirm?: boolean;
|
||
quantityHint?: string;
|
||
} {
|
||
if (raw == null || raw === '') return { quantity: null, unitFromQty: '' };
|
||
if (typeof raw === 'number') {
|
||
return Number.isFinite(raw) && raw > 0
|
||
? { quantity: Math.round(raw * 1000) / 1000, unitFromQty: '' }
|
||
: { quantity: null, unitFromQty: '' };
|
||
}
|
||
|
||
let text = normalizeQuantityText(raw);
|
||
if (!text) return { quantity: null, unitFromQty: '' };
|
||
|
||
const unitMatch = text.match(new RegExp(`^(.*?)(${QTY_UNIT_PATTERN})$`, 'i'));
|
||
let unitFromQty = '';
|
||
if (unitMatch) {
|
||
unitFromQty = unitMatch[2];
|
||
text = unitMatch[1];
|
||
}
|
||
|
||
text = text.replace(/^[xX×*]+/, '').replace(/[xX×*]+$/, '');
|
||
if (!text) return { quantity: null, unitFromQty };
|
||
|
||
const fuzzy = QTY_FUZZY_RE.test(text);
|
||
|
||
const asFloat = Number.parseFloat(text);
|
||
if (Number.isFinite(asFloat) && asFloat > 0 && /^[\d.]+$/.test(text)) {
|
||
return { quantity: Math.round(asFloat * 1000) / 1000, unitFromQty };
|
||
}
|
||
|
||
const chinese = parseChineseNumeral(text);
|
||
if (chinese != null && chinese > 0 && !fuzzy) {
|
||
return { quantity: chinese, unitFromQty };
|
||
}
|
||
|
||
// 兜底:提取首个数字片段(如 "约10" / "Qty:3.5")
|
||
const digits = text.match(/(\d+(?:\.\d+)?)/);
|
||
if (digits) {
|
||
const n = Number.parseFloat(digits[1]);
|
||
if (Number.isFinite(n) && n > 0) {
|
||
if (fuzzy) {
|
||
return {
|
||
quantity: Math.round(n * 1000) / 1000,
|
||
unitFromQty,
|
||
needsConfirm: true,
|
||
quantityHint: '口语约数/范围,请人工确认数量',
|
||
};
|
||
}
|
||
return { quantity: Math.round(n * 1000) / 1000, unitFromQty };
|
||
}
|
||
}
|
||
|
||
if (fuzzy) {
|
||
// 七八 / 十来 等:给中间估计值并强制确认
|
||
let estimate: number | null = null;
|
||
if (/七八/.test(text)) estimate = 7.5;
|
||
else if (/五六/.test(text)) estimate = 5.5;
|
||
else if (/两三|三两/.test(text)) estimate = 2.5;
|
||
else if (/十来/.test(text)) estimate = 10;
|
||
else if (chinese != null && chinese > 0) estimate = chinese;
|
||
return {
|
||
quantity: estimate,
|
||
unitFromQty,
|
||
needsConfirm: true,
|
||
quantityHint: '口语约数/范围,请人工确认数量',
|
||
};
|
||
}
|
||
|
||
return { quantity: null, unitFromQty };
|
||
}
|
||
|
||
/** 品名里夹带「数量+单位」时剥离,例如 西红柿10斤 / 鸡蛋×2板;可带行尾备注 */
|
||
export function peelQuantityFromProductName(
|
||
rawName: string,
|
||
currentQty: number | null,
|
||
currentUnit: string
|
||
): { name: string; quantity: number | null; unit: string; peeled: boolean; remark?: string } {
|
||
let name = String(rawName || '').trim();
|
||
if (!name) {
|
||
return { name: '', quantity: currentQty, unit: currentUnit, peeled: false };
|
||
}
|
||
|
||
const patterns: Array<{ re: RegExp; hasRemark: boolean }> = [
|
||
{
|
||
hasRemark: true,
|
||
re: new RegExp(
|
||
`^(.+?)\\s*(\\d+(?:\\.\\d+)?)\\s*(${QTY_UNIT_PATTERN})\\s*([\\u4e00-\\u9fa5A-Za-z].+)$`,
|
||
'i'
|
||
),
|
||
},
|
||
{
|
||
hasRemark: false,
|
||
re: new RegExp(`^(.+?)\\s*[xX×*]\\s*(\\d+(?:\\.\\d+)?)\\s*(${QTY_UNIT_PATTERN})?$`, 'i'),
|
||
},
|
||
{
|
||
hasRemark: false,
|
||
re: new RegExp(`^(.+?)\\s*(\\d+(?:\\.\\d+)?)\\s*(${QTY_UNIT_PATTERN})$`, 'i'),
|
||
},
|
||
{
|
||
hasRemark: false,
|
||
re: new RegExp(
|
||
`^(.+?)\\s*([半两俩零〇一二三四五六七八九十百]+)\\s*(${QTY_UNIT_PATTERN})$`,
|
||
'i'
|
||
),
|
||
},
|
||
];
|
||
|
||
for (const { re: pattern, hasRemark } of patterns) {
|
||
const match = name.match(pattern);
|
||
if (!match) continue;
|
||
const peeledName = String(match[1] || '').trim();
|
||
if (!peeledName || peeledName.length < 1) continue;
|
||
// 避免把「3号土豆」这类型号数字误当成数量(无单位时已由 pattern2 挡掉)
|
||
if (/^\d+号/.test(name) && !match[3]) continue;
|
||
|
||
const parsed = parseQuantityValue(`${match[2]}${match[3] || ''}`);
|
||
if (parsed.quantity == null || parsed.quantity <= 0) continue;
|
||
|
||
const trailingRemark = hasRemark ? String(match[4] || '').trim() : '';
|
||
if (hasRemark && trailingRemark.length < 2) continue;
|
||
|
||
const shouldPreferPeeled =
|
||
currentQty == null ||
|
||
currentQty <= 0 ||
|
||
currentQty === 1 ||
|
||
Math.abs(currentQty - parsed.quantity) < 1e-6 ||
|
||
Boolean(match[3]);
|
||
|
||
if (!shouldPreferPeeled) continue;
|
||
|
||
return {
|
||
name: peeledName,
|
||
quantity: parsed.quantity,
|
||
unit: currentUnit || parsed.unitFromQty || match[3] || '',
|
||
peeled: true,
|
||
remark: trailingRemark || undefined,
|
||
};
|
||
}
|
||
|
||
return { name, quantity: currentQty, unit: currentUnit, peeled: false };
|
||
}
|
||
|
||
/** 单位字段被粘上备注时拆开,如「只放红烧把脚壳放进去」 */
|
||
function peelRemarkFromUnitField(rawUnit: unknown): { unit: string; remark?: string } {
|
||
const text = String(rawUnit || '').trim();
|
||
if (!text) return { unit: '' };
|
||
const match = text.match(
|
||
new RegExp(`^(${QTY_UNIT_PATTERN})\\s*([\\u4e00-\\u9fa5A-Za-z].+)$`, 'i')
|
||
);
|
||
if (match && String(match[2] || '').trim().length >= 2) {
|
||
return { unit: match[1], remark: String(match[2]).trim() };
|
||
}
|
||
return { unit: text };
|
||
}
|
||
|
||
function resolveProcessingMethodWithAliases(
|
||
raw: string,
|
||
aliases: Array<{ alias: string; processingMethod: string }>
|
||
): string {
|
||
const text = String(raw || '').trim();
|
||
if (!text) return '';
|
||
const direct = PROCESSING_METHODS.find((method) => text.includes(method));
|
||
if (direct) return direct;
|
||
const exact = aliases.find((row) => row.alias.trim() === text);
|
||
if (exact) return exact.processingMethod;
|
||
const fuzzy = aliases.find((row) => text.includes(row.alias) || row.alias.includes(text));
|
||
return fuzzy?.processingMethod || '';
|
||
}
|
||
|
||
const PROMPT_TEMPLATE_MARKERS = [
|
||
'原样提取商品图片原文不得改写',
|
||
'原样提取对应数量的数值',
|
||
'原样提取对应单位',
|
||
'仅匹配去皮',
|
||
];
|
||
|
||
function isPromptTemplateItem(name: string): boolean {
|
||
const normalized = name.replace(/\s+/g, '');
|
||
if (PROMPT_TEMPLATE_MARKERS.some((marker) => normalized.includes(marker.replace(/\s+/g, '')))) {
|
||
return true;
|
||
}
|
||
// 短字段名只按整项过滤,避免误删名称中包含"商品名"或"编码"的真实商品。
|
||
return ['商品名', '商品原文', '编码'].includes(normalized);
|
||
}
|
||
|
||
function normalizeExtractedName(rawName: string): { name: string; processingMethod: string } {
|
||
let name = String(rawName || '').trim();
|
||
let processingMethod = '';
|
||
const parenMatch = name.match(/[((]([^))]+)[))]/);
|
||
if (parenMatch) {
|
||
const tag = parenMatch[1].trim();
|
||
const found = PROCESSING_METHODS.find((method) => tag.includes(method));
|
||
if (found) processingMethod = found;
|
||
name = name.replace(parenMatch[0], '').trim();
|
||
}
|
||
return { name, processingMethod };
|
||
}
|
||
|
||
function normalizeProcessingMethod(
|
||
value: unknown,
|
||
aliases: Array<{ alias: string; processingMethod: string }> = []
|
||
): string {
|
||
const text = String(value || '').trim();
|
||
if (!text) return '';
|
||
return resolveProcessingMethodWithAliases(text, aliases);
|
||
}
|
||
|
||
function normalizeUnit(value: unknown, processingMethod?: string): string {
|
||
let unit = String(value || '').trim();
|
||
if (!unit) return '';
|
||
if (processingMethod) {
|
||
unit = unit.replace(new RegExp(processingMethod, 'g'), '');
|
||
}
|
||
unit = unit
|
||
.replace(/[((][^))]*[))]/g, '')
|
||
.replace(/备注|加工方式|加工/g, '')
|
||
.trim();
|
||
return unit;
|
||
}
|
||
|
||
/**
|
||
* 模型原始输出(6 或 7 元组 / 对象)→ 抽取项。
|
||
*
|
||
* 导出仅为**可测**:7 字段规格是 2026-10-16 追加的,必须同时证明"新字段读得到"与
|
||
* "旧 6 字段输出不炸、只是 spec 为空"(向后兼容)—— 这两件事只有真跑这个纯函数才说得清。
|
||
*/
|
||
export function mapRawItemToExtracted(item: any): ExtractedItem | null {
|
||
const isArrayItem = Array.isArray(item);
|
||
const rawName = isArrayItem
|
||
? item[0]
|
||
: item.originalName ||
|
||
item.skuName ||
|
||
item.name ||
|
||
item.product ||
|
||
item.商品名 ||
|
||
item.商品原文 ||
|
||
item.名称 ||
|
||
item.品名 ||
|
||
'';
|
||
if (!rawName || isPromptTemplateItem(String(rawName))) return null;
|
||
const normalized = normalizeExtractedName(String(rawName));
|
||
const unitPeeled = peelRemarkFromUnitField(isArrayItem ? item[2] : item.unit || item.单位);
|
||
const rawUnit = unitPeeled.unit;
|
||
const rawQty = isArrayItem ? item[1] : item.quantity ?? item.qty ?? item.数量;
|
||
const rawProcessingText = String(
|
||
(isArrayItem ? item[3] : item.processingMethod) ||
|
||
item.processing_method ||
|
||
item.process ||
|
||
item.processType ||
|
||
item.加工方式 ||
|
||
''
|
||
).trim();
|
||
const processingFromField = normalizeProcessingMethod(rawProcessingText);
|
||
const processingMethod =
|
||
processingFromField ||
|
||
normalized.processingMethod ||
|
||
normalizeProcessingMethod(rawUnit) ||
|
||
extractProcessingMethod([rawName, rawUnit, rawProcessingText].join(' '), normalized.name);
|
||
|
||
const categoryLabel = String(
|
||
isArrayItem
|
||
? item[5] ?? ''
|
||
: item.categoryLabel ||
|
||
item.categoryName ||
|
||
item.category_name ||
|
||
item.category ||
|
||
item.分类 ||
|
||
item.categoryCode ||
|
||
item.category_code ||
|
||
''
|
||
).trim();
|
||
|
||
const rawRemark = isArrayItem
|
||
? item[4]
|
||
: item.remark ?? item.备注 ?? item.说明 ?? item.note ?? item.notes ?? '';
|
||
let remark =
|
||
normalizeExtractedRemark(rawRemark) ||
|
||
normalizeExtractedRemark(unitPeeled.remark) ||
|
||
// 模型常把行尾说明塞进第4位;非合法加工词则回收为备注
|
||
(!processingFromField ? normalizeExtractedRemark(rawProcessingText) : undefined);
|
||
|
||
const qtyParsed = parseQuantityValue(rawQty);
|
||
let quantity = qtyParsed.quantity;
|
||
let unit = normalizeUnit(rawUnit, processingMethod) || qtyParsed.unitFromQty || '';
|
||
|
||
/**
|
||
* 规格:**只取模型给的字段**(数组第 7 位 / 对象 `spec`),
|
||
* 不从品名里"猜剥"——品名是匹配 SKU/客户别名的输入,改它会连带影响既有命中率。
|
||
* 模型漏抽时留空,由录单员在行内人工补(本轮即为此提供了可编辑输入框)。
|
||
*/
|
||
const rawSpec = normalizeExtractedSpec(
|
||
isArrayItem
|
||
? item[6]
|
||
: item.spec ?? item.specification ?? item.规格 ?? item.packing ?? item.包装 ?? ''
|
||
);
|
||
|
||
const peeled = peelQuantityFromProductName(
|
||
stripProcessingMethod(normalized.name, processingMethod),
|
||
quantity,
|
||
unit
|
||
);
|
||
if (peeled.peeled) {
|
||
quantity = peeled.quantity;
|
||
unit = normalizeUnit(peeled.unit, processingMethod) || unit;
|
||
if (!remark && peeled.remark) {
|
||
remark = normalizeExtractedRemark(peeled.remark);
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 反「捏造规格」兜底(2026-10-16 开发者硬口径:「规格有就有 没有就没有 严禁捏造」):
|
||
* 提示词已明令只照抄可见文字,这里再挡两种**确定性**的伪规格 ——
|
||
* ① 把**数量+单位**原样抄进规格(`5袋`、`12瓶`)——那不是规格(规格应是包装/净含量);
|
||
* ② 把**品名原文**抄进规格。
|
||
* 只做这两条可判定规则,不做任何"猜测式"补全:拿不准就留空。
|
||
*/
|
||
const finalName = peeled.name || stripProcessingMethod(normalized.name, processingMethod);
|
||
const compact = (text: unknown) => String(text ?? '').replace(/\s+/g, '').toLowerCase();
|
||
let spec = rawSpec;
|
||
if (spec) {
|
||
const qtyNum = Number(quantity);
|
||
const qtyText = Number.isFinite(qtyNum) ? String(Math.round(qtyNum * 1000) / 1000) : '';
|
||
if (qtyText && unit && compact(spec) === compact(`${qtyText}${unit}`)) {
|
||
spec = undefined;
|
||
} else if (finalName && compact(spec) === compact(finalName)) {
|
||
spec = undefined;
|
||
}
|
||
}
|
||
|
||
return {
|
||
originalName: finalName,
|
||
quantity: quantity && quantity > 0 ? quantity : 1,
|
||
unit: unit || '个',
|
||
processingMethod,
|
||
remark,
|
||
spec,
|
||
categoryLabel: categoryLabel || undefined,
|
||
quantityNeedsConfirm: qtyParsed.needsConfirm || undefined,
|
||
quantityHint: qtyParsed.quantityHint,
|
||
};
|
||
}
|
||
|
||
function mapRawItemsArray(rawItems: unknown): ExtractedItem[] {
|
||
if (!Array.isArray(rawItems)) return [];
|
||
return rawItems
|
||
.map((item: any) => mapRawItemToExtracted(item))
|
||
.filter((item: ExtractedItem | null): item is ExtractedItem => Boolean(item?.originalName));
|
||
}
|
||
|
||
/** 从半截/损坏 JSON 中捞出已完整写出的明细行,避免仅为修 JSON 再打一轮模型 */
|
||
function salvageJsonItems(content: string): ExtractedItem[] {
|
||
const cleaned = content.replace(/```json\s*/gi, '').replace(/```\s*/gi, '').trim();
|
||
if (!cleaned) return [];
|
||
|
||
// 1) 截到最后一个完整 tuple 后补全括号再 parse
|
||
const lastTupleEnd = cleaned.lastIndexOf(']');
|
||
if (lastTupleEnd > 0) {
|
||
let candidate = cleaned.slice(0, lastTupleEnd + 1);
|
||
const openBraces = (candidate.match(/\{/g) || []).length;
|
||
const closeBraces = (candidate.match(/\}/g) || []).length;
|
||
const openBrackets = (candidate.match(/\[/g) || []).length;
|
||
const closeBrackets = (candidate.match(/\]/g) || []).length;
|
||
candidate += ']'.repeat(Math.max(0, openBrackets - closeBrackets));
|
||
candidate += '}'.repeat(Math.max(0, openBraces - closeBraces));
|
||
try {
|
||
const parsed = JSON.parse(candidate);
|
||
const raw =
|
||
parsed?.items ||
|
||
parsed?.商品 ||
|
||
parsed?.商品列表 ||
|
||
parsed?.data ||
|
||
parsed?.list ||
|
||
(Array.isArray(parsed) ? parsed : null);
|
||
const items = mapRawItemsArray(raw);
|
||
if (items.length) return items;
|
||
} catch {
|
||
// fall through to regex
|
||
}
|
||
}
|
||
|
||
// 2) 正则抽出完整 ["品名", 数, "单位", "加工"?, "备注"?, "分类"?]
|
||
const items: ExtractedItem[] = [];
|
||
const re =
|
||
/\[\s*"([^"\\]*(?:\\.[^"\\]*)*)"\s*,\s*(\d+(?:\.\d+)?)\s*,\s*"([^"\\]*(?:\\.[^"\\]*)*)"\s*(?:,\s*"([^"\\]*(?:\\.[^"\\]*)*)")?\s*(?:,\s*"([^"\\]*(?:\\.[^"\\]*)*)")?\s*(?:,\s*"([^"\\]*(?:\\.[^"\\]*)*)")?\s*\]/g;
|
||
let match: RegExpExecArray | null;
|
||
while ((match = re.exec(cleaned)) !== null) {
|
||
const mapped = mapRawItemToExtracted([
|
||
match[1].replace(/\\"/g, '"'),
|
||
Number(match[2]),
|
||
match[3].replace(/\\"/g, '"'),
|
||
(match[4] || '').replace(/\\"/g, '"'),
|
||
(match[5] || '').replace(/\\"/g, '"'),
|
||
(match[6] || '').replace(/\\"/g, '"'),
|
||
]);
|
||
if (mapped?.originalName) items.push(mapped);
|
||
}
|
||
return items;
|
||
}
|
||
|
||
function parseJsonItems(content: string): ExtractedItem[] {
|
||
try {
|
||
const cleaned = content.replace(/```json\s*/gi, '').replace(/```\s*/gi, '').trim();
|
||
if (!cleaned) return [];
|
||
|
||
let parsed: any;
|
||
const objectMatch = cleaned.match(/\{[\s\S]*\}/);
|
||
const arrayMatch = cleaned.match(/\[[\s\S]*\]/);
|
||
if (objectMatch) {
|
||
parsed = JSON.parse(objectMatch[0]);
|
||
} else if (arrayMatch) {
|
||
parsed = { items: JSON.parse(arrayMatch[0]) };
|
||
} else {
|
||
return [];
|
||
}
|
||
|
||
const rawItems =
|
||
parsed.items ||
|
||
parsed.商品 ||
|
||
parsed.商品列表 ||
|
||
parsed.data ||
|
||
parsed.list ||
|
||
(Array.isArray(parsed) ? parsed : []);
|
||
return mapRawItemsArray(rawItems);
|
||
} catch (error) {
|
||
console.warn('parseJsonItems failed:', error instanceof Error ? error.message : error);
|
||
return [];
|
||
}
|
||
}
|
||
|
||
function parseItemsFromModelContent(content: string, source: string): ExtractedItem[] {
|
||
const items = parseJsonItems(content);
|
||
if (items.length) return items;
|
||
|
||
if (!content.trim()) return [];
|
||
|
||
const salvaged = salvageJsonItems(content);
|
||
if (salvaged.length) {
|
||
console.info('AI model JSON salvaged:', {
|
||
source,
|
||
salvagedCount: salvaged.length,
|
||
length: content.length,
|
||
});
|
||
return salvaged;
|
||
}
|
||
|
||
console.warn('AI model returned unparseable content:', {
|
||
source,
|
||
preview: content.replace(/\s+/g, ' ').slice(0, 400),
|
||
length: content.length,
|
||
});
|
||
return [];
|
||
}
|
||
|
||
function extractItemsFromTextLocally(text: string): ExtractedItem[] {
|
||
const items: ExtractedItem[] = [];
|
||
// 先按换行/中文分隔符切段,避免语音停顿后粘连导致一条吞两品
|
||
const chunks = String(text || '')
|
||
.split(/[\n\r]+|[,,、;;]+/u)
|
||
.map((part) => part.trim())
|
||
.filter(Boolean);
|
||
const segments = chunks.length ? chunks : [String(text || '').trim()].filter(Boolean);
|
||
if (!segments.length) return items;
|
||
|
||
const unitGroup = QTY_UNIT_PATTERN;
|
||
const patterns: Array<{ re: RegExp; nameFirst: boolean }> = [
|
||
{
|
||
nameFirst: true,
|
||
re: new RegExp(
|
||
`([\\u4e00-\\u9fa5A-Za-z0-9号]+?)\\s*[xX×*]?\\s*(\\d+(?:\\.\\d+)?|[半两俩零〇一二三四五六七八九十]+)\\s*(${unitGroup})`,
|
||
'gi'
|
||
),
|
||
},
|
||
{
|
||
nameFirst: false,
|
||
re: new RegExp(
|
||
`(\\d+(?:\\.\\d+)?|[半两俩零〇一二三四五六七八九十]+)\\s*(${unitGroup})\\s*([\\u4e00-\\u9fa5A-Za-z0-9号]+)`,
|
||
'gi'
|
||
),
|
||
},
|
||
];
|
||
|
||
for (const segment of segments) {
|
||
const normalized = segment.replace(/\s+/g, ' ').trim();
|
||
if (!normalized) continue;
|
||
let matchedInSegment = false;
|
||
for (const { re: pattern, nameFirst } of patterns) {
|
||
pattern.lastIndex = 0;
|
||
let match: RegExpExecArray | null;
|
||
while ((match = pattern.exec(normalized)) !== null) {
|
||
const name = (nameFirst ? match[1] : match[3] || '').trim();
|
||
const qtyRaw = nameFirst ? match[2] : match[1];
|
||
const unit = nameFirst ? match[3] : match[2];
|
||
const qtyParsed = parseQuantityValue(qtyRaw);
|
||
const quantity = qtyParsed.quantity;
|
||
if (name && quantity && quantity > 0) {
|
||
const processingMethod = extractProcessingMethod(normalized, name);
|
||
items.push({
|
||
originalName: stripProcessingMethod(name, processingMethod),
|
||
quantity,
|
||
unit: unit || qtyParsed.unitFromQty || '个',
|
||
processingMethod,
|
||
quantityNeedsConfirm: qtyParsed.needsConfirm || undefined,
|
||
quantityHint: qtyParsed.quantityHint,
|
||
});
|
||
matchedInSegment = true;
|
||
}
|
||
}
|
||
if (matchedInSegment) break;
|
||
}
|
||
if (!matchedInSegment) {
|
||
const peeled = peelQuantityFromProductName(normalized.slice(0, 40), null, '');
|
||
items.push({
|
||
originalName: stripProcessingMethod(
|
||
peeled.name || normalized.slice(0, 30),
|
||
extractProcessingMethod(normalized, peeled.name || normalized.slice(0, 30))
|
||
),
|
||
quantity: peeled.quantity && peeled.quantity > 0 ? peeled.quantity : 1,
|
||
unit: peeled.unit || '个',
|
||
processingMethod: extractProcessingMethod(normalized, peeled.name || normalized.slice(0, 30)),
|
||
});
|
||
}
|
||
}
|
||
|
||
return items;
|
||
}
|
||
|
||
function extractProcessingMethod(text: string, itemName: string): string {
|
||
const windowText = text.includes(itemName)
|
||
? text.slice(Math.max(0, text.indexOf(itemName) - 8), text.indexOf(itemName) + itemName.length + 16)
|
||
: text;
|
||
return PROCESSING_METHODS.find((method) => windowText.includes(method)) || '';
|
||
}
|
||
|
||
function stripProcessingMethod(name: string, processingMethod?: string): string {
|
||
let cleaned = String(name || '').trim();
|
||
if (processingMethod) {
|
||
cleaned = cleaned.replace(new RegExp(processingMethod, 'g'), '');
|
||
}
|
||
return cleaned.replace(/加工方式[::]?/g, '').trim() || String(name || '').trim();
|
||
}
|
||
|
||
/**
|
||
* 规格比对用的归一:只抹掉"写法差异",不改语义 ——
|
||
* 去空白、小写、乘号统一(`*` `×` `✕` `x`)、全角括号/斜杠折半角。
|
||
*/
|
||
export function normalizeSpecForMatch(raw: unknown): string {
|
||
return String(raw ?? '')
|
||
.trim()
|
||
// U+0130(İ):PG `lower('İ')` 得到 `i`,而 JS `toLowerCase()` 得到 `i`+U+0307(组合点)
|
||
// ⇒ 不折就会与 SQL 侧不等价(第三轮对抗实测)。先折成 `i` 再走后续流程。
|
||
.replace(/\u0130/g, 'i')
|
||
.toLowerCase()
|
||
// 全角数字/字母折半角(对抗实测:`1箱12瓶` 与 `1箱12瓶` 必须同值;U+FF10.. → ASCII 偏移 0xFEE0)
|
||
.replace(/[\uFF10-\uFF19\uFF21-\uFF3A\uFF41-\uFF5A]/g, (ch) =>
|
||
String.fromCharCode(ch.charCodeAt(0) - 0xfee0)
|
||
)
|
||
.replace(/\s+/g, '')
|
||
.replace(/[×✕✖x]/g, '*')
|
||
.replace(/(/g, '(')
|
||
.replace(/)/g, ')')
|
||
.replace(///g, '/');
|
||
}
|
||
|
||
/**
|
||
* 按**规格**在候选里消歧(2026-10-16)。
|
||
*
|
||
* 场景:同一个品名对应多条 SKU(一品多规格,如「旺仔牛奶 1箱24瓶 / 1箱12瓶」),
|
||
* 客户单据上写了 `1箱12瓶` ⇒ 应该直接落 12 瓶那条,而不是靠历史频次或让录单员猜。
|
||
*
|
||
* 口径(**宁可不选,也不猜错**):
|
||
* · 没写规格 / 候选为空 / 没有一个候选的规格与它相同 / **多个候选同规格** ⇒ 返回 null,
|
||
* 交回既有链路(历史频次自动消歧 → 仍歧义则把候选列表给录单员手选);
|
||
* · 只在**唯一命中**时才自动选中。
|
||
*/
|
||
export function pickCandidateBySpec(
|
||
candidates: Array<{ skuCode: string; skuName: string; spec?: string | null }>,
|
||
spec: unknown
|
||
): { skuCode: string; skuName: string } | null {
|
||
const target = normalizeSpecForMatch(spec);
|
||
if (!target || !Array.isArray(candidates) || candidates.length === 0) return null;
|
||
const hits = candidates.filter((c) => normalizeSpecForMatch(c.spec) === target);
|
||
if (hits.length !== 1) return null;
|
||
return { skuCode: hits[0].skuCode, skuName: hits[0].skuName };
|
||
}
|
||
|
||
async function resolveOrderPrompt(
|
||
featureKey:
|
||
| 'order.parse.text'
|
||
| 'order.parse.image'
|
||
| 'order.classify.category',
|
||
options?: ArkCallOptions,
|
||
vars?: Record<string, string>
|
||
): Promise<string> {
|
||
const prompt = await resolvePrompt(featureKey, { branchCode: options?.branchCode, vars });
|
||
return prompt.systemPrompt;
|
||
}
|
||
|
||
type ParseExtractOptions = ArkCallOptions & {
|
||
includeParseCategory?: boolean;
|
||
categoryList?: string;
|
||
};
|
||
|
||
/** 将模型给出的分类名/编码对上已有分类 */
|
||
export function matchCategoryLabelToCode(
|
||
raw: string,
|
||
categoryNames: Map<string, string>
|
||
): string | null {
|
||
const t = String(raw || '').trim();
|
||
if (!t) return null;
|
||
if (categoryNames.has(t)) return t;
|
||
const lower = t.toLowerCase();
|
||
for (const [code, name] of categoryNames) {
|
||
const n = String(name || '').trim();
|
||
if (n === t || n.toLowerCase() === lower) return code;
|
||
}
|
||
const paren = t.match(/^(.+?)[((]([^))]+)[))]$/);
|
||
if (paren) {
|
||
const maybeName = paren[1].trim();
|
||
const maybeCode = paren[2].trim();
|
||
if (categoryNames.has(maybeCode)) return maybeCode;
|
||
const byName = matchCategoryLabelToCode(maybeName, categoryNames);
|
||
if (byName) return byName;
|
||
}
|
||
const colon = t.split(/[::]/);
|
||
if (colon.length === 2) {
|
||
const a = colon[0].trim();
|
||
const b = colon[1].trim();
|
||
if (categoryNames.has(a)) return a;
|
||
if (categoryNames.has(b)) return b;
|
||
return matchCategoryLabelToCode(a, categoryNames) || matchCategoryLabelToCode(b, categoryNames);
|
||
}
|
||
return null;
|
||
}
|
||
|
||
function applyExtractedCategoryLabels(
|
||
items: ExtractedItem[],
|
||
categoryNames: Map<string, string> | null,
|
||
includeParseCategory: boolean
|
||
): void {
|
||
for (const item of items) {
|
||
const label = String(item.categoryLabel || item.categoryCode || '').trim();
|
||
if (!includeParseCategory) {
|
||
item.categoryCode = undefined;
|
||
item.categoryLabel = undefined;
|
||
item.suggestedCategoryName = undefined;
|
||
continue;
|
||
}
|
||
if (!label) {
|
||
item.categoryCode = undefined;
|
||
item.suggestedCategoryName = undefined;
|
||
continue;
|
||
}
|
||
const code = categoryNames ? matchCategoryLabelToCode(label, categoryNames) : null;
|
||
if (code) {
|
||
item.categoryCode = code;
|
||
item.suggestedCategoryName = undefined;
|
||
} else {
|
||
item.categoryCode = undefined;
|
||
item.suggestedCategoryName = label.slice(0, 40);
|
||
}
|
||
}
|
||
}
|
||
|
||
function formatCategoryListForPrompt(categoryNames: Map<string, string>): string {
|
||
return [...categoryNames.entries()]
|
||
.map(([code, name]) => `${name}(${code})`)
|
||
.join('\n');
|
||
}
|
||
|
||
/** 按入口选用对应拆条提示词(语音先转写为文本,复用 order.parse.text) */
|
||
async function resolveParseItemsPrompt(
|
||
featureKey: 'order.parse.text' | 'order.parse.image',
|
||
options?: ParseExtractOptions
|
||
): Promise<string> {
|
||
return resolveOrderPrompt(featureKey, options, {
|
||
category_list: options?.categoryList || '',
|
||
});
|
||
}
|
||
|
||
async function extractItemsWithLLM(
|
||
text: string,
|
||
options?: ParseExtractOptions
|
||
): Promise<ExtractedItem[]> {
|
||
const systemPrompt = await resolveParseItemsPrompt('order.parse.text', options);
|
||
const content = await callArkWithText(systemPrompt, text, options);
|
||
if (content) {
|
||
const items = parseItemsFromModelContent(content, 'text');
|
||
if (items.length) return items;
|
||
}
|
||
return extractItemsFromTextLocally(text);
|
||
}
|
||
|
||
/** 图片:一次多模态看图出 JSON,不再 OCR 后再文本拆条 */
|
||
async function extractItemsFromImage(
|
||
imageBase64: string,
|
||
options?: ParseExtractOptions
|
||
): Promise<{ items: ExtractedItem[]; ocrText: string }> {
|
||
const systemPrompt = await resolveParseItemsPrompt('order.parse.image', options);
|
||
console.info('Order image parse prompt:', {
|
||
featureKey: 'order.parse.image',
|
||
promptChars: systemPrompt.length,
|
||
promptHead: systemPrompt.replace(/\s+/g, ' ').slice(0, 48),
|
||
});
|
||
const content = (await callArkWithImage(systemPrompt, imageBase64, options)) || '';
|
||
if (!content.trim()) {
|
||
console.warn('AI image parse returned empty content (Responses 空正文或 Chat 兜底仍无输出)');
|
||
return { items: [], ocrText: '' };
|
||
}
|
||
console.info('Vision parse content length:', content.length);
|
||
const items = parseItemsFromModelContent(content, 'image');
|
||
return { items, ocrText: content };
|
||
}
|
||
|
||
async function extractItemsFromAudio(
|
||
audioBase64: string,
|
||
audioFormat: string | undefined,
|
||
options?: ParseExtractOptions
|
||
): Promise<ExtractedItem[]> {
|
||
const format = normalizeOrderAudioFormat(audioFormat);
|
||
// 兜底(ASR 未配置/失败时走 Ark 音频)需要租户上下文,故把 arkOptions 透传
|
||
const transcribed = await transcribeAudioBase64(audioBase64, format, options);
|
||
const spoken = transcribed.text.trim();
|
||
if (!spoken) return [];
|
||
console.info('Order voice ASR complete:', { chars: spoken.length, format, durationMs: transcribed.durationMs || null });
|
||
return extractItemsWithLLM(spoken, options);
|
||
}
|
||
|
||
function normalizeOrderAudioFormat(raw?: string): AudioFormat {
|
||
const t = String(raw || '').toLowerCase();
|
||
if (t.includes('wav')) return 'wav';
|
||
if (t.includes('mp3')) return 'mp3';
|
||
if (t.includes('ogg')) return 'ogg';
|
||
return 'webm';
|
||
}
|
||
|
||
async function extractItemsFromImageParallel(
|
||
imageBase64: string,
|
||
options?: ParseExtractOptions
|
||
): Promise<{
|
||
items: ExtractedItem[];
|
||
ocrText: string;
|
||
mode: 'multimodal';
|
||
parallelCount: number;
|
||
requestItemCounts: number[];
|
||
}> {
|
||
const startedAt = Date.now();
|
||
const { items, ocrText } = await extractItemsFromImage(imageBase64, options);
|
||
console.info('Order image multimodal parse complete:', {
|
||
itemCount: items.length,
|
||
ocrTextLen: ocrText.length,
|
||
elapsedMs: Date.now() - startedAt,
|
||
});
|
||
return {
|
||
items,
|
||
ocrText,
|
||
mode: 'multimodal',
|
||
parallelCount: 1,
|
||
requestItemCounts: [items.length],
|
||
};
|
||
}
|
||
|
||
async function matchCustomerSkuLibrary(customerCode: string, originalName: string) {
|
||
const exact = await pool.query(
|
||
`SELECT cs.sku_code, cs.customer_sku_name, cs.customer_unit, cs.processing_method, s.sku_name
|
||
FROM customer_skus cs
|
||
LEFT JOIN skus s ON s.sku_code = cs.sku_code
|
||
WHERE cs.customer_code = $1 AND cs.customer_sku_name ILIKE $2
|
||
ORDER BY cs.usage_count DESC NULLS LAST
|
||
LIMIT 1`,
|
||
[customerCode, originalName]
|
||
);
|
||
if (exact.rows[0]) {
|
||
const row = exact.rows[0];
|
||
return {
|
||
skuCode: row.sku_code,
|
||
skuName: row.sku_name || row.customer_sku_name,
|
||
unit: row.customer_unit,
|
||
processingMethod: row.processing_method || '',
|
||
confidence: 0.98,
|
||
layer: 0 as const,
|
||
};
|
||
}
|
||
|
||
const fuzzy = await pool.query(
|
||
`SELECT cs.sku_code, cs.customer_sku_name, cs.customer_unit, cs.processing_method, s.sku_name
|
||
FROM customer_skus cs
|
||
LEFT JOIN skus s ON s.sku_code = cs.sku_code
|
||
WHERE cs.customer_code = $1 AND cs.customer_sku_name ILIKE $2
|
||
ORDER BY cs.usage_count DESC NULLS LAST
|
||
LIMIT 1`,
|
||
[customerCode, `%${originalName}%`]
|
||
);
|
||
if (fuzzy.rows[0]) {
|
||
const row = fuzzy.rows[0];
|
||
return {
|
||
skuCode: row.sku_code,
|
||
skuName: row.sku_name || row.customer_sku_name,
|
||
unit: row.customer_unit,
|
||
processingMethod: row.processing_method || '',
|
||
confidence: 0.92,
|
||
layer: 0 as const,
|
||
};
|
||
}
|
||
return null;
|
||
}
|
||
|
||
async function matchCustomerAlias(customerCode: string, originalName: string) {
|
||
const exact = await pool.query(
|
||
`SELECT csa.sku_code, s.sku_name, csa.confidence_score
|
||
FROM customer_sku_aliases csa
|
||
LEFT JOIN skus s ON s.sku_code = csa.sku_code
|
||
WHERE csa.customer_code = $1 AND csa.alias_name = $2 AND csa.status = 1
|
||
ORDER BY csa.is_primary DESC, csa.usage_count DESC
|
||
LIMIT 1`,
|
||
[customerCode, originalName]
|
||
);
|
||
if (exact.rows[0]) {
|
||
return {
|
||
skuCode: exact.rows[0].sku_code,
|
||
skuName: exact.rows[0].sku_name || originalName,
|
||
confidence: exact.rows[0].confidence_score || 0.95,
|
||
layer: 1 as const,
|
||
};
|
||
}
|
||
|
||
const fuzzy = await pool.query(
|
||
`SELECT csa.sku_code, s.sku_name, csa.confidence_score
|
||
FROM customer_sku_aliases csa
|
||
LEFT JOIN skus s ON s.sku_code = csa.sku_code
|
||
WHERE csa.customer_code = $1 AND csa.alias_name ILIKE $2 AND csa.status = 1
|
||
ORDER BY csa.is_primary DESC, csa.usage_count DESC NULLS LAST
|
||
LIMIT 1`,
|
||
[customerCode, `%${originalName}%`]
|
||
);
|
||
if (fuzzy.rows[0]) {
|
||
return {
|
||
skuCode: fuzzy.rows[0].sku_code,
|
||
skuName: fuzzy.rows[0].sku_name || originalName,
|
||
confidence: fuzzy.rows[0].confidence_score || 0.85,
|
||
layer: 1 as const,
|
||
};
|
||
}
|
||
return null;
|
||
}
|
||
|
||
async function matchDirectSku(originalName: string) {
|
||
const exact = await pool.query(
|
||
`SELECT sku_code, sku_name FROM skus WHERE sku_name = $1 AND status = 1 LIMIT 1`,
|
||
[originalName]
|
||
);
|
||
if (exact.rows[0]) {
|
||
return {
|
||
skuCode: exact.rows[0].sku_code,
|
||
skuName: exact.rows[0].sku_name,
|
||
confidence: 0.75,
|
||
layer: 3 as const,
|
||
};
|
||
}
|
||
|
||
const startsWith = await pool.query(
|
||
`SELECT sku_code, sku_name
|
||
FROM skus
|
||
WHERE sku_name ILIKE $1 AND status = 1
|
||
ORDER BY length(sku_name) ASC
|
||
LIMIT 1`,
|
||
[`${originalName}%`]
|
||
);
|
||
if (startsWith.rows[0]) {
|
||
return {
|
||
skuCode: startsWith.rows[0].sku_code,
|
||
skuName: startsWith.rows[0].sku_name,
|
||
confidence: 0.72,
|
||
layer: 3 as const,
|
||
};
|
||
}
|
||
|
||
const fuzzy = await pool.query(
|
||
`SELECT sku_code, sku_name
|
||
FROM skus
|
||
WHERE sku_name ILIKE $1 AND status = 1
|
||
ORDER BY length(sku_name) ASC
|
||
LIMIT 1`,
|
||
[`%${originalName}%`]
|
||
);
|
||
if (fuzzy.rows[0]) {
|
||
return {
|
||
skuCode: fuzzy.rows[0].sku_code,
|
||
skuName: fuzzy.rows[0].sku_name,
|
||
confidence: 0.7,
|
||
layer: 3 as const,
|
||
};
|
||
}
|
||
return null;
|
||
}
|
||
|
||
type ParseMatchResult = {
|
||
skuCode: string;
|
||
skuName: string;
|
||
unit?: string;
|
||
processingMethod?: string;
|
||
confidence: number;
|
||
layer: 0 | 1 | 3;
|
||
/** 消歧候选:Layer 3 模糊匹配到多个 SKU 时返回 */
|
||
candidates?: SkuCandidate[];
|
||
};
|
||
|
||
interface SmartClassificationRule {
|
||
keyword: string;
|
||
categoryCode: string;
|
||
matchType: string;
|
||
priority: number;
|
||
}
|
||
|
||
interface ParseMatchContext {
|
||
customerSkus: Array<{
|
||
name: string;
|
||
skuCode: string;
|
||
skuName: string;
|
||
unit: string;
|
||
processingMethod: string;
|
||
usageCount: number;
|
||
categoryCode: string;
|
||
}>;
|
||
customerAliases: Array<{
|
||
alias: string;
|
||
skuCode: string;
|
||
skuName: string;
|
||
confidence: number;
|
||
usageCount: number;
|
||
}>;
|
||
skus: Array<{ skuCode: string; skuName: string; categoryCode: string; spec?: string | null }>;
|
||
customerSkuCodes: Set<string>;
|
||
customerAliasKeys: Set<string>;
|
||
customerProcessingAliases: Array<{ alias: string; processingMethod: string }>;
|
||
skuCategoryByCode: Map<string, string>;
|
||
catalogParentByCode: Map<string, string>;
|
||
smartRules: SmartClassificationRule[];
|
||
}
|
||
|
||
function normMatchText(value: string) {
|
||
return String(value || '').trim().toLowerCase();
|
||
}
|
||
|
||
async function buildParseMatchContext(customerCode: string): Promise<ParseMatchContext> {
|
||
const [customerSkus, customerAliases, skus, smartRules, catalogRows] = await Promise.all([
|
||
pool.query(
|
||
`SELECT cs.customer_sku_name, cs.sku_code, cs.customer_unit, cs.processing_method, cs.category_code, s.sku_name, cs.usage_count
|
||
FROM customer_skus cs
|
||
LEFT JOIN skus s ON s.sku_code = cs.sku_code
|
||
WHERE cs.customer_code = $1`,
|
||
[customerCode]
|
||
),
|
||
pool.query(
|
||
`SELECT csa.alias_name, csa.sku_code, s.sku_name, csa.confidence_score, csa.usage_count
|
||
FROM customer_sku_aliases csa
|
||
LEFT JOIN skus s ON s.sku_code = csa.sku_code
|
||
WHERE csa.customer_code = $1 AND COALESCE(csa.status, 1) = 1`,
|
||
[customerCode]
|
||
),
|
||
pool.query(`SELECT sku_code, sku_name, category_code, spec FROM skus WHERE status = 1`),
|
||
pool.query(
|
||
`SELECT keyword, category_code, match_type, priority
|
||
FROM smart_classification_rules
|
||
WHERE is_active = true
|
||
ORDER BY priority DESC NULLS LAST, length(keyword) DESC`
|
||
),
|
||
pool.query(
|
||
`SELECT code, parent_code FROM product_catalog WHERE item_type = 'product' AND parent_code IS NOT NULL`
|
||
),
|
||
]);
|
||
|
||
let customerProcessingAliases: Array<{ alias_name: string; processing_method: string }> = [];
|
||
try {
|
||
const processingResult = await pool.query(
|
||
`SELECT alias_name, processing_method
|
||
FROM customer_processing_aliases
|
||
WHERE customer_code = $1 AND COALESCE(status, 1) = 1`,
|
||
[customerCode]
|
||
);
|
||
customerProcessingAliases = processingResult.rows;
|
||
} catch (error: any) {
|
||
if (error?.code !== '42P01') throw error;
|
||
console.warn('customer_processing_aliases table missing, skipping processing alias match');
|
||
}
|
||
|
||
const customerSkuCodes = new Set<string>();
|
||
const customerAliasKeys = new Set<string>();
|
||
customerSkus.rows.forEach((row) => customerSkuCodes.add(String(row.sku_code)));
|
||
customerAliases.rows.forEach((row) => {
|
||
customerAliasKeys.add(`${String(row.alias_name)}|${String(row.sku_code)}`);
|
||
});
|
||
|
||
const skuCategoryByCode = new Map<string, string>();
|
||
for (const row of skus.rows) {
|
||
const code = String(row.category_code || '').trim();
|
||
if (code) skuCategoryByCode.set(String(row.sku_code), code);
|
||
}
|
||
|
||
const catalogParentByCode = new Map<string, string>();
|
||
for (const row of catalogRows.rows) {
|
||
const parent = String(row.parent_code || '').trim();
|
||
if (parent) catalogParentByCode.set(String(row.code), parent);
|
||
}
|
||
|
||
return {
|
||
customerSkus: customerSkus.rows.map((row) => ({
|
||
name: String(row.customer_sku_name || ''),
|
||
skuCode: String(row.sku_code || ''),
|
||
skuName: String(row.sku_name || row.customer_sku_name || ''),
|
||
unit: String(row.customer_unit || ''),
|
||
processingMethod: String(row.processing_method || ''),
|
||
usageCount: Number(row.usage_count) || 0,
|
||
categoryCode: String(row.category_code || '').trim(),
|
||
})),
|
||
customerAliases: customerAliases.rows.map((row) => ({
|
||
alias: String(row.alias_name || ''),
|
||
skuCode: String(row.sku_code || ''),
|
||
skuName: String(row.sku_name || row.alias_name || ''),
|
||
confidence: Number(row.confidence_score) || 0.85,
|
||
usageCount: Number(row.usage_count) || 0,
|
||
})),
|
||
skus: skus.rows.map((row) => ({
|
||
skuCode: String(row.sku_code || ''),
|
||
skuName: String(row.sku_name || ''),
|
||
categoryCode: String(row.category_code || '').trim(),
|
||
spec: row.spec == null ? null : String(row.spec),
|
||
})),
|
||
customerSkuCodes,
|
||
customerAliasKeys,
|
||
customerProcessingAliases: customerProcessingAliases.map((row) => ({
|
||
alias: String(row.alias_name || ''),
|
||
processingMethod: String(row.processing_method || ''),
|
||
})),
|
||
skuCategoryByCode,
|
||
catalogParentByCode,
|
||
smartRules: smartRules.rows.map((row) => ({
|
||
keyword: String(row.keyword || ''),
|
||
categoryCode: String(row.category_code || ''),
|
||
matchType: String(row.match_type || 'contains'),
|
||
priority: Number(row.priority) || 0,
|
||
})),
|
||
};
|
||
}
|
||
|
||
function matchFromContext(ctx: ParseMatchContext, originalName: string): ParseMatchResult | null {
|
||
const name = originalName.trim();
|
||
const lower = normMatchText(name);
|
||
if (!lower) return null;
|
||
|
||
// 精确段优先别名(Layer 1),再客户商品库(Layer 0);层号仍表示来源表
|
||
const exactCustomerAlias = ctx.customerAliases.find((row) => normMatchText(row.alias) === lower);
|
||
if (exactCustomerAlias) {
|
||
return {
|
||
skuCode: exactCustomerAlias.skuCode,
|
||
skuName: exactCustomerAlias.skuName,
|
||
confidence: exactCustomerAlias.confidence || 0.95,
|
||
layer: 1,
|
||
};
|
||
}
|
||
|
||
const exactCustomerSku = ctx.customerSkus.find((row) => normMatchText(row.name) === lower);
|
||
if (exactCustomerSku) {
|
||
return {
|
||
skuCode: exactCustomerSku.skuCode,
|
||
skuName: exactCustomerSku.skuName,
|
||
unit: exactCustomerSku.unit,
|
||
processingMethod: exactCustomerSku.processingMethod,
|
||
confidence: 0.98,
|
||
layer: 0,
|
||
};
|
||
}
|
||
|
||
const fuzzyCustomerSku = [...ctx.customerSkus]
|
||
.sort((a, b) => b.usageCount - a.usageCount)
|
||
.find((row) => isSafeLooseNameContain(lower, normMatchText(row.name)));
|
||
if (fuzzyCustomerSku) {
|
||
return {
|
||
skuCode: fuzzyCustomerSku.skuCode,
|
||
skuName: fuzzyCustomerSku.skuName,
|
||
unit: fuzzyCustomerSku.unit,
|
||
processingMethod: fuzzyCustomerSku.processingMethod,
|
||
confidence: 0.92,
|
||
layer: 0,
|
||
};
|
||
}
|
||
|
||
const fuzzyCustomerAlias = [...ctx.customerAliases]
|
||
.sort((a, b) => b.usageCount - a.usageCount)
|
||
.find((row) => isSafeLooseNameContain(lower, normMatchText(row.alias)));
|
||
if (fuzzyCustomerAlias) {
|
||
return {
|
||
skuCode: fuzzyCustomerAlias.skuCode,
|
||
skuName: fuzzyCustomerAlias.skuName,
|
||
confidence: fuzzyCustomerAlias.confidence || 0.85,
|
||
layer: 1,
|
||
};
|
||
}
|
||
|
||
const exactSku = ctx.skus.find((row) => normMatchText(row.skuName) === lower);
|
||
if (exactSku) {
|
||
return { skuCode: exactSku.skuCode, skuName: exactSku.skuName, confidence: 0.75, layer: 3 };
|
||
}
|
||
|
||
const startsWithSku = [...ctx.skus]
|
||
.filter((row) => {
|
||
const skuName = normMatchText(row.skuName);
|
||
return skuName.startsWith(lower) && isSafeLooseNameContain(lower, skuName);
|
||
})
|
||
.sort((a, b) => a.skuName.length - b.skuName.length);
|
||
if (startsWithSku.length > 0) {
|
||
if (startsWithSku.length > 1) {
|
||
return {
|
||
skuCode: '',
|
||
skuName: startsWithSku[0].skuName,
|
||
confidence: 0.72,
|
||
layer: 3,
|
||
candidates: startsWithSku.slice(0, 8).map((row) => ({
|
||
skuCode: row.skuCode,
|
||
skuName: row.skuName,
|
||
unit: '',
|
||
categoryCode: row.categoryCode || '',
|
||
categoryName: '',
|
||
spec: row.spec ?? null,
|
||
orderCount: 0,
|
||
confidence: 0.72,
|
||
})),
|
||
};
|
||
}
|
||
return { skuCode: startsWithSku[0].skuCode, skuName: startsWithSku[0].skuName, confidence: 0.72, layer: 3 };
|
||
}
|
||
|
||
const fuzzySku = [...ctx.skus]
|
||
.filter((row) => isSafeLooseNameContain(lower, normMatchText(row.skuName)))
|
||
.sort((a, b) => a.skuName.length - b.skuName.length);
|
||
if (fuzzySku.length > 0) {
|
||
// 多个候选时返回消歧列表,供录单员选择
|
||
if (fuzzySku.length > 1) {
|
||
return {
|
||
skuCode: '',
|
||
skuName: fuzzySku[0].skuName,
|
||
confidence: 0.7,
|
||
layer: 3,
|
||
candidates: fuzzySku.slice(0, 8).map((row) => ({
|
||
skuCode: row.skuCode,
|
||
skuName: row.skuName,
|
||
unit: '',
|
||
categoryCode: row.categoryCode || '',
|
||
categoryName: '',
|
||
spec: row.spec ?? null,
|
||
orderCount: 0,
|
||
confidence: 0.7,
|
||
})),
|
||
};
|
||
}
|
||
return { skuCode: fuzzySku[0].skuCode, skuName: fuzzySku[0].skuName, confidence: 0.7, layer: 3 };
|
||
}
|
||
|
||
return null;
|
||
}
|
||
|
||
type SpokenRatioCandidate = {
|
||
match: ParseMatchResult;
|
||
leftover: number;
|
||
usageCount: number;
|
||
order: number;
|
||
};
|
||
|
||
function matchSpokenRatioFromContext(ctx: ParseMatchContext, originalName: string): ParseMatchResult | null {
|
||
const name = originalName.trim();
|
||
const lower = normMatchText(name);
|
||
if (!lower) return null;
|
||
|
||
// 精确段优先别名(Layer 1),再客户商品库(Layer 0);层号仍表示来源表
|
||
const exactCustomerAlias = ctx.customerAliases.find((row) => normMatchText(row.alias) === lower);
|
||
if (exactCustomerAlias) {
|
||
return {
|
||
skuCode: exactCustomerAlias.skuCode,
|
||
skuName: exactCustomerAlias.skuName,
|
||
confidence: exactCustomerAlias.confidence || 0.95,
|
||
layer: 1,
|
||
};
|
||
}
|
||
const exactCustomerSku = ctx.customerSkus.find((row) => normMatchText(row.name) === lower);
|
||
if (exactCustomerSku) {
|
||
return {
|
||
skuCode: exactCustomerSku.skuCode,
|
||
skuName: exactCustomerSku.skuName,
|
||
unit: exactCustomerSku.unit,
|
||
processingMethod: exactCustomerSku.processingMethod,
|
||
confidence: 0.98,
|
||
layer: 0,
|
||
};
|
||
}
|
||
const exactSku = ctx.skus.find((row) => normMatchText(row.skuName) === lower);
|
||
if (exactSku) {
|
||
return { skuCode: exactSku.skuCode, skuName: exactSku.skuName, confidence: 0.75, layer: 3 };
|
||
}
|
||
|
||
const candidates: SpokenRatioCandidate[] = [];
|
||
let order = 0;
|
||
const pushIfWindow = (label: string, match: ParseMatchResult, usageCount: number) => {
|
||
const score = spokenNameWindowScore(lower, label);
|
||
if (!score) return;
|
||
candidates.push({ match, leftover: score.leftover, usageCount, order: order++ });
|
||
};
|
||
|
||
for (const row of ctx.customerSkus) {
|
||
pushIfWindow(row.name, {
|
||
skuCode: row.skuCode,
|
||
skuName: row.skuName,
|
||
unit: row.unit,
|
||
processingMethod: row.processingMethod,
|
||
confidence: 0.92,
|
||
layer: 0,
|
||
}, row.usageCount);
|
||
}
|
||
for (const row of ctx.customerAliases) {
|
||
pushIfWindow(row.alias, {
|
||
skuCode: row.skuCode,
|
||
skuName: row.skuName,
|
||
confidence: row.confidence || 0.85,
|
||
layer: 1,
|
||
}, row.usageCount);
|
||
}
|
||
for (const row of ctx.skus) {
|
||
pushIfWindow(row.skuName, {
|
||
skuCode: row.skuCode,
|
||
skuName: row.skuName,
|
||
confidence: 0.7,
|
||
layer: 3,
|
||
}, 0);
|
||
}
|
||
|
||
if (!candidates.length) return null;
|
||
candidates.sort((a, b) => {
|
||
if (a.leftover !== b.leftover) return a.leftover - b.leftover;
|
||
if (a.usageCount !== b.usageCount) return b.usageCount - a.usageCount;
|
||
return a.order - b.order;
|
||
});
|
||
return candidates[0].match;
|
||
}
|
||
|
||
function isInCustomerLibraryFromContext(ctx: ParseMatchContext, skuCode: string, originalName: string) {
|
||
if (ctx.customerSkuCodes.has(skuCode)) return true;
|
||
return ctx.customerAliasKeys.has(`${originalName}|${skuCode}`);
|
||
}
|
||
|
||
async function loadCategoryNameMap(branchCode?: string | null): Promise<Map<string, string>> {
|
||
const rows = await fetchCategoryRows(branchCode);
|
||
return new Map(rows.map((row) => [row.category_code, row.category_name]));
|
||
}
|
||
|
||
function resolveCategoryFromSmartRulesInMemory(
|
||
originalName: string,
|
||
rules: SmartClassificationRule[]
|
||
): string | null {
|
||
const normalized = originalName.trim().toLowerCase();
|
||
if (!normalized) return null;
|
||
for (const rule of rules) {
|
||
const keyword = rule.keyword.toLowerCase();
|
||
if (!keyword) continue;
|
||
if (rule.matchType === 'exact' && normalized === keyword) {
|
||
return rule.categoryCode;
|
||
}
|
||
if (rule.matchType !== 'exact' && normalized.includes(keyword)) {
|
||
return rule.categoryCode;
|
||
}
|
||
}
|
||
return null;
|
||
}
|
||
|
||
function resolveCategoryCodeInMemory(
|
||
ctx: ParseMatchContext,
|
||
originalName: string,
|
||
skuCode?: string
|
||
): string | null {
|
||
const trimmedName = originalName.trim();
|
||
const code = String(skuCode || '').trim();
|
||
|
||
if (code) {
|
||
const fromSku = ctx.skuCategoryByCode.get(code);
|
||
if (fromSku) return fromSku;
|
||
const fromCatalog = ctx.catalogParentByCode.get(code);
|
||
if (fromCatalog) return fromCatalog;
|
||
const customerSku = ctx.customerSkus.find((row) => row.skuCode === code && row.categoryCode);
|
||
if (customerSku?.categoryCode) return customerSku.categoryCode;
|
||
}
|
||
|
||
if (trimmedName) {
|
||
const lower = normMatchText(trimmedName);
|
||
const byName = ctx.customerSkus.find((row) => normMatchText(row.name) === lower && row.categoryCode);
|
||
if (byName?.categoryCode) return byName.categoryCode;
|
||
|
||
const fuzzyName = [...ctx.customerSkus]
|
||
.filter((row) => {
|
||
if (!row.categoryCode) return false;
|
||
return isSafeLooseNameContain(lower, normMatchText(row.name));
|
||
})
|
||
.sort((a, b) => b.name.length - a.name.length)[0];
|
||
if (fuzzyName?.categoryCode) return fuzzyName.categoryCode;
|
||
|
||
const alias = ctx.customerAliases.find((row) => normMatchText(row.alias) === lower);
|
||
if (alias) {
|
||
const byAlias = ctx.customerSkus.find((row) => row.skuCode === alias.skuCode && row.categoryCode);
|
||
if (byAlias?.categoryCode) return byAlias.categoryCode;
|
||
}
|
||
}
|
||
|
||
return resolveCategoryFromSmartRulesInMemory(trimmedName, ctx.smartRules);
|
||
}
|
||
|
||
async function classifyItemsWithModel(
|
||
items: ParsedItem[],
|
||
categoryNames: Map<string, string>,
|
||
options?: ArkCallOptions
|
||
): Promise<void> {
|
||
const pending = items.filter((item) => !item.categoryCode);
|
||
if (!pending.length || categoryNames.size === 0 || !(await hasArkRuntimeConfig(options))) return;
|
||
|
||
const categoryList = [...categoryNames.entries()]
|
||
.map(([code, name]) => `${code}:${name}`)
|
||
.join('\n');
|
||
const nameList = pending.map((item) => item.originalName).join('\n');
|
||
const prompt = await resolveOrderPrompt('order.classify.category', options, {
|
||
category_list: categoryList,
|
||
});
|
||
|
||
const content = await callArkWithText(prompt, nameList, options);
|
||
if (!content) return;
|
||
|
||
try {
|
||
const cleaned = content.replace(/```json\s*/gi, '').replace(/```\s*/gi, '').trim();
|
||
const jsonMatch = cleaned.match(/\{[\s\S]*\}/);
|
||
if (!jsonMatch) return;
|
||
const parsed = JSON.parse(jsonMatch[0]);
|
||
const rows = parsed.items || [];
|
||
const codeMap = new Map<string, string>();
|
||
for (const row of rows) {
|
||
const name = String(row.originalName || row.name || '').trim();
|
||
const code = String(row.categoryCode || row.category_code || '').trim();
|
||
if (name && code && categoryNames.has(code)) {
|
||
codeMap.set(name, code);
|
||
}
|
||
}
|
||
|
||
for (const item of items) {
|
||
if (item.categoryCode) continue;
|
||
const code =
|
||
codeMap.get(item.originalName) ||
|
||
codeMap.get(item.skuName) ||
|
||
[...codeMap.entries()].find(([key]) => item.originalName.includes(key) || key.includes(item.originalName))?.[1];
|
||
if (code) {
|
||
item.categoryCode = code;
|
||
item.categoryName = categoryNames.get(code) || '';
|
||
}
|
||
}
|
||
} catch (error) {
|
||
console.warn('AI classify items failed:', error);
|
||
}
|
||
}
|
||
|
||
async function isInCustomerLibrary(customerCode: string, skuCode: string, originalName: string): Promise<boolean> {
|
||
const library = await pool.query(
|
||
`SELECT 1 FROM customer_skus WHERE customer_code = $1 AND sku_code = $2 LIMIT 1`,
|
||
[customerCode, skuCode]
|
||
);
|
||
if (library.rowCount) return true;
|
||
|
||
const alias = await pool.query(
|
||
`SELECT 1 FROM customer_sku_aliases
|
||
WHERE customer_code = $1 AND alias_name = $2 AND sku_code = $3 AND status = 1
|
||
LIMIT 1`,
|
||
[customerCode, originalName, skuCode]
|
||
);
|
||
return !!alias.rowCount;
|
||
}
|
||
|
||
async function fourLayerParse(
|
||
customerCode: string,
|
||
extractedItems: ExtractedItem[],
|
||
branchCode?: string | null,
|
||
matchMode: 'legacy' | 'spoken-ratio' = 'legacy'
|
||
): Promise<ParseResult> {
|
||
const [categoryNames, matchContext] = await Promise.all([
|
||
loadCategoryNameMap(branchCode),
|
||
buildParseMatchContext(customerCode),
|
||
]);
|
||
|
||
const resolveItemCategoryCode = (originalName: string, skuCode?: string, extractedCategoryCode?: string) => {
|
||
const fromCatalog = resolveCategoryCodeInMemory(matchContext, originalName, skuCode);
|
||
if (fromCatalog) return fromCatalog;
|
||
const fromModel = String(extractedCategoryCode || '').trim();
|
||
if (fromModel && categoryNames.has(fromModel)) return fromModel;
|
||
return null;
|
||
};
|
||
|
||
const rows = extractedItems.map((extracted) => {
|
||
const originalName = extracted.originalName?.trim();
|
||
if (!originalName) return null;
|
||
|
||
const match =
|
||
matchMode === 'spoken-ratio'
|
||
? matchSpokenRatioFromContext(matchContext, originalName)
|
||
: matchFromContext(matchContext, originalName);
|
||
|
||
if (match) {
|
||
// 消歧:有候选列表时,查询历史频次并尝试自动消歧
|
||
if (match.candidates && match.candidates.length > 0) {
|
||
// 延迟到 map 后统一查询,这里先标记
|
||
(match as any)._needsDisambiguation = true;
|
||
}
|
||
const categoryCode = resolveItemCategoryCode(originalName, match.skuCode, extracted.categoryCode);
|
||
const item: ParsedItem = {
|
||
originalName,
|
||
skuName: match.skuName,
|
||
skuCode: match.skuCode,
|
||
quantity: extracted.quantity || 1,
|
||
unit: match.unit || extracted.unit || '个',
|
||
matchLayer: match.layer,
|
||
confidence: match.confidence,
|
||
categoryCode: categoryCode || undefined,
|
||
categoryName: categoryCode ? categoryNames.get(categoryCode) || '' : '',
|
||
suggestedCategoryName: categoryCode ? undefined : extracted.suggestedCategoryName,
|
||
processingMethod: resolveProcessingMethodWithAliases(
|
||
extracted.processingMethod || match.processingMethod || '',
|
||
matchContext.customerProcessingAliases
|
||
) || extracted.processingMethod || match.processingMethod || '',
|
||
remark: extracted.remark,
|
||
spec: extracted.spec,
|
||
inCustomerLibrary: isInCustomerLibraryFromContext(matchContext, match.skuCode, originalName),
|
||
quantityNeedsConfirm: extracted.quantityNeedsConfirm,
|
||
quantityHint: extracted.quantityHint,
|
||
candidates: match.candidates || undefined,
|
||
};
|
||
return { item, unmatchedName: '', _match: match };
|
||
}
|
||
|
||
const categoryCode = resolveItemCategoryCode(originalName, undefined, extracted.categoryCode);
|
||
const item: ParsedItem = {
|
||
originalName,
|
||
skuName: originalName,
|
||
skuCode: '',
|
||
quantity: extracted.quantity || 1,
|
||
unit: extracted.unit || '个',
|
||
matchLayer: null,
|
||
confidence: 0,
|
||
categoryCode: categoryCode || undefined,
|
||
categoryName: categoryCode ? categoryNames.get(categoryCode) || '' : '',
|
||
suggestedCategoryName: categoryCode ? undefined : extracted.suggestedCategoryName,
|
||
processingMethod: resolveProcessingMethodWithAliases(
|
||
extracted.processingMethod || '',
|
||
matchContext.customerProcessingAliases
|
||
) || extracted.processingMethod || '',
|
||
remark: extracted.remark,
|
||
spec: extracted.spec,
|
||
inCustomerLibrary: false,
|
||
quantityNeedsConfirm: extracted.quantityNeedsConfirm,
|
||
quantityHint: extracted.quantityHint,
|
||
};
|
||
return { item, unmatchedName: originalName };
|
||
});
|
||
|
||
const parsedRows = rows.filter((row): row is { item: ParsedItem; unmatchedName: string; _match?: ParseMatchResult } => Boolean(row));
|
||
|
||
// 消歧后处理:查询历史频次,自动消歧或返回候选列表
|
||
const disambiguationItems = parsedRows.filter((row) => (row as any)._match?._needsDisambiguation);
|
||
if (disambiguationItems.length > 0) {
|
||
// 收集所有候选 SKU 码
|
||
const allCandidateCodes: string[] = [];
|
||
for (const row of disambiguationItems) {
|
||
const item = row.item;
|
||
if (item.candidates) {
|
||
for (const c of item.candidates) {
|
||
if (!allCandidateCodes.includes(c.skuCode)) allCandidateCodes.push(c.skuCode);
|
||
}
|
||
}
|
||
}
|
||
|
||
// 批量查询该客户对这些 SKU 的历史下单次数
|
||
const freqMap = new Map<string, number>();
|
||
if (allCandidateCodes.length > 0) {
|
||
const freqResult = await pool.query(
|
||
`SELECT oi.sku_code, COUNT(DISTINCT o.order_code)::int AS order_count
|
||
FROM order_items oi
|
||
JOIN orders o ON o.order_code = oi.order_code
|
||
WHERE o.customer_code = $1
|
||
AND oi.sku_code = ANY($2::text[])
|
||
AND o.order_status >= 20
|
||
AND o.deleted_at IS NULL
|
||
GROUP BY oi.sku_code`,
|
||
[customerCode, allCandidateCodes]
|
||
);
|
||
for (const row of freqResult.rows) {
|
||
freqMap.set(String(row.sku_code), Number(row.order_count) || 0);
|
||
}
|
||
}
|
||
|
||
// 对每个消歧项填充频次并尝试自动消歧
|
||
for (const row of disambiguationItems) {
|
||
const item = row.item;
|
||
if (!item.candidates) continue;
|
||
|
||
// 填充 orderCount
|
||
for (const c of item.candidates) {
|
||
c.orderCount = freqMap.get(c.skuCode) || 0;
|
||
}
|
||
|
||
/**
|
||
* **规格优先**(2026-10-16):客户单据上写了规格时,规格是**事实**、历史频次只是习惯,
|
||
* 所以规格唯一命中就直接定,不再走频次启发式。没写/不唯一 ⇒ 落回下面的既有链路。
|
||
*/
|
||
const bySpec = pickCandidateBySpec(item.candidates, item.spec);
|
||
if (bySpec) {
|
||
item.skuCode = bySpec.skuCode;
|
||
item.skuName = bySpec.skuName;
|
||
item.confidence = 0.9;
|
||
item.candidates = undefined; // 已按规格确定,不再返回候选
|
||
continue;
|
||
}
|
||
|
||
// 按 orderCount 降序排列
|
||
item.candidates.sort((a, b) => b.orderCount - a.orderCount);
|
||
|
||
// 自动消歧:如果第一名频次 > 0 且占总频次 > 70%,自动选中
|
||
const totalCount = item.candidates.reduce((sum, c) => sum + c.orderCount, 0);
|
||
const top = item.candidates[0];
|
||
if (totalCount > 0 && top.orderCount > 0 && top.orderCount / totalCount >= 0.7) {
|
||
item.skuCode = top.skuCode;
|
||
item.skuName = top.skuName;
|
||
item.confidence = 0.88;
|
||
item.candidates = undefined; // 自动选中,不再返回候选
|
||
}
|
||
// 否则保留 candidates 供前端展示,录单员手动选择
|
||
}
|
||
}
|
||
|
||
return {
|
||
items: parsedRows.map((row) => row.item),
|
||
unmatched: parsedRows.map((row) => row.unmatchedName).filter(Boolean),
|
||
};
|
||
}
|
||
|
||
export async function parseOrderThreeLayer(body: {
|
||
text?: string;
|
||
customerCode?: string;
|
||
imageBase64?: string;
|
||
audioBase64?: string;
|
||
audioFormat?: string;
|
||
branchCode?: string | null;
|
||
includeParseCategory?: boolean;
|
||
userId?: string | null;
|
||
}): Promise<ParseResult> {
|
||
const { text, customerCode, imageBase64, audioBase64, audioFormat, branchCode } = body;
|
||
const includeParseCategory = body.includeParseCategory === true;
|
||
const arkOptions: ParseExtractOptions = { branchCode, includeParseCategory };
|
||
if (!customerCode) {
|
||
throw new Error('请先选择客户');
|
||
}
|
||
if (!text && !imageBase64 && !audioBase64) {
|
||
throw new Error('请提供文本、图片或音频');
|
||
}
|
||
|
||
let extractedItems: ExtractedItem[] = [];
|
||
let extractedStats: ParseResult['extractedStats'];
|
||
let demoMode = false;
|
||
let message: string | undefined;
|
||
const totalStartedAt = Date.now();
|
||
const imageBytes = imageBase64 ? Math.ceil(imageBase64.length * 0.75) : 0;
|
||
|
||
const categoryNames = includeParseCategory ? await loadCategoryNameMap(branchCode) : null;
|
||
if (includeParseCategory) {
|
||
arkOptions.categoryList =
|
||
categoryNames && categoryNames.size > 0
|
||
? formatCategoryListForPrompt(categoryNames)
|
||
: '(暂无已有分类,请自拟短中文分类名)';
|
||
}
|
||
|
||
if (imageBase64) {
|
||
const arkConfigured = await hasArkRuntimeConfig(arkOptions);
|
||
const modelStartedAt = Date.now();
|
||
const imageParse = await extractItemsFromImageParallel(imageBase64, arkOptions);
|
||
extractedItems = imageParse.items;
|
||
extractedStats = {
|
||
parallelCount: imageParse.parallelCount,
|
||
requestItemCounts: imageParse.requestItemCounts,
|
||
mergedItemCount: extractedItems.length,
|
||
};
|
||
console.info('Order image parse model stage:', {
|
||
branchCode: branchCode || null,
|
||
imageBytes,
|
||
mode: imageParse.mode,
|
||
parallelCount: imageParse.parallelCount,
|
||
requestItemCounts: imageParse.requestItemCounts,
|
||
itemCount: extractedItems.length,
|
||
elapsedMs: Date.now() - modelStartedAt,
|
||
});
|
||
if (!extractedItems.length) {
|
||
demoMode = true;
|
||
message = !arkConfigured
|
||
? '未配置 ARK_API_KEY,识别失败;请配置后重试或改为手工录入(不再填充演示商品)'
|
||
: 'AI 未返回可解析商品,识别失败;请重新识别或手工录入(不再填充演示商品)';
|
||
}
|
||
} else if (audioBase64) {
|
||
const arkConfigured = await hasArkRuntimeConfig(arkOptions);
|
||
extractedItems = await extractItemsFromAudio(audioBase64, audioFormat, arkOptions);
|
||
extractedStats = {
|
||
parallelCount: 1,
|
||
requestItemCounts: [extractedItems.length],
|
||
mergedItemCount: extractedItems.length,
|
||
};
|
||
if (!extractedItems.length) {
|
||
demoMode = true;
|
||
message = !arkConfigured
|
||
? '未配置 ARK_API_KEY,识别失败;请配置后重试或改为手工录入'
|
||
: 'AI 未返回可解析商品,请重新录音或改为文字录入';
|
||
}
|
||
} else if (text) {
|
||
extractedItems = await extractItemsWithLLM(text, arkOptions);
|
||
}
|
||
|
||
applyExtractedCategoryLabels(extractedItems, categoryNames, includeParseCategory);
|
||
|
||
const matchStartedAt = Date.now();
|
||
const result = await fourLayerParse(
|
||
customerCode,
|
||
extractedItems,
|
||
branchCode,
|
||
'spoken-ratio'
|
||
);
|
||
if (imageBase64) {
|
||
for (const item of result.items) {
|
||
if (String(item.skuCode || '').trim()) continue;
|
||
const name = String(item.originalName || item.skuName || '').trim();
|
||
if (!name) continue;
|
||
const fuzzy = await findSkuByFuzzyName(name, branchCode, item.categoryCode || undefined);
|
||
if (!fuzzy) continue;
|
||
item.skuCode = fuzzy.skuCode;
|
||
item.skuName = fuzzy.skuName;
|
||
item.matchLayer = item.matchLayer ?? 3;
|
||
item.confidence = Math.max(item.confidence || 0, 0.72);
|
||
if (!item.categoryCode && fuzzy.categoryCode) {
|
||
item.categoryCode = fuzzy.categoryCode;
|
||
}
|
||
}
|
||
}
|
||
if (imageBase64) {
|
||
console.info('Order image parse match stage:', {
|
||
branchCode: branchCode || null,
|
||
itemCount: result.items.length,
|
||
unmatchedCount: result.unmatched.length,
|
||
elapsedMs: Date.now() - matchStartedAt,
|
||
});
|
||
}
|
||
const categoryNamesForClassify = await loadCategoryNameMap(branchCode);
|
||
// 图片/音频拆条已各调用一次多模态;分类优先用映射库/规则,避免再打一次 classify。
|
||
// Web 拆条已带分类(includeParseCategory),不再二次 classify。
|
||
if (!imageBase64 && !audioBase64 && !includeParseCategory) {
|
||
await classifyItemsWithModel(result.items, categoryNamesForClassify, arkOptions);
|
||
}
|
||
for (const item of result.items) {
|
||
if (item.categoryCode && !item.categoryName) {
|
||
item.categoryName = categoryNames?.get(item.categoryCode) || categoryNamesForClassify.get(item.categoryCode) || '';
|
||
}
|
||
}
|
||
const finalResult: ParseResult = { ...result, demoMode, message, extractedStats };
|
||
if (imageBase64) {
|
||
console.info('Order image parse complete:', {
|
||
branchCode: branchCode || null,
|
||
imageBytes,
|
||
itemCount: result.items.length,
|
||
demoMode,
|
||
elapsedMs: Date.now() - totalStartedAt,
|
||
});
|
||
}
|
||
return finalResult;
|
||
}
|
||
|
||
export async function parseImageOrder(body: {
|
||
imageBase64?: string;
|
||
customerCode?: string;
|
||
branchCode?: string | null;
|
||
includeParseCategory?: boolean;
|
||
userId?: string | null;
|
||
}): Promise<{ items: Array<{ skuName: string; quantity: number; unit: string }>; confidence: number; demoMode?: boolean; message?: string }> {
|
||
const customerCode = body.customerCode || 'self';
|
||
const parseResult = await parseOrderThreeLayer({
|
||
customerCode,
|
||
imageBase64: body.imageBase64,
|
||
branchCode: body.branchCode,
|
||
includeParseCategory: body.includeParseCategory === true,
|
||
userId: body.userId ?? null,
|
||
});
|
||
|
||
return {
|
||
items: parseResult.items.map((item) => ({
|
||
originalName: item.originalName,
|
||
skuName: item.skuName || item.originalName,
|
||
skuCode: item.skuCode,
|
||
quantity: item.quantity,
|
||
unit: item.unit,
|
||
processingMethod: item.processingMethod || '',
|
||
remark: item.remark || '',
|
||
categoryCode: item.categoryCode || '',
|
||
categoryName: item.categoryName || '',
|
||
suggestedCategoryName: item.suggestedCategoryName || '',
|
||
matchLayer: item.matchLayer,
|
||
confidence: item.confidence,
|
||
})),
|
||
confidence: parseResult.items.length
|
||
? parseResult.items.reduce((sum, item) => sum + item.confidence, 0) / parseResult.items.length
|
||
: 0,
|
||
demoMode: parseResult.demoMode,
|
||
message: parseResult.message,
|
||
};
|
||
}
|
||
|
||
export async function parseVoiceOrder(body: {
|
||
text?: string;
|
||
voiceText?: string;
|
||
audioBase64?: string;
|
||
audioFormat?: string;
|
||
customerCode?: string;
|
||
branchCode?: string | null;
|
||
includeParseCategory?: boolean;
|
||
}) {
|
||
const audioBase64 = String(body.audioBase64 || '').trim();
|
||
const text = body.text || body.voiceText;
|
||
if (!text && !audioBase64) throw new Error('缺少语音文本或音频');
|
||
const result = await parseOrderThreeLayer({
|
||
text: audioBase64 ? undefined : text,
|
||
audioBase64: audioBase64 || undefined,
|
||
audioFormat: body.audioFormat,
|
||
customerCode: body.customerCode || 'self',
|
||
branchCode: body.branchCode,
|
||
includeParseCategory: body.includeParseCategory === true,
|
||
});
|
||
return {
|
||
text,
|
||
items: result.items.map((item) => ({
|
||
originalName: item.originalName,
|
||
skuName: item.skuName || item.originalName,
|
||
skuCode: item.skuCode,
|
||
quantity: item.quantity,
|
||
unit: item.unit,
|
||
processingMethod: item.processingMethod || '',
|
||
remark: item.remark || '',
|
||
categoryCode: item.categoryCode || '',
|
||
categoryName: item.categoryName || '',
|
||
suggestedCategoryName: item.suggestedCategoryName || '',
|
||
matchLayer: item.matchLayer,
|
||
confidence: item.confidence,
|
||
})),
|
||
confidence: result.items.length
|
||
? result.items.reduce((sum, item) => sum + item.confidence, 0) / result.items.length
|
||
: 0,
|
||
demoMode: result.demoMode,
|
||
message: result.message,
|
||
};
|
||
}
|
||
|
||
export async function transcribeVoiceAudio(body: {
|
||
audioBase64?: string;
|
||
audioFormat?: string;
|
||
branchCode?: string | null;
|
||
}): Promise<{ text: string; durationMs?: number }> {
|
||
if (!body.audioBase64) {
|
||
throw new Error('缺少音频数据');
|
||
}
|
||
const format = (body.audioFormat || 'ogg') as AudioFormat;
|
||
// branchCode 此前被忽略,导致兜底/分公司 LLM 配置取不到正确租户
|
||
return transcribeAudioBase64(body.audioBase64, format, { branchCode: body.branchCode });
|
||
}
|
||
|
||
export async function learnAlias(body: {
|
||
customerCode?: string;
|
||
items?: Array<{ originalName: string; skuCode: string; skuName: string; matchLayer?: number | null }>;
|
||
}) {
|
||
const { customerCode, items = [] } = body;
|
||
if (!customerCode || !items.length) {
|
||
return { learned: 0 };
|
||
}
|
||
|
||
let learned = 0;
|
||
for (const item of items) {
|
||
if (!item.skuCode || !item.originalName) continue;
|
||
await pool.query(
|
||
`INSERT INTO customer_sku_aliases (customer_code, alias_name, sku_code, is_primary, confidence_score, usage_count, status)
|
||
VALUES ($1, $2, $3, false, 0.9, 1, 1)
|
||
ON CONFLICT (customer_code, alias_name) DO NOTHING`,
|
||
[customerCode, item.originalName, item.skuCode]
|
||
);
|
||
learned += 1;
|
||
}
|
||
return { learned };
|
||
}
|
||
|
||
export async function syncCustomerMappings(body: {
|
||
customerCode?: string;
|
||
branchCode?: string | null;
|
||
updateProductCatalog?: boolean;
|
||
items?: Array<{
|
||
originalName: string;
|
||
skuName: string;
|
||
skuCode?: string;
|
||
unit?: string;
|
||
categoryCode?: string;
|
||
processingMethod?: string;
|
||
processingOwner?: string;
|
||
inCustomerLibrary?: boolean;
|
||
categoryManuallySet?: boolean;
|
||
}>;
|
||
}) {
|
||
const { customerCode, items = [] } = body;
|
||
if (!customerCode || !items.length) {
|
||
return { synced: 0, skipped: items.length };
|
||
}
|
||
|
||
let branchCode = String(body.branchCode || '').trim();
|
||
if (!branchCode) {
|
||
const customerBranch = await pool.query(
|
||
`SELECT branch_code FROM customers WHERE customer_code = $1 LIMIT 1`,
|
||
[customerCode]
|
||
);
|
||
branchCode = String(customerBranch.rows[0]?.branch_code || '').trim();
|
||
}
|
||
|
||
let synced = 0;
|
||
let skipped = 0;
|
||
|
||
for (const item of items) {
|
||
const originalName = (item.originalName || item.skuName || '').trim();
|
||
const categoryCode = item.categoryCode;
|
||
const processingMethod = String(item.processingMethod || '').trim() || null;
|
||
const processingOwner = normalizeProcessingOwner(processingMethod, item.processingOwner);
|
||
if (!originalName || !categoryCode) {
|
||
skipped += 1;
|
||
continue;
|
||
}
|
||
|
||
let skuCode = item.skuCode;
|
||
if (!skuCode) {
|
||
const exactSku = branchCode
|
||
? await pool.query(
|
||
`SELECT sku_code FROM skus WHERE sku_name = $1 AND status = 1 AND branch_code = $2 LIMIT 1`,
|
||
[originalName, branchCode]
|
||
)
|
||
: await pool.query(
|
||
`SELECT sku_code FROM skus WHERE sku_name = $1 AND status = 1 LIMIT 1`,
|
||
[originalName]
|
||
);
|
||
skuCode = (exactSku.rows[0]?.sku_code as string | undefined) || undefined;
|
||
if (!skuCode) {
|
||
const fuzzySku = branchCode
|
||
? await pool.query(
|
||
`SELECT sku_code FROM skus WHERE sku_name ILIKE $1 AND status = 1 AND branch_code = $2 LIMIT 1`,
|
||
[`%${originalName}%`, branchCode]
|
||
)
|
||
: await pool.query(
|
||
`SELECT sku_code FROM skus WHERE sku_name ILIKE $1 AND status = 1 LIMIT 1`,
|
||
[`%${originalName}%`]
|
||
);
|
||
skuCode = (fuzzySku.rows[0]?.sku_code as string | undefined) || undefined;
|
||
}
|
||
}
|
||
|
||
if (skuCode) {
|
||
await pool.query(
|
||
`INSERT INTO customer_skus (
|
||
customer_code, sku_code, customer_sku_name, customer_unit, category_code,
|
||
processing_method, processing_owner, usage_count, last_order_at, branch_code
|
||
) VALUES ($1, $2, $3, $4, $5, $6, $7, 1, NOW(), NULLIF($8, ''))
|
||
ON CONFLICT (customer_code, sku_code) DO UPDATE SET
|
||
-- Keep the first/explicit customer display name stable. New wording
|
||
-- is recorded below as an alias instead of replacing the main name.
|
||
customer_sku_name = COALESCE(NULLIF(customer_skus.customer_sku_name, ''), EXCLUDED.customer_sku_name),
|
||
customer_unit = EXCLUDED.customer_unit,
|
||
category_code = EXCLUDED.category_code,
|
||
processing_method = EXCLUDED.processing_method,
|
||
processing_owner = EXCLUDED.processing_owner,
|
||
usage_count = customer_skus.usage_count + 1,
|
||
last_order_at = NOW(),
|
||
branch_code = COALESCE(NULLIF(customer_skus.branch_code, ''), EXCLUDED.branch_code),
|
||
updated_at = NOW()`,
|
||
[
|
||
customerCode,
|
||
skuCode,
|
||
originalName,
|
||
item.unit || '个',
|
||
categoryCode,
|
||
processingMethod,
|
||
processingOwner,
|
||
branchCode || null,
|
||
]
|
||
);
|
||
|
||
if (body.updateProductCatalog === true || item.categoryManuallySet) {
|
||
await syncProductCategoryToMasterData(
|
||
String(skuCode),
|
||
String(categoryCode),
|
||
branchCode || null
|
||
).catch(() => undefined);
|
||
}
|
||
synced += 1;
|
||
|
||
await pool.query(
|
||
`INSERT INTO customer_sku_aliases (
|
||
customer_code, alias_name, sku_code, is_primary, confidence_score, usage_count, status
|
||
) VALUES ($1, $2, $3, false, 0.95, 1, 1)
|
||
ON CONFLICT (customer_code, alias_name) DO UPDATE SET
|
||
sku_code = EXCLUDED.sku_code,
|
||
usage_count = customer_sku_aliases.usage_count + 1,
|
||
updated_at = NOW()`,
|
||
[customerCode, originalName, skuCode]
|
||
);
|
||
continue;
|
||
}
|
||
|
||
if (branchCode) {
|
||
const existingRule = await pool.query(
|
||
`SELECT id, category_code FROM smart_classification_rules
|
||
WHERE keyword = $1 AND is_active = true AND branch_code = $2
|
||
LIMIT 1`,
|
||
[originalName, branchCode]
|
||
);
|
||
if (existingRule.rowCount) {
|
||
if (existingRule.rows[0].category_code !== categoryCode) {
|
||
await pool.query(
|
||
`UPDATE smart_classification_rules
|
||
SET category_code = $2, updated_at = NOW()
|
||
WHERE keyword = $1 AND is_active = true AND branch_code = $3`,
|
||
[originalName, categoryCode, branchCode]
|
||
);
|
||
}
|
||
synced += 1;
|
||
continue;
|
||
}
|
||
|
||
await pool.query(
|
||
`INSERT INTO smart_classification_rules (keyword, category_code, match_type, priority, is_active, branch_code)
|
||
VALUES ($1, $2, 'contains', 60, true, $3)`,
|
||
[originalName, categoryCode, branchCode]
|
||
);
|
||
synced += 1;
|
||
continue;
|
||
}
|
||
|
||
skipped += 1;
|
||
}
|
||
|
||
return { synced, skipped };
|
||
}
|
||
|
||
/**
|
||
* 消歧候选选中:录单员从候选列表中选择一个 SKU,自动写入 customer_sku_aliases。
|
||
* 下次同一客户再说同样名称时,Layer 1 精确命中,不再需要消歧。
|
||
*/
|
||
export async function resolveCandidateAlias(params: {
|
||
customerCode: string;
|
||
originalName: string;
|
||
skuCode: string;
|
||
skuName: string;
|
||
}): Promise<void> {
|
||
const { customerCode, originalName, skuCode, skuName } = params;
|
||
const aliasName = String(originalName || '').trim();
|
||
if (!customerCode || !aliasName || !skuCode) return;
|
||
|
||
// 已有相同映射则跳过
|
||
const existing = await pool.query(
|
||
`SELECT 1 FROM customer_sku_aliases
|
||
WHERE customer_code = $1 AND alias_name = $2 AND sku_code = $3 AND status = 1
|
||
LIMIT 1`,
|
||
[customerCode, aliasName, skuCode]
|
||
);
|
||
if (existing.rowCount) {
|
||
// 增加 usage_count
|
||
await pool.query(
|
||
`UPDATE customer_sku_aliases SET usage_count = usage_count + 1
|
||
WHERE customer_code = $1 AND alias_name = $2 AND sku_code = $3`,
|
||
[customerCode, aliasName, skuCode]
|
||
);
|
||
return;
|
||
}
|
||
|
||
// 新建别名映射
|
||
await pool.query(
|
||
`INSERT INTO customer_sku_aliases (customer_code, alias_name, sku_code, is_primary, confidence_score, usage_count, status)
|
||
VALUES ($1, $2, $3, false, 0.95, 1, 1)
|
||
ON CONFLICT (customer_code, alias_name, sku_code)
|
||
DO UPDATE SET usage_count = customer_sku_aliases.usage_count + 1,
|
||
status = 1`,
|
||
[customerCode, aliasName, skuCode]
|
||
);
|
||
|
||
// 同步到 customer_skus 库(确保 Layer 0 也能命中)
|
||
await pool.query(
|
||
`INSERT INTO customer_skus (customer_code, sku_code, customer_sku_name, customer_unit, usage_count)
|
||
VALUES ($1, $2, $3, (SELECT base_unit FROM skus WHERE sku_code = $2 LIMIT 1), 1)
|
||
ON CONFLICT (customer_code, sku_code)
|
||
DO UPDATE SET usage_count = customer_skus.usage_count + 1`,
|
||
[customerCode, skuCode, skuName]
|
||
);
|
||
} |