inventory/product_catalog 加 storage_zone 并补 (sku_code,batch_no) 唯一约束;新增 bulkStockInbound(200/块、行级 SAVEPOINT、同批次累加、成本可空)与 Web 批量导入弹窗;库存页加区域列/筛选,仅有可用默认关闭。
373 lines
12 KiB
TypeScript
373 lines
12 KiB
TypeScript
export interface BulkImportResult {
|
||
success: number;
|
||
skipped: number;
|
||
failed: number;
|
||
errors: string[];
|
||
}
|
||
|
||
const UTF8_BOM = '\uFEFF';
|
||
|
||
/**
|
||
* CSV 公式注入防护(Excel / WPS 会把 `=` `+` `-` `@` 以及制表符/回车开头的单元格当公式执行,
|
||
* 即 CSV / Formula Injection)。
|
||
*
|
||
* 设计约束(2026-09-24 开发者要求:**不得影响业务流程、不得导致 CSV 无法导出**):
|
||
* 1. 只对「看起来像公式」的单元格加一个文本标记前缀,**纯数字一律不动**
|
||
* (`-5.00` / `+3.5` / `-1e5` 输出字节不变,财务数字列零影响);
|
||
* 2. 本函数**永不抛错**:任何意外都退回原字符串,导出流程与旧行为一致。
|
||
*
|
||
* 注意:CSV 里给单元格加引号(`"=1+1"`)**不能**防这个 —— 引号是解析层,Excel 拿到的
|
||
* 单元格值仍是 `=1+1`,照样按公式解释;必须改内容本身。
|
||
*/
|
||
const CSV_FORMULA_PREFIX = /^[=+\-@\t\r]/;
|
||
const PLAIN_NUMBER = /^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$/;
|
||
/** 超长数字串一律按可疑处理(正常金额/数量不会超过这个长度,避免极端输入拖慢正则) */
|
||
const CSV_NUMBER_MAX_LEN = 32;
|
||
const CSV_TEXT_PREFIX = "'";
|
||
|
||
/** 给「非纯数字的公式前缀」值加文本标记;纯数字与普通文本原样返回。永不抛错。 */
|
||
export function guardCsvFormulaInjection(value: string): string {
|
||
try {
|
||
if (!CSV_FORMULA_PREFIX.test(value)) return value;
|
||
if (value.length <= CSV_NUMBER_MAX_LEN && PLAIN_NUMBER.test(value.trim())) return value;
|
||
return `${CSV_TEXT_PREFIX}${value}`;
|
||
} catch {
|
||
return value;
|
||
}
|
||
}
|
||
|
||
let xlsxModule: typeof import('xlsx') | null = null;
|
||
|
||
async function loadXlsx() {
|
||
if (!xlsxModule) {
|
||
xlsxModule = await import('xlsx');
|
||
}
|
||
return xlsxModule;
|
||
}
|
||
|
||
/** 归一化表头用于打分:去空格/小写/全角括号转半角/去尾* */
|
||
function normalizeForScore(s: string): string {
|
||
return String(s || '')
|
||
.trim()
|
||
.toLowerCase()
|
||
.replace(/\s+/g, '')
|
||
.replace(/(/g, '(')
|
||
.replace(/)/g, ')')
|
||
.replace(/\*$/g, '');
|
||
}
|
||
|
||
const HEADER_SCORE_KEYWORDS = [
|
||
'商品', '名称', '品名', '分类', '单位', '规格', '品牌', '厂家', '编码', '条码',
|
||
'单价', '价格', '售价', '成本', '序号', '状态', '生鲜', '排序', '阈值', '拍照',
|
||
'name', 'sku', 'unit', 'price', 'spec', 'brand', 'code', 'category', 'item',
|
||
];
|
||
|
||
/**
|
||
* 自动检测表头行:扫描前 maxScan 行,按"含字段词 + 非空率"打分,
|
||
* 返回得分最高的行索引(0 基);都不像表头则返回 0(回退第 1 行)。
|
||
*/
|
||
function detectHeaderRowIndex(matrix: (string | number)[][], maxScan = 5): number {
|
||
const limit = Math.min(maxScan, matrix.length);
|
||
let bestIdx = 0;
|
||
let bestScore = -1;
|
||
for (let r = 0; r < limit; r += 1) {
|
||
const row = matrix[r] || [];
|
||
const cells = row.map((c) => String(c ?? '').trim());
|
||
const nonEmpty = cells.filter(Boolean);
|
||
if (nonEmpty.length < 2) continue; // 至少 2 列才算表头候选
|
||
let hits = 0;
|
||
for (const cell of nonEmpty) {
|
||
const norm = normalizeForScore(cell);
|
||
if (!norm) continue;
|
||
if (HEADER_SCORE_KEYWORDS.some((kw) => norm.includes(kw))) hits += 1;
|
||
}
|
||
const hitRatio = hits / nonEmpty.length;
|
||
// 纯数字行(如序号/数据行)不像表头:数字占比过高则降权
|
||
const numericCount = nonEmpty.filter((c) => /^-?\d+(\.\d+)?$/.test(c)).length;
|
||
const numericRatio = numericCount / nonEmpty.length;
|
||
const score = hitRatio * 2 + (nonEmpty.length / Math.max(cells.length, 1)) - numericRatio;
|
||
if (score > bestScore) {
|
||
bestScore = score;
|
||
bestIdx = r;
|
||
}
|
||
}
|
||
return bestScore > 0 ? bestIdx : 0;
|
||
}
|
||
|
||
function escapeCsvCell(value: unknown): string {
|
||
const str = guardCsvFormulaInjection(String(value ?? ''));
|
||
if (/[",\n\r]/.test(str)) {
|
||
return `"${str.replace(/"/g, '""')}"`;
|
||
}
|
||
return str;
|
||
}
|
||
|
||
function normalizeExcelRows(rows: (string | number | null | undefined)[][]) {
|
||
return rows.map((row) => row.map((cell) => (cell === null || cell === undefined ? '' : cell)));
|
||
}
|
||
|
||
/** 长数字(如 19 位税收编码)必须按文本写入,否则 Excel 会科学计数法并丢精度 */
|
||
function forceTextColumns(
|
||
X: typeof import('xlsx'),
|
||
ws: import('xlsx').WorkSheet,
|
||
headers: string[],
|
||
textHeaders: string[]
|
||
) {
|
||
if (!ws['!ref'] || !textHeaders.length) return;
|
||
const textCols = new Set<number>();
|
||
headers.forEach((header, index) => {
|
||
if (textHeaders.includes(header)) textCols.add(index);
|
||
});
|
||
if (!textCols.size) return;
|
||
|
||
const range = X.utils.decode_range(ws['!ref']);
|
||
for (let row = range.s.r + 1; row <= range.e.r; row += 1) {
|
||
for (const col of textCols) {
|
||
const address = X.utils.encode_cell({ r: row, c: col });
|
||
const cell = ws[address];
|
||
if (!cell || cell.v === null || cell.v === undefined || cell.v === '') continue;
|
||
const value = String(cell.v);
|
||
ws[address] = { t: 's', v: value, z: '@' };
|
||
}
|
||
}
|
||
}
|
||
|
||
async function buildWorksheet(
|
||
headers: string[],
|
||
rows: (string | number)[][],
|
||
textHeaders: string[] = []
|
||
) {
|
||
const X = await loadXlsx();
|
||
const ws = X.utils.aoa_to_sheet([headers, ...rows]);
|
||
ws['!cols'] = headers.map((header) => ({ wch: Math.max(12, header.length + 4) }));
|
||
forceTextColumns(X, ws, headers, textHeaders);
|
||
return ws;
|
||
}
|
||
|
||
/** CSV 导出(带 UTF-8 BOM,避免 Windows Excel 中文乱码) */
|
||
export function downloadCsv(
|
||
filename: string,
|
||
headers: string[],
|
||
rows: (string | number | null | undefined)[][]
|
||
) {
|
||
const lines = [
|
||
headers.map(escapeCsvCell).join(','),
|
||
...normalizeExcelRows(rows).map((row) => row.map(escapeCsvCell).join(',')),
|
||
];
|
||
const blob = new Blob([UTF8_BOM + lines.join('\r\n')], {
|
||
type: 'text/csv;charset=utf-8;',
|
||
});
|
||
const link = document.createElement('a');
|
||
const url = URL.createObjectURL(blob);
|
||
link.href = url;
|
||
link.download = filename.endsWith('.csv') ? filename : `${filename}.csv`;
|
||
document.body.appendChild(link);
|
||
link.click();
|
||
document.body.removeChild(link);
|
||
URL.revokeObjectURL(url);
|
||
}
|
||
|
||
/** Excel 数据导出(.xlsx,中文兼容最好) */
|
||
export async function downloadExcelData(
|
||
filename: string,
|
||
sheetName: string,
|
||
headers: string[],
|
||
rows: (string | number | null | undefined)[][]
|
||
) {
|
||
await downloadExcelWorkbook(filename, [{ name: sheetName, headers, rows }]);
|
||
}
|
||
|
||
/** 多工作表 Excel 导出 */
|
||
export async function downloadExcelWorkbook(
|
||
filename: string,
|
||
sheets: Array<{
|
||
name: string;
|
||
headers: string[];
|
||
rows: (string | number | null | undefined)[][];
|
||
/** 必须按文本导出的列名(避免长数字被 Excel 改成科学计数法) */
|
||
textHeaders?: string[];
|
||
}>
|
||
) {
|
||
const X = await loadXlsx();
|
||
const wb = X.utils.book_new();
|
||
for (const sheet of sheets) {
|
||
X.utils.book_append_sheet(
|
||
wb,
|
||
await buildWorksheet(
|
||
sheet.headers,
|
||
normalizeExcelRows(sheet.rows) as (string | number)[][],
|
||
sheet.textHeaders || []
|
||
),
|
||
sheet.name.slice(0, 31)
|
||
);
|
||
}
|
||
X.writeFile(wb, filename.endsWith('.xlsx') ? filename : `${filename}.xlsx`);
|
||
}
|
||
|
||
export async function downloadExcelTemplate(
|
||
filename: string,
|
||
sheetName: string,
|
||
headers: string[],
|
||
exampleRows: (string | number)[][],
|
||
extraSheets?: Array<{ name: string; headers: string[]; rows: (string | number)[][] }>
|
||
) {
|
||
const X = await loadXlsx();
|
||
const wb = X.utils.book_new();
|
||
X.utils.book_append_sheet(wb, await buildWorksheet(headers, exampleRows), sheetName);
|
||
if (extraSheets) {
|
||
for (const sheet of extraSheets) {
|
||
X.utils.book_append_sheet(wb, await buildWorksheet(sheet.headers, sheet.rows), sheet.name);
|
||
}
|
||
}
|
||
X.writeFile(wb, filename);
|
||
}
|
||
|
||
export interface ParsedExcel {
|
||
rows: Record<string, string>[];
|
||
headers: string[];
|
||
/** 表头行索引(0 基,相对整个 sheet) */
|
||
headerRowIndex: number;
|
||
}
|
||
|
||
export async function parseExcelFileDetailed(
|
||
file: File,
|
||
options?: {
|
||
preferredSheetNames?: string[];
|
||
requiredHeaderHints?: string[];
|
||
}
|
||
): Promise<ParsedExcel> {
|
||
const X = await loadXlsx();
|
||
const isCsv =
|
||
/\.csv$/i.test(file.name) || file.type === 'text/csv' || file.type === 'application/csv';
|
||
let workbook: any;
|
||
if (isCsv) {
|
||
// CSV:按文本读,优先 UTF-8(含 BOM);出现替换字符时回退 GBK(中文 CSV 常见)
|
||
const buf = await file.arrayBuffer();
|
||
let text = new TextDecoder('utf-8', { fatal: false }).decode(buf);
|
||
if (text.charCodeAt(0) === 0xfeff) text = text.slice(1);
|
||
if (text.includes('\uFFFD')) {
|
||
try {
|
||
text = new TextDecoder('gbk', { fatal: false }).decode(buf);
|
||
} catch {
|
||
/* 保持 utf-8 结果 */
|
||
}
|
||
}
|
||
workbook = X.read(text, { type: 'string' });
|
||
} else {
|
||
const buffer = await file.arrayBuffer();
|
||
workbook = X.read(buffer, { type: 'array' });
|
||
}
|
||
if (workbook.SheetNames.length === 0) return { rows: [], headers: [], headerRowIndex: 0 };
|
||
|
||
const readSheetHeaders = (sheetName: string) => {
|
||
const sheet = workbook.Sheets[sheetName];
|
||
const matrix = X.utils.sheet_to_json<(string | number)[]>(sheet, {
|
||
header: 1,
|
||
defval: '',
|
||
raw: false,
|
||
});
|
||
if (matrix.length === 0) return [] as string[];
|
||
return matrix[detectHeaderRowIndex(matrix)].map((cell) => String(cell ?? '').trim());
|
||
};
|
||
|
||
const sheetMatchesHints = (sheetName: string) => {
|
||
if (!options?.requiredHeaderHints?.length) return false;
|
||
const headers = readSheetHeaders(sheetName).map(normalizeHeader);
|
||
return options.requiredHeaderHints.some((hint) =>
|
||
headers.some((header) => header.includes(normalizeHeader(hint)))
|
||
);
|
||
};
|
||
|
||
let sheetName = workbook.SheetNames[0];
|
||
const preferredSheet = options?.preferredSheetNames
|
||
?.map((name: string) => workbook.SheetNames.find((sheet: string) => sheet.includes(name)))
|
||
.find(Boolean);
|
||
if (preferredSheet) {
|
||
sheetName = preferredSheet;
|
||
}
|
||
const hintedSheet = workbook.SheetNames.find((name: string) => sheetMatchesHints(name));
|
||
if (hintedSheet) {
|
||
sheetName = hintedSheet;
|
||
}
|
||
|
||
const sheet = workbook.Sheets[sheetName];
|
||
const matrix = X.utils.sheet_to_json<(string | number)[]>(sheet, {
|
||
header: 1,
|
||
defval: '',
|
||
raw: false,
|
||
});
|
||
|
||
const headerRowIndex = detectHeaderRowIndex(matrix);
|
||
if (matrix.length < headerRowIndex + 2) {
|
||
return { rows: [], headers: matrix[headerRowIndex]?.map((c) => String(c ?? '').trim()) || [], headerRowIndex };
|
||
}
|
||
|
||
const headers = matrix[headerRowIndex].map((cell) => String(cell ?? '').trim());
|
||
const rows = matrix
|
||
.slice(headerRowIndex + 1)
|
||
.filter((row) => row.some((cell) => String(cell ?? '').trim()))
|
||
.map((row, rowIndex) => {
|
||
const record: Record<string, string> = { __row: String(headerRowIndex + rowIndex + 2) };
|
||
headers.forEach((header, index) => {
|
||
if (!header) return;
|
||
record[header] = String(row[index] ?? '').trim();
|
||
});
|
||
return record;
|
||
});
|
||
return { rows, headers, headerRowIndex };
|
||
}
|
||
|
||
export async function parseExcelFile(
|
||
file: File,
|
||
options?: {
|
||
preferredSheetNames?: string[];
|
||
requiredHeaderHints?: string[];
|
||
}
|
||
): Promise<Record<string, string>[]> {
|
||
const detailed = await parseExcelFileDetailed(file, options);
|
||
return detailed.rows;
|
||
}
|
||
|
||
export function getCell(row: Record<string, string>, ...keys: string[]): string {
|
||
for (const key of keys) {
|
||
if (row[key]) return row[key].trim();
|
||
}
|
||
|
||
const normalizedKeys = keys.map((key) => normalizeHeader(key));
|
||
for (const [header, value] of Object.entries(row)) {
|
||
if (header === '__row') continue;
|
||
if (normalizedKeys.includes(normalizeHeader(header))) {
|
||
return value.trim();
|
||
}
|
||
}
|
||
|
||
return '';
|
||
}
|
||
|
||
function normalizeHeader(header: string) {
|
||
return header.replace(/\*$/g, '').replace(/\([^)]*\)/g, '').trim();
|
||
}
|
||
|
||
export function parseBooleanText(value: string, defaultValue = true): boolean {
|
||
const text = value.trim().toLowerCase();
|
||
if (!text) return defaultValue;
|
||
if (['是', 'yes', 'y', 'true', '1', '启用'].includes(text)) return true;
|
||
if (['否', 'no', 'n', 'false', '0', '停用'].includes(text)) return false;
|
||
return defaultValue;
|
||
}
|
||
|
||
export function parseStatusText(value: string, defaultValue = 1): number {
|
||
const text = value.trim().toLowerCase();
|
||
if (!text) return defaultValue;
|
||
if (['启用', '1', 'yes', 'true', '是'].includes(text)) return 1;
|
||
if (['停用', '0', 'no', 'false', '否'].includes(text)) return 0;
|
||
return defaultValue;
|
||
}
|
||
|
||
export function parseNumberText(value: string, defaultValue: number): number {
|
||
const text = value.trim();
|
||
if (!text) return defaultValue;
|
||
const parsed = Number(text);
|
||
return Number.isFinite(parsed) ? parsed : defaultValue;
|
||
}
|