- T1 资金/库存/报价/自采 P1(BIZ-1/2/3/4/10/13/14) - T2 主系统反向事件墓碑/改派/孤儿处理(BIZ-6/8/9) - T3 选分公司 ticket、trust proxy、角色权限收口(SEC-2/3/4) - T4 缺列/RLS/tenant 名单/FK/迁移执行器(DATA-1..8) - T5 401 登出/分页/映射口径/blob/ZIP 中文名(FE-1..4/BIZ-15) - T6 测试脚本目标守卫/config fail-fast/容器配置(OPS-2..8) - T7 前后端测试与 lint 门禁清零 - T8 应付卡片按关联订单日(口径 A) - T9 存储对象全链路归属校验、敏感列禁写、审计 target_id 超长修复
305 lines
11 KiB
TypeScript
305 lines
11 KiB
TypeScript
import React from 'react';
|
|
import { BulkImportModal } from '../BulkImportModal';
|
|
import { buildApiUrl } from '../../lib/apiConfig';
|
|
import { readAuthSessionRaw } from '../../lib/authSession';
|
|
import { getOperatingBranchHeader } from '../../utils/operatingBranch';
|
|
import {
|
|
parseExcelFile,
|
|
downloadExcelTemplate,
|
|
getCell,
|
|
type BulkImportResult,
|
|
} from '../../utils/excelImportExport';
|
|
import type { ImportFieldDef } from '../../utils/smartColumnMapping';
|
|
import {
|
|
fetchProductCatalog,
|
|
fetchCatalogCategories,
|
|
ensureCatalogCategoryChain,
|
|
generateCatalogProductCode,
|
|
insertCatalogProduct,
|
|
} from '../../utils/productCatalog';
|
|
import { useT } from '../../i18n';
|
|
import { notify } from '../../utils/notify';
|
|
|
|
const STOCK_IMPORT_HEADERS = [
|
|
'商品名称*',
|
|
'SKU编码',
|
|
'一级分类',
|
|
'二级分类',
|
|
'规格',
|
|
'单位*',
|
|
'品牌',
|
|
'数量*',
|
|
'成本价',
|
|
'批次号',
|
|
'生产日期',
|
|
'效期',
|
|
'仓库区域编号',
|
|
];
|
|
|
|
const STOCK_IMPORT_EXAMPLES: (string | number)[][] = [
|
|
['洋葱', '', '蔬菜', '根茎类', '散装', '斤', '', 10, 6, '', '', '', 'A-01'],
|
|
['土豆', '', '蔬菜', '根茎类', '中等', '斤', '', 20, '', '', '', '', 'A-02'],
|
|
];
|
|
|
|
/** 字段词典(键 = 智能映射后的行键;表头智能匹配,与商品导入同机制) */
|
|
export const STOCK_IMPORT_FIELD_DICT: ImportFieldDef[] = [
|
|
{ key: 'skuName', label: '商品名称', required: true, templateHeader: '商品名称*',
|
|
aliases: ['商品名称', '商品名', '品名', '名称', '产品名称', '货品名称', 'item', 'name', 'productname'],
|
|
patterns: [/品名|商品名|名称|品项/] },
|
|
{ key: 'skuCode', label: 'SKU编码', templateHeader: 'SKU编码',
|
|
aliases: ['sku编码', 'sku', '商品编码', '编码', '货号', 'code', 'skucode', 'barcode'],
|
|
patterns: [/sku|编码|货号|条码/] },
|
|
{ key: 'l1', label: '一级分类', templateHeader: '一级分类',
|
|
aliases: ['一级分类', '一级类目', '大类', '分类', '类目', '品类', 'category'],
|
|
patterns: [/一级|大类|分类|类目|品类/] },
|
|
{ key: 'l2', label: '二级分类', templateHeader: '二级分类',
|
|
aliases: ['二级分类', '二级类目', '小类', '子分类', '子类目', 'subcategory'],
|
|
patterns: [/二级|小类|子类/] },
|
|
{ key: 'spec', label: '规格', templateHeader: '规格', aliases: ['规格', '规格型号', '型号', 'spec'], patterns: [/规格|型号/] },
|
|
{ key: 'unit', label: '单位', templateHeader: '单位*', aliases: ['单位', '计量单位', '基本单位', 'unit', 'uom'], patterns: [/单位/] },
|
|
{ key: 'brand', label: '品牌', templateHeader: '品牌', aliases: ['品牌', '厂家', '厂商', 'brand'], patterns: [/品牌|厂家|厂商/] },
|
|
{ key: 'qty', label: '数量', required: true, templateHeader: '数量*',
|
|
aliases: ['数量', '入库数量', '库存数量', '数量(斤)', 'qty', 'quantity'], patterns: [/数量|库存|入库/] },
|
|
{ key: 'cost', label: '成本价', templateHeader: '成本价',
|
|
aliases: ['成本价', '成本', '进价', '单价', 'cost', 'unitcost'], patterns: [/成本|进价/] },
|
|
{ key: 'batch', label: '批次号', templateHeader: '批次号', aliases: ['批次号', '批次', 'batch', 'batchno'], patterns: [/批次/] },
|
|
{ key: 'prodDate', label: '生产日期', templateHeader: '生产日期', aliases: ['生产日期', '生产日', 'productiondate'], patterns: [/生产/] },
|
|
{ key: 'expiry', label: '效期', templateHeader: '效期', aliases: ['效期', '保质期至', '到期日', '保质期', 'expiry'], patterns: [/效期|保质|到期/] },
|
|
{ key: 'zone', label: '仓库区域编号', templateHeader: '仓库区域编号',
|
|
aliases: ['仓库区域编号', '区域编号', '库位', '库位号', '区域', 'zone', 'location'], patterns: [/区域|库位|货位/] },
|
|
];
|
|
|
|
const norm = (v: unknown) => String(v || '').trim().toLowerCase();
|
|
|
|
/** 数量容错:"10斤" / "10.5" / "10 斤" / "1,000" → 数字;无法识别返回 0 */
|
|
function parseQty(v: string): number {
|
|
const s = String(v || '').trim();
|
|
if (!s) return 0;
|
|
const cleaned = s.replace(/[^0-9.-]/g, '').replace(/(?!^)-/g, '');
|
|
const n = Number(cleaned);
|
|
return Number.isFinite(n) ? n : 0;
|
|
}
|
|
|
|
function authHeaders(): Record<string, string> {
|
|
const headers: Record<string, string> = {
|
|
'Content-Type': 'application/json',
|
|
...getOperatingBranchHeader(),
|
|
};
|
|
try {
|
|
const raw = readAuthSessionRaw();
|
|
if (raw) {
|
|
const session = JSON.parse(raw);
|
|
if (session?.access_token) headers.Authorization = `Bearer ${session.access_token}`;
|
|
}
|
|
} catch {
|
|
/* ignore */
|
|
}
|
|
return headers;
|
|
}
|
|
|
|
type ParsedRow = Record<string, string>;
|
|
|
|
type StockRow = {
|
|
idx: number;
|
|
skuCode: string;
|
|
name: string;
|
|
spec: string;
|
|
unit: string;
|
|
l1: string;
|
|
l2: string;
|
|
brand: string;
|
|
qty: number;
|
|
cost: string;
|
|
batchNo: string;
|
|
productionDate: string;
|
|
expiryDate: string;
|
|
zone: string;
|
|
};
|
|
|
|
function keysOf(key: string): string[] {
|
|
const f = STOCK_IMPORT_FIELD_DICT.find((x) => x.key === key);
|
|
return f ? [f.key, f.templateHeader, ...f.aliases] : [key];
|
|
}
|
|
|
|
function readRows(rows: ParsedRow[]): StockRow[] {
|
|
return rows.map((r, i) => ({
|
|
idx: i + 1,
|
|
skuCode: getCell(r, ...keysOf('skuCode')).trim(),
|
|
name: getCell(r, ...keysOf('skuName')).trim(),
|
|
spec: getCell(r, ...keysOf('spec')).trim(),
|
|
unit: getCell(r, ...keysOf('unit')).trim(),
|
|
l1: getCell(r, ...keysOf('l1')).trim(),
|
|
l2: getCell(r, ...keysOf('l2')).trim(),
|
|
brand: getCell(r, ...keysOf('brand')).trim(),
|
|
qty: parseQty(getCell(r, ...keysOf('qty'))),
|
|
cost: getCell(r, ...keysOf('cost')).trim(),
|
|
batchNo: getCell(r, ...keysOf('batch')).trim(),
|
|
productionDate: getCell(r, ...keysOf('prodDate')).trim(),
|
|
expiryDate: getCell(r, ...keysOf('expiry')).trim(),
|
|
zone: getCell(r, ...keysOf('zone')).trim(),
|
|
}));
|
|
}
|
|
|
|
async function parseRows(file: File, preMapped?: ParsedRow[]): Promise<StockRow[]> {
|
|
const rows = preMapped && preMapped.length ? preMapped : await parseExcelFile(file);
|
|
return readRows(rows).filter((r) => r.name || r.skuCode);
|
|
}
|
|
|
|
/** 去重:同「商品名 + 规格」只留首行(按你的口径) */
|
|
function dedupe(rows: StockRow[]): { kept: StockRow[]; skipped: number; invalid: number } {
|
|
const seen = new Set<string>();
|
|
const kept: StockRow[] = [];
|
|
let skipped = 0;
|
|
let invalid = 0;
|
|
for (const r of rows) {
|
|
if (!(r.name || r.skuCode) || !(r.qty > 0)) {
|
|
invalid += 1;
|
|
continue;
|
|
}
|
|
const key = `${norm(r.name)}|${norm(r.spec)}`;
|
|
if (seen.has(key)) {
|
|
skipped += 1;
|
|
continue;
|
|
}
|
|
seen.add(key);
|
|
kept.push(r);
|
|
}
|
|
return { kept, skipped, invalid };
|
|
}
|
|
|
|
async function doImport(
|
|
file: File,
|
|
preMapped: ParsedRow[] | undefined
|
|
): Promise<BulkImportResult> {
|
|
const rawRows: ParsedRow[] =
|
|
preMapped && preMapped.length ? preMapped : await parseExcelFile(file);
|
|
const rows = readRows(rawRows).filter((r) => r.name || r.skuCode || r.qty > 0);
|
|
const { kept, skipped, invalid } = dedupe(rows);
|
|
const errors: string[] = [];
|
|
let failed = invalid;
|
|
if (rows.length > 0 && kept.length === 0) {
|
|
const firstRaw = (rawRows[0] || {}) as Record<string, string>;
|
|
const headers = Object.keys(firstRaw)
|
|
.filter((k) => k !== '__row')
|
|
.join(' | ');
|
|
const qtyRaw = String(firstRaw['qty'] ?? firstRaw['数量'] ?? firstRaw['数量*'] ?? '');
|
|
errors.push(`未识别到可导入的「数量」。表头:${headers};首行数量原值=「${qtyRaw.slice(0, 30)}」`);
|
|
}
|
|
|
|
const catalog = await fetchProductCatalog();
|
|
let categories = await fetchCatalogCategories();
|
|
const keyOf = (n: string, s: string, u: string) => `${norm(n)}|${norm(s)}|${norm(u)}`;
|
|
const byKey = new Map(catalog.map((p) => [keyOf(p.name, p.spec || '', p.unit || ''), p.code]));
|
|
|
|
const payload: Record<string, unknown>[] = [];
|
|
for (const r of kept) {
|
|
let code = r.skuCode || byKey.get(keyOf(r.name, r.spec, r.unit)) || '';
|
|
if (!code) {
|
|
try {
|
|
const chain = await ensureCatalogCategoryChain(
|
|
categories,
|
|
r.l1 || '未分类',
|
|
r.l2 || undefined,
|
|
null
|
|
);
|
|
categories = chain.categories;
|
|
code = await generateCatalogProductCode();
|
|
await insertCatalogProduct({
|
|
code,
|
|
name: r.name,
|
|
parent_code: chain.code,
|
|
unit: r.unit || '斤',
|
|
spec: r.spec,
|
|
brand: r.brand,
|
|
stock_mode: 'inventory',
|
|
});
|
|
} catch (e: any) {
|
|
failed += 1;
|
|
errors.push(`#${r.idx} ${r.name}: ${e?.message || '建品失败'}`);
|
|
continue;
|
|
}
|
|
}
|
|
payload.push({
|
|
rowNumber: r.idx,
|
|
skuCode: code,
|
|
qty: r.qty,
|
|
unitCost: r.cost === '' ? null : Number(r.cost),
|
|
batchNo: r.batchNo || null,
|
|
productionDate: r.productionDate || null,
|
|
expiryDate: r.expiryDate || null,
|
|
storageZone: r.zone || null,
|
|
});
|
|
}
|
|
|
|
const res = await fetch(buildApiUrl('/workflow/inventory/import-stock'), {
|
|
method: 'POST',
|
|
headers: authHeaders(),
|
|
body: JSON.stringify({ rows: payload }),
|
|
});
|
|
const body = await res.json().catch(() => ({}));
|
|
if (!res.ok) throw new Error(body?.error_description || body?.error || '导入失败');
|
|
const data = body?.data || {};
|
|
for (const x of data.results || []) {
|
|
if (x.mode === 'failed') errors.push(`#${x.rowNumber} ${x.sku_code}: ${x.error}`);
|
|
}
|
|
return {
|
|
success: Number(data.ok_count) || 0,
|
|
skipped,
|
|
failed: failed + (Number(data.failed_count) || 0),
|
|
errors,
|
|
};
|
|
}
|
|
|
|
interface Props {
|
|
open: boolean;
|
|
onClose: () => void;
|
|
onDone: () => void;
|
|
}
|
|
|
|
export const StockImportModal: React.FC<Props> = ({ open, onClose, onDone }) => {
|
|
const t = useT();
|
|
|
|
const onDownloadTemplate = () =>
|
|
downloadExcelTemplate(
|
|
t('inventory.stockImport.templateFile'),
|
|
t('inventory.stockImport.sheet'),
|
|
STOCK_IMPORT_HEADERS,
|
|
STOCK_IMPORT_EXAMPLES
|
|
);
|
|
|
|
return (
|
|
<BulkImportModal
|
|
open={open}
|
|
title={t('inventory.stockImport.title')}
|
|
description={t('inventory.stockImport.hint')}
|
|
templateHint={t('inventory.stockImport.templateHint')}
|
|
infoAlert={t('inventory.stockImport.infoAlert')}
|
|
examplePreview={{ headers: STOCK_IMPORT_HEADERS, rows: STOCK_IMPORT_EXAMPLES }}
|
|
maxRowsHint={null}
|
|
onDownloadTemplate={onDownloadTemplate}
|
|
onClose={onClose}
|
|
onPreview={async (file, preMapped) => {
|
|
const rows = await parseRows(file, preMapped);
|
|
const { kept, skipped, invalid } = dedupe(rows);
|
|
return {
|
|
rowCount: rows.length,
|
|
willCreate: kept.length,
|
|
willSkip: skipped + invalid,
|
|
willFail: 0,
|
|
errors: rows.length === 0 ? [t('inventory.stockImport.nothingToImport')] : [],
|
|
};
|
|
}}
|
|
onImport={(file, preMapped) => doImport(file, preMapped)}
|
|
smartImport={{
|
|
importType: 'sku',
|
|
fields: STOCK_IMPORT_FIELD_DICT,
|
|
requiredHeaderHints: ['商品名称', '品名', '名称'],
|
|
}}
|
|
onComplete={() => {
|
|
notify.success(t('inventory.stockImport.done'));
|
|
onDone();
|
|
}}
|
|
/>
|
|
);
|
|
};
|