techtools

year.ts

TypeScript · 423 рядків

1import { mkdirSync, writeFileSync } from 'node:fs';
2import { parseArgs } from 'node:util';
3import pg from 'pg';
4import { PT } from './schema.ts';
5import { DDL_V3, MONTHS } from './schema3.ts';
6import { issueOrder, receiveLot, TX3, type IssueLine, type Lot } from './ops3.ts';
7
8// Рік роботи на структурі v3. Фаза 1 — заливка транзакціями приймання; фаза 2 — 365 модельних днів
9// з щомісячним закриттям періоду; фаза 3 — загальна статистика (report.md).
10const { values: opt } = parseArgs({
11  options: {
12    db: { type: 'string', default: 'wms_v3' },
13    url: { type: 'string', default: 'postgres://postgres@127.0.0.1:55432' },
14    warehouses: { type: 'string', default: '2' },
15    brands: { type: 'string', default: '50' },
16    'sku-min': { type: 'string', default: '4000' },
17    'sku-max': { type: 'string', default: '6000' },
18    'sku-pool': { type: 'string', default: '120000' },  // спільний пул кодів SKU: той самий SKU буває в кількох брендів
19    'stock-share': { type: 'string', default: '0.9' },  // частка товарів у наявності на складі
20    'stock-min': { type: 'string', default: '5' },
21    'stock-max': { type: 'string', default: '55' },     // середнє 30
22    clients: { type: 'string', default: '15' },         // одночасних комірників на склад
23    docs: { type: 'string', default: '10000' },         // документів руху на день на склад
24    mix: { type: 'string', default: '20,60,20' },       // переміщення, опт, роздріб (% документів)
25    truck: { type: 'string', default: '500' },          // товарів у фурі
26    'lot-min': { type: 'string', default: '15' },
27    'lot-max': { type: 'string', default: '25' },       // ~20 шт на товар
28    rop: { type: 'string', default: '10' },             // дозамовлення при доступному ≤
29    days: { type: 'string', default: '365' },
30    out: { type: 'string', default: 'out/year3' },
31    skipload: { type: 'boolean', default: false },
32  },
33});
34pg.types.setTypeParser(20, (v) => Number(v));
35pg.types.setTypeParser(1082, (v) => v);
36pg.types.setTypeParser(1184, (v) => v);
37const N = (k: keyof typeof opt) => Number(opt[k]);
38const WH = N('warehouses');
39const CLIENTS = N('clients');
40const OUT = opt.out!;
41mkdirSync(OUT, { recursive: true });
42
43const rnd = (a: number, b: number) => a + Math.floor(Math.random() * (b - a + 1));
44const pct = (a: number[], p: number) => { if (!a.length) return 0; const s = Float64Array.from(a).sort(); return s[Math.min(s.length - 1, Math.floor((p / 100) * s.length))]; };
45const f1 = (x: number) => x.toFixed(1);
46const fmt = (x: number) => Math.round(x).toLocaleString('uk-UA');
47const shuffle = <T>(a: T[]) => { for (let i = a.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [a[i], a[j]] = [a[j], a[i]]; } return a; };
48const iso = (ms: number) => new Date(ms).toISOString();
49const DAYMS = 86_400_000;
50
51// ---------- база ----------
52if (!opt.skipload) {
53  const admin = new pg.Client({ connectionString: `${opt.url}/postgres` });
54  await admin.connect();
55  await admin.query(`DROP DATABASE IF EXISTS ${opt.db} WITH (FORCE)`);
56  await admin.query(`CREATE DATABASE ${opt.db}`);
57  await admin.end();
58}
59const pool = new pg.Pool({ connectionString: `${opt.url}/${opt.db}`, max: WH * CLIENTS + 6 });
60const q = (sql: string, p: unknown[] = []) => pool.query(sql, p);
61const q1 = async (sql: string, p: unknown[] = []) => (await pool.query(sql, p)).rows[0];
62if (!opt.skipload) {
63  await q('CREATE EXTENSION IF NOT EXISTS pg_stat_statements');
64  await q(DDL_V3);
65}
66const PACK: Record<number, { p1: number; t1: number; life: number }> = {};
67for (const r of (await q('SELECT * FROM wms.category')).rows) PACK[r.id] = { p1: r.pack1, t1: r.pack1_type, life: Math.round((r.life_min + r.life_max) / 2) };
68
69function lotFor(pid: number, cat: number, qty: number, ts: number, loose = false): Lot {
70  const p = PACK[cat];
71  const lines = [];
72  if (!loose && p.p1 > 1 && qty >= p.p1) {
73    lines.push({ pack_type: p.t1, pack_size: p.p1, pack_count: Math.floor(qty / p.p1) });
74    if (qty % p.p1) lines.push({ pack_type: PT.unit, pack_size: 1, pack_count: qty % p.p1 });
75  } else lines.push({ pack_type: PT.unit, pack_size: 1, pack_count: qty });
76  const mfg = ts - rnd(0, 300) * DAYMS;
77  return { product_id: pid, lines, mfg: iso(mfg).slice(0, 10), expiry: iso(mfg + p.life * DAYMS).slice(0, 10), location: rnd(1, 100000) };
78}
79
80// ---------- метрики ----------
81type Kind = 'wholesale' | 'retail' | 'transfer_out' | 'transfer_in' | 'replenish' | 'fill';
82const KINDS: Kind[] = ['wholesale', 'retail', 'transfer_out', 'transfer_in', 'replenish', 'fill'];
83const newAcc = () => Object.fromEntries(KINDS.map((k) => [k, { n: 0, lines: 0, requested: 0, issued: 0, short: 0, units: 0, opened: 0, cut: 0, rows: 0, journal: 0, ms: [] as number[], errors: 0 }])) as Record<Kind, any>;
84let acc = newAcc();
85let docSeq = 1;
86let commits = 0;   // кожна задача — рівно одна транзакція БД
87
88// ---------- каталог ----------
89const tAll = performance.now();
90let catOf: Int8Array;
91let productCount = 0;
92const phase1: any = {};
93if (!opt.skipload) {
94  const t0 = performance.now();
95  const POOL = N('sku-pool');
96  const skuCat = new Int8Array(POOL + 1);
97  for (let s = 1; s <= POOL; s++) skuCat[s] = rnd(1, 9);
98  let catalogTx = 0;
99  for (let b = 1; b <= N('brands'); b++) {
100    const n = rnd(N('sku-min'), N('sku-max'));
101    const picked = shuffle(Array.from({ length: POOL }, (_, i) => i + 1)).slice(0, n);
102    for (let i = 0; i < picked.length; i += 1000) {
103      const part = picked.slice(i, i + 1000);
104      await q(`INSERT INTO wms.product (brand_id, sku, category_id)
105               SELECT $1, lpad(s::text, 6, '0'), c FROM unnest($2::int[], $3::smallint[]) AS x(s, c)`, [b, part, part.map((s) => skuCat[s])]);
106      catalogTx++;
107    }
108  }
109  phase1.catalogSeconds = (performance.now() - t0) / 1000;
110  phase1.catalogTx = catalogTx;
111}
112{
113  const r = await q1(`SELECT count(*) AS n, string_agg(category_id::text, '' ORDER BY id) AS cats, count(DISTINCT sku) AS skus, count(DISTINCT brand_id) AS brands FROM wms.product`);
114  productCount = Number(r.n);
115  catOf = Int8Array.from(('0' + r.cats).split('').map(Number));
116  phase1.products = productCount;
117  phase1.skus = Number(r.skus);
118  phase1.brands = Number(r.brands);
119}
120
121// Популярність: глобальний ранг товару; на кожному складі — список товарів у наявності за рангом (Ципф s=0.8).
122const rankPerm = shuffle(Array.from({ length: productCount }, (_, i) => i + 1));
123const stocked: Int32Array[] = [];
124const S = 0.8;
125const zipf = (n: number) => Math.min(n - 1, Math.floor(Math.pow(1 + Math.random() * (Math.pow(n, 1 - S) - 1), 1 / (1 - S))) - 1);
126const pick = (w: number) => stocked[w - 1][zipf(stocked[w - 1].length)];
127
128// ---------- виконання задач днями ----------
129interface Task { kind: Kind; wh: number; ts: number; lines?: IssueLine[]; lot?: Lot; dest?: number }
130// Черга з вказівником голови: shift() на сотнях тисяч задач зсуває весь масив щоразу.
131class Queue {
132  items: Task[] = [];
133  head = 0;
134  push(t: Task) { this.items.push(t); }
135  pushAll(ts: Task[]) { for (const t of ts) this.items.push(t); }
136  shift(): Task | undefined {
137    if (this.head >= this.items.length) return undefined;
138    const t = this.items[this.head++];
139    if (this.head > 65536 && this.head * 2 > this.items.length) { this.items = this.items.slice(this.head); this.head = 0; }
140    return t;
141  }
142  get length() { return this.items.length - this.head; }
143}
144const queues: Queue[] = Array.from({ length: WH }, () => new Queue());
145let inflight = 0;
146
147async function runTask(c: pg.PoolClient, t: Task, user: number): Promise<void> {
148  const a = acc[t.kind];
149  const s = performance.now();
150  for (let attempt = 0; ; attempt++) {
151    try {
152      if (t.lot) {
153        const r = await receiveLot(c, t.wh, t.lot, docSeq++, user, iso(t.ts), t.kind === 'transfer_in' ? TX3.TRANSFER_IN : TX3.RECEIVE);
154        a.units += r.units; a.rows += r.rows; a.journal += r.journal; a.lines += 1;
155      } else {
156        const r = await issueOrder(c, t.wh, t.lines!, docSeq++, user, iso(t.ts), t.kind === 'transfer_out' ? TX3.TRANSFER_OUT : TX3.ISSUE);
157        a.lines += t.lines!.length; a.requested += t.lines!.reduce((x, l) => x + l.qty, 0);
158        a.issued += r.issued; a.short += r.short; a.opened += r.opened; a.cut += r.cut; a.rows += r.rows; a.journal += r.journal;
159        if (t.kind === 'transfer_out') {
160          // Приймання на складі-одержувачі: кожен товар — окрема партія (потоварно), через годину модельного часу.
161          for (const [pid, v] of r.perProduct) {
162            const lot: Lot = { product_id: pid, lines: [{ pack_type: PT.unit, pack_size: 1, pack_count: v.qty }], mfg: v.mfg, expiry: v.expiry, location: rnd(1, 100000) };
163            queues[t.dest! - 1].push({ kind: 'transfer_in', wh: t.dest!, ts: t.ts + 3_600_000, lot });
164          }
165        }
166      }
167      break;
168    } catch (e: any) {
169      if ((e.code === '40P01' || e.code === '40001') && attempt < 5) continue;
170      a.errors++;
171      if (a.errors < 3) console.error(t.kind, e.code, e.message);
172      break;
173    }
174  }
175  a.ms.push(performance.now() - s);
176  a.n++;
177  commits++;
178}
179
180async function drain(): Promise<void> {
181  await Promise.all(Array.from({ length: WH * CLIENTS }, async (_, i) => {
182    const w = (i % WH) + 1;
183    const c = await pool.connect();
184    try {
185      for (;;) {
186        const t = queues[w - 1].shift();
187        if (t) {
188          inflight++;
189          await runTask(c, t, i + 1);
190          inflight--;
191          continue;
192        }
193        if (inflight === 0 && queues.every((x) => x.length === 0)) return;
194        await new Promise((r) => setTimeout(r, 2));
195      }
196    } finally {
197      c.release();
198    }
199  }));
200}
201
202const dbStats = async () => { await new Promise((r) => setTimeout(r, 1500)); return q1(`SELECT (SELECT sum(xact_commit) FROM pg_stat_database WHERE datname = current_database()) AS commits,
203  (SELECT sum(blks_read) FROM pg_stat_database WHERE datname = current_database()) AS rd, (SELECT sum(blks_hit) FROM pg_stat_database WHERE datname = current_database()) AS hit,
204  (SELECT wal_bytes FROM pg_stat_wal) AS wal`); };
205
206async function sizes() {
207  const r = (await q(`
208    SELECT CASE WHEN n.nspname = 'wms_archive' THEN 'журнал (відключені розділи)'
209                ELSE coalesce(parent.relname, c.relname) END AS tbl,
210           count(*) AS parts, sum(c.reltuples)::bigint AS rows, sum(pg_total_relation_size(c.oid)) AS bytes, sum(pg_indexes_size(c.oid)) AS idx
211    FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace AND n.nspname IN ('wms', 'wms_archive')
212    LEFT JOIN pg_inherits i ON i.inhrelid = c.oid LEFT JOIN pg_class parent ON parent.oid = i.inhparent
213    WHERE c.relkind = 'r' GROUP BY 1 ORDER BY bytes DESC`)).rows;
214  return r.map((x) => ({ tbl: x.tbl, parts: Number(x.parts), rows: Number(x.rows), MB: Number(x.bytes) / 2 ** 20, indexMB: Number(x.idx) / 2 ** 20 }));
215}
216
217const summarize = (a: Record<Kind, any>) => Object.fromEntries(KINDS.filter((k) => a[k].n).map((k) => {
218  const x = a[k];
219  return [k, { n: x.n, lines: x.lines, requested: x.requested, issued: x.issued, short: x.short, units: x.units, opened: x.opened, cut: x.cut,
220    rows: x.rows, journal: x.journal, errors: x.errors, p50: pct(x.ms, 50), p95: pct(x.ms, 95), p99: pct(x.ms, 99), max: x.ms.reduce((m: number, v: number) => Math.max(m, v), 0) }];
221}));
222
223// ---------- фаза 1: заливка ----------
224const FILL_TS = Date.UTC(2026, 11, 31);
225if (!opt.skipload) {
226  const t0 = performance.now();
227  const s0 = await dbStats();
228  let trucks = 0;
229  for (let w = 1; w <= WH; w++) {
230    const pids = shuffle(Array.from({ length: productCount }, (_, i) => i + 1).filter(() => Math.random() < N('stock-share')));
231    const tasks: Task[] = [];
232    for (let i = 0; i < pids.length; i++) {
233      const pid = pids[i];
234      const qty = rnd(N('stock-min'), N('stock-max'));
235      const parts = Math.random() < 0.3 && qty >= 10 ? [Math.floor(qty / 2), qty - Math.floor(qty / 2)] : [qty];
236      const ts = FILL_TS + Math.floor((i / pids.length) * DAYMS);
237      for (const part of parts) tasks.push({ kind: 'fill', wh: w, ts, lot: lotFor(pid, catOf[pid], part, ts) });
238    }
239    trucks += Math.ceil(pids.length / N('truck'));
240    queues[w - 1].pushAll(tasks);
241  }
242  await drain();
243  await q('ANALYZE');
244  const s1 = await dbStats();
245  const per = (await q(`SELECT warehouse_id AS wh, count(*) AS products, sum(quantity) AS units, round(avg(quantity), 1) AS avg FROM wms.product_stock GROUP BY 1 ORDER BY 1`)).rows;
246  Object.assign(phase1, { seconds: (performance.now() - t0) / 1000, trucks, commits: commits + (phase1.catalogTx ?? 0),
247    walMB: (Number(s1.wal) - Number(s0.wal)) / 2 ** 20, perWarehouse: per.map((r) => ({ wh: r.wh, products: Number(r.products), units: Number(r.units), avg: Number(r.avg) })),
248    fill: summarize(acc).fill, sizes: await sizes() });
249  writeFileSync(`${OUT}/phase1.json`, JSON.stringify(phase1, null, 1));
250  console.log(`ФАЗА 1: ${fmt(phase1.products)} товарів (${phase1.brands} брендів, ${fmt(phase1.skus)} SKU); заливка ${f1(phase1.seconds)} с, фур ${trucks}, партій ${fmt(phase1.fill.n)}, комітів ${fmt(phase1.commits)}, партія p50 ${f1(phase1.fill.p50)} мс p99 ${f1(phase1.fill.p99)} мс`);
251  for (const r of phase1.perWarehouse) console.log(`  склад ${r.wh}: товарів ${fmt(r.products)}, одиниць ${fmt(r.units)}, сер. ${r.avg}`);
252}
253for (let w = 1; w <= WH; w++) {
254  const have = new Set((await q('SELECT product_id FROM wms.product_stock WHERE warehouse_id = $1', [w])).rows.map((r) => r.product_id));
255  stocked.push(Int32Array.from(rankPerm.filter((p) => have.has(p))));
256}
257
258// ---------- фаза 2: рік ----------
259commits = 0;
260acc = newAcc();
261await q('SELECT public.pg_stat_statements_reset()');
262const [mixT, mixW, mixR] = opt.mix!.split(',').map((x) => Number(x) / 100);
263const months: any[] = [];
264let prevClose = Date.UTC(2026, 11, 1);
265let monthStart = performance.now();
266let mStats = await dbStats();
267let replenish = { trucks: 0, lots: 0 };
268const START = Date.UTC(2027, 0, 1);
269
270for (let d = 0; d < N('days'); d++) {
271  const dayMs = START + d * DAYMS;
272  // дозамовлення: фури по 500 товарів для позицій із доступним ≤ ROP
273  for (let w = 1; w <= WH; w++) {
274    const low = (await q('SELECT product_id FROM wms.product_stock WHERE warehouse_id = $1 AND available <= $2', [w, N('rop')])).rows.map((r) => r.product_id);
275    replenish.trucks += Math.ceil(low.length / N('truck'));
276    replenish.lots += low.length;
277    const tasks: Task[] = low.map((pid, i) => {
278      const p = PACK[catOf[pid]];
279      let qty = rnd(N('lot-min'), N('lot-max'));
280      if (p.p1 > 1) qty = Math.ceil(qty / p.p1) * p.p1;
281      const ts = dayMs + Math.floor((i / Math.max(1, low.length)) * 0.4 * DAYMS);   // фури — у першій половині дня
282      return { kind: 'replenish', wh: w, ts, lot: lotFor(pid, catOf[pid], qty, ts) };
283    });
284    const docs = N('docs');
285    for (let i = 0; i < docs; i++) {
286      const r = Math.random();
287      const kind: Kind = r < mixT ? 'transfer_out' : r < mixT + mixW ? 'wholesale' : 'retail';
288      const [nmin, nmax, qmin, qmax] = kind === 'retail' ? [1, 3, 1, 4] : [1, 10, 1, 10];
289      const m = new Map<number, number>();
290      const n = rnd(nmin, nmax);
291      for (let k = 0; k < n; k++) { const pid = pick(w); m.set(pid, (m.get(pid) ?? 0) + rnd(qmin, qmax)); }
292      const lines = [...m].map(([product_id, qty]) => ({ product_id, qty }));
293      tasks.push({ kind, wh: w, ts: dayMs + Math.floor(Math.random() * DAYMS * 0.95), lines, dest: kind === 'transfer_out' ? (w % WH) + 1 : undefined });
294    }
295    queues[w - 1].pushAll(shuffle(tasks));
296  }
297  await drain();
298
299  // кінець місяця: закриття періоду, відключення розділу M−2, знімок
300  const next = new Date(dayMs + DAYMS);
301  if (next.getUTCDate() === 1) {
302    const close = Date.UTC(next.getUTCFullYear(), next.getUTCMonth(), 1);
303    const wall = (performance.now() - monthStart) / 1000;
304    let t = performance.now();
305    const rec = await q1(`
306      WITH t AS (SELECT warehouse_id, product_id, sum(qty_delta) AS q FROM wms.inventory_transaction
307                 WHERE created_at >= $1 AND created_at < $2 GROUP BY 1, 2)
308      SELECT count(*) FILTER (WHERE s.quantity <> s.checked_quantity + coalesce(t.q, 0)) AS bad,
309             count(*) AS positions, count(t.q) AS moved
310      FROM wms.product_stock s LEFT JOIN t USING (warehouse_id, product_id)`, [iso(prevClose), iso(close)]);
311    const reconcileMs = performance.now() - t;
312    t = performance.now();
313    await q('UPDATE wms.product_stock SET checked_quantity = quantity, checked_at = $1', [iso(close)]);
314    const checkpointMs = performance.now() - t;
315    // відключити розділ журналу на два місяці старший за закритий
316    const old = MONTHS[MONTHS.findIndex((m) => m.from === iso(close).slice(0, 10)) - 3];
317    let detachMs = 0;
318    if (old) {
319      const exists = await q1(`SELECT count(*) AS n FROM pg_inherits WHERE inhrelid = 'wms.inventory_transaction_${old.tag}'::regclass`);
320      if (Number(exists.n)) {
321        t = performance.now();
322        await q(`ALTER TABLE wms.inventory_transaction DETACH PARTITION wms.inventory_transaction_${old.tag}`);
323        await q(`ALTER TABLE wms.inventory_transaction_${old.tag} SET SCHEMA wms_archive`);
324        detachMs = performance.now() - t;
325      }
326    }
327    const s1 = await dbStats();
328    const mon = {
329      month: iso(dayMs).slice(0, 7), wallSeconds: wall, ops: summarize(acc), replenish: { ...replenish },
330      commits, walMB: (Number(s1.wal) - Number(mStats.wal)) / 2 ** 20,
331      cacheHitPct: (100 * (Number(s1.hit) - Number(mStats.hit))) / Math.max(1, Number(s1.hit) - Number(mStats.hit) + Number(s1.rd) - Number(mStats.rd)),
332      reconcile: { bad: Number(rec.bad), positions: Number(rec.positions), moved: Number(rec.moved), ms: reconcileMs, checkpointMs, detached: old?.tag ?? null, detachMs },
333      sizes: await sizes(),
334    };
335    months.push(mon);
336    writeFileSync(`${OUT}/month-${mon.month}.json`, JSON.stringify(mon, null, 1));
337    const o = mon.ops;
338    const sold = (o.wholesale?.issued ?? 0) + (o.retail?.issued ?? 0);
339    const reqs = KINDS.reduce((s, k) => s + (o[k]?.n ?? 0), 0);
340    console.log(`${mon.month}: ${f1(wall)} с, запитів ${fmt(reqs)} (${fmt(reqs / wall)}/с), продано ${fmt(sold)} шт, переміщено ${fmt(o.transfer_out?.issued ?? 0)}, фур ${replenish.trucks} (${fmt(replenish.lots)} партій), комітів ${fmt(mon.commits)}, розкрито ${fmt((o.wholesale?.opened ?? 0) + (o.retail?.opened ?? 0) + (o.transfer_out?.opened ?? 0))} | опт p50 ${f1(o.wholesale?.p50 ?? 0)} p95 ${f1(o.wholesale?.p95 ?? 0)} мс, роздріб p50 ${f1(o.retail?.p50 ?? 0)} мс, партія p50 ${f1(o.replenish?.p50 ?? 0)} мс | звірка ${f1(reconcileMs)} мс, розбіжн. ${mon.reconcile.bad}${old ? `, відключено ${old.tag}` : ''}`);
341    acc = newAcc();
342    commits = 0;
343    replenish = { trucks: 0, lots: 0 };
344    prevClose = close;
345    monthStart = performance.now();
346    mStats = s1;
347  }
348}
349
350// ---------- фаза 3: підсумок ----------
351const top = (await q(`SELECT calls, round(total_exec_time::numeric) AS total_ms, round(mean_exec_time::numeric, 3) AS mean_ms,
352  round((100 * total_exec_time / sum(total_exec_time) OVER ())::numeric, 1) AS pct, left(regexp_replace(query, '\\s+', ' ', 'g'), 100) AS q
353  FROM public.pg_stat_statements WHERE dbid = (SELECT oid FROM pg_database WHERE datname = current_database()) ORDER BY total_exec_time DESC LIMIT 10`)).rows;
354// Повна перевірка року: журнал (гарячі + відключені розділи) = кеш
355let t = performance.now();
356const archParts = (await q(`SELECT c.relname FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = 'wms_archive' AND c.relkind = 'r'`)).rows.map((r) => r.relname);
357const union = ['SELECT warehouse_id, product_id, qty_delta FROM wms.inventory_transaction', ...archParts.map((p) => `SELECT warehouse_id, product_id, qty_delta FROM wms_archive.${p}`)].join(' UNION ALL ');
358const full = await q1(`WITH t AS (SELECT warehouse_id, product_id, sum(qty_delta) q FROM (${union}) x GROUP BY 1, 2)
359  SELECT count(*) FILTER (WHERE s.quantity <> coalesce(t.q, 0)) AS bad FROM wms.product_stock s LEFT JOIN t USING (warehouse_id, product_id)`);
360const fullMs = performance.now() - t;
361const finalSizes = await sizes();
362await pool.end();
363
364const yearTotal = (k: Kind, f: string) => months.reduce((s, m) => s + (m.ops[k]?.[f] ?? 0), 0);
365const summary = {
366  phase1, months: months.length, totalSeconds: (performance.now() - tAll) / 1000,
367  sold: yearTotal('wholesale', 'issued') + yearTotal('retail', 'issued'), transferred: yearTotal('transfer_out', 'issued'),
368  replenishedUnits: yearTotal('replenish', 'units'), requests: months.reduce((s, m) => s + KINDS.reduce((x, k) => x + (m.ops[k]?.n ?? 0), 0), 0),
369  commits: months.reduce((s, m) => s + m.commits, 0), journalRows: months.reduce((s, m) => s + KINDS.reduce((x, k) => x + (m.ops[k]?.journal ?? 0), 0), 0),
370  fullYearCheck: { bad: Number(full.bad), ms: fullMs }, topStatements: top, finalSizes,
371};
372writeFileSync(`${OUT}/summary.json`, JSON.stringify(summary, null, 1));
373
374// report.md
375const row = (m: any) => {
376  const o = m.ops;
377  const sold = (o.wholesale?.issued ?? 0) + (o.retail?.issued ?? 0);
378  const reqs = KINDS.reduce((s, k) => s + (o[k]?.n ?? 0), 0);
379  const opened = (o.wholesale?.opened ?? 0) + (o.retail?.opened ?? 0) + (o.transfer_out?.opened ?? 0);
380  const shortPct = (100 * ((o.wholesale?.short ?? 0) + (o.retail?.short ?? 0))) / Math.max(1, (o.wholesale?.requested ?? 0) + (o.retail?.requested ?? 0));
381  const j = m.sizes.find((s: any) => s.tbl === 'inventory_transaction');
382  const ja = m.sizes.find((s: any) => s.tbl.startsWith('журнал'));
383  const it = m.sizes.find((s: any) => s.tbl === 'inventory_item');
384  const ar = m.sizes.find((s: any) => s.tbl === 'inventory_item_archive');
385  return `| ${m.month} | ${f1(m.wallSeconds)} | ${fmt(reqs)} | ${fmt(m.commits)} | ${fmt(sold)} | ${f1(shortPct)}% | ${fmt(o.transfer_out?.issued ?? 0)} | ${m.replenish.trucks} / ${fmt(m.replenish.lots)} | ${fmt(opened)} | ${fmt(KINDS.reduce((x, k) => x + (o[k]?.journal ?? 0), 0))} | ${f1(o.wholesale?.p50 ?? 0)} / ${f1(o.wholesale?.p95 ?? 0)} / ${f1(o.wholesale?.p99 ?? 0)} | ${f1(o.retail?.p50 ?? 0)} / ${f1(o.retail?.p95 ?? 0)} | ${f1(o.replenish?.p50 ?? 0)} / ${f1(o.replenish?.p95 ?? 0)} | ${f1(m.cacheHitPct)}% | ${fmt(j?.MB ?? 0)} / ${fmt(ja?.MB ?? 0)} | ${fmt(it?.MB ?? 0)} | ${fmt(ar?.MB ?? 0)} | ${f1(m.reconcile.ms)} / ${m.reconcile.bad} |`;
386};
387const md = `# Рік роботи на структурі v3
388
389Склади: ${WH}; брендів ${phase1.brands}, SKU ${fmt(phase1.skus)}, товарів ${fmt(phase1.products)}; ${CLIENTS} комірників на склад; ${opt.docs} документів на день на склад (переміщення/опт/роздріб ${opt.mix}%); фура ${opt.truck} товарів по ${opt['lot-min']}–${opt['lot-max']} шт; дозамовлення при доступному ≤ ${opt.rop}.
390
391## Фаза 1 — заливка
392
393${phase1.seconds ? `Час ${f1(phase1.seconds)} с; каталог ${f1(phase1.catalogSeconds)} с (${phase1.catalogTx} транзакцій); фур ${phase1.trucks}; партій (транзакцій приймання) ${fmt(phase1.fill.n)}; комітів ${fmt(phase1.commits)}; партія p50 ${f1(phase1.fill.p50)} / p95 ${f1(phase1.fill.p95)} / p99 ${f1(phase1.fill.p99)} мс; WAL ${fmt(phase1.walMB)} МБ.
394
395| склад | товарів | одиниць | середнє на товар |
396|---|---|---|---|
397${phase1.perWarehouse.map((r: any) => `| ${r.wh} | ${fmt(r.products)} | ${fmt(r.units)} | ${r.avg} |`).join('\n')}` : '(пропущено)'}
398
399## Фаза 2 — щомісяця
400
401| місяць | час, с | запитів | комітів | продано шт | недостача | переміщено шт | фур / партій | розкрито пакувань | рядків журналу | опт p50/p95/p99 мс | роздріб p50/p95 мс | партія p50/p95 мс | кеш | журнал гарячий / відключений МБ | запас МБ | архів МБ | звірка мс / розбіжн. |
402|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
403${months.map(row).join('\n')}
404
405## Фаза 3 — рік
406
407Загальний час ${f1(summary.totalSeconds / 60)} хв; запитів ${fmt(summary.requests)}; комітів ${fmt(summary.commits)}; рядків журналу ${fmt(summary.journalRows)}; продано ${fmt(summary.sold)} шт; переміщено ${fmt(summary.transferred)} шт; поповнено ${fmt(summary.replenishedUnits)} шт. Повна перевірка року (гарячий + відключений журнал = кеш): розбіжностей ${summary.fullYearCheck.bad}, ${f1(fullMs / 1000)} с.
408
409Розміри на кінець року:
410
411| таблиця | розділів | рядків | МБ | з них індекси МБ |
412|---|---|---|---|---|
413${finalSizes.map((s) => `| ${s.tbl} | ${s.parts} | ${fmt(s.rows)} | ${fmt(s.MB)} | ${fmt(s.indexMB)} |`).join('\n')}
414
415Топ операторів за часом бази:
416
417| % | викликів | сер. мс | оператор |
418|---|---|---|---|
419${top.map((x) => `| ${x.pct} | ${fmt(Number(x.calls))} | ${x.mean_ms} | \`${x.q}\` |`).join('\n')}
420`;
421writeFileSync(`${OUT}/report.md`, md);
422console.log(`\nготово: ${f1(summary.totalSeconds / 60)} хв; звіт ${OUT}/report.md`);
423