Files
SupplierSystem/server/src/services/stockInboundBatchService.ts
T
雨天andCursor e3ae7ee6e7
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
feat(库存入库): 按行入库 + 保质期年/月/日选择 + 弹层抬层
小程序识别结果逐行入库;保质期拆数值与单位(AI 三选一或人手选)落库原文;选择商品弹层 root-portal 防 tab 遮挡,并预填 AI 品名。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-15 10:43:47 +08:00

689 lines
25 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* 库存入库:多商品(送货单 / 实物堆)识别 → 人工审核 → 批量入库。
* 设计:docs/design/20261010-多商品识别审核与批量入库.md
*
* 口径:
* - 识别用称重台同款 ARK 视觉口径(buildWeighStationLlmOptions),避免被分公司视觉配置带偏。
* - 入库复用 bulkStockInbound(200/块、每块一事务、行级 SAVEPOINT、同批次累加、成本可空),不新造库存写入语义。
* - 新增 AI 能力已登记 AI-28(docs/design/20260929-AI门槛与计量登记表.md)。
*/
import type { PoolClient } from 'pg';
import { pool } from '../db';
import { buildWeighStationLlmOptions, callWithImage, callWithImages, callWithText, hasRuntimeConfig } from './llmService';
import { resolvePrompt } from './promptRegistryService';
import {
createCatalogSkuForInbound,
listSimilarSkusForInbound,
} from './skuProvisioningService';
import {
bulkStockInbound,
type BulkStockInboundResult,
type StockImportRowInput,
type StockImportRowResult,
} from './stockInboundService';
import { composeShelfLifeText, normalizeRecognizedDate } from '../utils/shelfLife';
export interface InboundLineBackfill {
unit: string | null;
origin: string | null;
category_code: string | null;
category_name: string | null;
/** 最近一批 cost_price */
last_cost_price: number | null;
/** 最近一批实际所在区域 */
last_storage_zone: string | null;
/** 最近一批 expiry_date − production_date(天) */
last_shelf_life_days: number | null;
/** 最近一批 created_at(ISO);无入库历史则 null */
last_inbound_at: string | null;
}
export const EMPTY_BACKFILL: InboundLineBackfill = {
unit: null,
origin: null,
category_code: null,
category_name: null,
last_cost_price: null,
last_storage_zone: null,
last_shelf_life_days: null,
last_inbound_at: null,
};
export interface InboundLineCandidate {
sku_code: string;
sku_name: string;
spec: string | null;
brand: string | null;
unit: string | null;
quote_cost: number | null;
backfill: InboundLineBackfill;
}
export interface InboundRecognizedLine {
item_name: string;
spec: string | null;
unit: string | null;
origin: string | null;
qty: number | null;
unit_cost: number | null;
production_date: string | null;
shelf_life: string | null;
/** AI 从「已有分类列表」里选的分类(仅未命中商品时用;命中时以商品档案为准) */
category_code: string | null;
category_name: string | null;
confidence: number;
matched: {
/** 品名+规格唯一命中时给出,或由「最近入库」在多候选中选出的那个;否则 null */
sku_code: string | null;
candidates: InboundLineCandidate[];
/** 被选中 SKU 的回填数据(前端只用来补空位) */
backfill: InboundLineBackfill | null;
};
}
export interface RecognizeInboundLinesResult {
kind: 'document' | 'goods' | 'none';
items: InboundRecognizedLine[];
no_llm?: boolean;
message?: string;
}
/** 单次识别最多接受的行数(防一张乱图刷出几百行) */
const MAX_LINES = 100;
function trimText(value: unknown): string {
return String(value ?? '').trim();
}
function stripImageBase64(raw: string): string {
const trimmed = trimText(raw);
const m = /^data:[^;]+;base64,(.+)$/i.exec(trimmed);
return m ? m[1] : trimmed;
}
/** 归一化入参:支持新的 imagesBase64(多图)与旧的 imageBase64(单图);统一为去前缀的 base64 数组 */
function normalizeRecognizedImages(input: { imageBase64?: unknown; imagesBase64?: unknown }): string[] {
const list: string[] = [];
if (Array.isArray(input.imagesBase64)) {
for (const item of input.imagesBase64) {
const t = stripImageBase64(trimText(item));
if (t) list.push(t);
}
}
const single = stripImageBase64(trimText(input.imageBase64));
if (single) list.push(single);
return list;
}
function toNumOrNull(value: unknown): number | null {
if (value === null || value === undefined || value === '') return null;
const n = Number(value);
return Number.isFinite(n) ? n : null;
}
function normalizeKey(value: unknown): string {
return trimText(value).toLowerCase().replace(/\s+/g, '');
}
function parseItemsJson(raw: string | null): { kind: 'document' | 'goods' | 'none'; items: unknown[] } {
const text = trimText(raw);
if (!text) return { kind: 'none', items: [] };
const fenced = text.match(/```(?:json)?\s*([\s\S]*?)```/i);
const body = fenced ? fenced[1] : text;
const start = body.indexOf('{');
const end = body.lastIndexOf('}');
if (start < 0 || end <= start) return { kind: 'none', items: [] };
try {
const obj = JSON.parse(body.slice(start, end + 1)) as Record<string, unknown>;
const kindRaw = trimText(obj.kind).toLowerCase();
const kind = kindRaw === 'goods' ? 'goods' : kindRaw === 'document' ? 'document' : 'none';
const items = Array.isArray(obj.items) ? obj.items : [];
return { kind, items };
} catch {
return { kind: 'none', items: [] };
}
}
/**
* 取每个 SKU 的「匹配回填」数据:商品单位/分类 + 最近一批(按 created_at)的成本价/区域/保质期天数。
* 最近一批用 to_char 取日期字符串,避免时区解析歧义。
*/
async function loadInboundBackfill(
client: PoolClient,
skuCodes: string[]
): Promise<Map<string, InboundLineBackfill>> {
const map = new Map<string, InboundLineBackfill>();
const codes = [...new Set(skuCodes.map((c) => trimText(c)).filter(Boolean))];
if (!codes.length) return map;
for (const code of codes) map.set(code, { ...EMPTY_BACKFILL });
const products = await client.query(
`SELECT s.sku_code,
COALESCE(NULLIF(TRIM(pc.unit), ''), NULLIF(TRIM(s.unit), '')) AS unit,
NULLIF(TRIM(s.origin), '') AS origin,
COALESCE(NULLIF(TRIM(pc.parent_code), ''), NULLIF(TRIM(s.category_code), '')) AS category_code,
COALESCE(NULLIF(TRIM(c.category_name), ''), NULLIF(TRIM(pcat.name), '')) AS category_name
FROM skus s
LEFT JOIN product_catalog pc ON pc.item_type = 'product' AND pc.code = s.sku_code
LEFT JOIN categories c ON c.category_code = COALESCE(NULLIF(TRIM(pc.parent_code), ''), NULLIF(TRIM(s.category_code), ''))
LEFT JOIN product_catalog pcat ON pcat.item_type = 'category' AND pcat.code = COALESCE(NULLIF(TRIM(pc.parent_code), ''), NULLIF(TRIM(s.category_code), ''))
WHERE s.sku_code = ANY($1::text[])`,
[codes]
);
for (const row of products.rows) {
const cur = map.get(String(row.sku_code));
if (!cur) continue;
cur.unit = trimText(row.unit) || null;
cur.origin = trimText(row.origin) || null;
cur.category_code = trimText(row.category_code) || null;
cur.category_name = trimText(row.category_name) || null;
}
const last = await client.query(
`SELECT DISTINCT ON (sku_code)
sku_code,
cost_price,
storage_zone,
to_char(production_date, 'YYYY-MM-DD') AS production_date,
to_char(expiry_date, 'YYYY-MM-DD') AS expiry_date,
to_char(created_at AT TIME ZONE 'Asia/Shanghai', 'YYYYMMDDHH24MISS') AS created_at
FROM inventory
WHERE sku_code = ANY($1::text[])
ORDER BY sku_code, created_at DESC`,
[codes]
);
for (const row of last.rows) {
const cur = map.get(String(row.sku_code));
if (!cur) continue;
cur.last_cost_price = toNumOrNull(row.cost_price);
cur.last_storage_zone = trimText(row.storage_zone) || null;
cur.last_inbound_at = trimText(row.created_at) || null;
const pd = trimText(row.production_date);
const ed = trimText(row.expiry_date);
if (pd && ed) {
const days = Math.round(
(Date.parse(`${ed}T00:00:00Z`) - Date.parse(`${pd}T00:00:00Z`)) / 86400000
);
cur.last_shelf_life_days = Number.isFinite(days) && days > 0 ? days : null;
}
}
return map;
}
export interface InboundSkuOption {
sku_code: string;
sku_name: string;
spec: string | null;
brand: string | null;
unit: string | null;
origin: string | null;
category_code: string | null;
category_name: string | null;
backfill: InboundLineBackfill;
}
/**
* 「直接选择已有商品」(2026-10-11 开发者需求):按关键词检索商品档案,并带**与拍照识别同一份**回填
* (单位/产地/分类 + 最近一批的成本价/存放区域/保质期天数)。设计见
* docs/design/20261011-入库直接选择已有商品并按上次设置预填.md。
*
* 为什么不复用 `/processing/standalone/sku-options`:那个接口权限是 `processing_manage`(库存角色没有),
* 且不返回回填数据。本函数口径一律复用 `loadInboundBackfill`,不另写一套"上次值"算法。
*
* ⚠️ **不带出生产日期**(开发者原话:「生产日期需要其自己再次填写,因为同一个商品生产日期肯定是不一样的」):
* 本结构里没有 `production_date`,前端拿到后也不会去填 —— 见前端单测钉死。
*/
export async function listInboundSkuOptions(input: {
branchCode?: string | null;
search?: string | null;
limit?: number;
}): Promise<InboundSkuOption[]> {
const branchCode = trimText(input.branchCode);
if (!branchCode) return [];
const search = trimText(input.search);
const limit = Math.min(50, Math.max(1, Number(input.limit) || 20));
const client = await pool.connect();
try {
const result = await client.query(
`SELECT s.sku_code,
COALESCE(NULLIF(TRIM(s.sku_name), ''), s.sku_code) AS sku_name,
NULLIF(TRIM(s.spec), '') AS spec,
NULLIF(TRIM(s.brand), '') AS brand
FROM skus s
WHERE s.status = 1
AND ($2 = '' OR s.branch_code IS NULL OR s.branch_code = $2)
AND (
$3 = ''
OR COALESCE(s.sku_code, '') ILIKE '%' || $3 || '%'
OR COALESCE(s.sku_name, '') ILIKE '%' || $3 || '%'
)
ORDER BY s.sku_name ASC, s.sku_code ASC
LIMIT $1`,
[limit, branchCode, search]
);
const codes = result.rows.map((r) => String(r.sku_code));
const backfillMap = await loadInboundBackfill(client, codes);
return result.rows.map((r) => {
const code = String(r.sku_code);
const backfill = backfillMap.get(code) || { ...EMPTY_BACKFILL };
return {
sku_code: code,
sku_name: String(r.sku_name || code),
spec: r.spec ? String(r.spec) : null,
brand: r.brand ? String(r.brand) : null,
unit: backfill.unit,
origin: backfill.origin,
category_code: backfill.category_code,
category_name: backfill.category_name,
backfill,
};
});
} finally {
client.release();
}
}
/** 已有存放区域:从库存表取去重值(存放区域是自由文本,无独立表) */
export async function listStorageZones(): Promise<string[]> {
const res = await pool.query(
`SELECT DISTINCT storage_zone FROM inventory
WHERE storage_zone IS NOT NULL AND TRIM(storage_zone) <> ''
ORDER BY storage_zone
LIMIT 200`
);
return res.rows.map((r) => String(r.storage_zone));
}
/** 识别一张或多张图里的多行商品,并逐行匹配商品库。 */
export async function recognizeInboundLinesFromImage(input: {
imageBase64?: string | null;
imagesBase64?: string[] | null;
branchCode?: string | null;
}): Promise<RecognizeInboundLinesResult> {
const images = normalizeRecognizedImages(input);
const branchCode = trimText(input.branchCode) || undefined;
if (!images.length) {
return { kind: 'none', items: [], message: '请先拍照或选择图片' };
}
const options = buildWeighStationLlmOptions(branchCode);
if (!(await hasRuntimeConfig(options))) {
return {
kind: 'none',
items: [],
no_llm: true,
message: '未配置多模态识别(LLM),请手动添加商品',
};
}
// 已有分类列表:注入提示词供 AI 选分类,并用于校验 AI 返回的编码(防止自造)
const categoryMap = new Map<string, string>();
const categoryNameToCode = new Map<string, string>();
const categoryLines: string[] = [];
try {
// 不按分公司过滤(避免 branch_code 大小写/取值不一致时整列漏掉)——与前端分类选择器同源,取该租户全部启用分类
const categoryRes = await pool.query(
`SELECT DISTINCT ON (category_code) category_code, category_name
FROM categories
WHERE status = 1
ORDER BY category_code, branch_code NULLS FIRST`
);
for (const row of categoryRes.rows) {
const code = trimText(row.category_code);
if (!code || categoryMap.has(code)) continue;
const name = trimText(row.category_name) || code;
categoryMap.set(code, name);
const nameKey = normalizeKey(name);
if (nameKey && !categoryNameToCode.has(nameKey)) categoryNameToCode.set(nameKey, code);
categoryLines.push(`${code}:${name}`);
}
} catch (error) {
console.warn('[stock-inbound-batch] load categories failed:', error);
}
let parsed: { kind: 'document' | 'goods' | 'none'; items: unknown[] } = { kind: 'none', items: [] };
try {
const resolved = await resolvePrompt('stock_inbound.recognize.lines', {
branchCode,
vars: { category_list: categoryLines.join('\n') },
});
// 多图一次性交给模型(可自行合并同一商品);单图退化为 callWithImage
const raw = await callWithImages(resolved.systemPrompt, images, options);
parsed = parseItemsJson(raw);
if (!parsed.items.length && images.length > 1) {
// 多图单次调用为空 → 逐图回退,避免因多图能力缺失而整批识别失效
const merged: unknown[] = [];
let kind: 'document' | 'goods' | 'none' = 'none';
for (const img of images) {
const partRaw = await callWithImage(resolved.systemPrompt, img, options);
const part = parseItemsJson(partRaw);
if (part.kind !== 'none') kind = part.kind;
merged.push(...part.items);
}
parsed = { kind, items: merged };
}
} catch (error) {
console.warn('[stock-inbound-batch] recognize failed:', error);
return { kind: 'none', items: [], message: '识别失败,请重试或手动添加商品' };
}
const rows = parsed.items.slice(0, MAX_LINES);
const client = await pool.connect();
try {
// 1) 逐行取候选项(品名收窄 + 打分由 listSimilarSkusForInbound 负责)
const staged: Array<{
record: Record<string, unknown>;
itemName: string;
spec: string | null;
candidates: Array<{
sku_code: string;
sku_name: string;
spec: string | null;
brand: string | null;
unit: string | null;
quote_cost: number | null;
}>;
}> = [];
for (const row of rows) {
const record = row as Record<string, unknown>;
const itemName = trimText(record.item_name);
if (!itemName) continue;
const spec = trimText(record.spec) || null;
const candidates = await listSimilarSkusForInbound(client, {
name: itemName,
spec,
branchCode,
limit: 8,
});
staged.push({ record, itemName, spec, candidates });
}
// 2) 一次性取「最近一批」回填数据(成本/区域/保质期天数 + 商品单位/分类)
const backfillMap = await loadInboundBackfill(
client,
staged.flatMap((s) => s.candidates.map((c) => c.sku_code))
);
// 3) 组装:候选项带 backfill;选定 SKU(唯一命中→直接选;多候选→选最近入库)
const items: InboundRecognizedLine[] = staged.map(({ record, itemName, spec, candidates }) => {
const withBf = candidates.map((c) => ({
sku_code: c.sku_code,
sku_name: c.sku_name,
spec: c.spec,
brand: c.brand,
unit: c.unit,
quote_cost: c.quote_cost,
backfill: backfillMap.get(c.sku_code) ?? { ...EMPTY_BACKFILL },
}));
const nameKey = normalizeKey(itemName);
const specKey = normalizeKey(spec);
const nameMatches = withBf.filter((c) => normalizeKey(c.sku_name) === nameKey);
const exactMatches = specKey
? nameMatches.filter((c) => normalizeKey(c.spec) === specKey)
: nameMatches;
let selected: string | null = null;
if (exactMatches.length === 1) {
selected = exactMatches[0].sku_code;
} else if (nameMatches.length === 1) {
selected = nameMatches[0].sku_code;
} else {
const pool = exactMatches.length ? exactMatches : nameMatches;
const latest = pool
.filter((c) => c.backfill.last_inbound_at)
.sort((a, b) =>
String(b.backfill.last_inbound_at).localeCompare(String(a.backfill.last_inbound_at))
)[0];
selected = latest?.sku_code ?? null;
}
const selectedBackfill = selected
? withBf.find((c) => c.sku_code === selected)?.backfill ?? null
: null;
const aiCategoryRaw = trimText(record.category_code);
const categoryCode =
(aiCategoryRaw && categoryMap.has(aiCategoryRaw) ? aiCategoryRaw : null) ||
(aiCategoryRaw ? categoryNameToCode.get(normalizeKey(aiCategoryRaw)) ?? null : null);
return {
item_name: itemName,
spec,
unit: trimText(record.unit) || null,
origin: trimText(record.origin) || null,
qty: toNumOrNull(record.qty),
unit_cost: toNumOrNull(record.unit_cost),
production_date: normalizeRecognizedDate(record.production_date),
// 保质期:提示词要求模型给「数值 + 单位(年/月/日)」,这里组装回**原文**落库(与库存口径一致);
// 兼容仍返回旧字段 shelf_life 原文 的机型/旧提示词缓存
shelf_life:
composeShelfLifeText(record.shelf_life_value, record.shelf_life_unit) ||
trimText(record.shelf_life) ||
null,
category_code: categoryCode,
category_name: categoryCode ? categoryMap.get(categoryCode) ?? null : null,
confidence: toNumOrNull(record.confidence) ?? 0,
matched: {
sku_code: selected,
candidates: withBf,
backfill: selectedBackfill,
},
};
});
// 兜底:模型漏给分类的行,用文本分类提示词补一次(保证「待新建」行有分类可选)
if (categoryLines.length) {
const missing = items.filter((it) => !it.category_code && trimText(it.item_name));
if (missing.length) {
try {
const classifyPrompt = await resolvePrompt('order.classify.category', {
branchCode,
vars: { category_list: categoryLines.join('\n') },
});
const rawClassify = await callWithText(
classifyPrompt.systemPrompt,
missing.map((it) => it.item_name).join('\n'),
options
);
const parsedClassify = parseItemsJson(rawClassify);
const byName = new Map<string, string>();
for (const row of parsedClassify.items as Array<Record<string, unknown>>) {
const nm = trimText(row?.originalName);
const cd = trimText(row?.categoryCode);
if (nm && cd) byName.set(normalizeKey(nm), cd);
}
for (const it of missing) {
const code = byName.get(normalizeKey(it.item_name));
if (code && categoryMap.has(code)) {
it.category_code = code;
it.category_name = categoryMap.get(code) ?? null;
}
}
} catch (error) {
console.warn('[stock-inbound-batch] category fallback failed:', error);
}
}
}
return { kind: parsed.kind, items };
} finally {
client.release();
}
}
export interface BatchInboundRowInput {
sku_code?: string | null;
/** 未匹配商品时的建品信息(须含分类) */
new_product?: {
name: string;
category_code?: string | null;
spec?: string | null;
brand?: string | null;
unit?: string | null;
origin?: string | null;
} | null;
qty: number;
unit_cost?: number | null;
production_date?: string | null;
/** 保质期原文(如「7天」「6个月」);服务端据此与生产日期推算 expiry_date */
shelf_life?: string | null;
storage_zone?: string | null;
}
export interface BatchInboundCommon {
production_date?: string | null;
storage_zone?: string | null;
}
export interface BatchStockInboundRowsResult extends BulkStockInboundResult {
created_count: number;
}
function failedRow(args: {
rowNumber: number;
skuCode: string;
qty: number;
storageZone: string | null;
error: string;
}): StockImportRowResult {
return {
rowNumber: args.rowNumber,
sku_code: args.skuCode,
sku_name: null,
unit: null,
batch_no: null,
qty: Number.isFinite(args.qty) ? args.qty : 0,
unit_cost: 0,
mode: 'failed',
inventory_id: null,
storage_zone: args.storageZone,
error: args.error,
};
}
/**
* 批量入库:缺 sku_code 的行先建品(各自事务,失败不拖累他行),再统一走 bulkStockInbound。
* 整批统一的「生产日期 / 仓库区域」只作用到行内未单独填写的行。
*/
export async function batchStockInboundRows(input: {
branchCode: string;
operatorId?: string | null;
rows: BatchInboundRowInput[];
common?: BatchInboundCommon | null;
/** 库存流水备注(区分 Web / 小程序入口) */
remark?: string | null;
}): Promise<BatchStockInboundRowsResult> {
const branchCode = trimText(input.branchCode);
if (!branchCode) {
throw Object.assign(new Error('请选择当前操作分公司'), { status: 400, code: 'branch_required' });
}
const rows = Array.isArray(input.rows) ? input.rows : [];
if (!rows.length) {
throw Object.assign(new Error('没有可入库的行'), { status: 400, code: 'empty_rows' });
}
const common = input.common || {};
const bulkRows: StockImportRowInput[] = [];
const failed: StockImportRowResult[] = [];
let createdCount = 0;
const client = await pool.connect();
try {
for (let i = 0; i < rows.length; i += 1) {
const row = rows[i];
const rowNumber = i + 1;
const qty = Number(row.qty);
const storageZone = trimText(row.storage_zone) || trimText(common.storage_zone) || null;
let skuCode = trimText(row.sku_code);
if (!Number.isFinite(qty) || qty <= 0) {
failed.push(
failedRow({ rowNumber, skuCode, qty, storageZone, error: '入库数量须大于 0' })
);
continue;
}
if (!skuCode) {
const name = trimText(row.new_product?.name);
if (!name) {
failed.push(
failedRow({
rowNumber,
skuCode: '',
qty,
storageZone,
error: '未匹配商品,也未提供新建信息',
})
);
continue;
}
try {
await client.query('BEGIN');
const created = await createCatalogSkuForInbound(client, {
name,
parentCode: trimText(row.new_product?.category_code),
branchCode,
unit: row.new_product?.unit,
spec: row.new_product?.spec,
brand: row.new_product?.brand,
origin: row.new_product?.origin,
stockMode: 'inventory',
});
await client.query('COMMIT');
skuCode = created.skuCode;
createdCount += 1;
} catch (e: unknown) {
try {
await client.query('ROLLBACK');
} catch {
/* ignore */
}
failed.push(
failedRow({
rowNumber,
skuCode: '',
qty,
storageZone,
error: (e as { message?: string })?.message || '新建商品失败',
})
);
continue;
}
}
const productionDate =
trimText(row.production_date) || trimText(common.production_date) || null;
bulkRows.push({
rowNumber,
skuCode,
qty,
unitCost: toNumOrNull(row.unit_cost),
productionDate,
// 保质期原文随行落库(`inventory.shelf_life`);有效期在 writeStockImportRow 里由它推算
shelfLife: trimText(row.shelf_life) || null,
storageZone,
});
}
} finally {
client.release();
}
const bulk: BulkStockInboundResult = bulkRows.length
? await bulkStockInbound({
branchCode,
operatorId: input.operatorId,
rows: bulkRows,
remark: input.remark,
})
: { results: [], ok_count: 0, failed_count: 0, new_batch_count: 0, accumulated_count: 0 };
const results = [...failed, ...bulk.results].sort(
(a, b) => (a.rowNumber || 0) - (b.rowNumber || 0)
);
const ok = results.filter((r) => r.mode !== 'failed');
return {
results,
ok_count: ok.length,
failed_count: results.length - ok.length,
new_batch_count: ok.filter((r) => r.mode === 'new_batch').length,
accumulated_count: ok.filter((r) => r.mode === 'accumulated').length,
created_count: createdCount,
};
}