techtools
Головна / proto / flow-old / shared / decision.ts

decision.ts

TypeScript · 116 рядків

1// DECISION — таблиця рішень (R-23 §2, шар «правила»; P1 з R-23 §9.3). Однаково для рушія, перевірки й редактора.
2//
3//   {
4//     "resultPath": "dest",
5//     "rows": [
6//       { "label": "неперевірене", "when": "data.line.facts.missingData == true", "port": "next", "set": { "destination": "control", "target": "CTRL" } },
7//       { "label": "резерв клієнта", "when": "data.line.facts.reserveOrder != \"\"", "set": { "destination": "crossdock", "target": "=data.line.facts.reserveOrder" } },
8//       { "label": "інакше", "when": "", "set": { "destination": "storage", "target": "normal" } }
9//     ]
10//   }
11//
12// Рядки перевіряються згори вниз; перший, чия умова істинна (порожня — завжди), записує свої значення в data.<resultPath>
13// (значення — як в ACTION: літерал або вираз з "=") і назву рядка в data.<resultPath>.rule — «чому так вирішено».
14// Вихід — port рядка (за замовчуванням "next"); рядки з однаковим port ведуть в один вихід. Якщо рядка «інакше» немає
15// й жодна умова не спрацювала — вихід "none".
16import { actionExpression, evaluateCondition, evaluateExpression, inferExpressionType, validateCondition } from './condition.ts'
17import { literalType } from './action.ts'
18
19export const DECISION_DEFAULT_PORT = 'next'
20export const DECISION_NO_MATCH_PORT = 'none'
21
22const portOf = (row: any) => String(row?.port || '').trim() || DECISION_DEFAULT_PORT
23const isFallback = (row: any) => !String(row?.when ?? '').trim()
24const resultPathOf = (config: any) => String(config?.resultPath || 'decision').trim()
25
26/** Виходи блока в порядку рядків; "none" — якщо немає рядка без умови. */
27export function decisionPorts(config: any = {}): string[] {
28  const rows = Array.isArray(config.rows) ? config.rows : []
29  const ports = [...new Set(rows.map(portOf))] as string[]
30  if (!rows.some(isFallback)) ports.push(DECISION_NO_MATCH_PORT)
31  return ports
32}
33
34/** Стовпці таблиці — поля set усіх рядків у порядку першої появи. */
35export function decisionColumns(config: any = {}): string[] {
36  const columns: string[] = []
37  for (const row of config.rows || []) for (const key of Object.keys(row?.set || {})) if (!columns.includes(key)) columns.push(key)
38  return columns
39}
40
41function setValue(object: any, path: string, value: any) {
42  const keys = path.split('.')
43  const last = keys.pop() as string
44  const target = keys.reduce((current, key) => {
45    if (!current[key] || typeof current[key] !== 'object') current[key] = {}
46    return current[key]
47  }, object)
48  target[last] = value
49}
50
51/** Виконати таблицю над контекстом: { port, row } — row = індекс рядка або -1. */
52export function runDecision(config: any = {}, context: any, scopes: any = {}) {
53  const rows = config.rows || []
54  const all = { ...scopes, data: context, input: context }
55  for (let index = 0; index < rows.length; index += 1) {
56    const row = rows[index]
57    if (!isFallback(row) && !evaluateCondition(String(row.when).trim(), all)) continue
58    const result: any = {}
59    for (const [field, value] of Object.entries(row.set || {})) {
60      const expression = actionExpression(value)
61      result[field] = expression === null ? structuredClone(value) : evaluateExpression(expression, all)
62    }
63    result.rule = String(row.label || '').trim() || `#${index + 1}`
64    setValue(context, resultPathOf(config), result)
65    return { port: portOf(row), row: index }
66  }
67  return { port: DECISION_NO_MATCH_PORT, row: -1 }
68}
69
70const sameType = (left: any, right: any) => JSON.stringify(left) === JSON.stringify(right)
71  || [left, right].includes('any') || (['number', 'integer'].includes(left) && ['number', 'integer'].includes(right))
72
73/**
74 * Схема data після блока і помилки таблиці. scopeSchemas — { task, event }. Результат однаковий для всіх виходів:
75 * кожен рядок пише ті самі стовпці (рядок без значення в стовпці — помилка, бо далі поле може бути не записане).
76 */
77export function decisionOutputSchema(config: any = {}, inherited: any = {}, scopeSchemas: any = {}) {
78  const errors: string[] = []
79  const rows = Array.isArray(config.rows) ? config.rows : []
80  const resultPath = resultPathOf(config)
81  if (!/^[A-Za-z_$][\w$]*(\.[A-Za-z_$][\w$]*)*$/.test(resultPath)) errors.push(`result path is invalid: ${resultPath}`)
82  if (!rows.length) errors.push('at least one row is required')
83  const columns = decisionColumns(config)
84  const schema = { ...scopeSchemas, data: inherited, input: inherited }
85  const result: any = {}
86  rows.forEach((row: any, index: number) => {
87    const name = String(row?.label || '').trim() || `#${index + 1}`
88    if (!isFallback(row)) for (const error of validateCondition(String(row.when).trim(), schema).errors) errors.push(`row ${name}: ${error}`)
89    if (isFallback(row) && index < rows.length - 1) errors.push(`row ${name}: a row without a condition must be last — rows below it never run`)
90    for (const column of columns) {
91      if (!(column in (row?.set || {}))) { errors.push(`row ${name}: no value for "${column}"`); continue }
92      const value = row.set[column]
93      const expression = actionExpression(value)
94      let type = literalType(value)
95      if (expression !== null) {
96        const inferred = inferExpressionType(expression, schema)
97        for (const error of inferred.errors) errors.push(`row ${name} · ${column}: ${error}`)
98        type = inferred.type
99      }
100      if (column in result && !sameType(result[column], type)) errors.push(`column "${column}": rows give ${JSON.stringify(result[column])} and ${JSON.stringify(type)}`)
101      else if (!(column in result) || result[column] === 'any') result[column] = type
102    }
103  })
104  result.rule = 'string'
105  const out = structuredClone(inherited || {})
106  setValue(out, resultPath, result)
107  return { schema: out, errors: [...new Set(errors)] }
108}
109
110/** Помилки конфігурації, яких не видно зі схеми: виходи блока мають відповідати рядкам. */
111export function validateDecisionPorts(node: any): string[] {
112  const expected = decisionPorts(node.config)
113  const actual = (node.outputs || []).map((port: any) => port.id)
114  return JSON.stringify(expected) === JSON.stringify(actual) ? [] : [`output ports must match the rows: ${expected.join(', ')}`]
115}
116