feat(库存入库): 小程序品名改商品选择器 + 建品查重
- 小程序「品名」格改为商品选择器(搜索已有 / 选中带出上次设置 / 输入新名待新建), 与 Web 口径一致;生产日期与数量不带出 - 后端 createCatalogSkuForInbound 加查重:同名(+规格)已有启用商品即复用, 避免重复新建(Web / 小程序 / 批量入库 / 自助采购 四个入口一并生效) - 新增 GET /mobile/inventory/sku-options;补查重单测与设计文档
This commit is contained in:
@@ -0,0 +1,103 @@
|
||||
# 小程序库存入库:品名格改为「商品选择器」+ 建品查重
|
||||
|
||||
> 需求(开发者 2026-11-01):「给小程序的库存入库的商品名选择效果也改为 Web 的这种效果;
|
||||
> 如果商品名不存在,确认入库后就是新建,商品库那边要更新;但是要注意**别出现商品库里面存在这个商品名却重复新建**的情况。」
|
||||
>
|
||||
> Web 权威实现(本批把同一套搬到小程序):`docs/design/20261011-入库直接选择已有商品并按上次设置预填.md`。
|
||||
> 触【商品主数据冻结】——本批**只加「建品查重(命中即复用)」,不改商品档案价格面 / 批量导入硬参数 / 同步方向**。
|
||||
|
||||
## 1. 目标 / 非目标
|
||||
|
||||
- 目标:
|
||||
1. 小程序「品名」格 = **商品选择器**:输入即搜商品档案;选中 → 带出该商品「上次设置」;直接输入新名 → 待新建。
|
||||
2. **建品查重**:建品前按「归一化商品名(+规格)」查已有**启用**商品,命中即**复用**,不再新增同名重复商品。
|
||||
- 非目标:
|
||||
1. 不改商品档案的价格面(`skus`/`product_catalog` 无销售价/成本价列);
|
||||
2. 不改批量导入硬参数(≤200/块、串行、单文件 20MB、无行数上限);
|
||||
3. 不改商品同步方向(`skus`/`categories` 上零触发器);
|
||||
4. 不新增表 / 列(无迁移)。
|
||||
|
||||
## 2. 改前实测事实(先立事实)
|
||||
|
||||
| # | 事实 | 证据 |
|
||||
|---|---|---|
|
||||
| F1 | 小程序「品名」是**纯文本输入**;分类/存放区域已是**搜索弹层**(`sheetOpen`) | `miniprogram/components/stock-inbound-panel/index.wxml`(品名 `<input cell--name>`);`index.js` `openSheet/refreshSheet` |
|
||||
| F2 | Web「品名」= `SearchableSelect` + `listInventorySkuOptionsApi`(`GET /inventory/sku-options`);选中走 `applyInboundBackfill`;自由文本 → `new_product` | `src/pages/inventory/StockInboundPanel.tsx`;`src/utils/inboundSkuPrefill.ts` |
|
||||
| F3 | 小程序**没有** `sku-options` 端点,只有 `/mobile/inventory/sku-similar` | `grep` `mobileInventoryRoutes.ts`;`miniprogram/utils/request.js` |
|
||||
| F4 | **建品无同名查重**:`createCatalogSkuForInbound` 只校验"生成的 code 是否已存在",**不查同名** | `server/src/services/skuProvisioningService.ts:669`(`exists` 只比对 `code`) |
|
||||
| F5 | 三个入口都经 `createCatalogSkuForInbound`:Web `/inventory/catalog-product`、小程序 `/mobile/catalog/products`、`batchStockInboundRows`(批入库)、`selfPurchaseStockInboundService` | 各调用点 |
|
||||
| F6 | 既有查重语义在 `productNameKey.ts`(`normalizeProductNameKey` / `productNameMatchKeys` / `productNamesSoftEqual`),`findProductByName` 已用它 | `server/src/utils/productNameKey.ts` |
|
||||
|
||||
## 3. 设计
|
||||
|
||||
### 3.1 小程序「品名」选择器(对齐 Web)
|
||||
|
||||
- 复用小程序现有弹层框架(`sheetType` 增加 `product`),数据源 = 新端点 `GET /mobile/inventory/sku-options`(输入**防抖**远程搜,复用 `listInboundSkuOptions`)。
|
||||
- **选中已有商品** → 套用**同一份**预填规则:
|
||||
- `spec`/`unit` 取**商品档案**;`unit_cost`/`category`/`storage_zone`/`shelf_life`/`origin` 取**上次设置**(仅补空,不覆盖操作员已填);
|
||||
- ⚠️ **生产日期 / 数量永不带出**(与 Web 同口径,有回归单测钉死);
|
||||
- 回填 `sku_code`。
|
||||
- **自由输入新名** → 记 `item_name`、清 `sku_code`(= 待新建),确认入库时建品。
|
||||
- 行首 `badge`:有 `sku_code` → `已选 <code>`;否则 `待新建`。
|
||||
|
||||
### 3.2 建品查重(根因修复,**前后端都受益**)
|
||||
|
||||
在 `createCatalogSkuForInbound` **开头**加查重(不改 code 生成器、不改插入逻辑):
|
||||
|
||||
- 取归一化名 `normalizeProductNameKey(name)` 命中 `skus`(`status = 1`)的候选;
|
||||
- **命中规则**(明确、可解释,**不做「鲜」前缀 / 包含 等模糊合并**,避免误并不同商品):
|
||||
1. 无同名候选 → **新建**;
|
||||
2. 有候选且 `归一化(spec)` 相等者 → **复用**该 sku;
|
||||
3. incoming `spec` 为空 → **复用**同名第一个;
|
||||
4. 有候选其 `spec` 为空 → **复用**它;
|
||||
5. 否则(同名但规格都非空且不相等)→ **新建**(视为不同规格,有意允许并存)。
|
||||
- 复用命中写一条 info 日志(可观测"本次未新建、复用了 X")。
|
||||
- 返回结构不变(`{ skuCode, barcode, name }`)⇒ 三个入口零改动即获得查重。
|
||||
|
||||
### 3.3 移动端新增端点
|
||||
|
||||
- `GET /mobile/inventory/sku-options?search=&limit=`(`requireStockInboundRole`)→ 复用 `listInboundSkuOptions({ branchCode: ctx.branchCode, search, limit })`。
|
||||
|
||||
## 4. 迁移清单
|
||||
|
||||
- **无**(不加表/列;`skus` / `product_catalog` 结构不动)。
|
||||
|
||||
## 5. 验收标准
|
||||
|
||||
- 小程序「品名」可**搜索并选中**已有商品,选中后带出上次设置(**生产日期/数量不动**);自由输入 → 待新建。
|
||||
- **同名(按 §3.2 规则)建品 → 返回既有 `sku_code`,不新增行**;商品库不出现同名重复。
|
||||
- 回归:Web「直接选已有商品」、小程序既有识别候选、`/mobile/catalog/products`、自助采购建品**行为不劣化**(正常新建仍能新建)。
|
||||
- `server tsc` / Web `tsc`+`build` / 小程序 `node --check` / 相关单测(含新增查重契约测试)通过。
|
||||
|
||||
## 6. 风险 / 冻结口径
|
||||
|
||||
| # | 风险 | 级别 | 规避 |
|
||||
|---|---|---|---|
|
||||
| A | 误并**不同商品** | 中 | 只按**归一化名精确**匹配;同名不同规格允许并存(§3.2-5) |
|
||||
| B | 触商品主数据冻结 | 中 | 只加"查重复用",**不动**价格面/导入参数/同步方向 |
|
||||
| C | 影响其它建品入口 | 低 | 返回结构不变;`selfPurchaseStockInboundService` 一并获得查重(有益) |
|
||||
| D | 小程序 UI 回归 | 低 | 复用既有弹层框架;生产日期/数量不带出(与 Web 同单测口径) |
|
||||
|
||||
## 7. 验证(实现后回填)
|
||||
|
||||
- **后端 tsc**:`server && ./node_modules/.bin/tsc --noEmit` ✅ 0 error。
|
||||
- **小程序**:`node --check`(`stock-inbound-panel/index.js`、`utils/request.js`)✅。
|
||||
- **单测**:新增 `server/tests/inboundProductDedupe.test.ts`(4 例,钉住查重 4 条规则);
|
||||
`npx vitest run tests/inboundProductDedupe.test.ts tests/inventorySkuOptions.test.ts` ✅ 14/14。
|
||||
- **真库实测**(`tenant_sup35143228`):查重 SQL 对「库里 `( 精)仔猪肋排10kg`」输入「`精仔猪肋排10kg`」
|
||||
能命中(括号/空格不敏感)⇒ 归属同一商品,复用不新建。
|
||||
- **门禁九闸**:`check.py` / `check-structure` / `check-refs` / `check-migrations` / `check-self-test` ✅;
|
||||
`check-ai-cost.py` 保持库内既有红(未修)。
|
||||
- **未做的验证**:小程序真机联调(品名弹层搜索/选中/新建三态)留待人工点测。
|
||||
|
||||
### 变更清单
|
||||
|
||||
| 文件 | 类型 | 改动 |
|
||||
|---|---|---|
|
||||
| `server/src/services/skuProvisioningService.ts` | 改 | `createCatalogSkuForInbound` 加查重(`findReusableProductForInbound`) |
|
||||
| `server/src/routes/mobile/mobileInventoryRoutes.ts` | 改 | 新增 `GET /mobile/inventory/sku-options` |
|
||||
| `server/tests/inboundProductDedupe.test.ts` | 新增 | 查重契约单测(4 例) |
|
||||
| `miniprogram/utils/request.js` | 改 | 新增 `fetchStockInboundSkuOptions` |
|
||||
| `miniprogram/components/stock-inbound-panel/index.{js,wxml}` | 改 | 「品名」格 = 商品选择器(搜索/选中/新建三态 + 预填) |
|
||||
| `docs/design/20261101-小程序库存入库品名选择与建品查重.md` | 新增 | 本文 |
|
||||
| 迁移 | — | 无 |
|
||||
@@ -1,6 +1,7 @@
|
||||
const {
|
||||
fetchStockInboundCategories,
|
||||
fetchStockInboundStorageZones,
|
||||
fetchStockInboundSkuOptions,
|
||||
createStockInboundCategory,
|
||||
recognizeStockInboundLines,
|
||||
submitStockInboundBatch,
|
||||
@@ -143,6 +144,8 @@ Component({
|
||||
sheetList: [],
|
||||
sheetCanCreate: false,
|
||||
sheetCreateLabel: '',
|
||||
/** 「商品选择」远程检索结果(带上次设置回填) */
|
||||
productOptions: [],
|
||||
},
|
||||
|
||||
lifetimes: {
|
||||
@@ -201,9 +204,10 @@ Component({
|
||||
this.setData({ categoryOptions: options });
|
||||
},
|
||||
|
||||
// ── 分类 / 存放区域:输入下拉 + 可新建(弹层)────────
|
||||
// ── 分类 / 存放区域 / 商品:输入下拉 + 可新建(弹层)────────
|
||||
sheetSource(type) {
|
||||
if (type === 'category') return this.data.categoryOptions || [];
|
||||
if (type === 'product') return this.data.productOptions || [];
|
||||
return (this.data.zoneOptions || []).map((z) => ({ code: z, label: z }));
|
||||
},
|
||||
|
||||
@@ -215,6 +219,13 @@ Component({
|
||||
this.openSheet('zone', Number(e.currentTarget.dataset.index));
|
||||
},
|
||||
|
||||
/** 「品名」格 = 商品选择器:打开弹层并远程搜商品档案(与 Web 口径一致) */
|
||||
openProductSheet(e) {
|
||||
const index = Number(e.currentTarget.dataset.index);
|
||||
this.openSheet('product', index);
|
||||
this.searchProducts('');
|
||||
},
|
||||
|
||||
openSheet(type, index) {
|
||||
if (!Number.isInteger(index) || index < 0) return;
|
||||
this.setData({
|
||||
@@ -234,13 +245,31 @@ Component({
|
||||
|
||||
refreshSheet(query) {
|
||||
const type = this.data.sheetType;
|
||||
const all = this.sheetSource(type);
|
||||
this.refreshSheetLocal(query, this.sheetSource(type));
|
||||
// 商品:本地过滤后仍走远程搜(商品库大,需服务端检索)
|
||||
if (type === 'product') this.searchProducts(String(query || ''));
|
||||
},
|
||||
|
||||
refreshSheetLocal(query, all) {
|
||||
const type = this.data.sheetType;
|
||||
const q = String(query || '');
|
||||
const ql = q.trim().toLowerCase();
|
||||
const list = ql ? all.filter((o) => o.label.toLowerCase().indexOf(ql) >= 0) : all;
|
||||
const list = ql
|
||||
? (all || []).filter((o) => String(o.label || '').toLowerCase().indexOf(ql) >= 0)
|
||||
: all || [];
|
||||
const trimmed = q.trim();
|
||||
const canCreate = Boolean(trimmed) && !all.some((o) => o.label.trim() === trimmed);
|
||||
const createLabel = type === 'category' ? `+ 新建分类「${trimmed}」` : `+ 使用区域「${trimmed}」`;
|
||||
const matched = (all || []).some((o) =>
|
||||
type === 'product'
|
||||
? String(o.sku_name || '').trim() === trimmed
|
||||
: String(o.label || '').trim() === trimmed
|
||||
);
|
||||
const canCreate = Boolean(trimmed) && !matched;
|
||||
const createLabel =
|
||||
type === 'category'
|
||||
? `+ 新建分类「${trimmed}」`
|
||||
: type === 'product'
|
||||
? `+ 使用「${trimmed}」作为新商品`
|
||||
: `+ 使用区域「${trimmed}」`;
|
||||
this.setData({
|
||||
sheetQuery: q,
|
||||
sheetList: list,
|
||||
@@ -249,6 +278,35 @@ Component({
|
||||
});
|
||||
},
|
||||
|
||||
/** 「品名」远程检索(防抖) */
|
||||
searchProducts(query) {
|
||||
if (this._skuTimer) clearTimeout(this._skuTimer);
|
||||
const q = String(query || '');
|
||||
this._skuTimer = setTimeout(async () => {
|
||||
try {
|
||||
const res = await fetchStockInboundSkuOptions({ search: q, limit: 20 });
|
||||
const rows = (res && (res.data || res)) || [];
|
||||
const options = (Array.isArray(rows) ? rows : []).map((o) => ({
|
||||
code: String(o.sku_code || ''),
|
||||
sku_name: String(o.sku_name || o.sku_code || ''),
|
||||
label: o.spec ? `${o.sku_name} · ${o.spec}` : String(o.sku_name || o.sku_code || ''),
|
||||
spec: o.spec || '',
|
||||
unit: o.unit || '',
|
||||
origin: o.origin || '',
|
||||
category_code: o.category_code || '',
|
||||
category_name: o.category_name || '',
|
||||
backfill: o.backfill || null,
|
||||
}));
|
||||
this.setData({ productOptions: options });
|
||||
if (this.data.sheetType === 'product') {
|
||||
this.refreshSheetLocal(this.data.sheetQuery, options);
|
||||
}
|
||||
} catch (e) {
|
||||
// 搜索失败静默:不阻断手输 / 新建
|
||||
}
|
||||
}, 300);
|
||||
},
|
||||
|
||||
closeSheet() {
|
||||
this.setData({ sheetOpen: false });
|
||||
},
|
||||
@@ -259,12 +317,75 @@ Component({
|
||||
onSheetPick(e) {
|
||||
const code = String(e.currentTarget.dataset.code || '');
|
||||
const label = String(e.currentTarget.dataset.label || '');
|
||||
if (this.data.sheetType === 'product') {
|
||||
const opt = (this.data.productOptions || []).find((o) => o.code === code);
|
||||
if (opt) {
|
||||
this.applyProductPick(opt);
|
||||
return;
|
||||
}
|
||||
}
|
||||
this.applySheetValue(code, label);
|
||||
},
|
||||
|
||||
/** 选中已有商品:回填 sku + 上次设置(生产日期 / 数量不动) */
|
||||
applyProductPick(opt) {
|
||||
const index = this.data.sheetIndex;
|
||||
if (!Number.isInteger(index) || index < 0) {
|
||||
this.setData({ sheetOpen: false });
|
||||
return;
|
||||
}
|
||||
const line = (this.data.lines || [])[index] || {};
|
||||
const bf = opt.backfill || null;
|
||||
const patch = {
|
||||
[`lines[${index}].sku_code`]: opt.code,
|
||||
[`lines[${index}].item_name`]: opt.sku_name || opt.label,
|
||||
[`lines[${index}].candidates`]: [],
|
||||
sheetOpen: false,
|
||||
};
|
||||
// 规格 / 单位:商品档案优先
|
||||
if (opt.spec) patch[`lines[${index}].spec`] = opt.spec;
|
||||
if (opt.unit) patch[`lines[${index}].unit`] = opt.unit;
|
||||
if (bf) {
|
||||
// 分类:商品档案 / 上次设置优先
|
||||
if (bf.category_code) {
|
||||
patch[`lines[${index}].category_code`] = bf.category_code;
|
||||
patch[`lines[${index}].category_name`] = bf.category_name || '';
|
||||
}
|
||||
// 成本价 / 存放区域 / 保质期 / 生产地区:空才回填
|
||||
if (!String(line.unit_cost ?? '').trim() && bf.last_cost_price != null) {
|
||||
patch[`lines[${index}].unit_cost`] = String(bf.last_cost_price);
|
||||
}
|
||||
if (!String(line.storage_zone || '').trim() && bf.last_storage_zone) {
|
||||
patch[`lines[${index}].storage_zone`] = bf.last_storage_zone;
|
||||
}
|
||||
if (!String(line.shelf_life || '').trim() && bf.last_shelf_life_days != null) {
|
||||
patch[`lines[${index}].shelf_life`] = `${bf.last_shelf_life_days}天`;
|
||||
}
|
||||
if (!String(line.origin || '').trim() && bf.origin) {
|
||||
patch[`lines[${index}].origin`] = bf.origin;
|
||||
}
|
||||
}
|
||||
this.setData(patch);
|
||||
},
|
||||
|
||||
async onSheetCreate() {
|
||||
const q = String(this.data.sheetQuery || '').trim();
|
||||
if (!q) return;
|
||||
// 商品:输入新名 ⇒ 记为待新建(确认入库时才建品/查重)
|
||||
if (this.data.sheetType === 'product') {
|
||||
const index = this.data.sheetIndex;
|
||||
if (Number.isInteger(index) && index >= 0) {
|
||||
this.setData({
|
||||
[`lines[${index}].item_name`]: q,
|
||||
[`lines[${index}].sku_code`]: '',
|
||||
[`lines[${index}].candidates`]: [],
|
||||
sheetOpen: false,
|
||||
});
|
||||
} else {
|
||||
this.setData({ sheetOpen: false });
|
||||
}
|
||||
return;
|
||||
}
|
||||
// 存放区域是自由文本,直接采用输入值
|
||||
if (this.data.sheetType === 'zone') {
|
||||
this.applySheetValue(q, q);
|
||||
|
||||
@@ -26,7 +26,7 @@
|
||||
</view>
|
||||
|
||||
<view class="line-row">
|
||||
<input class="input cell cell--name" placeholder="品名" data-index="{{index}}" data-field="item_name" value="{{item.item_name}}" bindinput="onLineField" />
|
||||
<view class="cell cell--name cell-pick {{item.item_name ? '' : 'cell-pick--empty'}}" data-index="{{index}}" bindtap="openProductSheet">{{item.item_name || '品名'}} ▾</view>
|
||||
<input class="input cell cell--spec" placeholder="规格" data-index="{{index}}" data-field="spec" value="{{item.spec}}" bindinput="onLineField" />
|
||||
<input class="input cell cell--qty" type="digit" placeholder="数量" data-index="{{index}}" data-field="qty" value="{{item.qty}}" bindinput="onLineField" />
|
||||
<input class="input cell cell--unit" placeholder="单位" data-index="{{index}}" data-field="unit" value="{{item.unit}}" bindinput="onLineField" />
|
||||
@@ -59,8 +59,8 @@
|
||||
|
||||
<view wx:if="{{sheetOpen}}" class="sheet-mask" catchtap="closeSheet">
|
||||
<view class="sheet" catchtap="noop">
|
||||
<view class="sheet-title">{{sheetType === 'category' ? '选择分类' : '选择存放区域'}}</view>
|
||||
<input class="sheet-input" placeholder="{{sheetType === 'category' ? '搜索或输入新分类' : '搜索或输入新区域'}}" value="{{sheetQuery}}" bindinput="onSheetInput" confirm-type="done" />
|
||||
<view class="sheet-title">{{sheetType === 'product' ? '选择商品' : (sheetType === 'category' ? '选择分类' : '选择存放区域')}}</view>
|
||||
<input class="sheet-input" placeholder="{{sheetType === 'product' ? '搜索已有商品,或输入新商品名' : (sheetType === 'category' ? '搜索或输入新分类' : '搜索或输入新区域')}}" value="{{sheetQuery}}" bindinput="onSheetInput" confirm-type="done" />
|
||||
<scroll-view scroll-y class="sheet-list">
|
||||
<view wx:if="{{sheetCanCreate}}" class="sheet-item sheet-item-create" bindtap="onSheetCreate">{{sheetCreateLabel}}</view>
|
||||
<view class="sheet-item" wx:for="{{sheetList}}" wx:key="code" data-code="{{item.code}}" data-label="{{item.label}}" bindtap="onSheetPick">{{item.label}}</view>
|
||||
|
||||
@@ -603,6 +603,14 @@ function fetchStockInboundSkuSimilar(params = {}) {
|
||||
return request(`/mobile/inventory/sku-similar${qs}`);
|
||||
}
|
||||
|
||||
function fetchStockInboundSkuOptions(params = {}) {
|
||||
const parts = [];
|
||||
if (params.search) parts.push(`search=${encodeURIComponent(params.search)}`);
|
||||
if (params.limit) parts.push(`limit=${encodeURIComponent(params.limit)}`);
|
||||
const qs = parts.length ? `?${parts.join('&')}` : '';
|
||||
return request(`/mobile/inventory/sku-options${qs}`);
|
||||
}
|
||||
|
||||
function createStockInboundProduct(payload) {
|
||||
return request('/mobile/catalog/products', {
|
||||
method: 'POST',
|
||||
@@ -1310,6 +1318,7 @@ module.exports = {
|
||||
createStockInboundCategory,
|
||||
recognizeStockInboundCatalog,
|
||||
fetchStockInboundSkuSimilar,
|
||||
fetchStockInboundSkuOptions,
|
||||
createStockInboundProduct,
|
||||
submitStockInbound,
|
||||
recognizeStockInboundLines,
|
||||
|
||||
@@ -6,6 +6,7 @@ import { pool } from '../../db';
|
||||
import { recognizeCatalogForInbound } from '../../services/weighStationService';
|
||||
import {
|
||||
batchStockInboundRows,
|
||||
listInboundSkuOptions,
|
||||
listStorageZones,
|
||||
recognizeInboundLinesFromImage,
|
||||
} from '../../services/stockInboundBatchService';
|
||||
@@ -79,6 +80,25 @@ router.get('/inventory/sku-similar', authMiddleware, async (req: AuthRequest, re
|
||||
}
|
||||
});
|
||||
|
||||
/** 库存入库「直接选择已有商品」:按关键词检索商品档案(带上次设置回填,不带生产日期),与 Web /inventory/sku-options 同源 */
|
||||
router.get('/inventory/sku-options', authMiddleware, async (req: AuthRequest, res: Response) => {
|
||||
try {
|
||||
await requireStockInboundRole(req);
|
||||
const ctx = await loadTenantContext(req.userId);
|
||||
const data = await listInboundSkuOptions({
|
||||
branchCode: ctx?.branchCode || null,
|
||||
search: typeof req.query?.search === 'string' ? req.query.search : '',
|
||||
limit: Number(req.query?.limit) || 20,
|
||||
});
|
||||
return res.json({ data });
|
||||
} catch (error: any) {
|
||||
return res.status(error?.status || 500).json({
|
||||
error: error?.code || 'server_error',
|
||||
error_description: error?.message || '加载可选商品失败',
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
router.get('/inventory/categories', authMiddleware, async (req: AuthRequest, res: Response) => {
|
||||
try {
|
||||
await requireStockInboundRole(req);
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { PoolClient } from 'pg';
|
||||
import { assertBranchAllowsProductCatalog } from './platformBranch';
|
||||
import { productNameMatchKeys } from '../utils/productNameKey';
|
||||
import { productNameMatchKeys, normalizeProductNameKey } from '../utils/productNameKey';
|
||||
|
||||
function trimText(value: unknown): string {
|
||||
return String(value || '').trim();
|
||||
@@ -666,6 +666,59 @@ export async function ensureSkuFromPurchaseCompletion(
|
||||
}
|
||||
|
||||
/** 独立入库:新建商品(对齐商品管理精简字段;触发器同步 skus) */
|
||||
/**
|
||||
* 建品查重(2026-11-01):归一化名精确匹配**启用**商品,命中即复用,避免同名重复新建。
|
||||
* 规则见 docs/design/20261101-小程序库存入库品名选择与建品查重.md §3.2:
|
||||
* ① 无同名候选 ⇒ null(调用方新建);
|
||||
* ② 有候选且归一化 spec 相等 ⇒ 复用该行;
|
||||
* ③ incoming spec 为空 ⇒ 复用同名第一个;
|
||||
* ④ 有候选其 spec 为空 ⇒ 复用它;
|
||||
* ⑤ 否则(同名、规格都非空且不等)⇒ null(视为不同规格,允许并存)。
|
||||
* ⚠️ 只做「归一化名精确」匹配,**不做「鲜」前缀/包含 等模糊合并**(避免误并不同商品)。
|
||||
*/
|
||||
async function findReusableProductForInbound(
|
||||
client: PoolClient,
|
||||
input: { name: string; spec?: string | null; branchCode?: string | null }
|
||||
): Promise<{ skuCode: string; barcode: string | null; name: string } | null> {
|
||||
const nameKey = normalizeProductNameKey(input.name);
|
||||
if (!nameKey) return null;
|
||||
const branch = trimText(input.branchCode);
|
||||
const rows = await client.query(
|
||||
`SELECT s.sku_code,
|
||||
NULLIF(TRIM(s.spec), '') AS spec,
|
||||
COALESCE(NULLIF(TRIM(s.sku_name), ''), s.sku_code) AS sku_name,
|
||||
NULLIF(TRIM(pc.barcode), '') AS barcode
|
||||
FROM skus s
|
||||
LEFT JOIN product_catalog pc ON pc.item_type = 'product' AND pc.code = s.sku_code
|
||||
WHERE s.status = 1
|
||||
AND ($2 = '' OR s.branch_code IS NULL OR s.branch_code = $2)
|
||||
AND (
|
||||
TRIM(s.sku_name) = $1
|
||||
OR s.sku_name ILIKE '%' || $1 || '%'
|
||||
OR regexp_replace(lower(TRIM(s.sku_name)), '[[:space:]()()]+', '', 'g')
|
||||
= regexp_replace(lower(TRIM($1)), '[[:space:]()()]+', '', 'g')
|
||||
)
|
||||
LIMIT 50`,
|
||||
[trimText(input.name), branch]
|
||||
);
|
||||
const candidates = rows.rows
|
||||
.filter((r) => normalizeProductNameKey(String(r.sku_name || '')) === nameKey)
|
||||
.map((r) => ({
|
||||
skuCode: String(r.sku_code),
|
||||
name: String(r.sku_name || r.sku_code),
|
||||
specKey: normalizeProductNameKey(String(r.spec || '')),
|
||||
barcode: r.barcode ? String(r.barcode) : null,
|
||||
}));
|
||||
if (!candidates.length) return null;
|
||||
const specKey = normalizeProductNameKey(input.spec || '');
|
||||
const pick =
|
||||
(specKey ? candidates.find((c) => c.specKey && c.specKey === specKey) : undefined) ||
|
||||
(!specKey ? candidates[0] : undefined) ||
|
||||
candidates.find((c) => !c.specKey);
|
||||
if (!pick) return null;
|
||||
return { skuCode: pick.skuCode, barcode: pick.barcode, name: pick.name };
|
||||
}
|
||||
|
||||
export async function createCatalogSkuForInbound(
|
||||
client: PoolClient,
|
||||
input: {
|
||||
@@ -684,6 +737,24 @@ export async function createCatalogSkuForInbound(
|
||||
if (!name) {
|
||||
throw Object.assign(new Error('请填写品名'), { status: 400, code: 'invalid_request' });
|
||||
}
|
||||
|
||||
// 建品查重(2026-11-01):同名(+规格)已有启用商品 ⇒ 直接复用,不新增(防重复新建)。
|
||||
const reusable = await findReusableProductForInbound(client, {
|
||||
name,
|
||||
spec: input.spec,
|
||||
branchCode: input.branchCode,
|
||||
});
|
||||
if (reusable) {
|
||||
console.info(
|
||||
`[sku-provision] 建品查重命中,复用既有商品 ${reusable.skuCode}(${reusable.name}),未新建`
|
||||
);
|
||||
return {
|
||||
skuCode: reusable.skuCode,
|
||||
barcode: reusable.barcode || defaultProductBarcode(reusable.skuCode),
|
||||
name: reusable.name,
|
||||
};
|
||||
}
|
||||
|
||||
if (!parentCode) {
|
||||
throw Object.assign(new Error('请选择分类'), { status: 400, code: 'invalid_request' });
|
||||
}
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
|
||||
/**
|
||||
* 库存入库「建品查重」(开发者 2026-11-01):
|
||||
* 「…别出现商品库里面存在这个商品名 但是重复新建的情况」。
|
||||
* 设计:docs/design/20261101-小程序库存入库品名选择与建品查重.md §3.2。
|
||||
*
|
||||
* 这里钉住 `createCatalogSkuForInbound` 的查重语义(命中即复用,不再 INSERT):
|
||||
* ① 同名(含括号/空格差异)已有启用商品 ⇒ 复用,不新建;
|
||||
* ② 无同名候选 ⇒ 正常新建;
|
||||
* ③ 同名但两方规格都非空且不等 ⇒ **不误并**(视为不同规格,允许新建);
|
||||
* ④ 同名、incoming 规格为空 ⇒ 复用同名第一个。
|
||||
*/
|
||||
vi.mock('../src/db', () => ({
|
||||
pool: { query: vi.fn(), connect: vi.fn() },
|
||||
getRawPoolQuery: () => vi.fn(),
|
||||
}));
|
||||
|
||||
import { createCatalogSkuForInbound } from '../src/services/skuProvisioningService';
|
||||
|
||||
type Row = { rows: Record<string, unknown>[]; rowCount?: number };
|
||||
|
||||
function makeClient(handler: (sql: string, params?: unknown[]) => Row) {
|
||||
const calls: Array<{ sql: string; params?: unknown[] }> = [];
|
||||
const query = vi.fn(async (sql: string, params?: unknown[]) => {
|
||||
calls.push({ sql: String(sql), params });
|
||||
const r = handler(String(sql), params);
|
||||
return { rows: r.rows, rowCount: r.rowCount ?? r.rows.length };
|
||||
});
|
||||
return { query, calls, release: vi.fn() } as any;
|
||||
}
|
||||
|
||||
const guardRow = (over: Record<string, unknown>) => ({
|
||||
sku_code: 'SKU-EXIST',
|
||||
spec: '件',
|
||||
sku_name: '( 精)仔猪肋排10kg',
|
||||
barcode: 'BC-1',
|
||||
...over,
|
||||
});
|
||||
|
||||
describe('createCatalogSkuForInbound 查重(防同名重复新建)', () => {
|
||||
it('① 同名已有启用商品(含括号/空格差异)⇒ 复用其 sku,不再 INSERT', async () => {
|
||||
const client = makeClient((sql) =>
|
||||
sql.includes('FROM skus s') ? { rows: [guardRow({})] } : { rows: [] }
|
||||
);
|
||||
const out = await createCatalogSkuForInbound(client, {
|
||||
name: '精仔猪肋排10kg', // 与库里「( 精)仔猪肋排10kg」只差括号/空格
|
||||
parentCode: 'CAT',
|
||||
branchCode: 'BR002',
|
||||
spec: '件',
|
||||
});
|
||||
expect(out.skuCode).toBe('SKU-EXIST');
|
||||
expect(out.barcode).toBe('BC-1');
|
||||
expect(client.query).toHaveBeenCalledTimes(1); // 只查重一次,无生成编码、无 INSERT
|
||||
expect(client.calls.some((c: { sql: string }) => /INSERT INTO product_catalog/i.test(c.sql))).toBe(false);
|
||||
});
|
||||
|
||||
it('② 无同名候选 ⇒ 正常新建(生成新 code 并 INSERT)', async () => {
|
||||
const client = makeClient(() => ({ rows: [] }));
|
||||
const out = await createCatalogSkuForInbound(client, {
|
||||
name: '全新商品X',
|
||||
parentCode: 'CAT',
|
||||
branchCode: 'BR002',
|
||||
});
|
||||
expect(out.skuCode).toMatch(/^SKU/);
|
||||
expect(client.calls.some((c: { sql: string }) => /INSERT INTO product_catalog/i.test(c.sql))).toBe(true);
|
||||
});
|
||||
|
||||
it('③ 同名但规格都非空且不等 ⇒ 不误并(新建)', async () => {
|
||||
const client = makeClient((sql) =>
|
||||
sql.includes('FROM skus s')
|
||||
? { rows: [guardRow({ sku_code: 'SKU-1KG', sku_name: '土豆', spec: '1kg' })] }
|
||||
: { rows: [] }
|
||||
);
|
||||
const out = await createCatalogSkuForInbound(client, {
|
||||
name: '土豆',
|
||||
parentCode: 'CAT',
|
||||
branchCode: 'BR002',
|
||||
spec: '2kg',
|
||||
});
|
||||
expect(out.skuCode).not.toBe('SKU-1KG');
|
||||
expect(client.calls.some((c: { sql: string }) => /INSERT INTO product_catalog/i.test(c.sql))).toBe(true);
|
||||
});
|
||||
|
||||
it('④ 同名、incoming 规格为空 ⇒ 复用同名第一个', async () => {
|
||||
const client = makeClient((sql) =>
|
||||
sql.includes('FROM skus s')
|
||||
? { rows: [guardRow({ sku_code: 'SKU-A', sku_name: '香菇', spec: '500g' })] }
|
||||
: { rows: [] }
|
||||
);
|
||||
const out = await createCatalogSkuForInbound(client, {
|
||||
name: '香菇',
|
||||
parentCode: 'CAT',
|
||||
branchCode: 'BR002',
|
||||
});
|
||||
expect(out.skuCode).toBe('SKU-A');
|
||||
expect(client.calls.some((c: { sql: string }) => /INSERT INTO product_catalog/i.test(c.sql))).toBe(false);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user