techtools
Головна / proto / flow-old / test / r30-stages.test.ts

r30-stages.test.ts

TypeScript · 128 рядків

1// R-30.12: етап — область одного борду. Задача етапу приймає події лише від TASK-подій у своїй області;
2// модель контексту — властивість етапу; передача TASK → етап видима як handoff.
3import test, { after, before } from 'node:test'
4import assert from 'node:assert/strict'
5import { stageHandoffs, stageOf, validateStages } from '../shared/stages.ts'
6import { validateWorkflow } from '../server/validation.ts'
7import { demoModels } from '../server/demo.ts'
8import { edge, node, publishWorkflow, testServer } from './helpers.ts'
9
10const at = (n: any, x: number, y: number) => ({ ...n, x, y })
11const stages = [
12  { id: 'pick', name: 'Відбір', x: 300, y: 0, width: 700, height: 300, taskContextModelId: 'r30-ctx' },
13  { id: 'pack', name: 'Пакування', x: 1100, y: 0, width: 700, height: 300, taskContextModelId: 'r30-ctx' },
14]
15const task = (id: string, stage: string, entityType: string, entityIdPath: string) => node(id, 'TASK', {
16  handlerStageId: stage, entityType, entityIdPath, assigneeType: 'group', assignee: 'picker', taskType: stage.toUpperCase(),
17  title: `${stage} {{data.orderId}}`, payloadMapping: { orderId: 'data.orderId', basket: 'data.basket' },
18}, ['next', 'task'], ['data'])
19const done = (id: string, text: string) => node(id, 'SCREEN', { kind: 'done', text, expect: 'none', tone: 'ok' }, [])
20const complete = (id: string) => node(id, 'TASK_UPDATE', { taskModelId: 'system-task', taskIdPath: 'task.id', state: 'done', complete: true }, ['next', 'task'], ['data', 'task'])
21
22function board() {
23  return {
24    id: 'r30-board', name: 'R30 · Відбір і пакування', settings: { stages },
25    nodes: [
26      at(node('order', 'EVENT', { event: 'ORDER_READY', activation: 'START', modelId: 'r30-order' }, ['next'], []), 0, 100),
27      at(task('to-pick', 'pick', 'order', 'data.orderId'), 0, 260),
28      // етап «Відбір»: скан → передати кошик на пакування → закрити задачу відбору
29      at(node('pick-scan', 'EVENT', { event: 'SCAN', activation: 'TASK', modelId: 'r30-scan' }, ['next'], []), 320, 40),
30      at(task('to-pack', 'pack', 'basket', 'data.basket'), 560, 40),
31      at(complete('pick-done'), 780, 40),
32      at(done('pick-screen', 'Кошик {{data.basket}} — на пакування'), 780, 180),
33      // етап «Пакування»: та сама подія SCAN — інша задача
34      at(node('pack-scan', 'EVENT', { event: 'SCAN', activation: 'TASK', modelId: 'r30-scan' }, ['next'], []), 1120, 40),
35      at(complete('pack-done'), 1360, 40),
36      at(done('pack-screen', 'Замовлення {{data.orderId}} запаковано'), 1580, 40),
37    ],
38    edges: [
39      edge('order', 'next', 'to-pick', 'data'),
40      edge('pick-scan', 'next', 'to-pack', 'data'),
41      edge('to-pack', 'next', 'pick-done', 'data'),
42      edge('pick-done', 'next', 'pick-screen'),
43      edge('pack-scan', 'next', 'pack-done', 'data'),
44      edge('pack-done', 'next', 'pack-screen'),
45    ],
46  }
47}
48
49function models() {
50  const now = new Date().toISOString()
51  return [
52    ...demoModels(),
53    { id: 'r30-order', name: 'R30Order', schema: { event: 'string', orderId: 'string', basket: 'string' }, createdAt: now, updatedAt: now },
54    { id: 'r30-scan', name: 'R30Scan', schema: { event: 'string', code: 'string' }, createdAt: now, updatedAt: now },
55    { id: 'r30-ctx', name: 'R30Context', schema: { orderId: 'string', basket: 'string' }, createdAt: now, updatedAt: now },
56  ]
57}
58
59test('a block belongs to the stage that contains its centre; hand-offs go from the TASK stage to the handler stage', () => {
60  const b = board()
61  const byId = (id: string) => b.nodes.find((n) => n.id === id)
62  assert.equal(stageOf(b, byId('pick-scan'))?.id, 'pick')
63  assert.equal(stageOf(b, byId('pack-done'))?.id, 'pack')
64  assert.equal(stageOf(b, byId('order')), null)
65  assert.deepEqual(stageHandoffs(b).map((h) => [h.from, h.to, h.label]), [[null, 'pick', 'order'], ['pick', 'pack', 'basket']])
66})
67
68test('the board validates: stage context model gives data.* of TASK events and the TASK payload contract', () => {
69  const { issues } = validateWorkflow(board(), models(), [])
70  assert.deepEqual(issues.filter((i) => i.severity !== 'warning').map((i) => i.message), [])
71  const broken = board()
72  broken.nodes.find((n) => n.id === 'to-pack').config.payloadMapping = { orderId: 'data.orderId' }
73  const errors = validateWorkflow(broken, models(), []).issues.map((i) => i.message)
74  assert.ok(errors.some((m) => m.includes('handler task context') && m.includes('basket')), errors.join('\n'))
75})
76
77test('stage checks: unknown stage, stage without a TASK event, stage and workflow handler together', () => {
78  const b = board()
79  b.nodes.find((n) => n.id === 'to-pack').config.handlerStageId = 'nope'
80  assert.ok(validateStages(b).some((i) => i.message.includes('handler stage not found')))
81  const empty = board()
82  empty.nodes = empty.nodes.filter((n) => n.id !== 'pack-scan')
83  assert.ok(validateStages(empty).some((i) => i.severity === 'warning' && i.message.includes('no TASK event')))
84  const both = board()
85  both.nodes.find((n) => n.id === 'to-pick').config.handlerWorkflowId = 'other'
86  assert.ok(validateStages(both).some((i) => i.message.includes('not both')))
87})
88
89let t: Awaited<ReturnType<typeof testServer>>
90const ids = new Map<string, string>()
91// API моделей видає id сам — процес посилається на видані (як scripts/r23/receiving.ts)
92const withIds = (value: any) => {
93  let text = JSON.stringify(value)
94  for (const [local, saved] of ids) text = text.replaceAll(JSON.stringify(local), JSON.stringify(saved))
95  return JSON.parse(text)
96}
97before(async () => {
98  t = await testServer('r30stages')
99  for (const { id, ...model } of models().filter((m) => m.id.startsWith('r30-'))) {
100    const r = await t.call('POST', '/api/models', model)
101    assert.equal(r.status, 201, JSON.stringify(r.body))
102    ids.set(id, r.body.id)
103  }
104})
105after(async () => { await t.stop() })
106
107test('one board: the same SCAN goes to the picking stage for the order and to the packing stage for the basket', async () => {
108  await publishWorkflow(t.call, withIds(board()))
109  await t.call('POST', '/api/events?responseMode=sync', { event: 'ORDER_READY', entityType: 'order', entityId: 'O-1', orderId: 'O-1', basket: 'K-7' })
110  const tasks = async () => (await t.sql.query<{ data: any }>(`SELECT data FROM workflow_tasks ORDER BY updated_at`)).map((r) => r.data)
111  const [pick] = await tasks()
112  assert.equal(pick.handlerStageId, 'pick')
113  assert.equal(pick.handlerWorkflowId, 'r30-board')
114
115  const picked = await t.call('POST', '/api/events?responseMode=sync', { event: 'SCAN', entityType: 'order', entityId: 'O-1', code: '01111' })
116  assert.equal(picked.status, 200, JSON.stringify(picked.body))
117  assert.equal(picked.body.screen.text, 'Кошик K-7 — на пакування')
118  const afterPick = await tasks()
119  const pack = afterPick.find((x) => x.handlerStageId === 'pack')
120  assert.equal(pack.entityType, 'basket')
121  assert.equal(pack.entityId, 'K-7')
122  assert.equal(afterPick.find((x) => x.handlerStageId === 'pick').status, 'completed')
123
124  const packed = await t.call('POST', '/api/events?responseMode=sync', { event: 'SCAN', entityType: 'basket', entityId: 'K-7', code: '01111' })
125  assert.equal(packed.body.screen.text, 'Замовлення O-1 запаковано')
126  assert.equal((await tasks()).find((x) => x.handlerStageId === 'pack').status, 'completed')
127})
128