techtools
Головна / proto / flow-old / server / normalize.ts

normalize.ts

TypeScript · 229 рядків

1// Нормалізація визначень workflow і системних моделей — перенесено зі SQLite-сховища (store.js) без змін логіки.
2// Застосовується при імпорті зі SQLite, демо-заповненні й збереженні чернетки; опубліковані версії не змінюються.
3import { demoModels } from './demo.ts'
4
5export function removeDeprecatedNodes(workflow) {
6  let changed = false
7  for (const node of workflow.nodes) {
8    if (node.type === 'WAIT') {
9      node.type = 'EVENT'
10      changed = true
11    }
12  }
13  for (const node of workflow.nodes.filter(item =>
14    item.type === 'CONDITION' && Array.isArray(item.config?.routes)
15  )) {
16    node.config.routes = Object.fromEntries(
17      node.config.routes.map(route => [
18        route.port,
19        String(route.expression || '').replace(/\b(?:context|event)\./g, 'data.')
20      ])
21    )
22    node.outputs = Object.keys(node.config.routes).map(id => ({ id, name: id }))
23    changed = true
24  }
25  if (workflow.id === 'demo-putaway') {
26    const location = workflow.nodes.find(node => node.id === 'wait-location')
27    const condition = workflow.nodes.find(node => node.id === 'validate')
28    if (location && location.config?.modelId !== 'demo-location-event') {
29      location.config.modelId = 'demo-location-event'
30      changed = true
31    }
32    if (condition && condition.config?.routes?.correct !== 'data.locationId === 8812') {
33      condition.config.routes = {
34        correct: 'data.locationId === 8812',
35        intermediate: '',
36        error: '$error'
37      }
38      condition.outputs = Object.keys(condition.config.routes).map(id => ({ id, name: id }))
39      changed = true
40    }
41  }
42  for (const node of workflow.nodes.filter(item =>
43    ['NOTIFICATION', 'UPDATE_ENTITY'].includes(item.type)
44  )) {
45    const incoming = workflow.edges.filter(edge => edge.target === node.id)
46    const outgoing = workflow.edges.filter(edge => edge.source === node.id)
47    workflow.edges = workflow.edges.filter(edge => edge.target !== node.id && edge.source !== node.id)
48    for (const before of incoming) {
49      for (const after of outgoing) {
50        workflow.edges.push({
51          id: crypto.randomUUID(),
52          source: before.source,
53          sourcePort: before.sourcePort,
54          target: after.target,
55          targetPort: after.targetPort,
56          condition: before.condition || after.condition || ''
57        })
58      }
59    }
60    workflow.nodes = workflow.nodes.filter(item => item.id !== node.id)
61    changed = true
62  }
63  return changed
64}
65
66export function normalizeWorkflows(workflows) {
67  let changed = false
68  for (const workflow of workflows) {
69    if (removeDeprecatedNodes(workflow)) changed = true
70    const incoming = new Set(workflow.edges.map(edge => edge.target))
71    for (const node of workflow.nodes) {
72      node.config ||= {}
73      if (node.type === 'EVENT' && !node.config.activation && !incoming.has(node.id)) {
74        node.config.activation = 'START'
75        changed = true
76      }
77      if (node.type === 'API_REQUEST') {
78        node.outputs ||= []
79        if (!node.outputs.some(port => port.id === 'error')) {
80          node.outputs.push({ id: 'error', name: 'error' })
81          changed = true
82        }
83        if (!node.config.errorModelId) {
84          node.config.errorModelId = 'system-api-error'
85          changed = true
86        }
87        if (node.config.responseModelId && !node.config.modelId) {
88          node.config.modelId = node.config.responseModelId
89          delete node.config.responseModelId
90          changed = true
91        }
92        if (!node.config.method) {
93          node.config.method = 'GET'
94          changed = true
95        }
96        if (!node.config.url && node.config.mockResponse) {
97          node.config.url = `/mock/${node.id}`
98          changed = true
99        }
100      }
101      if (node.type === 'MAPPING' && !node.config.mapping) {
102        node.config.mapping = node.config.fields
103          ? Object.fromEntries(
104            Object.entries(node.config.fields).map(([source, target]) => [
105              target,
106              source.startsWith('data.') ? source : `data.${source}`
107            ])
108          )
109          : { $copy: 'data' }
110        delete node.config.fields
111        changed = true
112      }
113      if (node.type === 'DELAY') {
114        for (const key of ['modelId', 'outputModelId', 'responseModelId', 'outputModels']) {
115          if (key in node.config) {
116            delete node.config[key]
117            changed = true
118          }
119        }
120      }
121      if (['TASK', 'TASK_UPDATE'].includes(node.type)) {
122        node.config.taskModelId = 'system-task'
123        const inputs = node.type === 'TASK'
124          ? [{ id: 'data', name: 'data' }]
125          : [{ id: 'data', name: 'data' }, { id: 'task', name: 'task' }]
126        const outputs = [{ id: 'next', name: 'next' }, { id: 'task', name: 'task' }]
127        if (JSON.stringify(node.inputs) !== JSON.stringify(inputs)) {
128          node.inputs = inputs
129          changed = true
130        }
131        if (JSON.stringify(node.outputs) !== JSON.stringify(outputs)) {
132          for (const edge of workflow.edges.filter(edge => edge.source === node.id)) {
133            if (!['next', 'task'].includes(edge.sourcePort)) edge.sourcePort = 'next'
134          }
135          node.outputs = outputs
136          changed = true
137        }
138        if (node.type === 'TASK') {
139          if (!node.config.taskType) {
140            node.config.taskType = node.config.type || 'GENERAL'
141            changed = true
142          }
143          if (!node.config.assigneeType) {
144            node.config.assigneeType = 'group'
145            changed = true
146          }
147          if (!node.config.assignee) {
148            node.config.assignee = node.config.role || 'unassigned'
149            changed = true
150          }
151          for (const [key, value] of Object.entries({
152            title: 'New task',
153            description: '',
154            priority: 'normal',
155            progress: 'waiting',
156            state: 'created',
157            entityType: 'warehouse_item'
158          })) {
159            if (node.config[key] === undefined) {
160              node.config[key] = value
161              changed = true
162            }
163          }
164          if (!node.config.payloadMapping) {
165            node.config.payloadMapping = { $copy: 'data' }
166            changed = true
167          }
168          delete node.config.type
169          delete node.config.role
170        } else {
171          if (node.config.complete === undefined) {
172            node.config.complete = false
173            changed = true
174          }
175        }
176      }
177      if (node.type === 'CLIENT_RESPONSE' && node.outputs?.length) {
178        node.outputs = []
179        changed = true
180      }
181    }
182  }
183
184  for (const workflow of workflows) {
185    for (const node of workflow.nodes) {
186      if (node.type === 'WORKFLOW' && 'inputMapping' in node.config) {
187        delete node.config.inputMapping
188        changed = true
189      }
190      if (node.type === 'MAPPING' && 'outputModelId' in node.config) {
191        delete node.config.outputModelId
192        changed = true
193      }
194      if (node.type === 'WORKFLOW_OUTPUT') {
195        for (const key of ['modelId', 'mapping', 'outputModelId', 'outputModels']) {
196          if (key in node.config) {
197            delete node.config[key]
198            changed = true
199          }
200        }
201      }
202    }
203  }
204  return changed
205}
206
207/** Системні моделі (Task, ApiError, WorkflowError) — завжди актуальні; демо-моделі — якщо їх немає. Повертає змінені / додані. */
208export function syncSystemModels(models) {
209  const changed = []
210  for (const candidate of demoModels().filter(model => model.system)) {
211    const existing = models.find(model => model.id === candidate.id)
212    if (!existing) {
213      models.push(candidate)
214      changed.push(candidate)
215    } else if (JSON.stringify(existing.schema) !== JSON.stringify(candidate.schema)) {
216      existing.schema = candidate.schema
217      existing.updatedAt = new Date().toISOString()
218      changed.push(existing)
219    }
220  }
221  for (const candidate of demoModels().filter(model => !model.system)) {
222    if (!models.some(model => model.id === candidate.id)) {
223      models.push(candidate)
224      changed.push(candidate)
225    }
226  }
227  return changed
228}
229