mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-24 19:49:19 +08:00
refacor: 重构目录架构
This commit is contained in:
@@ -0,0 +1,2 @@
|
||||
node_modules/
|
||||
package-lock.json
|
||||
Executable
+364
@@ -0,0 +1,364 @@
|
||||
#!/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 { 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;
|
||||
const parts = str.split('-');
|
||||
if (parts.length === 1) return [Number(parts[0]), Number(parts[0])];
|
||||
return [Number(parts[0]), Number(parts[1])];
|
||||
}
|
||||
|
||||
// ─── Seed ───────────────────────────────────────────────────
|
||||
async function seedHandler(opts) {
|
||||
const DAYS_AGO = 30;
|
||||
const now = new Date();
|
||||
|
||||
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 {
|
||||
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 companyAnswers = await promptMissingOptions({ company: undefined, companyList: companies });
|
||||
companyId = companyAnswers.company;
|
||||
|
||||
const company = await verifyCompany(conn, companyId);
|
||||
const specList = await fetchSpecs(conn, companyId);
|
||||
if (specList.length === 0) { console.error(`公司 ${companyId} 下没有规格`); process.exit(1); }
|
||||
|
||||
const shopList = await fetchShops(conn, companyId, [...new Set(specList.map(s => s.product_id))]);
|
||||
if (shopList.length === 0) { console.error(`公司 ${companyId} 下没有店铺`); process.exit(1); }
|
||||
|
||||
const statusList = await fetchStatuses(conn, companyId);
|
||||
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 || '',
|
||||
});
|
||||
|
||||
const picked = pickRandomSpecs(specList, answers.specCount);
|
||||
specEntries = picked.map(s => s.spec_code || String(s.id));
|
||||
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');
|
||||
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('已取消'); 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 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})`);
|
||||
} 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('没有匹配的规格'); process.exit(1); }
|
||||
|
||||
const productIds = [...new Set(specs.map(s => s.product_id))];
|
||||
const shops = await fetchShops(conn, companyId, productIds, shopIds);
|
||||
if (shops.length === 0) { console.error('没有匹配的店铺'); process.exit(1); }
|
||||
|
||||
const statuses = await fetchStatuses(conn, companyId, statusIds);
|
||||
if (statuses.length === 0) { console.error('没有匹配的状态'); process.exit(1); }
|
||||
|
||||
if (dailyMin < 0 || dailyMax < 0 || dailyMin > dailyMax) {
|
||||
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(shops.length * dayCount * shopDailyAvg);
|
||||
|
||||
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('');
|
||||
|
||||
if (deleteExisting && !dryRun) {
|
||||
console.log('清空已有订单...');
|
||||
const deleted = await deleteExistingOrders(conn, companyId, specs, verbose);
|
||||
console.log(`已删除 ${deleted} 条.\n`);
|
||||
}
|
||||
|
||||
const priceRange = parsePriceRange(unitPrice);
|
||||
const seenOrderNos = new Set();
|
||||
const remarkPool = [null, null, null, '测试数据,请忽略', '系统生成测试订单', null, null];
|
||||
|
||||
const genConfig = {
|
||||
companyId, specs, shops, statuses, priceRange,
|
||||
dailyMin, dailyMax, confirm,
|
||||
startDate, endDate, seenOrderNos, remarkPool,
|
||||
};
|
||||
|
||||
if (dryRun) {
|
||||
let count = 0;
|
||||
const samples = [];
|
||||
for (const order of iterateOrders(genConfig)) {
|
||||
if (samples.length < 5) samples.push(order);
|
||||
count++;
|
||||
}
|
||||
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;
|
||||
}
|
||||
|
||||
// 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('错误:', err.message);
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"name": "ecom-script",
|
||||
"version": "1.0.0",
|
||||
"private": true,
|
||||
"description": "ECOM 订单刷单/删单工具",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"start": "node main.js",
|
||||
"start:help": "node main.js --help"
|
||||
},
|
||||
"dependencies": {
|
||||
"@inquirer/prompts": "^8.5.0",
|
||||
"cli-progress": "^3.12.0",
|
||||
"commander": "^14.0.3",
|
||||
"inquirer": "^9.3.8",
|
||||
"mysql2": "^3.14.0"
|
||||
}
|
||||
}
|
||||
@@ -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 };
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import mysql from 'mysql2/promise';
|
||||
|
||||
export async function createConnection(opts) {
|
||||
const config = {
|
||||
host: opts.dbHost || '192.168.3.100',
|
||||
port: opts.dbPort || 3306,
|
||||
user: opts.dbUser || 'ecom_dmb_test',
|
||||
password: opts.dbPassword || 'ecom_dmb_test',
|
||||
database: opts.dbName || 'ecom_dmb_test',
|
||||
};
|
||||
|
||||
const conn = await mysql.createConnection(config);
|
||||
return conn;
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
export async function verifyCompany(conn, companyId) {
|
||||
const [rows] = await conn.execute('SELECT id, name FROM org_company WHERE id = ?', [companyId]);
|
||||
if (rows.length === 0) {
|
||||
throw new Error(`Company with id ${companyId} not found`);
|
||||
}
|
||||
return rows[0];
|
||||
}
|
||||
|
||||
export async function fetchSpecs(conn, companyId, specIds, specCodes) {
|
||||
const results = [];
|
||||
|
||||
if (specIds && specIds.length > 0) {
|
||||
const placeholders = specIds.map(() => '?').join(',');
|
||||
const [rows] = await conn.execute(
|
||||
`SELECT ps.*, p.name AS product_name, p.product_code
|
||||
FROM ec_product_spec ps
|
||||
JOIN ec_product p ON ps.product_id = p.id
|
||||
WHERE ps.company_id = ? AND ps.id IN (${placeholders})`,
|
||||
[companyId, ...specIds]
|
||||
);
|
||||
results.push(...rows);
|
||||
}
|
||||
|
||||
if (specCodes && specCodes.length > 0) {
|
||||
const placeholders = specCodes.map(() => '?').join(',');
|
||||
const [rows] = await conn.execute(
|
||||
`SELECT ps.*, p.name AS product_name, p.product_code
|
||||
FROM ec_product_spec ps
|
||||
JOIN ec_product p ON ps.product_id = p.id
|
||||
WHERE ps.company_id = ? AND ps.spec_code IN (${placeholders})`,
|
||||
[companyId, ...specCodes]
|
||||
);
|
||||
results.push(...rows);
|
||||
}
|
||||
|
||||
if (specIds === undefined && specCodes === undefined) {
|
||||
const [rows] = await conn.execute(
|
||||
`SELECT ps.*, p.name AS product_name, p.product_code
|
||||
FROM ec_product_spec ps
|
||||
JOIN ec_product p ON ps.product_id = p.id
|
||||
WHERE ps.company_id = ?`,
|
||||
[companyId]
|
||||
);
|
||||
results.push(...rows);
|
||||
}
|
||||
|
||||
const seen = new Set();
|
||||
return results.filter(s => {
|
||||
if (seen.has(s.id)) return false;
|
||||
seen.add(s.id);
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
export async function fetchShops(conn, companyId, productIds, shopIds) {
|
||||
if (shopIds && shopIds.length > 0) {
|
||||
const placeholders = shopIds.map(() => '?').join(',');
|
||||
const [rows] = await conn.execute(
|
||||
`SELECT id, name, platform_id FROM ec_shop
|
||||
WHERE company_id = ? AND id IN (${placeholders})`,
|
||||
[companyId, ...shopIds]
|
||||
);
|
||||
return rows;
|
||||
}
|
||||
|
||||
if (!productIds || productIds.length === 0) {
|
||||
const [rows] = await conn.execute(
|
||||
'SELECT id, name, platform_id FROM ec_shop WHERE company_id = ?',
|
||||
[companyId]
|
||||
);
|
||||
return rows;
|
||||
}
|
||||
|
||||
const productPlaceholders = productIds.map(() => '?').join(',');
|
||||
const [rows] = await conn.execute(
|
||||
`SELECT DISTINCT s.id, s.name, s.platform_id
|
||||
FROM ec_shop s
|
||||
JOIN ec_shop_product_relation spr ON s.id = spr.shop_id
|
||||
WHERE s.company_id = ? AND spr.product_id IN (${productPlaceholders})`,
|
||||
[companyId, ...productIds]
|
||||
);
|
||||
return rows;
|
||||
}
|
||||
|
||||
export async function fetchStatuses(conn, companyId, statusIds) {
|
||||
if (statusIds && statusIds.length > 0) {
|
||||
const placeholders = statusIds.map(() => '?').join(',');
|
||||
const [rows] = await conn.execute(
|
||||
`SELECT id, status_name FROM ec_order_status
|
||||
WHERE company_id = ? AND id IN (${placeholders})`,
|
||||
[companyId, ...statusIds]
|
||||
);
|
||||
return rows;
|
||||
}
|
||||
|
||||
const [rows] = await conn.execute(
|
||||
'SELECT id, status_name FROM ec_order_status WHERE company_id = ? ORDER BY sort_order',
|
||||
[companyId]
|
||||
);
|
||||
return rows;
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
export function rand(min, max) {
|
||||
return Math.random() * (max - min) + min;
|
||||
}
|
||||
|
||||
export function randInt(min, max) {
|
||||
return Math.floor(rand(min, max + 1));
|
||||
}
|
||||
|
||||
export function randomDate(start, end) {
|
||||
return new Date(start.getTime() + Math.random() * (end.getTime() - start.getTime()));
|
||||
}
|
||||
|
||||
export function formatDateTime(d) {
|
||||
const y = d.getFullYear();
|
||||
const M = String(d.getMonth() + 1).padStart(2, '0');
|
||||
const D = String(d.getDate()).padStart(2, '0');
|
||||
const h = String(d.getHours()).padStart(2, '0');
|
||||
const m = String(d.getMinutes()).padStart(2, '0');
|
||||
const s = String(d.getSeconds()).padStart(2, '0');
|
||||
return `${y}-${M}-${D} ${h}:${m}:${s}`;
|
||||
}
|
||||
|
||||
export function formatDate(d) {
|
||||
const y = d.getFullYear();
|
||||
const M = String(d.getMonth() + 1).padStart(2, '0');
|
||||
const D = String(d.getDate()).padStart(2, '0');
|
||||
return `${y}-${M}-${D}`;
|
||||
}
|
||||
|
||||
export function generatePlatformOrderNo(companyId, seenSet) {
|
||||
for (let attempt = 0; attempt < 100; attempt++) {
|
||||
const ts = Date.now().toString(36).toUpperCase();
|
||||
const randStr = Math.random().toString(36).substring(2, 10).toUpperCase();
|
||||
const no = `${ts}-${companyId}${randStr}`;
|
||||
if (!seenSet.has(no)) {
|
||||
seenSet.add(no);
|
||||
return no;
|
||||
}
|
||||
}
|
||||
throw new Error('Unable to generate unique platform order number');
|
||||
}
|
||||
|
||||
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,
|
||||
startDate, endDate, seenOrderNos,
|
||||
remarkPool,
|
||||
} = config;
|
||||
|
||||
const cfg = { companyId, confirm };
|
||||
let total = 0;
|
||||
|
||||
// 单量按「店 × 天」控制;每笔订单从所选规格中随机挑选
|
||||
let current = new Date(startDate);
|
||||
const end = new Date(endDate);
|
||||
|
||||
while (current <= end) {
|
||||
const dayStart = new Date(current);
|
||||
const dayEnd = new Date(current);
|
||||
dayEnd.setHours(23, 59, 59, 999);
|
||||
|
||||
for (const shop of shops) {
|
||||
const count = randInt(dailyMin, dailyMax);
|
||||
for (let i = 0; i < count; i++) {
|
||||
const spec = specs[randInt(0, specs.length - 1)];
|
||||
const status = statuses[randInt(0, statuses.length - 1)];
|
||||
const orderTime = randomDate(dayStart, dayEnd);
|
||||
total++;
|
||||
|
||||
yield makeOrder(cfg, spec, shop, status, orderTime, seenOrderNos, remarkPool, priceRange);
|
||||
}
|
||||
}
|
||||
|
||||
current.setDate(current.getDate() + 1);
|
||||
}
|
||||
|
||||
return total;
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
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) {
|
||||
const [result] = await conn.execute(
|
||||
'DELETE FROM ec_order WHERE company_id = ? AND product_spec_id = ?',
|
||||
[companyId, spec.id]
|
||||
);
|
||||
total += result.affectedRows;
|
||||
if (verbose) {
|
||||
console.log(` Deleted ${result.affectedRows} orders for spec [${spec.id}] ${spec.name}`);
|
||||
}
|
||||
}
|
||||
return total;
|
||||
}
|
||||
|
||||
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 ?`;
|
||||
|
||||
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;
|
||||
}
|
||||
@@ -0,0 +1,333 @@
|
||||
import inquirer from 'inquirer';
|
||||
|
||||
export async function promptMissingOptions(options) {
|
||||
const {
|
||||
company, companyList,
|
||||
specs, specList,
|
||||
shops, shopList,
|
||||
statuses, statusList,
|
||||
} = 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: 'list',
|
||||
name: 'datePreset',
|
||||
message: '选择时间范围:',
|
||||
choices: [
|
||||
{ name: '最近 7 天', value: '7d' },
|
||||
{ name: '最近 30 天', value: '30d' },
|
||||
{ name: '最近 90 天', value: '90d' },
|
||||
{ name: '本月', value: 'thisMonth' },
|
||||
{ name: '上月', value: 'lastMonth' },
|
||||
{ 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');
|
||||
const today = `${y}-${m}-${d}`;
|
||||
const monthStart = `${y}-${m}-01`;
|
||||
const lastM = now.getMonth() === 0 ? 12 : now.getMonth();
|
||||
const lastY = now.getMonth() === 0 ? y - 1 : y;
|
||||
const lastMonthStr = `${lastY}-${String(lastM).padStart(2, '0')}-01`;
|
||||
|
||||
prompts.push({
|
||||
type: 'input',
|
||||
name: 'startDate',
|
||||
message: '开始日期 (YYYY-MM-DD):',
|
||||
default: options.startDate,
|
||||
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):',
|
||||
default: options.endDate,
|
||||
when: a => a.datePreset === 'custom',
|
||||
validate: v => /^\d{4}-\d{2}-\d{2}$/.test(v) || '格式: YYYY-MM-DD',
|
||||
});
|
||||
}
|
||||
|
||||
if ((!specs || specs.length === 0) && specList) {
|
||||
prompts.push({
|
||||
type: 'number',
|
||||
name: 'specCount',
|
||||
message: `随机选取几个规格刷单?(共有 ${specList.length} 个):`,
|
||||
default: Math.min(5, specList.length),
|
||||
validate: v => (v > 0 && v <= specList.length) || `请输入 1~${specList.length}`,
|
||||
});
|
||||
}
|
||||
|
||||
if ((!shops || shops.length === 0) && shopList) {
|
||||
prompts.push({
|
||||
type: 'checkbox',
|
||||
name: 'shops',
|
||||
message: '选择店铺(空格勾选):',
|
||||
choices: shopList.map(sh => ({
|
||||
name: `[${sh.id}] ${sh.name}`,
|
||||
value: sh.id,
|
||||
checked: true,
|
||||
})),
|
||||
pageSize: 15,
|
||||
validate: v => v.length > 0 || '至少选一个店铺',
|
||||
});
|
||||
}
|
||||
|
||||
if ((!statuses || statuses.length === 0) && statusList) {
|
||||
prompts.push({
|
||||
type: 'checkbox',
|
||||
name: 'statuses',
|
||||
message: '选择订单状态(空格勾选):',
|
||||
choices: statusList.map(st => ({
|
||||
name: `[${st.id}] ${st.status_name}`,
|
||||
value: st.id,
|
||||
checked: true,
|
||||
})),
|
||||
pageSize: 15,
|
||||
validate: v => v.length > 0 || '至少选一个状态',
|
||||
});
|
||||
}
|
||||
|
||||
prompts.push({
|
||||
type: 'input',
|
||||
name: 'dailyRange',
|
||||
message: '每店每日单量区间 (如 "3-8"):',
|
||||
default: `${options.dailyMin ?? 1}-${options.dailyMax ?? 5}`,
|
||||
validate: v => /^\d+-\d+$/.test(v) || '格式: 最小-最大 (如 3-8)',
|
||||
});
|
||||
|
||||
prompts.push({
|
||||
type: 'input',
|
||||
name: 'unitPrice',
|
||||
message: '单价区间 (如 "19.9-99.9",留空自动生成):',
|
||||
default: options.unitPrice || '',
|
||||
});
|
||||
|
||||
prompts.push({
|
||||
type: 'confirm',
|
||||
name: 'deleteExisting',
|
||||
message: '是否先清空这些规格的已有订单?',
|
||||
default: false,
|
||||
});
|
||||
|
||||
prompts.push({
|
||||
type: 'confirm',
|
||||
name: 'confirmInsert',
|
||||
message: '确认写入数据库?',
|
||||
default: true,
|
||||
});
|
||||
}
|
||||
|
||||
const answers = await inquirer.prompt(prompts);
|
||||
|
||||
if (answers.datePreset && 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;
|
||||
case 'lastMonth': {
|
||||
const lm = m === 1 ? 12 : m - 1;
|
||||
const ly = m === 1 ? y - 1 : y;
|
||||
const lastMonthEnd = new Date(y, m - 1, 0);
|
||||
answers.startDate = `${ly}-${pad(lm)}-01`;
|
||||
answers.endDate = `${ly}-${pad(lm)}-${pad(lastMonthEnd.getDate())}`;
|
||||
break;
|
||||
}
|
||||
}
|
||||
delete answers.datePreset;
|
||||
}
|
||||
|
||||
if (answers.dailyRange) {
|
||||
const parts = answers.dailyRange.split('-').map(Number);
|
||||
answers.dailyMin = parts[0];
|
||||
answers.dailyMax = parts[1];
|
||||
delete answers.dailyRange;
|
||||
}
|
||||
|
||||
return answers;
|
||||
}
|
||||
|
||||
function shuffle(arr) {
|
||||
for (let i = arr.length - 1; i > 0; i--) {
|
||||
const j = Math.floor(Math.random() * (i + 1));
|
||||
[arr[i], arr[j]] = [arr[j], arr[i]];
|
||||
}
|
||||
return arr;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
Reference in New Issue
Block a user