storyboard.ts
TypeScript · 125 рядків
1// Розкадровка приймання (R-23 §12): з трасування прогону (out/r23-trace.json, scripts/r23/run.ts) — кроки з подією,
2// хто відреагував, шлях блоків зі зміною даних після кожного блока, екран ТСД і зміни WMS / задач / ERP.
3// Дані вбудовуються в research/r-23-presentation/template.html → index.html (портал, без сервера) і artifact.html (публікація).
4//
5// node scripts/r23/run.ts && node scripts/r23/storyboard.ts
6import { readFileSync, writeFileSync } from 'node:fs'
7import { dirname, join } from 'node:path'
8import { fileURLToPath } from 'node:url'
9
10type Json = any
11
12const here = dirname(fileURLToPath(import.meta.url))
13const root = join(here, '..', '..')
14const pageDir = join(root, '..', '..', 'research', 'r-23-presentation')
15const trace = JSON.parse(readFileSync(join(root, 'out', 'r23-trace.json'), 'utf8'))
16
17/** Плоска мапа шлях → значення; масиви коротко. */
18function flat(value: Json, prefix = '', out: Record<string, string> = {}) {
19 if (value === null || value === undefined || typeof value !== 'object') {
20 const text = JSON.stringify(value ?? null)
21 if (prefix) out[prefix] = text.length > 90 ? `${text.slice(0, 87)}…"` : text
22 return out
23 }
24 if (Array.isArray(value)) {
25 // масив об'єктів (задачі, палети) — лише кількість; короткий масив значень — як є
26 out[prefix] = value.length > 3 || value.some((item) => item && typeof item === 'object') ? `[${value.length} ел.]` : JSON.stringify(value)
27 return out
28 }
29 for (const [key, item] of Object.entries(value)) flat(item, prefix ? `${prefix}.${key}` : key, out)
30 return out
31}
32
33function delta(before: Json, after: Json) {
34 const a = flat(before), b = flat(after)
35 const rows: Json[] = []
36 for (const [path, value] of Object.entries(b)) if (a[path] !== value) rows.push({ path, from: a[path] ?? null, to: value })
37 for (const path of Object.keys(a)) if (!(path in b)) rows.push({ path, from: a[path], to: null })
38 return rows
39}
40
41function wmsChanges(before: Json, after: Json) {
42 const changes: Json[] = []
43 const lineKey = (l: Json) => `${l.pallet_id}/${l.sku}`
44 const lines = new Map(before.lines.map((l: Json) => [lineKey(l), l]))
45 for (const l of after.lines) {
46 const was: Json = lines.get(lineKey(l))
47 if (!was) changes.push({ kind: 'рядок ордера', text: `${l.pallet_id} · ${l.sku}: очікується ${l.expected}` })
48 else if (was.received !== l.received) changes.push({ kind: 'прийнято', text: `${l.pallet_id} · ${l.sku}: ${was.received} → ${l.received} з ${l.expected}` })
49 }
50 for (const d of after.documents) {
51 const was = before.documents.find((x: Json) => x.order_id === d.order_id)
52 if (!was) changes.push({ kind: 'документ', text: `ордер ${d.order_id}, фура ${d.truck}` })
53 else if (was.status !== d.status) changes.push({ kind: 'документ', text: `ордер ${d.order_id}: ${was.status} → ${d.status}` })
54 }
55 const boxes = new Map(before.containers.map((c: Json) => [c.code, c]))
56 for (const c of after.containers) {
57 const was: Json = boxes.get(c.code)
58 if (!was) { changes.push({ kind: 'тара', text: `нова ${c.code} · ${c.destination} → ${c.target}` }); continue }
59 if (was.status !== c.status) changes.push({ kind: 'тара', text: `${c.code}: ${was.status} → ${c.status}` })
60 const items = new Map((was.items || []).map((i: Json) => [i.sku, i]))
61 for (const i of c.items || []) {
62 const w: Json = items.get(i.sku)
63 if (!w || w.qty !== i.qty) changes.push({ kind: 'у тарі', text: `${c.code} · ${i.sku}: ${w?.qty ?? 0} → ${i.qty} шт` })
64 if (w && w.placed !== i.placed) changes.push({ kind: 'викладено', text: `${c.code} · ${i.sku}: ${w.placed} → ${i.placed} з ${i.qty}` })
65 }
66 }
67 for (const s of after.stock) {
68 const was = before.stock.find((x: Json) => x.address === s.address && x.sku === s.sku)
69 if (!was || was.qty !== s.qty) changes.push({ kind: 'залишок', text: `${s.address} · ${s.sku}: ${was?.qty ?? 0} → ${s.qty}` })
70 }
71 const erp = after.erp.slice(before.erp.length).map((e: Json) => ({ type: e.type, text: [e.payload.orderId, e.payload.sku, e.payload.address].filter(Boolean).join(' · ') }))
72 return { changes, erp }
73}
74
75function taskChanges(before: Json[], after: Json[]) {
76 const out: Json[] = []
77 for (const t of after) {
78 const was = before.find((x) => x.id === t.id)
79 if (!was) out.push({ kind: 'створено', title: t.title, role: t.role, priority: t.priority, type: t.type })
80 else if (was.status !== t.status) out.push({ kind: t.status === 'completed' ? 'виконано' : t.status, title: t.title, role: t.role, priority: t.priority, type: t.type })
81 }
82 return out
83}
84
85const workflows = trace.workflows.map((w: Json) => ({
86 id: w.id, name: w.name, version: w.version,
87 nodes: w.nodes.map((n: Json) => ({ id: n.id, type: n.type, name: n.name, x: n.x, y: n.y, outputs: n.outputs, rows: n.type === 'DECISION' ? n.config.rows.map((r: Json) => r.label) : undefined })),
88 edges: w.edges,
89}))
90const nodeOf = (workflowId: string, nodeId: string) => workflows.find((w: Json) => w.id === workflowId)?.nodes.find((n: Json) => n.id === nodeId)
91
92const steps = trace.steps.map((s: Json) => {
93 const runs = s.runs.map((r: Json) => {
94 let previous = r.contextBefore || {}
95 const path = r.path.map((p: Json) => {
96 const node = nodeOf(r.workflowId, p.nodeId)
97 const row: Json = { nodeId: p.nodeId, name: p.name, type: node?.type || p.kind, port: p.port, error: p.error || null, delta: [] }
98 if (p.context) {
99 row.delta = delta(previous, p.context).filter((d: Json) => !d.path.startsWith('entity.'))
100 previous = p.context
101 }
102 if (node?.type === 'DECISION') {
103 const result = Object.values(p.context || {}).find((v: Json) => v && typeof v === 'object' && 'rule' in v) as Json
104 row.rule = result?.rule || null
105 }
106 if (p.response) row.screen = p.response.body?.screen || null
107 return row
108 })
109 return { workflowId: r.workflowId, version: r.version, status: r.status, error: r.error, kind: r.kind, task: r.task, path }
110 })
111 const { changes, erp } = wmsChanges(s.before.wms, s.after.wms)
112 return {
113 n: s.n, who: s.who, source: s.source, event: s.event, eventId: s.eventId, duplicate: s.duplicate, status: s.status,
114 screen: s.response?.screen || null, error: s.response?.error || null, runs, wms: changes, erp, tasks: taskChanges(s.before.tasks, s.after.tasks),
115 }
116})
117
118const data = { generatedAt: trace.generatedAt, workflows, steps }
119const template = readFileSync(join(pageDir, 'template.html'), 'utf8')
120const page = template.replace('/*__DATA__*/null', JSON.stringify(data).replace(/</g, '\\u003c'))
121// artifact.html — фрагмент для публікації (обгортку документа додає публікація); index.html — повний документ для порталу
122writeFileSync(join(pageDir, 'artifact.html'), page)
123writeFileSync(join(pageDir, 'index.html'), `<!doctype html>\n<html lang="uk">\n<head>\n<meta charset="utf-8">\n<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">\n</head>\n<body>\n${page}\n</body>\n</html>\n`)
124console.log(`${steps.length} кроків → ${join(pageDir, 'index.html')} (${Math.round(page.length / 1024)} КБ)`)
125