techtools

load.ts

TypeScript · 552 рядків

1import { mkdirSync, rmSync, statSync, writeFileSync } from 'node:fs';
2import type { AddressInfo } from 'node:net';
3import { cpus, platform, totalmem } from 'node:os';
4import { parseArgs } from 'node:util';
5import { createApi } from './api.ts';
6import { httpClient } from './client.ts';
7import { composeReceipt, newCounters, PROFILES, Rng, type Dating, type SimProduct } from './faker.ts';
8import type { InventoryOptions, IssueLineIn, IssueResult, LotIn } from './inventory.ts';
9
10// Навантажувальний прогін: SKU × бренди, старт фурами, поповнення кожні 2–3 дні до цільового рівня,
11// відвантаження за каналами; кожен товар має дату виготовлення і строк придатності або «вжити до».
12// Заміряє кожен запит, профілює SQL, аналізує строки. --optimized вмикає оптимізації для порівняння.
13const { values: opt } = parseArgs({
14  options: {
15    skus: { type: 'string', default: '500' },
16    brands: { type: 'string', default: '20' },
17    days: { type: 'string', default: '365' },
18    seed: { type: 'string', default: '7' },
19    initial: { type: 'string', default: '1000000' },
20    truck: { type: 'string', default: '10000' },
21    'daily-min': { type: 'string', default: '4000' },
22    'daily-max': { type: 'string', default: '8000' },
23    mix: { type: 'string', default: '20,30,50' }, // % од.: переміщення, опт, роздріб
24    'use-by': { type: 'string', default: '0.3' },  // частка товарів із датою «вжити до» замість строку на картці
25    'old-stock': { type: 'string', default: '0.07' }, // частка партій, що приходять уже залежаними
26    'check-every': { type: 'string', default: '1' },
27    out: { type: 'string', default: 'out/load' },
28    sync: { type: 'string', default: 'FULL' },
29    optimized: { type: 'boolean', default: false },
30  },
31});
32const SKUS = Number(opt.skus);
33const BRANDS = Number(opt.brands);
34const DAYS = Number(opt.days);
35const INITIAL = Number(opt.initial);
36const TRUCK = Number(opt.truck);
37const CHECK = Number(opt['check-every']);
38const OUT = opt.out!;
39const dbFile = `${OUT}/load.db`;
40const OPTIONS: InventoryOptions = opt.optimized
41  ? { orderTx: true, fastIssue: true, incrementalReconcile: true, fastSummary: true, indexes: true }
42  : {};
43
44mkdirSync(OUT, { recursive: true });
45for (const f of [dbFile, `${dbFile}-wal`, `${dbFile}-shm`]) rmSync(f, { force: true });
46const { server } = createApi(dbFile, opt.sync as 'OFF' | 'NORMAL' | 'FULL', OPTIONS);
47await new Promise<void>((r) => server.listen(0, '127.0.0.1', r));
48const client = httpClient(`http://127.0.0.1:${(server.address() as AddressInfo).port}`);
49
50// ---------- заміри ----------
51
52interface Lat { rtt: number[]; handler: number[]; ops: number[] }
53const lat = new Map<string, Lat>();
54const monthly = new Map<string, number[]>(); // `${label}|${month}` → RTT
55let totalOps = 0;
56let handlerTotal = 0;
57let curDay = 0;
58const monthOf = (d: number) => Math.min(12, Math.floor((Math.max(d, 1) - 1) / 30.42) + 1);
59
60async function api<T = any>(label: string, method: string, path: string, body?: unknown): Promise<{ data: T; rtt: number }> {
61  const t = performance.now();
62  const r = await client.call(method, path, body);
63  const rtt = performance.now() - t;
64  if (r.status !== 200) throw new Error(`${method} ${path}: ${r.status} ${JSON.stringify(r.body)}`);
65  const l = lat.get(label) ?? lat.set(label, { rtt: [], handler: [], ops: [] }).get(label)!;
66  const ops = Number(r.headers['x-db-ops']);
67  const h = Number(r.headers['x-handler-ms']);
68  l.rtt.push(rtt);
69  l.handler.push(h);
70  l.ops.push(ops);
71  totalOps += ops;
72  handlerTotal += h;
73  if (curDay > 0) {
74    const k = `${label}|${monthOf(curDay)}`;
75    (monthly.get(k) ?? monthly.set(k, []).get(k)!).push(rtt);
76  }
77  return { data: r.body as T, rtt };
78}
79
80const pct = (a: number[], p: number) => {
81  if (!a.length) return 0;
82  const s = [...a].sort((x, y) => x - y);
83  return s[Math.min(s.length - 1, Math.floor((p / 100) * s.length))];
84};
85const avg = (a: number[]) => (a.length ? a.reduce((s, x) => s + x, 0) / a.length : 0);
86const sum = (a: number[]) => a.reduce((s, x) => s + x, 0);
87const maxOf = (a: number[]) => a.reduce((m, x) => (x > m ? x : m), -Infinity); // без spread: масиви до сотень тисяч
88const f1 = (x: number) => x.toFixed(1);
89const f2 = (x: number) => x.toFixed(2);
90const int = (x: number) => Math.round(x).toLocaleString('uk-UA');
91const pc = (a: number, b: number) => (b ? `${f1((100 * a) / b)}%` : '—');
92
93// ---------- каталог: SKU × бренди, строки придатності ----------
94
95const rng = new Rng(Number(opt.seed));             // каталог і постачання
96const demand = new Rng(Number(opt.seed) * 7919 + 1); // замовлення — не залежать від результатів відбору
97const counters = newCounters();
98const BRAND_NAMES = ['Bosch', 'Febi Bilstein', 'SWAG', 'Mann-Filter', 'Mahle', 'NGK', 'Denso', 'TRW', 'Brembo', 'SKF',
99  'INA', 'Gates', 'Valeo', 'Continental', 'Delphi', 'Hella', 'Lemförder', 'Sachs', 'Monroe', 'Castrol'];
100const brands = Array.from({ length: BRANDS }, (_, i) => BRAND_NAMES[i] ?? `Brand${i + 1}`);
101const totalShare = PROFILES.reduce((s, p) => s + p.share, 0);
102// Строк придатності за категорією, днів (умовно: «уявімо, що кожен товар має строк»).
103const LIFE: Record<string, [number, number]> = {
104  'Кріплення': [1825, 3650], 'Свічки': [1825, 3650], 'Фільтри': [1095, 1825], 'Гальмівні колодки': [1095, 1825],
105  'Лампи': [1825, 3650], 'Герметики': [365, 720], 'Масла': [1095, 1825], 'Підшипники і ремені': [1095, 2555],
106  'Дорогі вузли (серійні)': [1825, 3650],
107};
108
109interface Dated { life: number; useBy: boolean }
110const dates = new Map<SimProduct, Dated>();
111const catalog: SimProduct[] = [];
112for (let s = 0; s < SKUS; s++) {
113  let x = rng.next() * totalShare;
114  const prof = PROFILES.find((p) => (x -= p.share) < 0) ?? PROFILES[0];
115  const sku = `${rng.int(10, 99)}-${String(rng.int(0, 99999)).padStart(5, '0')}`;
116  const name = rng.pick(prof.names);
117  const top = prof.levels.at(-1);
118  const [lo, hi] = LIFE[prof.category] ?? [1095, 1825];
119  for (const brand of brands) {
120    const life = rng.int(lo, hi);
121    const useBy = rng.chance(Number(opt['use-by']));
122    const sp: SimProduct = {
123      input: { brand, sku, name: `${name} ${brand}`, category: prof.category, is_serial: !!prof.serial,
124        shelf_life_days: useBy ? null : life, std_pack_type: top?.type ?? null, std_pack_size: top?.size ?? null },
125      profile: prof, cls: 'A', lambda: 0, lead: 0, rop: 0, orderQty: 0,
126    };
127    dates.set(sp, { life, useBy });
128    catalog.push(sp);
129  }
130}
131
132// Дати партії: зазвичай свіжа (вік до 30% строку), частина — залежана (30–80%).
133// Товар зі строком на картці отримує дату виготовлення; «вжити до» — лише кінцеву дату.
134const receiptFreshness = { lots: 0, units: 0, buckets: { '< 50%': 0, '50–70%': 0, '70–90%': 0, '≥ 90%': 0 } as Record<string, number> };
135function dating(sp: SimProduct, day: number): Dating {
136  const d = dates.get(sp)!;
137  return () => {
138    const age = rng.chance(Number(opt['old-stock'])) ? rng.int(Math.floor(d.life * 0.3), Math.floor(d.life * 0.8)) : rng.int(0, Math.floor(d.life * 0.3));
139    const mfg = day - age;
140    return d.useBy ? { expiry_day: mfg + d.life } : { mfg_day: mfg };
141  };
142}
143function noteFreshness(sp: SimProduct, lot: LotIn, day: number): void {
144  const d = dates.get(sp)!;
145  const expiry = lot.expiry_day ?? (lot.mfg_day != null ? lot.mfg_day + d.life : null);
146  if (expiry == null) return;
147  const f = (expiry - day) / d.life;
148  const units = lot.lines.reduce((s, l) => s + l.pack_size * l.pack_count, 0);
149  const b = f < 0.5 ? '< 50%' : f < 0.7 ? '50–70%' : f < 0.9 ? '70–90%' : '≥ 90%';
150  receiptFreshness.lots++;
151  receiptFreshness.units += units;
152  receiptFreshness.buckets[b] += units;
153}
154
155// Попит за Ципфом: вага товару = 1 / ранг^0.8 у випадковому порядку.
156const order = catalog.map((_, i) => i).sort(() => rng.next() - 0.5);
157const weight = new Array<number>(catalog.length);
158order.forEach((idx, rank) => (weight[idx] = 1 / Math.pow(rank + 1, 0.8)));
159const cum: number[] = [];
160weight.reduce((s, w, i) => (cum[i] = s + w), 0);
161const pickProduct = () => {
162  const x = demand.next() * cum[cum.length - 1];
163  let lo = 0;
164  let hi = cum.length - 1;
165  while (lo < hi) {
166    const mid = (lo + hi) >> 1;
167    if (cum[mid] < x) lo = mid + 1;
168    else hi = mid;
169  }
170  return catalog[lo];
171};
172// Найменше пакування товару: до нього округлюються цільовий рівень і поставка (розсип — 1).
173const unitOf = (sp: SimProduct) => (sp.profile.serial ? 1 : sp.profile.levels[0]?.size ?? 1);
174const roundUp = (q: number, u: number) => Math.ceil(q / u) * u;
175
176const tStart = performance.now();
177for (let i = 0; i < catalog.length; i += 1000) {
178  const part = catalog.slice(i, i + 1000);
179  const { data } = await api<{ id: number }[]>('products (1000 шт.)', 'POST', '/products', part.map((p) => p.input));
180  data.forEach((r, k) => (part[k].id = r.id));
181}
182const byId = new Map(catalog.map((p) => [p.id!, p]));
183const sumW = cum[cum.length - 1];
184// Цільовий рівень товару (max) ∝ попиту, кратний найменшому пакуванню; серійних — не більше 40 шт.
185const target = new Map<number, number>();
186const SERIAL_CAP = 40;
187let scale = 1;
188for (let iter = 0; iter < 20; iter++) {
189  let total = 0;
190  for (let i = 0; i < catalog.length; i++) {
191    const u = unitOf(catalog[i]);
192    let t = Math.max(u, Math.floor((scale * INITIAL * weight[i]) / sumW / u) * u);
193    if (catalog[i].profile.serial) t = Math.min(t, SERIAL_CAP);
194    target.set(catalog[i].id!, t);
195    total += t;
196  }
197  if (Math.abs(total - INITIAL) / INITIAL < 0.01) break;
198  scale *= INITIAL / total;
199}
200
201// ---------- фури ----------
202
203interface TruckStat { day: number; products: number; lots: number; places: number; units: number; requests: number; busyMs: number; wallMs: number }
204const trucks: TruckStat[] = [];
205let truckSeq = 0;
206
207function loadTrucks(plan: { sp: SimProduct; qty: number }[]): { sp: SimProduct; qty: number }[][] {
208  const out: { sp: SimProduct; qty: number }[][] = [];
209  let cur: { sp: SimProduct; qty: number }[] = [];
210  let cap = TRUCK * (0.9 + rng.next() * 0.2);
211  let units = 0;
212  for (const p of plan) {
213    cur.push(p);
214    units += p.qty;
215    if (units >= cap) {
216      out.push(cur);
217      cur = [];
218      units = 0;
219      cap = TRUCK * (0.9 + rng.next() * 0.2);
220    }
221  }
222  if (cur.length) out.push(cur);
223  return out;
224}
225
226// Розвантаження: кожна партія (спайка/палета/група рядків) — окремий запит приймання, як підтвердження комірника.
227async function unload(truck: { sp: SimProduct; qty: number }[], day: number): Promise<number> {
228  const doc = `TRK-${++truckSeq}`;
229  const t = performance.now();
230  let busy = 0;
231  let lots = 0;
232  let places = 0;
233  let units = 0;
234  for (const { sp, qty } of truck) {
235    for (const lot of composeReceipt(sp, qty, day, rng, counters, dating(sp, day)) as LotIn[]) {
236      const { rtt } = await api('receipt: партія', 'POST', '/receipts', [{ doc, day, lots: [lot] }]);
237      noteFreshness(sp, lot, day);
238      busy += rtt;
239      lots++;
240      // Фізичні місця: спайка/палета — одне місце; поза нею — кожне пакування; розсип — одне місце.
241      places += lot.container ? 1 : lot.lines.reduce((n, l) => n + (l.pack_type === 'unit' ? 1 : l.pack_count), 0);
242    }
243    units += qty;
244  }
245  trucks.push({ day, products: truck.length, lots, places, units, requests: lots, busyMs: busy, wallMs: performance.now() - t });
246  return units;
247}
248
249const tInitial = performance.now();
250const initialPlan = catalog.map((sp) => ({ sp, qty: target.get(sp.id!)! })).sort(() => rng.next() - 0.5);
251let received = 0;
252for (const t of loadTrucks(initialPlan)) received += await unload(t, 0);
253const initialMs = performance.now() - tInitial;
254const initialTrucks = trucks.length;
255console.log(`старт: ${initialTrucks} фур, ${int(received)} од., ${f1(initialMs / 1000)} с`);
256
257// ---------- канали ----------
258
259type Channel = 'transfer' | 'wholesale' | 'retail';
260const [mixT, mixW, mixR] = opt.mix!.split(',').map((x) => Number(x) / 100);
261const CH: Record<Channel, { share: number; label: string; prefix: string; lines: [number, number] }> = {
262  transfer: { share: mixT, label: 'issue: переміщення', prefix: 'TR', lines: [20, 60] },
263  wholesale: { share: mixW, label: 'issue: опт', prefix: 'WS', lines: [5, 20] },
264  retail: { share: mixR, label: 'issue: роздріб', prefix: 'RT', lines: [1, 3] },
265};
266const CHANNELS = Object.keys(CH) as Channel[];
267interface ChStat {
268  orders: number; lines: number; requested: number; issued: number; shortLines: number; opened: number; cut: number;
269  kinds: Record<string, number>; fefoViol: number; ageDays: number[]; fresh: Record<string, number>;
270  orderLat: { rtt: number; scannedPerLine: number }[];
271}
272const FRESH = ['< 10%', '10–25%', '25–50%', '50–75%', '≥ 75%'];
273const chStat = Object.fromEntries(CHANNELS.map((c) => [c, {
274  orders: 0, lines: 0, requested: 0, issued: 0, shortLines: 0, opened: 0, cut: 0,
275  kinds: { container: 0, pack: 0, loose: 0, serial: 0 }, fefoViol: 0, ageDays: [], fresh: Object.fromEntries(FRESH.map((b) => [b, 0])), orderLat: [],
276}])) as Record<Channel, ChStat>;
277
278// Рядок не більший за половину цільового рівня товару: клієнт не замовляє спайку того, що склад тримає десятками.
279function lineQty(sp: SimProduct, ch: Channel): number {
280  const q = rawQty(sp, ch);
281  const cap = Math.floor(target.get(sp.id!)! / 2);
282  if (q <= cap) return q;
283  const u = unitOf(sp);
284  return Math.max(1, Math.floor(cap / u) * u);
285}
286
287function rawQty(sp: SimProduct, ch: Channel): number {
288  const pr = sp.profile;
289  if (ch === 'retail' || pr.serial || !pr.levels.length) return demand.int(1, pr.serial ? 1 : 3);
290  const top = pr.levels.at(-1)!;
291  const ct = pr.container ? top.size * pr.container.of : 0;
292  const r = demand.next();
293  if (ch === 'transfer') return ct && r < 0.4 ? ct : top.size * demand.int(1, 5); // великі замовлення
294  if (r < 0.2) return demand.int(1, pr.smallMax);
295  if (r < 0.9) return demand.pick(pr.levels).size * demand.int(1, 3);
296  return ct || top.size * demand.int(2, 5);
297}
298
299function buildOrders(day: number, ch: Channel, budget: number): IssueLineIn[][] {
300  const orders: IssueLineIn[][] = [];
301  const [minL, maxL] = CH[ch].lines;
302  let n = 0;
303  while (budget > 0) {
304    const lines: IssueLineIn[] = [];
305    const want = demand.int(minL, maxL);
306    const ord = `${CH[ch].prefix}-${day}-${++n}`;
307    while (lines.length < want && budget > 0) {
308      const sp = pickProduct();
309      const qty = lineQty(sp, ch);
310      lines.push({ order: ord, product_id: sp.id, qty });
311      budget -= qty;
312    }
313    orders.push(lines);
314  }
315  return orders;
316}
317
318// ---------- дні ----------
319
320interface DayStat { day: number; outUnits: number; requests: number; busyMs: number; trucks: number; reconcileMs: number }
321const days: DayStat[] = [];
322const growth: { day: number; items: number; archive: number; tx: number; stock: number }[] = [];
323const expiredByMonth: number[] = new Array(13).fill(0);
324const writtenByMonth: number[] = new Array(13).fill(0);
325let nextDelivery = rng.int(2, 3);
326let violations = 0;
327
328for (let day = 1; day <= DAYS; day++) {
329  curDay = day;
330  const ds: DayStat = { day, outUnits: 0, requests: 0, busyMs: 0, trucks: 0, reconcileMs: 0 };
331  const call = async <T>(label: string, method: string, path: string, body?: unknown) => {
332    const r = await api<T>(label, method, path, body);
333    ds.requests++;
334    ds.busyMs += r.rtt;
335    return r.data;
336  };
337
338  // поставка: довезти все продане до цільового рівня
339  if (day === nextDelivery) {
340    nextDelivery = day + rng.int(2, 3);
341    const stock = await call<{ product_id: number; available: number }[]>('stock: зведення', 'GET', '/stock');
342    const plan = stock
343      .map((s) => ({ sp: byId.get(s.product_id)!, deficit: target.get(s.product_id)! - s.available }))
344      .filter((x) => x.sp && x.deficit > 0)
345      .map((x) => ({ sp: x.sp, qty: roundUp(x.deficit, unitOf(x.sp)) }))
346      .sort(() => rng.next() - 0.5);
347    for (const t of loadTrucks(plan)) {
348      const before = trucks.length;
349      await unload(t, day);
350      ds.trucks++;
351      ds.requests += trucks[before].requests;
352      ds.busyMs += trucks[before].busyMs;
353    }
354  }
355
356  expiredByMonth[monthOf(day)] += (await call<{ expired_items: number }>('maintenance: строки', 'POST', '/maintenance/expire', { day })).expired_items;
357
358  // відвантаження
359  const U = demand.int(Number(opt['daily-min']), Number(opt['daily-max']));
360  const orders = CHANNELS.flatMap((ch) => buildOrders(day, ch, Math.round(U * CH[ch].share)).map((o) => ({ ch, o })))
361    .sort(() => demand.next() - 0.5);
362  for (const { ch, o } of orders) {
363    const { data: res, rtt } = await api<(IssueResult | { error: string })[]>(CH[ch].label, 'POST', '/issues', { day, lines: o });
364    ds.requests++;
365    ds.busyMs += rtt;
366    const st = chStat[ch];
367    st.orders++;
368    let scanned = 0;
369    for (const r of res) {
370      if ('error' in r) continue;
371      st.lines++;
372      st.requested += r.requested;
373      st.issued += r.issued;
374      scanned += r.scanned;
375      if (r.short) st.shortLines++;
376      if (r.fefo_violation) st.fefoViol++;
377      st.opened += r.opened_packs;
378      st.cut += r.opened_containers;
379      const d = dates.get(byId.get(r.product_id)!)!;
380      for (const p of r.picks) {
381        st.kinds[p.kind] += p.qty;
382        if (p.expiry_day == null) continue;
383        const f = (p.expiry_day - day) / d.life;
384        st.fresh[f < 0.1 ? FRESH[0] : f < 0.25 ? FRESH[1] : f < 0.5 ? FRESH[2] : f < 0.75 ? FRESH[3] : FRESH[4]] += p.qty;
385        st.ageDays.push(day - (p.expiry_day - d.life));
386      }
387      ds.outUnits += r.issued;
388    }
389    st.orderLat.push({ rtt, scannedPerLine: scanned / Math.max(1, res.length) });
390  }
391
392  if (day % 30 === 0) writtenByMonth[monthOf(day)] += (await call<{ qty: number }>('maintenance: списання', 'POST', '/maintenance/write-off-expired', { day, doc: `WO-${day}` })).qty;
393  if (day % CHECK === 0 || day === DAYS) {
394    const t = performance.now();
395    const rc = await call<{ ok: boolean; violations: unknown[] }>('reconcile', 'GET', '/reconcile');
396    ds.reconcileMs = performance.now() - t;
397    violations += rc.violations.length;
398  }
399  if (day % 7 === 0 || day === 1 || day === DAYS) {
400    const st = await call<any>('stats', 'GET', '/stats');
401    growth.push({ day, items: st.items_current, archive: st.items_archive, tx: st.transactions, stock: st.stock_units });
402  }
403  days.push(ds);
404  if (day % 30 === 0 || day === DAYS) {
405    const g = growth.at(-1)!;
406    console.log(`день ${day}: залишок ${int(g.stock)}, записів ${int(g.items)}, архів ${int(g.archive)}, транзакцій ${int(g.tx)}, фур ${trucks.length}, ${f1((performance.now() - tStart) / 1000)} с`);
407  }
408}
409
410const expiry = (await api<any>('expiry-report', 'GET', `/expiry-report?day=${DAYS}`)).data;
411const prof = (await api<any>('profile', 'GET', '/profile')).data as { sql: { sql: string; calls: number; ms: number; rows: number }[]; recordsPerProduct: Record<string, number> };
412// Сирі дані зберігаються до побудови звіту, щоб помилка у звіті не коштувала прогону.
413writeFileSync(`${OUT}/raw.json`, JSON.stringify({ opt, options: OPTIONS, profile: prof, expiry, receiptFreshness, trucks, days, growth, chStat,
414  expiredByMonth, writtenByMonth, handlerTotal, totalOps, latency: Object.fromEntries(lat), monthly: Object.fromEntries(monthly) }));
415client.close();
416server.close();
417
418// ---------- звіт ----------
419
420const totalMs = performance.now() - tStart;
421const dbBytes = [dbFile, `${dbFile}-wal`].reduce((s, f) => { try { return s + statSync(f).size; } catch { return s; } }, 0);
422const allReq = [...lat.values()].reduce((s, l) => s + l.rtt.length, 0);
423const later = trucks.slice(initialTrucks);
424const g = growth.at(-1)!;
425const requested = sum(CHANNELS.map((c) => chStat[c].requested));
426const issued = sum(CHANNELS.map((c) => chStat[c].issued));
427
428const latRows = [...lat.entries()].filter(([k]) => !['expiry-report', 'profile'].includes(k)).map(([k, l]) =>
429  `| ${k} | ${int(l.rtt.length)} | ${f2(pct(l.rtt, 50))} | ${f2(pct(l.rtt, 95))} | ${f2(pct(l.rtt, 99))} | ${f1(maxOf(l.rtt))} | ${f2(pct(l.handler, 50))} | ${f1(avg(l.ops))} |`);
430const truckRow = (name: string, ts: TruckStat[]) => !ts.length ? '' :
431  `| ${name} | ${ts.length} | ${int(avg(ts.map((t) => t.units)))} | ${int(avg(ts.map((t) => t.products)))} | ${int(avg(ts.map((t) => t.places)))} | ${int(avg(ts.map((t) => t.lots)))} | ${f2(pct(ts.map((t) => t.wallMs / 1000), 50))} | ${f2(maxOf(ts.map((t) => t.wallMs / 1000)))} | ${f2(avg(ts.map((t) => t.busyMs / t.lots)))} |`;
432const chRows = CHANNELS.map((c) => {
433  const s = chStat[c];
434  const tot = Object.values(s.kinds).reduce((a, b) => a + b, 0) || 1;
435  return `| ${c} | ${int(s.orders)} | ${int(s.lines)} | ${f1(s.lines / s.orders)} | ${int(s.issued)} | ${pc(s.issued, s.requested)} | ${f1((1000 * s.opened) / s.lines)} / ${f1((1000 * s.cut) / s.lines)} | ${f1((100 * s.kinds.container) / tot)} / ${f1((100 * s.kinds.pack) / tot)} / ${f1((100 * (s.kinds.loose + s.kinds.serial)) / tot)} |`;
436});
437const MONTH_LABELS = ['issue: роздріб', 'issue: опт', 'issue: переміщення', 'receipt: партія', 'stock: зведення', 'reconcile'];
438const monthRows = Array.from({ length: 12 }, (_, i) => i + 1).map((m) =>
439  `| ${m} | ${MONTH_LABELS.map((l) => { const a = monthly.get(`${l}|${m}`) ?? []; return a.length ? `${f2(pct(a, 50))} / ${f2(pct(a, 95))}` : '—'; }).join(' | ')} |`);
440const SCAN = [[0, 5], [5, 10], [10, 20], [20, 50], [50, Infinity]] as const;
441const scanRows = CHANNELS.flatMap((c) => SCAN.map(([a, b]) => {
442  const xs = chStat[c].orderLat.filter((x) => x.scannedPerLine >= a && x.scannedPerLine < b).map((x) => x.rtt);
443  return xs.length ? `| ${c} | ${a}–${b === Infinity ? '…' : b} | ${int(xs.length)} | ${f2(pct(xs, 50))} | ${f2(pct(xs, 95))} |` : '';
444}).filter(Boolean));
445const sqlTotal = sum(prof.sql.map((x) => x.ms));
446const commit = prof.sql.find((x) => x.sql === 'COMMIT');
447const profRows = prof.sql.slice(0, 14).map((x) =>
448  `| ${f1(x.ms / 1000)} | ${pc(x.ms, handlerTotal)} | ${int(x.calls)} | ${f1((1000 * x.ms) / Math.max(1, x.calls))} | ${f1(x.rows / Math.max(1, x.calls))} | \`${x.sql.length > 110 ? x.sql.slice(0, 107) + '…' : x.sql}\` |`);
449const freshRows = CHANNELS.map((c) => {
450  const s = chStat[c];
451  const tot = sum(Object.values(s.fresh)) || 1;
452  return `| ${c} | ${FRESH.map((b) => f1((100 * s.fresh[b]) / tot)).join(' | ')} | ${int(pct(s.ageDays, 50))} / ${int(pct(s.ageDays, 95))} | ${int(s.fefoViol)} |`;
453});
454const cats = Object.keys(expiry.byCategory).sort();
455const wo = new Map((expiry.writtenOff as { category: string; qty: number; records: number }[]).map((r) => [r.category, r]));
456const expRows = cats.map((c) => {
457  const b = expiry.byCategory[c];
458  const tot = sum(Object.values(b) as number[]) || 1;
459  return `| ${c} | ${int(tot)} | ${(expiry.buckets as string[]).map((k) => f1((100 * b[k]) / tot)).join(' | ')} | ${int(wo.get(c)?.qty ?? 0)} |`;
460});
461const pick = (d: number) => growth.reduce((b, x) => (Math.abs(x.day - d) < Math.abs(b.day - d) ? x : b));
462const recAt = (d: number) => avg(days.filter((x) => x.reconcileMs && Math.abs(x.day - d) <= 3).map((x) => x.reconcileMs));
463
464const report = `# Навантажувальний прогін stock-sim${opt.optimized ? ' (оптимізований)' : ' (базовий)'}
465
466${SKUS} SKU × ${BRANDS} брендів = ${int(catalog.length)} товарів; старт ${int(INITIAL)} од. фурами по ~${int(TRUCK)}; поставка кожні 2–3 дні довозить продане до цільового рівня; відвантаження ${opt['daily-min']}–${opt['daily-max']} од./день: переміщення ${mixT * 100}% / опт ${mixW * 100}% / роздріб ${mixR * 100}%; кожен товар має дату виготовлення і строк (${Number(opt['use-by']) * 100}% — лише «вжити до»), ${Number(opt['old-stock']) * 100}% партій приходять залежаними; ${DAYS} днів, seed ${opt.seed}.
467
468Оптимізації: ${opt.optimized ? Object.keys(OPTIONS).join(', ') : 'немає'}. Середовище: ${cpus()[0]?.model.trim() ?? '?'} × ${cpus().length}, ${f1(totalmem() / 2 ** 30)} ГБ, ${platform()}, Node ${process.version}, SQLite WAL, synchronous=${opt.sync}, один клієнт, запити послідовні.
469
470## Підсумок
471
472| показник | значення |
473|---|---|
474| загальний час прогону | ${f1(totalMs / 1000)} с |
475| HTTP-запитів / SQL-операторів | ${int(allReq)} / ${int(totalOps)} |
476| час обробників сумарно | ${f1(handlerTotal / 1000)} с, з них SQL ${pc(sqlTotal - (commit?.ms ?? 0), handlerTotal)}, COMMIT (fsync) ${pc(commit?.ms ?? 0, handlerTotal)} |
477| запитано / видано | ${int(requested)} / ${int(issued)} од. (${pc(issued, requested)}) |
478| прийнято поповненням | ${int(sum(later.map((t) => t.units)))} од., фур ${later.length} (старт ${initialTrucks}) |
479| транзакцій журналу | ${int(g.tx)} |
480| поточних записів / архів | ${int(g.items)} / ${int(g.archive)} |
481| записів на товар p50 / p95 / p99 / max | ${prof.recordsPerProduct.p50} / ${prof.recordsPerProduct.p95} / ${prof.recordsPerProduct.p99} / ${prof.recordsPerProduct.max} |
482| розмір БД | ${f1(dbBytes / 2 ** 20)} МБ |
483| порушень інваріантів | ${violations} |
484
485## Час на запит, мс (RTT клієнта)
486
487| запит | кількість | p50 | p95 | p99 | max | handler p50 | SQL сер. |
488|---|---|---|---|---|---|---|---|
489${latRows.join('\n')}
490
491## Динаміка за місяцями, p50 / p95 мс
492
493| місяць | ${MONTH_LABELS.join(' | ')} |
494|---|${MONTH_LABELS.map(() => '---').join('|')}|
495${monthRows.join('\n')}
496
497## Час замовлення від кількості прочитаних записів на рядок
498
499| канал | записів на рядок | замовлень | p50, мс | p95, мс |
500|---|---|---|---|---|
501${scanRows.join('\n')}
502
503## Профіль SQL (топ за сумарним часом)
504
505| с | частка часу обробників | викликів | мкс/виклик | рядків/виклик | оператор |
506|---|---|---|---|---|---|
507${profRows.join('\n')}
508
509## Фури
510
511| | фур | од./фуру | товарів | фізичних місць | партій (запитів) | облік p50, с | max, с | мс на партію |
512|---|---|---|---|---|---|---|---|---|
513${truckRow('старт', trucks.slice(0, initialTrucks))}
514${truckRow('поповнення', later)}
515
516## Канали
517
518| канал | замовлень | рядків | рядків/замовл. | видано од. | виконано | розкрито пакувань / спайок на 1000 рядків | спайки / пакування / розсип, % |
519|---|---|---|---|---|---|---|---|
520${chRows.join('\n')}
521
522## Строки придатності
523
524**На прийманні** — частка строку, що лишилась (од. з ${int(receiptFreshness.units)}): ${Object.entries(receiptFreshness.buckets).map(([k, v]) => `${k}: ${pc(v, receiptFreshness.units)}`).join('; ')}.
525
526**При видачі** — частка строку, що лишилась, % од.; вік від виготовлення; порушення FEFO (рядки):
527
528| канал | ${FRESH.join(' | ')} | вік p50 / p95, дн | FEFO-порушень |
529|---|${FRESH.map(() => '---').join('|')}|---|---|
530${freshRows.join('\n')}
531
532**Прострочення за місяцями** (записів, що стали EXPIRED / списано од.): ${Array.from({ length: 12 }, (_, i) => `${i + 1}: ${expiredByMonth[i + 1]}/${writtenByMonth[i + 1]}`).join('; ')}.
533
534**Залишок на кінець року за категоріями** — % од. за часткою строку, що лишилась; списано за рік:
535
536| категорія | од. | ${(expiry.buckets as string[]).join(' | ')} | списано од. |
537|---|---|${(expiry.buckets as string[]).map(() => '---').join('|')}|---|
538${expRows.join('\n')}
539
540**Залишок за днями до кінця строку:** ${Object.entries(expiry.byDaysLeft as Record<string, number>).map(([k, v]) => `${k}: ${int(v)}`).join('; ')}.
541
542## Ріст даних і вартість звірки
543
544| день | поточних записів | архів | транзакцій | залишок | звірка, мс |
545|---|---|---|---|---|---|
546${[1, 91, 182, 273, DAYS].map((d) => { const x = pick(d); return `| ${x.day} | ${int(x.items)} | ${int(x.archive)} | ${int(x.tx)} | ${int(x.stock)} | ${f1(recAt(x.day))} |`; }).join('\n')}
547`;
548writeFileSync(`${OUT}/report.md`, report);
549writeFileSync(`${OUT}/report.json`, JSON.stringify({ opt, options: OPTIONS, profile: prof, expiry, receiptFreshness, trucks, days, growth,
550  latency: Object.fromEntries([...lat.entries()].map(([k, l]) => [k, { n: l.rtt.length, p50: pct(l.rtt, 50), p95: pct(l.rtt, 95), p99: pct(l.rtt, 99) }])) }, null, 1));
551console.log(`\nготово за ${f1(totalMs / 1000)} с; запитів ${int(allReq)}; порушень ${violations}; звіт: ${OUT}/report.md`);
552