来源仓库: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 经哈希比对与线上同值), 整包推送会把这些凭据永久带入本仓库,故只取「当前版本」的单提交快照。 供应商系统后续开发自本提交开始。
434 lines
15 KiB
JavaScript
434 lines
15 KiB
JavaScript
#!/usr/bin/env node
|
||
/**
|
||
* 根据「自贡商品明细_去重汇总含报价」类 Excel,为泸州客户创建并激活报价单。
|
||
*
|
||
* 当前生产数据:无独立「泸州」分公司;客户「泸州市邮政分公司」挂在自贡 BR002。
|
||
* 默认绑定该客户;SKU 按商品名匹配共享商品库(branch_code NULL)。
|
||
*
|
||
* 用法:
|
||
* node scripts/import-luzhou-quote-from-xlsx.cjs --file "path.xlsx" --dry-run
|
||
* node scripts/import-luzhou-quote-from-xlsx.cjs --file "path.xlsx" --execute
|
||
* node scripts/import-luzhou-quote-from-xlsx.cjs --file "path.xlsx" --execute --customer CUS34985111820
|
||
* node scripts/import-luzhou-quote-from-xlsx.cjs --file "path.xlsx" --execute --branch BR002 --title "泸州报价单"
|
||
*/
|
||
const fs = require('fs');
|
||
const path = require('path');
|
||
const XLSX = require('xlsx');
|
||
const { Pool } = 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 args = process.argv.slice(2);
|
||
const execute = args.includes('--execute');
|
||
const dryRun = !execute;
|
||
const fileArgIdx = args.indexOf('--file');
|
||
const branchArgIdx = args.indexOf('--branch');
|
||
const customerArgIdx = args.indexOf('--customer');
|
||
const titleArgIdx = args.indexOf('--title');
|
||
const cycleArgIdx = args.indexOf('--cycle');
|
||
const createMissing = args.includes('--create-missing');
|
||
|
||
const filePath =
|
||
fileArgIdx >= 0
|
||
? args[fileArgIdx + 1]
|
||
: 'c:/Users/ADMIN/Desktop/project/数据/自贡商品明细_去重汇总含报价(1)(2).xlsx';
|
||
const branchOverride = branchArgIdx >= 0 ? args[branchArgIdx + 1] : null;
|
||
const customerOverride = customerArgIdx >= 0 ? args[customerArgIdx + 1] : null;
|
||
const titleOverride = titleArgIdx >= 0 ? args[titleArgIdx + 1] : null;
|
||
const quoteCycle = cycleArgIdx >= 0 ? args[cycleArgIdx + 1] : 'month';
|
||
|
||
const DEFAULT_LUZHOU_CUSTOMER_NAME = '泸州市邮政分公司';
|
||
|
||
function normalizeName(value) {
|
||
return String(value ?? '')
|
||
.trim()
|
||
.replace(/\s+/g, '')
|
||
.replace(/(/g, '(')
|
||
.replace(/)/g, ')');
|
||
}
|
||
|
||
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];
|
||
return XLSX.utils.sheet_to_json(workbook.Sheets[sheetName], { defval: '' }).filter(isDataRow);
|
||
}
|
||
|
||
function newSheetCode() {
|
||
return `QS${Date.now()}${Math.random().toString(36).slice(2, 6).toUpperCase()}`;
|
||
}
|
||
|
||
function newQuoteVersionCode() {
|
||
return `QV${Date.now()}${Math.random().toString(36).slice(2, 8).toUpperCase()}`;
|
||
}
|
||
|
||
function computeExpiresAt(from, cycle) {
|
||
const daysMap = { week: 7, half_month: 15, month: 30, half_year: 180, year: 365 };
|
||
const days = daysMap[cycle] || 30;
|
||
return new Date(from.getTime() + days * 86400000);
|
||
}
|
||
|
||
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()}`;
|
||
}
|
||
|
||
async function nextSheetVersionNo(client, branchCode) {
|
||
const r = await client.query(
|
||
`SELECT COALESCE(MAX(version_no), 0) + 1 AS next_version
|
||
FROM customer_quote_sheets WHERE branch_code = $1`,
|
||
[branchCode]
|
||
);
|
||
return Number(r.rows[0]?.next_version) || 1;
|
||
}
|
||
|
||
async function activateQuoteSheet(client, quoteSheetCode) {
|
||
const result = await client.query(
|
||
`UPDATE customer_quote_sheets
|
||
SET approval_status = 30,
|
||
approved_at = NOW(),
|
||
status = 1,
|
||
effective_at = COALESCE(effective_at, NOW()),
|
||
expires_at = COALESCE(expires_at, NOW() + INTERVAL '30 days'),
|
||
updated_at = NOW()
|
||
WHERE quote_sheet_code = $1
|
||
RETURNING *`,
|
||
[quoteSheetCode]
|
||
);
|
||
if (!result.rows.length) throw new Error(`报价单不存在: ${quoteSheetCode}`);
|
||
const sheet = result.rows[0];
|
||
|
||
await client.query(
|
||
`UPDATE customer_quote_sheets SET status = 3, updated_at = NOW()
|
||
WHERE quote_sheet_code <> $1 AND status = 1 AND approval_status = 30
|
||
AND branch_code IS NOT DISTINCT FROM $2
|
||
AND quote_sheet_code IN (
|
||
SELECT qsc1.quote_sheet_code FROM customer_quote_sheet_customers qsc1
|
||
WHERE qsc1.customer_code IN (
|
||
SELECT customer_code FROM customer_quote_sheet_customers WHERE quote_sheet_code = $1
|
||
)
|
||
)`,
|
||
[quoteSheetCode, sheet.branch_code]
|
||
);
|
||
|
||
const [itemsResult, customersResult] = await Promise.all([
|
||
client.query(`SELECT * FROM customer_quote_sheet_items WHERE quote_sheet_code = $1`, [
|
||
quoteSheetCode,
|
||
]),
|
||
client.query(
|
||
`SELECT customer_code FROM customer_quote_sheet_customers WHERE quote_sheet_code = $1`,
|
||
[quoteSheetCode]
|
||
),
|
||
]);
|
||
|
||
for (const customerRow of customersResult.rows) {
|
||
const customerCode = customerRow.customer_code;
|
||
for (const item of itemsResult.rows) {
|
||
const versionResult = await client.query(
|
||
`SELECT COALESCE(MAX(version_no), 0) + 1 AS next_version
|
||
FROM customer_quote_versions WHERE customer_code = $1 AND sku_code = $2`,
|
||
[customerCode, item.sku_code]
|
||
);
|
||
const versionNo = Number(versionResult.rows[0]?.next_version) || 1;
|
||
const salePrice = Number(item.sale_price ?? item.price) || 0;
|
||
|
||
await client.query(
|
||
`UPDATE customer_quote_versions SET status = 0, expired_at = NOW()
|
||
WHERE customer_code = $1 AND sku_code = $2 AND status = 1
|
||
AND branch_code IS NOT DISTINCT FROM $3`,
|
||
[customerCode, item.sku_code, sheet.branch_code]
|
||
);
|
||
|
||
await client.query(
|
||
`INSERT INTO customer_quote_versions
|
||
(quote_version_code, customer_code, sku_code, unit, price, version_no, source_type,
|
||
branch_code, status, approval_status, quote_cycle, expires_at, effective_at,
|
||
quote_sheet_code, approved_at)
|
||
VALUES ($1,$2,$3,$4,$5,$6,'quote_sheet',$7,1,30,$8,$9,NOW(),$10,NOW())`,
|
||
[
|
||
newQuoteVersionCode(),
|
||
customerCode,
|
||
item.sku_code,
|
||
item.unit,
|
||
salePrice,
|
||
versionNo,
|
||
sheet.branch_code,
|
||
sheet.quote_cycle,
|
||
sheet.expires_at,
|
||
quoteSheetCode,
|
||
]
|
||
);
|
||
}
|
||
}
|
||
|
||
return sheet;
|
||
}
|
||
|
||
async function main() {
|
||
if (!process.env.DATABASE_URL) {
|
||
throw new Error('缺少 DATABASE_URL');
|
||
}
|
||
|
||
const rows = readRows(path.resolve(filePath));
|
||
const pool = new Pool({ connectionString: process.env.DATABASE_URL });
|
||
const client = await pool.connect();
|
||
|
||
try {
|
||
console.log(`\n=== 泸州报价单导入 (${dryRun ? 'DRY-RUN' : 'EXECUTE'}) ===\n`);
|
||
console.log('file', path.resolve(filePath));
|
||
console.log('excel_rows', rows.length);
|
||
|
||
let branchCode = branchOverride;
|
||
if (!branchCode) {
|
||
const br = await client.query(
|
||
`SELECT branch_code, branch_name FROM branches
|
||
WHERE branch_name ILIKE '%泸州%' OR branch_code ILIKE '%泸州%'
|
||
ORDER BY branch_code LIMIT 1`
|
||
);
|
||
if (br.rowCount) {
|
||
branchCode = br.rows[0].branch_code;
|
||
console.log('branch_by_name', br.rows[0]);
|
||
} else {
|
||
const zigong = await client.query(
|
||
`SELECT branch_code, branch_name FROM branches
|
||
WHERE branch_name ILIKE '%自贡%' ORDER BY branch_code LIMIT 1`
|
||
);
|
||
branchCode = zigong.rows[0]?.branch_code || 'BR002';
|
||
console.log('no_luzhou_branch_use', zigong.rows[0] || { branch_code: branchCode });
|
||
}
|
||
}
|
||
|
||
let customer;
|
||
if (customerOverride) {
|
||
const c = await client.query(
|
||
`SELECT customer_code, company_name, branch_code, status
|
||
FROM customers WHERE customer_code = $1`,
|
||
[customerOverride]
|
||
);
|
||
customer = c.rows[0];
|
||
} else {
|
||
const c = await client.query(
|
||
`SELECT customer_code, company_name, branch_code, status
|
||
FROM customers
|
||
WHERE company_name ILIKE $1
|
||
ORDER BY CASE WHEN branch_code = $2 THEN 0 ELSE 1 END, customer_code
|
||
LIMIT 1`,
|
||
[`%${DEFAULT_LUZHOU_CUSTOMER_NAME}%`, branchCode]
|
||
);
|
||
customer = c.rows[0];
|
||
}
|
||
if (!customer) throw new Error('未找到泸州客户,请用 --customer 指定');
|
||
if (customer.branch_code && customer.branch_code !== branchCode) {
|
||
console.log('align_branch_to_customer', customer.branch_code);
|
||
branchCode = customer.branch_code;
|
||
}
|
||
console.log('customer', customer);
|
||
console.log('branch_code', branchCode);
|
||
|
||
const skus = await client.query(
|
||
`SELECT sku_code, sku_name, unit, branch_code, status
|
||
FROM skus
|
||
WHERE status = 1
|
||
AND (branch_code IS NULL OR branch_code = $1)`,
|
||
[branchCode]
|
||
);
|
||
const byName = new Map();
|
||
for (const sku of skus.rows) {
|
||
const key = normalizeName(sku.sku_name);
|
||
if (!key) continue;
|
||
if (!byName.has(key)) byName.set(key, []);
|
||
byName.get(key).push(sku);
|
||
}
|
||
|
||
const items = [];
|
||
const missing = [];
|
||
const noPrice = [];
|
||
const ambiguous = [];
|
||
|
||
for (const row of rows) {
|
||
const name = String(row['商品名'] ?? row['商品名称'] ?? '').trim();
|
||
const key = normalizeName(name);
|
||
const unit = String(row['规格'] ?? row['单位'] ?? '').trim() || '斤';
|
||
const salePrice = Number(row['销售价'] ?? row['销售价格'] ?? row['售价']);
|
||
const costPrice = Number(row['成本价'] ?? row['采购价']);
|
||
if (!(Number.isFinite(salePrice) && salePrice > 0)) {
|
||
noPrice.push(name);
|
||
continue;
|
||
}
|
||
|
||
const matches = byName.get(key) || [];
|
||
if (!matches.length) {
|
||
missing.push({ name, unit, salePrice, costPrice });
|
||
continue;
|
||
}
|
||
if (matches.length > 1) {
|
||
ambiguous.push({ name, codes: matches.map((m) => m.sku_code) });
|
||
}
|
||
const sku = matches[0];
|
||
items.push({
|
||
sku_code: sku.sku_code,
|
||
sku_name: sku.sku_name || name,
|
||
unit: unit || sku.unit || '斤',
|
||
sale_price: salePrice,
|
||
cost_price: Number.isFinite(costPrice) && costPrice > 0 ? costPrice : 0,
|
||
price: salePrice,
|
||
});
|
||
}
|
||
|
||
// 去重:同 sku 保留表格靠后的价格
|
||
const itemMap = new Map();
|
||
for (const item of items) itemMap.set(item.sku_code, item);
|
||
const uniqueItems = [...itemMap.values()];
|
||
|
||
console.log('\nmatch_summary', {
|
||
excelRows: rows.length,
|
||
withSalePrice: rows.length - noPrice.length,
|
||
matched: uniqueItems.length,
|
||
missing: missing.length,
|
||
noPrice: noPrice.length,
|
||
ambiguous: ambiguous.length,
|
||
});
|
||
if (missing.length) {
|
||
console.log('missing_sample', missing.slice(0, 15));
|
||
}
|
||
if (ambiguous.length) {
|
||
console.log('ambiguous_sample', ambiguous.slice(0, 10));
|
||
}
|
||
console.log('item_sample', uniqueItems.slice(0, 5));
|
||
|
||
if (!uniqueItems.length && !(createMissing && missing.length)) {
|
||
throw new Error('没有可写入的报价行(需销售价>0 且能匹配到 SKU)');
|
||
}
|
||
|
||
if (dryRun) {
|
||
console.log('\nDRY-RUN 完成。确认后加 --execute 创建并激活报价单。');
|
||
if (missing.length && !createMissing) {
|
||
console.log(`提示: ${missing.length} 个商品未匹配,可加 --create-missing 自动建品后再报价。`);
|
||
}
|
||
return;
|
||
}
|
||
|
||
await client.query('BEGIN');
|
||
try {
|
||
if (createMissing && missing.length) {
|
||
for (const m of missing) {
|
||
const skuCode = await generateUniqueCode(client, 'SKU');
|
||
await client.query(
|
||
`INSERT INTO product_catalog (
|
||
item_type, code, name, parent_code, unit, sale_price, cost_price, status
|
||
) VALUES ('product', $1, $2, NULL, $3, $4, $5, 1)`,
|
||
[skuCode, m.name, m.unit, m.salePrice, m.costPrice || 0]
|
||
);
|
||
uniqueItems.push({
|
||
sku_code: skuCode,
|
||
sku_name: m.name,
|
||
unit: m.unit,
|
||
sale_price: m.salePrice,
|
||
cost_price: m.costPrice || 0,
|
||
price: m.salePrice,
|
||
});
|
||
}
|
||
console.log('created_missing_products', missing.length);
|
||
}
|
||
|
||
const versionNo = await nextSheetVersionNo(client, branchCode);
|
||
const quoteSheetCode = newSheetCode();
|
||
const effectiveAt = new Date();
|
||
const expiresAt = computeExpiresAt(effectiveAt, quoteCycle);
|
||
const title =
|
||
titleOverride?.trim() ||
|
||
`泸州报价单(Excel导入) V${versionNo}`;
|
||
|
||
await client.query(
|
||
`INSERT INTO customer_quote_sheets
|
||
(quote_sheet_code, title, version_no, quote_cycle, effective_at, expires_at, status, approval_status,
|
||
branch_code, created_at, updated_at)
|
||
VALUES ($1, $2, $3, $4, $5, $6, 0, 10, $7, NOW(), NOW())`,
|
||
[
|
||
quoteSheetCode,
|
||
title,
|
||
versionNo,
|
||
quoteCycle,
|
||
effectiveAt.toISOString(),
|
||
expiresAt.toISOString(),
|
||
branchCode,
|
||
]
|
||
);
|
||
|
||
await client.query(
|
||
`INSERT INTO customer_quote_sheet_customers (quote_sheet_code, customer_code) VALUES ($1, $2)`,
|
||
[quoteSheetCode, customer.customer_code]
|
||
);
|
||
|
||
for (let i = 0; i < uniqueItems.length; i += 1) {
|
||
const item = uniqueItems[i];
|
||
await client.query(
|
||
`INSERT INTO customer_quote_sheet_items
|
||
(quote_sheet_code, sku_code, sku_name, unit, price, cost_price, sale_price, sort_order)
|
||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)`,
|
||
[
|
||
quoteSheetCode,
|
||
item.sku_code,
|
||
item.sku_name,
|
||
item.unit,
|
||
item.sale_price,
|
||
item.cost_price,
|
||
item.sale_price,
|
||
i,
|
||
]
|
||
);
|
||
}
|
||
|
||
await activateQuoteSheet(client, quoteSheetCode);
|
||
await client.query('COMMIT');
|
||
|
||
const versions = await pool.query(
|
||
`SELECT COUNT(*)::int AS n FROM customer_quote_versions
|
||
WHERE quote_sheet_code = $1 AND status = 1`,
|
||
[quoteSheetCode]
|
||
);
|
||
|
||
console.log('\ncreated', {
|
||
quoteSheetCode,
|
||
title,
|
||
branchCode,
|
||
customer: customer.company_name,
|
||
customerCode: customer.customer_code,
|
||
items: uniqueItems.length,
|
||
activeVersions: versions.rows[0].n,
|
||
expiresAt: expiresAt.toISOString(),
|
||
});
|
||
} catch (error) {
|
||
await client.query('ROLLBACK');
|
||
throw error;
|
||
}
|
||
} finally {
|
||
client.release();
|
||
await pool.end();
|
||
}
|
||
}
|
||
|
||
main().catch((error) => {
|
||
console.error(error);
|
||
process.exit(1);
|
||
});
|