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

store.test.ts

TypeScript · 109 рядків

1// Перенесено з SQLite-версії (store.test.js): ті самі перевірки міграцій старих блоків, ревізій, задач і inbox —
2// тепер через імпорт SQLite-бази в PostgreSQL, чернетку → публікацію й правила видалення.
3import test from 'node:test'
4import assert from 'node:assert/strict'
5import fs from 'node:fs'
6import os from 'node:os'
7import path from 'node:path'
8import { DatabaseSync } from 'node:sqlite'
9import { importSqlite } from '../server/bootstrap.ts'
10import { demoModels, demoWorkflow } from '../server/demo.ts'
11import { testServer } from './helpers.ts'
12
13/** SQLite-база в схемі старої версії з «застарілими» вузлами й ревізіями. */
14function legacySqlite(): string {
15  const file = path.join(os.tmpdir(), `wms-flow-${crypto.randomUUID()}.sqlite`)
16  const db = new DatabaseSync(file)
17  db.exec(`
18    CREATE TABLE workflows (id TEXT PRIMARY KEY, name TEXT, version INTEGER, status TEXT, definition TEXT, created_at TEXT, updated_at TEXT);
19    CREATE TABLE data_models (id TEXT PRIMARY KEY, name TEXT, schema TEXT, created_at TEXT, updated_at TEXT, data TEXT);
20    CREATE TABLE inbox_events (event_id TEXT PRIMARY KEY, event TEXT, entity_type TEXT, entity_id TEXT, status TEXT, received_at TEXT, processed_at TEXT, data TEXT);`)
21  const now = new Date().toISOString()
22  const workflow: any = demoWorkflow()
23  const api = workflow.nodes.find((n) => n.type === 'API_REQUEST')
24  api.config.responseModelId = 'demo-warehouse-event'
25  delete api.config.errorModelId
26  api.outputs = api.outputs.filter((p) => p.id !== 'error')
27  workflow.nodes.push(
28    { id: 'legacy-wait', type: 'WAIT', name: 'LEGACY WAIT', inputs: [], outputs: [], config: { event: 'LEGACY', modelId: 'demo-warehouse-event' } },
29    { id: 'legacy-notification', type: 'NOTIFICATION', name: 'LEGACY NOTIFICATION', inputs: [{ id: 'in' }], outputs: [{ id: 'next' }], config: {} },
30    { id: 'legacy-update', type: 'UPDATE_ENTITY', name: 'LEGACY UPDATE', inputs: [{ id: 'in' }], outputs: [], config: {} },
31  )
32  workflow.edges.push({ id: 'n1', source: 'completed', sourcePort: 'next', target: 'legacy-notification', targetPort: 'in' })
33  workflow.version = 3
34  workflow.revisions = [{ ...structuredClone(demoWorkflow()), version: 1, name: 'Putaway v1' }, { ...structuredClone(demoWorkflow()), version: 2, name: 'Putaway v2' }]
35  db.prepare('INSERT INTO workflows VALUES (?, ?, ?, ?, ?, ?, ?)').run(workflow.id, workflow.name, 3, 'published', JSON.stringify(workflow), now, now)
36  for (const model of demoModels().filter((m) => !m.system)) {
37    db.prepare('INSERT INTO data_models VALUES (?, ?, ?, ?, ?, ?)').run(model.id, model.name, JSON.stringify(model.schema), now, now, JSON.stringify(model))
38  }
39  const inbox = { eventId: 'persisted-event', event: 'SCAN_POST1', entityType: 'item', entityId: 'handler-reference', status: 'processed', result: { processed: 1 }, receivedAt: now, processedAt: now }
40  db.prepare('INSERT INTO inbox_events VALUES (?, ?, ?, ?, ?, ?, ?, ?)').run(inbox.eventId, inbox.event, inbox.entityType, inbox.entityId, inbox.status, now, now, JSON.stringify(inbox))
41  db.close()
42  return file
43}
44
45test('SQLite import migrates legacy blocks, revisions and inbox; drafts publish versions; delete honours active tasks', async () => {
46  const t = await testServer('store', { bootstrap: false })
47  const file = legacySqlite()
48  try {
49    await t.db.transaction((sql) => importSqlite(sql, file))
50
51    const workflow = (await t.call('GET', '/api/workflows/demo-putaway')).body
52    const apiNode = workflow.nodes.find((node) => node.type === 'API_REQUEST')
53    assert.equal(apiNode.config.modelId, 'demo-warehouse-event')
54    assert.equal(apiNode.config.responseModelId, undefined)
55    assert.equal(apiNode.config.errorModelId, 'system-api-error')
56    assert.ok(apiNode.outputs.some((p) => p.id === 'error'))
57    assert.equal(workflow.nodes.find((node) => node.id === 'legacy-wait').type, 'EVENT')
58    assert.equal(workflow.nodes.some((node) => ['NOTIFICATION', 'UPDATE_ENTITY'].includes(node.type)), false)
59    assert.equal(workflow.version, 3)
60    assert.deepEqual((await t.call('GET', '/api/workflows/demo-putaway/versions')).body.map((v) => v.version), [3, 2, 1])
61
62    const models = (await t.call('GET', '/api/models')).body
63    assert.equal(models.find((m) => m.id === 'system-api-error').system, true)
64    assert.equal((await t.call('DELETE', '/api/models/system-api-error')).status, 403)
65
66    // чернетка → публікація: версія лише при публікації, попередня версія доступна
67    const created = (await t.call('POST', '/api/workflows', { name: 'Temporary', status: 'draft', nodes: [], edges: [] })).body
68    assert.equal(created.version, 0)
69    assert.equal(created.hasDraft, true)
70    assert.equal((await t.call('POST', `/api/workflows/${created.id}/publish`)).body.version, 1)
71    const revised = (await t.call('PUT', `/api/workflows/${created.id}`, { ...created, name: 'Temporary revised' })).body
72    assert.equal(revised.version, 1)
73    assert.equal(revised.hasDraft, true)
74    assert.equal((await t.call('POST', `/api/workflows/${created.id}/publish`)).body.version, 2)
75    const [v1] = await t.sql.query('SELECT definition FROM workflow_versions WHERE workflow_id = :id AND version = 1', { id: created.id })
76    assert.equal(v1.definition.name, 'Temporary')
77
78    // виконання, журнал і задачі, що посилаються на workflow
79    const now = new Date().toISOString()
80    const execution = { id: 'remove-execution', workflowId: created.id, workflowVersion: 2, entityType: 'item', entityId: '1', status: 'completed', currentNodeId: null, waitingFor: null, context: {}, history: [], startedAt: now, updatedAt: now, completedAt: now }
81    await t.sql.query(`INSERT INTO workflow_executions (id, workflow_id, workflow_version, entity_type, entity_id, status, updated_at, data) VALUES ('remove-execution', :wf, 2, 'item', '1', 'completed', now(), :data)`,
82      { wf: created.id, data: JSON.stringify(execution) })
83    await t.sql.query(`INSERT INTO workflow_execution_logs (id, execution_id, created_at, data) VALUES ('remove-log', 'remove-execution', now(), '{"id":"remove-log"}')`)
84    const task = (id: string, executionId: string, entityId: string, handler: string | null, status: string) => t.sql.query(`
85      INSERT INTO workflow_tasks (id, execution_id, entity_type, entity_id, type, handler_workflow_id, handler_workflow_version, status, updated_at, data)
86      VALUES (:id, :executionId, 'item', :entityId, 'TEST', :handler, 1, :status, now(), :data)`,
87    { id, executionId, entityId, handler, status, data: JSON.stringify({ id, executionId, entityType: 'item', entityId, type: 'TEST', handlerWorkflowId: handler, handlerWorkflowVersion: 1, status }) })
88    await task('remove-task', 'remove-execution', '1', null, 'waiting')
89    await task('active-handler-task', 'creation-execution', 'handler-reference', created.id, 'open')
90    await task('active-created-task', 'remove-execution', 'creator-reference', 'demo-putaway', 'open')
91
92    const inbox = await t.sql.query("SELECT result FROM inbox_events WHERE event_id = 'persisted-event'")
93    assert.equal(inbox[0].result.processed, 1)
94
95    assert.equal((await t.call('DELETE', `/api/workflows/${created.id}`)).status, 409)
96    await t.sql.query("UPDATE workflow_tasks SET status = 'completed' WHERE id = 'active-handler-task'")
97    assert.equal((await t.call('DELETE', `/api/workflows/${created.id}`)).status, 409)
98    await t.sql.query("UPDATE workflow_tasks SET status = 'completed' WHERE id = 'active-created-task'")
99    assert.equal((await t.call('DELETE', `/api/workflows/${created.id}`)).status, 204)
100    assert.equal((await t.call('GET', `/api/workflows/${created.id}`)).status, 404)
101    assert.equal((await t.call('GET', '/api/executions/remove-execution')).status, 404)
102    assert.equal((await t.sql.query("SELECT 1 FROM workflow_execution_logs WHERE id = 'remove-log'")).length, 0)
103    assert.equal((await t.sql.query("SELECT 1 FROM workflow_tasks WHERE id = 'remove-task'")).length, 0)
104  } finally {
105    await t.stop()
106    fs.rmSync(file, { force: true })
107  }
108})
109