techtools

sim.ts

TypeScript · 291 рядків

1import { mkdirSync, rmSync, writeFileSync } from 'node:fs';
2import type { AddressInfo } from 'node:net';
3import { parseArgs } from 'node:util';
4import { createApi } from './api.ts';
5import { httpClient } from './client.ts';
6import { composeReceipt, drawQty, generateCatalog, newCounters, Rng, type SimProduct } from './faker.ts';
7import type { IssueLineIn, IssuePolicy, IssueResult, Item, ReceiptIn, ReturnIn } from './inventory.ts';
8
9// Рік роботи складу через мікро-API: приймання, видача, повернення, інвентаризація, дозамовлення, щоденна звірка.
10const { values: opt } = parseArgs({
11  options: {
12    products: { type: 'string', default: '3000' },
13    days: { type: 'string', default: '365' },
14    seed: { type: 'string', default: '42' },
15    out: { type: 'string', default: 'out' },
16    'check-every': { type: 'string', default: '1' },
17    policy: { type: 'string', default: 'fefo' },
18  },
19});
20const N = Number(opt.products);
21const DAYS = Number(opt.days);
22const CHECK = Number(opt['check-every']);
23const OUT = opt.out!;
24const dbFile = `${OUT}/sim.db`;
25
26mkdirSync(OUT, { recursive: true });
27for (const f of [dbFile, `${dbFile}-wal`, `${dbFile}-shm`]) rmSync(f, { force: true });
28
29const { server } = createApi(dbFile);
30await new Promise<void>((r) => server.listen(0, '127.0.0.1', r));
31const client = httpClient(`http://127.0.0.1:${(server.address() as AddressInfo).port}`);
32let httpCalls = 0;
33
34async function api<T = any>(method: string, path: string, body?: unknown): Promise<T> {
35  httpCalls++;
36  const r = await client.call(method, path, body);
37  if (r.status !== 200) throw new Error(`${method} ${path}: ${r.status} ${JSON.stringify(r.body)}`);
38  return r.body as T;
39}
40
41async function chunked<T>(items: T[], size: number, fn: (part: T[]) => Promise<unknown>): Promise<void> {
42  for (let i = 0; i < items.length; i += size) await fn(items.slice(i, i + size));
43}
44
45const t0 = Date.now();
46const rng = new Rng(Number(opt.seed));
47const counters = newCounters();
48
49// ---------- контрольний сценарій ----------
50
51const demoLog: string[] = [];
52async function scenario(): Promise<void> {
53  const [p] = await api('POST', '/products', [{ brand: 'DEMO', sku: 'SP-1000', name: 'Болт М8 демо', category: 'Кріплення', std_pack_type: 'box', std_pack_size: 100 }]);
54  const show = async (title: string) => {
55    const s = await api<{ total: number; items: Item[] }>('GET', `/stock?product_id=${p.id}`);
56    demoLog.push(`**${title}** — залишок ${s.total}`, '', '| id | тип | у контейнері | походження | пакувань × розмір | кількість | стан |', '|---|---|---|---|---|---|---|');
57    for (const i of s.items) demoLog.push(`| ${i.id} | ${i.pack_type} | ${i.contained_in_id ?? ''} | ${i.source_inventory_id ?? ''} | ${i.pack_count} × ${i.pack_size} | ${i.quantity}${i.is_container ? ' (вміст)' : ''} | ${i.status} |`);
58    demoLog.push('');
59  };
60  const lot = (label: string) => ({ product_id: p.id, location: 'A1-1-1-1', container: { type: 'bundle', total: 1000, label },
61    lines: [{ pack_type: 'box', pack_size: 100, pack_count: 9 }, { pack_type: 'bag', pack_size: 10, pack_count: 10 }] });
62  await api('POST', '/receipts', [{ doc: 'DEMO-PR-1', day: 0, lots: [lot('WL-DEMO-1'), lot('WL-DEMO-2')] }]);
63  await show('Прийнято 2 спайки по 1000 = коробка × 9 по 100 + пакет × 10 по 10');
64  const bad = await client.call('POST', '/receipts', [{ doc: 'DEMO-PR-BAD', day: 0, lots: [{ ...lot('x'), container: { type: 'bundle', total: 1000 }, lines: [{ pack_type: 'box', pack_size: 100, pack_count: 9 }] }] }]);
65  demoLog.push(`Перевірка: спайка 1000 з рядком лише 9 × 100 → HTTP ${bad.status} ${JSON.stringify(bad.body)}`, '');
66  for (const [qty, title] of [[1, 'Видано 1 шт'], [1000, 'Видано 1000 шт'], [250, 'Видано 250 шт']] as const) {
67    const [r] = await api<IssueResult[]>('POST', '/issues', { day: 0, lines: [{ order: `DEMO-SO-${qty}`, product_id: p.id, qty }] });
68    demoLog.push(`Відбір ${qty}: ${r.picks.map((x) => `${x.kind} #${x.item_id} ${x.packs}×${x.pack_type} = ${x.qty}`).join('; ')}; розкрито пакувань ${r.opened_packs}, контейнерів ${r.opened_containers}`, '');
69    await show(title);
70  }
71}
72await scenario();
73
74// ---------- каталог і початковий залишок ----------
75
76const catalog = generateCatalog(N, rng);
77await chunked(catalog, 1000, async (part) => {
78  const res = await api<{ id: number }[]>('POST', '/products', part.map((p) => p.input));
79  res.forEach((r, i) => (part[i].id = r.id));
80});
81const byId = new Map<number, SimProduct>(catalog.map((p) => [p.id!, p]));
82
83let docSeq = 0;
84const receipt = (sp: SimProduct, qty: number, day: number): ReceiptIn => ({ doc: `PR-${day}-${++docSeq}`, day, lots: composeReceipt(sp, qty, day, rng, counters) });
85await chunked(catalog.map((sp) => receipt(sp, sp.rop + sp.orderQty, 0)), 300, (part) => api('POST', '/receipts', part));
86
87// ---------- рік ----------
88
89const m = {
90  lines: 0, requested: 0, issued: 0, shortLines: 0, shortQty: 0, picks: 0,
91  qtyByKind: { container: 0, pack: 0, loose: 0, serial: 0 } as Record<string, number>,
92  linesNoOpening: 0, openedPacks: 0, openedContainers: 0, fefoViolations: 0, fefoLines: 0,
93  receipts: 0, receivedQty: 0, returns: 0, adjustments: 0, adjustmentOpenings: 0, labels: 0, labelErrors: 0,
94  repackedItems: 0, packsCreated: 0, expiredItems: 0, writtenOffQty: 0, reorders: 0,
95  reconcileRuns: 0, apiErrors: [] as string[],
96};
97const violations: { day: number; check: string; detail: string }[] = [];
98const seenViolations = new Set<string>(); // одне порушення рахується один раз, з днем першого виявлення
99const pending = new Map<number, number>(); // product_id → день прибуття
100const arrivals = new Map<number, number[]>();
101const returnsDue = new Map<number, ReturnIn[]>();
102const push = <T>(map: Map<number, T[]>, day: number, v: T) => (map.get(day) ?? map.set(day, []).get(day)!).push(v);
103const daily: { day: number; items: number; archive: number; tx: number; stock: number; ms: number }[] = [];
104
105for (let day = 1; day <= DAYS; day++) {
106  const dayStart = Date.now();
107
108  // приходи за дозамовленнями
109  const due = (arrivals.get(day) ?? []).map((pid) => {
110    pending.delete(pid);
111    const sp = byId.get(pid)!;
112    m.receipts++;
113    m.receivedQty += sp.orderQty;
114    return receipt(sp, sp.orderQty, day);
115  });
116  await chunked(due, 300, (part) => api('POST', '/receipts', part));
117
118  m.expiredItems += (await api('POST', '/maintenance/expire', { day })).expired_items;
119
120  // замовлення
121  const lines: IssueLineIn[] = [];
122  let so = 0;
123  for (const sp of catalog) {
124    for (let k = rng.poisson(sp.lambda); k > 0; k--) lines.push({ order: `SO-${day}-${++so}`, product_id: sp.id, qty: drawQty(sp, rng), policy: opt.policy as IssuePolicy });
125  }
126  await chunked(lines, 2000, async (part) => {
127    const res = await api<(IssueResult | { error: string })[]>('POST', '/issues', { day, lines: part });
128    for (const r of res) {
129      if ('error' in r) { m.apiErrors.push(r.error); continue; }
130      m.lines++;
131      m.requested += r.requested;
132      m.issued += r.issued;
133      if (r.short) { m.shortLines++; m.shortQty += r.short; }
134      m.picks += r.picks.length;
135      for (const p of r.picks) m.qtyByKind[p.kind] += p.qty;
136      if (!r.opened_packs && !r.opened_containers) m.linesNoOpening++;
137      m.openedPacks += r.opened_packs;
138      m.openedContainers += r.opened_containers;
139      if (byId.get(r.product_id)?.profile.shelfLife) { m.fefoLines++; if (r.fefo_violation) m.fefoViolations++; }
140      // ~1% рядків повертається протягом 1–14 днів
141      if (r.picks.length && rng.chance(0.01)) {
142        const p = rng.pick(r.picks);
143        if (p.kind === 'container') continue;
144        const ret: ReturnIn = p.kind === 'pack'
145          ? { order: `RT-${r.order}`, source_item_id: p.item_id, qty: p.qty / p.packs, sealed_pack: { pack_type: p.pack_type, pack_size: p.qty / p.packs } }
146          : { order: `RT-${r.order}`, source_item_id: p.item_id, qty: p.kind === 'serial' ? 1 : Math.min(p.qty, rng.int(1, 3)) };
147        push(returnsDue, day + rng.int(1, 14), ret);
148      }
149    }
150  });
151
152  const rets = returnsDue.get(day) ?? [];
153  if (rets.length) {
154    const res = await api<any[]>('POST', '/returns', { day, lines: rets });
155    m.returns += res.filter((r) => !r.error).length;
156  }
157
158  // щотижня: інвентаризація вибірки, складські етикетки, перепакування розсипу
159  if (day % 7 === 0) {
160    const adj: { item_id: number; delta: number; reason: string; serials?: string[] }[] = [];
161    const lab: { item_id: number }[] = [];
162    for (let i = 0; i < 20; i++) {
163      const sp = rng.pick(catalog);
164      const items = (await api<Item[]>('GET', `/items?product_id=${sp.id}`)).filter((x) => !x.is_container && x.status === 'ACTIVE');
165      if (!items.length) continue;
166      const it = rng.pick(items);
167      if (i < 12) {
168        const delta = rng.chance(0.7) ? -rng.int(1, Math.min(3, it.quantity)) : rng.int(1, 2);
169        const serials = it.serial_number && delta > 0 ? Array.from({ length: delta }, (_, k) => `INV${day}-${i}-${k}`) : undefined;
170        adj.push({ item_id: it.id, delta, reason: `INV-${day}`, serials });
171      }
172      else if (!it.label_code) lab.push({ item_id: it.id });
173    }
174    const ar = await api<any[]>('POST', '/adjustments', { day, lines: adj });
175    for (const r of ar) if (r.error) m.apiErrors.push(r.error); else { m.adjustments++; m.adjustmentOpenings += r.opened; }
176    const lr = await api<any[]>('POST', '/labels', { day, lines: lab });
177    for (const r of lr) if (r.error) { m.labelErrors++; m.apiErrors.push(r.error); } else m.labels++;
178    const rp = await api('POST', '/maintenance/repack', { day, min_packs: 2 });
179    m.repackedItems += rp.repacked_items;
180    m.packsCreated += rp.packs_created;
181  }
182  if (day % 30 === 0) m.writtenOffQty += (await api('POST', '/maintenance/write-off-expired', { day, doc: `WO-${day}` })).qty;
183
184  // дозамовлення при досягненні порогу доступного залишку
185  for (const s of await api<{ product_id: number; available: number }[]>('GET', '/stock')) {
186    const sp = byId.get(s.product_id);
187    if (!sp || pending.has(sp.id!) || s.available >= sp.rop) continue;
188    pending.set(sp.id!, day + sp.lead);
189    push(arrivals, day + sp.lead, sp.id!);
190    m.reorders++;
191  }
192
193  if (day % CHECK === 0 || day === DAYS) {
194    m.reconcileRuns++;
195    const rc = await api<{ ok: boolean; violations: { check: string; detail: string }[] }>('GET', '/reconcile');
196    for (const v of rc.violations) {
197      const key = `${v.check}|${v.detail}`;
198      if (!seenViolations.has(key) && violations.length < 200) violations.push({ day, ...v });
199      seenViolations.add(key);
200    }
201  }
202  const st = await api('GET', '/stats');
203  daily.push({ day, items: st.items_current, archive: st.items_archive, tx: st.transactions, stock: st.stock_units, ms: Date.now() - dayStart });
204  if (day % 30 === 0 || day === DAYS) {
205    console.log(`день ${day}: рядків ${m.lines}, поточних записів ${st.items_current}, архів ${st.items_archive}, транзакцій ${st.transactions}, порушень ${violations.length}, ${((Date.now() - t0) / 1000).toFixed(0)} с`);
206  }
207}
208
209// ---------- звіт ----------
210
211const stats = await api('GET', '/stats');
212const sample = (await api<{ id: number; source_inventory_id: number | null }[]>('GET', `/items?product_id=${catalog[0].id}`)).find((i) => i.source_inventory_id);
213const gen = sample ? await api<{ chain: Item[] }>('GET', `/genealogy?id=${sample.id}`) : null;
214client.close();
215server.close();
216
217const pct = (a: number, b: number) => (b ? ((100 * a) / b).toFixed(1) + '%' : '—');
218const sumKind = Object.values(m.qtyByKind).reduce((s, x) => s + x, 0);
219const secs = (Date.now() - t0) / 1000;
220const report = `# Симуляція складу: ${N} товарів, ${DAYS} днів, seed ${opt.seed}, відбір ${opt.policy}
221
222Згенеровано stock-sim (R-02). Час прогону ${secs.toFixed(0)} с, HTTP-викликів ${httpCalls}.
223
224## Інваріанти
225
226Звірок: ${m.reconcileRuns}. Унікальних порушень: **${violations.length}**.${violations.length ? '\n\n| день | перевірка | деталі |\n|---|---|---|\n' + violations.slice(0, 30).map((v) => `| ${v.day} | ${v.check} | \`${v.detail}\` |`).join('\n') : ''}
227
228Помилок API у рядках: ${m.apiErrors.length}${m.apiErrors.length ? ' — ' + [...new Set(m.apiErrors)].slice(0, 5).join('; ') : ''}.
229
230## Обсяг даних
231
232| показник | значення |
233|---|---|
234| поточні записи запасу | ${stats.items_current} (з них контейнерів ${stats.containers_current}) |
235| архів | ${stats.items_archive} |
236| транзакції | ${stats.transactions} |
237| записів на товар, максимум | ${stats.items_per_product_max} |
238| залишок, од. | ${stats.stock_units} |
239| з етикеткою складу / серійних одиниць | ${stats.labeled_items} / ${stats.serial_units} |
240
241Транзакції за типом: ${Object.entries(stats.tx_by_type).map(([k, v]) => `${k} ${v}`).join(', ')}.
242
243## Видача
244
245| показник | значення |
246|---|---|
247| рядків замовлень | ${m.lines} |
248| запитано / видано, од. | ${m.requested} / ${m.issued} (${pct(m.issued, m.requested)}) |
249| рядків з недостачею | ${m.shortLines} (${pct(m.shortLines, m.lines)}), ${m.shortQty} од. |
250| рядків без жодного розкриття | ${m.linesNoOpening} (${pct(m.linesNoOpening, m.lines)}) |
251| розкрито пакувань / контейнерів | ${m.openedPacks} / ${m.openedContainers} (на 1000 рядків: ${(1000 * m.openedPacks / m.lines).toFixed(1)} / ${(1000 * m.openedContainers / m.lines).toFixed(1)}) |
252| записів у відборі на рядок | ${(m.picks / m.lines).toFixed(2)} |
253| видано цілими контейнерами | ${pct(m.qtyByKind.container, sumKind)} |
254| видано цілими пакуваннями | ${pct(m.qtyByKind.pack, sumKind)} |
255| видано з розсипу | ${pct(m.qtyByKind.loose, sumKind)} |
256| видано серійних | ${m.qtyByKind.serial} од. |
257| FEFO-порушень (товари зі строком) | ${m.fefoViolations} з ${m.fefoLines} рядків (${pct(m.fefoViolations, m.fefoLines)}) |
258
259## Фрагментація розсипу
260
261Записів розсипу на товар: в середньому ${stats.loose_records_per_product_avg}, максимум ${stats.loose_records_per_product_max}; товарів із більш ніж одним записом розсипу — ${stats.products_with_multiple_loose}. Перепаковано записів ${m.repackedItems}, сформовано пакувань ${m.packsCreated}.
262
263## Приймання та граничні випадки
264
265| показник | значення |
266|---|---|
267| дозамовлень / приходів | ${m.reorders} / ${m.receipts} (${m.receivedQty} од.) |
268| спайок/палет прийнято | ${counters.containers} |
269| спайка з різних пакувань (коробки + пакети) | ${counters.mixed_pack_container} |
270| спайка з коробок і розсипу | ${counters.mixed_loose_container} |
271| неповне пакування в спайці | ${counters.nonstandard_pack} |
272| спайку розібрано через різні дати | ${counters.mixed_date_disassembled} |
273| серійні в спайці | ${counters.serial_in_container} |
274| етикетка на спайку / коробку при прийманні | ${counters.container_labels} / ${counters.box_labels_at_receipt} |
275| етикеток після приймання (з відділенням) | ${m.labels} (відмов ${m.labelErrors}) |
276| повернень | ${m.returns} |
277| коригувань / розкриттів через них | ${m.adjustments} / ${m.adjustmentOpenings} |
278| прострочено записів / списано од. | ${m.expiredItems} / ${m.writtenOffQty} |
279
280## Приклад походження
281
282${gen ? gen.chain.map((i) => `#${i.id} ${i.pack_type} ${i.pack_count}×${i.pack_size} (${i.status}${i.origin_doc ? ', ' + i.origin_doc : ''})`).join(' ← ') : '—'}
283
284## Контрольний сценарій
285
286${demoLog.join('\n')}
287`;
288writeFileSync(`${OUT}/report.md`, report);
289writeFileSync(`${OUT}/report.json`, JSON.stringify({ opt, metrics: m, counters, stats, violations, daily }, null, 1));
290console.log(`\nготово за ${secs.toFixed(0)} с; порушень ${violations.length}; звіт: ${OUT}/report.md`);
291