From ede706a8e0abddceaeb6cacda02e855309a6ea0a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=B0=8F=E8=9F=91=E8=9E=82?= Date: Thu, 28 May 2026 02:13:47 +0800 Subject: [PATCH] =?UTF-8?q?refactor:=20=E8=AE=A2=E5=8D=95=E7=94=9F?= =?UTF-8?q?=E6=88=90=E6=94=B9=E4=B8=BA=E6=B5=81=E5=BC=8F=E8=BF=AD=E4=BB=A3?= =?UTF-8?q?=E9=99=8D=E4=BD=8E=E5=86=85=E5=AD=98=EF=BC=8C=E6=96=B0=E5=A2=9E?= =?UTF-8?q?=E5=88=A0=E5=8D=95=E6=A8=A1=E5=BC=8F(cleaner)=EF=BC=8C=E6=89=B9?= =?UTF-8?q?=E9=87=8F=E6=8F=92=E5=85=A5(BATCH=5FSIZE)=EF=BC=8C=E6=97=A5?= =?UTF-8?q?=E6=9C=9F=E9=A2=84=E8=AE=BE=E9=80=89=E6=8B=A9=EF=BC=8CCLI?= =?UTF-8?q?=E5=90=88=E5=B9=B6=E5=8D=95=E5=85=A5=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ecom-script/main.js | 427 +++++++++++++++++++++-------------- ecom-script/package.json | 7 +- ecom-script/src/cleaner.js | 42 ++++ ecom-script/src/generator.js | 93 ++++---- ecom-script/src/inserter.js | 60 ++--- ecom-script/src/prompt.js | 127 +++++++++++ 6 files changed, 496 insertions(+), 260 deletions(-) create mode 100644 ecom-script/src/cleaner.js diff --git a/ecom-script/main.js b/ecom-script/main.js index e9b2cb1b..d14d54db 100755 --- a/ecom-script/main.js +++ b/ecom-script/main.js @@ -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(必填)') - .option('-s, --spec ', '商品规格ID或spec_code(逗号分隔;不传则随机选)') - .option('--spec-count ', '随机选取几个规格(配合 -s 不传时使用)', '5') - .option('--start-date ', '开始日期 (YYYY-MM-DD)') - .option('--end-date ', '结束日期 (YYYY-MM-DD)') - .option('--daily-min ', '每店每日最少订单数', '1') - .option('--daily-max ', '每店每日最多订单数', '5') - .option('--shop ', '店铺ID(逗号分隔)') - .option('-p, --unit-price ', '单价区间,如 "19.9-99.9"') - .option('--status ', '订单状态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 ', '模式: seed=刷单, delete=删单(不传则交互选择)') + .option('-c, --company ', '公司ID') + .option('-s, --spec ', '规格ID或 spec_code') + .option('--spec-count ', '随机选几个规格(刷单模式)', '5') + .option('--start-date ', '开始日期') + .option('--end-date ', '结束日期') + .option('--daily-min ', '每店每日最少单量', '1') + .option('--daily-max ', '每店每日最多单量', '5') + .option('--shop ', '店铺ID') + .option('-p, --unit-price ', '单价区间') + .option('--status ', '状态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); }); diff --git a/ecom-script/package.json b/ecom-script/package.json index b8128d1f..4e574b1d 100644 --- a/ecom-script/package.json +++ b/ecom-script/package.json @@ -2,12 +2,11 @@ "name": "ecom-script", "version": "1.0.0", "private": true, - "description": "ECOM data seed scripts", + "description": "ECOM 订单刷单/删单工具", "type": "module", "scripts": { - "seed": "node main.js", - "seed:help": "node main.js --help", - "seed:interactive": "node main.js -i" + "start": "node main.js", + "start:help": "node main.js --help" }, "dependencies": { "@inquirer/prompts": "^8.5.0", diff --git a/ecom-script/src/cleaner.js b/ecom-script/src/cleaner.js new file mode 100644 index 00000000..25e5b24a --- /dev/null +++ b/ecom-script/src/cleaner.js @@ -0,0 +1,42 @@ +export async function deleteOrders(conn, { companyId, specIds, shopIds, startDate, endDate, verbose, dryRun }) { + const conditions = ['company_id = ?']; + const params = [companyId]; + + if (specIds && specIds.length > 0) { + const placeholders = specIds.map(() => '?').join(','); + conditions.push(`product_spec_id IN (${placeholders})`); + params.push(...specIds); + } + + if (shopIds && shopIds.length > 0) { + const placeholders = shopIds.map(() => '?').join(','); + conditions.push(`shop_id IN (${placeholders})`); + params.push(...shopIds); + } + + if (startDate) { + conditions.push('order_time >= ?'); + params.push(startDate + ' 00:00:00'); + } + + if (endDate) { + conditions.push('order_time <= ?'); + params.push(endDate + ' 23:59:59'); + } + + const where = conditions.join(' AND '); + + if (dryRun) { + const [rows] = await conn.execute( + `SELECT COUNT(*) AS cnt FROM ec_order WHERE ${where}`, + params + ); + return { matched: rows[0].cnt, deleted: 0 }; + } + + const [result] = await conn.execute( + `DELETE FROM ec_order WHERE ${where}`, + params + ); + return { matched: result.affectedRows, deleted: result.affectedRows }; +} diff --git a/ecom-script/src/generator.js b/ecom-script/src/generator.js index e58e9288..86d92346 100644 --- a/ecom-script/src/generator.js +++ b/ecom-script/src/generator.js @@ -40,7 +40,51 @@ export function generatePlatformOrderNo(companyId, seenSet) { throw new Error('Unable to generate unique platform order number'); } -export function generateOrders(config) { +function makeOrder(config, spec, shop, status, orderTime, seenOrderNos, remarkPool, priceRange) { + const quantity = randInt(1, 5); + + let unitPrice; + if (priceRange) { + unitPrice = Math.round(rand(priceRange[0], priceRange[1]) * 100) / 100; + } else { + const baseCost = Number(spec.product_cost); + if (baseCost >= 10) { + unitPrice = Math.round(baseCost * rand(1.3, 3.0) * 100) / 100; + } else if (baseCost > 0) { + unitPrice = Math.round(rand(9.9, 59.9) * 100) / 100; + } else { + unitPrice = Math.round(rand(9.9, 99.9) * 100) / 100; + } + } + if (unitPrice < 1) unitPrice = Math.round(rand(9.9, 49.9) * 100) / 100; + + const receivedAmount = Math.round(unitPrice * quantity * rand(0.85, 1.0) * 100) / 100; + const platformOrderNo = generatePlatformOrderNo(config.companyId, seenOrderNos); + const remark = remarkPool[randInt(0, remarkPool.length - 1)]; + + return { + company_id: config.companyId, + shop_id: shop.id, + product_spec_id: spec.id, + spec_code: spec.spec_code, + status_id: status.id, + platform_order_no: platformOrderNo, + link_product_name: spec.product_name, + link_spec_name: spec.name, + received_amount: receivedAmount, + quantity, + unit_price: unitPrice, + product_cost: spec.product_cost, + shipping_cost: spec.shipping_cost, + other_cost: spec.other_cost, + remark, + import_task_id: null, + confirm: config.confirm, + order_time: formatDateTime(orderTime), + }; +} + +export function* iterateOrders(config) { const { companyId, specs, shops, statuses, priceRange, dailyMin, dailyMax, confirm, @@ -48,7 +92,8 @@ export function generateOrders(config) { remarkPool, } = config; - const orders = []; + const cfg = { companyId, confirm }; + let total = 0; for (const spec of specs) { let current = new Date(startDate); @@ -64,47 +109,9 @@ export function generateOrders(config) { for (let i = 0; i < count; i++) { const status = statuses[randInt(0, statuses.length - 1)]; const orderTime = randomDate(dayStart, dayEnd); - const quantity = randInt(1, 5); + total++; - let unitPrice; - if (priceRange) { - unitPrice = Math.round(rand(priceRange[0], priceRange[1]) * 100) / 100; - } else { - const baseCost = Number(spec.product_cost); - if (baseCost >= 10) { - unitPrice = Math.round(baseCost * rand(1.3, 3.0) * 100) / 100; - } else if (baseCost > 0) { - unitPrice = Math.round(rand(9.9, 59.9) * 100) / 100; - } else { - unitPrice = Math.round(rand(9.9, 99.9) * 100) / 100; - } - } - if (unitPrice < 1) unitPrice = Math.round(rand(9.9, 49.9) * 100) / 100; - - const receivedAmount = Math.round(unitPrice * quantity * rand(0.85, 1.0) * 100) / 100; - const platformOrderNo = generatePlatformOrderNo(companyId, seenOrderNos); - const remark = remarkPool[randInt(0, remarkPool.length - 1)]; - - orders.push({ - company_id: companyId, - shop_id: shop.id, - product_spec_id: spec.id, - spec_code: spec.spec_code, - status_id: status.id, - platform_order_no: platformOrderNo, - link_product_name: spec.product_name, - link_spec_name: spec.name, - received_amount: receivedAmount, - quantity, - unit_price: unitPrice, - product_cost: spec.product_cost, - shipping_cost: spec.shipping_cost, - other_cost: spec.other_cost, - remark, - import_task_id: null, - confirm, - order_time: formatDateTime(orderTime), - }); + yield makeOrder(cfg, spec, shop, status, orderTime, seenOrderNos, remarkPool, priceRange); } } @@ -112,5 +119,5 @@ export function generateOrders(config) { } } - return orders; + return total; } diff --git a/ecom-script/src/inserter.js b/ecom-script/src/inserter.js index 6d7e516d..c0d357a5 100644 --- a/ecom-script/src/inserter.js +++ b/ecom-script/src/inserter.js @@ -1,5 +1,7 @@ import cliProgress from 'cli-progress'; +export const BATCH_SIZE = 1000; + export async function deleteExistingOrders(conn, companyId, specs, verbose) { let total = 0; for (const spec of specs) { @@ -15,45 +17,23 @@ export async function deleteExistingOrders(conn, companyId, specs, verbose) { return total; } -export async function insertOrders(conn, orders, verbose) { - const sql = `INSERT INTO ec_order - (company_id, shop_id, product_spec_id, spec_code, status_id, platform_order_no, - link_product_name, link_spec_name, received_amount, quantity, unit_price, - product_cost, shipping_cost, other_cost, remark, import_task_id, confirm, order_time) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, ?, ?)`; +const SQL = `INSERT INTO ec_order + (company_id, shop_id, product_spec_id, spec_code, status_id, platform_order_no, + link_product_name, link_spec_name, received_amount, quantity, unit_price, + product_cost, shipping_cost, other_cost, remark, import_task_id, confirm, order_time) + VALUES ?`; - const total = orders.length; - let inserted = 0; - let failed = 0; - - const bar = new cliProgress.SingleBar({ - format: '刷入进度 |{bar}| {percentage}% | {value}/{total} 条 | 成功: {inserted} 失败: {failed}', - barCompleteChar: '█', - barIncompleteChar: '░', - hideCursor: true, - }, cliProgress.Presets.shades_classic); - - bar.start(total, 0, { inserted: 0, failed: 0 }); - - for (let i = 0; i < orders.length; i++) { - const o = orders[i]; - try { - await conn.execute(sql, [ - o.company_id, o.shop_id, o.product_spec_id, o.spec_code, o.status_id, o.platform_order_no, - o.link_product_name, o.link_spec_name, o.received_amount, o.quantity, o.unit_price, - o.product_cost, o.shipping_cost, o.other_cost, - o.remark, o.confirm, o.order_time, - ]); - inserted++; - } catch (err) { - failed++; - if (verbose) { - bar.log(` Failed: ${err.message}\n`); - } - } - bar.update(i + 1, { inserted, failed }); - } - - bar.stop(); - return { inserted, failed }; +function toRow(o) { + return [ + o.company_id, o.shop_id, o.product_spec_id, o.spec_code, o.status_id, o.platform_order_no, + o.link_product_name, o.link_spec_name, o.received_amount, o.quantity, o.unit_price, + o.product_cost, o.shipping_cost, o.other_cost, + o.remark, null, o.confirm, o.order_time, + ]; +} + +export async function insertBatch(conn, batch) { + const rows = batch.map(toRow); + const [result] = await conn.query(SQL, [rows]); + return result.affectedRows; } diff --git a/ecom-script/src/prompt.js b/ecom-script/src/prompt.js index b9b641a6..66957938 100644 --- a/ecom-script/src/prompt.js +++ b/ecom-script/src/prompt.js @@ -204,3 +204,130 @@ export function pickRandomSpecs(specList, count) { const shuffled = shuffle([...specList]); return shuffled.slice(0, Math.min(count, specList.length)); } + +export async function promptDeleteOptions(options) { + const { company, companyList, specList } = options; + const prompts = []; + + if (!company && companyList) { + prompts.push({ + type: 'list', + name: 'company', + message: '选择公司:', + choices: companyList.map(c => ({ name: `[${c.id}] ${c.name}`, value: c.id })), + pageSize: 15, + }); + } + + if (company) { + prompts.push({ + type: 'confirm', + name: 'deleteAll', + message: `清空该公司所有订单?`, + default: false, + }); + + prompts.push({ + type: 'list', + name: 'datePreset', + message: '按时间范围筛选(可选):', + choices: [ + { name: '不限时间', value: 'all' }, + { name: '最近 7 天', value: '7d' }, + { name: '最近 30 天', value: '30d' }, + { name: '最近 90 天', value: '90d' }, + { name: '本月', value: 'thisMonth' }, + { name: '自定义', value: 'custom' }, + ], + }); + + { + const now = new Date(); + const y = now.getFullYear(); + const m = String(now.getMonth() + 1).padStart(2, '0'); + const d = String(now.getDate()).padStart(2, '0'); + + prompts.push({ + type: 'input', + name: 'startDate', + message: '开始日期 (YYYY-MM-DD):', + when: a => a.datePreset === 'custom', + validate: v => /^\d{4}-\d{2}-\d{2}$/.test(v) || '格式: YYYY-MM-DD', + }); + + prompts.push({ + type: 'input', + name: 'endDate', + message: '结束日期 (YYYY-MM-DD):', + when: a => a.datePreset === 'custom', + validate: v => /^\d{4}-\d{2}-\d{2}$/.test(v) || '格式: YYYY-MM-DD', + }); + } + + if (!options.deleteAll && specList) { + prompts.push({ + type: 'number', + name: 'specCount', + message: `随机选取几个规格删除?(共有 ${specList.length} 个,0=全部规格):`, + default: 0, + validate: v => (v >= 0 && v <= specList.length) || `请输入 0~${specList.length}`, + }); + } + + prompts.push({ + type: 'confirm', + name: 'dryRun', + message: '先预览要删除的数量?', + default: true, + }); + + prompts.push({ + type: 'confirm', + name: 'confirmDelete', + message: '确认删除?', + default: false, + when: a => !a.dryRun, + }); + } + + const answers = await inquirer.prompt(prompts); + + if (answers.datePreset && answers.datePreset !== 'all' && answers.datePreset !== 'custom') { + const now = new Date(); + const y = now.getFullYear(); + const m = now.getMonth() + 1; + const d = now.getDate(); + const pad = (n) => String(n).padStart(2, '0'); + + switch (answers.datePreset) { + case '7d': { + const sd = new Date(now); + sd.setDate(d - 6); + answers.startDate = `${sd.getFullYear()}-${pad(sd.getMonth() + 1)}-${pad(sd.getDate())}`; + answers.endDate = `${y}-${pad(m)}-${pad(d)}`; + break; + } + case '30d': { + const sd = new Date(now); + sd.setDate(d - 29); + answers.startDate = `${sd.getFullYear()}-${pad(sd.getMonth() + 1)}-${pad(sd.getDate())}`; + answers.endDate = `${y}-${pad(m)}-${pad(d)}`; + break; + } + case '90d': { + const sd = new Date(now); + sd.setDate(d - 89); + answers.startDate = `${sd.getFullYear()}-${pad(sd.getMonth() + 1)}-${pad(sd.getDate())}`; + answers.endDate = `${y}-${pad(m)}-${pad(d)}`; + break; + } + case 'thisMonth': + answers.startDate = `${y}-${pad(m)}-01`; + answers.endDate = `${y}-${pad(m)}-${pad(d)}`; + break; + } + delete answers.datePreset; + } + + return answers; +}