Added approval tree flow API

This commit is contained in:
romanskijdev 2026-07-16 10:12:11 +03:00
parent 8254447e7e
commit 0db4e20c93
3 changed files with 780 additions and 0 deletions

View File

@ -11,6 +11,7 @@ import (
authhandler "bitrix_balancer_api/rest_admin_service/handlers/auth"
dashboardhandler "bitrix_balancer_api/rest_admin_service/handlers/dashboard"
departmentshandler "bitrix_balancer_api/rest_admin_service/handlers/departments"
nodeshandler "bitrix_balancer_api/rest_admin_service/handlers/flow_nodes"
notificationshandler "bitrix_balancer_api/rest_admin_service/handlers/notification"
permissionshandler "bitrix_balancer_api/rest_admin_service/handlers/permission"
profilehandler "bitrix_balancer_api/rest_admin_service/handlers/profile"
@ -221,6 +222,7 @@ func registerRoutes(router chi.Router, ipc *typesm.InternalProviderControl) erro
{"approval-tasks", approvaltaskshandler.RegisterApprovalTasksRoutes},
{"dashboard", dashboardhandler.RegisterDashboardRoutes},
{"notifications", notificationshandler.RegisterNotificationRoutes},
{"flownodes", nodeshandler.RegisterFlowNodesRoutes},
}
// Регистрация всех маршрутов

View File

@ -0,0 +1,728 @@
package nodeshandler
import (
"bitrix_balancer_api/core/typescore"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"strconv"
"github.com/go-chi/chi/v5"
)
func (s *FlowNodesReg) GetFlowNodesByTopicIDHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) {
topicIDStr := chi.URLParam(r, "topic_id")
topicID, err := strconv.ParseUint(topicIDStr, 10, 64)
if err != nil {
return nil, errors.New("invalid topic_id")
}
ctx := r.Context()
// Проверяем, что тема существует
topic, err := s.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, topicID)
if err != nil {
return nil, err
}
if topic == nil {
return nil, errors.New("topic not found")
}
// Получаем все узлы для этой темы
nodes, _, err := s.ipc.Database.ApprovalFlowNode.GetApprovalFlowNodesListDB(ctx, typescore.ListDbOptions{
Filtering: &typescore.ApprovalFlowNode{TopicID: &topicID},
})
if err != nil {
return nil, err
}
// Строим дерево для ответа
tree := s.buildTreeFromNodes(nodes)
return &typescore.ApiResponseBase{
TotalCount: uint64(len(nodes)),
Data: tree,
}, nil
}
// ============================================================
// GET /{id} — Получить узел по ID
// ============================================================
func (s *FlowNodesReg) GetFlowNodeByIDHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) {
idStr := chi.URLParam(r, "id")
if idStr == "" {
return nil, errors.New("node id is required")
}
id, err := strconv.ParseUint(idStr, 10, 64)
if err != nil {
return nil, errors.New("invalid node id")
}
ctx := r.Context()
node, err := s.ipc.Database.ApprovalFlowNode.GetFlowNodeByIDDB(ctx, id)
if err != nil {
return nil, err
}
if node == nil {
return nil, errors.New("node not found")
}
return node, nil
}
// ============================================================
// POST / — Создать узел
// ============================================================
func (s *FlowNodesReg) CreateFlowNodeHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) {
defer r.Body.Close()
body, err := io.ReadAll(r.Body)
if err != nil {
return nil, err
}
var req typescore.ApprovalFlowNode
if err := json.Unmarshal(body, &req); err != nil {
return nil, errors.New("invalid request body")
}
// Валидация обязательных полей
if req.TopicID == nil {
return nil, errors.New("topic_id is required")
}
if req.Key == nil || *req.Key == "" {
return nil, errors.New("key is required")
}
if req.Label == nil || *req.Label == "" {
return nil, errors.New("label is required")
}
ctx := r.Context()
// Проверяем, что тема существует
topic, err := s.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *req.TopicID)
if err != nil {
return nil, err
}
if topic == nil {
return nil, errors.New("topic not found")
}
// Проверяем, что родительский узел существует (если задан)
if req.ParentID != nil {
parent, err := s.ipc.Database.ApprovalFlowNode.GetFlowNodeByIDDB(ctx, *req.ParentID)
if err != nil {
return nil, err
}
if parent == nil {
return nil, errors.New("parent node not found")
}
// Проверяем, что родитель принадлежит той же теме
if parent.TopicID == nil || *parent.TopicID != *req.TopicID {
return nil, errors.New("parent node belongs to a different topic")
}
}
// Проверяем уникальность ключа в рамках темы
existing, _, err := s.ipc.Database.ApprovalFlowNode.GetApprovalFlowNodesListDB(ctx, typescore.ListDbOptions{
Filtering: &typescore.ApprovalFlowNode{
TopicID: req.TopicID,
Key: req.Key,
},
})
if err != nil {
return nil, err
}
if len(existing) > 0 {
return nil, fmt.Errorf("node with key '%s' already exists in this topic", *req.Key)
}
// Устанавливаем значения по умолчанию
if req.IsInput == nil {
v := false
req.IsInput = &v
}
if req.IsMultiSelect == nil {
v := false
req.IsMultiSelect = &v
}
if req.SortOrder == nil {
v := 0
req.SortOrder = &v
}
created, _, err := s.ipc.Database.ApprovalFlowNode.CreateApprovalFlowNodeDB(ctx, nil, &req, true)
if err != nil {
return nil, err
}
return created, nil
}
// ============================================================
// PUT / — Обновить узел
// ============================================================
func (s *FlowNodesReg) UpdateFlowNodeHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) {
defer r.Body.Close()
body, err := io.ReadAll(r.Body)
if err != nil {
return nil, err
}
var req typescore.ApprovalFlowNode
if err := json.Unmarshal(body, &req); err != nil {
return nil, errors.New("invalid request body")
}
if req.ID == nil {
return nil, errors.New("id is required")
}
ctx := r.Context()
// Проверяем, что узел существует
existing, err := s.ipc.Database.ApprovalFlowNode.GetFlowNodeByIDDB(ctx, *req.ID)
if err != nil {
return nil, err
}
if existing == nil {
return nil, errors.New("node not found")
}
// Если меняется parent_id — проверяем корректность
if req.ParentID != nil && (existing.ParentID == nil || *existing.ParentID != *req.ParentID) {
parent, err := s.ipc.Database.ApprovalFlowNode.GetFlowNodeByIDDB(ctx, *req.ParentID)
if err != nil {
return nil, err
}
if parent == nil {
return nil, errors.New("parent node not found")
}
// Проверяем, что родитель принадлежит той же теме
if parent.TopicID == nil || existing.TopicID == nil || *parent.TopicID != *existing.TopicID {
return nil, errors.New("parent node belongs to a different topic")
}
// Проверяем, что не пытаемся сделать узел ребёнком самого себя или своего потомка
if err := s.checkNoCyclicReference(ctx, *req.ID, *req.ParentID); err != nil {
return nil, err
}
}
// Если меняется key — проверяем уникальность
if req.Key != nil && *req.Key != "" {
if existing.Key == nil || *existing.Key != *req.Key {
topicID := existing.TopicID
if req.TopicID != nil {
topicID = req.TopicID
}
existingNodes, _, err := s.ipc.Database.ApprovalFlowNode.GetApprovalFlowNodesListDB(ctx, typescore.ListDbOptions{
Filtering: &typescore.ApprovalFlowNode{
TopicID: topicID,
Key: req.Key,
},
})
if err != nil {
return nil, err
}
if len(existingNodes) > 0 {
return nil, fmt.Errorf("node with key '%s' already exists in this topic", *req.Key)
}
}
}
updated, _, err := s.ipc.Database.ApprovalFlowNode.UpdateApprovalFlowNodeDB(ctx, nil, &req, true)
if err != nil {
return nil, err
}
return updated, nil
}
// ============================================================
// DELETE / — Удалить узел (и всех детей каскадно через FK)
// ============================================================
func (s *FlowNodesReg) DeleteFlowNodeHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) {
defer r.Body.Close()
body, err := io.ReadAll(r.Body)
if err != nil {
return nil, err
}
var req typescore.ApprovalFlowNode
if err := json.Unmarshal(body, &req); err != nil {
return nil, errors.New("invalid request body")
}
if req.ID == nil {
return nil, errors.New("id is required")
}
ctx := r.Context()
// Проверяем, что узел существует
existing, err := s.ipc.Database.ApprovalFlowNode.GetFlowNodeByIDDB(ctx, *req.ID)
if err != nil {
return nil, err
}
if existing == nil {
return nil, errors.New("node not found")
}
err = s.ipc.Database.ApprovalFlowNode.DeleteApprovalFlowNodeDB(ctx, &req)
if err != nil {
return nil, err
}
return true, nil
}
// ============================================================
// POST /topic/{topic_id}/tree — Сохранить всё дерево целиком
// ============================================================
func (s *FlowNodesReg) SaveEntireTreeHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) {
topicIDStr := chi.URLParam(r, "topic_id")
topicID, err := strconv.ParseUint(topicIDStr, 10, 64)
if err != nil {
return nil, errors.New("invalid topic_id")
}
defer r.Body.Close()
body, err := io.ReadAll(r.Body)
if err != nil {
return nil, err
}
var req struct {
Nodes []*typescore.ApprovalFlowNode `json:"nodes"`
}
if err := json.Unmarshal(body, &req); err != nil {
return nil, errors.New("invalid request body")
}
ctx := r.Context()
// Проверяем, что тема существует
topic, err := s.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, topicID)
if err != nil {
return nil, err
}
if topic == nil {
return nil, errors.New("topic not found")
}
// Удаляем старое дерево
if err := s.ipc.Database.ApprovalFlowNode.DeleteFlowNodesByTopicIDDB(ctx, topicID); err != nil {
return nil, err
}
// Сохраняем новое дерево (рекурсивно)
if err := s.saveNodesRecursive(ctx, req.Nodes, topicID, nil); err != nil {
return nil, err
}
return true, nil
}
// ============================================================
// POST /{id}/move — Переместить узел (изменить родителя и/или порядок)
// ============================================================
func (s *FlowNodesReg) MoveFlowNodeHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) {
idStr := chi.URLParam(r, "id")
id, err := strconv.ParseUint(idStr, 10, 64)
if err != nil {
return nil, errors.New("invalid node id")
}
defer r.Body.Close()
body, err := io.ReadAll(r.Body)
if err != nil {
return nil, err
}
var req struct {
NewParentID *uint64 `json:"new_parent_id"` // nil — не менять родителя
NewSortOrder *int `json:"new_sort_order"` // nil — не менять порядок
}
if err := json.Unmarshal(body, &req); err != nil {
return nil, errors.New("invalid request body")
}
ctx := r.Context()
// Получаем текущий узел
node, err := s.ipc.Database.ApprovalFlowNode.GetFlowNodeByIDDB(ctx, id)
if err != nil {
return nil, err
}
if node == nil {
return nil, errors.New("node not found")
}
// Если меняем родителя — проверяем корректность
if req.NewParentID != nil {
// Нельзя сделать узел родителем самого себя
if *req.NewParentID == id {
return nil, errors.New("node cannot be its own parent")
}
parent, err := s.ipc.Database.ApprovalFlowNode.GetFlowNodeByIDDB(ctx, *req.NewParentID)
if err != nil {
return nil, err
}
if parent == nil {
return nil, errors.New("new parent node not found")
}
// Родитель должен принадлежать той же теме
if parent.TopicID == nil || node.TopicID == nil || *parent.TopicID != *node.TopicID {
return nil, errors.New("new parent belongs to a different topic")
}
// Проверяем циклические ссылки
if err := s.checkNoCyclicReference(ctx, id, *req.NewParentID); err != nil {
return nil, err
}
}
// Формируем объект для обновления
update := &typescore.ApprovalFlowNode{ID: &id}
if req.NewParentID != nil {
update.ParentID = req.NewParentID
}
if req.NewSortOrder != nil {
update.SortOrder = req.NewSortOrder
}
updated, _, err := s.ipc.Database.ApprovalFlowNode.UpdateApprovalFlowNodeDB(ctx, nil, update, true)
if err != nil {
return nil, err
}
return updated, nil
}
// ============================================================
// POST /{id}/duplicate — Дублировать узел со всеми детьми
// ============================================================
func (s *FlowNodesReg) DuplicateFlowNodeHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) {
idStr := chi.URLParam(r, "id")
id, err := strconv.ParseUint(idStr, 10, 64)
if err != nil {
return nil, errors.New("invalid node id")
}
ctx := r.Context()
// Получаем исходный узел
original, err := s.ipc.Database.ApprovalFlowNode.GetFlowNodeByIDDB(ctx, id)
if err != nil {
return nil, err
}
if original == nil {
return nil, errors.New("node not found")
}
// Получаем всех детей исходного узла (для рекурсивного дублирования)
allNodes, _, err := s.ipc.Database.ApprovalFlowNode.GetApprovalFlowNodesListDB(ctx, typescore.ListDbOptions{
Filtering: &typescore.ApprovalFlowNode{TopicID: original.TopicID},
})
if err != nil {
return nil, err
}
// Находим всех потомков (BFS)
descendants := s.collectDescendants(id, allNodes)
// Генерируем уникальный суффикс для ключей
suffix := s.generateCopySuffix(ctx, original)
// Дублируем корневой узел
newKey := *original.Key + suffix
newLabel := *original.Label + " (копия)"
copy := &typescore.ApprovalFlowNode{
TopicID: original.TopicID,
ParentID: original.ParentID, // остаётся на том же уровне
Key: &newKey,
Label: &newLabel,
DataKey: original.DataKey,
DataValue: original.DataValue,
IsInput: original.IsInput,
InputKey: original.InputKey,
InputHint: original.InputHint,
IsMultiSelect: original.IsMultiSelect,
MultiSelectKey: original.MultiSelectKey,
MultiSelectValue: original.MultiSelectValue,
TopicCode: original.TopicCode,
SortOrder: original.SortOrder,
}
createdCopy, _, err := s.ipc.Database.ApprovalFlowNode.CreateApprovalFlowNodeDB(ctx, nil, copy, true)
if err != nil {
return nil, err
}
// Дублируем потомков рекурсивно
if len(descendants) > 0 {
// Строим маппинг старых ID → новые ID
idMapping := map[uint64]uint64{
id: *createdCopy.ID,
}
// Сортируем потомков по уровню вложенности (чтобы родители создавались раньше детей)
sortedDescendants := s.sortByDepth(id, descendants, allNodes)
for _, desc := range sortedDescendants {
descKey := *desc.Key + suffix
descCopy := &typescore.ApprovalFlowNode{
TopicID: desc.TopicID,
Key: &descKey,
Label: desc.Label,
DataKey: desc.DataKey,
DataValue: desc.DataValue,
IsInput: desc.IsInput,
InputKey: desc.InputKey,
InputHint: desc.InputHint,
IsMultiSelect: desc.IsMultiSelect,
MultiSelectKey: desc.MultiSelectKey,
MultiSelectValue: desc.MultiSelectValue,
TopicCode: desc.TopicCode,
SortOrder: desc.SortOrder,
}
// Устанавливаем новый parent_id
if desc.ParentID != nil {
if newParentID, ok := idMapping[*desc.ParentID]; ok {
descCopy.ParentID = &newParentID
}
}
createdDesc, _, err := s.ipc.Database.ApprovalFlowNode.CreateApprovalFlowNodeDB(ctx, nil, descCopy, true)
if err != nil {
return nil, err
}
if desc.ID != nil && createdDesc != nil && createdDesc.ID != nil {
idMapping[*desc.ID] = *createdDesc.ID
}
}
}
return createdCopy, nil
}
// ============================================================
// Вспомогательные методы
// ============================================================
// buildTreeFromNodes строит иерархическое дерево из плоского списка узлов
func (s *FlowNodesReg) buildTreeFromNodes(nodes []*typescore.ApprovalFlowNode) []*typescore.ApprovalFlowNode {
nodeMap := make(map[uint64]*typescore.ApprovalFlowNode)
var roots []*typescore.ApprovalFlowNode
for _, n := range nodes {
if n.ID != nil {
nodeMap[*n.ID] = n
}
}
for _, n := range nodes {
if n.ParentID == nil {
roots = append(roots, n)
} else if parent, ok := nodeMap[*n.ParentID]; ok {
parent.Children = append(parent.Children, n)
}
}
return roots
}
// saveNodesRecursive рекурсивно сохраняет узлы дерева в БД
func (s *FlowNodesReg) saveNodesRecursive(ctx context.Context, nodes []*typescore.ApprovalFlowNode, topicID uint64, parentID *uint64) error {
for i, node := range nodes {
node.TopicID = &topicID
node.ParentID = parentID
sortOrder := i
node.SortOrder = &sortOrder
created, _, err := s.ipc.Database.ApprovalFlowNode.CreateApprovalFlowNodeDB(ctx, nil, node, true)
if err != nil {
return err
}
if len(node.Children) > 0 {
if err := s.saveNodesRecursive(ctx, node.Children, topicID, created.ID); err != nil {
return err
}
}
}
return nil
}
// checkNoCyclicReference проверяет, что при перемещении узла не создаётся цикл
// (т.е. узел не становится своим же потомком)
func (s *FlowNodesReg) checkNoCyclicReference(ctx context.Context, nodeID, newParentID uint64) error {
// Идём вверх по родителям от newParentID — если встретим nodeID, значит цикл
currentID := newParentID
visited := make(map[uint64]bool)
for currentID != 0 {
if visited[currentID] {
break // защита от уже существующих циклов
}
visited[currentID] = true
if currentID == nodeID {
return errors.New("cyclic reference detected: cannot move node under its own descendant")
}
parent, err := s.ipc.Database.ApprovalFlowNode.GetFlowNodeByIDDB(ctx, currentID)
if err != nil || parent == nil {
break
}
if parent.ParentID == nil {
break
}
currentID = *parent.ParentID
}
return nil
}
// collectDescendants собирает всех потомков узла (BFS)
func (s *FlowNodesReg) collectDescendants(rootID uint64, allNodes []*typescore.ApprovalFlowNode) []*typescore.ApprovalFlowNode {
// Строим map parent_id → children
childrenMap := make(map[uint64][]*typescore.ApprovalFlowNode)
for _, n := range allNodes {
if n.ParentID != nil {
childrenMap[*n.ParentID] = append(childrenMap[*n.ParentID], n)
}
}
var result []*typescore.ApprovalFlowNode
queue := []uint64{rootID}
for len(queue) > 0 {
current := queue[0]
queue = queue[1:]
for _, child := range childrenMap[current] {
result = append(result, child)
if child.ID != nil {
queue = append(queue, *child.ID)
}
}
}
return result
}
// sortByDepth сортирует потомков по глубине вложенности (ближайшие к корню — первые)
func (s *FlowNodesReg) sortByDepth(rootID uint64, descendants, allNodes []*typescore.ApprovalFlowNode) []*typescore.ApprovalFlowNode {
// Считаем глубину каждого узла
depthMap := make(map[uint64]int)
depthMap[rootID] = 0
// Строим map id → node
nodeMap := make(map[uint64]*typescore.ApprovalFlowNode)
for _, n := range allNodes {
if n.ID != nil {
nodeMap[*n.ID] = n
}
}
// Для каждого потомка считаем глубину
for _, d := range descendants {
if d.ID == nil {
continue
}
depth := 0
currentID := d.ID
for {
node, ok := nodeMap[*currentID]
if !ok || node.ParentID == nil {
break
}
depth++
currentID = node.ParentID
if *currentID == rootID {
break
}
}
depthMap[*d.ID] = depth
}
// Простая сортировка по глубине (bubble sort для небольшого N)
sorted := make([]*typescore.ApprovalFlowNode, len(descendants))
copy(sorted, descendants)
for i := 0; i < len(sorted); i++ {
for j := i + 1; j < len(sorted); j++ {
depthI := 0
depthJ := 0
if sorted[i].ID != nil {
depthI = depthMap[*sorted[i].ID]
}
if sorted[j].ID != nil {
depthJ = depthMap[*sorted[j].ID]
}
if depthJ < depthI {
sorted[i], sorted[j] = sorted[j], sorted[i]
}
}
}
return sorted
}
// generateCopySuffix генерирует уникальный суффикс для дублированного ключа
func (s *FlowNodesReg) generateCopySuffix(ctx context.Context, original *typescore.ApprovalFlowNode) string {
if original.TopicID == nil || original.Key == nil {
return "_copy"
}
// Ищем существующие копии
existing, _, err := s.ipc.Database.ApprovalFlowNode.GetApprovalFlowNodesListDB(ctx, typescore.ListDbOptions{
Filtering: &typescore.ApprovalFlowNode{TopicID: original.TopicID},
})
if err != nil {
return "_copy"
}
baseKey := *original.Key
maxNum := 0
for _, n := range existing {
if n.Key == nil {
continue
}
key := *n.Key
// Проверяем паттерн baseKey_copy_N
if len(key) > len(baseKey) && key[:len(baseKey)] == baseKey {
suffix := key[len(baseKey):]
if len(suffix) >= 6 && suffix[:5] == "_copy" {
if len(suffix) > 5 {
numStr := suffix[6:] // после "_copy_"
if num, err := strconv.Atoi(numStr); err == nil && num > maxNum {
maxNum = num
}
} else if suffix == "_copy" {
if maxNum < 1 {
maxNum = 1
}
}
}
}
}
return fmt.Sprintf("_copy_%d", maxNum+1)
}

View File

@ -0,0 +1,50 @@
package nodeshandler
import (
"bitrix_balancer_api/rest_admin_service/handlers"
typesm "bitrix_balancer_api/rest_admin_service/types"
"net/http"
"github.com/go-chi/chi/v5"
)
type FlowNodesReg struct {
ipc *typesm.InternalProviderControl
}
// RegisterFlowNodesRoutes регистрирует маршруты для управления узлами дерева
func RegisterFlowNodesRoutes(
r chi.Router,
ipc *typesm.InternalProviderControl,
) error {
s := &FlowNodesReg{
ipc: ipc,
}
r.Route("/api/flow-nodes", func(r chi.Router) {
r.Use(handlers.AccessCodeVerifier(ipc.Config))
r.Use(handlers.JWTVerifier(ipc.Config, ipc.Database.Admin, ipc.RedisClient))
// Получить дерево узлов для темы
handlers.RegisterRoute(r, http.MethodGet, "/topic/{topic_id}", s.GetFlowNodesByTopicIDHandler)
// CRUD операции с узлами
handlers.RegisterRoute(r, http.MethodPost, "/", s.CreateFlowNodeHandler)
handlers.RegisterRoute(r, http.MethodPut, "/", s.UpdateFlowNodeHandler)
handlers.RegisterRoute(r, http.MethodDelete, "/", s.DeleteFlowNodeHandler)
// Сохранить всё дерево целиком (для UI конструктора)
handlers.RegisterRoute(r, http.MethodPost, "/topic/{topic_id}/tree", s.SaveEntireTreeHandler)
// Переместить узел (изменить порядок или родителя)
handlers.RegisterRoute(r, http.MethodPost, "/{id}/move", s.MoveFlowNodeHandler)
// Дублировать узел с детьми
handlers.RegisterRoute(r, http.MethodPost, "/{id}/duplicate", s.DuplicateFlowNodeHandler)
// Получить узел по ID
handlers.RegisterRoute(r, http.MethodGet, "/{id}", s.GetFlowNodeByIDHandler)
})
return nil
}