Files
SupplierSystem/scripts/import-zigong-products.cjs
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

288 lines
9.3 KiB
JavaScript

#!/usr/bin/env node
/**
* 导入「自贡商品明细」类 Excel 到商品基础数据(product_catalog + skus 同步)
*
* 列映射:
* 商品名 -> name
* 分类 -> 一级分类
* 二级分类 -> 二级分类(可空)
* 规格 -> unit(单位)
* 规格详情 -> spec
* 厂家 -> brand(写入品牌字段)
*
* 用法:
* node scripts/import-zigong-products.cjs --file "path/to/file.xlsx" --dry-run
* node scripts/import-zigong-products.cjs --file "path/to/file.xlsx" --execute
* node scripts/import-zigong-products.cjs --file "path/to/file.xlsx" --execute --branch BR002
*/
const fs = require('fs');
const path = require('path');
const XLSX = require('xlsx');
const pg = require(path.join(__dirname, '../server/node_modules/pg'));
const dotenv = require(path.join(__dirname, '../server/node_modules/dotenv'));
dotenv.config({ path: path.join(__dirname, '../server/.env') });
const execute = process.argv.includes('--execute');
const dryRun = !execute;
const fileArgIdx = process.argv.indexOf('--file');
const branchArgIdx = process.argv.indexOf('--branch');
const filePath = fileArgIdx >= 0 ? process.argv[fileArgIdx + 1] : '';
const branchOverride = branchArgIdx >= 0 ? process.argv[branchArgIdx + 1] : null;
function normalizeName(value) {
return String(value ?? '').trim();
}
function isDataRow(row) {
const name = normalizeName(row['商品名'] ?? row['商品名称'] ?? row['商品名称*']);
if (!name) return false;
if (name.includes('AI生成') || name.includes('仅供参考')) return false;
return true;
}
function readRows(file) {
if (!fs.existsSync(file)) {
throw new Error(`文件不存在: ${file}`);
}
const workbook = XLSX.readFile(file);
const sheetName =
workbook.SheetNames.find((name) => /商品|汇总|导入/i.test(name)) || workbook.SheetNames[0];
const rows = XLSX.utils.sheet_to_json(workbook.Sheets[sheetName], { defval: '' });
return rows.filter(isDataRow);
}
function generateCode(prefix) {
return `${prefix}${Date.now().toString().slice(-9)}${Math.floor(Math.random() * 90 + 10)}`;
}
async function generateUniqueCode(client, prefix) {
for (let attempt = 0; attempt < 8; attempt++) {
const code = generateCode(prefix);
const { rows } = await client.query(
`SELECT 1 FROM product_catalog WHERE code = $1 LIMIT 1`,
[code]
);
if (!rows.length) return code;
}
return `${prefix}${Date.now()}${Math.random().toString(36).slice(2, 6).toUpperCase()}`;
}
function findLevel1(categories, name, branchCode) {
const normalized = normalizeName(name);
return categories.find(
(cat) =>
cat.branch_code === branchCode &&
!cat.parent_code &&
normalizeName(cat.category_name) === normalized
);
}
function findLevel2(categories, l1Code, l2Name, branchCode) {
const normalized = normalizeName(l2Name);
return categories.find(
(cat) =>
cat.branch_code === branchCode &&
cat.parent_code === l1Code &&
normalizeName(cat.category_name) === normalized
);
}
async function ensureCategoryChain(client, categories, branchCode, l1Name, l2Name, dryRunMode) {
const created = [];
const trimmedL1 = normalizeName(l1Name);
const trimmedL2 = normalizeName(l2Name);
if (!trimmedL1) throw new Error('一级分类不能为空');
let l1 = findLevel1(categories, trimmedL1, branchCode);
if (!l1) {
const code = dryRunMode ? `CAT_DRY_${trimmedL1}` : await generateUniqueCode(client, 'CAT');
l1 = {
category_code: code,
category_name: trimmedL1,
parent_code: null,
branch_code: branchCode,
level: 1,
};
categories.push(l1);
created.push(trimmedL1);
if (!dryRunMode) {
await client.query(
`INSERT INTO product_catalog (
item_type, code, name, parent_code, level, sort_order, loss_threshold, is_fresh, status, branch_code
) VALUES ('category', $1, $2, NULL, 1, 0, 5, true, 1, $3)`,
[code, trimmedL1, branchCode]
);
}
}
if (!trimmedL2) {
return { code: l1.category_code, categories, created };
}
let l2 = findLevel2(categories, l1.category_code, trimmedL2, branchCode);
if (!l2) {
const code = dryRunMode ? `CAT_DRY_${trimmedL1}_${trimmedL2}` : await generateUniqueCode(client, 'CAT');
l2 = {
category_code: code,
category_name: trimmedL2,
parent_code: l1.category_code,
branch_code: branchCode,
level: 2,
};
categories.push(l2);
created.push(`${trimmedL1}/${trimmedL2}`);
if (!dryRunMode) {
await client.query(
`INSERT INTO product_catalog (
item_type, code, name, parent_code, level, sort_order, loss_threshold, is_fresh, status, branch_code
) VALUES ('category', $2, $3, $1, 2, 0, 5, false, 1, $4)`,
[l1.category_code, code, trimmedL2, branchCode]
);
}
}
return { code: l2.category_code, categories, created };
}
async function main() {
if (!filePath) {
console.error('请指定 --file 路径');
process.exit(1);
}
if (!process.env.DATABASE_URL) {
console.error('缺少 DATABASE_URL,请在 server/.env 配置或通过环境变量传入');
process.exit(1);
}
const rows = readRows(path.resolve(filePath));
const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL });
const client = await pool.connect();
try {
const branchResult = branchOverride
? { rows: [{ branch_code: branchOverride }] }
: await client.query(
`SELECT branch_code FROM branches WHERE status = 1 ORDER BY branch_code LIMIT 1`
);
const branchCode = branchResult.rows[0]?.branch_code;
if (!branchCode) throw new Error('未找到可用分公司 branch_code');
const existingProducts = await client.query(
`SELECT code, name FROM product_catalog WHERE item_type = 'product'`
);
const existingCategories = await client.query(
`SELECT code AS category_code, parent_code, name AS category_name, branch_code
FROM product_catalog WHERE item_type = 'category' AND branch_code = $1`,
[branchCode]
);
const usedNames = new Set(existingProducts.rows.map((row) => normalizeName(row.name)));
const categories = existingCategories.rows.map((row) => ({ ...row, level: row.parent_code ? 2 : 1 }));
const result = {
dryRun,
branchCode,
totalRows: rows.length,
success: 0,
skipped: 0,
failed: 0,
categoriesCreated: 0,
errors: [],
};
if (dryRun) {
await client.query('BEGIN');
}
for (let index = 0; index < rows.length; index++) {
const row = rows[index];
const rowNumber = index + 2;
const skuName = normalizeName(row['商品名'] ?? row['商品名称'] ?? row['商品名称*']);
const l1Name = normalizeName(row['分类'] ?? row['一级分类'] ?? row['一级分类*']);
const l2Name = normalizeName(row['二级分类'] ?? row['二级分类*']);
const unit = normalizeName(row['规格'] ?? row['单位'] ?? row['单位*']) || '斤';
const spec = normalizeName(row['规格详情'] ?? row['规格']);
const brand = normalizeName(row['厂家'] ?? row['品牌'] ?? row['条码']);
if (!skuName) {
result.failed += 1;
result.errors.push(`第 ${rowNumber} 行:商品名称为空`);
continue;
}
if (!l1Name) {
result.failed += 1;
result.errors.push(`第 ${rowNumber} 行「${skuName}」:分类为空`);
continue;
}
if (usedNames.has(skuName)) {
result.skipped += 1;
result.errors.push(`第 ${rowNumber} 行:商品「${skuName}」已存在,已跳过`);
continue;
}
try {
const beforeCategoryCount = categories.length;
const ensured = await ensureCategoryChain(
client,
categories,
branchCode,
l1Name,
l2Name,
dryRun
);
result.categoriesCreated += Math.max(0, categories.length - beforeCategoryCount);
const skuCode = dryRun
? `SKU_DRY_${result.success + 1}`
: await generateUniqueCode(client, 'SKU');
if (!dryRun) {
await client.query(
`INSERT INTO product_catalog (
item_type, code, name, parent_code, unit, spec, barcode, brand,
default_loss_threshold, sale_price, cost_price, status, branch_code
) VALUES (
'product', $1, $2, $3, $4, $5, $6, NULLIF($7, ''), 5, 0, 0, 1, $8
)`,
[skuCode, skuName, ensured.code, unit, spec || null, skuCode, brand, branchCode]
);
}
usedNames.add(skuName);
result.success += 1;
} catch (error) {
result.failed += 1;
result.errors.push(`第 ${rowNumber} 行「${skuName}」:${error.message || error}`);
}
}
if (dryRun) {
await client.query('ROLLBACK');
}
console.log(JSON.stringify(result, null, 2));
if (result.errors.length) {
console.log('\n--- 明细 ---');
result.errors.slice(0, 30).forEach((line) => console.log(line));
if (result.errors.length > 30) {
console.log(`... 另有 ${result.errors.length - 30} 条`);
}
}
if (dryRun) {
console.log('\n[dry-run] 未写入数据库。确认后加 --execute');
} else {
console.log('\n导入完成。');
}
} finally {
client.release();
await pool.end();
}
}
main().catch((error) => {
console.error(error);
process.exit(1);
});