feat: 添加 ecom-script 刷单工具 (seed-orders CLI + 交互模式 + 随机选规格 + 进度条)

This commit is contained in:
小蟑螂
2026-05-28 01:35:40 +08:00
parent 05babc0daa
commit 054cac86a8
9 changed files with 1006 additions and 53 deletions
+2
View File
@@ -0,0 +1,2 @@
node_modules/
package-lock.json
+282
View File
@@ -0,0 +1,282 @@
#!/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);
});
+19
View File
@@ -0,0 +1,19 @@
{
"name": "ecom-script",
"version": "1.0.0",
"private": true,
"description": "ECOM data seed scripts",
"type": "module",
"scripts": {
"seed": "node main.js",
"seed:help": "node main.js --help",
"seed:interactive": "node main.js -i"
},
"dependencies": {
"@inquirer/prompts": "^8.5.0",
"cli-progress": "^3.12.0",
"commander": "^14.0.3",
"inquirer": "^9.3.8",
"mysql2": "^3.14.0"
}
}
+14
View File
@@ -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_dev',
password: opts.dbPassword || 'ecom_dmb_dev',
database: opts.dbName || 'ecom_dmb_dev',
};
const conn = await mysql.createConnection(config);
return conn;
}
+101
View File
@@ -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;
}
+116
View File
@@ -0,0 +1,116 @@
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');
}
export function generateOrders(config) {
const {
companyId, specs, shops, statuses, priceRange,
dailyMin, dailyMax, confirm,
startDate, endDate, seenOrderNos,
remarkPool,
} = config;
const orders = [];
for (const spec of specs) {
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 status = statuses[randInt(0, statuses.length - 1)];
const orderTime = randomDate(dayStart, dayEnd);
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(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),
});
}
}
current.setDate(current.getDate() + 1);
}
}
return orders;
}
+59
View File
@@ -0,0 +1,59 @@
import cliProgress from 'cli-progress';
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;
}
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 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 };
}
+206
View File
@@ -0,0 +1,206 @@
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));
}