fix-permissions #69

Merged
romanskijdev merged 2 commits from fix-permissions into main 2026-07-16 10:43:09 +03:00
3 changed files with 73 additions and 66 deletions

View File

@ -25,7 +25,7 @@ type ApprovalFlowNodeDBI interface {
CreateApprovalFlowNodeDB(ctx context.Context, tx pgx.Tx, node *typescore.ApprovalFlowNode, returnObj ...bool) (*typescore.ApprovalFlowNode, pgx.Tx, error)
UpdateApprovalFlowNodeDB(ctx context.Context, tx pgx.Tx, node *typescore.ApprovalFlowNode, returnObj ...bool) (*typescore.ApprovalFlowNode, pgx.Tx, error)
DeleteApprovalFlowNodeDB(ctx context.Context, node *typescore.ApprovalFlowNode) error
DeleteFlowNodesByTopicIDDB(ctx context.Context, topicID uint64) error
DeleteFlowNodesByCategoryIDDB(ctx context.Context, catID uint64) error
GetFlowNodeByIDDB(ctx context.Context, id uint64) (*typescore.ApprovalFlowNode, error)
}
@ -148,10 +148,10 @@ func (u *ApprovalFlowNodeDB) DeleteApprovalFlowNodeDB(ctx context.Context, node
return err
}
func (u *ApprovalFlowNodeDB) DeleteFlowNodesByTopicIDDB(ctx context.Context, topicID uint64) error {
func (u *ApprovalFlowNodeDB) DeleteFlowNodesByCategoryIDDB(ctx context.Context, catID uint64) error {
query, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
Delete(dbcoretablenames.TableNameApprovalFlowNodes.ToString()).
Where(squirrel.Eq{"topic_id": topicID}).
Where(squirrel.Eq{"category_id": catID}).
ToSql()
if err != nil {
return err

View File

@ -13,27 +13,31 @@ import (
"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)
// ============================================================
// GET /category/{category_id} — Получить дерево узлов категории
// ============================================================
func (s *FlowNodesReg) GetFlowNodesByCategoryIDHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) {
categoryIDStr := chi.URLParam(r, "category_id")
categoryID, err := strconv.ParseUint(categoryIDStr, 10, 64)
if err != nil {
return nil, errors.New("invalid topic_id")
return nil, errors.New("invalid category_id")
}
ctx := r.Context()
// Проверяем, что тема существует
topic, err := s.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, topicID)
// Проверяем, что категория существует
category, err := s.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, categoryID)
if err != nil {
return nil, err
}
if topic == nil {
return nil, errors.New("topic not found")
if category == nil {
return nil, errors.New("category not found")
}
// Получаем все узлы для этой темы
// Получаем все узлы для этой категории
nodes, _, err := s.ipc.Database.ApprovalFlowNode.GetApprovalFlowNodesListDB(ctx, typescore.ListDbOptions{
Filtering: &typescore.ApprovalFlowNode{TopicID: &topicID},
Filtering: &typescore.ApprovalFlowNode{CategoryID: &categoryID},
})
if err != nil {
return nil, err
@ -92,8 +96,8 @@ func (s *FlowNodesReg) CreateFlowNodeHandler(w http.ResponseWriter, r *http.Requ
}
// Валидация обязательных полей
if req.TopicID == nil {
return nil, errors.New("topic_id is required")
if req.CategoryID == nil {
return nil, errors.New("category_id is required")
}
if req.Key == nil || *req.Key == "" {
return nil, errors.New("key is required")
@ -104,13 +108,13 @@ func (s *FlowNodesReg) CreateFlowNodeHandler(w http.ResponseWriter, r *http.Requ
ctx := r.Context()
// Проверяем, что тема существует
topic, err := s.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *req.TopicID)
// Проверяем, что категория существует
category, err := s.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, *req.CategoryID)
if err != nil {
return nil, err
}
if topic == nil {
return nil, errors.New("topic not found")
if category == nil {
return nil, errors.New("category not found")
}
// Проверяем, что родительский узел существует (если задан)
@ -122,24 +126,24 @@ func (s *FlowNodesReg) CreateFlowNodeHandler(w http.ResponseWriter, r *http.Requ
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")
// Проверяем, что родитель принадлежит той же категории
if parent.CategoryID == nil || *parent.CategoryID != *req.CategoryID {
return nil, errors.New("parent node belongs to a different category")
}
}
// Проверяем уникальность ключа в рамках темы
// Проверяем уникальность ключа в рамках категории
existing, _, err := s.ipc.Database.ApprovalFlowNode.GetApprovalFlowNodesListDB(ctx, typescore.ListDbOptions{
Filtering: &typescore.ApprovalFlowNode{
TopicID: req.TopicID,
Key: req.Key,
CategoryID: req.CategoryID,
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)
return nil, fmt.Errorf("node with key '%s' already exists in this category", *req.Key)
}
// Устанавливаем значения по умолчанию
@ -156,6 +160,11 @@ func (s *FlowNodesReg) CreateFlowNodeHandler(w http.ResponseWriter, r *http.Requ
req.SortOrder = &v
}
// Примечание: req.MessageTemplate / req.CodeTemplate, если переданы,
// сохранятся автоматически — они являются обычными полями структуры
// ApprovalFlowNode и не требуют отдельной обработки. Задаются, как правило,
// на терминальных узлах, где также заполнен TopicCode.
created, _, err := s.ipc.Database.ApprovalFlowNode.CreateApprovalFlowNodeDB(ctx, nil, &req, true)
if err != nil {
return nil, err
@ -204,9 +213,9 @@ func (s *FlowNodesReg) UpdateFlowNodeHandler(w http.ResponseWriter, r *http.Requ
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 parent.CategoryID == nil || existing.CategoryID == nil || *parent.CategoryID != *existing.CategoryID {
return nil, errors.New("parent node belongs to a different category")
}
// Проверяем, что не пытаемся сделать узел ребёнком самого себя или своего потомка
if err := s.checkNoCyclicReference(ctx, *req.ID, *req.ParentID); err != nil {
@ -214,24 +223,24 @@ func (s *FlowNodesReg) UpdateFlowNodeHandler(w http.ResponseWriter, r *http.Requ
}
}
// Если меняется key — проверяем уникальность
// Если меняется 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
categoryID := existing.CategoryID
if req.CategoryID != nil {
categoryID = req.CategoryID
}
existingNodes, _, err := s.ipc.Database.ApprovalFlowNode.GetApprovalFlowNodesListDB(ctx, typescore.ListDbOptions{
Filtering: &typescore.ApprovalFlowNode{
TopicID: topicID,
Key: req.Key,
CategoryID: categoryID,
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)
return nil, fmt.Errorf("node with key '%s' already exists in this category", *req.Key)
}
}
}
@ -284,14 +293,14 @@ func (s *FlowNodesReg) DeleteFlowNodeHandler(w http.ResponseWriter, r *http.Requ
}
// ============================================================
// POST /topic/{topic_id}/tree — Сохранить всё дерево целиком
// POST /category/{category_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)
categoryIDStr := chi.URLParam(r, "category_id")
categoryID, err := strconv.ParseUint(categoryIDStr, 10, 64)
if err != nil {
return nil, errors.New("invalid topic_id")
return nil, errors.New("invalid category_id")
}
defer r.Body.Close()
@ -309,22 +318,22 @@ func (s *FlowNodesReg) SaveEntireTreeHandler(w http.ResponseWriter, r *http.Requ
ctx := r.Context()
// Проверяем, что тема существует
topic, err := s.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, topicID)
// Проверяем, что категория существует
category, err := s.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, categoryID)
if err != nil {
return nil, err
}
if topic == nil {
return nil, errors.New("topic not found")
if category == nil {
return nil, errors.New("category not found")
}
// Удаляем старое дерево
if err := s.ipc.Database.ApprovalFlowNode.DeleteFlowNodesByTopicIDDB(ctx, topicID); err != nil {
if err := s.ipc.Database.ApprovalFlowNode.DeleteFlowNodesByCategoryIDDB(ctx, categoryID); err != nil {
return nil, err
}
// Сохраняем новое дерево (рекурсивно)
if err := s.saveNodesRecursive(ctx, req.Nodes, topicID, nil); err != nil {
if err := s.saveNodesRecursive(ctx, req.Nodes, categoryID, nil); err != nil {
return nil, err
}
@ -382,9 +391,9 @@ func (s *FlowNodesReg) MoveFlowNodeHandler(w http.ResponseWriter, r *http.Reques
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 parent.CategoryID == nil || node.CategoryID == nil || *parent.CategoryID != *node.CategoryID {
return nil, errors.New("new parent belongs to a different category")
}
// Проверяем циклические ссылки
@ -432,9 +441,9 @@ func (s *FlowNodesReg) DuplicateFlowNodeHandler(w http.ResponseWriter, r *http.R
return nil, errors.New("node not found")
}
// Получаем всех детей исходного узла (для рекурсивного дублирования)
// Получаем все узлы категории исходного узла (для рекурсивного дублирования)
allNodes, _, err := s.ipc.Database.ApprovalFlowNode.GetApprovalFlowNodesListDB(ctx, typescore.ListDbOptions{
Filtering: &typescore.ApprovalFlowNode{TopicID: original.TopicID},
Filtering: &typescore.ApprovalFlowNode{CategoryID: original.CategoryID},
})
if err != nil {
return nil, err
@ -450,7 +459,8 @@ func (s *FlowNodesReg) DuplicateFlowNodeHandler(w http.ResponseWriter, r *http.R
newKey := *original.Key + suffix
newLabel := *original.Label + " (копия)"
copy := &typescore.ApprovalFlowNode{
copyNode := &typescore.ApprovalFlowNode{
CategoryID: original.CategoryID,
TopicID: original.TopicID,
ParentID: original.ParentID, // остаётся на том же уровне
Key: &newKey,
@ -465,9 +475,11 @@ func (s *FlowNodesReg) DuplicateFlowNodeHandler(w http.ResponseWriter, r *http.R
MultiSelectValue: original.MultiSelectValue,
TopicCode: original.TopicCode,
SortOrder: original.SortOrder,
MessageTemplate: original.MessageTemplate,
CodeTemplate: original.CodeTemplate,
}
createdCopy, _, err := s.ipc.Database.ApprovalFlowNode.CreateApprovalFlowNodeDB(ctx, nil, copy, true)
createdCopy, _, err := s.ipc.Database.ApprovalFlowNode.CreateApprovalFlowNodeDB(ctx, nil, copyNode, true)
if err != nil {
return nil, err
}
@ -485,6 +497,7 @@ func (s *FlowNodesReg) DuplicateFlowNodeHandler(w http.ResponseWriter, r *http.R
for _, desc := range sortedDescendants {
descKey := *desc.Key + suffix
descCopy := &typescore.ApprovalFlowNode{
CategoryID: desc.CategoryID,
TopicID: desc.TopicID,
Key: &descKey,
Label: desc.Label,
@ -498,6 +511,8 @@ func (s *FlowNodesReg) DuplicateFlowNodeHandler(w http.ResponseWriter, r *http.R
MultiSelectValue: desc.MultiSelectValue,
TopicCode: desc.TopicCode,
SortOrder: desc.SortOrder,
MessageTemplate: desc.MessageTemplate,
CodeTemplate: desc.CodeTemplate,
}
// Устанавливаем новый parent_id
@ -547,9 +562,9 @@ func (s *FlowNodesReg) buildTreeFromNodes(nodes []*typescore.ApprovalFlowNode) [
}
// saveNodesRecursive рекурсивно сохраняет узлы дерева в БД
func (s *FlowNodesReg) saveNodesRecursive(ctx context.Context, nodes []*typescore.ApprovalFlowNode, topicID uint64, parentID *uint64) error {
func (s *FlowNodesReg) saveNodesRecursive(ctx context.Context, nodes []*typescore.ApprovalFlowNode, categoryID uint64, parentID *uint64) error {
for i, node := range nodes {
node.TopicID = &topicID
node.CategoryID = &categoryID
node.ParentID = parentID
sortOrder := i
@ -561,7 +576,7 @@ func (s *FlowNodesReg) saveNodesRecursive(ctx context.Context, nodes []*typescor
}
if len(node.Children) > 0 {
if err := s.saveNodesRecursive(ctx, node.Children, topicID, created.ID); err != nil {
if err := s.saveNodesRecursive(ctx, node.Children, categoryID, created.ID); err != nil {
return err
}
}
@ -686,13 +701,13 @@ func (s *FlowNodesReg) sortByDepth(rootID uint64, descendants, allNodes []*types
// generateCopySuffix генерирует уникальный суффикс для дублированного ключа
func (s *FlowNodesReg) generateCopySuffix(ctx context.Context, original *typescore.ApprovalFlowNode) string {
if original.TopicID == nil || original.Key == nil {
if original.CategoryID == nil || original.Key == nil {
return "_copy"
}
// Ищем существующие копии
existing, _, err := s.ipc.Database.ApprovalFlowNode.GetApprovalFlowNodesListDB(ctx, typescore.ListDbOptions{
Filtering: &typescore.ApprovalFlowNode{TopicID: original.TopicID},
Filtering: &typescore.ApprovalFlowNode{CategoryID: original.CategoryID},
})
if err != nil {
return "_copy"

View File

@ -4,11 +4,8 @@ import (
configcore "bitrix_balancer_api/core/config"
clientcontrollers "bitrix_balancer_api/core/lib/internally/client-controllers"
tgupdatehandler "bitrix_balancer_api/telegram_service/common/update"
"bitrix_balancer_api/telegram_service/migrate"
"bitrix_balancer_api/telegram_service/scheduler"
"bitrix_balancer_api/telegram_service/types"
"context"
"github.com/sirupsen/logrus"
"log"
"runtime/debug"
)
@ -33,11 +30,6 @@ func initService() error {
return err
}
err = migrate.SeedAllTopics(context.Background(), ipc)
if err != nil {
logrus.Error(err)
return err
}
delegationChecker := scheduler.NewDelegationChecker(ipc)
delegationChecker.Start()