presentation-data.ts
TypeScript · 180 рядків
1import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
2import { fileURLToPath } from 'node:url';
3import { openDb } from './db.ts';
4import { Inventory } from './inventory.ts';
5
6// Deterministic snapshots from the same implementation as examples.ts.
7// Never opens or changes the databases of existing simulation runs.
8const inv = new Inventory(openDb(':memory:'));
9const products = inv.addProducts([
10 { brand: 'Febi Bilstein', sku: '12345', name: 'Болт М8×25', category: 'Кріплення', std_pack_type: 'box', std_pack_size: 100 },
11 { brand: 'SWAG', sku: '12345', name: 'Кліпса обшивки', category: 'Кріплення', std_pack_type: 'bag', std_pack_size: 10 },
12 { brand: 'Mann-Filter', sku: 'W 712/95', name: 'Фільтр масляний', category: 'Фільтри', std_pack_type: 'carton', std_pack_size: 12 },
13 { brand: 'Bosch', sku: '0445110369', name: 'Форсунка паливна', category: 'Дорогі вузли', is_serial: true },
14 { brand: 'Loctite', sku: '243-50ML', name: 'Фіксатор різьби', category: 'Герметики', shelf_life_days: 540, std_pack_type: 'box', std_pack_size: 12 },
15]);
16const [bolt, clip, filter, injector, sealant] = products.map(p => p.id);
17const snapshots: Record<string, unknown> = {};
18// Observe completed semantic operations in the real model, without modifying its source.
19// Paired OPEN/SPLIT deltas are presented together; partial SQL writes are never a committed state.
20function tracing(model: Inventory) {
21 let pid = 0, enabled = false, depth = 0, txStart = 0;
22 let archiveBefore = new Set<unknown>();
23 let events: any[] = [];
24 const state = () => ({
25 items: model.items(pid),
26 stock: model.stockSummary().find(s => s.product_id === pid)!,
27 ledger: (model.db.prepare('SELECT COALESCE(SUM(qty_delta),0) n FROM inventory_transaction WHERE product_id=?').get(pid) as { n: number }).n,
28 transactions: model.db.prepare('SELECT * FROM inventory_transaction WHERE product_id=? AND id>? ORDER BY id').all(pid, txStart),
29 archive: model.db.prepare('SELECT * FROM inventory_item_archive WHERE product_id=? ORDER BY id').all(pid).filter(row => !archiveBefore.has(row.id)),
30 });
31 const methods = model as unknown as Record<string, (...args: any[]) => any>;
32 for (const name of ['openContainer', 'openPack', 'reduce', 'label', 'returnItem', 'repack', 'writeOffExpired']) {
33 const original = methods[name].bind(model);
34 methods[name] = (...args: any[]) => {
35 const record = enabled && depth === 0;
36 const before = record ? state() : null;
37 const details = record ? JSON.parse(JSON.stringify(args)) : null;
38 depth++;
39 try {
40 const result = original(...args);
41 if (record) events.push({ kind: name, details, before, after: state() });
42 return result;
43 } finally { depth--; }
44 };
45 }
46 const log = methods.log.bind(model);
47 methods.log = (...args: any[]) => {
48 log(...args);
49 if (enabled && depth === 0 && (['RECEIVE', 'STATUS'].includes(args[1]) || (args[1] === 'ADJUSTMENT' && args[4] > 0))) {
50 events.push({ kind: args[1], details: args, after: state() });
51 }
52 };
53 return {
54 start(productId: number) {
55 pid = productId; events = []; enabled = true;
56 txStart = (model.db.prepare('SELECT COALESCE(MAX(id),0) n FROM inventory_transaction').get() as { n: number }).n;
57 archiveBefore = new Set(model.db.prepare('SELECT id FROM inventory_item_archive').all().map(row => row.id));
58 return state();
59 },
60 finish() { enabled = false; return events; },
61 };
62}
63const observer = tracing(inv);
64function capture(key: string, pid: number, action: () => unknown) {
65 const before = JSON.stringify(inv.db.prepare('SELECT * FROM inventory_item ORDER BY id').all());
66 const beforeState = observer.start(pid);
67 const txStart = (inv.db.prepare('SELECT COALESCE(MAX(id),0) n FROM inventory_transaction').get() as { n: number }).n;
68 const archivedIds = new Set(inv.db.prepare('SELECT id FROM inventory_item_archive').all().map(row => row.id));
69 let result: unknown = null;
70 let error: string | null = null;
71 try { result = action(); } catch (e) { error = (e as Error).message; }
72 const trace = observer.finish();
73 const items = inv.items(pid);
74 const stock = inv.stockSummary().find(s => s.product_id === pid)!;
75 const ledger = (inv.db.prepare('SELECT COALESCE(SUM(qty_delta),0) n FROM inventory_transaction WHERE product_id=?').get(pid) as { n: number }).n;
76 const check = inv.reconcile();
77 if (!check.ok) throw new Error(`${key}: ${JSON.stringify(check.violations)}`);
78 const transactions = inv.db.prepare('SELECT * FROM inventory_transaction WHERE id>? ORDER BY id').all(txStart);
79 const archive = inv.db.prepare('SELECT * FROM inventory_item_archive ORDER BY id').all().filter(row => !archivedIds.has(row.id));
80 if (error && (before !== JSON.stringify(inv.db.prepare('SELECT * FROM inventory_item ORDER BY id').all()) || transactions.length || archive.length)) {
81 throw new Error(`${key}: rejected operation changed data`);
82 }
83 snapshots[key] = { product: products.find(p => p.id === pid), before: beforeState, trace: error ? [] : trace, items, transactions, archive, stock, ledger, result, error, check };
84}
85
86// Small isolated introduction. Its IDs do not change the R-02 examples below.
87const simple = new Inventory(openDb(':memory:'));
88const simpleProduct = simple.addProducts([{ brand: 'Febi Bilstein', sku: '12345', name: 'Болт М8×25', category: 'Кріплення' }])[0];
89const simpleObserver = tracing(simple);
90for (const [key, action] of [
91 ['simple10', () => simple.receive({ doc: 'PR-10', day: 1, lots: [{ product_id: simpleProduct.id, location: 'A1', lines: [{ pack_type: 'unit', pack_size: 1, pack_count: 10 }] }] })],
92 ['simpleIssue', () => simple.issue({ order: 'SO-1', product_id: simpleProduct.id, qty: 1 }, 2)],
93] as const) {
94 const before = simpleObserver.start(simpleProduct.id);
95 const result = action();
96 const trace = simpleObserver.finish();
97 const after = trace.at(-1).after;
98 const check = simple.reconcile();
99 if (!check.ok) throw new Error(`${key}: ${JSON.stringify(check.violations)}`);
100 snapshots[key] = { product: simpleProduct, before, trace, ...after, result, error: null, check };
101}
102simple.db.close();
103
104capture('receipt', bolt, () => inv.receive({ doc: 'PR-1', day: 1, lots: [1, 2].map(n => ({ product_id: bolt, location: 'A1-01-1-1',
105 container: { type: 'bundle', total: 1000, label: n === 1 ? 'WL0000001' : undefined },
106 lines: [{ pack_type: 'box', pack_size: 100, pack_count: 9 }, { pack_type: 'bag', pack_size: 10, pack_count: 10 }],
107})) }));
108capture('one', bolt, () => inv.issue({ order: 'SO-1', product_id: bolt, qty: 1 }, 2));
109capture('twofifty', bolt, () => inv.issue({ order: 'SO-2', product_id: bolt, qty: 250 }, 2));
110capture('thousand', bolt, () => inv.issue({ order: 'SO-3', product_id: bolt, qty: 1000 }, 3));
111capture('looseReceipt', clip, () => inv.receive({ doc: 'PR-2', day: 1, lots: [{ product_id: clip, location: 'A1-02-1-1', lines: [
112 { pack_type: 'bag', pack_size: 10, pack_count: 7 }, { pack_type: 'bag', pack_size: 8, pack_count: 1 }, { pack_type: 'unit', pack_size: 1, pack_count: 5 },
113] }] }));
114capture('eighteen', clip, () => inv.issue({ order: 'SO-4', product_id: clip, qty: 18 }, 2));
115capture('badReceipt', clip, () => inv.receive({ doc: 'PR-3', day: 2, lots: [{ product_id: clip, location: 'A1-02-1-1',
116 container: { type: 'bundle', total: 100 }, lines: [{ pack_type: 'bag', pack_size: 10, pack_count: 9 }],
117}] }));
118capture('pallet', filter, () => inv.receive({ doc: 'PR-4', day: 1, lots: [{ product_id: filter, location: 'B2-10-1-1',
119 container: { type: 'pallet', total: 240 }, lines: [{ pack_type: 'carton', pack_size: 12, pack_count: 20 }],
120}] }));
121const carton = inv.items(filter).find(i => i.pack_type === 'carton')!;
122capture('label', filter, () => inv.label(carton.id, 'WL0000002', 2));
123capture('cartonIssue', filter, () => inv.issue({ order: 'SO-5', product_id: filter, qty: 12 }, 3));
124capture('serialReceipt', injector, () => inv.receive({ doc: 'PR-5', day: 1, lots: [
125 { product_id: injector, location: 'S1-01-1-1', container: { type: 'bundle', total: 4, label: 'WL0000003' },
126 lines: [{ pack_type: 'unit', pack_size: 1, pack_count: 4, serials: ['BOS2600000101', 'BOS2600000102', 'BOS2600000103', 'BOS2600000104'] }] },
127 { product_id: injector, location: 'S1-01-1-2', lines: [{ pack_type: 'unit', pack_size: 1, pack_count: 1, serials: ['BOS2600000105'] }] },
128] }));
129capture('serialIssue', injector, () => inv.issue({ order: 'SO-6', product_id: injector, qty: 2 }, 2));
130const issued = (inv.db.prepare("SELECT item_id FROM inventory_transaction WHERE doc='SO-6' AND type='ISSUE' ORDER BY id LIMIT 1").get() as { item_id: number }).item_id;
131capture('return', injector, () => inv.returnItem({ order: 'RT-6', source_item_id: issued, qty: 1 }, 5));
132capture('badSerial', injector, () => inv.adjust(inv.items(injector)[0].id, 1, 6, 'INV-6'));
133capture('datedReceipt', sealant, () => inv.receive({ doc: 'PR-6', day: 100, lots: [
134 ...[0, 40, 80].map(day => ({ product_id: sealant, location: 'C3-01-1-1', mfg_day: day, lines: [{ pack_type: 'box', pack_size: 12, pack_count: 1 }] })),
135 { product_id: sealant, location: 'C3-01-1-2', mfg_day: 90, container: { type: 'bundle', total: 120 }, lines: [{ pack_type: 'box', pack_size: 12, pack_count: 10 }] },
136] }));
137capture('fefoIssue', sealant, () => inv.issue({ order: 'SO-7', product_id: sealant, qty: 3 }, 101));
138capture('adjust', sealant, () => inv.adjust(inv.items(sealant).find(i => i.contained_in_id != null)!.id, -2, 102, 'INV-102'));
139capture('expired', sealant, () => inv.expire(545));
140capture('writeoff', sealant, () => inv.writeOffExpired(545, 'WO-545'));
141const genealogy = inv.genealogy(inv.items(bolt).find(i => i.pack_type === 'unit')!.id);
142// Explicit teaching case: annual runs never accumulated enough loose units for REPACK.
143capture('repackBefore', bolt, () => inv.receive({ doc: 'PR-REPACK', day: 546, lots: [{ product_id: bolt, location: 'A1-01-1-2',
144 lines: [{ pack_type: 'unit', pack_size: 1, pack_count: 250 }],
145}] }));
146capture('repack', bolt, () => inv.repack(547, 2));
147
148function report(path: string) { return JSON.parse(readFileSync(new URL(`../out/${path}/report.json`, import.meta.url), 'utf8')); }
149function annual(path: string) {
150 const { opt, metrics, counters, stats, violations } = report(path);
151 return { opt, metrics, counters, stats, violations };
152}
153const load = report('load-full');
154const loadOff = report('load-off');
155const selectedDays = [1, 91, 182, 273, 365];
156const data = {
157 provenance: { research: 'R-02, чернетка, 05.10.2026', snapshots: 'research/lab/stock-sim/src/presentation-data.ts → Inventory (:memory:)',
158 reports: ['out/year-fefo/report.json', 'out/year-pack-first/report.json', 'out/load-full/report.json', 'out/load-off/report.json'] },
159 products, snapshots, genealogy,
160 annual: { fefo: annual('year-fefo'), packFirst: annual('year-pack-first') },
161 load: { opt: load.opt, latency: load.latency, latencyOff: loadOff.latency, channels: load.chStat,
162 growth: load.growth.filter((g: any) => selectedDays.includes(g.day)).map((g: any) => ({ ...g, reconcileMs: load.days.find((d: any) => d.day === g.day).reconcileMs })),
163 trucks: { initial: load.trucks.filter((t: any) => t.day === 0).length, replenishment: load.trucks.filter((t: any) => t.day > 0).length },
164 httpCalls: Object.values(load.latency).reduce((n: number, l: any) => n + l.n, 0),
165 counters: load.counters,
166 },
167};
168const asset = (name: string) => readFileSync(new URL(`../presentation/${name}`, import.meta.url), 'utf8');
169const safeScript = (script: string) => script.replace(/<\/script/gi, '<\\/script');
170const html = asset('page.html')
171 .replace('<link rel="stylesheet" href="style.css">', () => `<style>\n${asset('style.css')}\n</style>`)
172 .replace('<script defer src="data.js"></script>', '')
173 .replace('<script defer src="presentation.js"></script>', '')
174 .replace('</body>', () => `<script>\n/* Anime.js 4.5.0 — license included for standalone redistribution.\n${asset('vendor/LICENSE-animejs.md').replace(/\*\//g, '* /')}\n*/\n(function(module, exports, define) {\n${safeScript(asset('vendor/anime.umd.min.js'))}\n})();\n</script>\n<script>\nwindow.R02_DATA = ${safeScript(JSON.stringify(data))};\n${safeScript(asset('process.js'))}\n${safeScript(asset('presentation.js'))}\n</script>\n</body>`);
175const target = new URL('../../../r-02-presentation/index.html', import.meta.url);
176mkdirSync(new URL('.', target), { recursive: true });
177writeFileSync(target, html);
178console.log(`${Object.keys(snapshots).length} snapshots, all reconciled; ${fileURLToPath(target)}`);
179inv.db.close();
180