seed.ts
TypeScript · 83 рядків
1// Заливка через API: склади, бренди, 100 категорій, товари фейкера, початкові залишки звичайним прийманням.
2//
3// node scripts/seed.ts [--url http://127.0.0.1:3000] [--brands 10] [--sku 300-600] [--share 0.9] [--qty 5-55]
4// [--bundles 0.05] [--workers 16] [--seed 42] [--reset]
5//
6// Типово — невеликий каталог для сторінки (~4,5 тис. товарів). Для прогону: --brands 50 --sku 4000-6000 (як R-05).
7import { parseArgs } from 'node:util';
8import { Api } from './client.ts';
9import { Faker } from './faker.ts';
10import { Latency, fmt, int, latencyTable, pool } from './measure.ts';
11
12const { values: v } = parseArgs({
13 options: {
14 url: { type: 'string', default: 'http://127.0.0.1:3000' },
15 brands: { type: 'string', default: '10' },
16 sku: { type: 'string', default: '300-600' },
17 share: { type: 'string', default: '0.9' },
18 qty: { type: 'string', default: '5-55' },
19 bundles: { type: 'string', default: '0.05' },
20 warehouses: { type: 'string', default: '2' },
21 workers: { type: 'string', default: '16' },
22 seed: { type: 'string', default: '42' },
23 reset: { type: 'boolean', default: false },
24 },
25});
26const range = (s: string): [number, number] => { const [a, b] = s.split('-').map(Number); return [a, b ?? a]; };
27const [skuMin, skuMax] = range(v.sku!);
28const [qtyMin, qtyMax] = range(v.qty!);
29
30const api = new Api(v.url!);
31const f = new Faker(Number(v.seed));
32const lat = new Latency();
33const t0 = performance.now();
34
35const meta = await api.get('/api/meta');
36if (meta.products > 0) {
37 if (!v.reset) {
38 console.error(`У базі вже ${meta.products} товарів. Повторна заливка: --reset (очистить запас, журнал і каталог).`);
39 process.exit(1);
40 }
41 await api.post('/api/maintenance/reset', { catalog: true });
42}
43
44// 1. довідники й каталог
45const warehouses = Array.from({ length: Number(v.warehouses) }, (_, i) => ({ id: i + 1, name: `Склад ${i + 1}` }));
46const brands = f.brands(Number(v.brands));
47const products = f.products({ brands, skuMin, skuMax, categoriesPerBrand: [8, 40], sharedSkuShare: 0.04 });
48await api.post('/api/catalog/import', { warehouses, brands, categories: f.categories() });
49const ids: number[] = [];
50for (let i = 0; i < products.length; i += 10_000) {
51 const chunk = products.slice(i, i + 10_000);
52 const r = await lat.time('import 10k товарів', () => api.post<{ productIds: number[] }>('/api/catalog/import', { products: chunk }));
53 ids.push(...r!.productIds);
54}
55const tCatalog = performance.now();
56console.log(`каталог: ${int(products.length)} товарів, ${brands.length} брендів, 100 категорій — ${fmt((tCatalog - t0) / 1000)} с`);
57
58// 2. початкові залишки — звичайним прийманням (той самий шлях, що й фура)
59const now = Date.now();
60const tasks: (() => Promise<unknown>)[] = [];
61let units = 0;
62for (const w of warehouses) {
63 products.forEach((p, i) => {
64 if (!f.rng.chance(Number(v.share))) return;
65 const qty = f.roundToPack(p.category_id, f.rng.int(qtyMin, qtyMax));
66 const lot = f.lot(p.category_id, qty, now, { bundleShare: Number(v.bundles) });
67 const locationId = f.location();
68 units += qty;
69 tasks.push(() => lat.time('receive', () => api.post('/api/receipts', { warehouseId: w.id, productId: ids[i], locationId, ...lot })));
70 });
71}
72f.rng.shuffle(tasks);
73await pool(Number(v.workers), tasks);
74const tStock = performance.now();
75
76const inv = await api.get('/api/invariants');
77console.log(`залишки: ${int(tasks.length)} партій, ${int(units)} од. — ${fmt((tStock - tCatalog) / 1000)} с, ${int(tasks.length / ((tStock - tCatalog) / 1000))} партій/с`);
78console.log(latencyTable(lat));
79console.log(`інваріанти: ${inv.ok ? 'OK' : inv.violations.map((x: any) => `${x.code} ${x.count}`).join(', ')} (${fmt(inv.ms)} мс)`);
80const sample = products.slice(0, 3).map((p) => `${brands[p.brand_id - 1].name} ${p.sku}`);
81console.log(`для сторінки, наприклад: ${sample.join(' · ')}`);
82api.close();
83