diff --git a/core/db/db.go b/core/db/db.go index 34f19f8..8afd57b 100644 --- a/core/db/db.go +++ b/core/db/db.go @@ -34,6 +34,7 @@ type ModuleDB struct { ApprovalAdditionalObserver *dbcore.ApprovalAdditionalObserverDB ApprovalTopicExecutor *dbcore.ApprovalTopicExecutorDB Admin *dbcore.AdminDB + ApprovalFlowNode *dbcore.ApprovalFlowNodeDB } func NewModuleDB( @@ -84,6 +85,7 @@ func initDBModules(modules *ModuleDB, redisClient *redismodule.ModuleRedis) *Mod modules.ApprovalAdditionalObserver = dbcore.NewApprovalAdditionalObserverDB(modules.Pool) modules.ApprovalTopicExecutor = dbcore.NewApprovalTopicExecutorDB(modules.Pool) modules.Admin = dbcore.NewAdminDB(modules.Pool) + modules.ApprovalFlowNode = dbcore.NewApprovalFlowNodeDB(modules.Pool) return modules } diff --git a/core/db/db_migration/tables.go b/core/db/db_migration/tables.go index 5dcea35..0f8550e 100644 --- a/core/db/db_migration/tables.go +++ b/core/db/db_migration/tables.go @@ -38,6 +38,7 @@ func (m *MigrationFunctions) migrateTables() error { tablesmigration.ApprovalAdditionalObserverTableMigrate, tablesmigration.ApprovalTopicExecutorsTableMigrate, tablesmigration.AdminsTableMigrate, + tablesmigration.ApprovalFlowNodesTableMigrate, } for _, migrate := range migrations { diff --git a/core/db/db_migration/tables/approval_flow_nodes.go b/core/db/db_migration/tables/approval_flow_nodes.go new file mode 100644 index 0000000..63356da --- /dev/null +++ b/core/db/db_migration/tables/approval_flow_nodes.go @@ -0,0 +1,52 @@ +package tablesmigration + +import ( + "gorm.io/gorm" + "time" +) + +// ApprovalFlowNodesTableMigrate создаёт таблицу узлов дерева навигации +func ApprovalFlowNodesTableMigrate(db *gorm.DB) error { + hasTable := db.Migrator().HasTable(&LocalApprovalFlowNodeProvider{}) + + if err := db.AutoMigrate(&LocalApprovalFlowNodeProvider{}); err != nil { + return err + } + + if !hasTable { + time.Sleep(5 * time.Second) + + // Foreign key на approval_topics + db.Exec(`ALTER TABLE approval_flow_nodes ADD CONSTRAINT fk_approval_flow_nodes_topic_id FOREIGN KEY (topic_id) REFERENCES approval_topics(id) ON DELETE CASCADE ON UPDATE CASCADE`) + + // Самореференсный foreign key (parent_id -> id) + db.Exec(`ALTER TABLE approval_flow_nodes ADD CONSTRAINT fk_approval_flow_nodes_parent_id FOREIGN KEY (parent_id) REFERENCES approval_flow_nodes(id) ON DELETE CASCADE ON UPDATE CASCADE`) + + // Уникальный индекс (topic_id, key) — чтобы ключи узлов были уникальны в рамках одной темы + db.Exec(`CREATE UNIQUE INDEX IF NOT EXISTS idx_flow_nodes_topic_key ON approval_flow_nodes(topic_id, key)`) + + // Комментарии + execComments(db, ` + COMMENT ON TABLE "approval_flow_nodes" IS 'Узлы дерева навигации темы согласования: описывают структуру кнопок, шагов ввода и мультиселекта для динамического построения флоу'; + COMMENT ON COLUMN "approval_flow_nodes".id IS 'Внутренний уникальный идентификатор узла'; + COMMENT ON COLUMN "approval_flow_nodes".topic_id IS 'ID темы согласования, к которой принадлежит узел (ссылка на approval_topics.id)'; + COMMENT ON COLUMN "approval_flow_nodes".parent_id IS 'ID родительского узла (ссылка на approval_flow_nodes.id). NULL для корневого узла'; + COMMENT ON COLUMN "approval_flow_nodes".key IS 'Уникальный ключ узла в рамках темы (используется для навигации и идентификации)'; + COMMENT ON COLUMN "approval_flow_nodes".label IS 'Отображаемое название узла (текст на кнопке)'; + COMMENT ON COLUMN "approval_flow_nodes".data_key IS 'Ключ в map collected, куда сохраняется значение при выборе этого узла'; + COMMENT ON COLUMN "approval_flow_nodes".data_value IS 'Значение, сохраняемое в collected[data_key] при выборе этого узла'; + COMMENT ON COLUMN "approval_flow_nodes".is_input IS 'Флаг: является ли узел шагом текстового ввода'; + COMMENT ON COLUMN "approval_flow_nodes".input_key IS 'Ключ в collected, куда сохраняется введённый пользователем текст'; + COMMENT ON COLUMN "approval_flow_nodes".input_hint IS 'Подсказка/шаблон для пользователя при текстовом вводе'; + COMMENT ON COLUMN "approval_flow_nodes".is_multi_select IS 'Флаг: является ли узел узлом мультиселекта (выбор нескольких значений)'; + COMMENT ON COLUMN "approval_flow_nodes".multi_select_key IS 'Ключ в collected, куда сохраняется результат мультиселекта (через запятую)'; + COMMENT ON COLUMN "approval_flow_nodes".multi_select_value IS 'Значение этого варианта в мультиселекте'; + COMMENT ON COLUMN "approval_flow_nodes".topic_code IS 'Код темы для проверки прав доступа (если задан — кнопка показывается только при наличии права create на эту тему)'; + COMMENT ON COLUMN "approval_flow_nodes".sort_order IS 'Порядок сортировки узла среди братьев (0, 1, 2, ...)'; + COMMENT ON COLUMN "approval_flow_nodes".created_at IS 'Дата и время создания узла'; + COMMENT ON COLUMN "approval_flow_nodes".updated_at IS 'Дата и время последнего изменения узла'; + `) + } + + return nil +} diff --git a/core/db/db_migration/tables/providers.go b/core/db/db_migration/tables/providers.go index 29b3b6f..ede7abd 100644 --- a/core/db/db_migration/tables/providers.go +++ b/core/db/db_migration/tables/providers.go @@ -24,6 +24,7 @@ type ApprovalCommentsProvider typescore.ApprovalComment type LocalSuggestionProvider typescore.Suggestion type LocalSuggestionMessagesProvider typescore.SuggestionMessage type LocalApprovalTopicExecutorProvider typescore.ApprovalTopicExecutor +type LocalApprovalFlowNodeProvider typescore.ApprovalFlowNode func (LocalUserProvider) TableName() string { return dbcoretablenames.TableNameUsers.ToString() @@ -82,3 +83,6 @@ func (ApprovalAdditionalObserver) TableName() string { func (LocalApprovalTopicExecutorProvider) TableName() string { return dbcoretablenames.TableNameApprovalTopicExecutor.ToString() } +func (LocalApprovalFlowNodeProvider) TableName() string { + return dbcoretablenames.TableNameApprovalFlowNodes.ToString() +} diff --git a/core/db/methods/approval_flow_node.go b/core/db/methods/approval_flow_node.go new file mode 100644 index 0000000..13317d2 --- /dev/null +++ b/core/db/methods/approval_flow_node.go @@ -0,0 +1,175 @@ +package dbcore + +import ( + dbcoretablenames "bitrix_balancer_api/core/db/table_names" + "bitrix_balancer_api/core/typescore" + dbutils "bitrix_balancer_api/core/utilscore/db" + "context" + "errors" + + "github.com/Masterminds/squirrel" + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgxpool" +) + +type ApprovalFlowNodeDB struct { + pool *pgxpool.Pool +} + +func NewApprovalFlowNodeDB(pool *pgxpool.Pool) *ApprovalFlowNodeDB { + return &ApprovalFlowNodeDB{pool: pool} +} + +type ApprovalFlowNodeDBI interface { + GetApprovalFlowNodesListDB(ctx context.Context, options ...typescore.ListDbOptions) ([]*typescore.ApprovalFlowNode, uint64, error) + 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 + GetFlowNodeByIDDB(ctx context.Context, id uint64) (*typescore.ApprovalFlowNode, error) +} + +func (u *ApprovalFlowNodeDB) GetApprovalFlowNodesListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.ApprovalFlowNode, uint64, error) { + fields := dbutils.GetStructFieldsDB(&typescore.ApprovalFlowNode{}, dbcoretablenames.TableNameApprovalFlowNodes.ToString()) + selectFields := append(fields, "COUNT(*) OVER() AS total_count") + + options, filter, err := dbutils.GetOptionsDB[typescore.ApprovalFlowNode](opts...) + if err != nil { + return nil, 0, err + } + + query := dbutils.BuildSelectQuery(dbcoretablenames.TableNameApprovalFlowNodes.ToString(), selectFields) + query = dbutils.SetterLimitAndOffsetQuery(query, options.Offset, options.Limit) + query = dbutils.ApplyFilters(query, filter, options.LikeFields, dbcoretablenames.TableNameApprovalFlowNodes.ToString()) + query = query.OrderBy("sort_order ASC, id ASC") + + sql, args, err := query.ToSql() + if err != nil { + return nil, 0, err + } + + rows, err := u.pool.Query(ctx, sql, args...) + if err != nil { + return nil, 0, err + } + defer rows.Close() + + var nodes []*typescore.ApprovalFlowNode + var totalCount uint64 + for rows.Next() { + node := &typescore.ApprovalFlowNode{} + if err := dbutils.ScanRowsToStructRows(rows, node, &totalCount); err != nil { + continue + } + nodes = append(nodes, node) + } + + return nodes, totalCount, nil +} + +func (u *ApprovalFlowNodeDB) CreateApprovalFlowNodeDB(ctx context.Context, tx pgx.Tx, node *typescore.ApprovalFlowNode, returnObj ...bool) (*typescore.ApprovalFlowNode, pgx.Tx, error) { + if node == nil { + return nil, nil, errors.New("node is nil") + } + + err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error { + query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). + Insert(dbcoretablenames.TableNameApprovalFlowNodes.ToString()) + + sqlV, args, err := dbutils.GenerateInsertRequest(query, node) + if err != nil { + return err + } + + _, err = tx.Exec(ctx, *sqlV, args...) + return err + }) + + if err != nil { + return nil, tx, err + } + + if len(returnObj) > 0 && returnObj[0] { + nodes, _, _ := u.GetApprovalFlowNodesListDB(ctx, typescore.ListDbOptions{Filtering: node}) + if len(nodes) > 0 { + return nodes[0], tx, nil + } + } + + return nil, tx, nil +} + +func (u *ApprovalFlowNodeDB) UpdateApprovalFlowNodeDB(ctx context.Context, tx pgx.Tx, node *typescore.ApprovalFlowNode, returnObj ...bool) (*typescore.ApprovalFlowNode, pgx.Tx, error) { + if node == nil || node.ID == nil { + return nil, nil, errors.New("node or node.ID is nil") + } + + err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error { + query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). + Update(dbcoretablenames.TableNameApprovalFlowNodes.ToString()) + query = dbutils.AddNonNullFieldsToQueryUpdate(query, *node) + query = query.Where(squirrel.Eq{"id": node.ID}) + + sql, args, err := query.ToSql() + if err != nil { + return err + } + + _, err = tx.Exec(ctx, sql, args...) + return err + }) + + if err != nil { + return nil, tx, err + } + + if len(returnObj) > 0 && returnObj[0] { + updated, _ := u.GetFlowNodeByIDDB(ctx, *node.ID) + return updated, tx, nil + } + + return nil, tx, nil +} + +func (u *ApprovalFlowNodeDB) DeleteApprovalFlowNodeDB(ctx context.Context, node *typescore.ApprovalFlowNode) error { + if node == nil || node.ID == nil { + return errors.New("node or node.ID is nil") + } + + query, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). + Delete(dbcoretablenames.TableNameApprovalFlowNodes.ToString()). + Where(squirrel.Eq{"id": *node.ID}). + ToSql() + if err != nil { + return err + } + + _, err = u.pool.Exec(ctx, query, args...) + return err +} + +func (u *ApprovalFlowNodeDB) DeleteFlowNodesByTopicIDDB(ctx context.Context, topicID uint64) error { + query, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). + Delete(dbcoretablenames.TableNameApprovalFlowNodes.ToString()). + Where(squirrel.Eq{"topic_id": topicID}). + ToSql() + if err != nil { + return err + } + + _, err = u.pool.Exec(ctx, query, args...) + return err +} + +func (u *ApprovalFlowNodeDB) GetFlowNodeByIDDB(ctx context.Context, id uint64) (*typescore.ApprovalFlowNode, error) { + nodes, _, err := u.GetApprovalFlowNodesListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.ApprovalFlowNode{ID: &id}, + }) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, nil + } + return nodes[0], nil +} diff --git a/core/db/table_names/table_names.go b/core/db/table_names/table_names.go index 42b6f4e..942165a 100644 --- a/core/db/table_names/table_names.go +++ b/core/db/table_names/table_names.go @@ -23,6 +23,7 @@ const ( TableNameSuggestionMessages TableName = "suggestion_messages" TableNameApprovalTopicExecutor TableName = "approval_topic_executor" TableNameAdmin TableName = "admin" + TableNameApprovalFlowNodes TableName = "approval_flow_nodes" ) func (t TableName) ToString() string { diff --git a/core/typescore/approval.go b/core/typescore/approval.go index d165d9b..290799c 100644 --- a/core/typescore/approval.go +++ b/core/typescore/approval.go @@ -57,7 +57,8 @@ type ApprovalMetadata struct { // Тип изменения ChangeType string `json:"change_type,omitempty"` // Любые другие поля из collected которые нужно сохранить - Extra map[string]string `json:"extra,omitempty"` + Extra map[string]string `json:"extra,omitempty"` + Labels map[string]string `json:"labels,omitempty"` } func (m *ApprovalMetadata) ToJSON() (*string, error) { diff --git a/core/typescore/approval_flow_node.go b/core/typescore/approval_flow_node.go new file mode 100644 index 0000000..7c7fd22 --- /dev/null +++ b/core/typescore/approval_flow_node.go @@ -0,0 +1,40 @@ +package typescore + +import "time" + +// ApprovalFlowNode — узел дерева навигации темы согласования +type ApprovalFlowNode struct { + ID *uint64 `gorm:"column:id;type:bigserial;autoIncrement;not null;unique" ignore_update_db:"true" json:"id" db:"id" mapstructure:"id"` + TopicID *uint64 `gorm:"type:bigint;not null;index;column:topic_id" json:"topic_id" db:"topic_id" mapstructure:"topic_id"` + ParentID *uint64 `gorm:"type:bigint;index;column:parent_id" json:"parent_id,omitempty" db:"parent_id" mapstructure:"parent_id"` + + // Идентификация узла + Key *string `gorm:"type:text;not null;column:key" json:"key" db:"key" mapstructure:"key"` + Label *string `gorm:"type:text;not null;column:label" json:"label" db:"label" mapstructure:"label"` + + // Связь с данными (для обычных кнопок) + DataKey *string `gorm:"type:text;column:data_key" json:"data_key,omitempty" db:"data_key" mapstructure:"data_key"` + DataValue *string `gorm:"type:text;column:data_value" json:"data_value,omitempty" db:"data_value" mapstructure:"data_value"` + + // Текстовый ввод + IsInput *bool `gorm:"type:boolean;default:false;column:is_input" json:"is_input" db:"is_input" mapstructure:"is_input"` + InputKey *string `gorm:"type:text;column:input_key" json:"input_key,omitempty" db:"input_key" mapstructure:"input_key"` + InputHint *string `gorm:"type:text;column:input_hint" json:"input_hint,omitempty" db:"input_hint" mapstructure:"input_hint"` + + // Мультиселект + IsMultiSelect *bool `gorm:"type:boolean;default:false;column:is_multi_select" json:"is_multi_select" db:"is_multi_select" mapstructure:"is_multi_select"` + MultiSelectKey *string `gorm:"type:text;column:multi_select_key" json:"multi_select_key,omitempty" db:"multi_select_key" mapstructure:"multi_select_key"` + MultiSelectValue *string `gorm:"type:text;column:multi_select_value" json:"multi_select_value,omitempty" db:"multi_select_value" mapstructure:"multi_select_value"` + + // Код темы для проверки прав доступа + TopicCode *string `gorm:"type:text;column:topic_code" json:"topic_code,omitempty" db:"topic_code" mapstructure:"topic_code"` + + // Порядок сортировки + SortOrder *int `gorm:"type:integer;default:0;column:sort_order" json:"sort_order" db:"sort_order" mapstructure:"sort_order"` + + CreatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:created_at" json:"created_at" db:"created_at" mapstructure:"created_at"` + UpdatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:updated_at" json:"updated_at" db:"updated_at" mapstructure:"updated_at"` + + // Не сохраняется в БД — для построения дерева в API + Children []*ApprovalFlowNode `gorm:"-" json:"children,omitempty"` +} diff --git a/core/typescore/approval_topic.go b/core/typescore/approval_topic.go index 5294fd1..917af52 100644 --- a/core/typescore/approval_topic.go +++ b/core/typescore/approval_topic.go @@ -26,10 +26,15 @@ type ApprovalTopic struct { AllowApproverSelection *bool `gorm:"type:boolean;not null;default:false;column:allow_approver_selection" json:"allow_approver_selection,omitempty" db:"allow_approver_selection" mapstructure:"allow_approver_selection"` AllowObserverSelection *bool `gorm:"type:boolean;not null;default:false;column:allow_observer_selection" json:"allow_observer_selection,omitempty" db:"allow_observer_selection" mapstructure:"allow_observer_selection"` + IsTreeRoot *bool `gorm:"type:boolean;default:false;column:is_tree_root" json:"is_tree_root" db:"is_tree_root" mapstructure:"is_tree_root"` + RequireApproverComment *bool `gorm:"type:boolean;default:false;column:require_approver_comment" json:"require_approver_comment" db:"require_approver_comment"` RequiresFile *bool `gorm:"type:boolean;not null;default:false;column:requires_file" json:"requires_file" db:"requires_file"` RequireObserverSelection *bool `gorm:"type:boolean;not null;default:false;column:require_observer_selection" json:"require_observer_selection" db:"require_observer_selection"` + MessageTemplate *string `gorm:"type:text;column:message_template" json:"message_template,omitempty" db:"message_template" mapstructure:"message_template"` + CodeTemplate *string `gorm:"type:text;column:code_template" json:"code_template,omitempty" db:"code_template" mapstructure:"code_template"` + IsActive *bool `gorm:"type:boolean;not null;default:true;column:is_active" json:"is_active" db:"is_active" mapstructure:"is_active"` CreatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:created_at" json:"created_at" db:"created_at"` UpdatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:updated_at" json:"updated_at" db:"updated_at"` diff --git a/service/rest_admin_service/cmd/app.go b/service/rest_admin_service/cmd/app.go index 2f98b2e..6bb702f 100644 --- a/service/rest_admin_service/cmd/app.go +++ b/service/rest_admin_service/cmd/app.go @@ -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" permissionshandler "bitrix_balancer_api/rest_admin_service/handlers/permission" profilehandler "bitrix_balancer_api/rest_admin_service/handlers/profile" roleshandler "bitrix_balancer_api/rest_admin_service/handlers/roles" @@ -217,6 +218,7 @@ func registerRoutes(router chi.Router, ipc *typesm.InternalProviderControl) erro {"permissions", permissionshandler.RegisterPermissionRoutes}, {"approval-tasks", approvaltaskshandler.RegisterApprovalTasksRoutes}, {"dashboard", dashboardhandler.RegisterDashboardRoutes}, + {"nodes", nodeshandler.RegisterFlowNodesRoutes}, } // Регистрация всех маршрутов diff --git a/service/rest_admin_service/handlers/flow_nodes/handler.go b/service/rest_admin_service/handlers/flow_nodes/handler.go new file mode 100644 index 0000000..3c34b7e --- /dev/null +++ b/service/rest_admin_service/handlers/flow_nodes/handler.go @@ -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) +} diff --git a/service/rest_admin_service/handlers/flow_nodes/router.go b/service/rest_admin_service/handlers/flow_nodes/router.go new file mode 100644 index 0000000..b39a0f3 --- /dev/null +++ b/service/rest_admin_service/handlers/flow_nodes/router.go @@ -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 +} diff --git a/service/system_service/database_additionally/topic_migration.go b/service/system_service/database_additionally/topic_migration.go new file mode 100644 index 0000000..224d12c --- /dev/null +++ b/service/system_service/database_additionally/topic_migration.go @@ -0,0 +1,1323 @@ +package database_additionally + +import ( + "bitrix_balancer_api/core/typescore" + "bitrix_balancer_api/system_service/types" + "context" + "fmt" + "github.com/sirupsen/logrus" +) + +// MigrateTopicsToDB переносит все хардкод-темы в БД +func MigrateTopicsToDB(ctx context.Context, ipc *types.InternalProviderControl) error { + logrus.Info("Starting topics migration...") + + // Все темы для миграции + topicsData := []topicMigrationData{ + getAbsenceData(), + getClientChangesData(), + getGoodsOrderData(), + getManagerExpensesData(), + getNonBudgetExpensesData(), + getNonBudgetExpensesPetLineData(), + getNonstandardContractData(), + getOtkConditionsData(), + getPaymentsCashlessData(), + getRatesLogisticsData(), + getReceiptsData(), + getReturnsData(), + getShipmentsSOHData(), + getTransactionPassportData(), + // Free темы + getFreeTopicData("delivery_clients", "Доставка клиентам/на склад", "Доставка клиентам", "Иванов Иван Иванович\nТел 89781234567\nПаспорт 1234 567890\nДАФ н862нн46 п/п АА8473|46\n\n61 бц с ад - 52 кор\nЧП000001676\n\nЕПР-СтройКрым"), + getFreeTopicData("v_shipments", "В. Отгрузки", "В. Отгрузки", "ООО Нива на 370 тыс. руб. под 19%"), + getFreeTopicData("shipments", "Отгрузки", "Отгрузки", "Если не входит в рамки согласованного лимита, добавь руководителя соответствующего филиала к согласованию через кнопку 'Добавить согласующего'"), + getFreeTopicData("vacancies", "Вакансии", "Вакансии", ""), + getFreeTopicData("delivery_rates_ap", "Ставки доставки АП", "Ставки доставки АП", "Прошу согласовать доставку 14 кор преформы клиенту Олег-Выдув-Сочи за 34 000 руб."), + getFreeTopicData("freelancers_approval", "Утверждение фрилансеров", "Утверждение фрилансеров", "Одного помощника на выгрузку полной фуры с крышкой ручкой с КТ на 23.04.2026 на весь день"), + getFreeTopicData("non_working_day", "Выход в нерабочий день", "Выход в нерабочий день", "Прошу вывести склад для учета c 25.04 по 26.04"), + getFreeTopicData("suggestions", "Предложения и пожелания", "Предложения и пожелания", ""), + getFreeTopicData("cash_balance", "Остаток в кассах", "Остаток в кассах", ""), + getFreeTopicData("client_sales", "Продажи по клиенту", "Продажи по клиенту", ""), + getFreeTopicData("manager_expenses_report", "Проведенные расходы по менеджеру", "Проведенные расходы по менеджеру", ""), + getFreeTopicData("remote_access", "Согласование удаленной работы", "Согласование удаленной работы", "Прошу согласовать удалённый выход на работу 06.06.2026"), + } + + topicsData = append(topicsData, getAllFreeTopicsData()...) + + for _, data := range topicsData { + if err := migrateTopic(ctx, ipc, data); err != nil { + logrus.Errorf("Failed to migrate topic %s: %v", data.topicCode, err) + return err + } + } + + logrus.Info("Topics migration completed successfully") + return nil +} + +type topicMigrationData struct { + categoryCode string + categoryName string + topicCode string + topicName string + messageTemplate string + codeTemplate string + nodes []*typescore.ApprovalFlowNode + instructions string + firstApproverRoleCode string // 🆕 Роль первого согласующего + allowApproverSelection bool // 🆕 Разрешить выбор согласующего + requiresFile bool // 🆕 Требовать файл + requireObserverSelection bool // 🆕 Требовать выбор наблюдателя + isTreeRoot bool +} + +func migrateTopic(ctx context.Context, ipc *types.InternalProviderControl, data topicMigrationData) error { + // 1. Создаём или находим категорию + category, err := ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByCodeDB(ctx, data.categoryCode) + if err != nil { + return fmt.Errorf("get category: %w", err) + } + + if category == nil { + category = &typescore.ApprovalTopicCategory{ + Code: strPtr(data.categoryCode), + Name: strPtr(data.categoryName), + IsActive: boolPtr(true), + } + created, _, err := ipc.Database.ApprovalTopicCategory.CreateApprovalTopicCategoryDB(ctx, nil, category, true) + if err != nil { + return fmt.Errorf("create category: %w", err) + } + category = created + } + + // 2. Создаём или находим тему + topic, err := ipc.Database.ApprovalTopic.GetApprovalTopicByCodeDB(ctx, data.topicCode) + if err != nil { + return fmt.Errorf("get topic: %w", err) + } + + if topic == nil { + topic = &typescore.ApprovalTopic{ + CategoryID: category.ID, + Code: strPtr(data.topicCode), + Name: strPtr(data.topicName), + IsActive: boolPtr(true), + ApprovalMode: strPtr("sequential"), + MessageTemplate: strPtr(data.messageTemplate), + IsTreeRoot: boolPtr(data.isTreeRoot), + } + if data.codeTemplate != "" { + topic.CodeTemplate = strPtr(data.codeTemplate) + } + if data.instructions != "" { + topic.Instructions = strPtr(data.instructions) + } + // 🆕 Добавляем важные настройки + if data.firstApproverRoleCode != "" { + topic.FirstApproverRoleCode = strPtr(data.firstApproverRoleCode) + } + if data.allowApproverSelection { + topic.AllowApproverSelection = boolPtr(true) + } + if data.requiresFile { + topic.RequiresFile = boolPtr(true) + } + if data.requireObserverSelection { + topic.RequireObserverSelection = boolPtr(true) + } + + created, _, err := ipc.Database.ApprovalTopic.CreateApprovalTopicDB(ctx, nil, topic, true) + if err != nil { + return fmt.Errorf("create topic: %w", err) + } + topic = created + } + + // 3. Проверяем, есть ли уже узлы для этой темы + existingNodes, _, err := ipc.Database.ApprovalFlowNode.GetApprovalFlowNodesListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.ApprovalFlowNode{TopicID: topic.ID}, + }) + if err != nil { + return fmt.Errorf("get existing nodes: %w", err) + } + + if len(existingNodes) > 0 { + logrus.Infof("Topic %s already has %d nodes, skipping", data.topicCode, len(existingNodes)) + return nil + } + + // 4. Создаём узлы дерева рекурсивно + if err := createNodesRecursive(ctx, ipc, topic.ID, nil, data.nodes); err != nil { + return fmt.Errorf("create nodes: %w", err) + } + + logrus.Infof("Migrated topic %s with %d nodes", data.topicCode, countNodes(data.nodes)) + return nil +} + +func createNodesRecursive(ctx context.Context, ipc *types.InternalProviderControl, topicID *uint64, parentID *uint64, nodes []*typescore.ApprovalFlowNode) error { + for i, node := range nodes { + node.TopicID = topicID + node.ParentID = parentID + sortOrder := i + node.SortOrder = &sortOrder + + created, _, err := ipc.Database.ApprovalFlowNode.CreateApprovalFlowNodeDB(ctx, nil, node, true) + if err != nil { + return err + } + + if len(node.Children) > 0 { + if err := createNodesRecursive(ctx, ipc, topicID, created.ID, node.Children); err != nil { + return err + } + } + } + return nil +} + +func countNodes(nodes []*typescore.ApprovalFlowNode) int { + count := len(nodes) + for _, n := range nodes { + count += countNodes(n.Children) + } + return count +} + +// Вспомогательные функции +func strPtr(s string) *string { return &s } +func boolPtr(b bool) *bool { return &b } +func intPtr(i int) *int { return &i } + +func mkNode(key, label string) *typescore.ApprovalFlowNode { + return &typescore.ApprovalFlowNode{ + Key: strPtr(key), + Label: strPtr(label), + } +} + +func mkNodeData(key, label, dataKey, dataValue string) *typescore.ApprovalFlowNode { + return &typescore.ApprovalFlowNode{ + Key: strPtr(key), + Label: strPtr(label), + DataKey: strPtr(dataKey), + DataValue: strPtr(dataValue), + } +} + +func mkInput(key, label, inputKey, inputHint string) *typescore.ApprovalFlowNode { + return &typescore.ApprovalFlowNode{ + Key: strPtr(key), + Label: strPtr(label), + IsInput: boolPtr(true), + InputKey: strPtr(inputKey), + InputHint: strPtr(inputHint), + } +} + +func mkInputData(key, label, inputKey, inputHint, dataKey, dataValue string) *typescore.ApprovalFlowNode { + return &typescore.ApprovalFlowNode{ + Key: strPtr(key), + Label: strPtr(label), + IsInput: boolPtr(true), + InputKey: strPtr(inputKey), + InputHint: strPtr(inputHint), + DataKey: strPtr(dataKey), + DataValue: strPtr(dataValue), + } +} + +func mkMultiSelect(key, label, multiSelectKey, multiSelectValue string) *typescore.ApprovalFlowNode { + return &typescore.ApprovalFlowNode{ + Key: strPtr(key), + Label: strPtr(label), + IsMultiSelect: boolPtr(true), + MultiSelectKey: strPtr(multiSelectKey), + MultiSelectValue: strPtr(multiSelectValue), + } +} + +// getFreeTopicData создаёт данные для free-темы +func getFreeTopicData(code, name, categoryName, template string) topicMigrationData { + hint := "Напишите текст согласования" + if template != "" { + hint = template + } + return topicMigrationData{ + categoryCode: code, + categoryName: categoryName, + topicCode: code, + topicName: name, + messageTemplate: `📋 Заявка на согласование + +👤 От: {{.initiator_name}} +📂 Тема: {{.topic_name}} +📝 Текст: +{{.content}}`, + nodes: []*typescore.ApprovalFlowNode{ + mkInput(code+"_input", name, "content", hint), + }, + } +} + +// getAbsenceData — единая тема для отгулов, отпусков и больничных +func getAbsenceData() topicMigrationData { + + // === Вспомогательные функции === + + // Ветка оплаты для отпуска + buildVacationPaymentBranch := func(key, label, paymentType, hint string) *typescore.ApprovalFlowNode { + return &typescore.ApprovalFlowNode{ + Key: strPtr(key), + Label: strPtr(label), + DataKey: strPtr("payment_type"), + DataValue: strPtr(paymentType), + Children: []*typescore.ApprovalFlowNode{ + mkInputData(key+"_input", label, "content", hint, "time_type", "full_day"), + }, + } + } + + // Ветка длительности для отпуска + buildVacationDuration := func(key, dataValue, label, hint string) *typescore.ApprovalFlowNode { + return &typescore.ApprovalFlowNode{ + Key: strPtr(key), + Label: strPtr(label), + DataKey: strPtr("duration_type"), + DataValue: strPtr(dataValue), // ← dataValue отдельно от key + Children: []*typescore.ApprovalFlowNode{ + buildVacationPaymentBranch(key+"_own", "За свой счёт", "own_expense", hint), + buildVacationPaymentBranch(key+"_vac", "В счёт отпуска", "vacation_account", hint), + }, + } + } + + // Ветка длительности для отгула + buildTimeOffDuration := func(key, label, fullHint, partialHint string) *typescore.ApprovalFlowNode { + return &typescore.ApprovalFlowNode{ + Key: strPtr(key), + Label: strPtr(label), + DataKey: strPtr("duration_type"), + DataValue: strPtr(key), + Children: []*typescore.ApprovalFlowNode{ + // Весь день + &typescore.ApprovalFlowNode{ + Key: strPtr(key + "_full"), + Label: strPtr("Весь день"), + DataKey: strPtr("time_type"), + DataValue: strPtr("full_day"), + Children: []*typescore.ApprovalFlowNode{ + &typescore.ApprovalFlowNode{ + Key: strPtr(key + "_full_own"), + Label: strPtr("За свой счёт"), + DataKey: strPtr("payment_type"), + DataValue: strPtr("own_expense"), + Children: []*typescore.ApprovalFlowNode{ + mkInput(key+"_full_own_input", "За свой счёт", "content", fullHint), + }, + }, + &typescore.ApprovalFlowNode{ + Key: strPtr(key + "_full_vac"), + Label: strPtr("В счёт отпуска"), + DataKey: strPtr("payment_type"), + DataValue: strPtr("vacation_account"), + Children: []*typescore.ApprovalFlowNode{ + mkInput(key+"_full_vac_input", "В счёт отпуска", "content", fullHint), + }, + }, + }, + }, + // Частично + &typescore.ApprovalFlowNode{ + Key: strPtr(key + "_partial"), + Label: strPtr("Частично"), + DataKey: strPtr("time_type"), + DataValue: strPtr("partial"), + Children: []*typescore.ApprovalFlowNode{ + mkInputData(key+"_partial_input", "Частично", "content", partialHint, "payment_type", "own_expense"), + }, + }, + }, + } + } + + // ✅ ИСПРАВЛЕНИЕ: key и dataValue теперь раздельные + // key — уникальный для БД, dataValue — для формирования кода темы + buildSickLeaveDuration := func(key, dataValue, label, hint string) *typescore.ApprovalFlowNode { + return &typescore.ApprovalFlowNode{ + Key: strPtr(key), + Label: strPtr(label), + DataKey: strPtr("duration_type"), + DataValue: strPtr(dataValue), // ← dataValue отдельно от key + Children: []*typescore.ApprovalFlowNode{ + mkInputData(key+"_input", label, "content", hint, "time_type", "full_day"), + }, + } + } + + return topicMigrationData{ + categoryCode: "absence", + categoryName: "Согласование отпусков/отгулов", + topicCode: "absence", + topicName: "Согласование отпусков/отгулов", + isTreeRoot: true, + messageTemplate: `{{if eq .absence_type "timeoff"}}📋 Тип: Отгул + +{{.initiator_name}}: прошу согласовать отгул +{{.content}} +{{.payment_type_label}} +{{else if eq .absence_type "vacation"}}📋 Тип: Отпуск + +{{.initiator_name}}: прошу согласовать отпуск +{{.content}} +{{.payment_type_label}} +{{else if eq .absence_type "sickleave"}}📋 Тип: Официальный больничный + +{{.initiator_name}}: прошу согласовать больничный +{{if .open_date}}Дата открытия больничного листа - {{.open_date}}. +{{end}}{{.content}} +{{.payment_type_label}} +{{end}}`, + + codeTemplate: `{{if eq .absence_type "timeoff"}}timeoff_{{.duration_type}}_{{.time_type}}_{{.payment_type}}{{else if eq .absence_type "vacation"}}vacation_{{.duration_type}}_full_day_{{.payment_type}}{{else if eq .absence_type "sickleave"}}sickleave_{{trimPrefix .duration_type "sl_"}}_full_day_{{.payment_type}}{{end}}`, + + nodes: []*typescore.ApprovalFlowNode{ + // Корневой узел + &typescore.ApprovalFlowNode{ + Key: strPtr("absence"), + Label: strPtr("Согласование отпусков/отгулов"), + Children: []*typescore.ApprovalFlowNode{ + + // === ОТПУСК === + &typescore.ApprovalFlowNode{ + Key: strPtr("absence_vacation"), + Label: strPtr("Отпуск"), + DataKey: strPtr("absence_type"), + DataValue: strPtr("vacation"), + Children: []*typescore.ApprovalFlowNode{ + buildVacationDuration("vac_single_day", "single_day", "На один день", "22.02.2022"), + buildVacationDuration("vac_date_range", "date_range", "Диапазон дат", "22.02.2022 - 25.02.2022"), + buildVacationDuration("vac_multi_day", "multi_day", "Несколько дней", "22.02.2022, 24.02.2022, 26.02.2022"), + }, + }, + + // === ОТПУЛ (отгул) === + &typescore.ApprovalFlowNode{ + Key: strPtr("absence_timeoff"), + Label: strPtr("Отгул"), + DataKey: strPtr("absence_type"), + DataValue: strPtr("timeoff"), + Children: []*typescore.ApprovalFlowNode{ + buildTimeOffDuration("single_day", "На один день", + "22.02.2022", + "22.02.2022 с 16:00 по 18:00"), + buildTimeOffDuration("multi_day", "Несколько дней", + "22.02.2022, 24.02.2022, 26.02.2022", + "22.02.2022 с 10:00 по 14:00, 24.02.2022 с 09:00 по 12:00"), + }, + }, + + // === БОЛЬНИЧНЫЙ === + &typescore.ApprovalFlowNode{ + Key: strPtr("absence_sickleave"), + Label: strPtr("Официальный больничный"), + DataKey: strPtr("absence_type"), + DataValue: strPtr("sickleave"), + Children: []*typescore.ApprovalFlowNode{ + &typescore.ApprovalFlowNode{ + Key: strPtr("sl_open_date"), + Label: strPtr("Официальный больничный"), + IsInput: boolPtr(true), + InputKey: strPtr("open_date"), + InputHint: strPtr("Введите дату открытия больничного листа (например: 22.02.2022)"), + Children: []*typescore.ApprovalFlowNode{ + // В счёт отпуска + &typescore.ApprovalFlowNode{ + Key: strPtr("sl_vacation"), + Label: strPtr("В счёт отпуска"), + DataKey: strPtr("payment_type"), + DataValue: strPtr("vacation_account"), + Children: []*typescore.ApprovalFlowNode{ + // ✅ Уникальные ключи, но одинаковые DataValue + buildSickLeaveDuration("sl_vacation_single_day", "sl_single_day", "На один день", "22.02.2022"), + buildSickLeaveDuration("sl_vacation_date_range", "sl_date_range", "Диапазон дат", "22.02.2022 - 25.02.2022"), + }, + }, + // Только официальный + &typescore.ApprovalFlowNode{ + Key: strPtr("sl_official"), + Label: strPtr("Только оф. больничный"), + DataKey: strPtr("payment_type"), + DataValue: strPtr("official"), + Children: []*typescore.ApprovalFlowNode{ + // ✅ Уникальные ключи, но одинаковые DataValue + buildSickLeaveDuration("sl_official_single_day", "sl_single_day", "На один день", "22.02.2022"), + buildSickLeaveDuration("sl_official_date_range", "sl_date_range", "Диапазон дат", "22.02.2022 - 25.02.2022"), + }, + }, + }, + }, + }, + }, + }, + }, + }, + } +} + +// getClientChangesData — миграция темы "Изменение клиента в ОКБ и 1С" +func getClientChangesData() topicMigrationData { + + // Вспомогательная функция для создания ветки региона + buildRegion := func(changeKey, regionKey, regionLabel string) *typescore.ApprovalFlowNode { + return &typescore.ApprovalFlowNode{ + Key: strPtr(changeKey + "_" + regionKey), + Label: strPtr(regionLabel), + DataKey: strPtr("region"), + DataValue: strPtr(regionKey), + Children: []*typescore.ApprovalFlowNode{ + // ОКБ — мультиселект + &typescore.ApprovalFlowNode{ + Key: strPtr(changeKey + "_" + regionKey + "_okb"), + Label: strPtr("ОКБ"), + IsMultiSelect: boolPtr(true), + MultiSelectKey: strPtr("systems"), + MultiSelectValue: strPtr("okb"), + Children: []*typescore.ApprovalFlowNode{ + mkInput(changeKey+"_"+regionKey+"_okb_input", "ОКБ", "content", "Опишите изменения: текущие данные → новые данные"), + }, + }, + // 1С — мультиселект + &typescore.ApprovalFlowNode{ + Key: strPtr(changeKey + "_" + regionKey + "_1c"), + Label: strPtr("1С"), + IsMultiSelect: boolPtr(true), + MultiSelectKey: strPtr("systems"), + MultiSelectValue: strPtr("1c"), + Children: []*typescore.ApprovalFlowNode{ + mkInput(changeKey+"_"+regionKey+"_1c_input", "1С", "content", "Опишите изменения: текущие данные → новые данные"), + }, + }, + }, + } + } + + // Вспомогательная функция для создания ветки типа изменения + buildChangeType := func(changeKey, changeLabel string) *typescore.ApprovalFlowNode { + return &typescore.ApprovalFlowNode{ + Key: strPtr(changeKey), + Label: strPtr(changeLabel), + DataKey: strPtr("change_type"), + DataValue: strPtr(changeKey), + Children: []*typescore.ApprovalFlowNode{ + buildRegion(changeKey, "crimea", "Крым"), + buildRegion(changeKey, "krasnodar", "Краснодар"), + }, + } + } + + return topicMigrationData{ + categoryCode: "client_changes", + categoryName: "Изменение клиента в ОКБ и 1С", + topicCode: "client_changes", + topicName: "Изменение клиента в ОКБ и 1С", + isTreeRoot: true, + // Шаблон сообщения — используем автоматические label-маппинги + messageTemplate: `📋 Изменение клиентов в ОКБ и 1С: – {{.change_type_label}} +🖥 Системы: {{.systems_label}} +📍 Регион: {{.region_label}} + +{{.initiator_name}}: +{{.content}}`, + + // Код формируется из change_type и region + codeTemplate: `client_changes_{{.change_type}}_{{.region}}`, + + // Дерево узлов + nodes: []*typescore.ApprovalFlowNode{ + // Корневой узел + &typescore.ApprovalFlowNode{ + Key: strPtr("client_changes"), + Label: strPtr("Изменение клиента"), + Children: []*typescore.ApprovalFlowNode{ + buildChangeType("rename", "Поменять название"), + buildChangeType("change_manager", "Сменить менеджера"), + buildChangeType("new_client", "Внести нового клиента"), + }, + }, + }, + } +} + +// getGoodsOrderData — миграция темы "Заказ товаров" +func getGoodsOrderData() topicMigrationData { + + // Вспомогательная функция для создания ветки региона + buildRegion := func(orderType, regionKey, regionLabel string) *typescore.ApprovalFlowNode { + return &typescore.ApprovalFlowNode{ + Key: strPtr(orderType + "_" + regionKey), + Label: strPtr(regionLabel), + DataKey: strPtr("region"), + DataValue: strPtr(regionKey), + Children: []*typescore.ApprovalFlowNode{ + mkInput(orderType+"_"+regionKey+"_input", regionLabel, "content", "Скилур заказ:\n22 гр.38 мм бесцветная (10176) ЕПМ - 5кор.\nф1, на склад Гвардейское, 2я декада."), + }, + } + } + + // Вспомогательная функция для создания ветки типа заказа + buildOrderType := func(orderType, orderLabel string) *typescore.ApprovalFlowNode { + return &typescore.ApprovalFlowNode{ + Key: strPtr(orderType), + Label: strPtr(orderLabel), + DataKey: strPtr("order_type"), + DataValue: strPtr(orderType), + Children: []*typescore.ApprovalFlowNode{ + buildRegion(orderType, "crimea", "Крым"), + buildRegion(orderType, "krasnodar", "Краснодар"), + }, + } + } + + return topicMigrationData{ + categoryCode: "goods_order", + categoryName: "Заказ товаров", + topicCode: "goods_order", + topicName: "Заказ товаров", + isTreeRoot: true, + // Шаблон сообщения + messageTemplate: `📋 Заказ товаров — {{.order_type_label}} +📍 Регион: {{.region_label}} + +{{.initiator_name}}: +{{.content}}`, + + // Код формируется из order_type и region (region опционален) + codeTemplate: `{{if .region}}goods_order_{{.order_type}}_{{.region}}{{else}}goods_order_{{.order_type}}{{end}}`, + + // Дерево узлов + nodes: []*typescore.ApprovalFlowNode{ + // Корневой узел + &typescore.ApprovalFlowNode{ + Key: strPtr("goods_order"), + Label: strPtr("Заказ товаров"), + Children: []*typescore.ApprovalFlowNode{ + buildOrderType("monthly", "На месяц"), + buildOrderType("additional", "Дополнительный заказ"), + }, + }, + }, + } +} + +// getManagerExpensesData — миграция темы "Менеджерские расходы" +func getManagerExpensesData() topicMigrationData { + + // Вспомогательная функция для создания ветки региона + buildRegion := func(regionKey, regionLabel string) *typescore.ApprovalFlowNode { + return &typescore.ApprovalFlowNode{ + Key: strPtr(regionKey), + Label: strPtr(regionLabel), + DataKey: strPtr("region"), + DataValue: strPtr(regionKey), + Children: []*typescore.ApprovalFlowNode{ + mkInput(regionKey+"_input", regionLabel, "content", "Оплата платной дороги Краснодар-Темрюк-Краснодар в сумме 1420 руб. (клиент РУСМолоко) (расход Макаренко)"), + }, + } + } + + return topicMigrationData{ + categoryCode: "manager_expenses", + categoryName: "Менеджерские расходы", + topicCode: "manager_expenses", + topicName: "Менеджерские расходы", + isTreeRoot: true, + // Шаблон сообщения + messageTemplate: `📋 Менеджерские расходы — {{.region_label}} + +{{.initiator_name}}: +{{.content}}`, + + // Код формируется из region + codeTemplate: `manager_expenses_{{.region}}`, + + // Дерево узлов + nodes: []*typescore.ApprovalFlowNode{ + // Корневой узел + &typescore.ApprovalFlowNode{ + Key: strPtr("manager_expenses"), + Label: strPtr("Менеджерские расходы"), + Children: []*typescore.ApprovalFlowNode{ + buildRegion("crimea", "Крым"), + buildRegion("krasnodar", "Краснодар"), + }, + }, + }, + } +} + +// getNonBudgetExpensesData — миграция темы "Внебюджетные расходы" +func getNonBudgetExpensesData() topicMigrationData { + + // Ветка с развилкой ПП (для Ф1) + buildExpenseTypeWithPP := func(key, typeVal, label, hint string) *typescore.ApprovalFlowNode { + return &typescore.ApprovalFlowNode{ + Key: strPtr(key), + Label: strPtr(label), + DataKey: strPtr("expense_type"), + DataValue: strPtr(typeVal), + Children: []*typescore.ApprovalFlowNode{ + // ✅ Нужна ПП + &typescore.ApprovalFlowNode{ + Key: strPtr(key + "_pp_yes"), + Label: strPtr("✅ Нужна ПП"), + DataKey: strPtr("pp_required"), + DataValue: strPtr("yes"), + Children: []*typescore.ApprovalFlowNode{ + mkInput(key+"_pp_yes_input", "✅ Нужна ПП", "content", hint), + }, + }, + // ❌ Не нужна ПП + &typescore.ApprovalFlowNode{ + Key: strPtr(key + "_pp_no"), + Label: strPtr("❌ Не нужна ПП"), + DataKey: strPtr("pp_required"), + DataValue: strPtr("no"), + Children: []*typescore.ApprovalFlowNode{ + mkInput(key+"_pp_no_input", "❌ Не нужна ПП", "content", hint), + }, + }, + }, + } + } + + // Ветка без развилки ПП (для Ф2) + buildExpenseTypeSimple := func(key, typeVal, label, hint string) *typescore.ApprovalFlowNode { + return &typescore.ApprovalFlowNode{ + Key: strPtr(key), + Label: strPtr(label), + DataKey: strPtr("expense_type"), + DataValue: strPtr(typeVal), + Children: []*typescore.ApprovalFlowNode{ + mkInput(key+"_input", label, "content", hint), + }, + } + } + + return topicMigrationData{ + categoryCode: "non_budget_expenses", + categoryName: "Внебюджетные расходы", + topicCode: "non_budget_expenses", + topicName: "Внебюджетные расходы", + isTreeRoot: true, + // Шаблон сообщения + messageTemplate: `📋 Внебюджетные расходы — {{.branch_label}} ({{.expense_type_label}}){{if .pp_required}} +💳 ПП: {{.pp_required_label}}{{end}} + +{{.initiator_name}}: +{{.content}}`, + + // Код формируется из branch, expense_type и опционально pp_required + codeTemplate: `{{if .pp_required}}non_budget_expenses_{{.branch}}_{{.expense_type}}_pp_{{.pp_required}}{{else}}non_budget_expenses_{{.branch}}_{{.expense_type}}{{end}}`, + + // Дерево узлов + nodes: []*typescore.ApprovalFlowNode{ + // Корневой узел + &typescore.ApprovalFlowNode{ + Key: strPtr("non_budget_expenses"), + Label: strPtr("Внебюджетные расходы"), + Children: []*typescore.ApprovalFlowNode{ + // Ф1 — с развилкой ПП + &typescore.ApprovalFlowNode{ + Key: strPtr("f1"), + Label: strPtr("Ф1"), + DataKey: strPtr("branch"), + DataValue: strPtr("f1"), + Children: []*typescore.ApprovalFlowNode{ + buildExpenseTypeWithPP("f1_tmc", "tmc", "ТМЦ", + "Прошу согласовать и оплатить Счет от ООО Интернет Решения (Озон) за ноутбук и мышь для закупщика в сумме 31 335 руб. С НДС"), + buildExpenseTypeWithPP("f1_expense", "expense", "Расход", + "Прошу оплатить счет ИП Гулякина на сумму 3180,00 руб (без НДС) за продление 1С-Отчетность на 1 год"), + }, + }, + // Ф2 — без развилки ПП + &typescore.ApprovalFlowNode{ + Key: strPtr("f2"), + Label: strPtr("Ф2"), + DataKey: strPtr("branch"), + DataValue: strPtr("f2"), + Children: []*typescore.ApprovalFlowNode{ + buildExpenseTypeSimple("f2_tmc", "tmc", "ТМЦ", + "Прошу согласовать и оплатить Счет от ООО Интернет Решения (Озон) за ноутбук и мышь для закупщика в сумме 31 335 руб. С НДС"), + buildExpenseTypeSimple("f2_expense", "expense", "Расход", + "Прошу оплатить счет ИП Гулякина на сумму 3180,00 руб (без НДС) за продление 1С-Отчетность на 1 год"), + }, + }, + }, + }, + }, + } +} + +// getNonBudgetExpensesPetLineData — миграция темы "Внебюджетные расходы ПЭТ Лайн" +func getNonBudgetExpensesPetLineData() topicMigrationData { + + // Вспомогательная функция для создания ветки типа расхода + buildExpenseType := func(key, typeVal, label, hint string) *typescore.ApprovalFlowNode { + return &typescore.ApprovalFlowNode{ + Key: strPtr(key), + Label: strPtr(label), + DataKey: strPtr("expense_type"), + DataValue: strPtr(typeVal), + Children: []*typescore.ApprovalFlowNode{ + mkInput(key+"_input", label, "content", hint), + }, + } + } + + // Вспомогательная функция для создания ветки филиала + buildBranch := func(branchKey, branchLabel string) *typescore.ApprovalFlowNode { + return &typescore.ApprovalFlowNode{ + Key: strPtr(branchKey), + Label: strPtr(branchLabel), + DataKey: strPtr("branch"), + DataValue: strPtr(branchKey), + Children: []*typescore.ApprovalFlowNode{ + buildExpenseType(branchKey+"_tmc", "tmc", "ТМЦ", + "Опишите расход ТМЦ ПЭТ Лайн: наименование, количество, сумма"), + buildExpenseType(branchKey+"_expense", "expense", "Расход", + "Опишите расход ПЭТ Лайн: назначение, сумма, детали"), + }, + } + } + + return topicMigrationData{ + categoryCode: "non_budget_expenses_pet_line", + categoryName: "Внебюджетные расходы ПЭТ Лайн", + topicCode: "non_budget_expenses_pet_line", + topicName: "Внебюджетные расходы ПЭТ Лайн", + isTreeRoot: true, + // Шаблон сообщения + messageTemplate: `📋 Внебюджетные расходы ПЭТ Лайн — {{.branch_label}} ({{.expense_type_label}}) + +{{.initiator_name}}: +{{.content}}`, + + // Код формируется из branch и expense_type + codeTemplate: `non_budget_expenses_pet_line_{{.branch}}_{{.expense_type}}`, + + // Дерево узлов + nodes: []*typescore.ApprovalFlowNode{ + // Корневой узел + &typescore.ApprovalFlowNode{ + Key: strPtr("non_budget_expenses_pet_line"), + Label: strPtr("Внебюджетные расходы ПЭТ Лайн"), + Children: []*typescore.ApprovalFlowNode{ + buildBranch("f1", "Ф1"), + buildBranch("f2", "Ф2"), + }, + }, + }, + } +} + +// getNonstandardContractData — миграция темы "Нестандартные условия договора поставки" +func getNonstandardContractData() topicMigrationData { + + // Вспомогательная функция для создания ветки региона + buildRegion := func(regionKey, regionLabel string) *typescore.ApprovalFlowNode { + return &typescore.ApprovalFlowNode{ + Key: strPtr(regionKey), + Label: strPtr(regionLabel), + DataKey: strPtr("region"), + DataValue: strPtr(regionKey), + Children: []*typescore.ApprovalFlowNode{ + mkInput(regionKey+"_input", regionLabel, "content", + "Прошу согласовать отсрочку 21 день для клиента ООО Роса (другое юрлицо ООО Аквариум) (менеджер Петров)"), + }, + } + } + + return topicMigrationData{ + categoryCode: "nonstandard_contract", + categoryName: "Нестандартные условия договора поставки", + topicCode: "nonstandard_contract", + topicName: "Нестандартные условия договора поставки", + isTreeRoot: true, + // Шаблон сообщения + messageTemplate: `📋 Нестандартные условия договора поставки — {{.region_label}} + +{{.initiator_name}}: +{{.content}}`, + + // Код формируется из region + codeTemplate: `nonstandard_contract_{{.region}}`, + + // Дерево узлов + nodes: []*typescore.ApprovalFlowNode{ + // Корневой узел + &typescore.ApprovalFlowNode{ + Key: strPtr("nonstandard_contract"), + Label: strPtr("Нестандартные условия договора поставки"), + Children: []*typescore.ApprovalFlowNode{ + buildRegion("crimea", "Крым"), + buildRegion("krasnodar", "Краснодар"), + buildRegion("belarus", "Беларусь"), + }, + }, + }, + } +} + +// getOtkConditionsData — миграция темы "Долгосрочные условия ОТК" +func getOtkConditionsData() topicMigrationData { + + // Вспомогательная функция для создания ветки региона + buildRegion := func(regionKey, regionLabel string) *typescore.ApprovalFlowNode { + return &typescore.ApprovalFlowNode{ + Key: strPtr(regionKey), + Label: strPtr(regionLabel), + DataKey: strPtr("region"), + DataValue: strPtr(regionKey), + Children: []*typescore.ApprovalFlowNode{ + mkInput(regionKey+"_input", regionLabel, "content", "Опишите долгосрочные условия ОТК"), + }, + } + } + + return topicMigrationData{ + categoryCode: "otk_conditions", + categoryName: "Долгосрочные условия ОТК", + topicCode: "otk_conditions", + topicName: "Долгосрочные условия ОТК", + isTreeRoot: true, + // Шаблон сообщения — с fallback на "—" для пустых значений (как в оригинале) + messageTemplate: `📋 Долгосрочные условия ОТК — {{if .region_label}}{{.region_label}}{{else}}—{{end}} + +👤 Инициатор: {{if .initiator_name}}{{.initiator_name}}{{else}}—{{end}} +📝 Текст: +{{if .content}}{{.content}}{{else}}—{{end}}`, + + // Код формируется из region + codeTemplate: `otk_conditions_{{.region}}`, + + // Дерево узлов + nodes: []*typescore.ApprovalFlowNode{ + // Корневой узел + &typescore.ApprovalFlowNode{ + Key: strPtr("otk_conditions"), + Label: strPtr("Долгосрочные условия ОТК"), + Children: []*typescore.ApprovalFlowNode{ + buildRegion("crimea", "Крым"), + buildRegion("krasnodar", "Краснодар"), + buildRegion("belarus", "Беларусь"), + }, + }, + }, + } +} + +// getPaymentsCashlessData — миграция темы "Утверждение оплат безнал" +func getPaymentsCashlessData() topicMigrationData { + + // Вспомогательная функция для создания ветки категории с развилкой ПП + buildCategoryWithPP := func(key, label, hint string) *typescore.ApprovalFlowNode { + return &typescore.ApprovalFlowNode{ + Key: strPtr(key), + Label: strPtr(label), + DataKey: strPtr("payment_category"), + DataValue: strPtr(key), + Children: []*typescore.ApprovalFlowNode{ + // ✅ Нужна ПП + &typescore.ApprovalFlowNode{ + Key: strPtr(key + "_pp_yes"), + Label: strPtr("✅ Нужна ПП"), + DataKey: strPtr("pp_required"), + DataValue: strPtr("yes"), + Children: []*typescore.ApprovalFlowNode{ + mkInput(key+"_pp_yes_input", "✅ Нужна ПП", "content", hint), + }, + }, + // ❌ Не нужна ПП + &typescore.ApprovalFlowNode{ + Key: strPtr(key + "_pp_no"), + Label: strPtr("❌ Не нужна ПП"), + DataKey: strPtr("pp_required"), + DataValue: strPtr("no"), + Children: []*typescore.ApprovalFlowNode{ + mkInput(key+"_pp_no_input", "❌ Не нужна ПП", "content", hint), + }, + }, + }, + } + } + + return topicMigrationData{ + categoryCode: "payments_cashless", + categoryName: "Утверждение оплат безнал", + topicCode: "payments_cashless", + topicName: "Утверждение оплат безнал", + isTreeRoot: true, + // Шаблон сообщения + messageTemplate: `📋 Оплата безнал — {{.payment_category_label}}{{if .pp_required}} +💳 ПП: {{.pp_required_label}}{{end}} + +{{.initiator_name}}: +{{.content}}`, + + // Код формируется из payment_category и опционально pp_required + codeTemplate: `{{if .pp_required}}payments_cashless_{{.payment_category}}_pp_{{.pp_required}}{{else}}payments_cashless_{{.payment_category}}{{end}}`, + + // Дерево узлов + nodes: []*typescore.ApprovalFlowNode{ + // Корневой узел + &typescore.ApprovalFlowNode{ + Key: strPtr("payments_cashless"), + Label: strPtr("Утверждение оплат безнал"), + Children: []*typescore.ApprovalFlowNode{ + buildCategoryWithPP("goods", "Товар", + "Счет 2838 от 12.05.2026 от ООО Упаковка на сумму 2 464 700,16 руб."), + buildCategoryWithPP("misc", "Разное", + "Счет 2838 от 12.05.2026 от ООО Упаковка на сумму 2 464 700,16 руб."), + }, + }, + }, + } +} + +// getRatesLogisticsData — миграция темы "Ставки логистика" +func getRatesLogisticsData() topicMigrationData { + + // Вспомогательная функция для создания ветки типа ставки + buildRateType := func(rateKey, rateLabel, hint string) *typescore.ApprovalFlowNode { + return &typescore.ApprovalFlowNode{ + Key: strPtr(rateKey), + Label: strPtr(rateLabel), + DataKey: strPtr("rate_type"), + DataValue: strPtr(rateKey), + Children: []*typescore.ApprovalFlowNode{ + mkInput(rateKey+"_input", rateLabel, "content", hint), + }, + } + } + + return topicMigrationData{ + categoryCode: "rates_logistics", + categoryName: "Ставки логистика", + topicCode: "rates_logistics", + topicName: "Ставки логистика", + isTreeRoot: true, + // Шаблон сообщения + messageTemplate: `📋 Ставки логистика — {{.rate_type_label}} + +{{.initiator_name}}: +{{.content}}`, + + // Код формируется из rate_type + codeTemplate: `rates_logistics_{{.rate_type}}`, + + // Дерево узлов + nodes: []*typescore.ApprovalFlowNode{ + // Корневой узел + &typescore.ApprovalFlowNode{ + Key: strPtr("rates_logistics"), + Label: strPtr("Ставки логистика"), + Children: []*typescore.ApprovalFlowNode{ + buildRateType("once", "Разово", + "Опишите разовые ставки: маршрут, стоимость, срок"), + buildRateType("long_term", "Надолго", + "Опишите долгосрочные ставки: маршрут, стоимость, период"), + }, + }, + }, + } +} + +// getReceiptsData — миграция темы "Поступления по приходным документам" +func getReceiptsData() topicMigrationData { + + // Вспомогательная функция для создания ветки филиала + buildBranch := func(branchKey, branchLabel, hint string) *typescore.ApprovalFlowNode { + return &typescore.ApprovalFlowNode{ + Key: strPtr(branchKey), + Label: strPtr(branchLabel), + DataKey: strPtr("branch"), + DataValue: strPtr(branchKey), + Children: []*typescore.ApprovalFlowNode{ + mkInput(branchKey+"_input", branchLabel, "content", hint), + }, + } + } + + return topicMigrationData{ + categoryCode: "receipts", + requiresFile: true, // 🆕 Receipts требует файл + allowApproverSelection: true, + categoryName: "Поступления по приходным документам", + topicCode: "receipts", + topicName: "Поступления по приходным документам", + isTreeRoot: true, + // Шаблон сообщения + messageTemplate: `📋 Поступления — {{.branch_label}} + +{{.initiator_name}}: +{{.content}}`, + + // Код формируется из branch + codeTemplate: `receipts_{{.branch}}`, + + // Дерево узлов + nodes: []*typescore.ApprovalFlowNode{ + // Корневой узел + &typescore.ApprovalFlowNode{ + Key: strPtr("receipts"), + Label: strPtr("Поступления"), + Children: []*typescore.ApprovalFlowNode{ + buildBranch("f1", "Ф1", + "Опишите поступление по филиалу Ф1: товар, количество, поставщик"), + buildBranch("f2", "Ф2", + "Опишите поступление по филиалу Ф2: товар, количество, поставщик"), + }, + }, + }, + } +} + +// getReturnsData — миграция темы "Возвраты" +func getReturnsData() topicMigrationData { + + // Вспомогательная функция для создания ветки региона + buildRegion := func(returnType, regionKey, regionLabel, hint string) *typescore.ApprovalFlowNode { + return &typescore.ApprovalFlowNode{ + Key: strPtr(returnType + "_" + regionKey), + Label: strPtr(regionLabel), + DataKey: strPtr("region"), + DataValue: strPtr(regionKey), + Children: []*typescore.ApprovalFlowNode{ + mkInput(returnType+"_"+regionKey+"_input", regionLabel, "content", hint), + }, + } + } + + // Вспомогательная функция для создания ветки типа возврата + buildReturnType := func(returnType, returnLabel, hint string) *typescore.ApprovalFlowNode { + return &typescore.ApprovalFlowNode{ + Key: strPtr(returnType), + Label: strPtr(returnLabel), + DataKey: strPtr("return_type"), + DataValue: strPtr(returnType), + Children: []*typescore.ApprovalFlowNode{ + buildRegion(returnType, "crimea", "Крым", hint), + buildRegion(returnType, "krasnodar", "Краснодар", hint), + }, + } + } + + return topicMigrationData{ + categoryCode: "returns", + categoryName: "Возвраты", + topicCode: "returns", + topicName: "Возвраты", + isTreeRoot: true, + // Шаблон сообщения + messageTemplate: `📋 {{.return_type_label}} — {{.region_label}} + +{{.initiator_name}}: +{{.content}}`, + + // Код формируется из return_type и region + codeTemplate: `returns_{{.return_type}}_{{.region}}`, + + // Дерево узлов + nodes: []*typescore.ApprovalFlowNode{ + // Корневой узел + &typescore.ApprovalFlowNode{ + Key: strPtr("returns"), + Label: strPtr("Возвраты"), + Children: []*typescore.ApprovalFlowNode{ + buildReturnType("supplier", "Возврат поставщику", + "Бишули\n28 гр.1881 бесцветная (9504) ПФ - 2 короба\nРеализация товаров и услуг ЧП000001326 от 20.04.2026 8:00:01\nФ1\n\nПричина: Короб приехал с завода и сильно порвался в дороге, клиент не может на свою продукцию использовать его"), + buildReturnType("other_manager", "Продажа другим менеджером", + "Бишули\n61 гр.38 мм бесцветная (3888) ЕП - 11 коробов\nРеализация товаров и услуг ЧП000000584 от 05.03.2026 8:00:01\nФ1\n\nПричина: Часть заказа отвалилась, будут переходить на эту позицию не раньше, чем через 3 мес\n\nПродаст выбранный менеджер на Бойко"), + buildReturnType("self_sale", "Самостоятельная продажа", + "ТД Крымэколайф\n40,5 гр.1881 бесцветная (7808) ПФ - 52 короба\nРеализация товаров и услуг ЧП000003123 от 4.08.25\nФ1\n\nПричина: для сокращения долга клиента\n\nДействия: продам ООО Нива"), + }, + }, + }, + } +} + +// getShipmentsSOHData — миграция темы "Отгрузки на СОХ" +func getShipmentsSOHData() topicMigrationData { + + // Вспомогательная функция для создания ветки типа отгрузки + buildShipmentType := func(regionKey, shipmentType, shipmentLabel, hint string) *typescore.ApprovalFlowNode { + return &typescore.ApprovalFlowNode{ + Key: strPtr(regionKey + "_" + shipmentType), + Label: strPtr(shipmentLabel), + DataKey: strPtr("shipment_type"), + DataValue: strPtr(shipmentType), + Children: []*typescore.ApprovalFlowNode{ + mkInput(regionKey+"_"+shipmentType+"_input", shipmentLabel, "content", hint), + }, + } + } + + // Вспомогательная функция для создания ветки региона + buildRegion := func(regionKey, regionLabel string) *typescore.ApprovalFlowNode { + return &typescore.ApprovalFlowNode{ + Key: strPtr(regionKey), + Label: strPtr(regionLabel), + DataKey: strPtr("region"), + DataValue: strPtr(regionKey), + Children: []*typescore.ApprovalFlowNode{ + buildShipmentType(regionKey, "real", "Реальная", + "Прошу согласовать перемещение на СОХ\nНива ООО \n31,6 гр. 1810 бесцветная (8352) АТФ 5 кор. 7,21 руб.\n81 гр.48 мм бесцветная (2464) ОП 10 кор. 18,23 руб.\nна сумму 750 276,8 руб.\nОстаток лимита у клиента с учётом текущей задолженности 2 656 689,12 руб."), + buildShipmentType(regionKey, "limit", "Для лимита", + "ЭКОИЛЬИЧПРОДУКТ ООО\nна сумму 750 276,8 руб\nОстаток лимита у клиента с учётом текущей задолженности 2 656 689,12 руб"), + }, + } + } + + return topicMigrationData{ + categoryCode: "shipments_soh", + categoryName: "Отгрузки на СОХ", + topicCode: "shipments_soh", + topicName: "Отгрузки на СОХ", + requiresFile: true, + isTreeRoot: true, + // Шаблон сообщения + messageTemplate: `📋 Отгрузки на СОХ — {{.region_label}} ({{.shipment_type_label}}) + +{{.initiator_name}}: +{{.content}}`, + + // Код формируется из region и shipment_type + codeTemplate: `shipments_soh_{{.region}}_{{.shipment_type}}`, + + // Дерево узлов + nodes: []*typescore.ApprovalFlowNode{ + // Корневой узел + &typescore.ApprovalFlowNode{ + Key: strPtr("shipments_soh"), + Label: strPtr("Отгрузки на СОХ"), + Children: []*typescore.ApprovalFlowNode{ + buildRegion("crimea", "Крым"), + buildRegion("krasnodar", "Краснодар"), + }, + }, + }, + } +} + +// getTransactionPassportData — миграция темы "Паспорт сделки" +func getTransactionPassportData() topicMigrationData { + + // Вспомогательная функция для создания ветки региона + buildRegion := func(regionKey, regionLabel, hint string) *typescore.ApprovalFlowNode { + return &typescore.ApprovalFlowNode{ + Key: strPtr(regionKey), + Label: strPtr(regionLabel), + DataKey: strPtr("region"), + DataValue: strPtr(regionKey), + Children: []*typescore.ApprovalFlowNode{ + mkInput(regionKey+"_input", regionLabel, "content", hint), + }, + } + } + + return topicMigrationData{ + categoryCode: "transaction_passport", + categoryName: "Паспорт сделки", + topicCode: "transaction_passport", + topicName: "Паспорт сделки", + requiresFile: true, // 🆕 Transaction passport требует файл + isTreeRoot: true, + // Шаблон сообщения + messageTemplate: `📋 Паспорт сделки — {{.region_label}} + +{{.initiator_name}}: +{{.content}}`, + + // Код формируется из region + codeTemplate: `transaction_passport_{{.region}}`, + + // Дерево узлов + nodes: []*typescore.ApprovalFlowNode{ + // Корневой узел + &typescore.ApprovalFlowNode{ + Key: strPtr("transaction_passport"), + Label: strPtr("Паспорт сделки"), + Children: []*typescore.ApprovalFlowNode{ + buildRegion("krasnodar", "Краснодар", "Текст для паспорта сделки (Краснодар)"), + buildRegion("crimea", "Крым", "Текст для паспорта сделки (Крым)"), + buildRegion("belarus", "Беларусь", "Текст для паспорта сделки (Беларусь)"), + }, + }, + }, + } +} + +// getAllFreeTopicsData возвращает данные для всех free-тем +func getAllFreeTopicsData() []topicMigrationData { + freeTopics := []struct { + code string + name string + template string + instructions string + firstApproverRoleCode string + allowApproverSelection bool + requiresFile bool + requireObserverSelection bool + }{ + {"delivery_clients", "Доставка клиентам/на склад", "Иванов Иван Иванович\nТел 89781234567\nПаспорт 1234 567890\nДАФ н862нн46 п/п АА8473|46\n\n61 бц с ад - 52 кор\nЧП000001676\n\nЕПР-СтройКрым", "", "manager", false, false, false}, + {"v_shipments", "В. Отгрузки", "ООО Нива на 370 тыс. руб. под 19%", "", "", false, false, false}, + {"shipments", "Отгрузки", "", "Если не входит в рамки согласованного лимита, добавь руководителя соответствующего филиала к согласованию через кнопку 'Добавить согласующего'", "", true, false, true}, + {"vacancies", "Вакансии", "", "", "supervisor", false, false, false}, + {"delivery_rates_ap", "Ставки доставки АП", "Прошу согласовать доставку 14 кор преформы клиенту Олег-Выдув-Сочи за 34 000 руб.", "", "", false, false, false}, + {"freelancers_approval", "Утверждение фрилансеров", "Одного помощника на выгрузку полной фуры с крышкой ручкой с КТ на 23.04.2026 на весь день", "", "", false, false, false}, + {"non_working_day", "Выход в нерабочий день", "Прошу вывести склад для учета c 25.04 по 26.04", "", "", false, false, false}, + {"suggestions", "Предложения и пожелания", "", "", "", false, false, false}, + {"cash_balance", "Остаток в кассах", "", "", "supervisor", false, false, false}, + {"client_sales", "Продажи по клиенту", "", "", "manager", true, false, false}, + {"manager_expenses_report", "Проведенные расходы по менеджеру", "", "", "manager", false, false, false}, + {"remote_access", "Согласование удаленной работы", "Прошу согласовать удалённый выход на работу 06.06.2026", "", "", false, false, false}, + } + + var result []topicMigrationData + for _, t := range freeTopics { + hint := "Напишите текст согласования" + if t.template != "" { + hint = t.template + } + + result = append(result, topicMigrationData{ + categoryCode: t.code, + categoryName: t.name, + topicCode: t.code, + topicName: t.name, + instructions: t.instructions, + isTreeRoot: true, + firstApproverRoleCode: t.firstApproverRoleCode, + allowApproverSelection: t.allowApproverSelection, + requiresFile: t.requiresFile, + requireObserverSelection: t.requireObserverSelection, + messageTemplate: `📋 Заявка на согласование + +👤 От: {{.initiator_name}} +📂 Тема: {{.topic_name}} +📝 Текст: +{{.content}}{{if .instructions}} + +💡 Инструкция: +{{.instructions}}{{end}}`, + nodes: []*typescore.ApprovalFlowNode{ + mkInput(t.code+"_input", t.name, "content", hint), + }, + }) + } + + return result +} diff --git a/service/system_service/jobs/init.go b/service/system_service/jobs/init.go index 46b8ca4..ff0731d 100644 --- a/service/system_service/jobs/init.go +++ b/service/system_service/jobs/init.go @@ -1,7 +1,9 @@ package workerjobs import ( + "bitrix_balancer_api/system_service/database_additionally" "bitrix_balancer_api/system_service/types" + "context" "github.com/sirupsen/logrus" ) @@ -19,6 +21,11 @@ func WorkerJobsStart(ipc *types.InternalProviderControl) error { if err != nil { return err } + + err = database_additionally.MigrateTopicsToDB(context.Background(), ipc) + if err != nil { + return err + } logrus.Info("🟢🟢🟢 Database migration completed successfully") } else { logrus.Info("⚠️ production environment variable is set to prod mode. Skip migration") diff --git a/service/telegram_service/approvalflow/dynamic_topic.go b/service/telegram_service/approvalflow/dynamic_topic.go new file mode 100644 index 0000000..5590c0a --- /dev/null +++ b/service/telegram_service/approvalflow/dynamic_topic.go @@ -0,0 +1,489 @@ +package approvalflow + +import ( + "bitrix_balancer_api/core/typescore" + "bytes" + "fmt" + "sort" + "strings" + "text/template" +) + +// DynamicTopic — универсальная тема, загружаемая из БД +type DynamicTopic struct { + dbTopic *typescore.ApprovalTopic + nodes []*typescore.ApprovalFlowNode // плоский список узлов из БД +} + +func NewDynamicTopic(dbTopic *typescore.ApprovalTopic, nodes []*typescore.ApprovalFlowNode) *DynamicTopic { + return &DynamicTopic{ + dbTopic: dbTopic, + nodes: nodes, + } +} + +func (d *DynamicTopic) Code() string { + if d.dbTopic.Code != nil { + return *d.dbTopic.Code + } + return "" +} + +func (d *DynamicTopic) Name() string { + if d.dbTopic.Name != nil { + return *d.dbTopic.Name + } + return "" +} + +// BuildTree строит дерево FlowNode из плоского списка узлов БД +func (d *DynamicTopic) BuildTree() *FlowNode { + if len(d.nodes) == 0 { + return nil + } + + // Создаём map для быстрого доступа + nodeMap := make(map[uint64]*FlowNode) + var root *FlowNode + + // Первый проход: создаём все FlowNode + for _, dbNode := range d.nodes { + if dbNode.ID == nil { + continue + } + + fn := &FlowNode{ + Key: safeString(dbNode.Key), + Label: safeString(dbNode.Label), + DataKey: safeString(dbNode.DataKey), + DataValue: safeString(dbNode.DataValue), + IsInput: safeBool(dbNode.IsInput), + InputKey: safeString(dbNode.InputKey), + InputHint: safeString(dbNode.InputHint), + IsMultiSelect: safeBool(dbNode.IsMultiSelect), + MultiSelectKey: safeString(dbNode.MultiSelectKey), + MultiSelectValue: safeString(dbNode.MultiSelectValue), + TopicCode: safeString(dbNode.TopicCode), + } + nodeMap[*dbNode.ID] = fn + } + + // Второй проход: строим иерархию + for _, dbNode := range d.nodes { + if dbNode.ID == nil { + continue + } + + fn := nodeMap[*dbNode.ID] + + if dbNode.ParentID == nil { + // Корневой узел + root = fn + } else { + // Добавляем к родителю + if parent, ok := nodeMap[*dbNode.ParentID]; ok { + parent.Children = append(parent.Children, fn) + } + } + } + + // Сортируем детей по sort_order + for _, fn := range nodeMap { + sort.Slice(fn.Children, func(i, j int) bool { + // Сортировка уже выполнена на уровне БД, но для безопасности + return fn.Children[i].Key < fn.Children[j].Key + }) + } + + return root +} + +// TopicCodeFromCollected формирует код темы на основе собранных данных +func (d *DynamicTopic) TopicCodeFromCollected(collected map[string]string) (string, error) { + baseCode := d.Code() + + // Если задан шаблон кода — используем его + if d.dbTopic.CodeTemplate != nil && *d.dbTopic.CodeTemplate != "" { + return d.applyCodeTemplate(*d.dbTopic.CodeTemplate, collected) + } + + // Иначе формируем автоматически из всех DataValue + var parts []string + parts = append(parts, baseCode) + + // Сортируем ключи для детерминированности + var keys []string + for k := range collected { + if k != "content" && k != "instructions" { + keys = append(keys, k) + } + } + sort.Strings(keys) + + for _, k := range keys { + v := collected[k] + if v != "" { + parts = append(parts, v) + } + } + + return strings.Join(parts, "_"), nil +} + +func createTemplateFuncMap() template.FuncMap { + return template.FuncMap{ + // Строковые функции + "trimPrefix": strings.TrimPrefix, + "trimSuffix": strings.TrimSuffix, + "toUpper": strings.ToUpper, + "toLower": strings.ToLower, + "replace": strings.ReplaceAll, + + // Функции для работы со списками + "join": func(items []string, sep string) string { + return strings.Join(items, sep) + }, + "split": func(s, sep string) []string { + return strings.Split(s, sep) + }, + + // Условные функции + "eq": func(a, b string) bool { + return a == b + }, + "ne": func(a, b string) bool { + return a != b + }, + "contains": strings.Contains, + "hasPrefix": strings.HasPrefix, + "hasSuffix": strings.HasSuffix, + } +} + +// applyCodeTemplate применяет Go-шаблон для формирования кода +func (d *DynamicTopic) applyCodeTemplate(tmpl string, data map[string]string) (string, error) { + t, err := template.New("code").Funcs(createTemplateFuncMap()).Parse(tmpl) + if err != nil { + return "", fmt.Errorf("parse code template: %w", err) + } + + var buf bytes.Buffer + if err := t.Execute(&buf, data); err != nil { + return "", fmt.Errorf("execute code template: %w", err) + } + + return buf.String(), nil +} + +func (d *DynamicTopic) applyMessageTemplate(tmpl, initiatorName string, data map[string]string) string { + t, err := template.New("message").Funcs(createTemplateFuncMap()).Parse(tmpl) + if err != nil { + return d.defaultMessage(initiatorName, data) + } + + // Создаём map с данными для шаблона + templateData := make(map[string]interface{}) + + // Копируем все данные из collected + for k, v := range data { + templateData[k] = v + } + + // Добавляем стандартные переменные + templateData["initiator_name"] = initiatorName + templateData["topic_name"] = d.Name() + + // Добавляем label-маппинги + d.addLabelMappings(templateData, data) + + var buf bytes.Buffer + if err := t.Execute(&buf, templateData); err != nil { + return d.defaultMessage(initiatorName, data) + } + + return buf.String() +} + +// FormatApproverMessage форматирует сообщение для согласующего +func (d *DynamicTopic) FormatApproverMessage(initiator *typescore.User, collected map[string]string) string { + initiatorName := "—" + if initiator != nil && initiator.FullName != nil { + initiatorName = *initiator.FullName + } + + // Если задан шаблон — используем его + if d.dbTopic.MessageTemplate != nil && *d.dbTopic.MessageTemplate != "" { + // 🆕 Добавляем инструкции в collected, если они есть + if d.dbTopic.Instructions != nil && *d.dbTopic.Instructions != "" { + if collected == nil { + collected = make(map[string]string) + } + collected["instructions"] = *d.dbTopic.Instructions + } + return d.applyMessageTemplate(*d.dbTopic.MessageTemplate, initiatorName, collected) + } + + // Дефолтный шаблон + content := collected["content"] + if content == "" { + content = "—" + } + + return fmt.Sprintf( + "📋 Заявка на согласование\n\n"+ + "👤 От: %s\n"+ + "📂 Тема: %s\n"+ + "📝 Текст:\n%s", + initiatorName, d.Name(), content, + ) +} + +func (d *DynamicTopic) addLabelMappings(templateData map[string]interface{}, data map[string]string) { + // Region labels + if region, ok := data["region"]; ok { + regionLabels := map[string]string{ + "crimea": "Крым", + "krasnodar": "Краснодар", + "belarus": "Беларусь", + } + if label, exists := regionLabels[region]; exists { + templateData["region_label"] = label + } else { + templateData["region_label"] = region + } + } + + // Absence type labels + if absenceType, ok := data["absence_type"]; ok { + absenceLabels := map[string]string{ + "timeoff": "Отгул", + "vacation": "Отпуск", + "sickleave": "Официальный больничный", + } + if label, exists := absenceLabels[absenceType]; exists { + templateData["absence_type_label"] = label + } else { + templateData["absence_type_label"] = absenceType + } + } + + // Change type labels + if changeType, ok := data["change_type"]; ok { + changeLabels := map[string]string{ + "rename": "Поменять название", + "change_manager": "Сменить менеджера", + "new_client": "Внести нового клиента", + } + if label, exists := changeLabels[changeType]; exists { + templateData["change_type_label"] = label + } else { + templateData["change_type_label"] = changeType + } + } + + // Payment type labels + if paymentType, ok := data["payment_type"]; ok { + paymentLabels := map[string]string{ + "own_expense": "за свой счёт", + "vacation_account": "в счёт ежегодного отпуска", + "official": "только официальный больничный", + } + if label, exists := paymentLabels[paymentType]; exists { + templateData["payment_type_label"] = label + } else { + templateData["payment_type_label"] = paymentType + } + } + + // Branch labels + if branch, ok := data["branch"]; ok { + branchLabels := map[string]string{ + "f1": "Ф1", + "f2": "Ф2", + } + if label, exists := branchLabels[branch]; exists { + templateData["branch_label"] = label + } else { + templateData["branch_label"] = branch + } + } + + // Expense type labels + if expenseType, ok := data["expense_type"]; ok { + expenseLabels := map[string]string{ + "tmc": "ТМЦ", + "expense": "Расход", + } + if label, exists := expenseLabels[expenseType]; exists { + templateData["expense_type_label"] = label + } else { + templateData["expense_type_label"] = expenseType + } + } + + // PP required labels + if ppRequired, ok := data["pp_required"]; ok { + ppLabels := map[string]string{ + "yes": "✅ Нужна ПП", + "no": "❌ Не нужна ПП", + } + if label, exists := ppLabels[ppRequired]; exists { + templateData["pp_required_label"] = label + } else { + templateData["pp_required_label"] = ppRequired + } + } + + // Return type labels + if returnType, ok := data["return_type"]; ok { + returnLabels := map[string]string{ + "supplier": "Возврат поставщику", + "other_manager": "Продажа другим менеджером", + "self_sale": "Самостоятельная продажа", + } + if label, exists := returnLabels[returnType]; exists { + templateData["return_type_label"] = label + } else { + templateData["return_type_label"] = returnType + } + } + + // Order type labels + if orderType, ok := data["order_type"]; ok { + orderLabels := map[string]string{ + "monthly": "На месяц", + "additional": "Дополнительный заказ", + } + if label, exists := orderLabels[orderType]; exists { + templateData["order_type_label"] = label + } else { + templateData["order_type_label"] = orderType + } + } + + // Rate type labels + if rateType, ok := data["rate_type"]; ok { + rateLabels := map[string]string{ + "once": "Разово", + "long_term": "Надолго", + } + if label, exists := rateLabels[rateType]; exists { + templateData["rate_type_label"] = label + } else { + templateData["rate_type_label"] = rateType + } + } + + // Shipment type labels + if shipmentType, ok := data["shipment_type"]; ok { + shipmentLabels := map[string]string{ + "real": "Реальная", + "limit": "Для лимита", + } + if label, exists := shipmentLabels[shipmentType]; exists { + templateData["shipment_type_label"] = label + } else { + templateData["shipment_type_label"] = shipmentType + } + } + + // Duration type labels + if durationType, ok := data["duration_type"]; ok { + durationLabels := map[string]string{ + "single_day": "На один день", + "multi_day": "Несколько дней", + "date_range": "Диапазон дат", + "sl_single_day": "На один день", + "sl_date_range": "Диапазон дат", + } + if label, exists := durationLabels[durationType]; exists { + templateData["duration_type_label"] = label + } else { + templateData["duration_type_label"] = durationType + } + } + + // Time type labels + if timeType, ok := data["time_type"]; ok { + timeLabels := map[string]string{ + "full_day": "Весь день", + "partial": "Частично", + } + if label, exists := timeLabels[timeType]; exists { + templateData["time_type_label"] = label + } else { + templateData["time_type_label"] = timeType + } + } + + // Payment category labels + if paymentCategory, ok := data["payment_category"]; ok { + categoryLabels := map[string]string{ + "goods": "Товар", + "misc": "Разное", + } + if label, exists := categoryLabels[paymentCategory]; exists { + templateData["payment_category_label"] = label + } else { + templateData["payment_category_label"] = paymentCategory + } + } + + // Systems labels + if systems, ok := data["systems"]; ok { + templateData["systems_label"] = d.mapSystems(systems) + } +} + +func (d *DynamicTopic) mapSystems(systems string) string { + if systems == "" { + return "не указаны" + } + parts := strings.Split(systems, ",") + var labels []string + for _, p := range parts { + p = strings.TrimSpace(p) + switch p { + case "okb": + labels = append(labels, "ОКБ") + case "1c": + labels = append(labels, "1С") + default: + labels = append(labels, p) + } + } + if len(labels) == 0 { + return "не указаны" + } + return strings.Join(labels, ", ") +} + +// defaultMessage — fallback шаблон при ошибке +func (d *DynamicTopic) defaultMessage(initiatorName string, data map[string]string) string { + content := data["content"] + if content == "" { + content = "—" + } + return fmt.Sprintf( + "📋 Заявка на согласование\n\n"+ + "👤 От: %s\n"+ + "📂 Тема: %s\n"+ + "📝 Текст:\n%s", + initiatorName, d.Name(), content, + ) +} + +// Вспомогательные функции +func safeString(s *string) string { + if s == nil { + return "" + } + return *s +} + +func safeBool(b *bool) bool { + if b == nil { + return false + } + return *b +} diff --git a/service/telegram_service/handlers/approval/handle_multiselect.go b/service/telegram_service/handlers/approval/handle_multiselect.go index fb0908e..11f3164 100644 --- a/service/telegram_service/handlers/approval/handle_multiselect.go +++ b/service/telegram_service/handlers/approval/handle_multiselect.go @@ -76,8 +76,8 @@ func (h *Handler) HandleMultiSelectConfirm(bot *tgbotapi.BotAPI, cq *tgbotapi.Ca chatID := cq.Message.Chat.ID telegramID := cq.From.ID - bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck - bot.Request(tgbotapi.NewDeleteMessage(chatID, cq.Message.MessageID)) //nolint:errcheck + bot.Request(tgbotapi.NewCallback(cq.ID, "")) + bot.Request(tgbotapi.NewDeleteMessage(chatID, cq.Message.MessageID)) flowState, err := h.States.Get(ctx, telegramID) if err != nil || flowState == nil { @@ -87,12 +87,10 @@ func (h *Handler) HandleMultiSelectConfirm(bot *tgbotapi.BotAPI, cq *tgbotapi.Ca selected := flowState.MultiSelected[flowState.MultiSelectNodeKey] if len(selected) == 0 { - // Напоминаем что нужно выбрать хотя бы один вариант - bot.Request(tgbotapi.NewCallback(cq.ID, "⚠️ Выберите хотя бы один вариант")) //nolint:errcheck + bot.Request(tgbotapi.NewCallback(cq.ID, "⚠️ Выберите хотя бы один вариант")) return } - // Сохраняем выбранные значения как строку через запятую в Collected topic, _ := h.Registry.Get(topicCode) if topic == nil { return @@ -103,19 +101,28 @@ func (h *Handler) HandleMultiSelectConfirm(bot *tgbotapi.BotAPI, cq *tgbotapi.Ca return } - // Берём MultiSelectKey из первого дочернего узла if len(node.Children) > 0 { msKey := node.Children[0].MultiSelectKey if msKey != "" { flowState.Collected[msKey] = strings.Join(selected, ",") + + var labels []string + for _, child := range node.Children { + for _, sel := range selected { + if child.MultiSelectValue == sel { + labels = append(labels, child.Label) + break + } + } + } + flowState.Collected[msKey+"_label"] = strings.Join(labels, ", ") } } flowState.AwaitMultiSelectConfirm = false flowState.MultiSelectNodeKey = "" - // Переходим к вводу текста — находим первый input среди детей выбранных узлов - // (InputHint берём из первого выбранного) + // Переходим к вводу текста var inputNode *approvalflow.FlowNode for _, child := range node.Children { for _, sel := range selected { @@ -134,16 +141,16 @@ func (h *Handler) HandleMultiSelectConfirm(bot *tgbotapi.BotAPI, cq *tgbotapi.Ca flowState.InputKey = inputNode.InputKey flowState.NodeKey = flowState.MultiSelectNodeKey - h.States.Set(ctx, telegramID, flowState) //nolint:errcheck + h.States.Set(ctx, telegramID, flowState) hint := fmt.Sprintf("Введите данные по шаблону:\n%s", inputNode.InputHint) msg := tgbotapi.NewMessage(chatID, hint) msg.ParseMode = "HTML" msg.ReplyMarkup = keyboard.BuildApprovalInputPrompt(topicCode) - bot.Send(msg) //nolint:errcheck + bot.Send(msg) return } - h.States.Set(ctx, telegramID, flowState) //nolint:errcheck + h.States.Set(ctx, telegramID, flowState) h.continueFlowAfterInput(bot, ctx, chatID, telegramID, flowState) } diff --git a/service/telegram_service/handlers/approval/handler.go b/service/telegram_service/handlers/approval/handler.go index 8080329..ee4fe2b 100644 --- a/service/telegram_service/handlers/approval/handler.go +++ b/service/telegram_service/handlers/approval/handler.go @@ -2,6 +2,7 @@ package approval import ( "bitrix_balancer_api/core/typescore" + "bitrix_balancer_api/core/variables" "bitrix_balancer_api/telegram_service/approvalflow" "bitrix_balancer_api/telegram_service/keyboard" "bitrix_balancer_api/telegram_service/state" @@ -22,11 +23,20 @@ type Handler struct { } func NewHandler(ipc *types.InternalProviderControl) *Handler { - return &Handler{ + h := &Handler{ ipc: ipc, - Registry: NewRegistry(), + Registry: NewRegistry(ipc), States: state.NewStateManager(ipc.RedisClient), } + + // Загружаем темы из БД при старте + ctx := context.Background() + ctx, _ = context.WithTimeout(ctx, variables.ContextTimeoutLong) + if err := h.Registry.LoadFromDB(ctx); err != nil { + logrus.Errorf("Failed to load topics from DB: %v", err) + } + + return h } // HandleMenu — первая страница меню. @@ -105,8 +115,8 @@ func (h *Handler) HandleCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuer chatID := cq.Message.Chat.ID telegramID := cq.From.ID - bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck - bot.Request(tgbotapi.NewDeleteMessage(chatID, cq.Message.MessageID)) //nolint:errcheck + bot.Request(tgbotapi.NewCallback(cq.ID, "")) + bot.Request(tgbotapi.NewDeleteMessage(chatID, cq.Message.MessageID)) topic, err := h.Registry.Get(topicCode) if err != nil { @@ -142,6 +152,7 @@ func (h *Handler) HandleCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuer if node.DataKey != "" { flowState.Collected[node.DataKey] = node.DataValue + flowState.Collected[node.DataKey+"_label"] = node.Label } if len(node.Children) == 0 && !node.IsInput { @@ -149,28 +160,28 @@ func (h *Handler) HandleCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuer return } - // Единственный ребёнок — input if len(node.Children) == 1 && node.Children[0].IsInput { inputNode := node.Children[0] if inputNode.DataKey != "" { flowState.Collected[inputNode.DataKey] = inputNode.DataValue + flowState.Collected[inputNode.DataKey+"_label"] = inputNode.Label } flowState.AwaitInput = true flowState.InputKey = inputNode.InputKey flowState.NodeKey = nodeKey - h.States.Set(ctx, telegramID, flowState) //nolint:errcheck + h.States.Set(ctx, telegramID, flowState) hint := fmt.Sprintf("Введите данные по шаблону:\n%s", inputNode.InputHint) msg := tgbotapi.NewMessage(chatID, hint) msg.ParseMode = "HTML" msg.ReplyMarkup = keyboard.BuildApprovalInputPrompt(topicCode) - bot.Send(msg) //nolint:errcheck + bot.Send(msg) return } flowState.NodeKey = nodeKey - h.States.Set(ctx, telegramID, flowState) //nolint:errcheck + h.States.Set(ctx, telegramID, flowState) visibleChildren := h.filterNodesByAccess(ctx, telegramID, node.Children) if len(visibleChildren) == 0 { @@ -179,7 +190,6 @@ func (h *Handler) HandleCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuer return } - // Детектируем мультиселект isMultiSelect := len(visibleChildren) > 0 && visibleChildren[0].IsMultiSelect if isMultiSelect { if flowState.MultiSelected == nil { @@ -187,19 +197,19 @@ func (h *Handler) HandleCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuer } flowState.AwaitMultiSelectConfirm = true flowState.MultiSelectNodeKey = nodeKey - h.States.Set(ctx, telegramID, flowState) //nolint:errcheck + h.States.Set(ctx, telegramID, flowState) msg := tgbotapi.NewMessage(chatID, "Выберите системы (можно несколько):") msg.ParseMode = "HTML" msg.ReplyMarkup = keyboard.BuildMultiSelectStep(topicCode, visibleChildren, nil, nil) - bot.Send(msg) //nolint:errcheck + bot.Send(msg) return } msg := tgbotapi.NewMessage(chatID, "Выберите:") msg.ParseMode = "HTML" msg.ReplyMarkup = keyboard.BuildApprovalStep(topicCode, visibleChildren) - bot.Send(msg) //nolint:errcheck + bot.Send(msg) } func (h *Handler) HandleTextInput(bot *tgbotapi.BotAPI, msg *tgbotapi.Message) bool { diff --git a/service/telegram_service/handlers/approval/helper.go b/service/telegram_service/handlers/approval/helper.go index e7ae3c5..f058c31 100644 --- a/service/telegram_service/handlers/approval/helper.go +++ b/service/telegram_service/handlers/approval/helper.go @@ -64,6 +64,7 @@ func (h *Handler) submitApproval(ctx context.Context, bot *tgbotapi.BotAPI, tele Region: flowState.Collected["region"], ChangeType: flowState.Collected["change_type"], Extra: make(map[string]string), + Labels: make(map[string]string), } if systems := flowState.Collected["systems"]; systems != "" { @@ -71,7 +72,16 @@ func (h *Handler) submitApproval(ctx context.Context, bot *tgbotapi.BotAPI, tele } for k, v := range flowState.Collected { - if k != "content" && k != "region" && k != "change_type" && k != "systems" { + if k == "content" { + continue + } + + // Если ключ заканчивается на _label — сохраняем в Labels + if strings.HasSuffix(k, "_label") { + baseKey := strings.TrimSuffix(k, "_label") + metadata.Labels[baseKey] = v + } else if k != "region" && k != "change_type" && k != "systems" { + // Остальные данные — в Extra metadata.Extra[k] = v } } @@ -337,16 +347,20 @@ func (h *Handler) getCollectedFromApproval(ctx context.Context, approval *typesc } if len(meta.SelectedSystems) > 0 { - systemsStr := strings.Join(meta.SelectedSystems, ", ") - collected["target_system"] = systemsStr - collected["target_systems"] = systemsStr + systemsStr := strings.Join(meta.SelectedSystems, ",") collected["systems"] = systemsStr - collected["selected_systems"] = systemsStr + collected["target_systems"] = systemsStr } for k, v := range meta.Extra { collected[k] = v } + + if meta.Labels != nil { + for k, v := range meta.Labels { + collected[k+"_label"] = v + } + } } } @@ -381,17 +395,26 @@ func (h *Handler) getAllowedTopicCodes(ctx context.Context, user *typescore.User } for _, t := range h.Registry.All() { - category, err := h.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByCodeDB(ctx, t.Code()) - if err != nil { - logrus.Warnf("getAllowedTopicCodes: GetApprovalTopicCategoryByCodeDB err=%v", err) - continue - } - if category == nil { - logrus.Warnf("getAllowedTopicCodes: category not found for code=%s", t.Code()) + topicCode := t.Code() + + dbTopic, err := h.ipc.Database.ApprovalTopic.GetApprovalTopicByCodeDB(ctx, topicCode) + if err != nil || dbTopic == nil || dbTopic.CategoryID == nil { continue } - if !allowed[t.Code()] && t.Code() == "absence" { + // Проверяем доступ по категории + if allowedCategoryIDs[*dbTopic.CategoryID] { + allowed[topicCode] = true + continue + } + + // Проверяем доступ по конкретной теме + if allowedTopicIDs[*dbTopic.ID] { + allowed[topicCode] = true + continue + } + + if topicCode == "absence" { childCodes := []string{"timeoff", "vacation", "sickleave"} for _, childCode := range childCodes { childCategory, err := h.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByCodeDB(ctx, childCode) @@ -399,48 +422,13 @@ func (h *Handler) getAllowedTopicCodes(ctx context.Context, user *typescore.User continue } if allowedCategoryIDs[*childCategory.ID] { - allowed[t.Code()] = true + allowed[topicCode] = true break } - // Или по конкретным подтемам - childTopics, _, err := h.ipc.Database.ApprovalTopic.GetApprovalTopicsListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.ApprovalTopic{CategoryID: childCategory.ID}, - }) - if err != nil { - continue - } - for _, ct := range childTopics { - if ct.ID != nil && allowedTopicIDs[*ct.ID] { - allowed[t.Code()] = true - break - } - } - if allowed[t.Code()] { - break - } - } - } - if allowedCategoryIDs[*category.ID] { - allowed[t.Code()] = true - continue - } - - topics, _, err := h.ipc.Database.ApprovalTopic.GetApprovalTopicsListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.ApprovalTopic{CategoryID: category.ID}, - }) - if err != nil { - logrus.Warnf("getAllowedTopicCodes: GetApprovalTopicsListDB err=%v", err) - continue - } - for _, topic := range topics { - if allowedTopicIDs[*topic.ID] { - allowed[t.Code()] = true - break } } } - logrus.Infof("getAllowedTopicCodes: result allowed=%v", allowed) return allowed, nil } diff --git a/service/telegram_service/handlers/approval/list.go b/service/telegram_service/handlers/approval/list.go index 7d7a65c..b864a8f 100644 --- a/service/telegram_service/handlers/approval/list.go +++ b/service/telegram_service/handlers/approval/list.go @@ -16,6 +16,7 @@ func (h *Handler) HandleMyApprovals(bot *tgbotapi.BotAPI, chatID int64, telegram ctx := context.Background() user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID) + if err != nil || user == nil || user.ID == nil { return } diff --git a/service/telegram_service/handlers/approval/registry.go b/service/telegram_service/handlers/approval/registry.go index 795f87e..a856ff1 100644 --- a/service/telegram_service/handlers/approval/registry.go +++ b/service/telegram_service/handlers/approval/registry.go @@ -1,90 +1,91 @@ package approval import ( + "bitrix_balancer_api/core/typescore" "bitrix_balancer_api/telegram_service/approvalflow" - "bitrix_balancer_api/telegram_service/handlers/approval/topics/absence" - clientchanges "bitrix_balancer_api/telegram_service/handlers/approval/topics/client_changes" - "bitrix_balancer_api/telegram_service/handlers/approval/topics/free" - goodsorder "bitrix_balancer_api/telegram_service/handlers/approval/topics/goods_order" - managerexpenses "bitrix_balancer_api/telegram_service/handlers/approval/topics/manager_expenses" - nonbudgetexpenses "bitrix_balancer_api/telegram_service/handlers/approval/topics/non_budget_expenses" - nonbudgetexpensespetline "bitrix_balancer_api/telegram_service/handlers/approval/topics/non_budget_expenses_pet_line" - nonstandardcontract "bitrix_balancer_api/telegram_service/handlers/approval/topics/nonstandard_contract" - otkconditions "bitrix_balancer_api/telegram_service/handlers/approval/topics/otk_conditions" - paymentscashless "bitrix_balancer_api/telegram_service/handlers/approval/topics/payments_cashless" - rateslogistics "bitrix_balancer_api/telegram_service/handlers/approval/topics/rates_logistics" - "bitrix_balancer_api/telegram_service/handlers/approval/topics/receipts" - "bitrix_balancer_api/telegram_service/handlers/approval/topics/returns" - shipmentssoh "bitrix_balancer_api/telegram_service/handlers/approval/topics/shipments_soh" - transactionpassport "bitrix_balancer_api/telegram_service/handlers/approval/topics/transaction_passport" + "bitrix_balancer_api/telegram_service/types" + "context" "fmt" + "sync" ) type Registry struct { + ipc *types.InternalProviderControl topics map[string]approvalflow.Topic order []string topicCodeToCategory map[string]string + + mu sync.RWMutex } -func NewRegistry() *Registry { +func NewRegistry(ipc *types.InternalProviderControl) *Registry { r := &Registry{ + ipc: ipc, topics: make(map[string]approvalflow.Topic), topicCodeToCategory: make(map[string]string), } - r.registerAll() return r } -func (r *Registry) registerAll() { - r.register(absence.NewAbsenceTopic()) - r.register(nonbudgetexpenses.NewNonBudgetExpensesTopic()) - r.register(nonbudgetexpensespetline.NewNonBudgetExpensesPetLineTopic()) - r.register(returns.NewReturnsTopic()) - r.register(clientchanges.NewClientChangesTopic()) - r.register(goodsorder.NewGoodsOrderTopic()) - r.register(shipmentssoh.NewShipmentsSOHTopic()) - r.register(transactionpassport.NewTransactionPassportTopic()) - r.register(rateslogistics.NewRatesLogisticsTopic()) - r.register(receipts.NewReceiptsTopic()) - r.register(paymentscashless.NewPaymentsCashlessTopic()) - r.register(managerexpenses.NewManagerExpensesTopic()) - r.register(nonstandardcontract.NewNonstandardContractTopic()) - r.register(otkconditions.NewOtkConditionsTopic()) +// LoadFromDB загружает все темы из БД +func (r *Registry) LoadFromDB(ctx context.Context) error { + r.mu.Lock() + defer r.mu.Unlock() - r.mapTopicToCategory("timeoff", "absence") - r.mapTopicToCategory("vacation", "absence") - r.mapTopicToCategory("sickleave", "absence") + r.topics = make(map[string]approvalflow.Topic) + r.order = nil - freeTopics := []struct{ code, name, template, instructions string }{ - {"delivery_clients", "Доставка клиентам/на склад", "Иванов Иван Иванович\nТел 89781234567\nПаспорт 1234 567890\nДАФ н862нн46 п/п АА8473|46\n\n61 бц с ад - 52 кор\nЧП000001676\n\nЕПР-СтройКрым", ""}, - {"v_shipments", "В. Отгрузки", "ООО Нива на 370 тыс. руб. под 19%", ""}, - {"shipments", "Отгрузки", "", "Если не входит в рамки согласованного лимита, добавь руководителя соответствующего филиала к согласованию через кнопку 'Добавить согласующего'"}, - {"vacancies", "Вакансии", "", ""}, - {"delivery_rates_ap", "Ставки доставки АП", "Прошу согласовать доставку 14 кор преформы клиенту Олег-Выдув-Сочи за 34 000 руб.", ""}, - {"freelancers_approval", "Утверждение фрилансеров", "Одного помощника на выгрузку полной фуры с крышкой ручкой с КТ на 23.04.2026 на весь день", ""}, - {"non_working_day", "Выход в нерабочий день", "Прошу вывести склад для учета c 25.04 по 26.04", ""}, - {"suggestions", "Предложения и пожелания", "", ""}, - {"cash_balance", "Остаток в кассах", "", ""}, - {"client_sales", "Продажи по клиенту", "", ""}, - {"manager_expenses_report", "Проведенные расходы по менеджеру", "", ""}, - {"remote_access", "Согласование удаленной работы", "Прошу согласовать удалённый выход на работу 06.06.2026", ""}, + topics, _, err := r.ipc.Database.ApprovalTopic.GetApprovalTopicsListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.ApprovalTopic{ + IsActive: boolPtr(true), + }, + }) + if err != nil { + return fmt.Errorf("load topics: %w", err) } - for _, t := range freeTopics { - r.register(free.NewFreeTopic(t.code, t.name, t.template)) + + for _, topic := range topics { + if topic.ID == nil || topic.Code == nil { + continue + } + + nodes, err := r.loadFlowNodes(ctx, *topic.ID) + if err != nil { + continue + } + + if len(nodes) == 0 { + continue + } + + dynamicTopic := approvalflow.NewDynamicTopic(topic, nodes) + topicCode := *topic.Code + r.topics[topicCode] = dynamicTopic + r.order = append(r.order, topicCode) } + + return nil } -func (r *Registry) mapTopicToCategory(topicCode, categoryCode string) { - r.topicCodeToCategory[topicCode] = categoryCode -} +// loadFlowNodes загружает все узлы дерева для темы +func (r *Registry) loadFlowNodes(ctx context.Context, topicID uint64) ([]*typescore.ApprovalFlowNode, error) { + nodes, _, err := r.ipc.Database.ApprovalFlowNode.GetApprovalFlowNodesListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.ApprovalFlowNode{ + TopicID: &topicID, + }, + }) + if err != nil { + return nil, err + } -func (r *Registry) register(t approvalflow.Topic) { - r.topics[t.Code()] = t - r.order = append(r.order, t.Code()) + return nodes, nil } func (r *Registry) Get(code string) (approvalflow.Topic, error) { + r.mu.RLock() + defer r.mu.RUnlock() + if t, ok := r.topics[code]; ok { return t, nil } @@ -99,9 +100,21 @@ func (r *Registry) Get(code string) (approvalflow.Topic, error) { } func (r *Registry) All() []approvalflow.Topic { + r.mu.RLock() + defer r.mu.RUnlock() + result := make([]approvalflow.Topic, 0, len(r.order)) for _, code := range r.order { result = append(result, r.topics[code]) } return result } + +// Reload перезагружает темы из БД +func (r *Registry) Reload(ctx context.Context) error { + return r.LoadFromDB(ctx) +} + +func boolPtr(b bool) *bool { + return &b +}