refactor: 订单生成改为流式迭代降低内存,新增删单模式(cleaner),批量插入(BATCH_SIZE),日期预设选择,CLI合并单入口

This commit is contained in:
小蟑螂
2026-05-28 02:13:47 +08:00
parent 054cac86a8
commit ede706a8e0
6 changed files with 496 additions and 260 deletions
+254 -173
View File
@@ -1,10 +1,13 @@
#!/usr/bin/env node
import { Command } from 'commander';
import inquirer from 'inquirer';
import cliProgress from 'cli-progress';
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';
import { iterateOrders, formatDate } from './src/generator.js';
import { deleteExistingOrders, insertBatch, BATCH_SIZE } from './src/inserter.js';
import { deleteOrders } from './src/cleaner.js';
import { promptMissingOptions, promptDeleteOptions, pickRandomSpecs } from './src/prompt.js';
function parsePriceRange(str) {
if (!str) return null;
@@ -13,45 +16,13 @@ function parsePriceRange(str) {
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;
// ─── Seed ───────────────────────────────────────────────────
async function seedHandler(opts) {
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;
@@ -67,73 +38,41 @@ async function main() {
const conn = await createConnection(opts);
try {
// Interactive mode: fetch reference data first
if (interactive) {
console.log('=== 交互模式 ===\n');
if (!opts.company) {
console.log('');
// 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);
}
if (companies.length === 0) { console.error('数据库中没有公司'); process.exit(1); }
// Let user pick company
const companyAnswers = await promptMissingOptions({
company: undefined,
companyList: companies,
});
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);
}
if (specList.length === 0) { console.error(`公司 ${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);
}
if (shopList.length === 0) { console.error(`公司 ${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);
}
if (statusList.length === 0) { console.error(`公司 ${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 || '',
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(`\n随机选中 ${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');
@@ -143,10 +82,7 @@ async function main() {
unitPrice = answers.unitPrice || undefined;
deleteExisting = answers.deleteExisting;
if (!answers.confirmInsert) {
console.log('Cancelled by user.');
return;
}
if (!answers.confirmInsert) { console.log('已取消'); return; }
}
const company = await verifyCompany(conn, companyId);
@@ -154,129 +90,274 @@ async function main() {
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);
if (allSpecs.length === 0) { console.error(`公司 ${companyId} 下没有规格`); process.exit(1); }
const count = Math.min(Number(opts.specCount), allSpecs.length);
specs = pickRandomSpecs(allSpecs, count);
console.log(`随机选中 ${specs.length} 个规格:`);
for (const s of specs) {
console.log(` [${s.id}] ${s.name} (${s.spec_code})`);
}
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);
}
if (specs.length === 0) { console.error('没有匹配的规格'); 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);
}
if (shops.length === 0) { console.error('没有匹配的店铺'); 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 (statuses.length === 0) { console.error('没有匹配的状态'); process.exit(1); }
if (dailyMin < 0 || dailyMax < 0 || dailyMin > dailyMax) {
console.error('Error: --daily-min must be >= 0 and <= --daily-max');
process.exit(1);
console.error('--daily-min 必须 >= 0 且 <= --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(`\n公司: ${company.name} (${company.id})`);
console.log(`时间: ${formatDate(startDate)} ~ ${formatDate(endDate)} (${dayCount} 天)`);
console.log(`单量: ${dailyMin} ~ ${dailyMax} 单/店/天`);
console.log(`规格: ${specs.length} 个 | 店铺: ${shops.length} 个 | 状态: ${statuses.length} 个`);
console.log(`预计: ~${estimatedTotal} 条订单`);
if (deleteExisting) console.log(`清空: 先删后刷`);
if (dryRun) console.log(`试运行: 只预览不写入`);
console.log('');
// Delete existing if requested
if (deleteExisting && !dryRun) {
console.log('Deleting existing orders...');
console.log('清空已有订单...');
const deleted = await deleteExistingOrders(conn, companyId, specs, verbose);
console.log(`Deleted ${deleted} existing orders.\n`);
console.log(`已删除 ${deleted} 条.\n`);
}
// Generate orders
const priceRange = parsePriceRange(unitPrice);
const seenOrderNos = new Set();
const remarkPool = [
null, null, null,
'测试数据,请忽略',
'系统生成测试订单',
null, null,
];
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.`);
const genConfig = {
companyId, specs, shops, statuses, priceRange,
dailyMin, dailyMax, confirm,
startDate, endDate, seenOrderNos, remarkPool,
};
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`);
}
let count = 0;
const samples = [];
for (const order of iterateOrders(genConfig)) {
if (samples.length < 5) samples.push(order);
count++;
}
console.log('\nDry run completed. No data inserted.');
console.log(`生成 ${count} 条订单.`);
if (samples.length > 0) {
console.log('\n样例:');
for (const o of samples) {
console.log(` ${o.platform_order_no} | 店铺=${o.shop_id} | 规格=[${o.product_spec_id}] | 数量=${o.quantity} | 单价=${o.unit_price} | 实收=${o.received_amount} | ${o.order_time}`);
}
if (count > 5) console.log(` ... 还有 ${count - 5} 条`);
}
console.log('\n试运行完成,未写入任何数据');
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}`);
// Streaming insert: generate + insert in batches
let inserted = 0;
let failed = 0;
let total = 0;
let batch = [];
const bar = new cliProgress.SingleBar({
format: '刷入进度 |{bar}| {percentage}% | {value}/{total} 条 | 成功: {inserted} 失败: {failed}',
barCompleteChar: '█',
barIncompleteChar: '░',
hideCursor: true,
}, cliProgress.Presets.shades_classic);
bar.start(estimatedTotal, 0, { inserted: 0, failed: 0 });
for (const order of iterateOrders(genConfig)) {
batch.push(order);
total++;
if (batch.length >= BATCH_SIZE) {
try {
const affected = await insertBatch(conn, batch);
inserted += affected;
} catch (err) {
failed += batch.length;
if (verbose) console.error(` Batch failed: ${err.message}`);
}
batch = [];
bar.update(total, { inserted, failed });
}
}
// Final batch
if (batch.length > 0) {
try {
const affected = await insertBatch(conn, batch);
inserted += affected;
} catch (err) {
failed += batch.length;
if (verbose) console.error(` Final batch failed: ${err.message}`);
}
}
bar.update(total, { inserted, failed });
bar.stop();
console.log(`\n完成。写入: ${inserted}, 失败: ${failed}, 总计: ${total}`);
} finally {
await conn.end();
}
}
// ─── Delete ─────────────────────────────────────────────────
async function deleteHandler(opts) {
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 startDate = opts.startDate;
let endDate = opts.endDate;
let dryRun = opts.dryRun || false;
let deleteAll = false;
const verbose = opts.verbose || false;
const conn = await createConnection(opts);
try {
if (!opts.company) {
console.log('');
const [companies] = await conn.execute('SELECT id, name FROM org_company ORDER BY id');
if (companies.length === 0) { console.error('数据库中没有公司'); process.exit(1); }
const answers = await promptDeleteOptions({ company: undefined, companyList: companies });
companyId = answers.company;
const company = await verifyCompany(conn, companyId);
const specList = await fetchSpecs(conn, companyId);
const more = await promptDeleteOptions({ company: companyId, specList, deleteAll: false });
deleteAll = more.deleteAll;
if (more.datePreset && more.datePreset !== 'all') {
startDate = more.startDate;
endDate = more.endDate;
}
if (!deleteAll && more.specCount > 0) {
const picked = pickRandomSpecs(specList, more.specCount);
specEntries = picked.map(s => String(s.id));
console.log(`\n随机选中 ${picked.length} 个规格删除:`);
for (const s of picked) console.log(` [${s.id}] ${s.name} (${s.spec_code})`);
console.log('');
}
dryRun = more.dryRun;
if (!dryRun && !more.confirmDelete) { console.log('已取消'); return; }
}
let deleteSpecIds;
if (deleteAll) {
deleteSpecIds = undefined;
} else if (specEntries.length > 0) {
const specIds = specEntries.filter(s => /^\d+$/.test(s)).map(Number);
const specCodes = specEntries.filter(s => !/^\d+$/.test(s));
const specs = await fetchSpecs(conn, companyId, specIds, specCodes);
deleteSpecIds = specs.map(s => s.id);
if (deleteSpecIds.length === 0) { console.error('没有匹配的规格'); process.exit(1); }
}
const result = await deleteOrders(conn, {
companyId, specIds: deleteSpecIds, shopIds,
startDate, endDate, verbose, dryRun,
});
if (dryRun) {
console.log(`\n预览: 共 ${result.matched} 条订单匹配。`);
if (result.matched > 0) {
const { proceed } = await inquirer.prompt([{
type: 'confirm',
name: 'proceed',
message: `确认删除这 ${result.matched} 条订单?`,
default: false,
}]);
if (!proceed) { console.log('已取消'); return; }
const final = await deleteOrders(conn, {
companyId, specIds: deleteSpecIds, shopIds,
startDate, endDate, verbose, dryRun: false,
});
console.log(`\n完成: 已删除 ${final.deleted} 条订单`);
}
} else {
console.log(`\n完成: 已删除 ${result.deleted} 条订单`);
}
} finally {
await conn.end();
}
}
// ─── CLI ────────────────────────────────────────────────────
const program = new Command();
program
.name('ecom-tool')
.description('电商订单刷单/删单工具')
.option('--mode <mode>', '模式: seed=刷单, delete=删单(不传则交互选择)')
.option('-c, --company <id>', '公司ID')
.option('-s, --spec <ids|codes>', '规格ID或 spec_code')
.option('--spec-count <n>', '随机选几个规格(刷单模式)', '5')
.option('--start-date <date>', '开始日期')
.option('--end-date <date>', '结束日期')
.option('--daily-min <n>', '每店每日最少单量', '1')
.option('--daily-max <n>', '每店每日最多单量', '5')
.option('--shop <ids>', '店铺ID')
.option('-p, --unit-price <range>', '单价区间')
.option('--status <ids>', '状态ID')
.option('--confirm <0|1>', '确认标记', '1')
.option('--delete-existing', '先清空再刷入(刷单模式)')
.option('--dry-run', '试运行/预览')
.option('-v, --verbose', '详细')
.addHelpText('after', `
示例:
npm start -- -c 3 --shop 6 --daily-min 2 --daily-max 5 --dry-run
npm start -- --mode delete -c 3 -s 845 --dry-run
npm start # 交互模式(选刷单还是删单)
`)
.parse(process.argv);
const opts = program.opts();
async function main() {
let mode = opts.mode;
// Interactive: ask for mode first
if (!mode && !opts.company && !opts.spec && !opts.startDate && !opts.shop) {
const { chosenMode } = await inquirer.prompt([{
type: 'list',
name: 'chosenMode',
message: '选择模式:',
choices: [
{ name: '刷单 — 批量生成测试订单', value: 'seed' },
{ name: '删单 — 按条件删除订单', value: 'delete' },
],
}]);
mode = chosenMode;
console.log('');
}
mode = mode || 'seed';
if (mode === 'delete') {
await deleteHandler(opts);
} else {
await seedHandler(opts);
}
}
main().catch(err => {
console.error('Fatal error:', err.message);
console.error('错误:', err.message);
process.exit(1);
});