task.ts
TypeScript · 146 рядків
1import { buildMappedData, deriveMappingSchema, validateMapping } from './mapping.ts'
2import { validateWorkflowContract } from './workflow-contract.ts'
3import { literalType } from './action.ts'
4import { stageById, stageContextModelId, stageOf } from './stages.ts'
5
6const pathPattern = /\b(?:data|task|event|parent)(?:\.[A-Za-z_$][\w$]*)+/g
7
8/**
9 * Модель контексту задачі (G1, R-12 §11.3): задається у властивостях workflow-обробника (settings.taskContextModelId).
10 * Це схема data.* на вході TASK-подій обробника і контракт payloadMapping блока TASK, що створює задачу.
11 * Блок EVENT може перевизначити її власним config.taskContextModelId (стара форма).
12 */
13export function taskContextModelId(workflow, node = null) {
14 // етап борду (R-30.12): TASK-подія в області етапу бере модель етапу
15 return node?.config?.taskContextModelId
16 || (node ? stageOf(workflow, node)?.taskContextModelId : null)
17 || workflow?.settings?.taskContextModelId
18 || null
19}
20
21/** Модель контексту задачі, яку створює блок TASK: етап цього борду (handlerStageId) або окремий workflow-обробник. */
22export function handlerContextModelId(board, workflows, config: any = {}) {
23 const stage = stageById(board, config?.handlerStageId)
24 if (stage) return stageContextModelId(board, stage)
25 return taskContextModelId(findHandlerWorkflow(workflows, config?.handlerWorkflowId))
26}
27
28/** Workflow-обробник за id або точною унікальною назвою — як resolveHandlerWorkflow у рушії. */
29export function findHandlerWorkflow(workflows, reference) {
30 const value = String(reference || '').trim()
31 if (!value) return null
32 const byId = (workflows || []).find(item => item.id === value)
33 if (byId) return byId
34 const byName = (workflows || []).filter(item => item.name === value)
35 return byName.length === 1 ? byName[0] : null
36}
37
38export function readRuntimePath(scopes, path) {
39 const parts = String(path || '').split('.').filter(Boolean)
40 const root = parts.shift()
41 const source = ['data', 'task', 'event', 'parent'].includes(root) ? scopes?.[root] : scopes?.data
42 const keys = ['data', 'task', 'event', 'parent'].includes(root) ? parts : [root, ...parts].filter(Boolean)
43 return keys.reduce((value, key) => value?.[key], source)
44}
45
46export function readTaskPath(data, path) {
47 return readRuntimePath({ data }, path)
48}
49
50export function renderTaskTemplate(template, data, scopes: any = {}) {
51 const runtime = { data, ...scopes }
52 return String(template ?? '').replace(
53 /{{\s*((?:data|task|event|parent)(?:\.[A-Za-z_$][\w$]*)+)\s*}}/g,
54 (_, path) => {
55 const value = readRuntimePath(runtime, path)
56 if (value === undefined) throw new Error(`Task field not found: ${path}`)
57 return typeof value === 'object' ? JSON.stringify(value) : String(value)
58 }
59 )
60}
61
62export function resolveTaskValue(value, data, scopes: any = {}) {
63 return typeof value === 'string' && /^(?:data|task|event|parent)\./.test(value.trim())
64 ? readRuntimePath({ data, ...scopes }, value.trim())
65 : value
66}
67
68export function taskPayload(mapping, data, scopes: any = {}) {
69 return buildMappedData(mapping || { $copy: 'data' }, data, scopes)
70}
71
72/** Значення за замовчуванням моделі (P4, R-23 §11): поле, якого мапінг не дав, береться з defaults. */
73export function withDefaults(payload: any, defaults: any) {
74 if (!defaults) return payload
75 const result = { ...(payload || {}) }
76 for (const [field, value] of Object.entries(defaults)) if (result[field] === undefined) result[field] = structuredClone(value)
77 return result
78}
79
80/**
81 * contextSchema — розгорнута модель контексту задачі обробника (G1): payloadMapping має дати всі її поля, крім тих,
82 * що мають значення за замовчуванням у моделі (contextDefaults).
83 */
84export function validateTaskConfig(config: any = {}, schema: any = {}, update = false, scopeSchemas: any = {}, contextSchema: any = null, contextDefaults: any = null) {
85 const errors = []
86 let taskValueSchema = schema
87
88 if (!update && config.itemsPath) {
89 const collectionSchema = readRuntimePath(
90 { data: schema, ...scopeSchemas },
91 config.itemsPath
92 )
93 if (!Array.isArray(collectionSchema)) {
94 errors.push('itemsPath must reference an array')
95 } else {
96 taskValueSchema = collectionSchema[0] || {}
97 }
98 // пакетна задача (P5, R-23 §11): data.* — елемент, parent.* — дані процесу навколо масиву
99 scopeSchemas = { ...scopeSchemas, parent: schema }
100 }
101
102 if (update) {
103 if (config.taskIdPath !== undefined && !String(config.taskIdPath).trim()) {
104 errors.push('taskIdPath cannot be empty')
105 }
106 if (config.complete !== undefined && typeof config.complete !== 'boolean') {
107 errors.push('complete must be boolean')
108 }
109 } else {
110 if (!['group', 'person'].includes(config.assigneeType)) {
111 errors.push('assigneeType must be group or person')
112 }
113 if (!String(config.assignee || '').trim()) errors.push('assignee is required')
114 if (!String(config.taskType || '').trim()) errors.push('taskType is required')
115 if (!String(config.title || '').trim()) errors.push('title is required')
116
117 errors.push(
118 ...validateMapping(
119 config.payloadMapping || { $copy: 'data' },
120 taskValueSchema,
121 scopeSchemas
122 ).errors
123 )
124 if (contextSchema) {
125 const defaultsSchema = contextDefaults ? literalType(contextDefaults) : null
126 const payloadSchema = withDefaults(deriveMappingSchema(config.payloadMapping || { $copy: 'data' }, taskValueSchema, scopeSchemas), defaultsSchema)
127 for (const error of validateWorkflowContract(payloadSchema, contextSchema).errors) {
128 errors.push(`payloadMapping → handler task context: ${error}`)
129 }
130 }
131 }
132
133 for (const [key, value] of Object.entries(config)) {
134 if (typeof value !== 'string') continue
135 const dataSchema = key === 'itemsPath' ? schema : taskValueSchema
136 const runtimeSchema = { data: dataSchema, ...scopeSchemas }
137 for (const path of value.match(pathPattern) || []) {
138 if (readRuntimePath(runtimeSchema, path) === undefined
139 && !(update && key === 'taskIdPath' && path === 'task.id')) {
140 errors.push(`${key}: field "${path}" is not available`)
141 }
142 }
143 }
144 return { valid: errors.length === 0, errors: [...new Set(errors)] }
145}
146