Compare commits
2 Commits
main
...
test-deplo
| Author | SHA1 | Date |
|---|---|---|
|
|
bd471f8628 | |
|
|
e3fffbeddc |
|
|
@ -34,6 +34,7 @@ type ModuleDB struct {
|
||||||
ApprovalAdditionalObserver *dbcore.ApprovalAdditionalObserverDB
|
ApprovalAdditionalObserver *dbcore.ApprovalAdditionalObserverDB
|
||||||
ApprovalTopicExecutor *dbcore.ApprovalTopicExecutorDB
|
ApprovalTopicExecutor *dbcore.ApprovalTopicExecutorDB
|
||||||
Admin *dbcore.AdminDB
|
Admin *dbcore.AdminDB
|
||||||
|
ApprovalFlowNode *dbcore.ApprovalFlowNodeDB
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewModuleDB(
|
func NewModuleDB(
|
||||||
|
|
@ -84,6 +85,7 @@ func initDBModules(modules *ModuleDB, redisClient *redismodule.ModuleRedis) *Mod
|
||||||
modules.ApprovalAdditionalObserver = dbcore.NewApprovalAdditionalObserverDB(modules.Pool)
|
modules.ApprovalAdditionalObserver = dbcore.NewApprovalAdditionalObserverDB(modules.Pool)
|
||||||
modules.ApprovalTopicExecutor = dbcore.NewApprovalTopicExecutorDB(modules.Pool)
|
modules.ApprovalTopicExecutor = dbcore.NewApprovalTopicExecutorDB(modules.Pool)
|
||||||
modules.Admin = dbcore.NewAdminDB(modules.Pool)
|
modules.Admin = dbcore.NewAdminDB(modules.Pool)
|
||||||
|
modules.ApprovalFlowNode = dbcore.NewApprovalFlowNodeDB(modules.Pool)
|
||||||
|
|
||||||
return modules
|
return modules
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -38,6 +38,7 @@ func (m *MigrationFunctions) migrateTables() error {
|
||||||
tablesmigration.ApprovalAdditionalObserverTableMigrate,
|
tablesmigration.ApprovalAdditionalObserverTableMigrate,
|
||||||
tablesmigration.ApprovalTopicExecutorsTableMigrate,
|
tablesmigration.ApprovalTopicExecutorsTableMigrate,
|
||||||
tablesmigration.AdminsTableMigrate,
|
tablesmigration.AdminsTableMigrate,
|
||||||
|
tablesmigration.ApprovalFlowNodesTableMigrate,
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, migrate := range migrations {
|
for _, migrate := range migrations {
|
||||||
|
|
|
||||||
|
|
@ -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
|
||||||
|
}
|
||||||
|
|
@ -24,6 +24,7 @@ type ApprovalCommentsProvider typescore.ApprovalComment
|
||||||
type LocalSuggestionProvider typescore.Suggestion
|
type LocalSuggestionProvider typescore.Suggestion
|
||||||
type LocalSuggestionMessagesProvider typescore.SuggestionMessage
|
type LocalSuggestionMessagesProvider typescore.SuggestionMessage
|
||||||
type LocalApprovalTopicExecutorProvider typescore.ApprovalTopicExecutor
|
type LocalApprovalTopicExecutorProvider typescore.ApprovalTopicExecutor
|
||||||
|
type LocalApprovalFlowNodeProvider typescore.ApprovalFlowNode
|
||||||
|
|
||||||
func (LocalUserProvider) TableName() string {
|
func (LocalUserProvider) TableName() string {
|
||||||
return dbcoretablenames.TableNameUsers.ToString()
|
return dbcoretablenames.TableNameUsers.ToString()
|
||||||
|
|
@ -82,3 +83,6 @@ func (ApprovalAdditionalObserver) TableName() string {
|
||||||
func (LocalApprovalTopicExecutorProvider) TableName() string {
|
func (LocalApprovalTopicExecutorProvider) TableName() string {
|
||||||
return dbcoretablenames.TableNameApprovalTopicExecutor.ToString()
|
return dbcoretablenames.TableNameApprovalTopicExecutor.ToString()
|
||||||
}
|
}
|
||||||
|
func (LocalApprovalFlowNodeProvider) TableName() string {
|
||||||
|
return dbcoretablenames.TableNameApprovalFlowNodes.ToString()
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -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
|
||||||
|
}
|
||||||
|
|
@ -23,6 +23,7 @@ const (
|
||||||
TableNameSuggestionMessages TableName = "suggestion_messages"
|
TableNameSuggestionMessages TableName = "suggestion_messages"
|
||||||
TableNameApprovalTopicExecutor TableName = "approval_topic_executor"
|
TableNameApprovalTopicExecutor TableName = "approval_topic_executor"
|
||||||
TableNameAdmin TableName = "admin"
|
TableNameAdmin TableName = "admin"
|
||||||
|
TableNameApprovalFlowNodes TableName = "approval_flow_nodes"
|
||||||
)
|
)
|
||||||
|
|
||||||
func (t TableName) ToString() string {
|
func (t TableName) ToString() string {
|
||||||
|
|
|
||||||
|
|
@ -57,7 +57,8 @@ type ApprovalMetadata struct {
|
||||||
// Тип изменения
|
// Тип изменения
|
||||||
ChangeType string `json:"change_type,omitempty"`
|
ChangeType string `json:"change_type,omitempty"`
|
||||||
// Любые другие поля из collected которые нужно сохранить
|
// Любые другие поля из 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) {
|
func (m *ApprovalMetadata) ToJSON() (*string, error) {
|
||||||
|
|
|
||||||
|
|
@ -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"`
|
||||||
|
}
|
||||||
|
|
@ -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"`
|
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"`
|
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"`
|
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"`
|
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"`
|
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"`
|
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"`
|
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"`
|
UpdatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:updated_at" json:"updated_at" db:"updated_at"`
|
||||||
|
|
|
||||||
|
|
@ -11,6 +11,7 @@ import (
|
||||||
authhandler "bitrix_balancer_api/rest_admin_service/handlers/auth"
|
authhandler "bitrix_balancer_api/rest_admin_service/handlers/auth"
|
||||||
dashboardhandler "bitrix_balancer_api/rest_admin_service/handlers/dashboard"
|
dashboardhandler "bitrix_balancer_api/rest_admin_service/handlers/dashboard"
|
||||||
departmentshandler "bitrix_balancer_api/rest_admin_service/handlers/departments"
|
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"
|
permissionshandler "bitrix_balancer_api/rest_admin_service/handlers/permission"
|
||||||
profilehandler "bitrix_balancer_api/rest_admin_service/handlers/profile"
|
profilehandler "bitrix_balancer_api/rest_admin_service/handlers/profile"
|
||||||
roleshandler "bitrix_balancer_api/rest_admin_service/handlers/roles"
|
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},
|
{"permissions", permissionshandler.RegisterPermissionRoutes},
|
||||||
{"approval-tasks", approvaltaskshandler.RegisterApprovalTasksRoutes},
|
{"approval-tasks", approvaltaskshandler.RegisterApprovalTasksRoutes},
|
||||||
{"dashboard", dashboardhandler.RegisterDashboardRoutes},
|
{"dashboard", dashboardhandler.RegisterDashboardRoutes},
|
||||||
|
{"nodes", nodeshandler.RegisterFlowNodesRoutes},
|
||||||
}
|
}
|
||||||
|
|
||||||
// Регистрация всех маршрутов
|
// Регистрация всех маршрутов
|
||||||
|
|
|
||||||
|
|
@ -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)
|
||||||
|
}
|
||||||
|
|
@ -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
|
||||||
|
}
|
||||||
|
|
@ -4,10 +4,14 @@ import (
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"github.com/go-chi/chi/v5"
|
|
||||||
"io"
|
"io"
|
||||||
|
"log"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"reflect"
|
||||||
|
"runtime"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
|
||||||
|
"github.com/go-chi/chi/v5"
|
||||||
)
|
)
|
||||||
|
|
||||||
// ErrorResponse структура для возврата ошибок
|
// ErrorResponse структура для возврата ошибок
|
||||||
|
|
@ -47,15 +51,31 @@ func (rw *responseWriterWrapper) Write(b []byte) (int, error) {
|
||||||
return rw.ResponseWriter.Write(b)
|
return rw.ResponseWriter.Write(b)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func getHandlerInfo(handler interface{}) (name, file string, line int) {
|
||||||
|
fn := runtime.FuncForPC(reflect.ValueOf(handler).Pointer())
|
||||||
|
if fn != nil {
|
||||||
|
name = fn.Name()
|
||||||
|
file, line = fn.FileLine(fn.Entry())
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
// WrapHandlerF обертка для обработчиков
|
// WrapHandlerF обертка для обработчиков
|
||||||
func WrapHandlerF(p WrapHandlerParams) http.HandlerFunc {
|
func WrapHandlerF(p WrapHandlerParams) http.HandlerFunc {
|
||||||
|
// Получаем информацию о хендлере один раз при инициализации
|
||||||
|
handlerName, handlerFile, handlerLine := getHandlerInfo(p.HandlerFunc)
|
||||||
|
|
||||||
return func(w http.ResponseWriter, r *http.Request) {
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
rw := &responseWriterWrapper{ResponseWriter: w}
|
rw := &responseWriterWrapper{ResponseWriter: w}
|
||||||
payload, err := p.HandlerFunc(rw, r)
|
payload, err := p.HandlerFunc(rw, r)
|
||||||
|
|
||||||
// 🆕 Проверяем, не файл ли это
|
if err != nil {
|
||||||
|
log.Printf("[ERROR] handler=%s location=%s:%d method=%s path=%s error=%q",
|
||||||
|
handlerName, handlerFile, handlerLine, r.Method, r.URL.Path, err.Error())
|
||||||
|
}
|
||||||
|
|
||||||
if fileResp, ok := payload.(*ExcelFileResponse); ok && err == nil {
|
if fileResp, ok := payload.(*ExcelFileResponse); ok && err == nil {
|
||||||
serveExcelFile(rw, fileResp)
|
serveExcelFile(rw, fileResp, handlerName, handlerFile, handlerLine, r)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -64,9 +84,7 @@ func WrapHandlerF(p WrapHandlerParams) http.HandlerFunc {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 🆕 serveExcelFile отправляет файл как бинарный ответ
|
func serveExcelFile(w http.ResponseWriter, fileResp *ExcelFileResponse, handlerName, handlerFile string, handlerLine int, r *http.Request) {
|
||||||
func serveExcelFile(w http.ResponseWriter, fileResp *ExcelFileResponse) {
|
|
||||||
// Устанавливаем заголовки ДО отправки тела
|
|
||||||
w.Header().Set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
|
w.Header().Set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
|
||||||
w.Header().Set("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, fileResp.FileName))
|
w.Header().Set("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, fileResp.FileName))
|
||||||
w.Header().Set("Content-Length", strconv.Itoa(len(fileResp.Data)))
|
w.Header().Set("Content-Length", strconv.Itoa(len(fileResp.Data)))
|
||||||
|
|
@ -74,11 +92,9 @@ func serveExcelFile(w http.ResponseWriter, fileResp *ExcelFileResponse) {
|
||||||
|
|
||||||
w.WriteHeader(http.StatusOK)
|
w.WriteHeader(http.StatusOK)
|
||||||
|
|
||||||
// Отправляем содержимое файла
|
|
||||||
if _, err := w.Write(fileResp.Data); err != nil {
|
if _, err := w.Write(fileResp.Data); err != nil {
|
||||||
// Логируем ошибку, но заголовки уже отправлены
|
log.Printf("[ERROR] handler=%s location=%s:%d method=%s path=%s stage=write_file error=%q",
|
||||||
// Можно добавить логгер здесь
|
handlerName, handlerFile, handlerLine, r.Method, r.URL.Path, err.Error())
|
||||||
_ = err
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
File diff suppressed because it is too large
Load Diff
|
|
@ -1,7 +1,9 @@
|
||||||
package workerjobs
|
package workerjobs
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"bitrix_balancer_api/system_service/database_additionally"
|
||||||
"bitrix_balancer_api/system_service/types"
|
"bitrix_balancer_api/system_service/types"
|
||||||
|
"context"
|
||||||
"github.com/sirupsen/logrus"
|
"github.com/sirupsen/logrus"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
@ -19,6 +21,11 @@ func WorkerJobsStart(ipc *types.InternalProviderControl) error {
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
err = database_additionally.MigrateTopicsToDB(context.Background(), ipc)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
logrus.Info("🟢🟢🟢 Database migration completed successfully")
|
logrus.Info("🟢🟢🟢 Database migration completed successfully")
|
||||||
} else {
|
} else {
|
||||||
logrus.Info("⚠️ production environment variable is set to prod mode. Skip migration")
|
logrus.Info("⚠️ production environment variable is set to prod mode. Skip migration")
|
||||||
|
|
|
||||||
|
|
@ -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(
|
||||||
|
"📋 <b>Заявка на согласование</b>\n\n"+
|
||||||
|
"👤 <b>От:</b> %s\n"+
|
||||||
|
"📂 <b>Тема:</b> %s\n"+
|
||||||
|
"📝 <b>Текст:</b>\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(
|
||||||
|
"📋 <b>Заявка на согласование</b>\n\n"+
|
||||||
|
"👤 <b>От:</b> %s\n"+
|
||||||
|
"📂 <b>Тема:</b> %s\n"+
|
||||||
|
"📝 <b>Текст:</b>\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
|
||||||
|
}
|
||||||
|
|
@ -76,8 +76,8 @@ func (h *Handler) HandleMultiSelectConfirm(bot *tgbotapi.BotAPI, cq *tgbotapi.Ca
|
||||||
chatID := cq.Message.Chat.ID
|
chatID := cq.Message.Chat.ID
|
||||||
telegramID := cq.From.ID
|
telegramID := cq.From.ID
|
||||||
|
|
||||||
bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck
|
bot.Request(tgbotapi.NewCallback(cq.ID, ""))
|
||||||
bot.Request(tgbotapi.NewDeleteMessage(chatID, cq.Message.MessageID)) //nolint:errcheck
|
bot.Request(tgbotapi.NewDeleteMessage(chatID, cq.Message.MessageID))
|
||||||
|
|
||||||
flowState, err := h.States.Get(ctx, telegramID)
|
flowState, err := h.States.Get(ctx, telegramID)
|
||||||
if err != nil || flowState == nil {
|
if err != nil || flowState == nil {
|
||||||
|
|
@ -87,12 +87,10 @@ func (h *Handler) HandleMultiSelectConfirm(bot *tgbotapi.BotAPI, cq *tgbotapi.Ca
|
||||||
|
|
||||||
selected := flowState.MultiSelected[flowState.MultiSelectNodeKey]
|
selected := flowState.MultiSelected[flowState.MultiSelectNodeKey]
|
||||||
if len(selected) == 0 {
|
if len(selected) == 0 {
|
||||||
// Напоминаем что нужно выбрать хотя бы один вариант
|
bot.Request(tgbotapi.NewCallback(cq.ID, "⚠️ Выберите хотя бы один вариант"))
|
||||||
bot.Request(tgbotapi.NewCallback(cq.ID, "⚠️ Выберите хотя бы один вариант")) //nolint:errcheck
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// Сохраняем выбранные значения как строку через запятую в Collected
|
|
||||||
topic, _ := h.Registry.Get(topicCode)
|
topic, _ := h.Registry.Get(topicCode)
|
||||||
if topic == nil {
|
if topic == nil {
|
||||||
return
|
return
|
||||||
|
|
@ -103,19 +101,28 @@ func (h *Handler) HandleMultiSelectConfirm(bot *tgbotapi.BotAPI, cq *tgbotapi.Ca
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// Берём MultiSelectKey из первого дочернего узла
|
|
||||||
if len(node.Children) > 0 {
|
if len(node.Children) > 0 {
|
||||||
msKey := node.Children[0].MultiSelectKey
|
msKey := node.Children[0].MultiSelectKey
|
||||||
if msKey != "" {
|
if msKey != "" {
|
||||||
flowState.Collected[msKey] = strings.Join(selected, ",")
|
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.AwaitMultiSelectConfirm = false
|
||||||
flowState.MultiSelectNodeKey = ""
|
flowState.MultiSelectNodeKey = ""
|
||||||
|
|
||||||
// Переходим к вводу текста — находим первый input среди детей выбранных узлов
|
// Переходим к вводу текста
|
||||||
// (InputHint берём из первого выбранного)
|
|
||||||
var inputNode *approvalflow.FlowNode
|
var inputNode *approvalflow.FlowNode
|
||||||
for _, child := range node.Children {
|
for _, child := range node.Children {
|
||||||
for _, sel := range selected {
|
for _, sel := range selected {
|
||||||
|
|
@ -134,16 +141,16 @@ func (h *Handler) HandleMultiSelectConfirm(bot *tgbotapi.BotAPI, cq *tgbotapi.Ca
|
||||||
flowState.InputKey = inputNode.InputKey
|
flowState.InputKey = inputNode.InputKey
|
||||||
flowState.NodeKey = flowState.MultiSelectNodeKey
|
flowState.NodeKey = flowState.MultiSelectNodeKey
|
||||||
|
|
||||||
h.States.Set(ctx, telegramID, flowState) //nolint:errcheck
|
h.States.Set(ctx, telegramID, flowState)
|
||||||
|
|
||||||
hint := fmt.Sprintf("Введите данные по шаблону:\n<code>%s</code>", inputNode.InputHint)
|
hint := fmt.Sprintf("Введите данные по шаблону:\n<code>%s</code>", inputNode.InputHint)
|
||||||
msg := tgbotapi.NewMessage(chatID, hint)
|
msg := tgbotapi.NewMessage(chatID, hint)
|
||||||
msg.ParseMode = "HTML"
|
msg.ParseMode = "HTML"
|
||||||
msg.ReplyMarkup = keyboard.BuildApprovalInputPrompt(topicCode)
|
msg.ReplyMarkup = keyboard.BuildApprovalInputPrompt(topicCode)
|
||||||
bot.Send(msg) //nolint:errcheck
|
bot.Send(msg)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
h.States.Set(ctx, telegramID, flowState) //nolint:errcheck
|
h.States.Set(ctx, telegramID, flowState)
|
||||||
h.continueFlowAfterInput(bot, ctx, chatID, telegramID, flowState)
|
h.continueFlowAfterInput(bot, ctx, chatID, telegramID, flowState)
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -2,6 +2,7 @@ package approval
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"bitrix_balancer_api/core/typescore"
|
"bitrix_balancer_api/core/typescore"
|
||||||
|
"bitrix_balancer_api/core/variables"
|
||||||
"bitrix_balancer_api/telegram_service/approvalflow"
|
"bitrix_balancer_api/telegram_service/approvalflow"
|
||||||
"bitrix_balancer_api/telegram_service/keyboard"
|
"bitrix_balancer_api/telegram_service/keyboard"
|
||||||
"bitrix_balancer_api/telegram_service/state"
|
"bitrix_balancer_api/telegram_service/state"
|
||||||
|
|
@ -22,11 +23,20 @@ type Handler struct {
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewHandler(ipc *types.InternalProviderControl) *Handler {
|
func NewHandler(ipc *types.InternalProviderControl) *Handler {
|
||||||
return &Handler{
|
h := &Handler{
|
||||||
ipc: ipc,
|
ipc: ipc,
|
||||||
Registry: NewRegistry(),
|
Registry: NewRegistry(ipc),
|
||||||
States: state.NewStateManager(ipc.RedisClient),
|
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 — первая страница меню.
|
// HandleMenu — первая страница меню.
|
||||||
|
|
@ -105,8 +115,8 @@ func (h *Handler) HandleCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuer
|
||||||
chatID := cq.Message.Chat.ID
|
chatID := cq.Message.Chat.ID
|
||||||
telegramID := cq.From.ID
|
telegramID := cq.From.ID
|
||||||
|
|
||||||
bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck
|
bot.Request(tgbotapi.NewCallback(cq.ID, ""))
|
||||||
bot.Request(tgbotapi.NewDeleteMessage(chatID, cq.Message.MessageID)) //nolint:errcheck
|
bot.Request(tgbotapi.NewDeleteMessage(chatID, cq.Message.MessageID))
|
||||||
|
|
||||||
topic, err := h.Registry.Get(topicCode)
|
topic, err := h.Registry.Get(topicCode)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|
@ -142,6 +152,7 @@ func (h *Handler) HandleCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuer
|
||||||
|
|
||||||
if node.DataKey != "" {
|
if node.DataKey != "" {
|
||||||
flowState.Collected[node.DataKey] = node.DataValue
|
flowState.Collected[node.DataKey] = node.DataValue
|
||||||
|
flowState.Collected[node.DataKey+"_label"] = node.Label
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(node.Children) == 0 && !node.IsInput {
|
if len(node.Children) == 0 && !node.IsInput {
|
||||||
|
|
@ -149,28 +160,28 @@ func (h *Handler) HandleCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuer
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// Единственный ребёнок — input
|
|
||||||
if len(node.Children) == 1 && node.Children[0].IsInput {
|
if len(node.Children) == 1 && node.Children[0].IsInput {
|
||||||
inputNode := node.Children[0]
|
inputNode := node.Children[0]
|
||||||
if inputNode.DataKey != "" {
|
if inputNode.DataKey != "" {
|
||||||
flowState.Collected[inputNode.DataKey] = inputNode.DataValue
|
flowState.Collected[inputNode.DataKey] = inputNode.DataValue
|
||||||
|
flowState.Collected[inputNode.DataKey+"_label"] = inputNode.Label
|
||||||
}
|
}
|
||||||
flowState.AwaitInput = true
|
flowState.AwaitInput = true
|
||||||
flowState.InputKey = inputNode.InputKey
|
flowState.InputKey = inputNode.InputKey
|
||||||
flowState.NodeKey = nodeKey
|
flowState.NodeKey = nodeKey
|
||||||
|
|
||||||
h.States.Set(ctx, telegramID, flowState) //nolint:errcheck
|
h.States.Set(ctx, telegramID, flowState)
|
||||||
|
|
||||||
hint := fmt.Sprintf("Введите данные по шаблону:\n<code>%s</code>", inputNode.InputHint)
|
hint := fmt.Sprintf("Введите данные по шаблону:\n<code>%s</code>", inputNode.InputHint)
|
||||||
msg := tgbotapi.NewMessage(chatID, hint)
|
msg := tgbotapi.NewMessage(chatID, hint)
|
||||||
msg.ParseMode = "HTML"
|
msg.ParseMode = "HTML"
|
||||||
msg.ReplyMarkup = keyboard.BuildApprovalInputPrompt(topicCode)
|
msg.ReplyMarkup = keyboard.BuildApprovalInputPrompt(topicCode)
|
||||||
bot.Send(msg) //nolint:errcheck
|
bot.Send(msg)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
flowState.NodeKey = nodeKey
|
flowState.NodeKey = nodeKey
|
||||||
h.States.Set(ctx, telegramID, flowState) //nolint:errcheck
|
h.States.Set(ctx, telegramID, flowState)
|
||||||
|
|
||||||
visibleChildren := h.filterNodesByAccess(ctx, telegramID, node.Children)
|
visibleChildren := h.filterNodesByAccess(ctx, telegramID, node.Children)
|
||||||
if len(visibleChildren) == 0 {
|
if len(visibleChildren) == 0 {
|
||||||
|
|
@ -179,7 +190,6 @@ func (h *Handler) HandleCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuer
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// Детектируем мультиселект
|
|
||||||
isMultiSelect := len(visibleChildren) > 0 && visibleChildren[0].IsMultiSelect
|
isMultiSelect := len(visibleChildren) > 0 && visibleChildren[0].IsMultiSelect
|
||||||
if isMultiSelect {
|
if isMultiSelect {
|
||||||
if flowState.MultiSelected == nil {
|
if flowState.MultiSelected == nil {
|
||||||
|
|
@ -187,19 +197,19 @@ func (h *Handler) HandleCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuer
|
||||||
}
|
}
|
||||||
flowState.AwaitMultiSelectConfirm = true
|
flowState.AwaitMultiSelectConfirm = true
|
||||||
flowState.MultiSelectNodeKey = nodeKey
|
flowState.MultiSelectNodeKey = nodeKey
|
||||||
h.States.Set(ctx, telegramID, flowState) //nolint:errcheck
|
h.States.Set(ctx, telegramID, flowState)
|
||||||
|
|
||||||
msg := tgbotapi.NewMessage(chatID, "Выберите системы (можно несколько):")
|
msg := tgbotapi.NewMessage(chatID, "Выберите системы (можно несколько):")
|
||||||
msg.ParseMode = "HTML"
|
msg.ParseMode = "HTML"
|
||||||
msg.ReplyMarkup = keyboard.BuildMultiSelectStep(topicCode, visibleChildren, nil, nil)
|
msg.ReplyMarkup = keyboard.BuildMultiSelectStep(topicCode, visibleChildren, nil, nil)
|
||||||
bot.Send(msg) //nolint:errcheck
|
bot.Send(msg)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
msg := tgbotapi.NewMessage(chatID, "Выберите:")
|
msg := tgbotapi.NewMessage(chatID, "Выберите:")
|
||||||
msg.ParseMode = "HTML"
|
msg.ParseMode = "HTML"
|
||||||
msg.ReplyMarkup = keyboard.BuildApprovalStep(topicCode, visibleChildren)
|
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 {
|
func (h *Handler) HandleTextInput(bot *tgbotapi.BotAPI, msg *tgbotapi.Message) bool {
|
||||||
|
|
|
||||||
|
|
@ -64,6 +64,7 @@ func (h *Handler) submitApproval(ctx context.Context, bot *tgbotapi.BotAPI, tele
|
||||||
Region: flowState.Collected["region"],
|
Region: flowState.Collected["region"],
|
||||||
ChangeType: flowState.Collected["change_type"],
|
ChangeType: flowState.Collected["change_type"],
|
||||||
Extra: make(map[string]string),
|
Extra: make(map[string]string),
|
||||||
|
Labels: make(map[string]string),
|
||||||
}
|
}
|
||||||
|
|
||||||
if systems := flowState.Collected["systems"]; systems != "" {
|
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 {
|
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
|
metadata.Extra[k] = v
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -337,16 +347,20 @@ func (h *Handler) getCollectedFromApproval(ctx context.Context, approval *typesc
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(meta.SelectedSystems) > 0 {
|
if len(meta.SelectedSystems) > 0 {
|
||||||
systemsStr := strings.Join(meta.SelectedSystems, ", ")
|
systemsStr := strings.Join(meta.SelectedSystems, ",")
|
||||||
collected["target_system"] = systemsStr
|
|
||||||
collected["target_systems"] = systemsStr
|
|
||||||
collected["systems"] = systemsStr
|
collected["systems"] = systemsStr
|
||||||
collected["selected_systems"] = systemsStr
|
collected["target_systems"] = systemsStr
|
||||||
}
|
}
|
||||||
|
|
||||||
for k, v := range meta.Extra {
|
for k, v := range meta.Extra {
|
||||||
collected[k] = v
|
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() {
|
for _, t := range h.Registry.All() {
|
||||||
category, err := h.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByCodeDB(ctx, t.Code())
|
topicCode := t.Code()
|
||||||
if err != nil {
|
|
||||||
logrus.Warnf("getAllowedTopicCodes: GetApprovalTopicCategoryByCodeDB err=%v", err)
|
dbTopic, err := h.ipc.Database.ApprovalTopic.GetApprovalTopicByCodeDB(ctx, topicCode)
|
||||||
continue
|
if err != nil || dbTopic == nil || dbTopic.CategoryID == nil {
|
||||||
}
|
|
||||||
if category == nil {
|
|
||||||
logrus.Warnf("getAllowedTopicCodes: category not found for code=%s", t.Code())
|
|
||||||
continue
|
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"}
|
childCodes := []string{"timeoff", "vacation", "sickleave"}
|
||||||
for _, childCode := range childCodes {
|
for _, childCode := range childCodes {
|
||||||
childCategory, err := h.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByCodeDB(ctx, childCode)
|
childCategory, err := h.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByCodeDB(ctx, childCode)
|
||||||
|
|
@ -399,48 +422,13 @@ func (h *Handler) getAllowedTopicCodes(ctx context.Context, user *typescore.User
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
if allowedCategoryIDs[*childCategory.ID] {
|
if allowedCategoryIDs[*childCategory.ID] {
|
||||||
allowed[t.Code()] = true
|
allowed[topicCode] = true
|
||||||
break
|
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
|
return allowed, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -16,6 +16,7 @@ func (h *Handler) HandleMyApprovals(bot *tgbotapi.BotAPI, chatID int64, telegram
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
|
|
||||||
user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID)
|
user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID)
|
||||||
|
|
||||||
if err != nil || user == nil || user.ID == nil {
|
if err != nil || user == nil || user.ID == nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,90 +1,91 @@
|
||||||
package approval
|
package approval
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"bitrix_balancer_api/core/typescore"
|
||||||
"bitrix_balancer_api/telegram_service/approvalflow"
|
"bitrix_balancer_api/telegram_service/approvalflow"
|
||||||
"bitrix_balancer_api/telegram_service/handlers/approval/topics/absence"
|
"bitrix_balancer_api/telegram_service/types"
|
||||||
clientchanges "bitrix_balancer_api/telegram_service/handlers/approval/topics/client_changes"
|
"context"
|
||||||
"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"
|
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"sync"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Registry struct {
|
type Registry struct {
|
||||||
|
ipc *types.InternalProviderControl
|
||||||
topics map[string]approvalflow.Topic
|
topics map[string]approvalflow.Topic
|
||||||
order []string
|
order []string
|
||||||
|
|
||||||
topicCodeToCategory map[string]string
|
topicCodeToCategory map[string]string
|
||||||
|
|
||||||
|
mu sync.RWMutex
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewRegistry() *Registry {
|
func NewRegistry(ipc *types.InternalProviderControl) *Registry {
|
||||||
r := &Registry{
|
r := &Registry{
|
||||||
|
ipc: ipc,
|
||||||
topics: make(map[string]approvalflow.Topic),
|
topics: make(map[string]approvalflow.Topic),
|
||||||
topicCodeToCategory: make(map[string]string),
|
topicCodeToCategory: make(map[string]string),
|
||||||
}
|
}
|
||||||
r.registerAll()
|
|
||||||
return r
|
return r
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *Registry) registerAll() {
|
// LoadFromDB загружает все темы из БД
|
||||||
r.register(absence.NewAbsenceTopic())
|
func (r *Registry) LoadFromDB(ctx context.Context) error {
|
||||||
r.register(nonbudgetexpenses.NewNonBudgetExpensesTopic())
|
r.mu.Lock()
|
||||||
r.register(nonbudgetexpensespetline.NewNonBudgetExpensesPetLineTopic())
|
defer r.mu.Unlock()
|
||||||
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())
|
|
||||||
|
|
||||||
r.mapTopicToCategory("timeoff", "absence")
|
r.topics = make(map[string]approvalflow.Topic)
|
||||||
r.mapTopicToCategory("vacation", "absence")
|
r.order = nil
|
||||||
r.mapTopicToCategory("sickleave", "absence")
|
|
||||||
|
|
||||||
freeTopics := []struct{ code, name, template, instructions string }{
|
topics, _, err := r.ipc.Database.ApprovalTopic.GetApprovalTopicsListDB(ctx, typescore.ListDbOptions{
|
||||||
{"delivery_clients", "Доставка клиентам/на склад", "Иванов Иван Иванович\nТел 89781234567\nПаспорт 1234 567890\nДАФ н862нн46 п/п АА8473|46\n\n61 бц с ад - 52 кор\nЧП000001676\n\nЕПР-СтройКрым", ""},
|
Filtering: &typescore.ApprovalTopic{
|
||||||
{"v_shipments", "В. Отгрузки", "ООО Нива на 370 тыс. руб. под 19%", ""},
|
IsActive: boolPtr(true),
|
||||||
{"shipments", "Отгрузки", "", "Если не входит в рамки согласованного лимита, добавь руководителя соответствующего филиала к согласованию через кнопку 'Добавить согласующего'"},
|
},
|
||||||
{"vacancies", "Вакансии", "", ""},
|
})
|
||||||
{"delivery_rates_ap", "Ставки доставки АП", "Прошу согласовать доставку 14 кор преформы клиенту Олег-Выдув-Сочи за 34 000 руб.", ""},
|
if err != nil {
|
||||||
{"freelancers_approval", "Утверждение фрилансеров", "Одного помощника на выгрузку полной фуры с крышкой ручкой с КТ на 23.04.2026 на весь день", ""},
|
return fmt.Errorf("load topics: %w", err)
|
||||||
{"non_working_day", "Выход в нерабочий день", "Прошу вывести склад для учета c 25.04 по 26.04", ""},
|
|
||||||
{"suggestions", "Предложения и пожелания", "", ""},
|
|
||||||
{"cash_balance", "Остаток в кассах", "", ""},
|
|
||||||
{"client_sales", "Продажи по клиенту", "", ""},
|
|
||||||
{"manager_expenses_report", "Проведенные расходы по менеджеру", "", ""},
|
|
||||||
{"remote_access", "Согласование удаленной работы", "Прошу согласовать удалённый выход на работу 06.06.2026", ""},
|
|
||||||
}
|
}
|
||||||
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) {
|
// loadFlowNodes загружает все узлы дерева для темы
|
||||||
r.topicCodeToCategory[topicCode] = categoryCode
|
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) {
|
return nodes, nil
|
||||||
r.topics[t.Code()] = t
|
|
||||||
r.order = append(r.order, t.Code())
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *Registry) Get(code string) (approvalflow.Topic, error) {
|
func (r *Registry) Get(code string) (approvalflow.Topic, error) {
|
||||||
|
r.mu.RLock()
|
||||||
|
defer r.mu.RUnlock()
|
||||||
|
|
||||||
if t, ok := r.topics[code]; ok {
|
if t, ok := r.topics[code]; ok {
|
||||||
return t, nil
|
return t, nil
|
||||||
}
|
}
|
||||||
|
|
@ -99,9 +100,21 @@ func (r *Registry) Get(code string) (approvalflow.Topic, error) {
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *Registry) All() []approvalflow.Topic {
|
func (r *Registry) All() []approvalflow.Topic {
|
||||||
|
r.mu.RLock()
|
||||||
|
defer r.mu.RUnlock()
|
||||||
|
|
||||||
result := make([]approvalflow.Topic, 0, len(r.order))
|
result := make([]approvalflow.Topic, 0, len(r.order))
|
||||||
for _, code := range r.order {
|
for _, code := range r.order {
|
||||||
result = append(result, r.topics[code])
|
result = append(result, r.topics[code])
|
||||||
}
|
}
|
||||||
return result
|
return result
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Reload перезагружает темы из БД
|
||||||
|
func (r *Registry) Reload(ctx context.Context) error {
|
||||||
|
return r.LoadFromDB(ctx)
|
||||||
|
}
|
||||||
|
|
||||||
|
func boolPtr(b bool) *bool {
|
||||||
|
return &b
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,3 @@
|
||||||
// telegram_service/keyboard/add_approver.go - ПОЛНОСТЬЮ ЗАМЕНИТЬ
|
|
||||||
|
|
||||||
package keyboard
|
package keyboard
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,3 @@
|
||||||
// telegram_service/keyboard/delegation.go - ПОЛНОСТЬЮ ЗАМЕНИТЬ
|
|
||||||
|
|
||||||
package keyboard
|
package keyboard
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue