stages.ts
TypeScript · 119 рядків
1/**
2 * Етапи борду (R-30.12, R-30.2): усі процеси — на одному борді, етап — область борду.
3 *
4 * - Етап — прямокутник у `workflow.settings.stages`: { id, name, x, y, width, height, color?, taskContextModelId? }.
5 * - Блок належить етапу, якщо центр блока лежить в області (вкладені — найменша область). Окремого поля в блоці
6 * немає: менеджер перетягує блок в область — і блок у етапі; рушій, перевірка й редактор рахують однаково.
7 * - Задача, створена блоком TASK з `handlerStageId`, обробляється TASK-подіями САМЕ цього етапу цього борду
8 * (закріплена версія борду — як для окремого workflow-обробника, R-12.3).
9 * - Модель контексту задачі — властивість етапу (замість властивості окремого workflow).
10 * - Передача між етапами (TASK → етап) видима на карті: з етапу блока TASK до етапу-обробника, з сутністю задачі
11 * (тара — R-30.3: етапи з'єднує тара, а не деталь).
12 */
13
14export const NODE_W = 190
15export const NODE_BASE_H = 92
16export const PORT_GAP = 28
17
18export function nodeHeight(node: any) {
19 return NODE_BASE_H + Math.max(0, Math.max(node?.inputs?.length || 0, node?.outputs?.length || 0) - 2) * PORT_GAP
20}
21
22export function boardStages(workflow: any): any[] {
23 const stages = workflow?.settings?.stages
24 return Array.isArray(stages) ? stages : []
25}
26
27export function stageById(workflow: any, id: any) {
28 const value = String(id || '').trim()
29 return value ? boardStages(workflow).find(stage => stage.id === value) || null : null
30}
31
32export function pointInStage(stage: any, x: number, y: number) {
33 return x >= stage.x && x <= stage.x + stage.width && y >= stage.y && y <= stage.y + stage.height
34}
35
36/** Етап, у якому лежить центр блока; при вкладених областях — найменша. */
37export function stageOf(workflow: any, node: any) {
38 if (!node) return null
39 const cx = Number(node.x) + NODE_W / 2
40 const cy = Number(node.y) + nodeHeight(node) / 2
41 let found = null
42 for (const stage of boardStages(workflow)) {
43 if (!pointInStage(stage, cx, cy)) continue
44 if (!found || stage.width * stage.height < found.width * found.height) found = stage
45 }
46 return found
47}
48
49export function stageNodes(workflow: any, stageId: string) {
50 return (workflow?.nodes || []).filter(node => stageOf(workflow, node)?.id === stageId)
51}
52
53/** Модель контексту задачі етапу; якщо етап її не задає — модель борду (settings.taskContextModelId). */
54export function stageContextModelId(workflow: any, stage: any) {
55 return stage?.taskContextModelId || workflow?.settings?.taskContextModelId || null
56}
57
58/** Передачі між етапами: блок TASK → етап-обробник цього борду. */
59export function stageHandoffs(workflow: any) {
60 const result = []
61 for (const node of workflow?.nodes || []) {
62 if (node.type !== 'TASK' || !node.config?.handlerStageId) continue
63 const to = stageById(workflow, node.config.handlerStageId)
64 if (!to) continue
65 result.push({
66 nodeId: node.id,
67 from: stageOf(workflow, node)?.id || null,
68 to: to.id,
69 label: String(node.config?.entityType || '').trim() || node.name,
70 title: node.name,
71 })
72 }
73 return result
74}
75
76/** Перевірка етапів: повідомлення для validation.ts (nodeId — щоб редактор підсвітив блок). */
77export function validateStages(workflow: any, models: any[] = []) {
78 const issues: { message: string; nodeId?: string; severity?: 'warning' }[] = []
79 const stages = boardStages(workflow)
80 const ids = new Set()
81 for (const stage of stages) {
82 const label = `Stage ${stage?.name || stage?.id || '?'}`
83 if (!String(stage?.id || '').trim()) issues.push({ message: `${label}: id is required` })
84 else if (ids.has(stage.id)) issues.push({ message: `${label}: duplicate stage id ${stage.id}` })
85 ids.add(stage?.id)
86 if (!String(stage?.name || '').trim()) issues.push({ message: `${label}: name is required` })
87 for (const key of ['x', 'y', 'width', 'height']) {
88 if (!Number.isFinite(Number(stage?.[key]))) issues.push({ message: `${label}: ${key} must be a number` })
89 }
90 if (Number(stage?.width) <= 0 || Number(stage?.height) <= 0) issues.push({ message: `${label}: size must be positive` })
91 if (stage?.taskContextModelId && !models.some(model => model.id === stage.taskContextModelId)) {
92 issues.push({ message: `${label}: task context model not found` })
93 }
94 }
95
96 const entries = new Map()
97 for (const node of workflow?.nodes || []) {
98 if (node.type === 'EVENT' && node.config?.activation === 'TASK') {
99 const stage = stageOf(workflow, node)
100 if (stage) entries.set(stage.id, (entries.get(stage.id) || 0) + 1)
101 }
102 }
103 for (const node of workflow?.nodes || []) {
104 if (node.type !== 'TASK' || !node.config?.handlerStageId) continue
105 const stage = stageById(workflow, node.config.handlerStageId)
106 if (!stage) {
107 issues.push({ message: `${node.name}: handler stage not found`, nodeId: node.id })
108 continue
109 }
110 if (String(node.config?.handlerWorkflowId || '').trim()) {
111 issues.push({ message: `${node.name}: set either a handler stage or a handler workflow, not both`, nodeId: node.id })
112 }
113 if (!entries.get(stage.id)) {
114 issues.push({ message: `${node.name}: stage «${stage.name}» has no TASK event — its tasks cannot receive events`, nodeId: node.id, severity: 'warning' })
115 }
116 }
117 return issues
118}
119