feat(商品): 商品名自动推荐税码分类与规格
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

复用一个已有推荐接口:服务端仍只把官方库检索的 top 15 税码候选与本分公司分类预筛 top 20 交给模型,一次调用返回税码/分类/规格;分类与税码都按序号回查,AI 造不出编码。前端只在字段为空且用户未手改时回填,防覆盖防循环;无 LLM 时降级为原规则引擎。
This commit is contained in:
雨天
2026-10-22 12:27:48 +08:00
parent a9caadc9ac
commit 7c514f48b3
12 changed files with 667 additions and 100 deletions
@@ -62,7 +62,7 @@
| AI-09 | 客户映射同步 | `/api/functions/sync-customer-mappings` | `server/src/services/orderParseService.ts` | 待补 | 待补 | 待补 | 待补 | 待补 |
| AI-10 | 行情 AI 自动配置 | `POST /market/auto-configure` | `server/src/services/marketAiAutoConfigureService.ts` | 待补 | 待补 | 待补 | 待补 | 待补 |
| AI-11 | 行情外部绑定 AI 识别 | `POST /market/external-bindings/auto-bind` | `server/src/services/marketAiExternalBindingService.ts` | 待补 | 待补 | 待补 | 待补 | 待补 |
| AI-12 | 税收分类编码 AI 推荐 | 待确认(无路由引用) | `server/src/services/taxCodeAiService.ts` | 待补 | 待补 | 待补 | 待补 | 待补 |
| AI-12 | 税收分类编码 AI 推荐 | `GET /catalog/tax-code/suggest`(`SkuManagement` 商品名防抖触发) | `server/src/services/taxCodeAiService.ts` | 待补 | 待补(分母 = 商品名触发的推荐调用次数) | 待补 + 负责人 | 未配置 LLM / 模型失败 ⇒ 只回规则引擎与官方库检索结果,税码非必填;AI 只能从本地候选里挑序号,服务端回查校验 | 待补(`llmService.callWithText` 出口暂未记录 usage) |
| AI-13 | 成本归因 AI 分析 | `financeRoutes` 成本根因入口 | `server/src/services/costAiService.ts` | 待补 | 待补 | 待补 | 待补 | 待补 |
| AI-14 | 称重终端图像识别 | `/api/inventory/...`(称台链路) | `server/src/services/weighStationService.ts` | 待补 | 待补 | 待补 | 待补 | 待补 |
| AI-15 | 免入库/直送 AI 解析 | `server/src/services/v9CompletionService.ts` 调用点 | `server/src/services/prepackagedInspectionService.ts` | 待补 | 待补 | 待补 | 待补 | 待补 |
@@ -81,6 +81,7 @@
| AI-28 | 多商品入库识别(送货单 / 实物堆,一次多行 → 人工审核 → 批量入库;含**单位/分类** AI 预填) | `POST /mobile/inventory/recognize-lines` | `server/src/services/stockInboundBatchService.ts` | 待补(品名命中率:人工确认后的行品名与识别原值一致率;分类命中率:人工保留的 AI 分类占已预填行比例) | 待补(分母 = 本流程实际发生的识别次数以及识别出的商品**行数**) | 待补 + 负责人 | 识别失败或未配置多模态 → 返回空行,界面转全手工(手动加行,品名/数量/成本价/分类均可手填;分类可在行内选择器新建);AI 分类只从已有分类列表选、服务端按列表校验,自造编码丢弃 | **不存在**(解析出口暂未记录 usage) |
| AI-29 | 入库批次报告 OCR 解析(仓库上传图/PDF → 商品名/生产日期 → 匹配入库批次;独立于 quality_reports) | `POST /api/workflow/inventory/batch-reports` | `server/src/services/inventoryBatchReportService.ts` | 待补(品名/生产日期命中率:人工确认的入库批次与报告识别原值一致率) | 待补(分母 = 仓库实际上传的批次报告份数 × 每份识别出的商品行数;负责人:待定) | 待补 + 负责人 | 识别失败或未配置多模态 → 只存文件、状态「待确认」,界面转人工手选入库批次(可多选),不阻断;匹配仅给建议,未经人工确认不落关联行 | **不存在**(复用 `quality.report.meta` 解析出口,暂未记录 usage) |
| AI-30 | 分拣 · 拍包装照读生产日期(商品名不必识别,只读生产日期 → 匹配出库批次) | `POST /mobile/picking/recognize-production-date` | `server/src/services/pickingBatchDateService.ts` | 待补(生产日期命中率:AI 读到的日期与所选批次 `production_date` 一致率) | 待补(分母 = 分拣环节实际拍照识别次数) | 待补 + 负责人 | 未配置多模态 / 识别失败 → 返回 `recognized:false`,照旧在同一个批次弹窗手动挑批次,不阻断分拣 | **不存在**(解析出口暂未记录 usage) |
| AI-31 | 商品新增:按商品名一次生成税码 / 分类 / 规格建议(扩展 AI-12 同一出口,不新增调用链路) | `GET /catalog/tax-code/suggest?need_category=1&need_spec=1` | `server/src/services/taxCodeLookupService.ts` | 待补(人工保留率:AI 预填的分类/规格未被改动的行占比;税码沿用 AI-12 口径) | 待补(分母 = 带 `need_category` 或 `need_spec` 的推荐调用次数) | 待补 + 负责人 | 未配置 LLM 或模型失败 ⇒ 只回规则引擎税码,分类/规格不回填;AI 分类只能从本分公司已启用分类候选里选序号、越界丢弃;界面只在字段为空时预填且可改,不阻断保存 | 待补(复用 `llmService.callWithText` 出口,暂未记录 usage) |
> **AI-19 是这张表里唯一填得出来的行** —— 而它是 R5 逼出来的(原文写「比对人工录单准确率」,无阈值、无法判 go/no-go)。
> 其余 18 行的"待补"就是本表要暴露的事实:**存量 AI 全部无门槛**。
@@ -0,0 +1,82 @@
# 商品新增:按商品名一次给出税码 / 分类 / 规格建议
- 日期:2026-10-22
- 开发者需求:「输入了商品名后 调用 ai 解析返回这个商品该用哪一个税收编码 同时带上 AI 感觉的分类、规格 这些可以修改」;
并明确约束「**别把 `server/data/` 里的税收编码文件都丢上去**,应该是想一个轻便的方案」。
## 1. 改前事实
| # | 事实 |
|---|---|
| F1 | 商品名/分类/规格变化后已有 **500ms 防抖**调用 `GET /catalog/tax-code/suggest`(`SkuManagement.tsx`) |
| F2 | 官方库 `server/data/tax-catalog-entries.json`(`version` 2026-07-10,1820 条)**只在服务端建索引**;进模型的只有 `searchTaxCatalog()` 取出的 **top 15** 候选 |
| F3 | AI 只被要求回一个候选**序号**(`{"index":0,"confidence":..}`),服务端用 `getTaxCatalogEntryByCode` 回查校验,**AI 造不出码** |
| F4 | 分类候选从未传给模型;模型无法参与分类选择 |
| F5 | 前端拿到结果只用于税码,分类与规格仍需全手填 |
| F6 | 分公司分类清单可由 `fetchCategoryRows(branchCode)` 取得(服务端) |
## 2. 方案(轻量:不加接口、不加调用次数上限外的开销)
**一次 LLM 调用同时产出三样**,仍走原接口:
1. **税码**:候选池不变(本地官方库检索 top 15),仍只让模型回序号,服务端回查校验。
2. **分类**:服务端取本分公司分类,按与商品名的字符重合度**本地预筛 top 20**(`loadCategoryCandidates`),
模型只回 `category_index`;越界/不存在一律丢弃 ⇒ **AI 不能自造分类编码**。
3. **规格**:模型输出一个 ≤20 字字符串(如 `500g/袋`),纯建议。
请求开关(由前端按字段是否为空决定,避免白花钱):
- `need_category=1`:仅当「所属分类」为空时请求;
- `need_spec=1`:仅当「规格」为空时请求;
- 两个都不传时,服务端行为与改前完全一致(AI 仍只在税码兜底阶段被调用)。
前端回填规则:
- **只填空字段**,用户已填的一律不覆盖;
- 用户**手动改过**分类/规格(`categoryTouchedRef` / `specTouchedRef`)后,即使又清空也不再自动回填;
- **AI 自己填的**值(`aiFilledCategoryRef` / `aiFilledSpecRef`)在用户未动的前提下,可被后续更准的建议更新
(避免商品名还没输完就定型);
- 分类必须真实存在于本分公司 `categoryOptions` 才回填,并与手选分类走同一套联动
(未手改税率则重算、安全线归 0、清分类校验错误);
- 回填后置 `aiFillSkipRef` **跳过下一轮自动推荐**,避免「AI 填规格 → 规格变化又触发 AI」的循环;
- 回填结果全部可手改;税码上一轮已改为非必填,不会阻塞保存。
## 3. 成本与降级
| 项 | 说明 |
|---|---|
| 提示词体积 | top 15 税码候选 + top 20 分类候选 ≈ 800~1000 字符;**官方库 1820 条永不出服务端** |
| 调用次数 | 不新增接口;分类/规格已填时不额外调用;需要时与税码推荐共用同一次调用 |
| 无 LLM 配置 | `hasArkRuntimeConfig` 为 false ⇒ 只回规则引擎税码,分类/规格不回填 |
| 模型失败/超时 | `catch` 后回空,不影响保存;分类/规格留空由用户手填 |
| 低置信度 | `<55` 整体不采用 |
## 4. 非目标
- 不改官方库文件、不加数据库列、不做迁移;
- 不改移动端/小程序表单;
- 不新增任何界面小字(沿用现有推荐卡片);
- 不恢复「税码必须确认才能保存」。
## 5. 改动面
| 侧 | 文件 |
|---|---|
| 后端 | `services/taxCodeAiService.ts`(分类候选 + 规格输出、序号校验)、`services/taxCodeLookupService.ts`(分类候选预筛、一次 AI 复用、结果透传)、`routes/catalog.ts`(`need_category` / `need_spec`)、`prompts/defaults.ts`(提示词升级) |
| 前端 | `utils/catalogApi.ts`(参数与类型)、`pages/products/SkuManagement.tsx`(回填 + 防循环) |
| 测试 | `server/tests/taxCodeAiSuggestion.test.ts`、`src/utils/catalogApi.taxSuggest.test.ts` |
## 6. 验收
1. 新增商品、分类与规格都空时输入商品名(如「土豆」)⇒ 约 0.5s 后:
- 分类被预填为一个真实存在的分类,规格出现建议值;
- 两者都能直接改;推荐卡片仍显示税码建议。
2. 已手选分类、已填规格后再改商品名 ⇒ 已填内容**不被覆盖**(请求也不带 `need_*`)。
3. 未配置 LLM ⇒ 分类/规格不预填,其余功能不受影响。
4. `npm run typecheck`、`cd server && npx tsc --noEmit` 通过;
`cd server && npx vitest run tests/taxCodeAiSuggestion.test.ts`、`npx vitest run src/utils/catalogApi.taxSuggest.test.ts` 全绿。
## 7. 部署注意(未执行)
`catalog.tax_code.suggest` 的提示词在 `prompts/defaults.ts` 已升级。线上若已有该 key 的**已发布版本**,
按平台冻结规则必须走发布流程升 `version`;`version = 1` 的提示词每次部署会被代码默认值覆盖。
+1
View File
@@ -155,6 +155,7 @@ AI 提示词清理已停用条目(7 条归档不删、清单过滤 archived、
**商品表单:标题改「税收编码」+ 去官方库搜索框 + 去输入占位**:开发者附截图「税收分类编码 变为税收编码修改文字 然后下方的手上实时官方库的那个输入框去掉」、「税收编码里面的默认文字去掉」——`products.form.taxCode` 文案改为「税收编码 / Tax code / Kode pajak」;税码输入下方那块「搜索实时官方库(货物和劳务名称 / 简称)」输入框、加载行、结果列表整体删除,并清理对应 state/防抖 effect/`searchTaxCatalogApi` 引用与弹窗重置调用;税码输入框的占位「规则引擎 + 官方库 + AI 分层匹配」也去掉。税码推荐卡片、候选、确认采用与税率联动未动,见 [20261022-商品表单税收编码标题与去官方库搜索框.md](./20261022-商品表单税收编码标题与去官方库搜索框.md)。**追加**:开发者「当前这块输入完毕商品名出现的推荐分类?首先改为推荐编码」——推荐卡片标题 `products.form.taxRecommend` 改为「推荐编码 / Suggested code / Kode disarankan」,卡片正文与推荐逻辑未动;该编码来自随代码发布的官方库(`server/data/tax-catalog-entries.json`,1820 条 / 19 位),同商品名同库版本下确定,AI 只能从候选中挑、不能造码。
**商品新增/编辑:去除计价单位字段**:开发者附截图「我们不需要计价单位 给我去除」——弹窗中「计价单位」整块 UI(label + `SearchableSelect`)已删,字段顺序变为 规格 → 品牌 → 区域编号;随之失效的 4 条三语文案键(`form.pricingUnit*`)同步删除。⚠️ **后端列保留**:`formData.pricing_unit` 与提交参数未删,新商品仍默认等于单位、编辑既有商品沿用库中值,备货价归一(`prepPriceNormalizeService`)不受影响,见 [20261022-商品表单去除计价单位字段.md](./20261022-商品表单去除计价单位字段.md)。
**商品新增:税收编码改为非必填**:开发者「税收编码别强制填写」——删掉 `handleSubmit` 开头那段「推荐未确认就不让保存」的拦截(新增商品时 `needs_confirmation && !taxCodeConfirmed` ⇒ toast 并 return),并删除随之失效的 `products.toast.taxConfirmNeeded` 三语文案。推荐卡片、「待确认」角标、「确认采用」按钮、其它候选均保留为**可选**;高置信度仍自动填码,后端本来就允许 `tax_code` 为空(无迁移),见 [20261022-商品税收编码改为非必填.md](./20261022-商品税收编码改为非必填.md)。
**商品新增:按商品名一次给出税码 / 分类 / 规格建议**:开发者「输入商品名后调 AI 解析返回该用哪个税收编码,同时带上 AI 感觉的分类、规格,这些可以修改」,并约束「别把 `server/data/` 里的税收编码文件都丢上去」——沿用原接口 `GET /catalog/tax-code/suggest`,仍然只把官方库检索的 **top 15** 候选(本地索引,1820 条文件永不出服务端)与本分公司分类**本地预筛 top 20** 给模型,一次调用返回 `index` / `category_index` / `spec`;服务端按序号回查校验,AI **造不出税码与分类编码**。前端仅在字段为空且用户未手改时回填分类(复用税率联动)与规格,并用 `aiFillSkipRef` 跳过下一轮避免循环;`need_category` / `need_spec` 两个开关控制是否额外请 AI,不传时行为与改前一致,无 LLM 时只回规则引擎税码。⚠️ 提示词已改,线上已发布版本需走发布流程升 `version`,见 [20261022-商品新增AI推荐税码分类规格.md](./20261022-商品新增AI推荐税码分类规格.md)。
## 全量对齐与改造方案(2026-09-28)
+7 -3
View File
@@ -94,10 +94,14 @@ index 为候选序号(从 0 开始);都不合适则 index=-1、confidence=
name: '商品主数据 · 税码 AI 建议',
modality: 'text',
wired: true,
systemTemplate: `你是中国增值税税收分类编码助手。根据商品信息,从候选列表中选择最合适的一项。
systemTemplate: `你是中国生鲜商品主数据助手。根据商品信息完成三件事:
1) 从候选税收分类中选出最合适的一项;
2) 从候选商品分类中选出最合适的一项;
3) 给出一个简短规格(如 500g/袋)。
只能输出 JSON,格式:
{"index":0,"confidence":0-100,"rationale":"简短理由"}
index 为候选序号(从 0 开始);若都不合适则 index 为 -1,confidence 为 0。`,
{"index":0,"category_index":0,"spec":"500g/袋","confidence":0-100,"rationale":"简短理由"}
index / category_index 为对应候选序号(从 0 开始);没有该项候选或都不合适时填 -1。
spec 最长 20 字,无法判断就填空字符串。`,
variablesSchema: [],
},
{
+3
View File
@@ -24,6 +24,7 @@ router.get('/tax-code/suggest', authMiddleware, async (req: AuthRequest, res: Re
const operatingBranch = readOperatingBranchCode(req);
const branchCode = getEffectiveBranchCode(ctx, operatingBranch);
const useAi = String(req.query.use_ai || 'true').toLowerCase() !== 'false';
const flagOn = (value: unknown) => ['1', 'true'].includes(String(value ?? '').toLowerCase());
const result = await resolveTaxCodeConfirmation({
skuName: String(req.query.sku_name || ''),
@@ -31,6 +32,8 @@ router.get('/tax-code/suggest', authMiddleware, async (req: AuthRequest, res: Re
spec: String(req.query.spec || ''),
branchCode,
useAi,
needCategory: flagOn(req.query.need_category),
needSpec: flagOn(req.query.need_spec),
});
return res.json({ data: result, error: null });
} catch (error: any) {
+70 -56
View File
@@ -3,6 +3,11 @@ import type { TaxCatalogEntry } from './taxCatalogService';
import { getTaxCatalogEntryByCode } from './taxCatalogService';
import { resolvePrompt } from './promptRegistryService';
export interface TaxCategoryCandidate {
category_code: string;
category_name: string;
}
export interface TaxCodeAiSuggestion {
matched: boolean;
tax_code: string | null;
@@ -10,6 +15,25 @@ export interface TaxCodeAiSuggestion {
short_name: string | null;
confidence: number;
rationale: string | null;
/** AI 从本分公司分类候选中选出的分类;未请求或未命中为 null */
category_code: string | null;
category_name: string | null;
/** AI 给出的规格建议(界面可改);未请求或未给出为 null */
suggested_spec: string | null;
}
function emptyAiSuggestion(rationale: string | null = null): TaxCodeAiSuggestion {
return {
matched: false,
tax_code: null,
tax_name: null,
short_name: null,
confidence: 0,
rationale,
category_code: null,
category_name: null,
suggested_spec: null,
};
}
function parseJson(text: string): Record<string, unknown> | null {
@@ -24,7 +48,7 @@ function parseJson(text: string): Record<string, unknown> | null {
}
}
/** AI 从官方库候选中挑选税收分类编码 */
/** AI 从官方库 / 分类候选中挑选税收分类编码,并给出分类与规格建议 */
export async function suggestTaxCodeWithAi(
input: {
skuName: string;
@@ -32,17 +56,16 @@ export async function suggestTaxCodeWithAi(
spec?: string;
},
candidates: Array<TaxCatalogEntry & { score?: number }>,
options?: { branchCode?: string | null }
options?: { branchCode?: string | null; categories?: TaxCategoryCandidate[] }
): Promise<TaxCodeAiSuggestion> {
if (!(await hasArkRuntimeConfig({ branchCode: options?.branchCode })) || !input.skuName.trim() || !candidates.length) {
return {
matched: false,
tax_code: null,
tax_name: null,
short_name: null,
confidence: 0,
rationale: null,
};
const categories = options?.categories || [];
const wantTax = candidates.length > 0;
if (
!(await hasArkRuntimeConfig({ branchCode: options?.branchCode })) ||
!input.skuName.trim() ||
(!wantTax && !categories.length)
) {
return emptyAiSuggestion();
}
const candidateLines = candidates
@@ -52,14 +75,19 @@ export async function suggestTaxCodeWithAi(
`${index}. [${item.tax_code}] ${item.name}${item.short_name && item.short_name !== item.name ? `(${item.short_name})` : ''}`
)
.join('\n');
const categoryLines = categories
.slice(0, 20)
.map((item, index) => `${index}. [${item.category_code}] ${item.category_name}`)
.join('\n');
const userText = [
`商品名称:${input.skuName.trim()}`,
input.categoryName ? `商品分类:${input.categoryName.trim()}` : '',
input.spec ? `规格:${input.spec.trim()}` : '',
'',
'候选税收分类(只能从中选择):',
candidateLines,
wantTax ? '\n候选税收分类(只能从中选择):' : '',
wantTax ? candidateLines : '',
categories.length ? '\n候选商品分类(只能从中选择):' : '',
categories.length ? categoryLines : '',
]
.filter(Boolean)
.join('\n');
@@ -68,60 +96,46 @@ export async function suggestTaxCodeWithAi(
const prompt = await resolvePrompt('catalog.tax_code.suggest', { branchCode: options?.branchCode });
const raw = await callArkWithText(prompt.systemPrompt, userText, { branchCode: options?.branchCode });
if (!raw) {
return {
matched: false,
tax_code: null,
tax_name: null,
short_name: null,
confidence: 0,
rationale: null,
};
return emptyAiSuggestion();
}
const parsed = parseJson(raw);
const index = Number(parsed?.index);
const confidence = Math.max(0, Math.min(100, Number(parsed?.confidence) || 0));
const rationale = String(parsed?.rationale || '').trim() || null;
if (!Number.isInteger(index) || index < 0 || index >= candidates.length || confidence < 55) {
return {
matched: false,
tax_code: null,
tax_name: null,
short_name: null,
confidence: 0,
rationale,
};
const taxIndex = Number(parsed?.index);
const categoryIndex = Number(parsed?.category_index);
const rawSpec = typeof parsed?.spec === 'string' ? parsed.spec.trim().slice(0, 40) : '';
const suggestedSpec = rawSpec || null;
if (confidence < 55) {
return emptyAiSuggestion(rationale);
}
const picked = candidates[index];
const validated = getTaxCatalogEntryByCode(picked.tax_code);
if (!validated) {
return {
matched: false,
tax_code: null,
tax_name: null,
short_name: null,
confidence: 0,
rationale: 'AI 选择未通过官方库校验',
};
const picked = wantTax && Number.isInteger(taxIndex) && taxIndex >= 0 && taxIndex < candidates.length
? candidates[taxIndex]
: null;
const validated = picked ? getTaxCatalogEntryByCode(picked.tax_code) : null;
const category =
categories.length && Number.isInteger(categoryIndex) && categoryIndex >= 0 && categoryIndex < categories.length
? categories[categoryIndex]
: null;
if (!validated && !category && !suggestedSpec) {
return emptyAiSuggestion(rationale);
}
return {
matched: true,
tax_code: validated.tax_code,
tax_name: validated.name,
short_name: validated.short_name,
matched: Boolean(validated),
tax_code: validated?.tax_code ?? null,
tax_name: validated?.name ?? null,
short_name: validated?.short_name ?? null,
confidence,
rationale,
rationale: picked && !validated ? 'AI 选择未通过官方库校验' : rationale,
category_code: category?.category_code ?? null,
category_name: category?.category_name ?? null,
suggested_spec: suggestedSpec,
};
} catch {
return {
matched: false,
tax_code: null,
tax_name: null,
short_name: null,
confidence: 0,
rationale: null,
};
return emptyAiSuggestion();
}
}
+150 -38
View File
@@ -13,7 +13,8 @@ import {
type TaxCatalogEntry,
} from './taxCatalogService';
import { lookupOfficialTaxCode } from './providers/taxCodeOfficialAdapter';
import { suggestTaxCodeWithAi } from './taxCodeAiService';
import { suggestTaxCodeWithAi, type TaxCategoryCandidate } from './taxCodeAiService';
import { fetchCategoryRows } from './categoryCatalogService';
export type TaxCodeSource =
| 'rule_exact'
@@ -43,6 +44,11 @@ export type TaxCodeSuggestion = {
catalog_version: string | null;
needs_confirmation: boolean;
candidates: TaxCodeCandidate[];
/** AI 建议的商品分类(前端需校验该编码存在于本分公司分类) */
category_code?: string | null;
category_name?: string | null;
/** AI 建议的规格(界面可直接修改) */
suggested_spec?: string | null;
};
function toCandidate(
@@ -101,6 +107,55 @@ function needsConfirmation(source: TaxCodeSource, confidence: number) {
return confidence < 85;
}
function scoreCategoryName(queryNorm: string, nameNorm: string) {
if (!nameNorm) return 0;
if (nameNorm === queryNorm) return 100;
if (nameNorm.includes(queryNorm) || queryNorm.includes(nameNorm)) {
const ratio = Math.min(queryNorm.length, nameNorm.length) / Math.max(queryNorm.length, nameNorm.length);
return 70 + Math.round(ratio * 20);
}
const queryChars = new Set(queryNorm.split(''));
let overlap = 0;
for (const ch of nameNorm) {
if (queryChars.has(ch)) overlap += 1;
}
return Math.round((overlap / Math.max(nameNorm.length, queryNorm.length)) * 55);
}
/**
* 只取本分公司分类里与商品名最相近的前 20 条给模型,避免把整棵分类树塞进提示词。
*/
async function loadCategoryCandidates(
branchCode: string | null | undefined,
query: string,
limit = 20
): Promise<TaxCategoryCandidate[]> {
const branch = String(branchCode || '').trim();
if (!branch) return [];
let rows: Awaited<ReturnType<typeof fetchCategoryRows>>;
try {
rows = await fetchCategoryRows(branch);
} catch {
return [];
}
const enabled = rows
.filter((row) => Number(row.status) === 1)
.filter((row) => String(row.category_code || '').trim() && String(row.category_name || '').trim())
.map((row) => ({ category_code: row.category_code, category_name: row.category_name }));
if (!enabled.length) return [];
const q = normalizeTaxText(query);
if (!q) return enabled.slice(0, limit);
return enabled
.map((item) => ({ item, score: scoreCategoryName(q, normalizeTaxText(item.category_name)) }))
.sort((a, b) => b.score - a.score)
.slice(0, limit)
.map((entry) => entry.item);
}
function buildSuggestion(
entry: TaxCatalogEntry,
source: TaxCodeSource,
@@ -174,6 +229,10 @@ export async function resolveTaxCodeConfirmation(input: {
spec?: string | null;
branchCode?: string | null;
useAi?: boolean;
/** 分类为空时请求 AI 补一个分类建议 */
needCategory?: boolean;
/** 规格为空时请求 AI 补一个规格建议 */
needSpec?: boolean;
}): Promise<TaxCodeSuggestion> {
const skuName = String(input.skuName || '').trim();
const categoryName = String(input.categoryName || '').trim() || '(无分类)';
@@ -191,10 +250,49 @@ export async function resolveTaxCodeConfirmation(input: {
toCandidate(item, item.score, 'official_search', 'official_catalog_search')
);
const wantCategory = input.needCategory === true;
const wantSpec = input.needSpec === true;
const wantExtras = wantCategory || wantSpec;
const categoryCandidates = wantExtras
? await loadCategoryCandidates(
input.branchCode,
skuName || (categoryName === '(无分类)' ? '' : categoryName)
)
: [];
// 只要请求了分类/规格建议就提前调一次 AI;这个结果同时供后面的税码兜底复用,不会重复调用
const aiResult =
wantExtras && useAi && skuName && (catalogCandidates.length || categoryCandidates.length)
? await suggestTaxCodeWithAi(
{ skuName, categoryName, spec },
catalogCandidates.map((item) => ({
tax_code: item.tax_code,
name: item.tax_name,
short_name: item.short_name,
norm: '',
short_norm: '',
score: item.score,
})),
{ branchCode: input.branchCode, categories: categoryCandidates }
)
: null;
const aiExtras: {
category_code?: string | null;
category_name?: string | null;
suggested_spec?: string | null;
} = {
...(wantCategory
? { category_code: aiResult?.category_code ?? null, category_name: aiResult?.category_name ?? null }
: {}),
...(wantSpec ? { suggested_spec: aiResult?.suggested_spec ?? null } : {}),
};
const ruleResult = suggestTaxCodeByRules({ skuName, categoryName });
if (ruleResult.matched && ruleResult.source === 'rule_exact') {
return {
...ruleResult,
...aiExtras,
candidates: [
toCandidate(
{
@@ -230,13 +328,16 @@ export async function resolveTaxCodeConfirmation(input: {
norm: '',
short_norm: '',
} as TaxCatalogEntry);
return buildSuggestion(
entry,
'official_api',
official.confidence,
official.message || 'official_api',
catalogCandidates
);
return {
...buildSuggestion(
entry,
'official_api',
official.confidence,
official.message || 'official_api',
catalogCandidates
),
...aiExtras,
};
}
} catch {
// 官方接口不可用时继续走本地库与 AI
@@ -252,18 +353,22 @@ export async function resolveTaxCodeConfirmation(input: {
norm: '',
short_norm: '',
};
return buildSuggestion(
entry,
'official_search',
topCatalog.score,
'official_catalog_search',
catalogCandidates.slice(1)
);
return {
...buildSuggestion(
entry,
'official_search',
topCatalog.score,
'official_catalog_search',
catalogCandidates.slice(1)
),
...aiExtras,
};
}
if (ruleResult.matched && ruleResult.confidence >= 80) {
return {
...ruleResult,
...aiExtras,
candidates: [
toCandidate(
{
@@ -282,40 +387,46 @@ export async function resolveTaxCodeConfirmation(input: {
};
}
if (useAi && skuName && catalogCandidates.length) {
const aiResult = await suggestTaxCodeWithAi(
{ skuName, categoryName, spec },
catalogCandidates.map((item) => ({
tax_code: item.tax_code,
name: item.tax_name,
short_name: item.short_name,
norm: '',
short_norm: '',
score: item.score,
})),
{ branchCode: input.branchCode }
);
const taxAiResult =
aiResult ??
(useAi && skuName && catalogCandidates.length
? await suggestTaxCodeWithAi(
{ skuName, categoryName, spec },
catalogCandidates.map((item) => ({
tax_code: item.tax_code,
name: item.tax_name,
short_name: item.short_name,
norm: '',
short_norm: '',
score: item.score,
})),
{ branchCode: input.branchCode }
)
: null);
if (aiResult.matched && aiResult.tax_code) {
return buildSuggestion(
if (taxAiResult?.matched && taxAiResult.tax_code) {
return {
...buildSuggestion(
{
tax_code: aiResult.tax_code,
name: aiResult.tax_name || aiResult.tax_code,
short_name: aiResult.short_name || aiResult.tax_name || aiResult.tax_code,
tax_code: taxAiResult.tax_code,
name: taxAiResult.tax_name || taxAiResult.tax_code,
short_name: taxAiResult.short_name || taxAiResult.tax_name || taxAiResult.tax_code,
norm: '',
short_norm: '',
},
'ai',
aiResult.confidence,
aiResult.rationale || 'ai_pick',
taxAiResult.confidence,
taxAiResult.rationale || 'ai_pick',
catalogCandidates
);
}
),
...aiExtras,
};
}
if (ruleResult.matched) {
return {
...ruleResult,
...aiExtras,
candidates: [
toCandidate(
{
@@ -347,10 +458,11 @@ export async function resolveTaxCodeConfirmation(input: {
catalog_version: getTaxCatalogVersion(),
needs_confirmation: true,
candidates: catalogCandidates.slice(0, 8),
...aiExtras,
};
}
return emptySuggestion();
return { ...emptySuggestion(), ...aiExtras };
}
export { searchTaxCatalog, getTaxCatalogVersion };
+102
View File
@@ -0,0 +1,102 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
const callWithTextMock = vi.fn();
const hasRuntimeConfigMock = vi.fn();
const resolvePromptMock = vi.fn();
const getTaxCatalogEntryByCodeMock = vi.fn();
vi.mock('../src/services/llmService', () => ({
callWithText: (...args: unknown[]) => callWithTextMock(...args),
hasRuntimeConfig: (...args: unknown[]) => hasRuntimeConfigMock(...args),
}));
vi.mock('../src/services/promptRegistryService', () => ({
resolvePrompt: (...args: unknown[]) => resolvePromptMock(...args),
}));
vi.mock('../src/services/taxCatalogService', () => ({
getTaxCatalogEntryByCode: (...args: unknown[]) => getTaxCatalogEntryByCodeMock(...args),
}));
import { suggestTaxCodeWithAi } from '../src/services/taxCodeAiService';
const taxCandidates = [
{
tax_code: '1010112000000000000',
name: '蔬菜及食用菌',
short_name: '蔬菜及食用菌',
norm: '',
short_norm: '',
score: 90,
},
];
const categories = [
{ category_code: 'CAT_VEG', category_name: '蔬菜' },
{ category_code: 'CAT_DRY', category_name: '干货' },
];
function reply(json: Record<string, unknown>) {
callWithTextMock.mockResolvedValue(JSON.stringify(json));
}
describe('税收编码 AI:一次调用同时给税码 / 分类 / 规格', () => {
beforeEach(() => {
callWithTextMock.mockReset();
hasRuntimeConfigMock.mockReset().mockResolvedValue(true);
resolvePromptMock.mockReset().mockResolvedValue({ systemPrompt: 'sys' });
getTaxCatalogEntryByCodeMock.mockReset().mockImplementation((code: string) =>
code === taxCandidates[0].tax_code ? taxCandidates[0] : null
);
});
it('税码按候选序号命中,同时返回分类与规格', async () => {
reply({
index: 0,
category_index: 1,
spec: ' 500g/袋 ',
confidence: 80,
rationale: '按名称判断',
});
const result = await suggestTaxCodeWithAi({ skuName: '土豆' }, taxCandidates, { categories });
expect(result.matched).toBe(true);
expect(result.tax_code).toBe('1010112000000000000');
expect(result.category_code).toBe('CAT_DRY');
expect(result.category_name).toBe('干货');
expect(result.suggested_spec).toBe('500g/袋');
});
it('没有税码候选时也要调用 AI,至少能给出分类建议', async () => {
reply({ index: -1, category_index: 0, spec: '', confidence: 70 });
const result = await suggestTaxCodeWithAi({ skuName: '不知名野菜' }, [], { categories });
expect(callWithTextMock).toHaveBeenCalledTimes(1);
expect(result.matched).toBe(false);
expect(result.tax_code).toBeNull();
expect(result.category_code).toBe('CAT_VEG');
expect(result.suggested_spec).toBeNull();
});
it('分类序号越界时不采用(AI 不能造分类)', async () => {
reply({ index: 0, category_index: 9, spec: '1kg/箱', confidence: 80 });
const result = await suggestTaxCodeWithAi({ skuName: '土豆' }, taxCandidates, { categories });
expect(result.category_code).toBeNull();
expect(result.category_name).toBeNull();
expect(result.suggested_spec).toBe('1kg/箱');
});
it('置信度不足 55 时整体不采用', async () => {
reply({ index: 0, category_index: 0, spec: '1kg/箱', confidence: 40 });
const result = await suggestTaxCodeWithAi({ skuName: '土豆' }, taxCandidates, { categories });
expect(result.matched).toBe(false);
expect(result.category_code).toBeNull();
expect(result.suggested_spec).toBeNull();
});
});
+96
View File
@@ -0,0 +1,96 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
const suggestAiMock = vi.fn();
const fetchCategoryRowsMock = vi.fn();
const lookupOfficialMock = vi.fn();
vi.mock('../src/services/taxCodeAiService', () => ({
suggestTaxCodeWithAi: (...args: unknown[]) => suggestAiMock(...args),
}));
vi.mock('../src/services/categoryCatalogService', () => ({
fetchCategoryRows: (...args: unknown[]) => fetchCategoryRowsMock(...args),
}));
vi.mock('../src/services/providers/taxCodeOfficialAdapter', () => ({
lookupOfficialTaxCode: (...args: unknown[]) => lookupOfficialMock(...args),
}));
import { resolveTaxCodeConfirmation } from '../src/services/taxCodeLookupService';
const categoryRows = [
{
category_code: 'CAT_VEG',
category_name: '蔬菜',
parent_code: null,
level: 1,
sort_order: 1,
loss_threshold: null,
is_fresh: true,
status: 1,
},
{
category_code: 'CAT_DISABLED',
category_name: '停用分类',
parent_code: null,
level: 1,
sort_order: 2,
loss_threshold: null,
is_fresh: false,
status: 0,
},
];
beforeEach(() => {
suggestAiMock.mockReset().mockResolvedValue({
matched: false,
tax_code: null,
tax_name: null,
short_name: null,
confidence: 80,
rationale: 'test',
category_code: 'CAT_VEG',
category_name: '蔬菜',
suggested_spec: '500g/袋',
});
fetchCategoryRowsMock.mockReset().mockResolvedValue(categoryRows);
lookupOfficialMock.mockReset().mockResolvedValue({ matched: false });
});
/**
* 商品名一输入就要有「分类 + 规格」建议 ⇒ 即使规则引擎已精确命中税码,
* 只要请求了 need_category / need_spec,也必须真的调一次 AI;
* 不请求时保持原成本路径(规则命中就不调 AI)。
*/
describe('resolveTaxCodeConfirmation:分类/规格建议开关', () => {
it('请求分类/规格时,规则精确命中也会调 AI 并透传建议', async () => {
const result = await resolveTaxCodeConfirmation({
skuName: '蔬菜及食用菌',
branchCode: 'BR001',
needCategory: true,
needSpec: true,
});
expect(result.source).toBe('rule_exact');
expect(suggestAiMock).toHaveBeenCalledTimes(1);
const aiOptions = suggestAiMock.mock.calls[0][2] as {
categories: Array<{ category_code: string }>;
};
// 停用分类不参与推荐
expect(aiOptions.categories).toEqual([{ category_code: 'CAT_VEG', category_name: '蔬菜' }]);
expect(result.category_code).toBe('CAT_VEG');
expect(result.suggested_spec).toBe('500g/袋');
});
it('不请求时不额外调 AI,也不回填分类/规格', async () => {
const result = await resolveTaxCodeConfirmation({
skuName: '蔬菜及食用菌',
branchCode: 'BR001',
});
expect(result.source).toBe('rule_exact');
expect(suggestAiMock).not.toHaveBeenCalled();
expect(result.category_code).toBeUndefined();
expect(result.suggested_spec).toBeUndefined();
});
});
+92 -2
View File
@@ -365,6 +365,14 @@ export const SkuManagement: React.FC = () => {
}, [inventoryZoneOptions, skus]);
const taxCodeManualOverrideRef = useRef(false);
const taxRateManualOverrideRef = useRef(false);
/** AI 回填分类/规格后,跳过下一轮自动推荐,避免自触发循环 */
const aiFillSkipRef = useRef(false);
/** 用户动过分类/规格后,AI 不再自动回填这两个字段 */
const categoryTouchedRef = useRef(false);
const specTouchedRef = useRef(false);
/** AI 上一次自己填的值:只要用户没改,就可以被后续更准的建议更新 */
const aiFilledCategoryRef = useRef<string | null>(null);
const aiFilledSpecRef = useRef<string | null>(null);
/** 用户是否手动改过「库存预警」勾选;未改过则跟随分类默认值 */
const [generatingSkuCode, setGeneratingSkuCode] = useState(false);
const [taxCodeSuggesting, setTaxCodeSuggesting] = useState(false);
@@ -430,6 +438,7 @@ export const SkuManagement: React.FC = () => {
effectiveBranchCode
);
await refetchCategories();
categoryTouchedRef.current = true;
const nextRate = taxRateManualOverrideRef.current
? null
: resolveFormTaxRate(formData.tax_code, categoryCode);
@@ -868,6 +877,56 @@ export const SkuManagement: React.FC = () => {
const applyTaxCodeSuggestion = useCallback((result: TaxCodeSuggestion, autoConfirm = false) => {
setTaxCodeSuggestion(result);
// AI 建议的分类/规格:只填空字段;分类必须是本分公司真实存在的分类编码
const suggestedCategory =
!categoryTouchedRef.current &&
(!formData.category_code || formData.category_code === aiFilledCategoryRef.current) &&
result.category_code &&
categoryOptions.some((opt) => opt.category_code === result.category_code)
? result.category_code
: null;
const suggestedSpec =
!specTouchedRef.current &&
(!formData.spec.trim() || formData.spec === aiFilledSpecRef.current) &&
result.suggested_spec
? result.suggested_spec
: null;
if (suggestedCategory || suggestedSpec) {
aiFillSkipRef.current = true;
if (suggestedCategory) {
setFormErrors((prev) => (prev.category_code ? { ...prev, category_code: undefined } : prev));
}
setFormData((prev) => {
let next = prev;
if (
suggestedCategory &&
(!prev.category_code || prev.category_code === aiFilledCategoryRef.current)
) {
// 与手选分类同一套联动:未手改税率则重算,安全线归 0
const nextRate = taxRateManualOverrideRef.current
? prev.tax_rate
: resolveFormTaxRate(prev.tax_code, suggestedCategory);
if (!taxRateManualOverrideRef.current) {
setTaxRatePercentInput(taxRateToPercentInput(nextRate));
}
next = {
...next,
category_code: suggestedCategory,
tax_rate: nextRate,
low_stock_alert_qty: 0,
};
}
if (suggestedSpec && (!prev.spec.trim() || prev.spec === aiFilledSpecRef.current)) {
next = { ...next, spec: suggestedSpec };
}
return next;
});
if (suggestedCategory) aiFilledCategoryRef.current = suggestedCategory;
if (suggestedSpec) aiFilledSpecRef.current = suggestedSpec;
}
if (!result.matched || !result.tax_code) {
setTaxCodeConfirmed(false);
return;
@@ -891,7 +950,7 @@ export const SkuManagement: React.FC = () => {
} else {
setTaxCodeConfirmed(false);
}
}, [resolveFormTaxRate]);
}, [categoryOptions, formData.category_code, formData.spec, resolveFormTaxRate]);
const confirmTaxCodeSuggestion = useCallback((code: string, name?: string) => {
taxCodeManualOverrideRef.current = false;
@@ -921,6 +980,10 @@ export const SkuManagement: React.FC = () => {
useEffect(() => {
if (!showModal || editingSku || taxCodeManualOverrideRef.current) return;
if (aiFillSkipRef.current) {
aiFillSkipRef.current = false;
return;
}
const skuName = formData.sku_name.trim();
const categoryName = getLeafCategoryName(formData.category_code);
@@ -936,6 +999,12 @@ export const SkuManagement: React.FC = () => {
skuName,
categoryName,
spec: formData.spec,
needCategory:
(!formData.category_code || formData.category_code === aiFilledCategoryRef.current) &&
!categoryTouchedRef.current,
needSpec:
(!formData.spec.trim() || formData.spec === aiFilledSpecRef.current) &&
!specTouchedRef.current,
})
.then((result) => {
if (taxCodeManualOverrideRef.current) return;
@@ -1670,6 +1739,11 @@ export const SkuManagement: React.FC = () => {
setTaxCodeSuggesting(false);
taxCodeManualOverrideRef.current = false;
taxRateManualOverrideRef.current = false;
aiFillSkipRef.current = false;
categoryTouchedRef.current = false;
specTouchedRef.current = false;
aiFilledCategoryRef.current = null;
aiFilledSpecRef.current = null;
setTaxRatePercentInput('0');
};
@@ -1682,6 +1756,11 @@ export const SkuManagement: React.FC = () => {
setQuoteSheetCode('');
taxCodeManualOverrideRef.current = false;
taxRateManualOverrideRef.current = false;
aiFillSkipRef.current = false;
categoryTouchedRef.current = false;
specTouchedRef.current = false;
aiFilledCategoryRef.current = null;
aiFilledSpecRef.current = null;
setTaxCodeSuggesting(false);
setTaxCodeSuggestion(null);
setTaxCodeConfirmed(Boolean(sku.tax_code?.trim()));
@@ -1799,6 +1878,11 @@ export const SkuManagement: React.FC = () => {
setQuoteSheetCode('');
taxCodeManualOverrideRef.current = false;
taxRateManualOverrideRef.current = false;
aiFillSkipRef.current = false;
categoryTouchedRef.current = false;
specTouchedRef.current = false;
aiFilledCategoryRef.current = null;
aiFilledSpecRef.current = null;
setTaxCodeSuggesting(false);
setTaxCodeSuggestion(null);
setTaxCodeConfirmed(false);
@@ -2732,6 +2816,7 @@ export const SkuManagement: React.FC = () => {
compact
value={formData.category_code}
onChange={(v) => {
categoryTouchedRef.current = true;
const nextRate = taxRateManualOverrideRef.current
? formData.tax_rate
: resolveFormTaxRate(formData.tax_code, v);
@@ -2824,7 +2909,10 @@ export const SkuManagement: React.FC = () => {
type="text"
value={formData.spec}
maxLength={60}
onChange={(e) => setFormData({ ...formData, spec: e.target.value })}
onChange={(e) => {
specTouchedRef.current = true;
setFormData({ ...formData, spec: e.target.value });
}}
className="app-input w-full px-3 py-2 border border-slate-300 rounded-lg text-slate-900 placeholder:text-slate-400 focus:ring-2 focus:ring-[var(--app-theme-accent)] dark:text-slate-100"
/>
</div>
@@ -3009,6 +3097,8 @@ export const SkuManagement: React.FC = () => {
value={formData.tax_code}
onChange={(e) => {
taxCodeManualOverrideRef.current = true;
// 手动改税码时把「跳过下一轮」清掉,避免吞掉后续一次正常推荐
aiFillSkipRef.current = false;
setTaxCodeConfirmed(true);
const tax_code = e.target.value;
const nextRate = taxRateManualOverrideRef.current
+53
View File
@@ -0,0 +1,53 @@
// @vitest-environment jsdom
import { afterEach, describe, expect, it, vi } from 'vitest';
vi.mock('../lib/apiConfig', () => ({
buildApiUrl: (path: string) => path,
}));
vi.mock('./categories', () => ({
invalidateCategoryRowsCache: vi.fn(),
}));
import { suggestTaxCodeApi } from './catalogApi';
function mockFetchOnce(body: unknown) {
const fetchMock = vi.fn(async (_url: string, _init?: RequestInit) => ({
ok: true,
status: 200,
json: async () => body,
}));
vi.stubGlobal('fetch', fetchMock as unknown as typeof fetch);
return fetchMock;
}
afterEach(() => {
vi.unstubAllGlobals();
});
/**
* 商品名变化后自动推荐「税码 + 分类 + 规格」时,前端要把 need_category / need_spec
* 传给后端;否则后端不会为分类/规格额外调模型(省钱路径)。
*/
describe('suggestTaxCodeApi:分类/规格建议开关', () => {
it('需要分类/规格建议时带 need_category=1 与 need_spec=1', async () => {
const fetchMock = mockFetchOnce({ data: { matched: false }, error: null });
await suggestTaxCodeApi({ skuName: '土豆', needCategory: true, needSpec: true });
const url = String(fetchMock.mock.calls[0][0]);
expect(url).toContain('need_category=1');
expect(url).toContain('need_spec=1');
expect(url).toContain('sku_name=');
});
it('字段已填时不请求额外建议', async () => {
const fetchMock = mockFetchOnce({ data: { matched: false }, error: null });
await suggestTaxCodeApi({ skuName: '土豆', needCategory: false, needSpec: false });
const url = String(fetchMock.mock.calls[0][0]);
expect(url).not.toContain('need_category');
expect(url).not.toContain('need_spec');
});
});
+9
View File
@@ -50,6 +50,11 @@ export type TaxCodeSuggestion = {
catalog_version: string | null;
needs_confirmation: boolean;
candidates: TaxCodeCandidate[];
/** AI 建议的商品分类(后端从本分公司分类候选中选) */
category_code?: string | null;
category_name?: string | null;
/** AI 建议的规格(可直接修改) */
suggested_spec?: string | null;
};
export type TaxCatalogSearchItem = {
@@ -79,12 +84,16 @@ export async function suggestTaxCodeApi(input: {
categoryName?: string;
spec?: string;
useAi?: boolean;
needCategory?: boolean;
needSpec?: boolean;
}): Promise<TaxCodeSuggestion> {
const query = new URLSearchParams();
if (input.skuName?.trim()) query.set('sku_name', input.skuName.trim());
if (input.categoryName?.trim()) query.set('category_name', input.categoryName.trim());
if (input.spec?.trim()) query.set('spec', input.spec.trim());
if (input.useAi === false) query.set('use_ai', 'false');
if (input.needCategory) query.set('need_category', '1');
if (input.needSpec) query.set('need_spec', '1');
const response = await fetch(buildApiUrl(`/catalog/tax-code/suggest?${query.toString()}`), {
headers: getAuthHeaders(),