mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-24 01:19:19 +08:00
283 lines
10 KiB
JavaScript
Executable File
283 lines
10 KiB
JavaScript
Executable File
#!/usr/bin/env node
|
|
import { Command } from 'commander';
|
|
import { createConnection } from './src/db.js';
|
|
import { verifyCompany, fetchSpecs, fetchShops, fetchStatuses } from './src/fetcher.js';
|
|
import { generateOrders, formatDate } from './src/generator.js';
|
|
import { deleteExistingOrders, insertOrders } from './src/inserter.js';
|
|
import { promptMissingOptions, pickRandomSpecs } from './src/prompt.js';
|
|
|
|
function parsePriceRange(str) {
|
|
if (!str) return null;
|
|
const parts = str.split('-');
|
|
if (parts.length === 1) return [Number(parts[0]), Number(parts[0])];
|
|
return [Number(parts[0]), Number(parts[1])];
|
|
}
|
|
|
|
const program = new Command();
|
|
|
|
program
|
|
.name('seed-orders')
|
|
.description('为指定公司的商品规格批量生成测试订单')
|
|
.option('-c, --company <id>', '公司ID(必填)')
|
|
.option('-s, --spec <ids|codes>', '商品规格ID或spec_code(逗号分隔;不传则随机选)')
|
|
.option('--spec-count <n>', '随机选取几个规格(配合 -s 不传时使用)', '5')
|
|
.option('--start-date <date>', '开始日期 (YYYY-MM-DD)')
|
|
.option('--end-date <date>', '结束日期 (YYYY-MM-DD)')
|
|
.option('--daily-min <n>', '每店每日最少订单数', '1')
|
|
.option('--daily-max <n>', '每店每日最多订单数', '5')
|
|
.option('--shop <ids>', '店铺ID(逗号分隔)')
|
|
.option('-p, --unit-price <range>', '单价区间,如 "19.9-99.9"')
|
|
.option('--status <ids>', '订单状态ID(逗号分隔)')
|
|
.option('--confirm <0|1>', '确认标记', '1')
|
|
.option('--delete-existing', '先清空指定规格的已有订单再刷入')
|
|
.option('--dry-run', '试运行,只预览不写入')
|
|
.option('-i, --interactive', '交互模式')
|
|
.option('-v, --verbose', '详细输出')
|
|
.addHelpText('after', `
|
|
示例:
|
|
$ npm run seed -- -c 3 -s 845,842 --daily-min 3 --daily-max 8 --start-date 2026-05-01 --end-date 2026-05-28
|
|
$ npm run seed -- -c 3 -s SLJ007,YQ068 --shop 6,7 --daily-min 2 --daily-max 10 --delete-existing --verbose
|
|
$ npm run seed:interactive # 交互模式
|
|
`)
|
|
.parse(process.argv);
|
|
|
|
const opts = program.opts();
|
|
|
|
async function main() {
|
|
const interactive = opts.interactive || process.argv.slice(2).length === 0;
|
|
const DAYS_AGO = 30;
|
|
const now = new Date();
|
|
|
|
// Default date values
|
|
let startDate = opts.startDate ? new Date(opts.startDate + 'T00:00:00') : new Date(now - DAYS_AGO * 86400000);
|
|
let endDate = opts.endDate ? new Date(opts.endDate + 'T23:59:59') : now;
|
|
|
|
let companyId = opts.company ? Number(opts.company) : undefined;
|
|
let specEntries = opts.spec ? opts.spec.split(',').map(s => s.trim()).filter(Boolean) : [];
|
|
let shopIds = opts.shop ? opts.shop.split(',').map(s => Number(s.trim())).filter(n => !isNaN(n)) : undefined;
|
|
let statusIds = opts.status ? opts.status.split(',').map(s => Number(s.trim())).filter(n => !isNaN(n)) : undefined;
|
|
let dailyMin = Number(opts.dailyMin);
|
|
let dailyMax = Number(opts.dailyMax);
|
|
let unitPrice = opts.unitPrice;
|
|
let confirm = opts.confirm !== undefined ? Number(opts.confirm) : 1;
|
|
let deleteExisting = opts.deleteExisting || false;
|
|
const dryRun = opts.dryRun || false;
|
|
const verbose = opts.verbose || false;
|
|
|
|
const conn = await createConnection(opts);
|
|
|
|
try {
|
|
// Interactive mode: fetch reference data first
|
|
if (interactive) {
|
|
console.log('=== 交互模式 ===\n');
|
|
|
|
// Fetch companies
|
|
const [companies] = await conn.execute('SELECT id, name FROM org_company ORDER BY id');
|
|
if (companies.length === 0) {
|
|
console.error('No companies found in database.');
|
|
process.exit(1);
|
|
}
|
|
|
|
// Let user pick company
|
|
const companyAnswers = await promptMissingOptions({
|
|
company: undefined,
|
|
companyList: companies,
|
|
});
|
|
companyId = companyAnswers.company;
|
|
|
|
const company = await verifyCompany(conn, companyId);
|
|
|
|
// Fetch specs for this company
|
|
const specList = await fetchSpecs(conn, companyId);
|
|
if (specList.length === 0) {
|
|
console.error(`No specs found for company ${companyId}.`);
|
|
process.exit(1);
|
|
}
|
|
|
|
// Fetch all shops for this company
|
|
const shopList = await fetchShops(conn, companyId, [...new Set(specList.map(s => s.product_id))]);
|
|
if (shopList.length === 0) {
|
|
console.error(`No shops found for company ${companyId}.`);
|
|
process.exit(1);
|
|
}
|
|
|
|
// Fetch all statuses for this company
|
|
const statusList = await fetchStatuses(conn, companyId);
|
|
if (statusList.length === 0) {
|
|
console.error(`No order statuses found for company ${companyId}.`);
|
|
process.exit(1);
|
|
}
|
|
|
|
const sd = formatDate(startDate);
|
|
const ed = formatDate(endDate);
|
|
|
|
const answers = await promptMissingOptions({
|
|
company: companyId,
|
|
specs: [],
|
|
specList,
|
|
shops: [],
|
|
shopList,
|
|
statuses: [],
|
|
statusList,
|
|
startDate: sd,
|
|
endDate: ed,
|
|
dailyMin,
|
|
dailyMax,
|
|
unitPrice: unitPrice || '',
|
|
});
|
|
|
|
// Randomly pick specs
|
|
const picked = pickRandomSpecs(specList, answers.specCount);
|
|
specEntries = picked.map(s => s.spec_code || String(s.id));
|
|
console.log(`随机选中 ${picked.length} 个规格:`);
|
|
for (const s of picked) {
|
|
console.log(` [${s.id}] ${s.name} (${s.spec_code})`);
|
|
}
|
|
console.log('');
|
|
shopIds = answers.shops;
|
|
statusIds = answers.statuses;
|
|
startDate = new Date(answers.startDate + 'T00:00:00');
|
|
endDate = new Date(answers.endDate + 'T23:59:59');
|
|
dailyMin = answers.dailyMin;
|
|
dailyMax = answers.dailyMax;
|
|
unitPrice = answers.unitPrice || undefined;
|
|
deleteExisting = answers.deleteExisting;
|
|
|
|
if (!answers.confirmInsert) {
|
|
console.log('Cancelled by user.');
|
|
return;
|
|
}
|
|
}
|
|
|
|
const company = await verifyCompany(conn, companyId);
|
|
|
|
let specs;
|
|
if (specEntries.length === 0) {
|
|
const allSpecs = await fetchSpecs(conn, companyId);
|
|
if (allSpecs.length === 0) {
|
|
console.error(`公司 ${companyId} 下没有商品规格`);
|
|
process.exit(1);
|
|
}
|
|
const specCount = Math.min(Number(opts.specCount), allSpecs.length);
|
|
specs = pickRandomSpecs(allSpecs, specCount);
|
|
console.log(`随机选中 ${specs.length} 个规格:`);
|
|
for (const s of specs) {
|
|
console.log(` [${s.id}] ${s.name} (${s.spec_code})`);
|
|
}
|
|
} else {
|
|
const specIds = specEntries.filter(s => /^\d+$/.test(s)).map(Number);
|
|
const specCodes = specEntries.filter(s => !/^\d+$/.test(s));
|
|
specs = await fetchSpecs(conn, companyId, specIds, specCodes);
|
|
}
|
|
if (specs.length === 0) {
|
|
console.error(`Error: No specs found for company ${companyId}`);
|
|
process.exit(1);
|
|
}
|
|
const productIds = [...new Set(specs.map(s => s.product_id))];
|
|
|
|
// Fetch shops
|
|
const shops = await fetchShops(conn, companyId, productIds, shopIds);
|
|
if (shops.length === 0) {
|
|
console.error(`Error: No shops found for company ${companyId}`);
|
|
process.exit(1);
|
|
}
|
|
|
|
// Fetch statuses
|
|
const statuses = await fetchStatuses(conn, companyId, statusIds);
|
|
if (statuses.length === 0) {
|
|
console.error(`Error: No order statuses found for company ${companyId}`);
|
|
process.exit(1);
|
|
}
|
|
|
|
if (dailyMin < 0 || dailyMax < 0 || dailyMin > dailyMax) {
|
|
console.error('Error: --daily-min must be >= 0 and <= --daily-max');
|
|
process.exit(1);
|
|
}
|
|
|
|
const dayCount = Math.floor((endDate - startDate) / 86400000) + 1;
|
|
const shopDailyAvg = (dailyMin + dailyMax) / 2;
|
|
const estimatedTotal = Math.ceil(specs.length * shops.length * dayCount * shopDailyAvg);
|
|
|
|
console.log(`\nCompany: ${company.name} (${company.id})`);
|
|
console.log(`Period: ${formatDate(startDate)} ~ ${formatDate(endDate)} (${dayCount} days)`);
|
|
console.log(`Daily range: ${dailyMin} ~ ${dailyMax} orders/shop/day`);
|
|
console.log(`Specs: ${specs.length}`);
|
|
if (verbose) {
|
|
for (const s of specs) {
|
|
console.log(` [${s.id}] ${s.name} (${s.spec_code})`);
|
|
}
|
|
}
|
|
console.log(`Shops: ${shops.length}`);
|
|
if (verbose) {
|
|
for (const sh of shops) {
|
|
console.log(` [${sh.id}] ${sh.name}`);
|
|
}
|
|
}
|
|
console.log(`Statuses: ${statuses.length}`);
|
|
console.log(`Estimated total: ~${estimatedTotal} orders`);
|
|
console.log(`Delete existing: ${deleteExisting ? 'YES' : 'no'}`);
|
|
console.log(`Dry run: ${dryRun ? 'YES' : 'no'}`);
|
|
console.log('');
|
|
|
|
// Delete existing if requested
|
|
if (deleteExisting && !dryRun) {
|
|
console.log('Deleting existing orders...');
|
|
const deleted = await deleteExistingOrders(conn, companyId, specs, verbose);
|
|
console.log(`Deleted ${deleted} existing orders.\n`);
|
|
}
|
|
|
|
// Generate orders
|
|
const seenOrderNos = new Set();
|
|
const remarkPool = [
|
|
null, null, null,
|
|
'测试数据,请忽略',
|
|
'系统生成测试订单',
|
|
null, null,
|
|
];
|
|
|
|
const orders = generateOrders({
|
|
companyId,
|
|
specs,
|
|
shops,
|
|
statuses,
|
|
priceRange: parsePriceRange(unitPrice),
|
|
dailyMin,
|
|
dailyMax,
|
|
confirm,
|
|
startDate,
|
|
endDate,
|
|
seenOrderNos,
|
|
remarkPool,
|
|
});
|
|
|
|
console.log(`Generated ${orders.length} orders.`);
|
|
|
|
if (dryRun) {
|
|
const samples = orders.slice(0, 5);
|
|
if (samples.length > 0) {
|
|
console.log('\nSample orders:');
|
|
for (const o of samples) {
|
|
console.log(` ${o.platform_order_no} | shop=${o.shop_id} | spec=[${o.product_spec_id}] | qty=${o.quantity} | price=${o.unit_price} | received=${o.received_amount} | ${o.order_time}`);
|
|
}
|
|
if (orders.length > 5) {
|
|
console.log(` ... and ${orders.length - 5} more`);
|
|
}
|
|
}
|
|
console.log('\nDry run completed. No data inserted.');
|
|
return;
|
|
}
|
|
|
|
// Insert orders
|
|
console.log('Inserting orders...');
|
|
const { inserted, failed } = await insertOrders(conn, orders, verbose);
|
|
console.log(`\nDone. Inserted: ${inserted}, Failed: ${failed}, Total: ${orders.length}`);
|
|
} finally {
|
|
await conn.end();
|
|
}
|
|
}
|
|
|
|
main().catch(err => {
|
|
console.error('Fatal error:', err.message);
|
|
process.exit(1);
|
|
});
|