Files
SupplierSystem/src/utils/quoteBulkImport.ts
T
Ubuntu deb3e72750
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
chore: 以 AI 生鲜配送系统 当前版本作为 SupplierSystem 起点
来源仓库:jxc/ai-fresh-delivery
来源提交:f0b1a180e2deb7e4673b9d1c8542619f7bc0f73d
快照树:  09f679334ff38f0ff25e907961c94a8223bcaedd(与来源 HEAD 工作树逐字节一致,3801 个文件)

按约定本仓库不带任何历史提交:来源仓库的历史中含真实凭据
(生产 SSH 私钥 deploy/id_rsa_tencent、server/.env、.env.tencent/.env.production/.env.gitea、
deploy/小程序AppSecret.txt,其中 MP_APPSECRET / S3 AccessKey 经哈希比对与线上同值),
整包推送会把这些凭据永久带入本仓库,故只取「当前版本」的单提交快照。
供应商系统后续开发自本提交开始。
2026-10-08 17:35:43 +08:00

316 lines
9.7 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.
import {
BulkImportResult,
downloadExcelTemplate,
getCell,
parseExcelFile,
parseNumberText,
} from './excelImportExport';
import { fetchCategoryRows, type CategoryRow } from './categories';
export const QUOTE_IMPORT_HEADERS = [
'序号',
'商品名*',
'一级分类',
'二级分类',
'规格',
'厂家',
'规格详情',
'成本价',
'销售价*',
];
/** 智能导入字段词典(免模板:识别其他平台表头) */
export const QUOTE_IMPORT_FIELD_DICT: import('./smartColumnMapping').ImportFieldDef[] = [
{
key: 'seq',
label: '序号',
templateHeader: '序号',
aliases: ['序号', '编号', '行号', 'no', 'index'],
patterns: [/序号|编号/],
},
{
key: 'skuName',
label: '商品名',
required: true,
templateHeader: '商品名*',
aliases: ['商品名', '商品名称', '品名', '产品名称', '名称', '菜名', 'sku名称', 'itemname', 'productname', 'name'],
patterns: [/品名|商品名|名称/],
},
{
key: 'l1',
label: '一级分类',
templateHeader: '一级分类',
aliases: ['一级分类', '大类', '品类', '分类', '类目', 'category', 'category1'],
patterns: [/一级|大类|分类/],
},
{
key: 'l2',
label: '二级分类',
templateHeader: '二级分类',
aliases: ['二级分类', '小类', '子分类', 'category2', 'subcategory'],
patterns: [/二级|小类/],
},
{
key: 'spec',
label: '规格',
templateHeader: '规格',
aliases: ['规格', '规格型号', '型号', 'spec', 'specification'],
patterns: [/规格|型号/],
},
{
key: 'brand',
label: '厂家',
templateHeader: '厂家',
aliases: ['厂家', '厂商', '品牌', '生产厂家', 'brand', 'manufacturer'],
patterns: [/厂家|厂商|品牌/],
},
{
key: 'specDetail',
label: '规格详情',
templateHeader: '规格详情',
aliases: ['规格详情', '详情', '备注规格', 'detail'],
patterns: [/规格详情|详情/],
},
{
key: 'cost',
label: '成本价',
templateHeader: '成本价',
aliases: ['成本价', '进价', '采购价', '成本', 'cost', 'costprice'],
patterns: [/成本|进价|采购价/],
},
{
key: 'sale',
label: '销售价',
required: true,
templateHeader: '销售价*',
aliases: ['销售价', '售价', '单价', '报价', '含税价', 'sale', 'price', 'saleprice'],
patterns: [/销售价|售价|单价|报价/],
},
];
export const QUOTE_IMPORT_EXAMPLES: (string | number)[][] = [
[1, '大白菜', '蔬菜', '叶菜类', '散装', '本地', '约500g/份', 2.5, 3.5],
[2, '五花肉', '猪肉', '', '冷鲜', '双汇', '冷鲜切块', 22, 28],
[3, '土豆', '蔬菜', '根茎类', '中等', '', '', 1.2, 2.0],
];
export interface QuoteImportSku {
sku_code: string;
sku_name: string;
unit?: string | null;
brand?: string | null;
spec?: string | null;
category_code?: string | null;
}
export interface QuoteImportLine {
sku_code: string;
sku_name: string;
unit: string;
cost_price: string;
sale_price: string;
}
function normalizeText(value: string) {
return String(value || '')
.trim()
.replace(/\s+/g, '')
.replace(/(/g, '(')
.replace(/)/g, ')')
.toLowerCase();
}
function resolveCategoryCode(
categories: CategoryRow[],
level1: string,
level2: string
): string | null {
const l1 = level1.trim();
const l2 = level2.trim();
if (!l1 && !l2) return null;
const byName = (name: string) =>
categories.filter((cat) => normalizeText(cat.category_name) === normalizeText(name));
if (l1 && l2) {
const parents = byName(l1).filter((cat) => !cat.parent_code);
for (const parent of parents) {
const child = categories.find(
(cat) =>
cat.parent_code === parent.category_code &&
normalizeText(cat.category_name) === normalizeText(l2)
);
if (child) return child.category_code;
}
return null;
}
const matches = byName(l1 || l2);
if (matches.length === 1) return matches[0].category_code;
const level2Match = matches.find((cat) => cat.parent_code);
return level2Match?.category_code || matches[0]?.category_code || null;
}
function categoryMatchesSku(
categories: CategoryRow[],
categoryCode: string | null,
skuCategoryCode?: string | null
) {
if (!categoryCode || !skuCategoryCode) return true;
if (categoryCode === skuCategoryCode) return true;
const skuCat = categories.find((cat) => cat.category_code === skuCategoryCode);
if (skuCat?.parent_code === categoryCode) return true;
const target = categories.find((cat) => cat.category_code === categoryCode);
if (target?.parent_code && target.parent_code === skuCat?.parent_code) return false;
return false;
}
function pickSkuMatch(
candidates: QuoteImportSku[],
row: Record<string, string>,
categories: CategoryRow[]
): { sku?: QuoteImportSku; error?: string } {
if (!candidates.length) {
return { error: '未找到对应商品,请先在商品管理中维护' };
}
let pool = [...candidates];
const level1 = getCell(row, '一级分类');
const level2 = getCell(row, '二级分类');
const categoryCode = resolveCategoryCode(categories, level1, level2);
if (categoryCode) {
const filtered = pool.filter((sku) => categoryMatchesSku(categories, categoryCode, sku.category_code));
if (filtered.length) pool = filtered;
}
const brand = getCell(row, '厂家', '品牌');
if (brand) {
const filtered = pool.filter((sku) => normalizeText(sku.brand || '') === normalizeText(brand));
if (!filtered.length) {
return { error: `未找到品牌为「${brand}」的对应商品` };
}
pool = filtered;
}
const spec = getCell(row, '规格');
const specDetail = getCell(row, '规格详情');
const specNeedle = normalizeText(spec || specDetail);
if (specNeedle) {
const filtered = pool.filter((sku) => {
const skuSpec = normalizeText(`${sku.spec || ''}${sku.unit || ''}`);
return skuSpec.includes(specNeedle) || specNeedle.includes(normalizeText(sku.spec || ''));
});
if (!filtered.length) {
return { error: '规格信息与商品库不一致,请核对规格或规格详情' };
}
pool = filtered;
}
if (pool.length === 1) return { sku: pool[0] };
if (pool.length > 1) {
return { error: '存在多个同名商品,请补充一级/二级分类、厂家或规格以区分' };
}
return { error: '未找到对应商品,请检查分类或厂家是否与商品库一致' };
}
export async function downloadQuoteImportTemplate() {
await downloadExcelTemplate(
'报价单批量导入模板.xlsx',
'报价导入',
QUOTE_IMPORT_HEADERS,
QUOTE_IMPORT_EXAMPLES,
[
{
name: '填写说明',
headers: ['字段', '说明'],
rows: [
['商品名*', '必填,按商品库名称匹配(需已存在商品)'],
['一级分类 / 二级分类', '选填,用于区分同名商品'],
['厂家', '选填,对应商品库中的品牌字段'],
['规格 / 规格详情', '选填,用于进一步匹配商品'],
['销售价*', '必填,须大于 0'],
['成本价', '选填,默认 0'],
['序号', '选填,仅用于 Excel 排序,系统不保存'],
],
},
]
);
}
export async function parseQuoteLinesFromExcel(
file: File,
skus: QuoteImportSku[],
branchCode?: string | null,
preMappedRows?: Record<string, string>[]
): Promise<{ lines: QuoteImportLine[]; result: BulkImportResult }> {
const rows =
preMappedRows ??
(await parseExcelFile(file, {
preferredSheetNames: ['报价导入', '报价单', '商品'],
requiredHeaderHints: ['商品名', '销售价'],
}));
const result: BulkImportResult = { success: 0, skipped: 0, failed: 0, errors: [] };
const lines: QuoteImportLine[] = [];
if (rows.length === 0) {
result.errors.push('文件中没有可导入的数据,请确认表头包含「商品名」「销售价」');
return { lines, result };
}
let categories: CategoryRow[] = [];
try {
categories = await fetchCategoryRows({ force: true, branchCode });
} catch (error: any) {
result.errors.push(error?.message || '读取分类失败');
result.failed = rows.length;
return { lines, result };
}
const byName = new Map<string, QuoteImportSku[]>();
for (const sku of skus) {
const key = normalizeText(sku.sku_name);
if (!key) continue;
if (!byName.has(key)) byName.set(key, []);
byName.get(key)!.push(sku);
}
const importedByCode = new Map<string, QuoteImportLine>();
for (const row of rows) {
const rowNo = row.__row || '?';
const name = getCell(row, '商品名', '商品名称', '商品名称*');
const salePrice = parseNumberText(getCell(row, '销售价', '销售价*', '销售单价'), NaN);
const costPrice = parseNumberText(getCell(row, '成本价', '成本单价'), NaN);
if (!name) {
result.skipped += 1;
continue;
}
if (!Number.isFinite(salePrice) || salePrice <= 0) {
result.failed += 1;
result.errors.push(`第 ${rowNo} 行「${name}」:销售价须大于 0`);
continue;
}
const candidates = byName.get(normalizeText(name)) || [];
const { sku, error } = pickSkuMatch(candidates, row, categories);
if (!sku || error) {
result.failed += 1;
result.errors.push(`第 ${rowNo} 行「${name}」:${error || '匹配失败'}`);
continue;
}
importedByCode.set(sku.sku_code, {
sku_code: sku.sku_code,
sku_name: sku.sku_name || name,
unit: sku.unit || '斤',
cost_price: Number.isFinite(costPrice) && costPrice >= 0 ? String(costPrice) : '',
sale_price: String(salePrice),
});
result.success += 1;
}
return { lines: [...importedByCode.values()], result };
}