diff --git a/.golangci.yml b/.golangci.yml
new file mode 100644
index 0000000..ea1405d
--- /dev/null
+++ b/.golangci.yml
@@ -0,0 +1,52 @@
+linters-settings:
+ errcheck: # Настройки для линтера errcheck, который проверяет, что ошибки не игнорируются
+ check-type-assertions: true # Не проверять утверждения типов на ошибки
+ check-blank: true # Проверять игнорирование ошибок через присваивание в _
+ prealloc: # Настройки для линтера prealloc, который предлагает предварительное выделение памяти для срезов
+ simple: true # Простой режим, предлагает предварительное выделение для простых циклов
+ range-loops: true # Предлагает предварительное выделение для циклов range
+ for-loops: false # Не предлагает предварительное выделение для обычных for-циклов
+ gocyclo: # Настройки для линтера gocyclo, который проверяет сложность функций
+ min-complexity: 15 # Установите порог сложности, который считаете приемлемым
+
+linters:
+ enable: # Список линтеров, которые будут включены
+ - noctx # Находит отправку HTTP-запроса без контекста.Контекст.
+ - protogetter # Сообщает о прямом чтении из полей прото-сообщения, когда следует использовать геттеры.
+ - reassign # Проверяет, что переменные пакета не переназначаются.
+ - rowserrcheck # Проверяет, успешно ли проверен Rows.Err строк.
+ - sqlclosecheck # Проверяет, что sql.Rows, sql.Stmt, sqlx.NamedStmt, pgx.Query закрыты.
+ - ineffassign # Обнаруживает, когда назначения существующим переменным не используются.
+ - nilerr # Находит код, который возвращает ноль, даже если он проверяет, что ошибка не равна нулю.
+ - makezero # Проверяет, что нулевые значения создаются правильно
+ - gochecksumtype # Проверяет, что тип контрольной суммы в go.sum соответствует содержимому
+ - copyloopvar # Проверяет, что циклические зависимости пакетов не имеют экспортируемых идентификаторов
+ - exhaustive # Проверьте полноту операторов перечисления.
+ - errchkjson # Проверяет типы, передаваемые функциям кодирования JSON. Сообщает о неподдерживаемых типах и событиях, при которых проверку возвращаемой ошибки можно опустить.
+ - durationcheck # Проверяет, что длительность таймаута не равна 0
+ - contextcheck # Проверяет, что контекст не игнорируется
+ - bodyclose # Проверяет, что тело запроса закрывается
+ - bidichk # Проверяет, что строки в исходном коде не содержат символов из разных языков
+ - govet # Проверяет код на наличие конструкций, которые могут быть ошибочными
+ - errcheck # Проверяет, что ошибки не игнорируются
+ - staticcheck # Статический анализ кода, находит ошибки, неэффективные конструкции и т.д.
+ - unused # Проверяет на неиспользуемые переменные, функции, константы
+ - gocritic # Линтер, основанный на проверке кода на соответствие определенным критериям качества и стиля
+ - stylecheck # Проверяет стиль кодирования
+ - whitespace # Проверяет проблемы с пробелами в коде
+ - gosec # Линтер gosec, который проверяет код на наличие потенциальных уязвимостей
+ - prealloc # Предлагает предварительное выделение памяти для срезов
+
+ - dupl # Находит дублирующийся код
+ - gocyclo # Проверяет сложность функций
+ - ineffassign # Обнаруживает неэффективные присваивания
+ - unparam # Находит неиспользуемые параметры функций
+
+ - gosimple # Предлагает упрощения кода
+
+ disable: # Список линтеров, которые будут отключены
+ - gofumpt # Более строгая версия gofmt, применяет дополнительные правила форматирования
+ # - golint # Отключает golint, который проверяет стиль написания кода на Go
+
+run:
+ timeout: 15m # Устанавливает тайм-аут для выполнения всех линтеров
\ No newline at end of file
diff --git a/.idea/.gitignore b/.idea/.gitignore
new file mode 100644
index 0000000..13566b8
--- /dev/null
+++ b/.idea/.gitignore
@@ -0,0 +1,8 @@
+# Default ignored files
+/shelf/
+/workspace.xml
+# Editor-based HTTP Client requests
+/httpRequests/
+# Datasource local storage ignored files
+/dataSources/
+/dataSources.local.xml
diff --git a/.idea/bitrix_balancer_api.iml b/.idea/bitrix_balancer_api.iml
new file mode 100644
index 0000000..5e764c4
--- /dev/null
+++ b/.idea/bitrix_balancer_api.iml
@@ -0,0 +1,9 @@
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/dataSources.xml b/.idea/dataSources.xml
new file mode 100644
index 0000000..8bb16e6
--- /dev/null
+++ b/.idea/dataSources.xml
@@ -0,0 +1,12 @@
+
+
+
+
+ postgresql
+ true
+ org.postgresql.Driver
+ jdbc:postgresql://localhost:5432/ruspetportal
+ $ProjectFileDir$
+
+
+
\ No newline at end of file
diff --git a/.idea/modules.xml b/.idea/modules.xml
new file mode 100644
index 0000000..9787d09
--- /dev/null
+++ b/.idea/modules.xml
@@ -0,0 +1,8 @@
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/sqldialects.xml b/.idea/sqldialects.xml
new file mode 100644
index 0000000..5c54fcb
--- /dev/null
+++ b/.idea/sqldialects.xml
@@ -0,0 +1,6 @@
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/vcs.xml b/.idea/vcs.xml
new file mode 100644
index 0000000..94a25f7
--- /dev/null
+++ b/.idea/vcs.xml
@@ -0,0 +1,6 @@
+
+
+
+
+
+
\ No newline at end of file
diff --git a/build_core.sh b/build_core.sh
new file mode 100644
index 0000000..673b199
--- /dev/null
+++ b/build_core.sh
@@ -0,0 +1,13 @@
+#!/bin/bash
+
+set -e
+trap 'echo "🔴 Error build core"; exit 1' ERR
+
+THIS_PATH=$(dirname "$(realpath "$0")")
+CORE_PATH="$THIS_PATH/core"
+
+echo "CORE_PATH: $CORE_PATH"
+
+cd "$CORE_PATH"
+go vet ./...
+go mod tidy
\ No newline at end of file
diff --git a/core/.golangci.yml b/core/.golangci.yml
new file mode 100644
index 0000000..ea1405d
--- /dev/null
+++ b/core/.golangci.yml
@@ -0,0 +1,52 @@
+linters-settings:
+ errcheck: # Настройки для линтера errcheck, который проверяет, что ошибки не игнорируются
+ check-type-assertions: true # Не проверять утверждения типов на ошибки
+ check-blank: true # Проверять игнорирование ошибок через присваивание в _
+ prealloc: # Настройки для линтера prealloc, который предлагает предварительное выделение памяти для срезов
+ simple: true # Простой режим, предлагает предварительное выделение для простых циклов
+ range-loops: true # Предлагает предварительное выделение для циклов range
+ for-loops: false # Не предлагает предварительное выделение для обычных for-циклов
+ gocyclo: # Настройки для линтера gocyclo, который проверяет сложность функций
+ min-complexity: 15 # Установите порог сложности, который считаете приемлемым
+
+linters:
+ enable: # Список линтеров, которые будут включены
+ - noctx # Находит отправку HTTP-запроса без контекста.Контекст.
+ - protogetter # Сообщает о прямом чтении из полей прото-сообщения, когда следует использовать геттеры.
+ - reassign # Проверяет, что переменные пакета не переназначаются.
+ - rowserrcheck # Проверяет, успешно ли проверен Rows.Err строк.
+ - sqlclosecheck # Проверяет, что sql.Rows, sql.Stmt, sqlx.NamedStmt, pgx.Query закрыты.
+ - ineffassign # Обнаруживает, когда назначения существующим переменным не используются.
+ - nilerr # Находит код, который возвращает ноль, даже если он проверяет, что ошибка не равна нулю.
+ - makezero # Проверяет, что нулевые значения создаются правильно
+ - gochecksumtype # Проверяет, что тип контрольной суммы в go.sum соответствует содержимому
+ - copyloopvar # Проверяет, что циклические зависимости пакетов не имеют экспортируемых идентификаторов
+ - exhaustive # Проверьте полноту операторов перечисления.
+ - errchkjson # Проверяет типы, передаваемые функциям кодирования JSON. Сообщает о неподдерживаемых типах и событиях, при которых проверку возвращаемой ошибки можно опустить.
+ - durationcheck # Проверяет, что длительность таймаута не равна 0
+ - contextcheck # Проверяет, что контекст не игнорируется
+ - bodyclose # Проверяет, что тело запроса закрывается
+ - bidichk # Проверяет, что строки в исходном коде не содержат символов из разных языков
+ - govet # Проверяет код на наличие конструкций, которые могут быть ошибочными
+ - errcheck # Проверяет, что ошибки не игнорируются
+ - staticcheck # Статический анализ кода, находит ошибки, неэффективные конструкции и т.д.
+ - unused # Проверяет на неиспользуемые переменные, функции, константы
+ - gocritic # Линтер, основанный на проверке кода на соответствие определенным критериям качества и стиля
+ - stylecheck # Проверяет стиль кодирования
+ - whitespace # Проверяет проблемы с пробелами в коде
+ - gosec # Линтер gosec, который проверяет код на наличие потенциальных уязвимостей
+ - prealloc # Предлагает предварительное выделение памяти для срезов
+
+ - dupl # Находит дублирующийся код
+ - gocyclo # Проверяет сложность функций
+ - ineffassign # Обнаруживает неэффективные присваивания
+ - unparam # Находит неиспользуемые параметры функций
+
+ - gosimple # Предлагает упрощения кода
+
+ disable: # Список линтеров, которые будут отключены
+ - gofumpt # Более строгая версия gofmt, применяет дополнительные правила форматирования
+ # - golint # Отключает golint, который проверяет стиль написания кода на Go
+
+run:
+ timeout: 15m # Устанавливает тайм-аут для выполнения всех линтеров
\ No newline at end of file
diff --git a/core/config/config-load-options.go b/core/config/config-load-options.go
new file mode 100644
index 0000000..4d25563
--- /dev/null
+++ b/core/config/config-load-options.go
@@ -0,0 +1,17 @@
+package configcore
+
+// ExposedServiceOptions определяет, какие сервисы нужно загружать
+type ExposedServiceOptions struct {
+ TelegramService bool
+ RESTBaseService bool
+}
+
+// ConfigLoadOptions определяет, какие группы конфигурации нужно загружать
+type ConfigLoadOptions struct {
+ Redis bool
+ Database bool
+ Bitrix bool
+ Secrets bool
+ Telegram bool
+ Server ExposedServiceOptions
+}
diff --git a/core/config/config-types.go b/core/config/config-types.go
new file mode 100644
index 0000000..ae82153
--- /dev/null
+++ b/core/config/config-types.go
@@ -0,0 +1,93 @@
+package configcore
+
+// RedisConfig конфигурация Redis
+type RedisConfig struct {
+ Host string `yaml:"host" env-required:"true"`
+ Port int `yaml:"port" env-required:"true"`
+ User string `yaml:"user" env-required:"true"`
+ Password string `yaml:"password" env-required:"true"`
+}
+
+// DatabaseConfig конфигурация базы данных
+type DatabaseConfig struct {
+ Host string `yaml:"host" env-required:"true"`
+ User string `yaml:"user" env-required:"true"`
+ Password string `yaml:"password" env-required:"true"`
+ DB string `yaml:"methods" env-required:"true"`
+ Port int `yaml:"port" env-required:"true"`
+ SSL string `yaml:"ssl" env-required:"true" default:"disable"`
+}
+
+// TelegramConfig конфигурация Telegram
+type TelegramConfig struct {
+ BotToken string `yaml:"bot_token"`
+ WebAppUrl string `yaml:"web_app_url"`
+}
+
+// ServiceConfig конфигурация сервиса
+type ServiceConfig struct {
+ Host string `yaml:"host" env-required:"true"`
+ Port int `yaml:"port" env-required:"true"`
+}
+
+// CorsConfig конфигурация CORS
+type CorsConfig struct {
+ AllowedOrigins []string `yaml:"allowed_origins"`
+}
+
+// SwaggerConfig конфигурация Swagger
+type SwaggerConfig struct {
+ User string `yaml:"user" env-required:"true"`
+ Pass string `yaml:"pass" env-required:"true"`
+}
+
+// RestServiceConfig конфигурация REST сервиса
+type RestServiceConfig struct {
+ PortRest int `yaml:"port_rest" env-required:"true"`
+ BindRest string `yaml:"bind_rest" env-required:"true"`
+ PortSocket int `yaml:"port_socket" env-required:"true"`
+ Cors CorsConfig `yaml:"cors"`
+ Swagger SwaggerConfig `yaml:"swagger"`
+ Internal string `yaml:"internally"`
+ MaxHttpBufferSize int64 `yaml:"max_http_buffer_size"`
+ MessageTimeout int64 `yaml:"message_timeout"`
+}
+
+// GrpcServiceConfig конфигурация gRPC сервиса
+type GrpcServiceConfig struct {
+ GrpcPort int `yaml:"grpc_port" env-required:"true"`
+ CertFileName string
+}
+
+type Server struct {
+ RESTBaseService RestServiceConfig `yaml:"rest_base_service"`
+ Telegram GrpcServiceConfig `yaml:"telegram_service"`
+}
+
+type Bitrix struct {
+ PortalID string `yaml:"portal_id"`
+ IsEnterprise bool `yaml:"is_enterprise"`
+}
+
+type Service struct {
+ Bind string `yaml:"bind"`
+ Port int `yaml:"port"`
+ Internal string `yaml:"internally"`
+ MaxHttpBufferSize int64 `yaml:"max_http_buffer_size"`
+ MessageTimeout int64 `yaml:"message_timeout"`
+}
+
+// SecretsConfig конфигурация секретов
+type SecretsConfig struct {
+ ApiPublicBase string `yaml:"api_public_base"`
+ ApiPrivateBase string `yaml:"api_private_base"`
+}
+
+type Config struct {
+ Redis RedisConfig `yaml:"redis"`
+ Database DatabaseConfig `yaml:"database"`
+ Telegram TelegramConfig `yaml:"telegram"`
+ Server Server `yaml:"server"`
+ Secrets SecretsConfig `yaml:"secrets"`
+ Bitrix Bitrix `yaml:"bitrix"`
+}
diff --git a/core/config/config.example.yml b/core/config/config.example.yml
new file mode 100644
index 0000000..544b125
--- /dev/null
+++ b/core/config/config.example.yml
@@ -0,0 +1,28 @@
+redis:
+ addr: ""
+ username: ""
+ password: "" # Password for the Redis server (if required)
+ port: 0 # Redis server port, default is 6379
+ db: 0
+secrets:
+ api_public_base: "test"
+ api_private_base: "testtest"
+bitrix:
+ portal_id: ""
+ is_enterprise: false
+database:
+ host: "localhost"
+ port: 5432
+ methods: "ruspetportal"
+ user: "postgres"
+ password: "root"
+telegram: # Telegram settings
+ bot_token: "19191919191:******-******************" # Telegram bot token
+ web_app_url: "https://google.com/"# Telegram web app URL
+server:
+ rest_base_service: # Base service address
+ bind_rest: "0.0.0.0"
+ port_rest: 15000
+ internal: "rest_base_service_balancer_c"
+ telegram_service:
+ grpc_port: 4553
\ No newline at end of file
diff --git a/core/config/config.yml b/core/config/config.yml
new file mode 100644
index 0000000..418ebaf
--- /dev/null
+++ b/core/config/config.yml
@@ -0,0 +1,28 @@
+redis:
+ addr: "127.0.0.1" # Redis server address, typically 'localhost' or a remote server IP
+ username: "" # Username for the Redis server (if required)
+ password: "" # Password for the Redis server (if required)
+ port: 6379 # Redis server port, default is 6379
+ db: 0
+bitrix:
+ portal_id: "thebest"
+ is_enterprise: false
+database:
+ host: "localhost" # 72.56.235.246
+ port: 5432
+ methods: "ruspetportal"
+ user: "postgres"
+ password: "root"
+telegram: # Telegram settings
+ bot_token: "8581818011:AAGq7kx2N0BL5CSYkPMZjtXWeB9xvJgOK8U" # Telegram bot token
+ web_app_url: "https://google.com/"# Telegram web app URL
+secrets:
+ api_public_base: "test"
+ api_private_base: "testtest"
+server:
+ rest_base_service: # Base service address
+ bind_rest: "0.0.0.0"
+ port_rest: 15000
+ internal: "rest_base_service_balancer_c"
+ telegram_service:
+ grpc_port: 4553
diff --git a/core/config/configcore.go b/core/config/configcore.go
new file mode 100644
index 0000000..f80c7c5
--- /dev/null
+++ b/core/config/configcore.go
@@ -0,0 +1,64 @@
+package configcore
+
+import (
+ cfgldrlib "bitrix_balancer_api/core/lib/internally/config-loader"
+ _ "embed"
+ "errors"
+ "fmt"
+)
+
+//go:embed config.yml
+var configYML string
+
+// LoadConfig загружает конфигурацию из встраиваемого YAML файла
+func LoadConfig(options *ConfigLoadOptions) (*Config, error) {
+ params := &cfgldrlib.ConfigLoaders{
+ ConfigYml: &configYML,
+ }
+
+ var fullConfig Config
+ config, err := cfgldrlib.LoadConfig[Config](params)
+ if err != nil {
+ return nil, errors.New(fmt.Sprintf("failed to load config using cfg-ldr: %v", err))
+ }
+ fullConfig = *config
+ result := &Config{}
+ copyConfigFields(options, &fullConfig, result)
+
+ return result, nil
+}
+
+// copyConfigFields копирует поля из source в target на основе опций options
+func copyConfigFields(options *ConfigLoadOptions, source, target *Config) {
+ // Копируем Redis
+ if options.Redis {
+ target.Redis = source.Redis
+ }
+
+ // Копируем Database
+ if options.Database {
+ target.Database = source.Database
+ }
+
+ // Копируем Telegram
+ if options.Telegram {
+ target.Telegram = source.Telegram
+ }
+
+ // Копируем Bitrix
+ if options.Bitrix {
+ target.Bitrix = source.Bitrix
+ }
+
+ if options.Secrets {
+ target.Secrets = source.Secrets
+ }
+
+ // Копируем ExposedServiceConfig
+ if options.Server.RESTBaseService {
+ target.Server.RESTBaseService = source.Server.RESTBaseService
+ }
+ if options.Server.TelegramService {
+ target.Server.Telegram = source.Server.Telegram
+ }
+}
diff --git a/core/db/db.go b/core/db/db.go
new file mode 100644
index 0000000..8d7d204
--- /dev/null
+++ b/core/db/db.go
@@ -0,0 +1,81 @@
+package database
+
+import (
+ dbmigration "bitrix_balancer_api/core/db/db_migration"
+ dbcore "bitrix_balancer_api/core/db/methods"
+ gormmodule "bitrix_balancer_api/core/lib/external/gorm"
+ pgxpoolmodule "bitrix_balancer_api/core/lib/external/pgxpool"
+ redismodule "bitrix_balancer_api/core/lib/internally/redis"
+ "github.com/jackc/pgx/v5/pgxpool"
+ "gorm.io/gorm"
+)
+
+type ModuleDB struct {
+ Pool *pgxpool.Pool
+ gormDB *gorm.DB
+
+ User *dbcore.UserDB
+ Approval *dbcore.ApprovalDB
+ ApprovalFile *dbcore.ApprovalFileDB
+ ApprovalStep *dbcore.ApprovalStepDB
+ ApprovalTopic *dbcore.ApprovalTopicDB
+ ApprovalTopicCategory *dbcore.ApprovalTopicCategoryDB
+ Department *dbcore.DepartmentDB
+ Permission *dbcore.PermissionDB
+ Role *dbcore.RoleDB
+ UserRole *dbcore.UserRoleDB
+ UserHierarchy *dbcore.UserHierarchyDB
+ ApprovalDelegation *dbcore.ApprovalDelegationDB
+ ApprovalAdditionalApprover *dbcore.ApprovalAdditionalApproverDB
+ ApprovalTasks *dbcore.ApprovalTaskDB
+}
+
+func NewModuleDB(
+ config *pgxpoolmodule.ConfigConnectPgxPool,
+ redisClient *redismodule.ModuleRedis,
+) (*ModuleDB, error) {
+ pool, err := pgxpoolmodule.ConnectDB(config)
+ if err != nil {
+ return nil, err
+ }
+
+ gormDataBase, _, err := gormmodule.GormDatabaseConnect(&gormmodule.ConfigConnectGorm{
+ Host: config.Host,
+ Port: config.Port,
+ User: config.User,
+ Password: config.Password,
+ Name: config.Name,
+ SslMode: config.SSLMode,
+ })
+ if err != nil {
+ return nil, err
+ }
+
+ moduleDB := &ModuleDB{Pool: pool, gormDB: gormDataBase}
+ moduleDB = initDBModules(moduleDB, redisClient)
+
+ return moduleDB, nil
+}
+
+func initDBModules(modules *ModuleDB, redisClient *redismodule.ModuleRedis) *ModuleDB {
+ modules.User = dbcore.NewUserDB(modules.Pool)
+ modules.Approval = dbcore.NewApprovalDB(modules.Pool)
+ modules.ApprovalStep = dbcore.NewApprovalStepDB(modules.Pool)
+ modules.ApprovalTopic = dbcore.NewApprovalTopicDB(modules.Pool)
+ modules.ApprovalTopicCategory = dbcore.NewApprovalTopicCategoryDB(modules.Pool)
+ modules.Department = dbcore.NewDepartmentDB(modules.Pool)
+ modules.Permission = dbcore.NewPermissionDB(modules.Pool)
+ modules.Role = dbcore.NewRoleDB(modules.Pool)
+ modules.UserHierarchy = dbcore.NewUserHierarchyDB(modules.Pool)
+ modules.UserRole = dbcore.NewUserRoleDB(modules.Pool)
+ modules.ApprovalFile = dbcore.NewApprovalFileDB(modules.Pool)
+ modules.ApprovalDelegation = dbcore.NewApprovalDelegationDB(modules.Pool)
+ modules.ApprovalAdditionalApprover = dbcore.NewApprovalAdditionalApproverDB(modules.Pool)
+ modules.ApprovalTasks = dbcore.NewApprovalTaskDB(modules.Pool)
+
+ return modules
+}
+
+func (m *ModuleDB) Migrate() *dbmigration.MigrationFunctions {
+ return dbmigration.NewMigrationFunctions(m.Pool, m.gormDB)
+}
diff --git a/core/db/db_migration/0_init.go b/core/db/db_migration/0_init.go
new file mode 100644
index 0000000..b2a15b3
--- /dev/null
+++ b/core/db/db_migration/0_init.go
@@ -0,0 +1,37 @@
+package dbmigration
+
+import (
+ gormmodule "bitrix_balancer_api/core/lib/external/gorm"
+ "github.com/jackc/pgx/v5/pgxpool"
+ "github.com/sirupsen/logrus"
+ "gorm.io/gorm"
+)
+
+type MigrationFunctions struct {
+ pool *pgxpool.Pool
+ gormDB *gorm.DB
+}
+
+func NewMigrationFunctions(pool *pgxpool.Pool, gorm *gorm.DB) *MigrationFunctions {
+ return &MigrationFunctions{
+ pool: pool,
+ gormDB: gorm,
+ }
+}
+
+func (m *MigrationFunctions) MigrateDB() error {
+ m.DropAllTriggers()
+
+ err := m.migrateTables()
+ if err != nil {
+ return err
+ }
+
+ m.TriggerMigrations()
+ m.DefaultDataSet()
+ // Закрытие соединения с базой данных
+ gormmodule.GormDatabaseDisconnect()
+
+ logrus.Info("🟢🟢🟢 Database migration completed successfully")
+ return nil
+}
diff --git a/core/db/db_migration/common.go b/core/db/db_migration/common.go
new file mode 100644
index 0000000..16b0ba0
--- /dev/null
+++ b/core/db/db_migration/common.go
@@ -0,0 +1,21 @@
+package dbmigration
+
+import (
+ "fmt"
+ "gorm.io/gorm"
+ "strings"
+)
+
+func CreateEnumType(db *gorm.DB, typeName string, values []string, comment string) error {
+ valuesStr := "'" + strings.Join(values, "', '") + "'"
+ createQuery := fmt.Sprintf(`
+ DO $$
+ BEGIN
+ IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = '%s') THEN
+ CREATE TYPE %s AS ENUM (%s);
+ COMMENT ON TYPE %s IS '%s';
+ END IF;
+ END $$;
+ `, typeName, typeName, valuesStr, typeName, comment)
+ return db.Exec(createQuery).Error
+}
diff --git a/core/db/db_migration/default_data.go b/core/db/db_migration/default_data.go
new file mode 100644
index 0000000..04f2ce8
--- /dev/null
+++ b/core/db/db_migration/default_data.go
@@ -0,0 +1,315 @@
+package dbmigration
+
+import (
+ "bitrix_balancer_api/core/typescore"
+ _ "embed"
+ "encoding/csv"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "reflect"
+ "regexp"
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/mitchellh/mapstructure"
+ "github.com/shopspring/decimal"
+ "github.com/sirupsen/logrus"
+ "gorm.io/gorm"
+)
+
+//go:embed default_data/approval_topic_categories.csv
+var approvalCategoriesCSV string
+
+//go:embed default_data/approval_topics.csv
+var approvalTopicsCSV string
+
+// identifierRe is compiled once and reused across all sanitizeIdentifier calls.
+var identifierRe = regexp.MustCompile(`[^a-z0-9_]`)
+
+// timeFormats lists candidate layouts tried in order when parsing a CSV time cell.
+var timeFormats = []string{
+ "2006-01-02 15:04:05.999999",
+ "2006-01-02 15:04:05",
+ "2006-01-02T15:04:05Z",
+ "2006-01-02T15:04:05.999Z",
+ "2006-01-02",
+}
+
+// dataEntry associates a table name, its model type, and its embedded CSV source.
+type dataEntry struct {
+ table string
+ model interface{}
+ csv string
+}
+
+// defaultDataEntries defines the ordered list of tables to seed.
+// Adding a new table only requires appending one entry here.
+var defaultDataEntries = []dataEntry{
+ {"approval_topic_categories", &typescore.ApprovalTopicCategory{}, approvalCategoriesCSV},
+ {"approval_topics", &typescore.ApprovalTopic{}, approvalTopicsCSV},
+}
+
+// DefaultDataSet seeds every table defined in defaultDataEntries.
+// It attempts all tables and returns a combined error if any fail.
+func (m *MigrationFunctions) DefaultDataSet() error {
+ if m.gormDB == nil {
+ return fmt.Errorf("DefaultDataSet: gormDB is nil")
+ }
+
+ logrus.Infof("🚀 Start db default data set: %s", time.Now().UTC())
+
+ var errs []error
+ for _, entry := range defaultDataEntries {
+ if err := m.seedTable(entry); err != nil {
+ logrus.Errorf("❌ seeding table %q: %v", entry.table, err)
+ errs = append(errs, fmt.Errorf("table %q: %w", entry.table, err))
+ }
+ }
+
+ return errors.Join(errs...)
+}
+
+// seedTable handles the full pipeline for a single table:
+// parse CSV → build field index → map to structs → upsert.
+func (m *MigrationFunctions) seedTable(entry dataEntry) error {
+ headers, records, err := readCSV(entry.csv)
+ if err != nil {
+ return fmt.Errorf("reading CSV: %w", err)
+ }
+
+ fieldIndex := buildFieldIndexMap(entry.model)
+
+ objects, err := mapRecordsToStructs(headers, records, fieldIndex, entry.model)
+ if err != nil {
+ return fmt.Errorf("mapping records: %w", err)
+ }
+
+ return m.upsertRecords(entry.table, objects)
+}
+
+// buildFieldIndexMap returns a map of sanitized db-tag → struct field index.
+func buildFieldIndexMap(model interface{}) map[string]int {
+ t := reflect.TypeOf(model).Elem()
+ index := make(map[string]int, t.NumField())
+ for i := range t.NumField() {
+ if tag := sanitizeIdentifier(t.Field(i).Tag.Get("db")); tag != "" {
+ index[tag] = i
+ }
+ }
+ return index
+}
+
+// mapRecordsToStructs converts raw CSV rows into a slice of model instances.
+func mapRecordsToStructs(
+ headers []string,
+ records [][]string,
+ fieldIndex map[string]int,
+ model interface{},
+) ([]interface{}, error) {
+ modelType := reflect.TypeOf(model).Elem()
+ results := make([]interface{}, 0, len(records))
+
+ for _, record := range records {
+ data := make(map[string]interface{}, len(headers))
+
+ for i, raw := range headers {
+ key := sanitizeIdentifier(raw)
+ if record[i] == "" {
+ continue
+ }
+ idx, ok := fieldIndex[key]
+ if !ok {
+ logrus.Errorf("❌ CSV column %q has no matching db tag in %s", key, modelType.Name())
+ continue
+ }
+ data[key] = convertType(key, record[i], modelType.Field(idx).Type)
+ }
+
+ // reflect.New returns a *T; pass it directly so mapstructure decodes into *T,
+ // not into a double pointer (**T).
+ obj := reflect.New(modelType).Interface()
+ dec, err := mapstructure.NewDecoder(&mapstructure.DecoderConfig{
+ TagName: "db",
+ Result: obj,
+ })
+ if err != nil {
+ return nil, fmt.Errorf("creating decoder: %w", err)
+ }
+ if err := dec.Decode(data); err != nil {
+ logrus.Errorf("❌ decoding CSV record into %s: %v", modelType.Name(), err)
+ continue
+ }
+ results = append(results, obj)
+ }
+
+ return results, nil
+}
+
+// upsertRecords inserts each object if it doesn't already exist in the given table.
+// Duplicate-key conflicts are silently skipped; all other errors are logged and collected.
+func (m *MigrationFunctions) upsertRecords(table string, objects []interface{}) error {
+ var errs []error
+ for _, obj := range objects {
+ err := m.gormDB.Table(table).FirstOrCreate(obj).Error
+ switch {
+ case err == nil:
+ // inserted or already existed — nothing to do
+ case errors.Is(err, gorm.ErrDuplicatedKey):
+ logrus.Warnf("⚠️ duplicate key in %q — skipping", table)
+ default:
+ logrus.Errorf("❌ inserting record into %q: %v", table, err)
+ errs = append(errs, err)
+ }
+ }
+ return errors.Join(errs...)
+}
+
+// sanitizeIdentifier lowercases s, trims whitespace, and removes any character
+// that is not a lowercase letter, digit, or underscore.
+func sanitizeIdentifier(s string) string {
+ return identifierRe.ReplaceAllString(strings.ToLower(strings.TrimSpace(s)), "")
+}
+
+// readCSV parses a CSV string and returns the header row and all data rows.
+func readCSV(data string) (headers []string, records [][]string, err error) {
+ r := csv.NewReader(strings.NewReader(data))
+
+ headers, err = r.Read()
+ if err != nil {
+ return nil, nil, fmt.Errorf("reading headers: %w", err)
+ }
+
+ for line := 2; ; line++ {
+ row, err := r.Read()
+ if errors.Is(err, io.EOF) {
+ break
+ }
+ if err != nil {
+ return nil, nil, fmt.Errorf("line %d: %w", line, err)
+ }
+ records = append(records, row)
+ }
+
+ if len(records) == 0 {
+ return nil, nil, errors.New("CSV contains no data rows")
+ }
+ return headers, records, nil
+}
+
+// convertType converts a CSV cell string to the Go type required by the struct field.
+// Pointer fields are handled by wrapping the converted base value.
+func convertType(field, value string, target reflect.Type) interface{} {
+ base := target
+ if base.Kind() == reflect.Ptr {
+ base = base.Elem()
+ }
+
+ result := convertValue(field, value, base)
+
+ if target.Kind() != reflect.Ptr || result == nil {
+ return result
+ }
+
+ // Wrap result in a pointer to base.
+ ptr := reflect.New(base)
+ v := reflect.ValueOf(result)
+ switch {
+ case v.Type().AssignableTo(base):
+ ptr.Elem().Set(v)
+ case v.Type().ConvertibleTo(base):
+ ptr.Elem().Set(v.Convert(base))
+ default:
+ logrus.Errorf("❌ cannot assign %v to *%v for field %q", v.Type(), base, field)
+ return nil
+ }
+ return ptr.Interface()
+}
+
+// convertValue converts value to the concrete (non-pointer) type t.
+func convertValue(field, value string, t reflect.Type) interface{} {
+ switch {
+ case t == reflect.TypeOf(decimal.Decimal{}):
+ d, err := decimal.NewFromString(value)
+ if err != nil {
+ logrus.Errorf("❌ %s → decimal: %v", field, err)
+ return decimal.Zero
+ }
+ return d
+
+ case t == reflect.TypeOf(json.RawMessage{}):
+ return json.RawMessage(value)
+
+ case t == reflect.TypeOf(time.Time{}):
+ return parseTime(field, value)
+
+ case t.Kind() == reflect.Slice, t.Kind() == reflect.Struct, t.Kind() == reflect.Map:
+ return unmarshalJSON(field, value, t)
+
+ default:
+ return convertPrimitive(field, value, t)
+ }
+}
+
+func parseTime(field, value string) time.Time {
+ for _, layout := range timeFormats {
+ if t, err := time.Parse(layout, value); err == nil {
+ return t
+ }
+ }
+ logrus.Errorf("❌ %s: cannot parse %q as time.Time", field, value)
+ return time.Time{}
+}
+
+func unmarshalJSON(field, value string, t reflect.Type) interface{} {
+ target := reflect.New(t).Interface()
+ if err := json.Unmarshal([]byte(value), target); err != nil {
+ logrus.Errorf("❌ %s: JSON unmarshal into %s: %v", field, t, err)
+ return reflect.Zero(t).Interface()
+ }
+ return reflect.ValueOf(target).Elem().Interface()
+}
+
+func convertPrimitive(field, value string, t reflect.Type) interface{} {
+ switch t.Kind() {
+ case reflect.String:
+ return value
+
+ case reflect.Bool:
+ b, err := strconv.ParseBool(strings.ToLower(value))
+ if err != nil {
+ logrus.Errorf("❌ %s → bool: %v", field, err)
+ return false
+ }
+ return b
+
+ case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
+ n, err := strconv.ParseInt(value, 10, 64)
+ if err != nil {
+ logrus.Errorf("❌ %s → int: %v", field, err)
+ return reflect.Zero(t).Interface()
+ }
+ return reflect.ValueOf(n).Convert(t).Interface()
+
+ case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
+ n, err := strconv.ParseUint(value, 10, 64)
+ if err != nil {
+ logrus.Errorf("❌ %s → uint: %v", field, err)
+ return reflect.Zero(t).Interface()
+ }
+ return reflect.ValueOf(n).Convert(t).Interface()
+
+ case reflect.Float32, reflect.Float64:
+ n, err := strconv.ParseFloat(value, 64)
+ if err != nil {
+ logrus.Errorf("❌ %s → float: %v", field, err)
+ return reflect.Zero(t).Interface()
+ }
+ return reflect.ValueOf(n).Convert(t).Interface()
+
+ default:
+ return unmarshalJSON(field, value, t)
+ }
+}
diff --git a/core/db/db_migration/default_data/approval_topic_categories.csv b/core/db/db_migration/default_data/approval_topic_categories.csv
new file mode 100644
index 0000000..c55a0a9
--- /dev/null
+++ b/core/db/db_migration/default_data/approval_topic_categories.csv
@@ -0,0 +1,27 @@
+id,name,code,description,is_active,created_at,updated_at
+2,Отпуск,vacation,Отпуск,true,2026-03-19 14:24:15.864523,2026-03-19 14:24:15.864523
+1,Отгул,timeoff,Отгул,true,2026-03-19 14:24:15.864523,2026-03-19 14:24:15.864523
+3,Больничный,sickleave,Больничный,true,2026-03-19 14:24:15.864523,2026-03-19 14:24:15.864523
+19,Альфапэт доставка,alphapet_delivery,"",true,2026-03-27 15:08:35.798487,2026-03-27 15:08:35.798487
+20,В. Отгрузки,v_shipments,"",true,2026-03-27 15:08:35.798487,2026-03-27 15:08:35.798487
+21,Внебюджетные расходы,non_budget_expenses,"",true,2026-03-27 15:08:35.798487,2026-03-27 15:08:35.798487
+22,Внебюджетные расходы ПЭТ Лайн,non_budget_expenses_pet_line,"",true,2026-03-27 15:08:35.798487,2026-03-27 15:08:35.798487
+23,Возвраты,returns,"",true,2026-03-27 15:08:35.798487,2026-03-27 15:08:35.798487
+24,Заведение новых клиентов,new_clients,"",true,2026-03-27 15:08:35.798487,2026-03-27 15:08:35.798487
+25,Заказы. Краснодар,orders_krasnodar,"",true,2026-03-27 15:08:35.798487,2026-03-27 15:08:35.798487
+26,Заказы. Крым,orders_crimea,"",true,2026-03-27 15:08:35.798487,2026-03-27 15:08:35.798487
+27,Менеджерские расходы,manager_expenses,"",true,2026-03-27 15:08:35.798487,2026-03-27 15:08:35.798487
+28,Отгрузки на СОХ,shipments_soh,"",true,2026-03-27 15:08:35.798487,2026-03-27 15:08:35.798487
+29,Отгрузки,shipments,"",true,2026-03-27 15:08:35.798487,2026-03-27 15:08:35.798487
+30,Нестандартные условия договора поставки,nonstandard_contract,"",true,2026-03-27 15:08:35.798487,2026-03-27 15:08:35.798487
+31,Расходы АЛЬФАПЭТ,expenses_alphapet,"",true,2026-03-27 15:08:35.798487,2026-03-27 15:08:35.798487
+32,Расходы склад Гвардейское,expenses_warehouse_gvardeysk,"",true,2026-03-27 15:08:35.798487,2026-03-27 15:08:35.798487
+33,РУСПЭТ ДОСТАВКА + НАПРЯМУЮ К КЛИЕНТУ,ruspet_delivery,"",true,2026-03-27 15:08:35.798487,2026-03-27 15:08:35.798487
+34,Вакансии,vacancies,"",true,2026-03-27 15:08:35.798487,2026-03-27 15:08:35.798487
+37,ПС Беларусь,ps_belarus,"",true,2026-03-27 15:08:35.798487,2026-03-27 15:08:35.798487
+38,ПС Краснодар,ps_krasnodar,"",true,2026-03-27 15:08:35.798487,2026-03-27 15:08:35.798487
+39,ПС Крым,ps_crimea,"",true,2026-03-27 15:08:35.798487,2026-03-27 15:08:35.798487
+40,Ставки доставки АП,delivery_rates_ap,"",true,2026-03-27 15:08:35.798487,2026-03-27 15:08:35.798487
+41,Утверждение оплат безнал,payments_cashless,"",true,2026-03-27 15:08:35.798487,2026-03-27 15:08:35.798487
+43,Утверждение фрилансеров,freelancers_approval,"",true,2026-03-27 15:08:35.798487,2026-03-27 15:08:35.798487
+42,Утверждение ставок,rates_logistics,"",true,2026-03-27 15:08:35.798487,2026-03-27 15:08:35.798487
diff --git a/core/db/db_migration/default_data/approval_topics.csv b/core/db/db_migration/default_data/approval_topics.csv
new file mode 100644
index 0000000..733fbbd
--- /dev/null
+++ b/core/db/db_migration/default_data/approval_topics.csv
@@ -0,0 +1,48 @@
+id,category_id,name,code,duration_type,time_type,payment_type,template,allows_file,is_active,created_at,updated_at
+1,1,"Отгул — несколько дней, частично",timeoff_multi_day_partial_own_expense,multi_day,partial,own_expense,"22.02.2022 с 10:00 по 14:00, 24.02.2022 с 09:00 по 12:00",false,true,2026-03-19 15:34:46.692804,2026-03-19 15:34:46.692804
+2,1,"Отгул — несколько дней, весь день, в счёт отпуска",timeoff_multi_day_full_day_vacation_account,multi_day,full_day,vacation_account,"22.02.2022, 24.02.2022, 26.02.2022",false,true,2026-03-19 15:34:46.692804,2026-03-19 15:34:46.692804
+3,1,"Отгул — несколько дней, весь день, за свой счёт",timeoff_multi_day_full_day_own_expense,multi_day,full_day,own_expense,"22.02.2022, 24.02.2022, 26.02.2022",false,true,2026-03-19 15:34:46.692804,2026-03-19 15:34:46.692804
+4,1,"Отгул — диапазон, частично",timeoff_date_range_partial_own_expense,date_range,partial,own_expense,22.02.2022 - 25.02.2022 с 16:00 по 18:00,false,true,2026-03-19 15:34:46.692804,2026-03-19 15:34:46.692804
+5,1,"Отгул — диапазон, весь день, в счёт отпуска",timeoff_date_range_full_day_vacation_account,date_range,full_day,vacation_account,22.02.2022 - 25.02.2022,false,true,2026-03-19 15:34:46.692804,2026-03-19 15:34:46.692804
+6,1,"Отгул — диапазон, весь день, за свой счёт",timeoff_date_range_full_day_own_expense,date_range,full_day,own_expense,22.02.2022 - 25.02.2022,false,true,2026-03-19 15:34:46.692804,2026-03-19 15:34:46.692804
+7,1,"Отгул — один день, частично",timeoff_single_day_partial_own_expense,single_day,partial,own_expense,22.02.2022 с 16:00 по 18:00,false,true,2026-03-19 15:34:46.692804,2026-03-19 15:34:46.692804
+8,1,"Отгул — один день, весь день, в счёт отпуска",timeoff_single_day_full_day_vacation_account,single_day,full_day,vacation_account,22.02.2022,false,true,2026-03-19 15:34:46.692804,2026-03-19 15:34:46.692804
+9,1,"Отгул — один день, весь день, за свой счёт",timeoff_single_day_full_day_own_expense,single_day,full_day,own_expense,22.02.2022,false,true,2026-03-19 15:34:46.692804,2026-03-19 15:34:46.692804
+28,2,"Отпуск — несколько дней, в счёт отпуска",vacation_multi_day_full_day_vacation_account,multi_day,full_day,vacation_account,"22.02.2022, 24.02.2022, 26.02.2022",false,true,2026-03-26 18:09:42.029177,2026-03-26 18:09:42.029177
+29,2,"Отпуск — несколько дней, за свой счёт",vacation_multi_day_full_day_own_expense,multi_day,full_day,own_expense,"22.02.2022, 24.02.2022, 26.02.2022",false,true,2026-03-26 18:09:42.029177,2026-03-26 18:09:42.029177
+30,2,"Отпуск — диапазон дат, в счёт отпуска",vacation_date_range_full_day_vacation_account,date_range,full_day,vacation_account,22.02.2022 - 25.02.2022,false,true,2026-03-26 18:09:42.029177,2026-03-26 18:09:42.029177
+31,2,"Отпуск — диапазон дат, за свой счёт",vacation_date_range_full_day_own_expense,date_range,full_day,own_expense,22.02.2022 - 25.02.2022,false,true,2026-03-26 18:09:42.029177,2026-03-26 18:09:42.029177
+32,2,"Отпуск — один день, в счёт отпуска",vacation_single_day_full_day_vacation_account,single_day,full_day,vacation_account,22.02.2022,false,true,2026-03-26 18:09:42.029177,2026-03-26 18:09:42.029177
+33,2,"Отпуск — один день, за свой счёт",vacation_single_day_full_day_own_expense,single_day,full_day,own_expense,22.02.2022,false,true,2026-03-26 18:09:42.029177,2026-03-26 18:09:42.029177
+34,3,"Больничный — несколько дней, официальный",sickleave_multi_day_full_day_official,multi_day,full_day,official,"22.02.2022, 24.02.2022, 26.02.2022",false,true,2026-03-26 18:09:42.031398,2026-03-26 18:09:42.031398
+35,3,"Больничный — несколько дней, в счёт отпуска",sickleave_multi_day_full_day_vacation_account,multi_day,full_day,vacation_account,"22.02.2022, 24.02.2022, 26.02.2022",false,true,2026-03-26 18:09:42.031398,2026-03-26 18:09:42.031398
+36,3,"Больничный — несколько дней, за свой счёт",sickleave_multi_day_full_day_own_expense,multi_day,full_day,own_expense,"22.02.2022, 24.02.2022, 26.02.2022",false,true,2026-03-26 18:09:42.031398,2026-03-26 18:09:42.031398
+37,3,"Больничный — диапазон дат, официальный",sickleave_date_range_full_day_official,date_range,full_day,official,22.02.2022 - 25.02.2022,false,true,2026-03-26 18:09:42.031398,2026-03-26 18:09:42.031398
+38,3,"Больничный — диапазон дат, в счёт отпуска",sickleave_date_range_full_day_vacation_account,date_range,full_day,vacation_account,22.02.2022 - 25.02.2022,false,true,2026-03-26 18:09:42.031398,2026-03-26 18:09:42.031398
+39,3,"Больничный — диапазон дат, за свой счёт",sickleave_date_range_full_day_own_expense,date_range,full_day,own_expense,22.02.2022 - 25.02.2022,false,true,2026-03-26 18:09:42.031398,2026-03-26 18:09:42.031398
+40,3,"Больничный — один день, официальный",sickleave_single_day_full_day_official,single_day,full_day,official,22.02.2022,false,true,2026-03-26 18:09:42.031398,2026-03-26 18:09:42.031398
+41,3,"Больничный — один день, в счёт отпуска",sickleave_single_day_full_day_vacation_account,single_day,full_day,vacation_account,22.02.2022,false,true,2026-03-26 18:09:42.031398,2026-03-26 18:09:42.031398
+42,3,"Больничный — один день, за свой счёт",sickleave_single_day_full_day_own_expense,single_day,full_day,own_expense,22.02.2022,false,true,2026-03-26 18:09:42.031398,2026-03-26 18:09:42.031398
+117,19,Альфапэт доставка,alphapet_delivery,,,,Опишите запрос в свободной форме,false,true,2026-03-27 15:34:36.518720,2026-03-27 15:34:36.518720
+118,20,В. Отгрузки,v_shipments,,,,Опишите запрос в свободной форме,false,true,2026-03-27 15:34:36.518720,2026-03-27 15:34:36.518720
+119,21,Внебюджетные расходы,non_budget_expenses,,,,Опишите запрос в свободной форме,false,true,2026-03-27 15:34:36.518720,2026-03-27 15:34:36.518720
+120,22,Внебюджетные расходы ПЭТ Лайн,non_budget_expenses_pet_line,,,,Опишите запрос в свободной форме,false,true,2026-03-27 15:34:36.518720,2026-03-27 15:34:36.518720
+121,23,Возвраты,returns,,,,Опишите запрос в свободной форме,false,true,2026-03-27 15:34:36.518720,2026-03-27 15:34:36.518720
+122,24,Заведение новых клиентов,new_clients,,,,Опишите запрос в свободной форме,false,true,2026-03-27 15:34:36.518720,2026-03-27 15:34:36.518720
+124,26,Заказы. Крым,orders_crimea,,,,Опишите запрос в свободной форме,false,true,2026-03-27 15:34:36.518720,2026-03-27 15:34:36.518720
+125,27,Менеджерские расходы,manager_expenses,,,,Опишите запрос в свободной форме,false,true,2026-03-27 15:34:36.518720,2026-03-27 15:34:36.518720
+126,28,Отгрузки на СОХ,shipments_soh,,,,Опишите запрос в свободной форме,false,true,2026-03-27 15:34:36.518720,2026-03-27 15:34:36.518720
+127,29,Отгрузки,shipments,,,,Опишите запрос в свободной форме,false,true,2026-03-27 15:34:36.518720,2026-03-27 15:34:36.518720
+128,30,Нестандартные условия договора поставки,nonstandard_contract,,,,Опишите запрос в свободной форме,false,true,2026-03-27 15:34:36.518720,2026-03-27 15:34:36.518720
+129,31,Расходы АЛЬФАПЭТ,expenses_alphapet,,,,Опишите запрос в свободной форме,false,true,2026-03-27 15:34:36.518720,2026-03-27 15:34:36.518720
+130,32,Расходы склад Гвардейское,expenses_warehouse_gvardeysk,,,,Опишите запрос в свободной форме,false,true,2026-03-27 15:34:36.518720,2026-03-27 15:34:36.518720
+131,33,РУСПЭТ ДОСТАВКА + НАПРЯМУЮ К КЛИЕНТУ,ruspet_delivery,,,,Опишите запрос в свободной форме,false,true,2026-03-27 15:34:36.518720,2026-03-27 15:34:36.518720
+132,34,Вакансии,vacancies,,,,Опишите запрос в свободной форме,false,true,2026-03-27 15:34:36.518720,2026-03-27 15:34:36.518720
+133,37,ПС Беларусь,ps_belarus,,,,Опишите запрос в свободной форме,false,true,2026-03-27 15:34:36.518720,2026-03-27 15:34:36.518720
+134,38,ПС Краснодар,ps_krasnodar,,,,Опишите запрос в свободной форме,false,true,2026-03-27 15:34:36.518720,2026-03-27 15:34:36.518720
+135,39,ПС Крым,ps_crimea,,,,Опишите запрос в свободной форме,false,true,2026-03-27 15:34:36.518720,2026-03-27 15:34:36.518720
+136,40,Ставки доставки АП,delivery_rates_ap,,,,Опишите запрос в свободной форме,false,true,2026-03-27 15:34:36.518720,2026-03-27 15:34:36.518720
+137,41,Утверждение оплат безнал,payments_cashless,,,,Опишите запрос в свободной форме,false,true,2026-03-27 15:34:36.518720,2026-03-27 15:34:36.518720
+138,43,Утверждение фрилансеров,freelancers_approval,,,,Опишите запрос в свободной форме,false,true,2026-03-27 15:34:36.518720,2026-03-27 15:34:36.518720
+139,42,Утверждение ставок,rates_logistics,,,,Опишите запрос в свободной форме,false,true,2026-03-27 15:34:36.518720,2026-03-27 15:34:36.518720
+123,25,Заказы. Краснодар,orders_krasnodar,,,,Опишите запрос в свободной форме,true,true,2026-03-27 15:34:36.518720,2026-03-27 15:34:36.518720
diff --git a/core/db/db_migration/tables.go b/core/db/db_migration/tables.go
new file mode 100644
index 0000000..4c18a31
--- /dev/null
+++ b/core/db/db_migration/tables.go
@@ -0,0 +1,44 @@
+package dbmigration
+
+import (
+ tablesmigration "bitrix_balancer_api/core/db/db_migration/tables"
+ "github.com/sirupsen/logrus"
+ "gorm.io/gorm"
+)
+
+func (m *MigrationFunctions) migrateTables() error {
+ logrus.Warningln("🔍 Initialize db migration...")
+
+ migrations := []func(*gorm.DB) error{
+ // Независимые справочники
+ tablesmigration.DepartmentsTableMigrate,
+ tablesmigration.RolesTableMigrate,
+ tablesmigration.ApprovalTopicCategoriesTableMigrate,
+
+ // Зависят от справочников
+ tablesmigration.UsersTableMigrate, // → departments
+ tablesmigration.ApprovalTopicsTableMigrate, // → approval_topic_categories
+ tablesmigration.PermissionsTableMigrate, // → roles, approval_topic_categories, approval_topics
+
+ // Зависят от users
+ tablesmigration.UserRolesTableMigrate, // → users, roles
+ tablesmigration.UserHierarchyTableMigrate, // → users, departments
+
+ // Зависят от всего выше
+ tablesmigration.ApprovalsTableMigrate, // → users, approval_topics, departments
+ tablesmigration.ApprovalStepsTableMigrate, // → approvals, users
+ tablesmigration.ApprovalsFilesTableMigrate, // → approvals
+
+ tablesmigration.ApprovalDelegationTableMigrate,
+ tablesmigration.ApprovalAdditionalApproverTableMigrate,
+ tablesmigration.ApprovalTasksTableMigrate,
+ }
+
+ for _, migrate := range migrations {
+ if err := migrate(m.gormDB); err != nil {
+ return err
+ }
+ }
+
+ return nil
+}
diff --git a/core/db/db_migration/tables/approval.go b/core/db/db_migration/tables/approval.go
new file mode 100644
index 0000000..ecaf200
--- /dev/null
+++ b/core/db/db_migration/tables/approval.go
@@ -0,0 +1,40 @@
+package tablesmigration
+
+import (
+ "gorm.io/gorm"
+ "time"
+)
+
+func ApprovalsTableMigrate(db *gorm.DB) error {
+ hasTable := db.Migrator().HasTable(&LocalApprovalProvider{})
+
+ if err := db.AutoMigrate(&LocalApprovalProvider{}); err != nil {
+ return err
+ }
+
+ if !hasTable {
+ time.Sleep(5 * time.Second)
+
+ db.Exec(`ALTER TABLE approvals ADD CONSTRAINT fk_approvals_initiator_id FOREIGN KEY (initiator_id) REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE`)
+ db.Exec(`ALTER TABLE approvals ADD CONSTRAINT fk_approvals_topic_id FOREIGN KEY (topic_id) REFERENCES approval_topics(id) ON DELETE RESTRICT ON UPDATE CASCADE`)
+ db.Exec(`ALTER TABLE approvals ADD CONSTRAINT fk_approvals_department_id FOREIGN KEY (department_id) REFERENCES departments(id) ON DELETE RESTRICT ON UPDATE CASCADE`)
+ db.Exec(`ALTER TABLE approvals ADD CONSTRAINT fk_approvals_revoked_by_id FOREIGN KEY (revoked_by_id) REFERENCES users(id) ON DELETE SET NULL ON UPDATE CASCADE`)
+
+ execComments(db, `
+ COMMENT ON TABLE "approvals" IS 'Заявки на согласование, поданные сотрудниками';
+ COMMENT ON COLUMN "approvals".id IS 'Внутренний ID заявки';
+ COMMENT ON COLUMN "approvals".initiator_id IS 'Сотрудник, подавший заявку';
+ COMMENT ON COLUMN "approvals".topic_id IS 'Тема заявки';
+ COMMENT ON COLUMN "approvals".department_id IS 'Снимок отдела инициатора на момент подачи. Не меняется при переводе сотрудника';
+ COMMENT ON COLUMN "approvals".content IS 'Данные, введённые пользователем по шаблону темы';
+ COMMENT ON COLUMN "approvals".status IS 'Статус заявки: draft | pending | approved | rejected | revoked';
+ COMMENT ON COLUMN "approvals".file_base64 IS 'Прикреплённый файл в формате base64. Заполняется только если тема допускает файл';
+ COMMENT ON COLUMN "approvals".file_name IS 'Оригинальное имя прикреплённого файла';
+ COMMENT ON COLUMN "approvals".revoked_by_id IS 'Кто отозвал заявку: сам инициатор или директор';
+ COMMENT ON COLUMN "approvals".revoked_at IS 'Дата и время отзыва заявки';
+ COMMENT ON COLUMN "approvals".created_at IS 'Дата подачи заявки';
+ COMMENT ON COLUMN "approvals".updated_at IS 'Дата последнего изменения заявки';
+ `)
+ }
+ return nil
+}
diff --git a/core/db/db_migration/tables/approval_additional_approver.go b/core/db/db_migration/tables/approval_additional_approver.go
new file mode 100644
index 0000000..9db720b
--- /dev/null
+++ b/core/db/db_migration/tables/approval_additional_approver.go
@@ -0,0 +1,38 @@
+package tablesmigration
+
+import (
+ "gorm.io/gorm"
+ "time"
+)
+
+func ApprovalAdditionalApproverTableMigrate(db *gorm.DB) error {
+ hasTable := db.Migrator().HasTable(&ApprovalAdditionalApprover{})
+
+ if err := db.AutoMigrate(&ApprovalAdditionalApprover{}); err != nil {
+ return err
+ }
+
+ if !hasTable {
+ time.Sleep(5 * time.Second)
+
+ // Foreign key constraints
+ db.Exec(`ALTER TABLE approval_additional_approvers ADD CONSTRAINT fk_approval_additional_approvers_approval_id FOREIGN KEY (approval_id) REFERENCES approvals(id) ON DELETE CASCADE ON UPDATE CASCADE`)
+ db.Exec(`ALTER TABLE approval_additional_approvers ADD CONSTRAINT fk_approval_additional_approvers_approver_id FOREIGN KEY (approver_id) REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE`)
+ db.Exec(`ALTER TABLE approval_additional_approvers ADD CONSTRAINT fk_approval_additional_approvers_added_by_id FOREIGN KEY (added_by_id) REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE`)
+
+ // Comments
+ execComments(db, `
+ COMMENT ON TABLE "approval_additional_approvers" IS 'Дополнительные согласующие заявки: кто добавлен для согласования конкретной заявки';
+ COMMENT ON COLUMN "approval_additional_approvers".id IS 'Внутренний уникальный идентификатор записи';
+ COMMENT ON COLUMN "approval_additional_approvers".approval_id IS 'ID заявки, к которой добавлен согласующий (ссылка на approvals.id)';
+ COMMENT ON COLUMN "approval_additional_approvers".approver_id IS 'ID сотрудника, добавленного как дополнительный согласующий (ссылка на users.id)';
+ COMMENT ON COLUMN "approval_additional_approvers".added_by_id IS 'ID сотрудника, который добавил этого согласующего (ссылка на users.id)';
+ COMMENT ON COLUMN "approval_additional_approvers".status IS 'Статус действия согласующего: pending, approved, rejected';
+ COMMENT ON COLUMN "approval_additional_approvers".comment IS 'Комментарий согласующего к своему решению (опционально)';
+ COMMENT ON COLUMN "approval_additional_approvers".acted_at IS 'Дата и время, когда согласующий принял решение (опционально)';
+ COMMENT ON COLUMN "approval_additional_approvers".created_at IS 'Дата и время создания записи';
+ COMMENT ON COLUMN "approval_additional_approvers".updated_at IS 'Дата и время последнего изменения записи';
+ `)
+ }
+ return nil
+}
diff --git a/core/db/db_migration/tables/approval_delegation.go b/core/db/db_migration/tables/approval_delegation.go
new file mode 100644
index 0000000..80a1cdd
--- /dev/null
+++ b/core/db/db_migration/tables/approval_delegation.go
@@ -0,0 +1,39 @@
+package tablesmigration
+
+import (
+ "gorm.io/gorm"
+ "time"
+)
+
+func ApprovalDelegationTableMigrate(db *gorm.DB) error {
+ hasTable := db.Migrator().HasTable(&LocalApprovalDelegationProvider{})
+
+ if err := db.AutoMigrate(&LocalApprovalDelegationProvider{}); err != nil {
+ return err
+ }
+
+ if !hasTable {
+ time.Sleep(5 * time.Second)
+
+ // Foreign key constraints
+ db.Exec(`ALTER TABLE approval_delegations ADD CONSTRAINT fk_approval_delegations_delegator_id FOREIGN KEY (delegator_id) REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE`)
+ db.Exec(`ALTER TABLE approval_delegations ADD CONSTRAINT fk_approval_delegations_delegate_id FOREIGN KEY (delegate_id) REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE`)
+ db.Exec(`ALTER TABLE approval_delegations ADD CONSTRAINT fk_approval_delegations_topic_id FOREIGN KEY (topic_id) REFERENCES approval_topics(id) ON DELETE RESTRICT ON UPDATE CASCADE`)
+
+ // Comments
+ execComments(db, `
+ COMMENT ON TABLE "approval_delegations" IS 'Делегирование прав согласования: кто кому может согласовывать заявки по определённым темам';
+ COMMENT ON COLUMN "approval_delegations".id IS 'Внутренний уникальный идентификатор записи делегирования';
+ COMMENT ON COLUMN "approval_delegations".delegator_id IS 'ID сотрудника, который делегирует право согласования (ссылка на users.id)';
+ COMMENT ON COLUMN "approval_delegations".delegate_id IS 'ID сотрудника, получающего право согласования вместо делегатора (ссылка на users.id)';
+ COMMENT ON COLUMN "approval_delegations".topic_id IS 'ID темы заявки, на которую распространяется делегирование (ссылка на approval_topics.id)';
+ COMMENT ON COLUMN "approval_delegations".valid_until IS 'Дата и время, до которого действует делегирование (включительно)';
+ COMMENT ON COLUMN "approval_delegations".is_active IS 'Флаг активности: true — делегирование применяется, false — временно отключено';
+ COMMENT ON COLUMN "approval_delegations".notified_day IS 'Флаг: отправлено ли уведомление делегатору за 1 день до истечения срока';
+ COMMENT ON COLUMN "approval_delegations".notified_2h IS 'Флаг: отправлено ли уведомление делегатору за 2 часа до истечения срока';
+ COMMENT ON COLUMN "approval_delegations".created_at IS 'Дата и время создания записи делегирования';
+ COMMENT ON COLUMN "approval_delegations".updated_at IS 'Дата и время последнего изменения записи';
+ `)
+ }
+ return nil
+}
diff --git a/core/db/db_migration/tables/approval_files.go b/core/db/db_migration/tables/approval_files.go
new file mode 100644
index 0000000..b39cbdc
--- /dev/null
+++ b/core/db/db_migration/tables/approval_files.go
@@ -0,0 +1,30 @@
+package tablesmigration
+
+import (
+ "gorm.io/gorm"
+ "time"
+)
+
+func ApprovalsFilesTableMigrate(db *gorm.DB) error {
+ hasTable := db.Migrator().HasTable(&LocalApprovalFileProvider{})
+
+ if err := db.AutoMigrate(&LocalApprovalFileProvider{}); err != nil {
+ return err
+ }
+
+ if !hasTable {
+ time.Sleep(5 * time.Second)
+
+ db.Exec(`ALTER TABLE approval_files ADD CONSTRAINT fk_approval_id FOREIGN KEY (initiator_id) REFERENCES approvals(id) ON DELETE CASCADE ON UPDATE CASCADE`)
+
+ execComments(db, `
+ COMMENT ON TABLE "approval_files" IS 'Файлы, приложенные к заявкам на согласование';
+ COMMENT ON COLUMN "approval_files".id IS 'Внутренний ID файла';
+ COMMENT ON COLUMN "approval_files".approval_id IS 'ID заявки, к которой привязаны файлы';
+ COMMENT ON COLUMN "approval_files".file_base64 IS 'Прикреплённый файл в формате base64. Заполняется только если тема допускает файл';
+ COMMENT ON COLUMN "approval_files".file_name IS 'Оригинальное имя прикреплённого файла';
+ COMMENT ON COLUMN "approval_files".created_at IS 'Дата создания файла';
+ `)
+ }
+ return nil
+}
diff --git a/core/db/db_migration/tables/approval_steps.go b/core/db/db_migration/tables/approval_steps.go
new file mode 100644
index 0000000..0fc96ff
--- /dev/null
+++ b/core/db/db_migration/tables/approval_steps.go
@@ -0,0 +1,37 @@
+package tablesmigration
+
+import (
+ "gorm.io/gorm"
+ "time"
+)
+
+func ApprovalStepsTableMigrate(db *gorm.DB) error {
+ hasTable := db.Migrator().HasTable(&LocalApprovalStepProvider{})
+
+ if err := db.AutoMigrate(&LocalApprovalStepProvider{}); err != nil {
+ return err
+ }
+
+ if !hasTable {
+ time.Sleep(5 * time.Second)
+
+ db.Exec(`ALTER TABLE approval_steps ADD CONSTRAINT fk_approval_steps_approval_id FOREIGN KEY (approval_id) REFERENCES approvals(id) ON DELETE CASCADE ON UPDATE CASCADE`)
+ db.Exec(`ALTER TABLE approval_steps ADD CONSTRAINT fk_approval_steps_approver_id FOREIGN KEY (approver_id) REFERENCES users(id) ON DELETE RESTRICT ON UPDATE CASCADE`)
+
+ execComments(db, `
+ COMMENT ON TABLE "approval_steps" IS 'Шаги согласования по каждой заявке. Один шаг — один согласующий';
+ COMMENT ON COLUMN "approval_steps".id IS 'Внутренний ID шага';
+ COMMENT ON COLUMN "approval_steps".approval_id IS 'Ссылка на заявку';
+ COMMENT ON COLUMN "approval_steps".approver_id IS 'Согласующий на данном шаге';
+ COMMENT ON COLUMN "approval_steps".step_order IS 'Порядковый номер шага. 1 = первый согласующий';
+ COMMENT ON COLUMN "approval_steps".status IS 'Статус шага: pending | approved | rejected';
+ COMMENT ON COLUMN "approval_steps".comment IS 'Комментарий согласующего при отклонении. Может быть пустым';
+ COMMENT ON COLUMN "approval_steps".approver_name_snapshot IS 'Снимок имени согласующего на момент действия. Для корректных исторических отчётов';
+ COMMENT ON COLUMN "approval_steps".approver_department_snapshot IS 'Снимок отдела согласующего на момент действия. Для корректных исторических отчётов';
+ COMMENT ON COLUMN "approval_steps".acted_at IS 'Дата и время принятия решения по шагу';
+ COMMENT ON COLUMN "approval_steps".created_at IS 'Дата создания шага';
+ COMMENT ON COLUMN "approval_steps".updated_at IS 'Дата последнего обновления шага';
+ `)
+ }
+ return nil
+}
diff --git a/core/db/db_migration/tables/approval_task.go b/core/db/db_migration/tables/approval_task.go
new file mode 100644
index 0000000..c3720bb
--- /dev/null
+++ b/core/db/db_migration/tables/approval_task.go
@@ -0,0 +1,37 @@
+package tablesmigration
+
+import (
+ "gorm.io/gorm"
+ "time"
+)
+
+func ApprovalTasksTableMigrate(db *gorm.DB) error {
+ hasTable := db.Migrator().HasTable(&ApprovalTaskProvider{})
+
+ if err := db.AutoMigrate(&ApprovalTaskProvider{}); err != nil {
+ return err
+ }
+
+ if !hasTable {
+ time.Sleep(5 * time.Second)
+
+ // Внешние ключи
+ db.Exec(`ALTER TABLE approval_tasks ADD CONSTRAINT fk_approval_tasks_approval_id FOREIGN KEY (approval_id) REFERENCES approvals(id) ON DELETE CASCADE ON UPDATE CASCADE`)
+ db.Exec(`ALTER TABLE approval_tasks ADD CONSTRAINT fk_approval_tasks_executor_id FOREIGN KEY (executor_id) REFERENCES users(id) ON DELETE RESTRICT ON UPDATE CASCADE`)
+
+ // Комментарии к таблице и колонкам
+ execComments(db, `
+ COMMENT ON TABLE "approval_tasks" IS 'Задачи согласования, назначенные исполнителям';
+ COMMENT ON COLUMN "approval_tasks".id IS 'Внутренний ID задачи';
+ COMMENT ON COLUMN "approval_tasks".approval_id IS 'Связанная заявка на согласование';
+ COMMENT ON COLUMN "approval_tasks".executor_id IS 'Сотрудник-исполнитель задачи';
+ COMMENT ON COLUMN "approval_tasks".task_text IS 'Текст или описание задачи';
+ COMMENT ON COLUMN "approval_tasks".status IS 'Статус задачи: pending | completed | rejected';
+ COMMENT ON COLUMN "approval_tasks".completed_at IS 'Дата и время выполнения задачи';
+ COMMENT ON COLUMN "approval_tasks".created_at IS 'Дата создания задачи';
+ COMMENT ON COLUMN "approval_tasks".updated_at IS 'Дата последнего изменения задачи';
+ `)
+ }
+
+ return nil
+}
diff --git a/core/db/db_migration/tables/approval_topic.go b/core/db/db_migration/tables/approval_topic.go
new file mode 100644
index 0000000..0ef0237
--- /dev/null
+++ b/core/db/db_migration/tables/approval_topic.go
@@ -0,0 +1,37 @@
+package tablesmigration
+
+import (
+ "gorm.io/gorm"
+ "time"
+)
+
+func ApprovalTopicsTableMigrate(db *gorm.DB) error {
+ hasTable := db.Migrator().HasTable(&LocalApprovalTopicProvider{})
+
+ if err := db.AutoMigrate(&LocalApprovalTopicProvider{}); err != nil {
+ return err
+ }
+
+ if !hasTable {
+ time.Sleep(5 * time.Second)
+
+ db.Exec(`ALTER TABLE approval_topics ADD CONSTRAINT fk_approval_topics_category_id FOREIGN KEY (category_id) REFERENCES approval_topic_categories(id) ON DELETE CASCADE ON UPDATE CASCADE`)
+
+ execComments(db, `
+ COMMENT ON TABLE "approval_topics" IS 'Конкретные темы согласований внутри категорий';
+ COMMENT ON COLUMN "approval_topics".id IS 'Внутренний ID темы';
+ COMMENT ON COLUMN "approval_topics".category_id IS 'Ссылка на категорию';
+ COMMENT ON COLUMN "approval_topics".name IS 'Название темы';
+ COMMENT ON COLUMN "approval_topics".code IS 'Уникальный код темы: otgul_single_full_own, otgul_single_partial и т.д.';
+ COMMENT ON COLUMN "approval_topics".duration_type IS 'Тип длительности: single_day | date_range | multi_day';
+ COMMENT ON COLUMN "approval_topics".time_type IS 'Тип времени: full_day | partial';
+ COMMENT ON COLUMN "approval_topics".payment_type IS 'Тип оплаты: own_expense | vacation_account | not_applicable';
+ COMMENT ON COLUMN "approval_topics".template IS 'Шаблон ввода для пользователя: 22.02.2022 или 22.02.2022 с 16:00 по 18:00';
+ COMMENT ON COLUMN "approval_topics".allows_file IS 'Разрешено ли прикрепление файла к заявке по этой теме';
+ COMMENT ON COLUMN "approval_topics".is_active IS 'Активна ли тема. Неактивная тема скрыта из меню бота';
+ COMMENT ON COLUMN "approval_topics".created_at IS 'Дата создания записи';
+ COMMENT ON COLUMN "approval_topics".updated_at IS 'Дата последнего обновления записи';
+ `)
+ }
+ return nil
+}
diff --git a/core/db/db_migration/tables/approval_topic_category.go b/core/db/db_migration/tables/approval_topic_category.go
new file mode 100644
index 0000000..1089852
--- /dev/null
+++ b/core/db/db_migration/tables/approval_topic_category.go
@@ -0,0 +1,30 @@
+package tablesmigration
+
+import (
+ "gorm.io/gorm"
+ "time"
+)
+
+func ApprovalTopicCategoriesTableMigrate(db *gorm.DB) error {
+ hasTable := db.Migrator().HasTable(&LocalApprovalTopicCategoryProvider{})
+
+ if err := db.AutoMigrate(&LocalApprovalTopicCategoryProvider{}); err != nil {
+ return err
+ }
+
+ if !hasTable {
+ time.Sleep(5 * time.Second)
+
+ execComments(db, `
+ COMMENT ON TABLE "approval_topic_categories" IS 'Категории тем согласований: Отгул, Отпуск, Больничный и т.д.';
+ COMMENT ON COLUMN "approval_topic_categories".id IS 'Внутренний ID категории';
+ COMMENT ON COLUMN "approval_topic_categories".name IS 'Название категории: Отгул, Отпуск, Больничный';
+ COMMENT ON COLUMN "approval_topic_categories".code IS 'Уникальный код категории: otgul, vacation, sick_leave';
+ COMMENT ON COLUMN "approval_topic_categories".description IS 'Описание категории';
+ COMMENT ON COLUMN "approval_topic_categories".is_active IS 'Активна ли категория. Неактивная категория скрыта из меню бота';
+ COMMENT ON COLUMN "approval_topic_categories".created_at IS 'Дата создания записи';
+ COMMENT ON COLUMN "approval_topic_categories".updated_at IS 'Дата последнего обновления записи';
+ `)
+ }
+ return nil
+}
diff --git a/core/db/db_migration/tables/department.go b/core/db/db_migration/tables/department.go
new file mode 100644
index 0000000..1b22519
--- /dev/null
+++ b/core/db/db_migration/tables/department.go
@@ -0,0 +1,30 @@
+package tablesmigration
+
+import (
+ "gorm.io/gorm"
+ "time"
+)
+
+func DepartmentsTableMigrate(db *gorm.DB) error {
+ hasTable := db.Migrator().HasTable(&LocalDepartmentProvider{})
+
+ if err := db.AutoMigrate(&LocalDepartmentProvider{}); err != nil {
+ return err
+ }
+
+ if !hasTable {
+ time.Sleep(5 * time.Second)
+
+ execComments(db, `
+ COMMENT ON TABLE "departments" IS 'Отделы компании';
+ COMMENT ON COLUMN "departments".id IS 'Внутренний ID отдела';
+ COMMENT ON COLUMN "departments".name IS 'Название отдела: Финансовый отдел, IT отдел и т.д.';
+ COMMENT ON COLUMN "departments".code IS 'Уникальный код отдела: finance, hr, it и т.д.';
+ COMMENT ON COLUMN "departments".description IS 'Описание отдела';
+ COMMENT ON COLUMN "departments".is_active IS 'Активен ли отдел. Неактивный отдел скрыт из интерфейса';
+ COMMENT ON COLUMN "departments".created_at IS 'Дата создания записи';
+ COMMENT ON COLUMN "departments".updated_at IS 'Дата последнего обновления записи';
+ `)
+ }
+ return nil
+}
diff --git a/core/db/db_migration/tables/helpers.go b/core/db/db_migration/tables/helpers.go
new file mode 100644
index 0000000..45fa420
--- /dev/null
+++ b/core/db/db_migration/tables/helpers.go
@@ -0,0 +1,15 @@
+package tablesmigration
+
+import (
+ "gorm.io/gorm"
+ "time"
+)
+
+func execComments(db *gorm.DB, sql string) {
+ for i := range 3 {
+ if err := db.Exec(sql).Error; err == nil {
+ return
+ }
+ time.Sleep(time.Duration(i+1) * time.Second)
+ }
+}
diff --git a/core/db/db_migration/tables/permission.go b/core/db/db_migration/tables/permission.go
new file mode 100644
index 0000000..d1e0119
--- /dev/null
+++ b/core/db/db_migration/tables/permission.go
@@ -0,0 +1,35 @@
+package tablesmigration
+
+import (
+ "gorm.io/gorm"
+ "time"
+)
+
+func PermissionsTableMigrate(db *gorm.DB) error {
+ hasTable := db.Migrator().HasTable(&LocalPermissionProvider{})
+
+ if err := db.AutoMigrate(&LocalPermissionProvider{}); err != nil {
+ return err
+ }
+
+ if !hasTable {
+ time.Sleep(5 * time.Second)
+
+ db.Exec(`ALTER TABLE permissions ADD CONSTRAINT fk_permissions_role_id FOREIGN KEY (role_id) REFERENCES roles(id) ON DELETE CASCADE ON UPDATE CASCADE`)
+ db.Exec(`ALTER TABLE permissions ADD CONSTRAINT fk_permissions_topic_category_id FOREIGN KEY (topic_category_id) REFERENCES approval_topic_categories(id) ON DELETE CASCADE ON UPDATE CASCADE`)
+ db.Exec(`ALTER TABLE permissions ADD CONSTRAINT fk_permissions_topic_id FOREIGN KEY (topic_id) REFERENCES approval_topics(id) ON DELETE CASCADE ON UPDATE CASCADE`)
+ db.Exec(`ALTER TABLE permissions ADD CONSTRAINT uq_permissions_role_category_action UNIQUE (role_id, topic_category_id, action)`)
+
+ execComments(db, `
+ COMMENT ON TABLE "permissions" IS 'Права ролей на действия в рамках тем или категорий согласований';
+ COMMENT ON COLUMN "permissions".id IS 'Внутренний ID записи';
+ COMMENT ON COLUMN "permissions".role_id IS 'Роль, которой выдано право';
+ COMMENT ON COLUMN "permissions".topic_category_id IS 'Категория тем. Если заполнено и topic_id = NULL — право на все темы категории';
+ COMMENT ON COLUMN "permissions".topic_id IS 'Конкретная тема. Если заполнено — право только на эту тему';
+ COMMENT ON COLUMN "permissions".action IS 'Действие: create | read | update | delete | approve | revoke';
+ COMMENT ON COLUMN "permissions".created_at IS 'Дата создания записи';
+ COMMENT ON COLUMN "permissions".updated_at IS 'Дата последнего обновления записи';
+ `)
+ }
+ return nil
+}
diff --git a/core/db/db_migration/tables/providers.go b/core/db/db_migration/tables/providers.go
new file mode 100644
index 0000000..ccd33c2
--- /dev/null
+++ b/core/db/db_migration/tables/providers.go
@@ -0,0 +1,64 @@
+package tablesmigration
+
+import (
+ dbcoretablenames "bitrix_balancer_api/core/db/table_names"
+ "bitrix_balancer_api/core/typescore"
+)
+
+type LocalUserProvider typescore.User
+type LocalDepartmentProvider typescore.Department
+type LocalRoleProvider typescore.Role
+type LocalUserRoleProvider typescore.UserRole
+type LocalUserHierarchyProvider typescore.UserHierarchy
+type LocalPermissionProvider typescore.Permission
+type LocalApprovalTopicCategoryProvider typescore.ApprovalTopicCategory
+type LocalApprovalTopicProvider typescore.ApprovalTopic
+type LocalApprovalProvider typescore.Approval
+type LocalApprovalDelegationProvider typescore.ApprovalDelegation
+type LocalApprovalFileProvider typescore.ApprovalFile
+type LocalApprovalStepProvider typescore.ApprovalStep
+type ApprovalAdditionalApprover typescore.ApprovalAdditionalApprover
+type ApprovalTaskProvider typescore.ApprovalTask
+
+func (LocalUserProvider) TableName() string {
+ return dbcoretablenames.TableNameUsers.ToString()
+}
+func (LocalDepartmentProvider) TableName() string {
+ return dbcoretablenames.TableNameDepartments.ToString()
+}
+func (LocalRoleProvider) TableName() string {
+ return dbcoretablenames.TableNameRoles.ToString()
+}
+func (LocalUserRoleProvider) TableName() string {
+ return dbcoretablenames.TableNameUserRoles.ToString()
+}
+func (LocalUserHierarchyProvider) TableName() string {
+ return dbcoretablenames.TableNameUserHierarchy.ToString()
+}
+func (LocalPermissionProvider) TableName() string {
+ return dbcoretablenames.TableNamePermissions.ToString()
+}
+func (LocalApprovalTopicCategoryProvider) TableName() string {
+ return dbcoretablenames.TableNameApprovalTopicCategories.ToString()
+}
+func (LocalApprovalTopicProvider) TableName() string {
+ return dbcoretablenames.TableNameApprovalTopics.ToString()
+}
+func (LocalApprovalProvider) TableName() string {
+ return dbcoretablenames.TableNameApprovals.ToString()
+}
+func (LocalApprovalStepProvider) TableName() string {
+ return dbcoretablenames.TableNameApprovalSteps.ToString()
+}
+func (LocalApprovalFileProvider) TableName() string {
+ return dbcoretablenames.TableNameApprovalFiles.ToString()
+}
+func (LocalApprovalDelegationProvider) TableName() string {
+ return dbcoretablenames.TableNameApprovalDelegations.ToString()
+}
+func (ApprovalAdditionalApprover) TableName() string {
+ return dbcoretablenames.TableNameApprovalAdditionalApprovers.ToString()
+}
+func (ApprovalTaskProvider) TableName() string {
+ return dbcoretablenames.TableNameApprovalTasks.ToString()
+}
diff --git a/core/db/db_migration/tables/role.go b/core/db/db_migration/tables/role.go
new file mode 100644
index 0000000..eaf0897
--- /dev/null
+++ b/core/db/db_migration/tables/role.go
@@ -0,0 +1,32 @@
+package tablesmigration
+
+import (
+ "gorm.io/gorm"
+ "time"
+)
+
+func RolesTableMigrate(db *gorm.DB) error {
+ hasTable := db.Migrator().HasTable(&LocalRoleProvider{})
+
+ if err := db.AutoMigrate(&LocalRoleProvider{}); err != nil {
+ return err
+ }
+
+ if !hasTable {
+ time.Sleep(5 * time.Second)
+
+ execComments(db, `
+ COMMENT ON TABLE "roles" IS 'Роли пользователей в системе согласований';
+ COMMENT ON COLUMN "roles".id IS 'Внутренний ID роли';
+ COMMENT ON COLUMN "roles".name IS 'Название роли: Сотрудник, Согласующий, Директор';
+ COMMENT ON COLUMN "roles".code IS 'Уникальный код роли: employee, approver, director';
+ COMMENT ON COLUMN "roles".is_default IS 'Назначается ли роль автоматически при регистрации пользователя';
+ COMMENT ON COLUMN "roles".is_director IS 'Получает финальные уведомления по всем отделам. Может отозвать любое согласование';
+ COMMENT ON COLUMN "roles".is_approver IS 'Может согласовывать заявки своих подчинённых';
+ COMMENT ON COLUMN "roles".description IS 'Описание роли';
+ COMMENT ON COLUMN "roles".created_at IS 'Дата создания записи';
+ COMMENT ON COLUMN "roles".updated_at IS 'Дата последнего обновления записи';
+ `)
+ }
+ return nil
+}
diff --git a/core/db/db_migration/tables/user.go b/core/db/db_migration/tables/user.go
new file mode 100644
index 0000000..5893d70
--- /dev/null
+++ b/core/db/db_migration/tables/user.go
@@ -0,0 +1,36 @@
+package tablesmigration
+
+import (
+ "gorm.io/gorm"
+ "time"
+)
+
+func UsersTableMigrate(db *gorm.DB) error {
+ hasTable := db.Migrator().HasTable(&LocalUserProvider{})
+
+ if err := db.AutoMigrate(&LocalUserProvider{}); err != nil {
+ return err
+ }
+
+ if !hasTable {
+ time.Sleep(5 * time.Second)
+
+ db.Exec(`ALTER TABLE users ADD CONSTRAINT fk_users_department_id FOREIGN KEY (department_id) REFERENCES departments(id) ON DELETE SET NULL ON UPDATE CASCADE`)
+
+ execComments(db, `
+ COMMENT ON TABLE "users" IS 'Сотрудники компании РусПЭТ';
+ COMMENT ON COLUMN "users".id IS 'Внутренний ID пользователя';
+ COMMENT ON COLUMN "users".telegram_id IS 'Уникальный Telegram ID пользователя';
+ COMMENT ON COLUMN "users".username IS 'Telegram @username, может быть NULL';
+ COMMENT ON COLUMN "users".full_name IS 'Полное имя сотрудника';
+ COMMENT ON COLUMN "users".language_code IS 'Языковой код клиента: ru, en и т.д.';
+ COMMENT ON COLUMN "users".department_id IS 'Основной отдел сотрудника. NULL — бот пуст, функционал недоступен';
+ COMMENT ON COLUMN "users".is_blocked IS 'Заблокирован ли пользователь';
+ COMMENT ON COLUMN "users".blocked_at IS 'Дата блокировки';
+ COMMENT ON COLUMN "users".last_login IS 'Дата последнего входа';
+ COMMENT ON COLUMN "users".created_at IS 'Дата регистрации';
+ COMMENT ON COLUMN "users".updated_at IS 'Дата последнего обновления записи';
+ `)
+ }
+ return nil
+}
diff --git a/core/db/db_migration/tables/user_hierarchy.go b/core/db/db_migration/tables/user_hierarchy.go
new file mode 100644
index 0000000..74eb664
--- /dev/null
+++ b/core/db/db_migration/tables/user_hierarchy.go
@@ -0,0 +1,34 @@
+package tablesmigration
+
+import (
+ "gorm.io/gorm"
+ "time"
+)
+
+func UserHierarchyTableMigrate(db *gorm.DB) error {
+ hasTable := db.Migrator().HasTable(&LocalUserHierarchyProvider{})
+
+ if err := db.AutoMigrate(&LocalUserHierarchyProvider{}); err != nil {
+ return err
+ }
+
+ if !hasTable {
+ time.Sleep(5 * time.Second)
+
+ db.Exec(`ALTER TABLE user_hierarchy ADD CONSTRAINT fk_user_hierarchy_subordinate_id FOREIGN KEY (subordinate_id) REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE`)
+ db.Exec(`ALTER TABLE user_hierarchy ADD CONSTRAINT fk_user_hierarchy_approver_id FOREIGN KEY (approver_id) REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE`)
+ db.Exec(`ALTER TABLE user_hierarchy ADD CONSTRAINT fk_user_hierarchy_department_id FOREIGN KEY (department_id) REFERENCES departments(id) ON DELETE CASCADE ON UPDATE CASCADE`)
+
+ execComments(db, `
+ COMMENT ON TABLE "user_hierarchy" IS 'Иерархия согласования. Определяет кто кому подчиняется в рамках отдела';
+ COMMENT ON COLUMN "user_hierarchy".id IS 'Внутренний ID записи';
+ COMMENT ON COLUMN "user_hierarchy".subordinate_id IS 'Подчинённый — инициатор согласования';
+ COMMENT ON COLUMN "user_hierarchy".approver_id IS 'Согласующий. Может быть привязан к нескольким отделам через разные записи';
+ COMMENT ON COLUMN "user_hierarchy".department_id IS 'Контекст связи — в рамках какого отдела действует иерархия';
+ COMMENT ON COLUMN "user_hierarchy".priority IS 'Порядок шага согласования. 1 = первый согласующий';
+ COMMENT ON COLUMN "user_hierarchy".created_at IS 'Дата создания записи';
+ COMMENT ON COLUMN "user_hierarchy".updated_at IS 'Дата последнего обновления записи';
+ `)
+ }
+ return nil
+}
diff --git a/core/db/db_migration/tables/user_role.go b/core/db/db_migration/tables/user_role.go
new file mode 100644
index 0000000..428019b
--- /dev/null
+++ b/core/db/db_migration/tables/user_role.go
@@ -0,0 +1,31 @@
+package tablesmigration
+
+import (
+ "gorm.io/gorm"
+ "time"
+)
+
+func UserRolesTableMigrate(db *gorm.DB) error {
+ hasTable := db.Migrator().HasTable(&LocalUserRoleProvider{})
+
+ if err := db.AutoMigrate(&LocalUserRoleProvider{}); err != nil {
+ return err
+ }
+
+ if !hasTable {
+ time.Sleep(5 * time.Second)
+
+ db.Exec(`ALTER TABLE user_roles ADD CONSTRAINT fk_user_roles_user_id FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE`)
+ db.Exec(`ALTER TABLE user_roles ADD CONSTRAINT fk_user_roles_role_id FOREIGN KEY (role_id) REFERENCES roles(id) ON DELETE CASCADE ON UPDATE CASCADE`)
+
+ execComments(db, `
+ COMMENT ON TABLE "user_roles" IS 'Связь пользователей и ролей. Один пользователь может иметь несколько ролей';
+ COMMENT ON COLUMN "user_roles".id IS 'Внутренний ID записи';
+ COMMENT ON COLUMN "user_roles".user_id IS 'Ссылка на пользователя';
+ COMMENT ON COLUMN "user_roles".role_id IS 'Ссылка на роль';
+ COMMENT ON COLUMN "user_roles".created_at IS 'Дата назначения роли';
+ COMMENT ON COLUMN "user_roles".updated_at IS 'Дата последнего обновления записи';
+ `)
+ }
+ return nil
+}
diff --git a/core/db/db_migration/triggers.go b/core/db/db_migration/triggers.go
new file mode 100644
index 0000000..efac995
--- /dev/null
+++ b/core/db/db_migration/triggers.go
@@ -0,0 +1,157 @@
+package dbmigration
+
+import (
+ "fmt"
+ "github.com/sirupsen/logrus"
+ "time"
+)
+
+func (m *MigrationFunctions) TriggerMigrations() {
+ logrus.Info(fmt.Sprintf(" Start db triggers creation: %s", time.Now().UTC()))
+
+ // Функция: назначает роль is_default=true пользователю если её ещё нет
+ m.gormDB.Exec(`
+ CREATE OR REPLACE FUNCTION assign_default_role_on_department()
+ RETURNS TRIGGER AS $$
+ DECLARE
+ v_default_role_id BIGINT;
+ BEGIN
+ -- Срабатываем только когда department_id впервые становится не NULL
+ -- или меняется с NULL на значение
+ IF (OLD.department_id IS NOT DISTINCT FROM NEW.department_id) THEN
+ RETURN NEW;
+ END IF;
+
+ IF NEW.department_id IS NULL THEN
+ RETURN NEW;
+ END IF;
+
+ -- Ищем роль с is_default = true
+ SELECT id INTO v_default_role_id
+ FROM roles
+ WHERE is_default = true
+ LIMIT 1;
+
+ IF v_default_role_id IS NULL THEN
+ RETURN NEW;
+ END IF;
+
+ -- Вставляем связь только если её ещё нет
+ INSERT INTO user_roles (user_id, role_id, created_at, updated_at)
+ VALUES (NEW.id, v_default_role_id, NOW(), NOW())
+ ON CONFLICT DO NOTHING;
+
+ RETURN NEW;
+ END;
+ $$ LANGUAGE plpgsql;
+ `)
+
+ m.gormDB.Exec(`
+ DROP TRIGGER IF EXISTS trg_assign_default_role_on_department ON users;
+ CREATE TRIGGER trg_assign_default_role_on_department
+ AFTER UPDATE OF department_id ON users
+ FOR EACH ROW
+ EXECUTE FUNCTION assign_default_role_on_department();
+ `)
+
+ // ─── Seed: базовые права для роли employee если permissions пусты ────────
+
+ // выдаёт права create на timeoff/vacation/sick_leave для роли employee
+ // Срабатывает при INSERT в roles — один раз при создании роли employee
+ m.gormDB.Exec(`
+ CREATE OR REPLACE FUNCTION seed_default_permissions_on_role()
+ RETURNS TRIGGER AS $$
+ BEGIN
+ -- Только для роли с is_default = true
+ IF NEW.is_default IS NOT TRUE THEN
+ RETURN NEW;
+ END IF;
+
+ -- Вставляем права на базовые категории если их ещё нет
+ INSERT INTO permissions (role_id, topic_category_id, action, created_at, updated_at)
+ SELECT
+ NEW.id,
+ tc.id,
+ 'create',
+ NOW(),
+ NOW()
+ FROM approval_topic_categories tc
+ WHERE tc.code IN ('timeoff', 'vacation', 'sick_leave')
+ AND tc.is_active = true
+ AND NOT EXISTS (
+ SELECT 1 FROM permissions p
+ WHERE p.role_id = NEW.id
+ AND p.topic_category_id = tc.id
+ AND p.action = 'create'
+ );
+
+ RETURN NEW;
+ END;
+ $$ LANGUAGE plpgsql;
+ `)
+
+ m.gormDB.Exec(`
+ DROP TRIGGER IF EXISTS trg_seed_default_permissions_on_role ON roles;
+ CREATE TRIGGER trg_seed_default_permissions_on_role
+ AFTER INSERT ON roles
+ FOR EACH ROW
+ EXECUTE FUNCTION seed_default_permissions_on_role();
+ `)
+
+ // ─── Страховка: выдать права если permissions пусты для existing ролей ───
+ m.gormDB.Exec(`
+ INSERT INTO permissions (role_id, topic_category_id, action, created_at, updated_at)
+ SELECT
+ r.id,
+ tc.id,
+ 'create',
+ NOW(),
+ NOW()
+ FROM roles r
+ CROSS JOIN approval_topic_categories tc
+ WHERE r.is_default = true
+ AND tc.code IN ('timeoff', 'vacation', 'sick_leave')
+ AND tc.is_active = true
+ AND NOT EXISTS (
+ SELECT 1 FROM permissions p
+ WHERE p.role_id = r.id
+ AND p.topic_category_id = tc.id
+ AND p.action = 'create'
+ );
+ `)
+}
+
+func (m *MigrationFunctions) DropAllTriggers() {
+ logrus.Info(fmt.Sprintf("🧹 Start dropping all database triggers: %s", time.Now().UTC()))
+
+ // Получаем список всех триггеров в схеме public
+ m.gormDB.Exec(`
+ DO $$
+ DECLARE
+ trigger_record RECORD;
+ BEGIN
+ -- Получаем все триггеры из схемы public
+ FOR trigger_record IN
+ SELECT
+ ns.nspname as schema_name,
+ tg.tgname as trigger_name,
+ rel.relname as table_name
+ FROM pg_trigger tg
+ JOIN pg_class rel ON tg.tgrelid = rel.oid
+ JOIN pg_namespace ns ON rel.relnamespace = ns.oid
+ WHERE ns.nspname = 'public'
+ AND NOT tg.tgisinternal -- исключаем системные триггеры
+ AND tg.tgname NOT LIKE 'pg_%' -- исключаем системные триггеры
+ LOOP
+ -- Формируем и выполняем DROP TRIGGER
+ EXECUTE format('DROP TRIGGER IF EXISTS %I ON %I.%I CASCADE',
+ trigger_record.trigger_name,
+ trigger_record.schema_name,
+ trigger_record.table_name
+ );
+ END LOOP;
+ END $$;
+ `)
+
+ logrus.Info(fmt.Sprintf("✅ All database triggers have been dropped: %s", time.Now().UTC()))
+}
diff --git a/core/db/methods/approval.go b/core/db/methods/approval.go
new file mode 100644
index 0000000..90a45c5
--- /dev/null
+++ b/core/db/methods/approval.go
@@ -0,0 +1,424 @@
+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"
+ "fmt"
+ "github.com/sirupsen/logrus"
+ "time"
+
+ "github.com/Masterminds/squirrel"
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgxpool"
+)
+
+type ApprovalDB struct {
+ pool *pgxpool.Pool
+}
+
+func NewApprovalDB(pool *pgxpool.Pool) *ApprovalDB {
+ return &ApprovalDB{
+ pool: pool,
+ }
+}
+
+type ApprovalDBI interface {
+ GetApprovalsListDB(ctx context.Context, options ...typescore.ListDbOptions) ([]*typescore.Approval, uint64, error)
+ CreateApprovalDB(ctx context.Context, tx pgx.Tx, ApprovalObj *typescore.Approval, returnObj ...bool) (*typescore.Approval, pgx.Tx, error)
+ UpdateApprovalDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.Approval, returnObj ...bool) (*typescore.Approval, pgx.Tx, error)
+ DeleteApprovalDB(ctx context.Context, params *typescore.Approval) error
+ GetApprovalByIDDB(ctx context.Context, id uint64) (*typescore.Approval, error)
+ GetActiveApprovalsByInitiatorDB(ctx context.Context, initiatorID uint64) ([]*typescore.Approval, error)
+ GetPendingApprovalsByApproverDB(ctx context.Context, approverID uint64) ([]*typescore.Approval, error)
+ GetApprovalsByInitiatorAndCategoryDB(ctx context.Context, initiatorID uint64, categoryCode string) ([]*typescore.Approval, error)
+ GetPendingApprovalsByApproverAndCategoryDB(ctx context.Context, approverID uint64, categoryCode string) ([]*typescore.Approval, error)
+ GetApprovalsByCategoryDB(ctx context.Context, categoryCode string) ([]*typescore.Approval, error)
+ GetClosedApprovalsByInitiatorDB(ctx context.Context, initiatorID uint64) ([]*typescore.Approval, error)
+}
+
+func (u *ApprovalDB) GetApprovalsListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.Approval, uint64, error) {
+ fields := dbutils.GetStructFieldsDB(&typescore.Approval{}, dbcoretablenames.TableNameApprovals.ToString())
+ selectFields := append(fields, "COUNT(*) OVER() AS total_count")
+
+ options, filter, err := dbutils.GetOptionsDB[typescore.Approval](opts...)
+ if err != nil {
+ return nil, 0, err
+ }
+
+ query := dbutils.BuildSelectQuery(dbcoretablenames.TableNameApprovals.ToString(), selectFields)
+ query = dbutils.SetterLimitAndOffsetQuery(query, options.Offset, options.Limit)
+ query = dbutils.ApplyFilters(query, filter, options.LikeFields, dbcoretablenames.TableNameApprovals.ToString())
+ query = query.OrderBy("created_at DESC")
+
+ 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 Approvals []*typescore.Approval
+ var totalCount uint64
+ for rows.Next() {
+ Approval := &typescore.Approval{}
+ if err := dbutils.ScanRowsToStructRows(rows, Approval, &totalCount); err != nil {
+ logrus.Warn("GetApprovalsListDB:ScanRowsToStructRows", err)
+ continue
+ }
+ Approvals = append(Approvals, Approval)
+ }
+
+ return Approvals, totalCount, nil
+}
+
+func (u *ApprovalDB) CreateApprovalDB(ctx context.Context, tx pgx.Tx, ApprovalObj *typescore.Approval, returnObj ...bool) (*typescore.Approval, pgx.Tx, error) {
+ if ApprovalObj == nil {
+ return nil, nil, errors.New("approval obj is nil")
+ }
+
+ var insertedID uint64
+
+ err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error {
+ query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
+ Insert(dbcoretablenames.TableNameApprovals.ToString())
+
+ sqlV, args, err := dbutils.GenerateInsertRequest(query, ApprovalObj)
+ if err != nil {
+ return err
+ }
+
+ *sqlV = *sqlV + " RETURNING id"
+
+ return tx.QueryRow(ctx, *sqlV, args...).Scan(&insertedID)
+ })
+
+ if err != nil {
+ return nil, tx, err
+ }
+
+ returnObjBool := len(returnObj) > 0 && returnObj[0]
+ if returnObjBool && insertedID > 0 {
+ created, err := u.GetApprovalByIDDB(ctx, insertedID)
+ return created, tx, err
+ }
+
+ return nil, tx, nil
+}
+
+func (u *ApprovalDB) UpdateApprovalDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.Approval, returnObj ...bool) (*typescore.Approval, pgx.Tx, error) {
+ if paramsUpdate.ID == nil {
+ return nil, nil, errors.New("approval obj is nil")
+ }
+
+ err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error {
+ query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).Update(dbcoretablenames.TableNameApprovals.ToString())
+ query = dbutils.AddNonNullFieldsToQueryUpdate(query, *paramsUpdate)
+ query = query.Where(squirrel.Eq{"id": paramsUpdate.ID})
+
+ sql, args, err := query.ToSql()
+ if err != nil {
+ return err
+ }
+
+ _, err = tx.Exec(ctx, sql, args...)
+ if err != nil {
+ return err
+ }
+
+ return nil
+ })
+
+ if err != nil {
+ return nil, tx, err
+ }
+
+ returnObjBool := false
+ if len(returnObj) > 0 {
+ returnObjBool = returnObj[0]
+ }
+
+ if returnObjBool {
+ options := typescore.ListDbOptions{Filtering: &typescore.Approval{ID: paramsUpdate.ID}}
+ getInfoUp, _, err := u.GetApprovalsListDB(ctx, options)
+ if err != nil {
+ return nil, nil, err
+ }
+ if len(getInfoUp) > 0 {
+ return getInfoUp[0], tx, nil
+ }
+ }
+
+ return nil, tx, nil
+}
+
+func (u *ApprovalDB) DeleteApprovalDB(ctx context.Context, params *typescore.Approval) error {
+ if params != nil && params.ID != nil {
+ query, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
+ Delete(dbcoretablenames.TableNameApprovals.ToString()).
+ Where(squirrel.Eq{"id": *params.ID}).
+ ToSql()
+
+ if err != nil {
+ return err
+ }
+
+ rows, err := u.pool.Query(ctx, query, args...)
+ if err != nil {
+ return err
+ }
+ defer rows.Close()
+
+ return nil
+ } else {
+ return errors.New("approval obj is nil")
+ }
+}
+
+func (u *ApprovalDB) GetApprovalByIDDB(ctx context.Context, id uint64) (*typescore.Approval, error) {
+ approvals, _, err := u.GetApprovalsListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.Approval{ID: &id},
+ })
+ if err != nil {
+ return nil, err
+ }
+ if len(approvals) == 0 {
+ return nil, nil
+ }
+ return approvals[0], nil
+}
+
+// GetActiveApprovalsByInitiatorDB — активные заявки инициатора (не закрытые)
+func (u *ApprovalDB) GetActiveApprovalsByInitiatorDB(ctx context.Context, initiatorID uint64) ([]*typescore.Approval, error) {
+ sql, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
+ Select(dbutils.GetStructFieldsDB(&typescore.Approval{}, dbcoretablenames.TableNameApprovals.ToString())...).
+ From(dbcoretablenames.TableNameApprovals.ToString()).
+ Where(squirrel.Eq{"initiator_id": initiatorID}).
+ // Показываем pending и approved — закрытые (revoked, rejected) не показываем
+ Where(squirrel.Eq{"status": []string{"pending", "approved"}}).
+ OrderBy("created_at DESC").
+ ToSql()
+ if err != nil {
+ return nil, err
+ }
+
+ rows, err := u.pool.Query(ctx, sql, args...)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+
+ var result []*typescore.Approval
+ for rows.Next() {
+ a := &typescore.Approval{}
+ if err := dbutils.ScanRowsToStructRows(rows, a, nil); err != nil {
+ logrus.Warn("GetActiveApprovalsByInitiatorDB:ScanRowsToStruct", err)
+ continue
+ }
+ result = append(result, a)
+ }
+ return result, nil
+}
+
+// GetPendingApprovalsByApproverDB — заявки ожидающие действия от согласующего
+func (u *ApprovalDB) GetPendingApprovalsByApproverDB(ctx context.Context, approverID uint64) ([]*typescore.Approval, error) {
+ sql, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
+ Select("DISTINCT a.*").
+ From(dbcoretablenames.TableNameApprovals.ToString() + " a").
+ Join(dbcoretablenames.TableNameApprovalSteps.ToString() + " s ON s.approval_id = a.id").
+ Where(squirrel.Eq{"s.approver_id": approverID}).
+ Where(squirrel.Eq{"s.status": "pending"}).
+ Where(squirrel.Eq{"a.status": "pending"}).
+ OrderBy("a.created_at DESC").
+ ToSql()
+ if err != nil {
+ return nil, err
+ }
+
+ rows, err := u.pool.Query(ctx, sql, args...)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+
+ var result []*typescore.Approval
+ for rows.Next() {
+ a := &typescore.Approval{}
+ if err := dbutils.ScanRowsToStructRows(rows, a, nil); err != nil {
+ logrus.Warn("GetPendingApprovalsByApproverDB:ScanRowsToStruct", err)
+ continue
+ }
+ result = append(result, a)
+ }
+ return result, nil
+}
+
+// GetApprovalsByInitiatorAndCategoryDB — заявки инициатора по категории
+func (u *ApprovalDB) GetApprovalsByInitiatorAndCategoryDB(ctx context.Context, initiatorID uint64, categoryCode string) ([]*typescore.Approval, error) {
+ sql, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
+ Select("a.*").
+ From(dbcoretablenames.TableNameApprovals.ToString() + " a").
+ Join(dbcoretablenames.TableNameApprovalTopics.ToString() + " t ON t.id = a.topic_id").
+ Join(dbcoretablenames.TableNameApprovalTopicCategories.ToString() + " c ON c.id = t.category_id").
+ Where(squirrel.Eq{"a.initiator_id": initiatorID}).
+ Where(squirrel.Eq{"c.code": categoryCode}).
+ Where(squirrel.Eq{"a.status": []string{"pending", "approved"}}).
+ OrderBy("a.created_at DESC").
+ ToSql()
+ if err != nil {
+ return nil, err
+ }
+ return u.queryApprovals(ctx, sql, args)
+}
+
+// GetPendingApprovalsByApproverAndCategoryDB — входящие по категории для согласующего
+func (u *ApprovalDB) GetPendingApprovalsByApproverAndCategoryDB(ctx context.Context, approverID uint64, categoryCode string) ([]*typescore.Approval, error) {
+ sql, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
+ Select("DISTINCT a.*").
+ From(dbcoretablenames.TableNameApprovals.ToString() + " a").
+ Join(dbcoretablenames.TableNameApprovalSteps.ToString() + " s ON s.approval_id = a.id").
+ Join(dbcoretablenames.TableNameApprovalTopics.ToString() + " t ON t.id = a.topic_id").
+ Join(dbcoretablenames.TableNameApprovalTopicCategories.ToString() + " c ON c.id = t.category_id").
+ Where(squirrel.Eq{"s.approver_id": approverID}).
+ Where(squirrel.Eq{"s.status": "pending"}).
+ Where(squirrel.Eq{"a.status": "pending"}).
+ Where(squirrel.Eq{"c.code": categoryCode}).
+ OrderBy("a.created_at DESC").
+ ToSql()
+ if err != nil {
+ return nil, err
+ }
+ return u.queryApprovals(ctx, sql, args)
+}
+
+// GetApprovalsByCategoryDB — все заявки по категории для наблюдателя
+func (u *ApprovalDB) GetApprovalsByCategoryDB(ctx context.Context, categoryCode string) ([]*typescore.Approval, error) {
+ sql, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
+ Select("a.*").
+ From(dbcoretablenames.TableNameApprovals.ToString() + " a").
+ Join(dbcoretablenames.TableNameApprovalTopics.ToString() + " t ON t.id = a.topic_id").
+ Join(dbcoretablenames.TableNameApprovalTopicCategories.ToString() + " c ON c.id = t.category_id").
+ Where(squirrel.Eq{"c.code": categoryCode}).
+ OrderBy("a.created_at DESC").
+ ToSql()
+ if err != nil {
+ return nil, err
+ }
+ return u.queryApprovals(ctx, sql, args)
+}
+
+// queryApprovals — общий сканер строк
+func (u *ApprovalDB) queryApprovals(ctx context.Context, sql string, args []interface{}) ([]*typescore.Approval, error) {
+ rows, err := u.pool.Query(ctx, sql, args...)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+
+ var result []*typescore.Approval
+ for rows.Next() {
+ a := &typescore.Approval{}
+ if err := dbutils.ScanRowsToStructRows(rows, a, nil); err != nil {
+ logrus.Warn("queryApprovals:ScanRowsToStruct", err)
+ continue
+ }
+ result = append(result, a)
+ }
+ return result, nil
+}
+
+// GetClosedApprovalsByInitiatorDB — отклонённые и отозванные заявки инициатора.
+func (u *ApprovalDB) GetClosedApprovalsByInitiatorDB(ctx context.Context, initiatorID uint64) ([]*typescore.Approval, error) {
+ sql, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
+ Select(dbutils.GetStructFieldsDB(&typescore.Approval{}, dbcoretablenames.TableNameApprovals.ToString())...).
+ From(dbcoretablenames.TableNameApprovals.ToString()).
+ Where(squirrel.Eq{"initiator_id": initiatorID}).
+ Where(squirrel.Eq{"status": []string{"rejected", "revoked"}}).
+ OrderBy("updated_at DESC").
+ Limit(50).
+ ToSql()
+ if err != nil {
+ return nil, err
+ }
+ return u.queryApprovals(ctx, sql, args)
+}
+
+// GetApprovalsForReportDB — получение согласований для отчёта с учётом всех ролей пользователя.
+// Пользователь видит согласования где он: инициатор, согласующий, наблюдатель или исполнитель.
+func (u *ApprovalDB) GetApprovalsForReportDB(ctx context.Context, filter typescore.ReportFilter) ([]*typescore.Approval, error) {
+ q := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
+ Select("DISTINCT a.*").
+ From(dbcoretablenames.TableNameApprovals.ToString() + " a").
+ OrderBy("a.created_at DESC")
+
+ if !filter.AllAccess && filter.UserID != nil {
+ subQ1 := buildApprovalIdSubquery("initiator", filter.UserID)
+ subQ2 := buildApprovalIdSubquery("approver", filter.UserID)
+ subQ3 := buildApprovalIdSubquery("observer", filter.UserID)
+ subQ4 := buildApprovalIdSubquery("executor", filter.UserID)
+
+ s1, a1, _ := subQ1.PlaceholderFormat(squirrel.Question).ToSql()
+ s2, a2, _ := subQ2.PlaceholderFormat(squirrel.Question).ToSql()
+ s3, a3, _ := subQ3.PlaceholderFormat(squirrel.Question).ToSql()
+ s4, a4, _ := subQ4.PlaceholderFormat(squirrel.Question).ToSql()
+
+ unionSQL := fmt.Sprintf("(%s) UNION (%s) UNION (%s) UNION (%s)", s1, s2, s3, s4)
+ allArgs := append(append(append(a1, a2...), a3...), a4...)
+
+ q = q.Where(squirrel.Expr("a.id IN ("+unionSQL+")", allArgs...))
+ }
+
+ if filter.DateFrom != nil {
+ q = q.Where(squirrel.GtOrEq{"a.created_at": filter.DateFrom})
+ }
+ if filter.DateTo != nil {
+ endOfDay := filter.DateTo.Add(24*time.Hour - time.Second)
+ q = q.Where(squirrel.LtOrEq{"a.created_at": endOfDay})
+ }
+
+ sql, args, err := q.ToSql()
+ if err != nil {
+ return nil, err
+ }
+ return u.queryApprovals(ctx, sql, args)
+}
+
+func buildApprovalIdSubquery(role string, userID *uint64) squirrel.SelectBuilder {
+ q := squirrel.Select("a.id").
+ From(dbcoretablenames.TableNameApprovals.ToString() + " a")
+
+ switch role {
+ case "initiator":
+ return q.Where(squirrel.Eq{"a.initiator_id": userID})
+
+ case "approver":
+ return q.
+ Join(dbcoretablenames.TableNameApprovalSteps.ToString() + " s ON s.approval_id = a.id").
+ Where(squirrel.Eq{"s.approver_id": userID})
+
+ case "executor":
+ return q.
+ Join(dbcoretablenames.TableNameApprovalTasks.ToString() + " task ON task.approval_id = a.id").
+ Where(squirrel.Eq{"task.executor_id": userID})
+
+ case "observer":
+ return q.
+ Join(dbcoretablenames.TableNameApprovalTopics.ToString() + " t ON t.id = a.topic_id").
+ Join(dbcoretablenames.TableNameApprovalTopicCategories.ToString() + " c ON c.id = t.category_id").
+ Join(dbcoretablenames.TableNamePermissions.ToString() + " p ON p.topic_category_id = c.id").
+ Join("user_roles ur ON ur.role_id = p.role_id").
+ Where(squirrel.And{
+ squirrel.Eq{"ur.user_id": userID},
+ squirrel.Eq{"p.action": "observe"},
+ })
+
+ default:
+ return q.Where(squirrel.Expr("false"))
+ }
+}
diff --git a/core/db/methods/approval_additional_approver.go b/core/db/methods/approval_additional_approver.go
new file mode 100644
index 0000000..e9a0350
--- /dev/null
+++ b/core/db/methods/approval_additional_approver.go
@@ -0,0 +1,186 @@
+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"
+ "github.com/sirupsen/logrus"
+)
+
+type ApprovalAdditionalApproverDB struct {
+ pool *pgxpool.Pool
+}
+
+func NewApprovalAdditionalApproverDB(pool *pgxpool.Pool) *ApprovalAdditionalApproverDB {
+ return &ApprovalAdditionalApproverDB{
+ pool: pool,
+ }
+}
+
+type ApprovalAdditionalApproverDBI interface {
+ GetApprovalAdditionalApproversListDB(ctx context.Context, options ...typescore.ListDbOptions) ([]*typescore.ApprovalAdditionalApprover, uint64, error)
+ CreateApprovalAdditionalApproverDB(ctx context.Context, tx pgx.Tx, ApprovalAdditionalApproverObj *typescore.ApprovalAdditionalApprover, returnObj ...bool) (*typescore.ApprovalAdditionalApprover, pgx.Tx, error)
+ UpdateApprovalAdditionalApproverDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.ApprovalAdditionalApprover, returnObj ...bool) (*typescore.ApprovalAdditionalApprover, pgx.Tx, error)
+ DeleteApprovalAdditionalApproverDB(ctx context.Context, params *typescore.ApprovalAdditionalApprover) error
+ GetApprovalAdditionalApproverByIDDB(ctx context.Context, id uint64) (*typescore.ApprovalAdditionalApprover, error)
+}
+
+func (u *ApprovalAdditionalApproverDB) GetApprovalAdditionalApproversListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.ApprovalAdditionalApprover, uint64, error) {
+ fields := dbutils.GetStructFieldsDB(&typescore.ApprovalAdditionalApprover{}, dbcoretablenames.TableNameApprovalAdditionalApprovers.ToString())
+ selectFields := append(fields, "COUNT(*) OVER() AS total_count")
+
+ options, filter, err := dbutils.GetOptionsDB[typescore.ApprovalAdditionalApprover](opts...)
+ if err != nil {
+ return nil, 0, err
+ }
+
+ query := dbutils.BuildSelectQuery(dbcoretablenames.TableNameApprovalAdditionalApprovers.ToString(), selectFields)
+ query = dbutils.SetterLimitAndOffsetQuery(query, options.Offset, options.Limit)
+ query = dbutils.ApplyFilters(query, filter, options.LikeFields, dbcoretablenames.TableNameApprovalAdditionalApprovers.ToString())
+ query = query.OrderBy("created_at DESC")
+
+ 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 ApprovalAdditionalApprovers []*typescore.ApprovalAdditionalApprover
+ var totalCount uint64
+ for rows.Next() {
+ ApprovalAdditionalApprover := &typescore.ApprovalAdditionalApprover{}
+ if err := dbutils.ScanRowsToStructRows(rows, ApprovalAdditionalApprover, &totalCount); err != nil {
+ logrus.Warn("GetApprovalAdditionalApproversListDB:ScanRowsToStructRows", err)
+ continue
+ }
+ ApprovalAdditionalApprovers = append(ApprovalAdditionalApprovers, ApprovalAdditionalApprover)
+ }
+
+ return ApprovalAdditionalApprovers, totalCount, nil
+}
+
+func (u *ApprovalAdditionalApproverDB) CreateApprovalAdditionalApproverDB(ctx context.Context, tx pgx.Tx, ApprovalAdditionalApproverObj *typescore.ApprovalAdditionalApprover, returnObj ...bool) (*typescore.ApprovalAdditionalApprover, pgx.Tx, error) {
+ if ApprovalAdditionalApproverObj == nil {
+ return nil, nil, errors.New("ApprovalAdditionalApprover obj is nil")
+ }
+
+ var insertedID uint64
+
+ err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error {
+ query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
+ Insert(dbcoretablenames.TableNameApprovalAdditionalApprovers.ToString())
+
+ sqlV, args, err := dbutils.GenerateInsertRequest(query, ApprovalAdditionalApproverObj)
+ if err != nil {
+ return err
+ }
+
+ *sqlV = *sqlV + " RETURNING id"
+
+ return tx.QueryRow(ctx, *sqlV, args...).Scan(&insertedID)
+ })
+
+ if err != nil {
+ return nil, tx, err
+ }
+
+ returnObjBool := len(returnObj) > 0 && returnObj[0]
+ if returnObjBool && insertedID > 0 {
+ created, err := u.GetApprovalAdditionalApproverByIDDB(ctx, insertedID)
+ return created, tx, err
+ }
+
+ return nil, tx, nil
+}
+
+func (u *ApprovalAdditionalApproverDB) UpdateApprovalAdditionalApproverDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.ApprovalAdditionalApprover, returnObj ...bool) (*typescore.ApprovalAdditionalApprover, pgx.Tx, error) {
+ if paramsUpdate.ID == nil {
+ return nil, nil, errors.New("ApprovalAdditionalApprover obj is nil")
+ }
+
+ err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error {
+ query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).Update(dbcoretablenames.TableNameApprovalAdditionalApprovers.ToString())
+ query = dbutils.AddNonNullFieldsToQueryUpdate(query, *paramsUpdate)
+ query = query.Where(squirrel.Eq{"id": paramsUpdate.ID})
+
+ sql, args, err := query.ToSql()
+ if err != nil {
+ return err
+ }
+
+ _, err = tx.Exec(ctx, sql, args...)
+ if err != nil {
+ return err
+ }
+
+ return nil
+ })
+
+ if err != nil {
+ return nil, tx, err
+ }
+
+ returnObjBool := false
+ if len(returnObj) > 0 {
+ returnObjBool = returnObj[0]
+ }
+
+ if returnObjBool {
+ options := typescore.ListDbOptions{Filtering: &typescore.ApprovalAdditionalApprover{ID: paramsUpdate.ID}}
+ getInfoUp, _, err := u.GetApprovalAdditionalApproversListDB(ctx, options)
+ if err != nil {
+ return nil, nil, err
+ }
+ if len(getInfoUp) > 0 {
+ return getInfoUp[0], tx, nil
+ }
+ }
+
+ return nil, tx, nil
+}
+
+func (u *ApprovalAdditionalApproverDB) DeleteApprovalAdditionalApproverDB(ctx context.Context, params *typescore.ApprovalAdditionalApprover) error {
+ if params != nil && params.ID != nil {
+ query, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
+ Delete(dbcoretablenames.TableNameApprovalAdditionalApprovers.ToString()).
+ Where(squirrel.Eq{"id": *params.ID}).
+ ToSql()
+
+ if err != nil {
+ return err
+ }
+
+ rows, err := u.pool.Query(ctx, query, args...)
+ if err != nil {
+ return err
+ }
+ defer rows.Close()
+
+ return nil
+ } else {
+ return errors.New("ApprovalAdditionalApprover obj is nil")
+ }
+}
+
+func (u *ApprovalAdditionalApproverDB) GetApprovalAdditionalApproverByIDDB(ctx context.Context, id uint64) (*typescore.ApprovalAdditionalApprover, error) {
+ ApprovalAdditionalApprovers, _, err := u.GetApprovalAdditionalApproversListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.ApprovalAdditionalApprover{ID: &id},
+ })
+ if err != nil {
+ return nil, err
+ }
+ if len(ApprovalAdditionalApprovers) == 0 {
+ return nil, nil
+ }
+ return ApprovalAdditionalApprovers[0], nil
+}
diff --git a/core/db/methods/approval_delegation.go b/core/db/methods/approval_delegation.go
new file mode 100644
index 0000000..eb58957
--- /dev/null
+++ b/core/db/methods/approval_delegation.go
@@ -0,0 +1,186 @@
+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"
+ "github.com/sirupsen/logrus"
+)
+
+type ApprovalDelegationDB struct {
+ pool *pgxpool.Pool
+}
+
+func NewApprovalDelegationDB(pool *pgxpool.Pool) *ApprovalDelegationDB {
+ return &ApprovalDelegationDB{
+ pool: pool,
+ }
+}
+
+type ApprovalDelegationDBI interface {
+ GetApprovalDelegationsListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.ApprovalDelegation, uint64, error)
+ CreateApprovalDelegationDB(ctx context.Context, tx pgx.Tx, ApprovalDelegationObj *typescore.ApprovalDelegation, returnObj ...bool) (*typescore.ApprovalDelegation, pgx.Tx, error)
+ UpdateApprovalDelegationDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.ApprovalDelegation, returnObj ...bool) (*typescore.ApprovalDelegation, pgx.Tx, error)
+ DeleteApprovalDelegationDB(ctx context.Context, params *typescore.ApprovalDelegation) error
+ GetApprovalDelegationByIDDB(ctx context.Context, id uint64) (*typescore.ApprovalDelegation, error)
+}
+
+func (u *ApprovalDelegationDB) GetApprovalDelegationsListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.ApprovalDelegation, uint64, error) {
+ fields := dbutils.GetStructFieldsDB(&typescore.ApprovalDelegation{}, dbcoretablenames.TableNameApprovalDelegations.ToString())
+ selectFields := append(fields, "COUNT(*) OVER() AS total_count")
+
+ options, filter, err := dbutils.GetOptionsDB[typescore.ApprovalDelegation](opts...)
+ if err != nil {
+ return nil, 0, err
+ }
+
+ query := dbutils.BuildSelectQuery(dbcoretablenames.TableNameApprovalDelegations.ToString(), selectFields)
+ query = dbutils.SetterLimitAndOffsetQuery(query, options.Offset, options.Limit)
+ query = dbutils.ApplyFilters(query, filter, options.LikeFields, dbcoretablenames.TableNameApprovalDelegations.ToString())
+ query = query.OrderBy("created_at DESC")
+
+ 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 ApprovalDelegations []*typescore.ApprovalDelegation
+ var totalCount uint64
+ for rows.Next() {
+ ApprovalDelegation := &typescore.ApprovalDelegation{}
+ if err := dbutils.ScanRowsToStructRows(rows, ApprovalDelegation, &totalCount); err != nil {
+ logrus.Warn("GetApprovalDelegationsListDB:ScanRowsToStructRows", err)
+ continue
+ }
+ ApprovalDelegations = append(ApprovalDelegations, ApprovalDelegation)
+ }
+
+ return ApprovalDelegations, totalCount, nil
+}
+
+func (u *ApprovalDelegationDB) CreateApprovalDelegationDB(ctx context.Context, tx pgx.Tx, ApprovalDelegationObj *typescore.ApprovalDelegation, returnObj ...bool) (*typescore.ApprovalDelegation, pgx.Tx, error) {
+ if ApprovalDelegationObj == nil {
+ return nil, nil, errors.New("ApprovalDelegation obj is nil")
+ }
+
+ var insertedID uint64
+
+ err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error {
+ query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
+ Insert(dbcoretablenames.TableNameApprovalDelegations.ToString())
+
+ sqlV, args, err := dbutils.GenerateInsertRequest(query, ApprovalDelegationObj)
+ if err != nil {
+ return err
+ }
+
+ *sqlV = *sqlV + " RETURNING id"
+
+ return tx.QueryRow(ctx, *sqlV, args...).Scan(&insertedID)
+ })
+
+ if err != nil {
+ return nil, tx, err
+ }
+
+ returnObjBool := len(returnObj) > 0 && returnObj[0]
+ if returnObjBool && insertedID > 0 {
+ created, err := u.GetApprovalDelegationByIDDB(ctx, insertedID)
+ return created, tx, err
+ }
+
+ return nil, tx, nil
+}
+
+func (u *ApprovalDelegationDB) UpdateApprovalDelegationDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.ApprovalDelegation, returnObj ...bool) (*typescore.ApprovalDelegation, pgx.Tx, error) {
+ if paramsUpdate.ID == nil {
+ return nil, nil, errors.New("ApprovalDelegation obj is nil")
+ }
+
+ err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error {
+ query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).Update(dbcoretablenames.TableNameApprovalDelegations.ToString())
+ query = dbutils.AddNonNullFieldsToQueryUpdate(query, *paramsUpdate)
+ query = query.Where(squirrel.Eq{"id": paramsUpdate.ID})
+
+ sql, args, err := query.ToSql()
+ if err != nil {
+ return err
+ }
+
+ _, err = tx.Exec(ctx, sql, args...)
+ if err != nil {
+ return err
+ }
+
+ return nil
+ })
+
+ if err != nil {
+ return nil, tx, err
+ }
+
+ returnObjBool := false
+ if len(returnObj) > 0 {
+ returnObjBool = returnObj[0]
+ }
+
+ if returnObjBool {
+ options := typescore.ListDbOptions{Filtering: &typescore.ApprovalDelegation{ID: paramsUpdate.ID}}
+ getInfoUp, _, err := u.GetApprovalDelegationsListDB(ctx, options)
+ if err != nil {
+ return nil, nil, err
+ }
+ if len(getInfoUp) > 0 {
+ return getInfoUp[0], tx, nil
+ }
+ }
+
+ return nil, tx, nil
+}
+
+func (u *ApprovalDelegationDB) DeleteApprovalDelegationDB(ctx context.Context, params *typescore.ApprovalDelegation) error {
+ if params != nil && params.ID != nil {
+ query, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
+ Delete(dbcoretablenames.TableNameApprovalDelegations.ToString()).
+ Where(squirrel.Eq{"id": *params.ID}).
+ ToSql()
+
+ if err != nil {
+ return err
+ }
+
+ rows, err := u.pool.Query(ctx, query, args...)
+ if err != nil {
+ return err
+ }
+ defer rows.Close()
+
+ return nil
+ } else {
+ return errors.New("ApprovalDelegation obj is nil")
+ }
+}
+
+func (u *ApprovalDelegationDB) GetApprovalDelegationByIDDB(ctx context.Context, id uint64) (*typescore.ApprovalDelegation, error) {
+ approvals, _, err := u.GetApprovalDelegationsListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.ApprovalDelegation{ID: &id},
+ })
+ if err != nil {
+ return nil, err
+ }
+ if len(approvals) == 0 {
+ return nil, nil
+ }
+ return approvals[0], nil
+}
diff --git a/core/db/methods/approval_file.go b/core/db/methods/approval_file.go
new file mode 100644
index 0000000..78d46e0
--- /dev/null
+++ b/core/db/methods/approval_file.go
@@ -0,0 +1,217 @@
+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"
+ "github.com/sirupsen/logrus"
+)
+
+type ApprovalFileDB struct {
+ pool *pgxpool.Pool
+}
+
+func NewApprovalFileDB(pool *pgxpool.Pool) *ApprovalFileDB {
+ return &ApprovalFileDB{
+ pool: pool,
+ }
+}
+
+type ApprovalFileDBI interface {
+ GetApprovalFilesListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.ApprovalFile, uint64, error)
+ CreateApprovalFileDB(ctx context.Context, tx pgx.Tx, ApprovalFileObj *typescore.ApprovalFile, returnObj ...bool) (*typescore.ApprovalFile, pgx.Tx, error)
+ UpdateApprovalFileDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.ApprovalFile, returnObj ...bool) (*typescore.ApprovalFile, pgx.Tx, error)
+ DeleteApprovalFileDB(ctx context.Context, params *typescore.ApprovalFile) error
+ GetFilesByApprovalIDDB(ctx context.Context, id uint64) ([]*typescore.ApprovalFile, error)
+ GetApprovalFileByIDDB(ctx context.Context, id uint64) (*typescore.ApprovalFile, error)
+}
+
+func (u *ApprovalFileDB) GetApprovalFilesListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.ApprovalFile, uint64, error) {
+ fields := dbutils.GetStructFieldsDB(&typescore.ApprovalFile{}, dbcoretablenames.TableNameApprovalFiles.ToString())
+ selectFields := append(fields, "COUNT(*) OVER() AS total_count")
+
+ options, filter, err := dbutils.GetOptionsDB[typescore.ApprovalFile](opts...)
+ if err != nil {
+ return nil, 0, err
+ }
+
+ query := dbutils.BuildSelectQuery(dbcoretablenames.TableNameApprovalFiles.ToString(), selectFields)
+ query = dbutils.SetterLimitAndOffsetQuery(query, options.Offset, options.Limit)
+ query = dbutils.ApplyFilters(query, filter, options.LikeFields, dbcoretablenames.TableNameApprovalFiles.ToString())
+ query = query.OrderBy("created_at DESC")
+
+ 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 ApprovalFiles []*typescore.ApprovalFile
+ var totalCount uint64
+ for rows.Next() {
+ ApprovalFile := &typescore.ApprovalFile{}
+ if err := dbutils.ScanRowsToStructRows(rows, ApprovalFile, &totalCount); err != nil {
+ logrus.Warn("GetApprovalFilesListDB:ScanRowsToStructRows", err)
+ continue
+ }
+ ApprovalFiles = append(ApprovalFiles, ApprovalFile)
+ }
+
+ return ApprovalFiles, totalCount, nil
+}
+
+func (u *ApprovalFileDB) CreateApprovalFileDB(ctx context.Context, tx pgx.Tx, ApprovalFileObj *typescore.ApprovalFile, returnObj ...bool) (*typescore.ApprovalFile, pgx.Tx, error) {
+ if ApprovalFileObj == nil {
+ return nil, nil, errors.New("ApprovalFile obj is nil")
+ }
+
+ var insertedID uint64
+
+ err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error {
+ query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
+ Insert(dbcoretablenames.TableNameApprovalFiles.ToString())
+
+ sqlV, args, err := dbutils.GenerateInsertRequest(query, ApprovalFileObj)
+ if err != nil {
+ return err
+ }
+
+ *sqlV = *sqlV + " RETURNING id"
+
+ return tx.QueryRow(ctx, *sqlV, args...).Scan(&insertedID)
+ })
+
+ if err != nil {
+ return nil, tx, err
+ }
+
+ returnObjBool := len(returnObj) > 0 && returnObj[0]
+ if returnObjBool && insertedID > 0 {
+ created, err := u.GetApprovalFileByIDDB(ctx, insertedID)
+ return created, tx, err
+ }
+
+ return nil, tx, nil
+}
+
+func (u *ApprovalFileDB) UpdateApprovalFileDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.ApprovalFile, returnObj ...bool) (*typescore.ApprovalFile, pgx.Tx, error) {
+ if paramsUpdate.ID == nil {
+ return nil, nil, errors.New("ApprovalFile obj is nil")
+ }
+
+ err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error {
+ query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).Update(dbcoretablenames.TableNameApprovalFiles.ToString())
+ query = dbutils.AddNonNullFieldsToQueryUpdate(query, *paramsUpdate)
+ query = query.Where(squirrel.Eq{"id": paramsUpdate.ID})
+
+ sql, args, err := query.ToSql()
+ if err != nil {
+ return err
+ }
+
+ _, err = tx.Exec(ctx, sql, args...)
+ if err != nil {
+ return err
+ }
+
+ return nil
+ })
+
+ if err != nil {
+ return nil, tx, err
+ }
+
+ returnObjBool := false
+ if len(returnObj) > 0 {
+ returnObjBool = returnObj[0]
+ }
+
+ if returnObjBool {
+ options := typescore.ListDbOptions{Filtering: &typescore.ApprovalFile{ID: paramsUpdate.ID}}
+ getInfoUp, _, err := u.GetApprovalFilesListDB(ctx, options)
+ if err != nil {
+ return nil, nil, err
+ }
+ if len(getInfoUp) > 0 {
+ return getInfoUp[0], tx, nil
+ }
+ }
+
+ return nil, tx, nil
+}
+
+func (u *ApprovalFileDB) DeleteApprovalFileDB(ctx context.Context, params *typescore.ApprovalFile) error {
+ if params != nil && params.ID != nil {
+ query, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
+ Delete(dbcoretablenames.TableNameApprovalFiles.ToString()).
+ Where(squirrel.Eq{"id": *params.ID}).
+ ToSql()
+
+ if err != nil {
+ return err
+ }
+
+ rows, err := u.pool.Query(ctx, query, args...)
+ if err != nil {
+ return err
+ }
+ defer rows.Close()
+
+ return nil
+ } else {
+ return errors.New("ApprovalFile obj is nil")
+ }
+}
+
+func (u *ApprovalFileDB) GetFilesByApprovalIDDB(ctx context.Context, id uint64) ([]*typescore.ApprovalFile, error) {
+ ApprovalFiles, _, err := u.GetApprovalFilesListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.ApprovalFile{ApprovalID: &id},
+ })
+ if err != nil {
+ return nil, err
+ }
+ return ApprovalFiles, nil
+}
+
+func (u *ApprovalFileDB) GetApprovalFileByIDDB(ctx context.Context, id uint64) (*typescore.ApprovalFile, error) {
+ approvals, _, err := u.GetApprovalFilesListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.Approval{ID: &id},
+ })
+ if err != nil {
+ return nil, err
+ }
+ if len(approvals) == 0 {
+ return nil, nil
+ }
+ return approvals[0], nil
+}
+
+// queryApprovalFiles — общий сканер строк
+func (u *ApprovalFileDB) queryApprovalFiles(ctx context.Context, sql string, args []interface{}) ([]*typescore.ApprovalFile, error) {
+ rows, err := u.pool.Query(ctx, sql, args...)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+
+ var result []*typescore.ApprovalFile
+ for rows.Next() {
+ a := &typescore.ApprovalFile{}
+ if err := dbutils.ScanRowsToStructRows(rows, a, nil); err != nil {
+ logrus.Warn("queryApprovalFiles:ScanRowsToStruct", err)
+ continue
+ }
+ result = append(result, a)
+ }
+ return result, nil
+}
diff --git a/core/db/methods/approval_step.go b/core/db/methods/approval_step.go
new file mode 100644
index 0000000..9cf04d3
--- /dev/null
+++ b/core/db/methods/approval_step.go
@@ -0,0 +1,234 @@
+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/sirupsen/logrus"
+
+ "github.com/Masterminds/squirrel"
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgxpool"
+)
+
+type ApprovalStepDB struct {
+ pool *pgxpool.Pool
+}
+
+func NewApprovalStepDB(pool *pgxpool.Pool) *ApprovalStepDB {
+ return &ApprovalStepDB{
+ pool: pool,
+ }
+}
+
+type ApprovalStepDBI interface {
+ GetApprovalStepsListDB(ctx context.Context, options ...typescore.ListDbOptions) ([]*typescore.ApprovalStep, uint64, error)
+ CreateApprovalStepDB(ctx context.Context, tx pgx.Tx, ApprovalStepObj *typescore.ApprovalStep, returnObj ...bool) (*typescore.ApprovalStep, pgx.Tx, error)
+ UpdateApprovalStepDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.ApprovalStep, returnObj ...bool) (*typescore.ApprovalStep, pgx.Tx, error)
+ DeleteApprovalStepDB(ctx context.Context, params *typescore.ApprovalStep) error
+
+ GetActiveStepDB(ctx context.Context, approvalID uint64) (*typescore.ApprovalStep, error)
+ GetNextStepDB(ctx context.Context, approvalID uint64, currentOrder int) (*typescore.ApprovalStep, error)
+}
+
+func (u *ApprovalStepDB) GetApprovalStepsListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.ApprovalStep, uint64, error) {
+ fields := dbutils.GetStructFieldsDB(&typescore.ApprovalStep{}, dbcoretablenames.TableNameApprovalSteps.ToString())
+ selectFields := append(fields, "COUNT(*) OVER() AS total_count")
+
+ options, filter, err := dbutils.GetOptionsDB[typescore.ApprovalStep](opts...)
+ if err != nil {
+ return nil, 0, err
+ }
+
+ query := dbutils.BuildSelectQuery(dbcoretablenames.TableNameApprovalSteps.ToString(), selectFields)
+ query = dbutils.SetterLimitAndOffsetQuery(query, options.Offset, options.Limit)
+ query = dbutils.ApplyFilters(query, filter, options.LikeFields, dbcoretablenames.TableNameApprovalSteps.ToString())
+ query = query.OrderBy("created_at DESC")
+
+ 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 ApprovalSteps []*typescore.ApprovalStep
+ var totalCount uint64
+ for rows.Next() {
+ ApprovalStep := &typescore.ApprovalStep{}
+ if err := dbutils.ScanRowsToStructRows(rows, ApprovalStep, &totalCount); err != nil {
+ logrus.Warn("GetApprovalStepsListDB:ScanRowsToStructRows", err)
+ continue
+ }
+ ApprovalSteps = append(ApprovalSteps, ApprovalStep)
+ }
+
+ return ApprovalSteps, totalCount, nil
+}
+
+func (u *ApprovalStepDB) CreateApprovalStepDB(ctx context.Context, tx pgx.Tx, ApprovalStepObj *typescore.ApprovalStep, returnObj ...bool) (*typescore.ApprovalStep, pgx.Tx, error) {
+ if ApprovalStepObj == nil {
+ return nil, nil, errors.New("ApprovalStep obj is nil")
+ }
+
+ err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error {
+ query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).Insert(dbcoretablenames.TableNameApprovalSteps.ToString())
+
+ sqlV, args, err := dbutils.GenerateInsertRequest(query, ApprovalStepObj)
+ if err != nil {
+ return err
+ }
+
+ _, err = tx.Exec(ctx, *sqlV, args...)
+ if err != nil {
+ return err
+ }
+
+ return nil
+ })
+
+ if err != nil {
+ return nil, tx, err
+ }
+
+ returnObjBool := false
+ if len(returnObj) > 0 {
+ returnObjBool = returnObj[0]
+ }
+ if returnObjBool {
+ ApprovalStep, _, err := u.GetApprovalStepsListDB(ctx, typescore.ListDbOptions{Filtering: ApprovalStepObj})
+ if err != nil {
+ return nil, tx, err
+ }
+ if len(ApprovalStep) > 0 {
+ return ApprovalStep[0], tx, nil
+ }
+ }
+
+ return nil, tx, nil
+}
+
+func (u *ApprovalStepDB) UpdateApprovalStepDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.ApprovalStep, returnObj ...bool) (*typescore.ApprovalStep, pgx.Tx, error) {
+ if paramsUpdate.ID == nil {
+ return nil, nil, errors.New("ApprovalStep obj is nil")
+ }
+
+ err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error {
+ query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).Update(dbcoretablenames.TableNameApprovalSteps.ToString())
+ query = dbutils.AddNonNullFieldsToQueryUpdate(query, *paramsUpdate)
+ query = query.Where(squirrel.Eq{"id": paramsUpdate.ID})
+
+ sql, args, err := query.ToSql()
+ if err != nil {
+ return err
+ }
+
+ _, err = tx.Exec(ctx, sql, args...)
+ if err != nil {
+ return err
+ }
+
+ return nil
+ })
+
+ if err != nil {
+ return nil, tx, err
+ }
+
+ returnObjBool := false
+ if len(returnObj) > 0 {
+ returnObjBool = returnObj[0]
+ }
+
+ if returnObjBool {
+ options := typescore.ListDbOptions{Filtering: &typescore.ApprovalStep{ID: paramsUpdate.ID}}
+ getInfoUp, _, err := u.GetApprovalStepsListDB(ctx, options)
+ if err != nil {
+ return nil, nil, err
+ }
+ if len(getInfoUp) > 0 {
+ return getInfoUp[0], tx, nil
+ }
+ }
+
+ return nil, tx, nil
+}
+
+func (u *ApprovalStepDB) DeleteApprovalStepDB(ctx context.Context, params *typescore.ApprovalStep) error {
+ if params != nil && params.ID != nil {
+ query, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
+ Delete(dbcoretablenames.TableNameApprovalSteps.ToString()).
+ Where(squirrel.Eq{"id": *params.ID}).
+ ToSql()
+
+ if err != nil {
+ return err
+ }
+
+ rows, err := u.pool.Query(ctx, query, args...)
+ if err != nil {
+ return err
+ }
+ defer rows.Close()
+
+ return nil
+ } else {
+ return errors.New("approvalStep obj is nil")
+ }
+}
+
+// GetActiveStepDB возвращает текущий активный шаг — первый pending по порядку.
+func (u *ApprovalStepDB) GetActiveStepDB(ctx context.Context, approvalID uint64) (*typescore.ApprovalStep, error) {
+ pendingStatus := "pending"
+ steps, _, err := u.GetApprovalStepsListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.ApprovalStep{
+ ApprovalID: &approvalID,
+ Status: &pendingStatus,
+ },
+ Limit: func() *uint64 { v := uint64(1); return &v }(),
+ })
+ if err != nil {
+ return nil, err
+ }
+ if len(steps) == 0 {
+ return nil, nil
+ }
+ return steps[0], nil
+}
+
+// GetNextStepDB возвращает следующий шаг после текущего (status = waiting, step_order > current).
+func (u *ApprovalStepDB) GetNextStepDB(ctx context.Context, approvalID uint64, currentOrder int) (*typescore.ApprovalStep, error) {
+ sql, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
+ Select(dbutils.GetStructFieldsDB(&typescore.ApprovalStep{}, dbcoretablenames.TableNameApprovalSteps.ToString())...).
+ From(dbcoretablenames.TableNameApprovalSteps.ToString()).
+ Where(squirrel.Eq{"approval_id": approvalID}).
+ Where(squirrel.Eq{"status": "waiting"}).
+ Where(squirrel.Gt{"step_order": currentOrder}).
+ OrderBy("step_order ASC").
+ Limit(1).
+ ToSql()
+ if err != nil {
+ return nil, err
+ }
+
+ rows, err := u.pool.Query(ctx, sql, args...)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+
+ if rows.Next() {
+ step := &typescore.ApprovalStep{}
+ if err := dbutils.ScanRowsToStructRows(rows, step, nil); err != nil {
+ return nil, err
+ }
+ return step, nil
+ }
+ return nil, nil
+}
diff --git a/core/db/methods/approval_task.go b/core/db/methods/approval_task.go
new file mode 100644
index 0000000..dcf256b
--- /dev/null
+++ b/core/db/methods/approval_task.go
@@ -0,0 +1,249 @@
+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"
+ "fmt"
+ "github.com/Masterminds/squirrel"
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgxpool"
+ "github.com/sirupsen/logrus"
+ "time"
+)
+
+type ApprovalTaskDB struct {
+ pool *pgxpool.Pool
+}
+
+func NewApprovalTaskDB(pool *pgxpool.Pool) *ApprovalTaskDB {
+ return &ApprovalTaskDB{
+ pool: pool,
+ }
+}
+
+type ApprovalTaskDBI interface {
+ GetApprovalTasksListDB(ctx context.Context, options ...typescore.ListDbOptions) ([]*typescore.ApprovalTask, uint64, error)
+ CreateApprovalTaskDB(ctx context.Context, tx pgx.Tx, ApprovalTaskObj *typescore.ApprovalTask, returnObj ...bool) (*typescore.ApprovalTask, pgx.Tx, error)
+ UpdateApprovalTaskDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.ApprovalTask, returnObj ...bool) (*typescore.ApprovalTask, pgx.Tx, error)
+ DeleteApprovalTaskDB(ctx context.Context, params *typescore.ApprovalTask) error
+ GetApprovalTaskByIDDB(ctx context.Context, id uint64) (*typescore.ApprovalTask, error)
+}
+
+func (u *ApprovalTaskDB) GetApprovalTasksListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.ApprovalTask, uint64, error) {
+ fields := dbutils.GetStructFieldsDB(&typescore.ApprovalTask{}, dbcoretablenames.TableNameApprovalTasks.ToString())
+ selectFields := append(fields, "COUNT(*) OVER() AS total_count")
+
+ options, filter, err := dbutils.GetOptionsDB[typescore.ApprovalTask](opts...)
+ if err != nil {
+ return nil, 0, err
+ }
+
+ query := dbutils.BuildSelectQuery(dbcoretablenames.TableNameApprovalTasks.ToString(), selectFields)
+ query = dbutils.SetterLimitAndOffsetQuery(query, options.Offset, options.Limit)
+ query = dbutils.ApplyFilters(query, filter, options.LikeFields, dbcoretablenames.TableNameApprovalTasks.ToString())
+ query = query.OrderBy("created_at DESC")
+
+ 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 ApprovalTasks []*typescore.ApprovalTask
+ var totalCount uint64
+ for rows.Next() {
+ ApprovalTask := &typescore.ApprovalTask{}
+ if err := dbutils.ScanRowsToStructRows(rows, ApprovalTask, &totalCount); err != nil {
+ logrus.Warn("GetApprovalTasksListDB:ScanRowsToStructRows", err)
+ continue
+ }
+ ApprovalTasks = append(ApprovalTasks, ApprovalTask)
+ }
+
+ return ApprovalTasks, totalCount, nil
+}
+
+func (u *ApprovalTaskDB) CreateApprovalTaskDB(ctx context.Context, tx pgx.Tx, ApprovalTaskObj *typescore.ApprovalTask, returnObj ...bool) (*typescore.ApprovalTask, pgx.Tx, error) {
+ if ApprovalTaskObj == nil {
+ return nil, nil, errors.New("ApprovalTask obj is nil")
+ }
+
+ var insertedID uint64
+
+ err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error {
+ query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
+ Insert(dbcoretablenames.TableNameApprovalTasks.ToString())
+
+ sqlV, args, err := dbutils.GenerateInsertRequest(query, ApprovalTaskObj)
+ if err != nil {
+ return err
+ }
+
+ *sqlV = *sqlV + " RETURNING id"
+
+ return tx.QueryRow(ctx, *sqlV, args...).Scan(&insertedID)
+ })
+
+ if err != nil {
+ return nil, tx, err
+ }
+
+ returnObjBool := len(returnObj) > 0 && returnObj[0]
+ if returnObjBool && insertedID > 0 {
+ created, err := u.GetApprovalTaskByIDDB(ctx, insertedID)
+ return created, tx, err
+ }
+
+ return nil, tx, nil
+}
+
+func (u *ApprovalTaskDB) UpdateApprovalTaskDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.ApprovalTask, returnObj ...bool) (*typescore.ApprovalTask, pgx.Tx, error) {
+ if paramsUpdate.ID == nil {
+ return nil, nil, errors.New("ApprovalTask obj is nil")
+ }
+
+ err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error {
+ query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).Update(dbcoretablenames.TableNameApprovalTasks.ToString())
+ query = dbutils.AddNonNullFieldsToQueryUpdate(query, *paramsUpdate)
+ query = query.Where(squirrel.Eq{"id": paramsUpdate.ID})
+
+ sql, args, err := query.ToSql()
+ if err != nil {
+ return err
+ }
+
+ _, err = tx.Exec(ctx, sql, args...)
+ if err != nil {
+ return err
+ }
+
+ return nil
+ })
+
+ if err != nil {
+ return nil, tx, err
+ }
+
+ returnObjBool := false
+ if len(returnObj) > 0 {
+ returnObjBool = returnObj[0]
+ }
+
+ if returnObjBool {
+ options := typescore.ListDbOptions{Filtering: &typescore.ApprovalTask{ID: paramsUpdate.ID}}
+ getInfoUp, _, err := u.GetApprovalTasksListDB(ctx, options)
+ if err != nil {
+ return nil, nil, err
+ }
+ if len(getInfoUp) > 0 {
+ return getInfoUp[0], tx, nil
+ }
+ }
+
+ return nil, tx, nil
+}
+
+func (u *ApprovalTaskDB) DeleteApprovalTaskDB(ctx context.Context, params *typescore.ApprovalTask) error {
+ if params != nil && params.ID != nil {
+ query, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
+ Delete(dbcoretablenames.TableNameApprovalTasks.ToString()).
+ Where(squirrel.Eq{"id": *params.ID}).
+ ToSql()
+
+ if err != nil {
+ return err
+ }
+
+ rows, err := u.pool.Query(ctx, query, args...)
+ if err != nil {
+ return err
+ }
+ defer rows.Close()
+
+ return nil
+ } else {
+ return errors.New("ApprovalTask obj is nil")
+ }
+}
+
+func (u *ApprovalTaskDB) GetApprovalTaskByIDDB(ctx context.Context, id uint64) (*typescore.ApprovalTask, error) {
+ ApprovalTasks, _, err := u.GetApprovalTasksListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.ApprovalTask{ID: &id},
+ })
+ if err != nil {
+ return nil, err
+ }
+ if len(ApprovalTasks) == 0 {
+ return nil, nil
+ }
+ return ApprovalTasks[0], nil
+}
+
+func (u *ApprovalTaskDB) GetTasksForReportDB(ctx context.Context, filter typescore.TaskReportFilter) ([]*typescore.ApprovalTask, error) {
+ q := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
+ Select("DISTINCT t.*").
+ From(dbcoretablenames.TableNameApprovalTasks.ToString() + " t").
+ Join(dbcoretablenames.TableNameApprovals.ToString() + " a ON a.id = t.approval_id").
+ OrderBy("t.created_at DESC")
+
+ if !filter.AllAccess && filter.UserID != nil {
+ subQ1 := buildApprovalIdSubquery("initiator", filter.UserID)
+ subQ2 := buildApprovalIdSubquery("approver", filter.UserID)
+ subQ3 := buildApprovalIdSubquery("observer", filter.UserID)
+ subQ4 := buildApprovalIdSubquery("executor", filter.UserID)
+
+ s1, a1, _ := subQ1.PlaceholderFormat(squirrel.Question).ToSql()
+ s2, a2, _ := subQ2.PlaceholderFormat(squirrel.Question).ToSql()
+ s3, a3, _ := subQ3.PlaceholderFormat(squirrel.Question).ToSql()
+ s4, a4, _ := subQ4.PlaceholderFormat(squirrel.Question).ToSql()
+
+ unionSQL := fmt.Sprintf("(%s) UNION (%s) UNION (%s) UNION (%s)", s1, s2, s3, s4)
+ allArgs := append(append(append(a1, a2...), a3...), a4...)
+
+ q = q.Where(squirrel.Expr("a.id IN ("+unionSQL+")", allArgs...))
+ }
+
+ // Применяем фильтр по датам (по дате создания задачи)
+ if filter.DateFrom != nil {
+ q = q.Where(squirrel.GtOrEq{"t.created_at": filter.DateFrom})
+ }
+ if filter.DateTo != nil {
+ // До конца дня
+ endOfDay := filter.DateTo.Add(24*time.Hour - time.Second)
+ q = q.Where(squirrel.LtOrEq{"t.created_at": endOfDay})
+ }
+
+ sql, args, err := q.ToSql()
+ if err != nil {
+ return nil, err
+ }
+ return u.queryTasks(ctx, sql, args)
+}
+
+// queryTasks — вспомогательная функция для выполнения запроса задач.
+func (u *ApprovalTaskDB) queryTasks(ctx context.Context, sql string, args []interface{}) ([]*typescore.ApprovalTask, error) {
+ rows, err := u.pool.Query(ctx, sql, args...)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+
+ var result []*typescore.ApprovalTask
+ for rows.Next() {
+ task := &typescore.ApprovalTask{}
+ if err := dbutils.ScanRowsToStructRows(rows, task, nil); err != nil {
+ logrus.Warn("queryTasks:ScanRowsToStruct", err)
+ continue
+ }
+ result = append(result, task)
+ }
+ return result, nil
+}
diff --git a/core/db/methods/approval_topic.go b/core/db/methods/approval_topic.go
new file mode 100644
index 0000000..be16758
--- /dev/null
+++ b/core/db/methods/approval_topic.go
@@ -0,0 +1,210 @@
+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/sirupsen/logrus"
+
+ "github.com/Masterminds/squirrel"
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgxpool"
+)
+
+type ApprovalTopicDB struct {
+ pool *pgxpool.Pool
+}
+
+func NewApprovalTopicDB(pool *pgxpool.Pool) *ApprovalTopicDB {
+ return &ApprovalTopicDB{
+ pool: pool,
+ }
+}
+
+type ApprovalTopicDBI interface {
+ GetApprovalTopicsListDB(ctx context.Context, options ...typescore.ListDbOptions) ([]*typescore.ApprovalTopic, uint64, error)
+ CreateApprovalTopicDB(ctx context.Context, tx pgx.Tx, ApprovalTopicObj *typescore.ApprovalTopic, returnObj ...bool) (*typescore.ApprovalTopic, pgx.Tx, error)
+ UpdateApprovalTopicDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.ApprovalTopic, returnObj ...bool) (*typescore.ApprovalTopic, pgx.Tx, error)
+ DeleteApprovalTopicDB(ctx context.Context, params *typescore.ApprovalTopic) error
+
+ GetApprovalTopicByIDDB(ctx context.Context, id uint64) (*typescore.ApprovalTopic, error)
+ GetApprovalTopicByCodeDB(ctx context.Context, code string) (*typescore.ApprovalTopic, error)
+}
+
+func (u *ApprovalTopicDB) GetApprovalTopicsListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.ApprovalTopic, uint64, error) {
+ fields := dbutils.GetStructFieldsDB(&typescore.ApprovalTopic{}, dbcoretablenames.TableNameApprovalTopics.ToString())
+ selectFields := append(fields, "COUNT(*) OVER() AS total_count")
+
+ options, filter, err := dbutils.GetOptionsDB[typescore.ApprovalTopic](opts...)
+ if err != nil {
+ return nil, 0, err
+ }
+
+ query := dbutils.BuildSelectQuery(dbcoretablenames.TableNameApprovalTopics.ToString(), selectFields)
+ query = dbutils.SetterLimitAndOffsetQuery(query, options.Offset, options.Limit)
+ query = dbutils.ApplyFilters(query, filter, options.LikeFields, dbcoretablenames.TableNameApprovalTopics.ToString())
+ query = query.OrderBy("created_at DESC")
+
+ 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 ApprovalTopics []*typescore.ApprovalTopic
+ var totalCount uint64
+ for rows.Next() {
+ ApprovalTopic := &typescore.ApprovalTopic{}
+ if err := dbutils.ScanRowsToStructRows(rows, ApprovalTopic, &totalCount); err != nil {
+ logrus.Warn("GetApprovalTopicsListDB:ScanRowsToStructRows", err)
+ continue
+ }
+ ApprovalTopics = append(ApprovalTopics, ApprovalTopic)
+ }
+
+ return ApprovalTopics, totalCount, nil
+}
+
+func (u *ApprovalTopicDB) CreateApprovalTopicDB(ctx context.Context, tx pgx.Tx, ApprovalTopicObj *typescore.ApprovalTopic, returnObj ...bool) (*typescore.ApprovalTopic, pgx.Tx, error) {
+ if ApprovalTopicObj == nil {
+ return nil, nil, errors.New("ApprovalTopic obj is nil")
+ }
+
+ err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error {
+ query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).Insert(dbcoretablenames.TableNameApprovalTopics.ToString())
+
+ sqlV, args, err := dbutils.GenerateInsertRequest(query, ApprovalTopicObj)
+ if err != nil {
+ return err
+ }
+
+ _, err = tx.Exec(ctx, *sqlV, args...)
+ if err != nil {
+ return err
+ }
+
+ return nil
+ })
+
+ if err != nil {
+ return nil, tx, err
+ }
+
+ returnObjBool := false
+ if len(returnObj) > 0 {
+ returnObjBool = returnObj[0]
+ }
+ if returnObjBool {
+ ApprovalTopic, _, err := u.GetApprovalTopicsListDB(ctx, typescore.ListDbOptions{Filtering: ApprovalTopicObj})
+ if err != nil {
+ return nil, tx, err
+ }
+ if len(ApprovalTopic) > 0 {
+ return ApprovalTopic[0], tx, nil
+ }
+ }
+
+ return nil, tx, nil
+}
+
+func (u *ApprovalTopicDB) UpdateApprovalTopicDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.ApprovalTopic, returnObj ...bool) (*typescore.ApprovalTopic, pgx.Tx, error) {
+ if paramsUpdate.ID == nil {
+ return nil, nil, errors.New("ApprovalTopic obj is nil")
+ }
+
+ err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error {
+ query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).Update(dbcoretablenames.TableNameApprovalTopics.ToString())
+ query = dbutils.AddNonNullFieldsToQueryUpdate(query, *paramsUpdate)
+ query = query.Where(squirrel.Eq{"id": paramsUpdate.ID})
+
+ sql, args, err := query.ToSql()
+ if err != nil {
+ return err
+ }
+
+ _, err = tx.Exec(ctx, sql, args...)
+ if err != nil {
+ return err
+ }
+
+ return nil
+ })
+
+ if err != nil {
+ return nil, tx, err
+ }
+
+ returnObjBool := false
+ if len(returnObj) > 0 {
+ returnObjBool = returnObj[0]
+ }
+
+ if returnObjBool {
+ options := typescore.ListDbOptions{Filtering: &typescore.ApprovalTopic{ID: paramsUpdate.ID}}
+ getInfoUp, _, err := u.GetApprovalTopicsListDB(ctx, options)
+ if err != nil {
+ return nil, nil, err
+ }
+ if len(getInfoUp) > 0 {
+ return getInfoUp[0], tx, nil
+ }
+ }
+
+ return nil, tx, nil
+}
+
+func (u *ApprovalTopicDB) DeleteApprovalTopicDB(ctx context.Context, params *typescore.ApprovalTopic) error {
+ if params != nil && params.ID != nil {
+ query, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
+ Delete(dbcoretablenames.TableNameApprovalTopics.ToString()).
+ Where(squirrel.Eq{"id": *params.ID}).
+ ToSql()
+
+ if err != nil {
+ return err
+ }
+
+ rows, err := u.pool.Query(ctx, query, args...)
+ if err != nil {
+ return err
+ }
+ defer rows.Close()
+
+ return nil
+ } else {
+ return errors.New("approvalTopic obj is nil")
+ }
+}
+
+func (u *ApprovalTopicDB) GetApprovalTopicByIDDB(ctx context.Context, id uint64) (*typescore.ApprovalTopic, error) {
+ topics, _, err := u.GetApprovalTopicsListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.ApprovalTopic{ID: &id},
+ })
+ if err != nil {
+ return nil, err
+ }
+ if len(topics) == 0 {
+ return nil, nil
+ }
+ return topics[0], nil
+}
+
+func (u *ApprovalTopicDB) GetApprovalTopicByCodeDB(ctx context.Context, code string) (*typescore.ApprovalTopic, error) {
+ topics, _, err := u.GetApprovalTopicsListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.ApprovalTopic{Code: &code},
+ })
+ if err != nil {
+ return nil, err
+ }
+ if len(topics) == 0 {
+ return nil, nil
+ }
+ return topics[0], nil
+}
diff --git a/core/db/methods/approval_topic_category.go b/core/db/methods/approval_topic_category.go
new file mode 100644
index 0000000..e78310d
--- /dev/null
+++ b/core/db/methods/approval_topic_category.go
@@ -0,0 +1,209 @@
+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/sirupsen/logrus"
+
+ "github.com/Masterminds/squirrel"
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgxpool"
+)
+
+type ApprovalTopicCategoryDB struct {
+ pool *pgxpool.Pool
+}
+
+func NewApprovalTopicCategoryDB(pool *pgxpool.Pool) *ApprovalTopicCategoryDB {
+ return &ApprovalTopicCategoryDB{
+ pool: pool,
+ }
+}
+
+type ApprovalTopicCategoryDBI interface {
+ GetApprovalTopicCategoryListDB(ctx context.Context, options ...typescore.ListDbOptions) ([]*typescore.ApprovalTopicCategory, uint64, error)
+ CreateApprovalTopicCategoryDB(ctx context.Context, tx pgx.Tx, ApprovalTopicCategoryObj *typescore.ApprovalTopicCategory, returnObj ...bool) (*typescore.ApprovalTopicCategory, pgx.Tx, error)
+ UpdateApprovalTopicCategoryDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.ApprovalTopicCategory, returnObj ...bool) (*typescore.ApprovalTopicCategory, pgx.Tx, error)
+ DeleteApprovalTopicCategoryDB(ctx context.Context, params *typescore.ApprovalTopicCategory) error
+ GetApprovalTopicCategoryByIDDB(ctx context.Context, id uint64) (*typescore.ApprovalTopicCategory, error)
+ GetApprovalTopicCategoryByCodeDB(ctx context.Context, code string) (*typescore.ApprovalTopicCategory, error)
+}
+
+func (u *ApprovalTopicCategoryDB) GetApprovalTopicCategoryListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.ApprovalTopicCategory, uint64, error) {
+ fields := dbutils.GetStructFieldsDB(&typescore.ApprovalTopicCategory{}, dbcoretablenames.TableNameApprovalTopicCategories.ToString())
+ selectFields := append(fields, "COUNT(*) OVER() AS total_count")
+
+ options, filter, err := dbutils.GetOptionsDB[typescore.ApprovalTopicCategory](opts...)
+ if err != nil {
+ return nil, 0, err
+ }
+
+ query := dbutils.BuildSelectQuery(dbcoretablenames.TableNameApprovalTopicCategories.ToString(), selectFields)
+ query = dbutils.SetterLimitAndOffsetQuery(query, options.Offset, options.Limit)
+ query = dbutils.ApplyFilters(query, filter, options.LikeFields, dbcoretablenames.TableNameApprovalTopicCategories.ToString())
+ query = query.OrderBy("created_at DESC")
+
+ 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 ApprovalTopicCategorys []*typescore.ApprovalTopicCategory
+ var totalCount uint64
+ for rows.Next() {
+ ApprovalTopicCategory := &typescore.ApprovalTopicCategory{}
+ if err := dbutils.ScanRowsToStructRows(rows, ApprovalTopicCategory, &totalCount); err != nil {
+ logrus.Warn("GetApprovalTopicCategorysListDB:ScanRowsToStructRows", err)
+ continue
+ }
+ ApprovalTopicCategorys = append(ApprovalTopicCategorys, ApprovalTopicCategory)
+ }
+
+ return ApprovalTopicCategorys, totalCount, nil
+}
+
+func (u *ApprovalTopicCategoryDB) CreateApprovalTopicCategoryDB(ctx context.Context, tx pgx.Tx, ApprovalTopicCategoryObj *typescore.ApprovalTopicCategory, returnObj ...bool) (*typescore.ApprovalTopicCategory, pgx.Tx, error) {
+ if ApprovalTopicCategoryObj == nil {
+ return nil, nil, errors.New("ApprovalTopicCategory obj is nil")
+ }
+
+ err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error {
+ query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).Insert(dbcoretablenames.TableNameApprovalTopicCategories.ToString())
+
+ sqlV, args, err := dbutils.GenerateInsertRequest(query, ApprovalTopicCategoryObj)
+ if err != nil {
+ return err
+ }
+
+ _, err = tx.Exec(ctx, *sqlV, args...)
+ if err != nil {
+ return err
+ }
+
+ return nil
+ })
+
+ if err != nil {
+ return nil, tx, err
+ }
+
+ returnObjBool := false
+ if len(returnObj) > 0 {
+ returnObjBool = returnObj[0]
+ }
+ if returnObjBool {
+ ApprovalTopicCategory, _, err := u.GetApprovalTopicCategoryListDB(ctx, typescore.ListDbOptions{Filtering: ApprovalTopicCategoryObj})
+ if err != nil {
+ return nil, tx, err
+ }
+ if len(ApprovalTopicCategory) > 0 {
+ return ApprovalTopicCategory[0], tx, nil
+ }
+ }
+
+ return nil, tx, nil
+}
+
+func (u *ApprovalTopicCategoryDB) UpdateApprovalTopicCategoryDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.ApprovalTopicCategory, returnObj ...bool) (*typescore.ApprovalTopicCategory, pgx.Tx, error) {
+ if paramsUpdate.ID == nil {
+ return nil, nil, errors.New("ApprovalTopicCategory obj is nil")
+ }
+
+ err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error {
+ query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).Update(dbcoretablenames.TableNameApprovalTopicCategories.ToString())
+ query = dbutils.AddNonNullFieldsToQueryUpdate(query, *paramsUpdate)
+ query = query.Where(squirrel.Eq{"id": paramsUpdate.ID})
+
+ sql, args, err := query.ToSql()
+ if err != nil {
+ return err
+ }
+
+ _, err = tx.Exec(ctx, sql, args...)
+ if err != nil {
+ return err
+ }
+
+ return nil
+ })
+
+ if err != nil {
+ return nil, tx, err
+ }
+
+ returnObjBool := false
+ if len(returnObj) > 0 {
+ returnObjBool = returnObj[0]
+ }
+
+ if returnObjBool {
+ options := typescore.ListDbOptions{Filtering: &typescore.ApprovalTopicCategory{ID: paramsUpdate.ID}}
+ getInfoUp, _, err := u.GetApprovalTopicCategoryListDB(ctx, options)
+ if err != nil {
+ return nil, nil, err
+ }
+ if len(getInfoUp) > 0 {
+ return getInfoUp[0], tx, nil
+ }
+ }
+
+ return nil, tx, nil
+}
+
+func (u *ApprovalTopicCategoryDB) DeleteApprovalTopicCategoryDB(ctx context.Context, params *typescore.ApprovalTopicCategory) error {
+ if params != nil && params.ID != nil {
+ query, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
+ Delete(dbcoretablenames.TableNameApprovalTopicCategories.ToString()).
+ Where(squirrel.Eq{"id": *params.ID}).
+ ToSql()
+
+ if err != nil {
+ return err
+ }
+
+ rows, err := u.pool.Query(ctx, query, args...)
+ if err != nil {
+ return err
+ }
+ defer rows.Close()
+
+ return nil
+ } else {
+ return errors.New("approvalTopicCategory obj is nil")
+ }
+}
+
+func (u *ApprovalTopicCategoryDB) GetApprovalTopicCategoryByIDDB(ctx context.Context, id uint64) (*typescore.ApprovalTopicCategory, error) {
+ categories, _, err := u.GetApprovalTopicCategoryListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.ApprovalTopicCategory{ID: &id},
+ })
+ if err != nil {
+ return nil, err
+ }
+ if len(categories) == 0 {
+ return nil, nil
+ }
+ return categories[0], nil
+}
+
+func (u *ApprovalTopicCategoryDB) GetApprovalTopicCategoryByCodeDB(ctx context.Context, code string) (*typescore.ApprovalTopicCategory, error) {
+ categories, _, err := u.GetApprovalTopicCategoryListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.ApprovalTopicCategory{Code: &code},
+ })
+ if err != nil {
+ return nil, err
+ }
+ if len(categories) == 0 {
+ return nil, nil
+ }
+ return categories[0], nil
+}
diff --git a/core/db/methods/department.go b/core/db/methods/department.go
new file mode 100644
index 0000000..c3d7797
--- /dev/null
+++ b/core/db/methods/department.go
@@ -0,0 +1,192 @@
+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/sirupsen/logrus"
+
+ "github.com/Masterminds/squirrel"
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgxpool"
+)
+
+type DepartmentDB struct {
+ pool *pgxpool.Pool
+}
+
+func NewDepartmentDB(pool *pgxpool.Pool) *DepartmentDB {
+ return &DepartmentDB{
+ pool: pool,
+ }
+}
+
+type DepartmentDBI interface {
+ GetDepartmentsListDB(ctx context.Context, options ...typescore.ListDbOptions) ([]*typescore.Department, uint64, error)
+ CreateDepartmentDB(ctx context.Context, tx pgx.Tx, DepartmentObj *typescore.Department, returnObj ...bool) (*typescore.Department, pgx.Tx, error)
+ UpdateDepartmentDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.Department, returnObj ...bool) (*typescore.Department, pgx.Tx, error)
+ DeleteDepartmentDB(ctx context.Context, params *typescore.Department) error
+ GetDepartmentByIDDB(ctx context.Context, id uint64) (*typescore.Department, error)
+}
+
+func (u *DepartmentDB) GetDepartmentsListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.Department, uint64, error) {
+ fields := dbutils.GetStructFieldsDB(&typescore.Department{}, dbcoretablenames.TableNameDepartments.ToString())
+ selectFields := append(fields, "COUNT(*) OVER() AS total_count")
+
+ options, filter, err := dbutils.GetOptionsDB[typescore.Department](opts...)
+ if err != nil {
+ return nil, 0, err
+ }
+
+ query := dbutils.BuildSelectQuery(dbcoretablenames.TableNameDepartments.ToString(), selectFields)
+ query = dbutils.SetterLimitAndOffsetQuery(query, options.Offset, options.Limit)
+ query = dbutils.ApplyFilters(query, filter, options.LikeFields, dbcoretablenames.TableNameDepartments.ToString())
+ query = query.OrderBy("created_at DESC")
+
+ 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 Departments []*typescore.Department
+ var totalCount uint64
+ for rows.Next() {
+ Department := &typescore.Department{}
+ if err := dbutils.ScanRowsToStructRows(rows, Department, &totalCount); err != nil {
+ logrus.Warn("GetDepartmentsListDB:ScanRowsToStructRows", err)
+ continue
+ }
+ Departments = append(Departments, Department)
+ }
+
+ return Departments, totalCount, nil
+}
+
+func (u *DepartmentDB) CreateDepartmentDB(ctx context.Context, tx pgx.Tx, DepartmentObj *typescore.Department, returnObj ...bool) (*typescore.Department, pgx.Tx, error) {
+ if DepartmentObj == nil {
+ return nil, nil, errors.New("Department obj is nil")
+ }
+
+ err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error {
+ query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).Insert(dbcoretablenames.TableNameDepartments.ToString())
+
+ sqlV, args, err := dbutils.GenerateInsertRequest(query, DepartmentObj)
+ if err != nil {
+ return err
+ }
+
+ _, err = tx.Exec(ctx, *sqlV, args...)
+ if err != nil {
+ return err
+ }
+
+ return nil
+ })
+
+ if err != nil {
+ return nil, tx, err
+ }
+
+ returnObjBool := false
+ if len(returnObj) > 0 {
+ returnObjBool = returnObj[0]
+ }
+ if returnObjBool {
+ Department, _, err := u.GetDepartmentsListDB(ctx, typescore.ListDbOptions{Filtering: DepartmentObj})
+ if err != nil {
+ return nil, tx, err
+ }
+ if len(Department) > 0 {
+ return Department[0], tx, nil
+ }
+ }
+
+ return nil, tx, nil
+}
+
+func (u *DepartmentDB) UpdateDepartmentDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.Department, returnObj ...bool) (*typescore.Department, pgx.Tx, error) {
+ if paramsUpdate.ID == nil {
+ return nil, nil, errors.New("Department obj is nil")
+ }
+
+ err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error {
+ query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).Update(dbcoretablenames.TableNameDepartments.ToString())
+ query = dbutils.AddNonNullFieldsToQueryUpdate(query, *paramsUpdate)
+ query = query.Where(squirrel.Eq{"id": paramsUpdate.ID})
+
+ sql, args, err := query.ToSql()
+ if err != nil {
+ return err
+ }
+
+ _, err = tx.Exec(ctx, sql, args...)
+ if err != nil {
+ return err
+ }
+
+ return nil
+ })
+
+ if err != nil {
+ return nil, tx, err
+ }
+
+ returnObjBool := false
+ if len(returnObj) > 0 {
+ returnObjBool = returnObj[0]
+ }
+
+ if returnObjBool {
+ options := typescore.ListDbOptions{Filtering: &typescore.Department{ID: paramsUpdate.ID}}
+ getInfoUp, _, err := u.GetDepartmentsListDB(ctx, options)
+ if err != nil {
+ return nil, nil, err
+ }
+ if len(getInfoUp) > 0 {
+ return getInfoUp[0], tx, nil
+ }
+ }
+
+ return nil, tx, nil
+}
+
+func (u *DepartmentDB) DeleteDepartmentDB(ctx context.Context, params *typescore.Department) error {
+ if params != nil && params.ID != nil {
+ query, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
+ Delete(dbcoretablenames.TableNameDepartments.ToString()).
+ Where(squirrel.Eq{"id": *params.ID}).
+ ToSql()
+
+ if err != nil {
+ return err
+ }
+
+ rows, err := u.pool.Query(ctx, query, args...)
+ if err != nil {
+ return err
+ }
+ defer rows.Close()
+
+ return nil
+ } else {
+ return errors.New("department obj is nil")
+ }
+}
+
+func (u *DepartmentDB) GetDepartmentByIDDB(ctx context.Context, id uint64) (*typescore.Department, error) {
+ deps, _, err := u.GetDepartmentsListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.Department{ID: &id},
+ })
+ if err != nil || len(deps) == 0 {
+ return nil, err
+ }
+ return deps[0], nil
+}
diff --git a/core/db/methods/permission.go b/core/db/methods/permission.go
new file mode 100644
index 0000000..9b6643f
--- /dev/null
+++ b/core/db/methods/permission.go
@@ -0,0 +1,221 @@
+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/sirupsen/logrus"
+
+ "github.com/Masterminds/squirrel"
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgxpool"
+)
+
+type PermissionDB struct {
+ pool *pgxpool.Pool
+}
+
+func NewPermissionDB(pool *pgxpool.Pool) *PermissionDB {
+ return &PermissionDB{
+ pool: pool,
+ }
+}
+
+type PermissionDBI interface {
+ GetPermissionsListDB(ctx context.Context, options ...typescore.ListDbOptions) ([]*typescore.Permission, uint64, error)
+ CreatePermissionDB(ctx context.Context, tx pgx.Tx, PermissionObj *typescore.Permission, returnObj ...bool) (*typescore.Permission, pgx.Tx, error)
+ UpdatePermissionDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.Permission, returnObj ...bool) (*typescore.Permission, pgx.Tx, error)
+ DeletePermissionDB(ctx context.Context, params *typescore.Permission) error
+ GetUserPermissionsDB(ctx context.Context, userID uint64, action string) ([]*typescore.Permission, error)
+}
+
+func (u *PermissionDB) GetPermissionsListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.Permission, uint64, error) {
+ fields := dbutils.GetStructFieldsDB(&typescore.Permission{}, dbcoretablenames.TableNamePermissions.ToString())
+ selectFields := append(fields, "COUNT(*) OVER() AS total_count")
+
+ options, filter, err := dbutils.GetOptionsDB[typescore.Permission](opts...)
+ if err != nil {
+ return nil, 0, err
+ }
+
+ query := dbutils.BuildSelectQuery(dbcoretablenames.TableNamePermissions.ToString(), selectFields)
+ query = dbutils.SetterLimitAndOffsetQuery(query, options.Offset, options.Limit)
+ query = dbutils.ApplyFilters(query, filter, options.LikeFields, dbcoretablenames.TableNamePermissions.ToString())
+ query = query.OrderBy("created_at DESC")
+
+ 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 Permissions []*typescore.Permission
+ var totalCount uint64
+ for rows.Next() {
+ Permission := &typescore.Permission{}
+ if err := dbutils.ScanRowsToStructRows(rows, Permission, &totalCount); err != nil {
+ logrus.Warn("GetPermissionsListDB:ScanRowsToStructRows", err)
+ continue
+ }
+ Permissions = append(Permissions, Permission)
+ }
+
+ return Permissions, totalCount, nil
+}
+
+func (u *PermissionDB) CreatePermissionDB(ctx context.Context, tx pgx.Tx, PermissionObj *typescore.Permission, returnObj ...bool) (*typescore.Permission, pgx.Tx, error) {
+ if PermissionObj == nil {
+ return nil, nil, errors.New("Permission obj is nil")
+ }
+
+ err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error {
+ query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).Insert(dbcoretablenames.TableNamePermissions.ToString())
+
+ sqlV, args, err := dbutils.GenerateInsertRequest(query, PermissionObj)
+ if err != nil {
+ return err
+ }
+
+ _, err = tx.Exec(ctx, *sqlV, args...)
+ if err != nil {
+ return err
+ }
+
+ return nil
+ })
+
+ if err != nil {
+ return nil, tx, err
+ }
+
+ returnObjBool := false
+ if len(returnObj) > 0 {
+ returnObjBool = returnObj[0]
+ }
+ if returnObjBool {
+ Permission, _, err := u.GetPermissionsListDB(ctx, typescore.ListDbOptions{Filtering: PermissionObj})
+ if err != nil {
+ return nil, tx, err
+ }
+ if len(Permission) > 0 {
+ return Permission[0], tx, nil
+ }
+ }
+
+ return nil, tx, nil
+}
+
+func (u *PermissionDB) UpdatePermissionDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.Permission, returnObj ...bool) (*typescore.Permission, pgx.Tx, error) {
+ if paramsUpdate.ID == nil {
+ return nil, nil, errors.New("Permission obj is nil")
+ }
+
+ err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error {
+ query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).Update(dbcoretablenames.TableNamePermissions.ToString())
+ query = dbutils.AddNonNullFieldsToQueryUpdate(query, *paramsUpdate)
+ query = query.Where(squirrel.Eq{"id": paramsUpdate.ID})
+
+ sql, args, err := query.ToSql()
+ if err != nil {
+ return err
+ }
+
+ _, err = tx.Exec(ctx, sql, args...)
+ if err != nil {
+ return err
+ }
+
+ return nil
+ })
+
+ if err != nil {
+ return nil, tx, err
+ }
+
+ returnObjBool := false
+ if len(returnObj) > 0 {
+ returnObjBool = returnObj[0]
+ }
+
+ if returnObjBool {
+ options := typescore.ListDbOptions{Filtering: &typescore.Permission{ID: paramsUpdate.ID}}
+ getInfoUp, _, err := u.GetPermissionsListDB(ctx, options)
+ if err != nil {
+ return nil, nil, err
+ }
+ if len(getInfoUp) > 0 {
+ return getInfoUp[0], tx, nil
+ }
+ }
+
+ return nil, tx, nil
+}
+
+func (u *PermissionDB) DeletePermissionDB(ctx context.Context, params *typescore.Permission) error {
+ if params != nil && params.ID != nil {
+ query, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
+ Delete(dbcoretablenames.TableNamePermissions.ToString()).
+ Where(squirrel.Eq{"id": *params.ID}).
+ ToSql()
+
+ if err != nil {
+ return err
+ }
+
+ rows, err := u.pool.Query(ctx, query, args...)
+ if err != nil {
+ return err
+ }
+ defer rows.Close()
+
+ return nil
+ } else {
+ return errors.New("permission obj is nil")
+ }
+}
+
+// GetUserPermissionsDB возвращает все permissions для пользователя через его роли.
+// action — фильтр: create | approve | revoke | "" (все)
+func (u *PermissionDB) GetUserPermissionsDB(ctx context.Context, userID uint64, action string) ([]*typescore.Permission, error) {
+ // Используем алиас "p" и в GetStructFieldsDB тоже
+ fields := dbutils.GetStructFieldsDB(&typescore.Permission{}, "p")
+
+ q := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
+ Select(fields...).
+ From(dbcoretablenames.TableNamePermissions.ToString() + " p").
+ Join(dbcoretablenames.TableNameUserRoles.ToString() + " ur ON ur.role_id = p.role_id").
+ Where(squirrel.Eq{"ur.user_id": userID})
+
+ if action != "" {
+ q = q.Where(squirrel.Eq{"p.action": action})
+ }
+
+ sql, args, err := q.ToSql()
+ if err != nil {
+ return nil, err
+ }
+
+ rows, err := u.pool.Query(ctx, sql, args...)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+
+ var perms []*typescore.Permission
+ for rows.Next() {
+ p := &typescore.Permission{}
+ if err := dbutils.ScanRowsToStructRows(rows, p, nil); err != nil {
+ logrus.Warn("GetUserPermissionsDB:ScanRowsToStruct", err)
+ continue
+ }
+ perms = append(perms, p)
+ }
+ return perms, nil
+}
diff --git a/core/db/methods/role.go b/core/db/methods/role.go
new file mode 100644
index 0000000..2c29360
--- /dev/null
+++ b/core/db/methods/role.go
@@ -0,0 +1,181 @@
+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/sirupsen/logrus"
+
+ "github.com/Masterminds/squirrel"
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgxpool"
+)
+
+type RoleDB struct {
+ pool *pgxpool.Pool
+}
+
+func NewRoleDB(pool *pgxpool.Pool) *RoleDB {
+ return &RoleDB{
+ pool: pool,
+ }
+}
+
+type RoleDBI interface {
+ GetRolesListDB(ctx context.Context, options ...typescore.ListDbOptions) ([]*typescore.Role, uint64, error)
+ CreateRoleDB(ctx context.Context, tx pgx.Tx, RoleObj *typescore.Role, returnObj ...bool) (*typescore.Role, pgx.Tx, error)
+ UpdateRoleDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.Role, returnObj ...bool) (*typescore.Role, pgx.Tx, error)
+ DeleteRoleDB(ctx context.Context, params *typescore.Role) error
+}
+
+func (u *RoleDB) GetRolesListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.Role, uint64, error) {
+ fields := dbutils.GetStructFieldsDB(&typescore.Role{}, dbcoretablenames.TableNameRoles.ToString())
+ selectFields := append(fields, "COUNT(*) OVER() AS total_count")
+
+ options, filter, err := dbutils.GetOptionsDB[typescore.Role](opts...)
+ if err != nil {
+ return nil, 0, err
+ }
+
+ query := dbutils.BuildSelectQuery(dbcoretablenames.TableNameRoles.ToString(), selectFields)
+ query = dbutils.SetterLimitAndOffsetQuery(query, options.Offset, options.Limit)
+ query = dbutils.ApplyFilters(query, filter, options.LikeFields, dbcoretablenames.TableNameRoles.ToString())
+ query = query.OrderBy("created_at DESC")
+
+ 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 Roles []*typescore.Role
+ var totalCount uint64
+ for rows.Next() {
+ Role := &typescore.Role{}
+ if err := dbutils.ScanRowsToStructRows(rows, Role, &totalCount); err != nil {
+ logrus.Warn("GetRolesListDB:ScanRowsToStructRows", err)
+ continue
+ }
+ Roles = append(Roles, Role)
+ }
+
+ return Roles, totalCount, nil
+}
+
+func (u *RoleDB) CreateRoleDB(ctx context.Context, tx pgx.Tx, RoleObj *typescore.Role, returnObj ...bool) (*typescore.Role, pgx.Tx, error) {
+ if RoleObj == nil {
+ return nil, nil, errors.New("Role obj is nil")
+ }
+
+ err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error {
+ query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).Insert(dbcoretablenames.TableNameRoles.ToString())
+
+ sqlV, args, err := dbutils.GenerateInsertRequest(query, RoleObj)
+ if err != nil {
+ return err
+ }
+
+ _, err = tx.Exec(ctx, *sqlV, args...)
+ if err != nil {
+ return err
+ }
+
+ return nil
+ })
+
+ if err != nil {
+ return nil, tx, err
+ }
+
+ returnObjBool := false
+ if len(returnObj) > 0 {
+ returnObjBool = returnObj[0]
+ }
+ if returnObjBool {
+ Role, _, err := u.GetRolesListDB(ctx, typescore.ListDbOptions{Filtering: RoleObj})
+ if err != nil {
+ return nil, tx, err
+ }
+ if len(Role) > 0 {
+ return Role[0], tx, nil
+ }
+ }
+
+ return nil, tx, nil
+}
+
+func (u *RoleDB) UpdateRoleDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.Role, returnObj ...bool) (*typescore.Role, pgx.Tx, error) {
+ if paramsUpdate.ID == nil {
+ return nil, nil, errors.New("Role obj is nil")
+ }
+
+ err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error {
+ query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).Update(dbcoretablenames.TableNameRoles.ToString())
+ query = dbutils.AddNonNullFieldsToQueryUpdate(query, *paramsUpdate)
+ query = query.Where(squirrel.Eq{"id": paramsUpdate.ID})
+
+ sql, args, err := query.ToSql()
+ if err != nil {
+ return err
+ }
+
+ _, err = tx.Exec(ctx, sql, args...)
+ if err != nil {
+ return err
+ }
+
+ return nil
+ })
+
+ if err != nil {
+ return nil, tx, err
+ }
+
+ returnObjBool := false
+ if len(returnObj) > 0 {
+ returnObjBool = returnObj[0]
+ }
+
+ if returnObjBool {
+ options := typescore.ListDbOptions{Filtering: &typescore.Role{ID: paramsUpdate.ID}}
+ getInfoUp, _, err := u.GetRolesListDB(ctx, options)
+ if err != nil {
+ return nil, nil, err
+ }
+ if len(getInfoUp) > 0 {
+ return getInfoUp[0], tx, nil
+ }
+ }
+
+ return nil, tx, nil
+}
+
+func (u *RoleDB) DeleteRoleDB(ctx context.Context, params *typescore.Role) error {
+ if params != nil && params.ID != nil {
+ query, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
+ Delete(dbcoretablenames.TableNameRoles.ToString()).
+ Where(squirrel.Eq{"id": *params.ID}).
+ ToSql()
+
+ if err != nil {
+ return err
+ }
+
+ rows, err := u.pool.Query(ctx, query, args...)
+ if err != nil {
+ return err
+ }
+ defer rows.Close()
+
+ return nil
+ } else {
+ return errors.New("role obj is nil")
+ }
+}
diff --git a/core/db/methods/user.go b/core/db/methods/user.go
new file mode 100644
index 0000000..1d849da
--- /dev/null
+++ b/core/db/methods/user.go
@@ -0,0 +1,359 @@
+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/sirupsen/logrus"
+
+ "github.com/Masterminds/squirrel"
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgxpool"
+)
+
+type UserDB struct {
+ pool *pgxpool.Pool
+}
+
+func NewUserDB(pool *pgxpool.Pool) *UserDB {
+ return &UserDB{
+ pool: pool,
+ }
+}
+
+type UserDBI interface {
+ GetUsersListDB(ctx context.Context, options ...typescore.ListDbOptions) ([]*typescore.User, uint64, error)
+ CreateUserDB(ctx context.Context, tx pgx.Tx, UserObj *typescore.User, returnObj ...bool) (*typescore.User, pgx.Tx, error)
+ UpdateUserDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.User, returnObj ...bool) (*typescore.User, pgx.Tx, error)
+ DeleteUserDB(ctx context.Context, params *typescore.User) error
+
+ GetUserByTelegramIDDB(ctx context.Context, telegramID int64) (*typescore.User, error)
+ GetUserByIDDB(ctx context.Context, id uint64) (*typescore.User, error)
+ GetDirectorsDB(ctx context.Context) ([]*typescore.User, error)
+ IsDirectorDB(ctx context.Context, userID uint64) (bool, error)
+ IsApproverDB(ctx context.Context, userID uint64) (bool, error)
+ IsExecutorDB(ctx context.Context, userID uint64) (bool, error)
+ GetObserversForCategoryDB(ctx context.Context, categoryCode string) ([]*typescore.User, error)
+}
+
+func (u *UserDB) GetUsersListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.User, uint64, error) {
+ fields := dbutils.GetStructFieldsDB(&typescore.User{}, dbcoretablenames.TableNameUsers.ToString())
+ selectFields := append(fields, "COUNT(*) OVER() AS total_count")
+
+ options, filter, err := dbutils.GetOptionsDB[typescore.User](opts...)
+ if err != nil {
+ return nil, 0, err
+ }
+
+ query := dbutils.BuildSelectQuery(dbcoretablenames.TableNameUsers.ToString(), selectFields)
+ query = dbutils.SetterLimitAndOffsetQuery(query, options.Offset, options.Limit)
+ query = dbutils.ApplyFilters(query, filter, options.LikeFields, dbcoretablenames.TableNameUsers.ToString())
+ query = query.OrderBy("created_at DESC")
+
+ 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 Users []*typescore.User
+ var totalCount uint64
+ for rows.Next() {
+ User := &typescore.User{}
+ if err := dbutils.ScanRowsToStructRows(rows, User, &totalCount); err != nil {
+ logrus.Warn("GetUsersListDB:ScanRowsToStructRows", err)
+ continue
+ }
+ Users = append(Users, User)
+ }
+
+ return Users, totalCount, nil
+}
+
+func (u *UserDB) CreateUserDB(ctx context.Context, tx pgx.Tx, UserObj *typescore.User, returnObj ...bool) (*typescore.User, pgx.Tx, error) {
+ if UserObj == nil {
+ return nil, nil, errors.New("user obj is nil")
+ }
+
+ err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error {
+ query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).Insert(dbcoretablenames.TableNameUsers.ToString())
+
+ sqlV, args, err := dbutils.GenerateInsertRequest(query, UserObj)
+ if err != nil {
+ return err
+ }
+
+ _, err = tx.Exec(ctx, *sqlV, args...)
+ if err != nil {
+ return err
+ }
+
+ return nil
+ })
+
+ if err != nil {
+ return nil, tx, err
+ }
+
+ returnObjBool := false
+ if len(returnObj) > 0 {
+ returnObjBool = returnObj[0]
+ }
+ if returnObjBool {
+ User, _, err := u.GetUsersListDB(ctx, typescore.ListDbOptions{Filtering: UserObj})
+ if err != nil {
+ return nil, tx, err
+ }
+ if len(User) > 0 {
+ return User[0], tx, nil
+ }
+ }
+
+ return nil, tx, nil
+}
+
+func (u *UserDB) UpdateUserDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.User, returnObj ...bool) (*typescore.User, pgx.Tx, error) {
+ if paramsUpdate.ID == nil {
+ return nil, nil, errors.New("user obj is nil")
+ }
+
+ err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error {
+ query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).Update(dbcoretablenames.TableNameUsers.ToString())
+ query = dbutils.AddNonNullFieldsToQueryUpdate(query, *paramsUpdate)
+ query = query.Where(squirrel.Eq{"id": paramsUpdate.ID})
+
+ sql, args, err := query.ToSql()
+ if err != nil {
+ return err
+ }
+
+ _, err = tx.Exec(ctx, sql, args...)
+ if err != nil {
+ return err
+ }
+
+ return nil
+ })
+
+ if err != nil {
+ return nil, tx, err
+ }
+
+ returnObjBool := false
+ if len(returnObj) > 0 {
+ returnObjBool = returnObj[0]
+ }
+
+ if returnObjBool {
+ options := typescore.ListDbOptions{Filtering: &typescore.User{ID: paramsUpdate.ID}}
+ getInfoUp, _, err := u.GetUsersListDB(ctx, options)
+ if err != nil {
+ return nil, nil, err
+ }
+ if len(getInfoUp) > 0 {
+ return getInfoUp[0], tx, nil
+ }
+ }
+
+ return nil, tx, nil
+}
+
+func (u *UserDB) DeleteUserDB(ctx context.Context, params *typescore.User) error {
+ if params != nil && params.ID != nil {
+ query, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
+ Delete(dbcoretablenames.TableNameUsers.ToString()).
+ Where(squirrel.Eq{"id": *params.ID}).
+ ToSql()
+
+ if err != nil {
+ return err
+ }
+
+ rows, err := u.pool.Query(ctx, query, args...)
+ if err != nil {
+ return err
+ }
+ defer rows.Close()
+
+ return nil
+ } else {
+ return errors.New("user obj is nil")
+ }
+}
+
+func (u *UserDB) GetUserByTelegramIDDB(ctx context.Context, telegramID int64) (*typescore.User, error) {
+ users, _, err := u.GetUsersListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.User{TelegramID: &telegramID},
+ })
+ if err != nil {
+ return nil, err
+ }
+ if len(users) == 0 {
+ return nil, nil
+ }
+ return users[0], nil
+}
+
+func (u *UserDB) GetUserByIDDB(ctx context.Context, id uint64) (*typescore.User, error) {
+ users, _, err := u.GetUsersListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.User{ID: &id},
+ })
+ if err != nil {
+ return nil, err
+ }
+ if len(users) == 0 {
+ return nil, nil
+ }
+ return users[0], nil
+}
+
+// GetDirectorsDB возвращает всех пользователей у которых есть роль с is_director = true.
+func (u *UserDB) GetDirectorsDB(ctx context.Context) ([]*typescore.User, error) {
+ sql, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
+ Select("DISTINCT u.*").
+ From(dbcoretablenames.TableNameUsers.ToString() + " u").
+ Join(dbcoretablenames.TableNameUserRoles.ToString() + " ur ON ur.user_id = u.id").
+ Join(dbcoretablenames.TableNameRoles.ToString() + " r ON r.id = ur.role_id").
+ Where(squirrel.Eq{"r.is_director": true}).
+ Where(squirrel.Eq{"u.is_blocked": false}).
+ ToSql()
+ if err != nil {
+ return nil, err
+ }
+
+ rows, err := u.pool.Query(ctx, sql, args...)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+
+ var users []*typescore.User
+ for rows.Next() {
+ user := &typescore.User{}
+ if err := dbutils.ScanRowsToStructRows(rows, user, nil, nil); err != nil {
+ logrus.Warn("GetDirectorsDB:ScanRowsToStruct", err)
+ continue
+ }
+ users = append(users, user)
+ }
+ return users, nil
+}
+
+// IsDirectorDB проверяет наличие директорской роли у конкретного пользователя.
+func (u *UserDB) IsDirectorDB(ctx context.Context, userID uint64) (bool, error) {
+ sql, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
+ Select("COUNT(*)").
+ From(dbcoretablenames.TableNameUserRoles.ToString() + " ur").
+ Join(dbcoretablenames.TableNameRoles.ToString() + " r ON r.id = ur.role_id").
+ Where(squirrel.Eq{"ur.user_id": userID}).
+ Where(squirrel.Eq{"r.is_director": true}).
+ ToSql()
+ if err != nil {
+ return false, err
+ }
+
+ var count int
+ if err := u.pool.QueryRow(ctx, sql, args...).Scan(&count); err != nil {
+ return false, err
+ }
+ return count > 0, nil
+}
+
+// IsApproverDB проверяет есть ли у пользователя роль с is_approver = true
+func (u *UserDB) IsApproverDB(ctx context.Context, userID uint64) (bool, error) {
+ sql, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
+ Select("COUNT(*)").
+ From(dbcoretablenames.TableNameUserRoles.ToString() + " ur").
+ Join(dbcoretablenames.TableNameRoles.ToString() + " r ON r.id = ur.role_id").
+ Where(squirrel.Eq{"ur.user_id": userID}).
+ Where(squirrel.Eq{"r.is_approver": true}).
+ ToSql()
+ if err != nil {
+ return false, err
+ }
+
+ var count int
+ if err := u.pool.QueryRow(ctx, sql, args...).Scan(&count); err != nil {
+ return false, err
+ }
+ return count > 0, nil
+}
+
+func (u *UserDB) IsObserverDB(ctx context.Context, userID uint64) (bool, error) {
+ sql, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
+ Select("COUNT(*)").
+ From(dbcoretablenames.TableNameUserRoles.ToString() + " ur").
+ Join(dbcoretablenames.TableNameRoles.ToString() + " r ON r.id = ur.role_id").
+ Where(squirrel.Eq{"ur.user_id": userID}).
+ Where(squirrel.Eq{"r.is_observer": true}).
+ ToSql()
+ if err != nil {
+ return false, err
+ }
+ var count int
+ if err := u.pool.QueryRow(ctx, sql, args...).Scan(&count); err != nil {
+ return false, err
+ }
+ return count > 0, nil
+}
+
+func (u *UserDB) IsExecutorDB(ctx context.Context, userID uint64) (bool, error) {
+ sql, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
+ Select("COUNT(*)").
+ From(dbcoretablenames.TableNameUserRoles.ToString() + " ur").
+ Join(dbcoretablenames.TableNameRoles.ToString() + " r ON r.id = ur.role_id").
+ Where(squirrel.Eq{"ur.user_id": userID}).
+ Where(squirrel.Eq{"r.is_executor": true}).
+ ToSql()
+ if err != nil {
+ return false, err
+ }
+
+ var count int
+ if err := u.pool.QueryRow(ctx, sql, args...).Scan(&count); err != nil {
+ return false, err
+ }
+ return count > 0, nil
+}
+
+// GetObserversForCategoryDB — пользователи с ролью наблюдателя и правом observe на категорию.
+func (u *UserDB) GetObserversForCategoryDB(ctx context.Context, categoryCode string) ([]*typescore.User, error) {
+ sql, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
+ Select("DISTINCT u.*").
+ From(dbcoretablenames.TableNameUsers.ToString() + " u").
+ Join(dbcoretablenames.TableNameUserRoles.ToString() + " ur ON ur.user_id = u.id").
+ Join(dbcoretablenames.TableNameRoles.ToString() + " r ON r.id = ur.role_id").
+ Join(dbcoretablenames.TableNamePermissions.ToString() + " p ON p.role_id = r.id").
+ Join(dbcoretablenames.TableNameApprovalTopicCategories.ToString() + " c ON c.id = p.topic_category_id").
+ Where(squirrel.Eq{"r.is_observer": true}).
+ Where(squirrel.Eq{"p.action": "observe"}).
+ Where(squirrel.Eq{"c.code": categoryCode}).
+ ToSql()
+ if err != nil {
+ return nil, err
+ }
+
+ rows, err := u.pool.Query(ctx, sql, args...)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+
+ var result []*typescore.User
+ for rows.Next() {
+ usr := &typescore.User{}
+ if err := dbutils.ScanRowsToStructRows(rows, usr, nil); err != nil {
+ logrus.Warn("GetObserversForCategoryDB:ScanRowsToStruct", err)
+ continue
+ }
+ result = append(result, usr)
+ }
+ return result, nil
+}
diff --git a/core/db/methods/user_hierarchy.go b/core/db/methods/user_hierarchy.go
new file mode 100644
index 0000000..324ddc4
--- /dev/null
+++ b/core/db/methods/user_hierarchy.go
@@ -0,0 +1,302 @@
+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/sirupsen/logrus"
+
+ "github.com/Masterminds/squirrel"
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgxpool"
+)
+
+type UserHierarchyDB struct {
+ pool *pgxpool.Pool
+}
+
+func NewUserHierarchyDB(pool *pgxpool.Pool) *UserHierarchyDB {
+ return &UserHierarchyDB{
+ pool: pool,
+ }
+}
+
+type UserHierarchyDBI interface {
+ GetUserHierarchyListDB(ctx context.Context, options ...typescore.ListDbOptions) ([]*typescore.UserHierarchy, uint64, error)
+ CreateUserHierarchyDB(ctx context.Context, tx pgx.Tx, UserHierarchyObj *typescore.UserHierarchy, returnObj ...bool) (*typescore.UserHierarchy, pgx.Tx, error)
+ UpdateUserHierarchyDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.UserHierarchy, returnObj ...bool) (*typescore.UserHierarchy, pgx.Tx, error)
+ DeleteUserHierarchyDB(ctx context.Context, params *typescore.UserHierarchy) error
+
+ GetApproversDB(ctx context.Context, subordinateID uint64, departmentID uint64) ([]*typescore.User, error)
+ GetExecutorDB(ctx context.Context, subordinateID, departmentID, topicID, categoryID uint64) (*typescore.User, error)
+}
+
+func (u *UserHierarchyDB) GetUserHierarchyListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.UserHierarchy, uint64, error) {
+ fields := dbutils.GetStructFieldsDB(&typescore.UserHierarchy{}, dbcoretablenames.TableNameUserHierarchy.ToString())
+ selectFields := append(fields, "COUNT(*) OVER() AS total_count")
+
+ options, filter, err := dbutils.GetOptionsDB[typescore.UserHierarchy](opts...)
+ if err != nil {
+ return nil, 0, err
+ }
+
+ query := dbutils.BuildSelectQuery(dbcoretablenames.TableNameUserHierarchy.ToString(), selectFields)
+ query = dbutils.SetterLimitAndOffsetQuery(query, options.Offset, options.Limit)
+ query = dbutils.ApplyFilters(query, filter, options.LikeFields, dbcoretablenames.TableNameUserHierarchy.ToString())
+ query = query.OrderBy("created_at DESC")
+
+ 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 UserHierarchys []*typescore.UserHierarchy
+ var totalCount uint64
+ for rows.Next() {
+ UserHierarchy := &typescore.UserHierarchy{}
+ if err := dbutils.ScanRowsToStructRows(rows, UserHierarchy, &totalCount); err != nil {
+ logrus.Warn("GetUserHierarchysListDB:ScanRowsToStructRows", err)
+ continue
+ }
+ UserHierarchys = append(UserHierarchys, UserHierarchy)
+ }
+
+ return UserHierarchys, totalCount, nil
+}
+
+func (u *UserHierarchyDB) CreateUserHierarchyDB(ctx context.Context, tx pgx.Tx, UserHierarchyObj *typescore.UserHierarchy, returnObj ...bool) (*typescore.UserHierarchy, pgx.Tx, error) {
+ if UserHierarchyObj == nil {
+ return nil, nil, errors.New("UserHierarchy obj is nil")
+ }
+
+ err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error {
+ query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).Insert(dbcoretablenames.TableNameUserHierarchy.ToString())
+
+ sqlV, args, err := dbutils.GenerateInsertRequest(query, UserHierarchyObj)
+ if err != nil {
+ return err
+ }
+
+ _, err = tx.Exec(ctx, *sqlV, args...)
+ if err != nil {
+ return err
+ }
+
+ return nil
+ })
+
+ if err != nil {
+ return nil, tx, err
+ }
+
+ returnObjBool := false
+ if len(returnObj) > 0 {
+ returnObjBool = returnObj[0]
+ }
+ if returnObjBool {
+ UserHierarchy, _, err := u.GetUserHierarchyListDB(ctx, typescore.ListDbOptions{Filtering: UserHierarchyObj})
+ if err != nil {
+ return nil, tx, err
+ }
+ if len(UserHierarchy) > 0 {
+ return UserHierarchy[0], tx, nil
+ }
+ }
+
+ return nil, tx, nil
+}
+
+func (u *UserHierarchyDB) UpdateUserHierarchyDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.UserHierarchy, returnObj ...bool) (*typescore.UserHierarchy, pgx.Tx, error) {
+ if paramsUpdate.ID == nil {
+ return nil, nil, errors.New("UserHierarchy obj is nil")
+ }
+
+ err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error {
+ query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).Update(dbcoretablenames.TableNameUserHierarchy.ToString())
+ query = dbutils.AddNonNullFieldsToQueryUpdate(query, *paramsUpdate)
+ query = query.Where(squirrel.Eq{"id": paramsUpdate.ID})
+
+ sql, args, err := query.ToSql()
+ if err != nil {
+ return err
+ }
+
+ _, err = tx.Exec(ctx, sql, args...)
+ if err != nil {
+ return err
+ }
+
+ return nil
+ })
+
+ if err != nil {
+ return nil, tx, err
+ }
+
+ returnObjBool := false
+ if len(returnObj) > 0 {
+ returnObjBool = returnObj[0]
+ }
+
+ if returnObjBool {
+ options := typescore.ListDbOptions{Filtering: &typescore.UserHierarchy{ID: paramsUpdate.ID}}
+ getInfoUp, _, err := u.GetUserHierarchyListDB(ctx, options)
+ if err != nil {
+ return nil, nil, err
+ }
+ if len(getInfoUp) > 0 {
+ return getInfoUp[0], tx, nil
+ }
+ }
+
+ return nil, tx, nil
+}
+
+func (u *UserHierarchyDB) DeleteUserHierarchyDB(ctx context.Context, params *typescore.UserHierarchy) error {
+ if params != nil && params.ID != nil {
+ query, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
+ Delete(dbcoretablenames.TableNameUserHierarchy.ToString()).
+ Where(squirrel.Eq{"id": *params.ID}).
+ ToSql()
+
+ if err != nil {
+ return err
+ }
+
+ rows, err := u.pool.Query(ctx, query, args...)
+ if err != nil {
+ return err
+ }
+ defer rows.Close()
+
+ return nil
+ } else {
+ return errors.New("userHierarchy obj is nil")
+ }
+}
+
+func (u *UserHierarchyDB) GetApproversDB(
+ ctx context.Context,
+ subordinateID uint64,
+ departmentID uint64,
+ topicID uint64,
+ topicCategoryID uint64,
+) ([]*typescore.User, error) {
+
+ // Ищем наиболее специфичное правило для этой тройки (subordinate, dept, тема).
+ // Приоритет: topic_id > topic_category_id > общее правило (оба NULL).
+ // Берём только правила одного уровня специфичности — наиболее точного.
+ rawSQL := `
+ WITH ranked AS (
+ SELECT
+ uh.approver_id,
+ uh.priority,
+ CASE
+ WHEN uh.topic_id = $3 THEN 1
+ WHEN uh.topic_category_id = $4 THEN 2
+ WHEN uh.topic_id IS NULL
+ AND uh.topic_category_id IS NULL THEN 3
+ END AS specificity
+ FROM user_hierarchy uh
+ WHERE uh.subordinate_id = $1
+ AND uh.department_id = $2
+ AND (
+ uh.topic_id = $3
+ OR uh.topic_category_id = $4
+ OR (uh.topic_id IS NULL AND uh.topic_category_id IS NULL)
+ )
+ ),
+ best AS (
+ -- берём только уровень с наивысшей специфичностью
+ SELECT MIN(specificity) AS min_spec FROM ranked
+ )
+ SELECT u.*
+ FROM ranked r
+ JOIN best b ON r.specificity = b.min_spec
+ JOIN users u ON u.id = r.approver_id
+ ORDER BY r.priority ASC
+ `
+
+ rows, err := u.pool.Query(ctx, rawSQL,
+ subordinateID,
+ departmentID,
+ topicID,
+ topicCategoryID,
+ )
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+
+ var result []*typescore.User
+ for rows.Next() {
+ usr := &typescore.User{}
+ if err := dbutils.ScanRowsToStructRows(rows, usr, nil); err != nil {
+ logrus.Warn("GetApproversDB:ScanRowsToStructRows", err)
+ continue
+ }
+ result = append(result, usr)
+ }
+ return result, nil
+}
+
+func (u *UserHierarchyDB) GetExecutorDB(ctx context.Context, subordinateID, departmentID, topicID, categoryID uint64) (*typescore.User, error) {
+ fields := dbutils.GetStructFieldsDB(&typescore.User{}, "u")
+
+ queryUser := func(where squirrel.Sqlizer) (*typescore.User, error) {
+ baseQuery := squirrel.Select(fields...).
+ From(dbcoretablenames.TableNameUserHierarchy.ToString() + " uh").
+ Join(dbcoretablenames.TableNameUsers.ToString() + " u ON u.id = uh.executor_id").
+ Where(squirrel.Eq{"uh.subordinate_id": subordinateID}).
+ Where(squirrel.Eq{"uh.department_id": departmentID}).
+ Where(squirrel.Expr("uh.executor_id IS NOT NULL")).
+ Where(where).
+ Limit(1)
+
+ sql, args, err := baseQuery.PlaceholderFormat(squirrel.Dollar).ToSql()
+ if err != nil {
+ return nil, err
+ }
+ logrus.Debugf("Generated SQL: %s, Args: %v", sql, args) // <-- добавь это
+
+ rows, err := u.pool.Query(ctx, sql, args...)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+
+ if !rows.Next() {
+ return nil, rows.Err()
+ }
+
+ user := &typescore.User{}
+ var totalCount uint64
+ if err := dbutils.ScanRowsToStructRows(rows, user, &totalCount); err != nil {
+ return nil, err
+ }
+
+ return user, nil
+ }
+
+ if topicID > 0 {
+ user, err := queryUser(squirrel.Eq{"uh.topic_id": topicID})
+ if err == nil && user != nil {
+ return user, nil
+ }
+ }
+
+ user, err := queryUser(squirrel.Eq{"uh.topic_category_id": categoryID})
+ if err != nil {
+ return nil, err
+ }
+
+ return user, nil
+}
diff --git a/core/db/methods/user_role.go b/core/db/methods/user_role.go
new file mode 100644
index 0000000..6266924
--- /dev/null
+++ b/core/db/methods/user_role.go
@@ -0,0 +1,181 @@
+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/sirupsen/logrus"
+
+ "github.com/Masterminds/squirrel"
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgxpool"
+)
+
+type UserRoleDB struct {
+ pool *pgxpool.Pool
+}
+
+func NewUserRoleDB(pool *pgxpool.Pool) *UserRoleDB {
+ return &UserRoleDB{
+ pool: pool,
+ }
+}
+
+type UserRoleDBI interface {
+ GetUserRolesListDB(ctx context.Context, options ...typescore.ListDbOptions) ([]*typescore.UserRole, uint64, error)
+ CreateUserRoleDB(ctx context.Context, tx pgx.Tx, UserRoleObj *typescore.UserRole, returnObj ...bool) (*typescore.UserRole, pgx.Tx, error)
+ UpdateUserRoleDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.UserRole, returnObj ...bool) (*typescore.UserRole, pgx.Tx, error)
+ DeleteUserRoleDB(ctx context.Context, params *typescore.UserRole) error
+}
+
+func (u *UserRoleDB) GetUserRolesListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.UserRole, uint64, error) {
+ fields := dbutils.GetStructFieldsDB(&typescore.UserRole{}, dbcoretablenames.TableNameUserRoles.ToString())
+ selectFields := append(fields, "COUNT(*) OVER() AS total_count")
+
+ options, filter, err := dbutils.GetOptionsDB[typescore.UserRole](opts...)
+ if err != nil {
+ return nil, 0, err
+ }
+
+ query := dbutils.BuildSelectQuery(dbcoretablenames.TableNameUserRoles.ToString(), selectFields)
+ query = dbutils.SetterLimitAndOffsetQuery(query, options.Offset, options.Limit)
+ query = dbutils.ApplyFilters(query, filter, options.LikeFields, dbcoretablenames.TableNameUserRoles.ToString())
+ query = query.OrderBy("created_at DESC")
+
+ 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 UserRoles []*typescore.UserRole
+ var totalCount uint64
+ for rows.Next() {
+ UserRole := &typescore.UserRole{}
+ if err := dbutils.ScanRowsToStructRows(rows, UserRole, &totalCount); err != nil {
+ logrus.Warn("GetUserRolesListDB:ScanRowsToStructRows", err)
+ continue
+ }
+ UserRoles = append(UserRoles, UserRole)
+ }
+
+ return UserRoles, totalCount, nil
+}
+
+func (u *UserRoleDB) CreateUserRoleDB(ctx context.Context, tx pgx.Tx, UserRoleObj *typescore.UserRole, returnObj ...bool) (*typescore.UserRole, pgx.Tx, error) {
+ if UserRoleObj == nil {
+ return nil, nil, errors.New("UserRole obj is nil")
+ }
+
+ err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error {
+ query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).Insert(dbcoretablenames.TableNameUserRoles.ToString())
+
+ sqlV, args, err := dbutils.GenerateInsertRequest(query, UserRoleObj)
+ if err != nil {
+ return err
+ }
+
+ _, err = tx.Exec(ctx, *sqlV, args...)
+ if err != nil {
+ return err
+ }
+
+ return nil
+ })
+
+ if err != nil {
+ return nil, tx, err
+ }
+
+ returnObjBool := false
+ if len(returnObj) > 0 {
+ returnObjBool = returnObj[0]
+ }
+ if returnObjBool {
+ UserRole, _, err := u.GetUserRolesListDB(ctx, typescore.ListDbOptions{Filtering: UserRoleObj})
+ if err != nil {
+ return nil, tx, err
+ }
+ if len(UserRole) > 0 {
+ return UserRole[0], tx, nil
+ }
+ }
+
+ return nil, tx, nil
+}
+
+func (u *UserRoleDB) UpdateUserRoleDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.UserRole, returnObj ...bool) (*typescore.UserRole, pgx.Tx, error) {
+ if paramsUpdate.ID == nil {
+ return nil, nil, errors.New("UserRole obj is nil")
+ }
+
+ err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error {
+ query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).Update(dbcoretablenames.TableNameUserRoles.ToString())
+ query = dbutils.AddNonNullFieldsToQueryUpdate(query, *paramsUpdate)
+ query = query.Where(squirrel.Eq{"id": paramsUpdate.ID})
+
+ sql, args, err := query.ToSql()
+ if err != nil {
+ return err
+ }
+
+ _, err = tx.Exec(ctx, sql, args...)
+ if err != nil {
+ return err
+ }
+
+ return nil
+ })
+
+ if err != nil {
+ return nil, tx, err
+ }
+
+ returnObjBool := false
+ if len(returnObj) > 0 {
+ returnObjBool = returnObj[0]
+ }
+
+ if returnObjBool {
+ options := typescore.ListDbOptions{Filtering: &typescore.UserRole{ID: paramsUpdate.ID}}
+ getInfoUp, _, err := u.GetUserRolesListDB(ctx, options)
+ if err != nil {
+ return nil, nil, err
+ }
+ if len(getInfoUp) > 0 {
+ return getInfoUp[0], tx, nil
+ }
+ }
+
+ return nil, tx, nil
+}
+
+func (u *UserRoleDB) DeleteUserRoleDB(ctx context.Context, params *typescore.UserRole) error {
+ if params != nil && params.ID != nil {
+ query, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
+ Delete(dbcoretablenames.TableNameUserRoles.ToString()).
+ Where(squirrel.Eq{"id": *params.ID}).
+ ToSql()
+
+ if err != nil {
+ return err
+ }
+
+ rows, err := u.pool.Query(ctx, query, args...)
+ if err != nil {
+ return err
+ }
+ defer rows.Close()
+
+ return nil
+ } else {
+ return errors.New("userRole obj is nil")
+ }
+}
diff --git a/core/db/table_names/table_names.go b/core/db/table_names/table_names.go
new file mode 100644
index 0000000..72903b7
--- /dev/null
+++ b/core/db/table_names/table_names.go
@@ -0,0 +1,24 @@
+package dbcoretablenames
+
+type TableName string
+
+const (
+ TableNameApprovals TableName = "approvals"
+ TableNameApprovalSteps TableName = "approval_steps"
+ TableNameApprovalTopics TableName = "approval_topics"
+ TableNameApprovalTopicCategories TableName = "approval_topic_categories"
+ TableNameDepartments TableName = "departments"
+ TableNamePermissions TableName = "permissions"
+ TableNameRoles TableName = "roles"
+ TableNameUsers TableName = "users"
+ TableNameUserHierarchy TableName = "user_hierarchy"
+ TableNameUserRoles TableName = "user_roles"
+ TableNameApprovalFiles TableName = "approval_files"
+ TableNameApprovalDelegations TableName = "approval_delegations"
+ TableNameApprovalAdditionalApprovers TableName = "approval_additional_approvers"
+ TableNameApprovalTasks TableName = "approval_tasks"
+)
+
+func (t TableName) ToString() string {
+ return string(t)
+}
diff --git a/core/go.mod b/core/go.mod
new file mode 100644
index 0000000..baf18d1
--- /dev/null
+++ b/core/go.mod
@@ -0,0 +1,52 @@
+module bitrix_balancer_api/core
+
+go 1.25.6
+
+require (
+ github.com/Masterminds/squirrel v1.5.4
+ github.com/go-telegram-bot-api/telegram-bot-api/v5 v5.5.1
+ github.com/google/uuid v1.6.0
+ github.com/hashicorp/vault/api v1.22.0
+ github.com/jackc/pgx/v5 v5.8.0
+ github.com/mitchellh/mapstructure v1.5.0
+ github.com/redis/go-redis/v9 v9.18.0
+ github.com/shopspring/decimal v1.4.0
+ github.com/sirupsen/logrus v1.9.4
+ gopkg.in/yaml.v3 v3.0.1
+ gorm.io/driver/postgres v1.6.0
+ gorm.io/gorm v1.31.1
+)
+
+require (
+ github.com/cenkalti/backoff/v4 v4.3.0 // indirect
+ github.com/cespare/xxhash/v2 v2.3.0 // indirect
+ github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
+ github.com/go-jose/go-jose/v4 v4.1.1 // indirect
+ github.com/hashicorp/errwrap v1.1.0 // indirect
+ github.com/hashicorp/go-cleanhttp v0.5.2 // indirect
+ github.com/hashicorp/go-multierror v1.1.1 // indirect
+ github.com/hashicorp/go-retryablehttp v0.7.8 // indirect
+ github.com/hashicorp/go-rootcerts v1.0.2 // indirect
+ github.com/hashicorp/go-secure-stdlib/parseutil v0.2.0 // indirect
+ github.com/hashicorp/go-secure-stdlib/strutil v0.1.2 // indirect
+ github.com/hashicorp/go-sockaddr v1.0.7 // indirect
+ github.com/hashicorp/hcl v1.0.1-vault-7 // indirect
+ github.com/jackc/pgpassfile v1.0.0 // indirect
+ github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
+ github.com/jackc/puddle/v2 v2.2.2 // indirect
+ github.com/jinzhu/inflection v1.0.0 // indirect
+ github.com/jinzhu/now v1.1.5 // indirect
+ github.com/kr/text v0.2.0 // indirect
+ github.com/lann/builder v0.0.0-20180802200727-47ae307949d0 // indirect
+ github.com/lann/ps v0.0.0-20150810152359-62de8c46ede0 // indirect
+ github.com/mitchellh/go-homedir v1.1.0 // indirect
+ github.com/rogpeppe/go-internal v1.14.1 // indirect
+ github.com/ryanuber/go-glob v1.0.0 // indirect
+ go.uber.org/atomic v1.11.0 // indirect
+ golang.org/x/crypto v0.40.0 // indirect
+ golang.org/x/net v0.42.0 // indirect
+ golang.org/x/sync v0.17.0 // indirect
+ golang.org/x/sys v0.41.0 // indirect
+ golang.org/x/text v0.29.0 // indirect
+ golang.org/x/time v0.12.0 // indirect
+)
diff --git a/core/go.sum b/core/go.sum
new file mode 100644
index 0000000..5de2c04
--- /dev/null
+++ b/core/go.sum
@@ -0,0 +1,123 @@
+github.com/Masterminds/squirrel v1.5.4 h1:uUcX/aBc8O7Fg9kaISIUsHXdKuqehiXAMQTYX8afzqM=
+github.com/Masterminds/squirrel v1.5.4/go.mod h1:NNaOrjSoIDfDA40n7sr2tPNZRfjzjA400rg+riTZj10=
+github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs=
+github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c=
+github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA=
+github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0=
+github.com/cenkalti/backoff/v4 v4.3.0 h1:MyRJ/UdXutAwSAT+s3wNd7MfTIcy71VQueUuFK343L8=
+github.com/cenkalti/backoff/v4 v4.3.0/go.mod h1:Y3VNntkOUPxTVeUxJ/G5vcM//AlwfmyYozVcomhLiZE=
+github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
+github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
+github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
+github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
+github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
+github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
+github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78=
+github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc=
+github.com/fatih/color v1.18.0 h1:S8gINlzdQ840/4pfAwic/ZE0djQEH3wM94VfqLTZcOM=
+github.com/fatih/color v1.18.0/go.mod h1:4FelSpRwEGDpQ12mAdzqdOukCy4u8WUtOY6lkT/6HfU=
+github.com/go-jose/go-jose/v4 v4.1.1 h1:JYhSgy4mXXzAdF3nUx3ygx347LRXJRrpgyU3adRmkAI=
+github.com/go-jose/go-jose/v4 v4.1.1/go.mod h1:BdsZGqgdO3b6tTc6LSE56wcDbMMLuPsw5d4ZD5f94kA=
+github.com/go-telegram-bot-api/telegram-bot-api/v5 v5.5.1 h1:wG8n/XJQ07TmjbITcGiUaOtXxdrINDz1b0J1w0SzqDc=
+github.com/go-telegram-bot-api/telegram-bot-api/v5 v5.5.1/go.mod h1:A2S0CWkNylc2phvKXWBBdD3K0iGnDBGbzRpISP2zBl8=
+github.com/go-test/deep v1.1.1 h1:0r/53hagsehfO4bzD2Pgr/+RgHqhmf+k1Bpse2cTu1U=
+github.com/go-test/deep v1.1.1/go.mod h1:5C2ZWiW0ErCdrYzpqxLbTX7MG14M9iiw8DgHncVwcsE=
+github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
+github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
+github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4=
+github.com/hashicorp/errwrap v1.1.0 h1:OxrOeh75EUXMY8TBjag2fzXGZ40LB6IKw45YeGUDY2I=
+github.com/hashicorp/errwrap v1.1.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4=
+github.com/hashicorp/go-cleanhttp v0.5.2 h1:035FKYIWjmULyFRBKPs8TBQoi0x6d9G4xc9neXJWAZQ=
+github.com/hashicorp/go-cleanhttp v0.5.2/go.mod h1:kO/YDlP8L1346E6Sodw+PrpBSV4/SoxCXGY6BqNFT48=
+github.com/hashicorp/go-hclog v1.6.3 h1:Qr2kF+eVWjTiYmU7Y31tYlP1h0q/X3Nl3tPGdaB11/k=
+github.com/hashicorp/go-hclog v1.6.3/go.mod h1:W4Qnvbt70Wk/zYJryRzDRU/4r0kIg0PVHBcfoyhpF5M=
+github.com/hashicorp/go-multierror v1.1.1 h1:H5DkEtf6CXdFp0N0Em5UCwQpXMWke8IA0+lD48awMYo=
+github.com/hashicorp/go-multierror v1.1.1/go.mod h1:iw975J/qwKPdAO1clOe2L8331t/9/fmwbPZ6JB6eMoM=
+github.com/hashicorp/go-retryablehttp v0.7.8 h1:ylXZWnqa7Lhqpk0L1P1LzDtGcCR0rPVUrx/c8Unxc48=
+github.com/hashicorp/go-retryablehttp v0.7.8/go.mod h1:rjiScheydd+CxvumBsIrFKlx3iS0jrZ7LvzFGFmuKbw=
+github.com/hashicorp/go-rootcerts v1.0.2 h1:jzhAVGtqPKbwpyCPELlgNWhE1znq+qwJtW5Oi2viEzc=
+github.com/hashicorp/go-rootcerts v1.0.2/go.mod h1:pqUvnprVnM5bf7AOirdbb01K4ccR319Vf4pU3K5EGc8=
+github.com/hashicorp/go-secure-stdlib/parseutil v0.2.0 h1:U+kC2dOhMFQctRfhK0gRctKAPTloZdMU5ZJxaesJ/VM=
+github.com/hashicorp/go-secure-stdlib/parseutil v0.2.0/go.mod h1:Ll013mhdmsVDuoIXVfBtvgGJsXDYkTw1kooNcoCXuE0=
+github.com/hashicorp/go-secure-stdlib/strutil v0.1.2 h1:kes8mmyCpxJsI7FTwtzRqEy9CdjCtrXrXGuOpxEA7Ts=
+github.com/hashicorp/go-secure-stdlib/strutil v0.1.2/go.mod h1:Gou2R9+il93BqX25LAKCLuM+y9U2T4hlwvT1yprcna4=
+github.com/hashicorp/go-sockaddr v1.0.7 h1:G+pTkSO01HpR5qCxg7lxfsFEZaG+C0VssTy/9dbT+Fw=
+github.com/hashicorp/go-sockaddr v1.0.7/go.mod h1:FZQbEYa1pxkQ7WLpyXJ6cbjpT8q0YgQaK/JakXqGyWw=
+github.com/hashicorp/hcl v1.0.1-vault-7 h1:ag5OxFVy3QYTFTJODRzTKVZ6xvdfLLCA1cy/Y6xGI0I=
+github.com/hashicorp/hcl v1.0.1-vault-7/go.mod h1:XYhtn6ijBSAj6n4YqAaf7RBPS4I06AItNorpy+MoQNM=
+github.com/hashicorp/vault/api v1.22.0 h1:+HYFquE35/B74fHoIeXlZIP2YADVboaPjaSicHEZiH0=
+github.com/hashicorp/vault/api v1.22.0/go.mod h1:IUZA2cDvr4Ok3+NtK2Oq/r+lJeXkeCrHRmqdyWfpmGM=
+github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
+github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
+github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
+github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
+github.com/jackc/pgx/v5 v5.8.0 h1:TYPDoleBBme0xGSAX3/+NujXXtpZn9HBONkQC7IEZSo=
+github.com/jackc/pgx/v5 v5.8.0/go.mod h1:QVeDInX2m9VyzvNeiCJVjCkNFqzsNb43204HshNSZKw=
+github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
+github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
+github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
+github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
+github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ=
+github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
+github.com/klauspost/cpuid/v2 v2.0.9 h1:lgaqFMSdTdQYdZ04uHyN2d/eKdOMyi2YLSvlQIBFYa4=
+github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
+github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0=
+github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk=
+github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
+github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
+github.com/lann/builder v0.0.0-20180802200727-47ae307949d0 h1:SOEGU9fKiNWd/HOJuq6+3iTQz8KNCLtVX6idSoTLdUw=
+github.com/lann/builder v0.0.0-20180802200727-47ae307949d0/go.mod h1:dXGbAdH5GtBTC4WfIxhKZfyBF/HBFgRZSWwZ9g/He9o=
+github.com/lann/ps v0.0.0-20150810152359-62de8c46ede0 h1:P6pPBnrTSX3DEVR4fDembhRWSsG5rVo6hYhAB/ADZrk=
+github.com/lann/ps v0.0.0-20150810152359-62de8c46ede0/go.mod h1:vmVJ0l/dxyfGW6FmdpVm2joNMFikkuWg0EoCKLGUMNw=
+github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHPsaIE=
+github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8=
+github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
+github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
+github.com/mitchellh/go-homedir v1.1.0 h1:lukF9ziXFxDFPkA1vsr5zpc1XuPDn/wFntq5mG+4E0Y=
+github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0=
+github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY=
+github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo=
+github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
+github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
+github.com/redis/go-redis/v9 v9.18.0 h1:pMkxYPkEbMPwRdenAzUNyFNrDgHx9U+DrBabWNfSRQs=
+github.com/redis/go-redis/v9 v9.18.0/go.mod h1:k3ufPphLU5YXwNTUcCRXGxUoF1fqxnhFQmscfkCoDA0=
+github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=
+github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=
+github.com/ryanuber/go-glob v1.0.0 h1:iQh3xXAumdQ+4Ufa5b25cRpC5TYKlno6hsv6Cb3pkBk=
+github.com/ryanuber/go-glob v1.0.0/go.mod h1:807d1WSdnB0XRJzKNil9Om6lcp/3a0v4qIHxIXzX/Yc=
+github.com/shopspring/decimal v1.4.0 h1:bxl37RwXBklmTi0C79JfXCEBD1cqqHt0bbgBAGFp81k=
+github.com/shopspring/decimal v1.4.0/go.mod h1:gawqmDU56v4yIKSwfBSFip1HdCCXN8/+DMd9qYNcwME=
+github.com/sirupsen/logrus v1.9.4 h1:TsZE7l11zFCLZnZ+teH4Umoq5BhEIfIzfRDZ1Uzql2w=
+github.com/sirupsen/logrus v1.9.4/go.mod h1:ftWc9WdOfJ0a92nsE2jF5u5ZwH8Bv2zdeOC42RjbV2g=
+github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
+github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
+github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
+github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
+github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
+github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
+github.com/zeebo/xxh3 v1.0.2 h1:xZmwmqxHZA8AI603jOQ0tMqmBr9lPeFwGg6d+xy9DC0=
+github.com/zeebo/xxh3 v1.0.2/go.mod h1:5NWz9Sef7zIDm2JHfFlcQvNekmcEl9ekUZQQKCYaDcA=
+go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE=
+go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0=
+golang.org/x/crypto v0.40.0 h1:r4x+VvoG5Fm+eJcxMaY8CQM7Lb0l1lsmjGBQ6s8BfKM=
+golang.org/x/crypto v0.40.0/go.mod h1:Qr1vMER5WyS2dfPHAlsOj01wgLbsyWtFn/aY+5+ZdxY=
+golang.org/x/net v0.42.0 h1:jzkYrhi3YQWD6MLBJcsklgQsoAcw89EcZbJw8Z614hs=
+golang.org/x/net v0.42.0/go.mod h1:FF1RA5d3u7nAYA4z2TkclSCKh68eSXtiFwcWQpPXdt8=
+golang.org/x/sync v0.17.0 h1:l60nONMj9l5drqw6jlhIELNv9I0A4OFgRsG9k2oT9Ug=
+golang.org/x/sync v0.17.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
+golang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k=
+golang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
+golang.org/x/text v0.29.0 h1:1neNs90w9YzJ9BocxfsQNHKuAT4pkghyXc4nhZ6sJvk=
+golang.org/x/text v0.29.0/go.mod h1:7MhJOA9CD2qZyOKYazxdYMF85OwPdEr9jTtBpO7ydH4=
+golang.org/x/time v0.12.0 h1:ScB/8o8olJvc+CQPWrK3fPZNfh7qgwCrY0zJmoEQLSE=
+golang.org/x/time v0.12.0/go.mod h1:CDIdPxbZBQxdj6cxyCIdrNogrJKMJ7pr37NYpMcMDSg=
+gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
+gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
+gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
+gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
+gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
+gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
+gorm.io/driver/postgres v1.6.0 h1:2dxzU8xJ+ivvqTRph34QX+WrRaJlmfyPqXmoGVjMBa4=
+gorm.io/driver/postgres v1.6.0/go.mod h1:vUw0mrGgrTK+uPHEhAdV4sfFELrByKVGnaVRkXDhtWo=
+gorm.io/gorm v1.31.1 h1:7CA8FTFz/gRfgqgpeKIBcervUn3xSyPUmr6B2WXJ7kg=
+gorm.io/gorm v1.31.1/go.mod h1:XyQVbO2k6YkOis7C2437jSit3SsDK72s7n7rsSHd+Gs=
diff --git a/core/lib/external/gorm/gorm.go b/core/lib/external/gorm/gorm.go
new file mode 100644
index 0000000..24071bd
--- /dev/null
+++ b/core/lib/external/gorm/gorm.go
@@ -0,0 +1,139 @@
+package gormmodule
+
+import (
+ "database/sql"
+ "errors"
+ "fmt"
+ "log"
+ "os"
+ "sync"
+ "time"
+
+ "github.com/sirupsen/logrus"
+
+ "gorm.io/driver/postgres"
+ "gorm.io/gorm"
+ "gorm.io/gorm/logger"
+)
+
+type ConfigConnectGorm struct {
+ Host string
+ Port string
+ User string
+ Password string
+ Name string
+ SslMode string
+}
+
+var (
+ gormDB *gorm.DB
+ once sync.Once
+)
+
+func connectGormDB(configObj *ConfigConnectGorm) (*gorm.DB, error) {
+ if configObj == nil {
+ return nil, errors.New("connectGormDB: configObj is nil")
+ }
+
+ log.Println("🚀 ConnectGormDB")
+ sslMode := "disable"
+ if configObj.SslMode != "" {
+ sslMode = configObj.SslMode
+ }
+
+ // Поддерживаем только disable и require
+ if sslMode != "disable" && sslMode != "require" {
+ return nil, errors.New("ConnectDB: unsupported sslmode, only 'disable' and 'require' are allowed")
+ }
+
+ connStr := fmt.Sprintf("host=%s port=%s user=%s password=%s dbname=%s sslmode=%s",
+ configObj.Host,
+ configObj.Port,
+ configObj.User,
+ configObj.Password,
+ configObj.Name,
+ sslMode)
+
+ newLogger := logger.New(
+ log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer
+ logger.Config{
+ SlowThreshold: time.Second, // медленный SQL порог
+ LogLevel: logger.Silent, // уровень логирования
+ IgnoreRecordNotFoundError: true, // игнорировать ошибки записи не найдены
+ Colorful: false, // отключить цвет
+ },
+ )
+
+ db, err := gorm.Open(postgres.Open(connStr), &gorm.Config{
+ Logger: newLogger,
+ })
+ if err != nil {
+ logrus.Errorf("🔴 error: %s: %+v", "connectGormDB-Open", err)
+ return nil, err
+ }
+
+ return db, nil
+}
+
+// Подключение к базе данных GORM с использованием Singleton
+func GormDatabaseConnect(configObj *ConfigConnectGorm) (*gorm.DB, *sql.DB, error) {
+ logrus.Info("🚀 GormDatabaseConnect")
+ if configObj == nil {
+ return nil, nil, errors.New("configObj is nil")
+ }
+
+ var err error
+ once.Do(func() {
+ gormDB, err = connectGormDB(configObj)
+ })
+
+ if err != nil {
+ return nil, nil, err
+ }
+
+ if gormDB == nil {
+ return nil, nil, errors.New("failed to connect database: GormDB instance is nil")
+ }
+
+ sqlDB, err := gormDB.DB()
+ if err != nil {
+ return nil, nil, errors.New("failed to get DB from GORM")
+ }
+
+ // SetMaxIdleConns устанавливает максимальное количество соединений в пуле простаивающих соединений.
+ sqlDB.SetMaxIdleConns(2)
+
+ // SetMaxOpenConns устанавливает максимальное количество открытых соединений с базой данных.
+ sqlDB.SetMaxOpenConns(10)
+
+ // SetConnMaxLifetime устанавливает максимальное время, в течение которого может быть повторно использовано соединение.
+ sqlDB.SetConnMaxLifetime(5 * time.Minute)
+
+ gormDB.Exec("CREATE EXTENSION IF NOT EXISTS \"uuid-ossp\";")
+ return gormDB, sqlDB, nil
+}
+
+// Отключение от базы данных GORM
+func GormDatabaseDisconnect() error {
+ if gormDB == nil {
+ return nil
+ }
+
+ sqlDB, err := gormDB.DB()
+ if err != nil {
+ return err
+ }
+
+ // Закрываем все открытые соединения
+ if err := sqlDB.Close(); err != nil {
+ return errors.New(fmt.Sprintf("failed to close database connections: %v", err))
+ }
+
+ // Очищаем пул соединений
+ sqlDB.SetMaxIdleConns(0)
+ sqlDB.SetMaxOpenConns(0)
+
+ // Обнуляем глобальную переменную
+ gormDB = nil
+ return nil
+}
diff --git a/core/lib/external/pgxpool/pgxpools.go b/core/lib/external/pgxpool/pgxpools.go
new file mode 100644
index 0000000..a0d43a1
--- /dev/null
+++ b/core/lib/external/pgxpool/pgxpools.go
@@ -0,0 +1,86 @@
+package pgxpoolmodule
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "log"
+ "sync"
+ "time"
+
+ "github.com/jackc/pgx/v5/pgxpool"
+)
+
+type ConfigConnectPgxPool struct {
+ Host string
+ Port string
+ User string
+ Password string
+ Name string
+ SSLMode string
+}
+
+var (
+ pool *pgxpool.Pool
+ once sync.Once
+)
+
+func ConnectDB(configObj *ConfigConnectPgxPool) (*pgxpool.Pool, error) {
+ var err error
+ once.Do(func() {
+ if configObj == nil {
+ err = errors.New("ConnectDB: configObj is nil")
+ return
+ }
+
+ log.Println("🚀 ConnectDB")
+ sslMode := "disable"
+ if configObj.SSLMode != "" {
+ sslMode = configObj.SSLMode
+ }
+
+ // Поддерживаем только disable и require
+ if sslMode != "disable" && sslMode != "require" {
+ err = errors.New("ConnectDB: unsupported sslmode, only 'disable' and 'require' are allowed")
+ return
+ }
+
+ log.Println("🚀 sslMode: ", sslMode)
+ connStr := fmt.Sprintf("host=%s port=%s user=%s password=%s dbname=%s sslmode=%s target_session_attrs=read-write",
+ configObj.Host,
+ configObj.Port,
+ configObj.User,
+ configObj.Password,
+ configObj.Name,
+ sslMode)
+
+ configDB, err := pgxpool.ParseConfig(connStr)
+ if err != nil {
+ err = errors.New("ConnectDB: failed to parse config: " + err.Error())
+ return
+ }
+
+ // настройки пула
+ configDB.MaxConns = 2 // Максимальное количество открытых соединений в пуле
+ configDB.MinConns = 1 // Минимальное количество открытых соединений, которое пул будет поддерживать
+ configDB.MaxConnLifetime = time.Second * 45 // Максимальное время жизни соединения. После этого времени соединение будет закрыто
+ configDB.MaxConnIdleTime = time.Second * 45 // Максимальное время простоя соединения. Если соединение не используется в течение этого времени, оно будет закрыто
+ configDB.HealthCheckPeriod = time.Second * 15 // Периодичность проверки состояния соединений в пуле
+
+ pool, err = pgxpool.NewWithConfig(context.Background(), configDB)
+ if err != nil {
+ err = errors.New("ConnectDB: failed to connect to database: " + err.Error())
+ return
+ }
+ })
+
+ if err != nil {
+ return nil, err
+ }
+
+ if pool == nil {
+ return nil, errors.New("ConnectDB: failed to connect to database: pool is nil")
+ }
+
+ return pool, nil
+}
diff --git a/core/lib/external/telegram/init.go b/core/lib/external/telegram/init.go
new file mode 100644
index 0000000..3da6e25
--- /dev/null
+++ b/core/lib/external/telegram/init.go
@@ -0,0 +1,51 @@
+package telegram
+
+import (
+ "errors"
+ "fmt"
+ "sync"
+
+ tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
+ "github.com/sirupsen/logrus"
+)
+
+type TgBotClient struct {
+ bot *tgbotapi.BotAPI
+ config *BotConfig
+}
+
+var (
+ onceTgBotClient sync.Once
+ tgBotClientInstance *TgBotClient
+)
+
+// NewTgBotClient создает новый экземпляр Client с заданным API ключом.
+func NewTgBotClient(config *BotConfig) (*TgBotClient, error) {
+ if config == nil {
+ return nil, errors.New("failed to init TgBotClient: Api key is nil")
+ }
+ if config.BotKey == "" {
+ return nil, errors.New("failed to init TgBotClient: Api key is nil")
+ }
+
+ onceTgBotClient.Do(func() {
+ bot, err := tgbotapi.NewBotAPI(config.BotKey)
+ if err != nil {
+ println(errors.New(fmt.Sprintf("🔴 error failed to setup telegram bot: %v", err)))
+ return
+ }
+
+ tgBotClientInstance = &TgBotClient{
+ bot: bot,
+ config: config,
+ }
+
+ logrus.Info("✅ Telegram BOT API success connected")
+ })
+
+ return tgBotClientInstance, nil
+}
+
+func (client *TgBotClient) GetBot() *tgbotapi.BotAPI {
+ return client.bot
+}
diff --git a/core/lib/external/telegram/message.go b/core/lib/external/telegram/message.go
new file mode 100644
index 0000000..91beee5
--- /dev/null
+++ b/core/lib/external/telegram/message.go
@@ -0,0 +1,56 @@
+package telegram
+
+import (
+ "errors"
+ "fmt"
+ "io"
+
+ tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
+ "github.com/sirupsen/logrus"
+)
+
+// SendMessageToTelegramBot отправляет сообщение в указанный чат.
+func (client *TgBotClient) SendMessageToTelegramBot(title, text *string, ChatID *int64, photoReader io.ReadCloser, buttonText, buttonURL *string) error {
+ if text == nil || ChatID == nil || title == nil {
+ logrus.Error("🔴 error SendMessageToTelegramBot: invalid parameter")
+ return errors.New("invalid parameter")
+ }
+
+ var markup *tgbotapi.InlineKeyboardMarkup
+ if buttonText != nil && *buttonText != "" && buttonURL != nil {
+ button := tgbotapi.NewInlineKeyboardButtonURL(*buttonText, *buttonURL)
+ row := tgbotapi.NewInlineKeyboardRow(button)
+ markup = &tgbotapi.InlineKeyboardMarkup{
+ InlineKeyboard: [][]tgbotapi.InlineKeyboardButton{row},
+ }
+ }
+
+ if photoReader != nil {
+ photoMsg := tgbotapi.NewPhoto(*ChatID, tgbotapi.FileReader{
+ Name: "photo",
+ Reader: photoReader,
+ })
+ photoMsg.Caption = fmt.Sprintf("%s\n\n%s", *title, *text)
+ photoMsg.ParseMode = "HTML"
+ if markup != nil {
+ photoMsg.ReplyMarkup = markup
+ }
+
+ if _, err := client.bot.Send(photoMsg); err != nil {
+ logrus.Error("🔴 error SendMessageToTelegramBot: Failed to send photo with message", err)
+ return err
+ }
+ } else {
+ msg := tgbotapi.NewMessage(*ChatID, fmt.Sprintf("%s\n\n%s", *title, *text))
+ msg.ParseMode = "HTML"
+ if markup != nil {
+ msg.ReplyMarkup = markup
+ }
+
+ if _, err := client.bot.Send(msg); err != nil {
+ logrus.Error("🔴 error SendMessageToTelegramBot: Failed to send message", err)
+ return err
+ }
+ }
+ return nil
+}
diff --git a/core/lib/external/telegram/req.go b/core/lib/external/telegram/req.go
new file mode 100644
index 0000000..0cbf34f
--- /dev/null
+++ b/core/lib/external/telegram/req.go
@@ -0,0 +1,60 @@
+package telegram
+
+import (
+ "bytes"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "net/http"
+)
+
+// apiResponse описывает ответ API Telegram
+type apiResponse struct {
+ Ok bool `json:"ok"`
+ Result json.RawMessage `json:"result"`
+}
+
+// sendRequest отправляет запрос к API Telegram и возвращает ответ
+func (client *TgBotClient) sendRequest(method string, requestBody interface{}) (*apiResponse, error) {
+ var reqBody []byte
+ var err error
+ if requestBody != nil {
+ reqBody, err = json.Marshal(requestBody)
+ if err != nil {
+ return nil, errors.New(fmt.Sprintf("marshaling request body: %v", err))
+ }
+ }
+
+ req, err := http.NewRequest(http.MethodPost, fmt.Sprintf("https://api.telegram.org/bot%s/%s", client.config.BotKey, method), bytes.NewReader(reqBody))
+ if err != nil {
+ return nil, errors.New(fmt.Sprintf("creating request: %v", err))
+ }
+ req.Header.Set("Content-Type", "application/json")
+ req.Header.Set("X-Telegram-Bot-Api-Secret-Token", client.config.BotKey)
+
+ resp, err := http.DefaultClient.Do(req)
+ if err != nil {
+ return nil, errors.New(fmt.Sprintf("sending request error: %v", err))
+ }
+ defer resp.Body.Close()
+
+ if resp.StatusCode != http.StatusOK {
+ bodyBytes, err := io.ReadAll(resp.Body)
+ if err != nil {
+ println(errors.New(fmt.Sprintf("🔴 error reading response body: %v", err)))
+ } else {
+ bodyString := string(bodyBytes)
+ println(errors.New(fmt.Sprintf("🔴 unexpected status body: %v", bodyString)))
+ }
+
+ return nil, errors.New(fmt.Sprintf("unexpected status code: %d", resp.StatusCode))
+ }
+
+ var apiResponse apiResponse
+ if err := json.NewDecoder(resp.Body).Decode(&apiResponse); err != nil {
+ return nil, errors.New(fmt.Sprintf("decoding response: %v", err))
+ }
+
+ return &apiResponse, nil
+}
diff --git a/core/lib/external/telegram/types.go b/core/lib/external/telegram/types.go
new file mode 100644
index 0000000..98f962c
--- /dev/null
+++ b/core/lib/external/telegram/types.go
@@ -0,0 +1,25 @@
+package telegram
+
+import tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
+
+type BotConfig struct {
+ BotKey string
+ ApiURL string
+}
+
+type InvoiceRequestAmount struct {
+ Amount *int `json:"amount"`
+}
+
+type InvoiceLink struct {
+ Link *string `json:"link"`
+}
+
+type InvoiceRequest struct {
+ Title string `json:"title"`
+ Description string `json:"description"`
+ Payload string `json:"payload"`
+ Currency string `json:"currency"`
+ Prices []tgbotapi.LabeledPrice `json:"prices"`
+ SubscriptionPeriod *int `json:"subscription_period"` //The currency must be set to “XTR” (Telegram Stars) if the parameter is used. Currently, it must always be 2592000 (30 days) if specified.
+}
diff --git a/core/lib/internally/client-controllers/0_init.go b/core/lib/internally/client-controllers/0_init.go
new file mode 100644
index 0000000..fec6696
--- /dev/null
+++ b/core/lib/internally/client-controllers/0_init.go
@@ -0,0 +1,47 @@
+package clientcontrollers
+
+import (
+ configcore "bitrix_balancer_api/core/config"
+ database "bitrix_balancer_api/core/db"
+ redismodule "bitrix_balancer_api/core/lib/internally/redis"
+ "errors"
+ "fmt"
+)
+
+type ClientsExternal struct {
+ Config *configcore.Config
+ Redis *redismodule.ModuleRedis
+ DB *database.ModuleDB
+}
+
+func ReturnClientsExternal(cfgOptions *configcore.ConfigLoadOptions) (ClientsExternal, error) {
+ clientsExternal := ClientsExternal{}
+ if cfgOptions == nil {
+ cfgOptions = &configcore.ConfigLoadOptions{}
+ return clientsExternal, errors.New("cfgOptions is nil")
+ }
+ cfg, err := configcore.LoadConfig(cfgOptions)
+ if err != nil {
+ return clientsExternal, errors.New(fmt.Sprintf("failed to load config file: %v", err))
+ }
+
+ clientsExternal.Config = cfg
+
+ if cfgOptions.Redis {
+ redisClient, err = getRedisClient(cfg)
+ if err != nil {
+ return clientsExternal, errors.New(fmt.Sprintf("failed to get redis client: %v", err))
+ }
+ clientsExternal.Redis = redisClient
+ }
+
+ if cfgOptions.Database {
+ dbClient, err = getDbClient(cfg)
+ if err != nil {
+ return clientsExternal, errors.New(fmt.Sprintf("failed to get db client: %v", err))
+ }
+ clientsExternal.DB = dbClient
+ }
+
+ return clientsExternal, nil
+}
diff --git a/core/lib/internally/client-controllers/db-client.go b/core/lib/internally/client-controllers/db-client.go
new file mode 100644
index 0000000..58b1ead
--- /dev/null
+++ b/core/lib/internally/client-controllers/db-client.go
@@ -0,0 +1,49 @@
+package clientcontrollers
+
+import (
+ configcore "bitrix_balancer_api/core/config"
+ database "bitrix_balancer_api/core/db"
+ pgxpoolmodule "bitrix_balancer_api/core/lib/external/pgxpool"
+ "fmt"
+ "sync"
+)
+
+var (
+ dbOnce sync.Once
+ dbClient *database.ModuleDB
+)
+
+func getDbClient(cfg *configcore.Config) (*database.ModuleDB, error) {
+ var err error
+
+ if redisClient == nil {
+ cfg0, err := configcore.LoadConfig(&configcore.ConfigLoadOptions{
+ Redis: true,
+ })
+ if err != nil {
+ return nil, err
+ }
+ redisClient, err = getRedisClient(cfg0)
+ if err != nil {
+ return nil, err
+ }
+ }
+
+ dbOnce.Do(func() {
+ var initErr error
+ dbClient, initErr = database.NewModuleDB(&pgxpoolmodule.ConfigConnectPgxPool{
+ Host: cfg.Database.Host,
+ Port: fmt.Sprintf("%d", cfg.Database.Port),
+ User: cfg.Database.User,
+ Password: cfg.Database.Password,
+ Name: cfg.Database.DB,
+ SSLMode: cfg.Database.SSL,
+ }, redisClient)
+ if initErr != nil {
+ err = initErr
+ return
+ }
+ })
+
+ return dbClient, err
+}
diff --git a/core/lib/internally/client-controllers/redis-client.go b/core/lib/internally/client-controllers/redis-client.go
new file mode 100644
index 0000000..1b03774
--- /dev/null
+++ b/core/lib/internally/client-controllers/redis-client.go
@@ -0,0 +1,34 @@
+package clientcontrollers
+
+import (
+ configcore "bitrix_balancer_api/core/config"
+ redismodule "bitrix_balancer_api/core/lib/internally/redis"
+ "fmt"
+ "sync"
+
+ "github.com/sirupsen/logrus"
+)
+
+var (
+ redisOnce sync.Once
+
+ redisClient *redismodule.ModuleRedis
+)
+
+func getRedisClient(cfg *configcore.Config) (*redismodule.ModuleRedis, error) {
+ var err error
+
+ redisOnce.Do(func() {
+ redisClient = redismodule.GetRedisModuleInstance(&redismodule.RedisConfig{
+ Host: cfg.Redis.Host,
+ Port: fmt.Sprintf("%d", cfg.Redis.Port),
+ User: cfg.Redis.User,
+ Password: cfg.Redis.Password,
+ })
+ if err != nil {
+ logrus.Errorln("🔴 failed to get Redis client: ", err)
+ }
+ })
+
+ return redisClient, err
+}
diff --git a/core/lib/internally/config-loader/cfgldr.go b/core/lib/internally/config-loader/cfgldr.go
new file mode 100644
index 0000000..b27f5f0
--- /dev/null
+++ b/core/lib/internally/config-loader/cfgldr.go
@@ -0,0 +1,22 @@
+package cfgldrlib
+
+import "errors"
+
+func LoadConfig[T any](params *ConfigLoaders) (*T, error) {
+ err := validateParams(params)
+ if err != nil {
+ return nil, err
+ }
+ configProvider, err := loadConfigProvider(params)
+ if err != nil {
+ return nil, err
+ }
+
+ if configProvider == ConfigProviderYml {
+ return loadConfigFromYml[T](params.ConfigYml)
+ } else if configProvider == ConfigProviderVault {
+ return loadConfigFromVault[T](params.VaultParams)
+ }
+
+ return nil, errors.New("config error detected")
+}
diff --git a/core/lib/internally/config-loader/loader.go b/core/lib/internally/config-loader/loader.go
new file mode 100644
index 0000000..aa9914a
--- /dev/null
+++ b/core/lib/internally/config-loader/loader.go
@@ -0,0 +1,28 @@
+package cfgldrlib
+
+import (
+ "strings"
+
+ "gopkg.in/yaml.v3"
+)
+
+func loadConfigFromYml[T any](configYML *string) (*T, error) {
+ readerConfig := strings.NewReader(*configYML)
+ decoder := yaml.NewDecoder(readerConfig)
+
+ var config T
+ if err := decoder.Decode(&config); err != nil {
+ return nil, err
+ }
+
+ return &config, nil
+}
+
+func loadConfigFromVault[T any](vaultParams *VaultParamsT) (*T, error) {
+ var config T
+ err := fillStructFromVault(&config, vaultParams.VaultClient, *vaultParams.KvName)
+ if err != nil {
+ return nil, err
+ }
+ return &config, nil
+}
diff --git a/core/lib/internally/config-loader/tag-worker.go b/core/lib/internally/config-loader/tag-worker.go
new file mode 100644
index 0000000..2e98c1a
--- /dev/null
+++ b/core/lib/internally/config-loader/tag-worker.go
@@ -0,0 +1,290 @@
+package cfgldrlib
+
+import (
+ "fmt"
+ "reflect"
+ "strings"
+
+ "github.com/hashicorp/vault/api"
+)
+
+func buildDataVaultPath(basePath string) (string, error) {
+ if basePath == "" {
+ return "", fmt.Errorf("basePath is empty")
+ }
+
+ slashIndex := strings.Index(basePath, "/")
+ if slashIndex == -1 {
+ return basePath + "/data", nil
+ }
+
+ return basePath[:slashIndex+1] + "data" + basePath[slashIndex:], nil
+}
+
+func getVaultValue(client *api.Client, vaultPath, key string) (any, error) {
+
+ secret, err := client.Logical().Read(vaultPath)
+ if err != nil {
+ return nil, err
+ }
+ if secret == nil || secret.Data == nil {
+ return nil, fmt.Errorf("vault: secret not found at path %s", vaultPath)
+ }
+
+ data, ok := secret.Data["data"].(map[string]any)
+ if !ok {
+ return nil, fmt.Errorf("vault: failed to get data from secret %s", vaultPath)
+ }
+
+ if key == "" {
+ return data, nil
+ }
+ val, ok := data[key]
+ if !ok {
+ return nil, fmt.Errorf("vault: key %s not found in secret %s", key, vaultPath)
+ }
+ return val, nil
+}
+
+func fillStructFromVault(v any, client *api.Client, basePath string) error {
+ val := reflect.ValueOf(v)
+ if val.Kind() != reflect.Ptr || val.IsNil() {
+ return fmt.Errorf("expected pointer to struct, got %T", v)
+ }
+ val = val.Elem()
+ typ := val.Type()
+ if typ.Kind() != reflect.Struct {
+ return fmt.Errorf("expected struct, got %T", v)
+ }
+
+ for _, field := range reflect.VisibleFields(typ) {
+ fieldVal := val.FieldByName(field.Name)
+ cfgldrTag := field.Tag.Get(TagName)
+ if cfgldrTag == "-" {
+ continue
+ }
+ vaultKey := field.Name
+ if cfgldrTag != "" {
+ for part := range strings.SplitSeq(cfgldrTag, ",") {
+ if v, ok := strings.CutPrefix(part, ValTagParam); ok {
+ vaultKey = v
+ }
+ }
+ }
+ if fieldVal.Kind() == reflect.Struct {
+ nextPath := vaultKey
+ if basePath != "" {
+ nextPath = basePath + "/" + vaultKey
+ }
+ err := fillStructFromVault(fieldVal.Addr().Interface(), client, nextPath)
+ if err != nil {
+ fmt.Printf("⚠️ Error processing nested struct at path %s: %v\n", nextPath, err)
+ }
+ continue
+ }
+
+ vaultPath, err := buildDataVaultPath(basePath)
+ if err != nil {
+ fmt.Printf("⚠️ Error building vault path: %s, %v\n", basePath, err)
+ continue
+ }
+
+ valFromVault, err := getVaultValue(client, vaultPath, vaultKey)
+ if err != nil {
+ fmt.Printf("⚠️ Value not found for key: %s (field: %s) — %v\n", basePath, vaultKey, err)
+ continue
+ }
+ if fieldVal.CanSet() {
+ err = setValue(fieldVal, valFromVault)
+ if err != nil {
+ fmt.Printf("⚠️ Failed to set value for %s (field: %s): %v\n", basePath, vaultKey, err)
+ }
+ }
+ }
+ return nil
+}
+
+func setValue(fieldVal reflect.Value, val any) error {
+ switch fieldVal.Kind() {
+ case reflect.String:
+ str, ok := val.(string)
+ if !ok {
+ str = fmt.Sprintf("%v", val)
+ }
+ fieldVal.SetString(str)
+ case reflect.Int, reflect.Int64, reflect.Int32, reflect.Int16, reflect.Int8:
+ var intVal int64
+ switch v := val.(type) {
+ case int:
+ intVal = int64(v)
+ case int64:
+ intVal = v
+ case float64:
+ intVal = int64(v)
+ case string:
+ var err error
+ intVal, err = parseStringToInt64(v)
+ if err != nil {
+ return err
+ }
+ default:
+ str := fmt.Sprintf("%v", v)
+ var err error
+ intVal, err = parseStringToInt64(str)
+ if err != nil {
+ return err
+ }
+ }
+ fieldVal.SetInt(intVal)
+ case reflect.Float32, reflect.Float64:
+ var floatVal float64
+ switch v := val.(type) {
+ case float64:
+ floatVal = v
+ case float32:
+ floatVal = float64(v)
+ case int:
+ floatVal = float64(v)
+ case int64:
+ floatVal = float64(v)
+ case string:
+ var err error
+ floatVal, err = parseStringToFloat64(v)
+ if err != nil {
+ return err
+ }
+ default:
+ str := fmt.Sprintf("%v", v)
+ var err error
+ floatVal, err = parseStringToFloat64(str)
+ if err != nil {
+ return err
+ }
+ }
+ fieldVal.SetFloat(floatVal)
+ case reflect.Bool:
+ var boolVal bool
+ switch v := val.(type) {
+ case bool:
+ boolVal = v
+ case string:
+ var err error
+ boolVal, err = parseStringToBool(v)
+ if err != nil {
+ return err
+ }
+ default:
+ str := fmt.Sprintf("%v", v)
+ var err error
+ boolVal, err = parseStringToBool(str)
+ if err != nil {
+ return err
+ }
+ }
+ fieldVal.SetBool(boolVal)
+ case reflect.Slice:
+ return setSliceValue(fieldVal, val)
+ default:
+ return fmt.Errorf("unsupported field type: %s", fieldVal.Kind())
+ }
+ return nil
+}
+
+func setSliceValue(fieldVal reflect.Value, val any) error {
+ elemType := fieldVal.Type().Elem()
+
+ if slice, ok := val.([]any); ok {
+ result := reflect.MakeSlice(fieldVal.Type(), len(slice), len(slice))
+
+ for i, item := range slice {
+ elem := reflect.New(elemType).Elem()
+
+ err := setValue(elem, item)
+ if err != nil {
+ return fmt.Errorf("failed to set slice element %d: %v", i, err)
+ }
+
+ result.Index(i).Set(elem)
+ }
+
+ fieldVal.Set(result)
+ return nil
+ }
+
+ if str, ok := val.(string); ok {
+ if strings.HasPrefix(strings.TrimSpace(str), "[") && strings.HasSuffix(strings.TrimSpace(str), "]") {
+ if elemType.Kind() == reflect.String {
+ content := strings.TrimSpace(str[1 : len(str)-1])
+ if content == "" {
+ fieldVal.Set(reflect.MakeSlice(fieldVal.Type(), 0, 0))
+ return nil
+ }
+
+ items := strings.Split(content, ",")
+ result := reflect.MakeSlice(fieldVal.Type(), len(items), len(items))
+
+ for i, item := range items {
+ cleanItem := strings.Trim(strings.TrimSpace(item), `"'`)
+ result.Index(i).SetString(cleanItem)
+ }
+
+ fieldVal.Set(result)
+ return nil
+ }
+ }
+
+ if elemType.Kind() == reflect.String {
+ items := strings.Split(str, ",")
+ result := reflect.MakeSlice(fieldVal.Type(), len(items), len(items))
+
+ for i, item := range items {
+ cleanItem := strings.TrimSpace(item)
+ result.Index(i).SetString(cleanItem)
+ }
+
+ fieldVal.Set(result)
+ return nil
+ }
+ }
+
+ elem := reflect.New(elemType).Elem()
+ err := setValue(elem, val)
+ if err != nil {
+ return fmt.Errorf("failed to set single element in slice: %v", err)
+ }
+
+ result := reflect.MakeSlice(fieldVal.Type(), 1, 1)
+ result.Index(0).Set(elem)
+ fieldVal.Set(result)
+
+ return nil
+}
+
+func parseStringToInt64(s string) (int64, error) {
+ var i int64
+ _, err := fmt.Sscanf(s, "%d", &i)
+ if err != nil {
+ return 0, fmt.Errorf("failed to parse int from string: %s", s)
+ }
+ return i, nil
+}
+
+func parseStringToFloat64(s string) (float64, error) {
+ var f float64
+ _, err := fmt.Sscanf(s, "%f", &f)
+ if err != nil {
+ return 0, fmt.Errorf("failed to parse float from string: %s", s)
+ }
+ return f, nil
+}
+
+func parseStringToBool(s string) (bool, error) {
+ s = strings.ToLower(strings.TrimSpace(s))
+ if s == "true" || s == "1" {
+ return true, nil
+ }
+ if s == "false" || s == "0" {
+ return false, nil
+ }
+ return false, fmt.Errorf("failed to parse bool from string: %s", s)
+}
diff --git a/core/lib/internally/config-loader/type.go b/core/lib/internally/config-loader/type.go
new file mode 100644
index 0000000..15a89f1
--- /dev/null
+++ b/core/lib/internally/config-loader/type.go
@@ -0,0 +1,26 @@
+package cfgldrlib
+
+import (
+ "github.com/hashicorp/vault/api"
+)
+
+const TagName = "cfgldr"
+const ValTagParam = "val="
+
+type ConfigProvider string
+
+const (
+ ConfigProviderYml ConfigProvider = "yml"
+ ConfigProviderVault ConfigProvider = "vault"
+)
+
+type ConfigLoaders struct {
+ ConfigYml *string
+ ConfigProvider *ConfigProvider
+ VaultParams *VaultParamsT
+}
+
+type VaultParamsT struct {
+ KvName *string
+ VaultClient *api.Client
+}
diff --git a/core/lib/internally/config-loader/validate.go b/core/lib/internally/config-loader/validate.go
new file mode 100644
index 0000000..834b7ef
--- /dev/null
+++ b/core/lib/internally/config-loader/validate.go
@@ -0,0 +1,40 @@
+package cfgldrlib
+
+import "errors"
+
+func validateParams(params *ConfigLoaders) error {
+ if params == nil {
+ return errors.New("params is nil")
+ }
+ if params.ConfigYml == nil && params.VaultParams == nil {
+ return errors.New("config yml or vault client is nil")
+ }
+
+ // Проверяем VaultParams только если они предоставлены
+ if params.VaultParams != nil {
+ if params.VaultParams.KvName == nil {
+ return errors.New("vault kv name is nil")
+ }
+ if params.VaultParams.VaultClient == nil {
+ return errors.New("vault client is nil")
+ }
+ }
+
+ return nil
+}
+
+func loadConfigProvider(params *ConfigLoaders) (ConfigProvider, error) {
+ if params.ConfigProvider != nil {
+ return *params.ConfigProvider, nil
+ }
+
+ if params.ConfigYml != nil {
+ return ConfigProviderYml, nil
+ }
+
+ if params.VaultParams != nil && params.VaultParams.VaultClient != nil {
+ return ConfigProviderVault, nil
+ }
+
+ return "", errors.New("config provider error detected")
+}
diff --git a/core/lib/internally/init.go b/core/lib/internally/init.go
new file mode 100644
index 0000000..d865753
--- /dev/null
+++ b/core/lib/internally/init.go
@@ -0,0 +1,7 @@
+package internalservices
+
+import redismodule "bitrix_balancer_api/core/lib/internally/redis"
+
+func InitRedisModule(redisConfigObj *redismodule.RedisConfig) *redismodule.ModuleRedis {
+ return redismodule.GetRedisModuleInstance(redisConfigObj)
+}
diff --git a/core/lib/internally/redis/0_init.go b/core/lib/internally/redis/0_init.go
new file mode 100644
index 0000000..f2ddb32
--- /dev/null
+++ b/core/lib/internally/redis/0_init.go
@@ -0,0 +1,82 @@
+package redismodule
+
+import (
+ "fmt"
+ "github.com/redis/go-redis/v9"
+ "os"
+ "sync"
+ "time"
+)
+
+var (
+ onceRedisModule sync.Once
+ redisModuleInstance *ModuleRedis
+)
+
+type ModuleRedis struct {
+ RedisConfig *RedisConfig
+ RedisClient *redis.Client
+}
+
+func GetRedisModuleInstance(redisConfigObj *RedisConfig) *ModuleRedis {
+ onceRedisModule.Do(func() {
+ redisClient := CreateRedisClient(redisConfigObj, 0)
+ redisModuleInstance = &ModuleRedis{
+ RedisConfig: redisConfigObj,
+ RedisClient: redisClient,
+ }
+ })
+ return redisModuleInstance
+}
+
+func CreateRedisClient(redisConfigObj *RedisConfig, redisNDb int) *redis.Client {
+ redisHost := os.Getenv("REDISHOST")
+ redisPort := os.Getenv("REDISPORT")
+ redisUser := ""
+ redisPassword := ""
+ redisConnectURI := ""
+
+ if redisHost == "" || redisPort == "" {
+ redisHost = redisConfigObj.Host
+ redisPort = redisConfigObj.Port
+ }
+ if redisConfigObj.User != "" {
+ redisUser = redisConfigObj.User
+ }
+ if redisConfigObj.Password != "" {
+ redisPassword = redisConfigObj.Password
+ } else {
+ if redisConfigObj.ConnectURI != "" {
+ redisConnectURI = redisConfigObj.ConnectURI
+ } else {
+ redisConnectURI = fmt.Sprintf("%s:%s", redisHost, redisPort)
+ }
+ }
+
+ var opts *redis.Options
+ if redisConnectURI != "" {
+ opts = &redis.Options{
+ Addr: redisConnectURI,
+ Username: redisUser,
+ Password: redisPassword,
+ DB: redisNDb,
+ }
+ } else { // Обычное подключение
+ opts = &redis.Options{
+ Addr: fmt.Sprintf("%s:%s", redisHost, redisPort),
+ Username: redisUser,
+ Password: redisPassword,
+ DB: redisNDb,
+ DialTimeout: 10 * time.Second,
+ ReadTimeout: 30 * time.Second,
+ WriteTimeout: 30 * time.Second,
+ PoolSize: 20,
+ PoolTimeout: 30 * time.Second,
+ }
+ }
+ return redis.NewClient(opts)
+}
+
+func (m *ModuleRedis) GetClient() *redis.Client {
+ return m.RedisClient
+}
diff --git a/core/lib/internally/redis/redis_check.go b/core/lib/internally/redis/redis_check.go
new file mode 100644
index 0000000..e0df130
--- /dev/null
+++ b/core/lib/internally/redis/redis_check.go
@@ -0,0 +1,39 @@
+package redismodule
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "time"
+
+ "github.com/redis/go-redis/v9"
+ "github.com/sirupsen/logrus"
+)
+
+// Проверка и удаление временных данных данных из Redis
+func (m *ModuleRedis) CheckAndDeleteFromRedis(userIdent, expectedValue, identType string) error {
+ ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
+ defer cancel()
+
+ userIdentCustom := fmt.Sprintf("%s:%s", identType, userIdent)
+
+ result, err := m.RedisClient.Get(ctx, userIdentCustom).Result()
+ if err == redis.Nil {
+ logrus.Error("🛑 error CheckAndDeleteFromRedis 1: ", err)
+ return errors.New("not_found")
+ } else if err != nil {
+ logrus.Error("🛑 error CheckAndDeleteFromRedis 0: ", err)
+ return errors.New("not_found")
+ }
+
+ if result != expectedValue {
+ return errors.New("invalid_code")
+ }
+
+ _, err = m.RedisClient.Del(ctx, userIdentCustom).Result()
+ if err != nil {
+ logrus.Error("🛑 error CheckAndDeleteFromRedis: ", err)
+ return errors.New("not_found")
+ }
+ return nil
+}
diff --git a/core/lib/internally/redis/redis_methods.go b/core/lib/internally/redis/redis_methods.go
new file mode 100644
index 0000000..5e16e8b
--- /dev/null
+++ b/core/lib/internally/redis/redis_methods.go
@@ -0,0 +1,26 @@
+package redismodule
+
+import (
+ "context"
+ "github.com/redis/go-redis/v9"
+ "time"
+)
+
+// Set сохраняет значение по ключу с TTL. ttl=0 — без истечения.
+func (m *ModuleRedis) Set(ctx context.Context, key string, value interface{}, ttl time.Duration) error {
+ return m.RedisClient.Set(ctx, key, value, ttl).Err()
+}
+
+// Get возвращает значение по ключу. Если ключ не найден — возвращает redis.Nil.
+func (m *ModuleRedis) Get(ctx context.Context, key string) (string, error) {
+ result, err := m.RedisClient.Get(ctx, key).Result()
+ if err == redis.Nil {
+ return "", err // пробрасываем redis.Nil как есть — caller сам решает
+ }
+ return result, err
+}
+
+// Del удаляет ключ. Не возвращает ошибку если ключа нет.
+func (m *ModuleRedis) Del(ctx context.Context, key string) error {
+ return m.RedisClient.Del(ctx, key).Err()
+}
diff --git a/core/lib/internally/redis/redis_w.go b/core/lib/internally/redis/redis_w.go
new file mode 100644
index 0000000..dd23ddf
--- /dev/null
+++ b/core/lib/internally/redis/redis_w.go
@@ -0,0 +1,42 @@
+package redismodule
+
+import (
+ "context"
+ "errors"
+ "reflect"
+ "strings"
+ "time"
+
+ "github.com/sirupsen/logrus"
+)
+
+func (m *ModuleRedis) GetRedisMemoryUsage() (*RedisMemoryInfo, error) {
+ ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
+ defer cancel()
+
+ result, err := m.RedisClient.Info(ctx, "memory").Result()
+ if err != nil {
+ logrus.Error("🛑 error GetRedisMemoryUsage: ", err)
+ return nil, errors.New("not_found")
+ }
+
+ lines := strings.Split(result, "\n")
+ info := &RedisMemoryInfo{}
+ v := reflect.ValueOf(info).Elem()
+
+ for _, line := range lines {
+ parts := strings.Split(line, ":")
+ if len(parts) != 2 {
+ logrus.Error("🛑 error GetRedisMemoryUsage: invalid line")
+ continue
+ }
+
+ fieldName := strings.ReplaceAll(parts[0], "-", "")
+ field := v.FieldByName(fieldName)
+ if field.IsValid() && field.CanSet() && field.Kind() == reflect.String {
+ field.SetString(parts[1])
+ }
+ }
+
+ return info, nil
+}
diff --git a/core/lib/internally/redis/request_quota.go b/core/lib/internally/redis/request_quota.go
new file mode 100644
index 0000000..a429816
--- /dev/null
+++ b/core/lib/internally/redis/request_quota.go
@@ -0,0 +1,109 @@
+package redismodule
+
+import (
+ "context"
+ "fmt"
+ "github.com/redis/go-redis/v9"
+ "github.com/sirupsen/logrus"
+ "time"
+)
+
+// Параметры Leaky Bucket из документации Bitrix24
+// Non-enterprise: X=50, Y=2/sec
+// Enterprise: X=250, Y=5/sec
+const (
+ QuotaLimitDefault = int64(50) // порог до блокировки (X)
+ QuotaDecreaseDefault = int64(2) // декремент в секунду (Y)
+ QuotaLimitEnterprise = int64(250)
+ QuotaDecreaseEnterprise = int64(5)
+)
+
+// QuotaKey — ключ счётчика в Redis для конкретного портала
+func QuotaKey(portalID string) string {
+ return fmt.Sprintf("bitrix_quota:%s", portalID)
+}
+
+// GetQuotaCounter возвращает текущее значение счётчика квоты
+func (m *ModuleRedis) GetQuotaCounter(ctx context.Context, portalID string) (int64, error) {
+ val, err := m.RedisClient.Get(ctx, QuotaKey(portalID)).Int64()
+ if err == redis.Nil {
+ return 0, nil // ключа нет — счётчик нулевой
+ }
+ return val, err
+}
+
+// GetFreeQuota возвращает сколько запросов ещё можно отправить до блокировки
+func (m *ModuleRedis) GetFreeQuota(ctx context.Context, portalID string, limit int64) (int64, error) {
+ counter, err := m.GetQuotaCounter(ctx, portalID)
+ if err != nil {
+ return 0, err
+ }
+ free := limit - counter
+ if free < 0 {
+ free = 0
+ }
+ return free, nil
+}
+
+// TryAcquireQuota атомарно проверяет и инкрементит счётчик.
+// Возвращает true если запрос разрешён, false если квота исчерпана.
+func (m *ModuleRedis) TryAcquireQuota(ctx context.Context, portalID string, limit int64) (bool, error) {
+ key := QuotaKey(portalID)
+
+ // Lua-скрипт: атомарно читаем, сравниваем и инкрементим
+ // Возвращает новое значение счётчика или -1 если квота исчерпана
+ script := redis.NewScript(`
+ local current = redis.call('GET', KEYS[1])
+ if current == false then current = 0 else current = tonumber(current) end
+ if current >= tonumber(ARGV[1]) then
+ return -1
+ end
+ local new = redis.call('INCR', KEYS[1])
+ -- TTL 60 секунд — страховка от зависшего счётчика
+ redis.call('EXPIRE', KEYS[1], 60)
+ return new
+ `)
+
+ result, err := script.Run(ctx, m.RedisClient, []string{key}, limit).Int64()
+ if err != nil {
+ return false, err
+ }
+ return result != -1, nil
+}
+
+// DecrementQuota уменьшает счётчик на delta (вызывается background-job каждую секунду)
+func (m *ModuleRedis) DecrementQuota(ctx context.Context, portalID string, delta int64) error {
+ key := QuotaKey(portalID)
+
+ script := redis.NewScript(`
+ local current = redis.call('GET', KEYS[1])
+ if current == false then return 0 end
+ local new = tonumber(current) - tonumber(ARGV[1])
+ if new <= 0 then
+ redis.call('DEL', KEYS[1])
+ return 0
+ end
+ redis.call('SET', KEYS[1], new)
+ return new
+ `)
+
+ return script.Run(ctx, m.RedisClient, []string{key}, delta).Err()
+}
+
+// StartQuotaLeaker запускает background-job который освобождает квоту
+// согласно алгоритму Leaky Bucket из документации Bitrix24.
+// Вызывать один раз при старте сервера в горутине.
+func (m *ModuleRedis) StartQuotaLeaker(portalID string, decreasePerSec int64) {
+ ticker := time.NewTicker(1 * time.Second)
+ defer ticker.Stop()
+
+ logrus.Infof("🪣 QuotaLeaker started for portal %s (-%d/sec)", portalID, decreasePerSec)
+
+ for range ticker.C {
+ ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
+ if err := m.DecrementQuota(ctx, portalID, decreasePerSec); err != nil {
+ logrus.Errorf("🛑 QuotaLeaker: DecrementQuota: %v", err)
+ }
+ cancel()
+ }
+}
diff --git a/core/lib/internally/redis/types.go b/core/lib/internally/redis/types.go
new file mode 100644
index 0000000..1e22cf1
--- /dev/null
+++ b/core/lib/internally/redis/types.go
@@ -0,0 +1,36 @@
+package redismodule
+
+type RedisConfig struct {
+ Host string
+ Port string
+ User string
+ Password string
+ ConnectURI string
+}
+
+type RedisMemoryInfo struct {
+ UsedMemory string // Общее количество байтов, выделенных Redis
+ UsedMemoryHuman string // Человеко-читаемое представление UsedMemory
+ UsedMemoryRss string // Количество памяти, которое Redis занимает в оперативной памяти
+ UsedMemoryRssHuman string // Человеко-читаемое представление UsedMemoryRss
+ UsedMemoryPeak string // Максимальное количество памяти, использованное Redis
+ UsedMemoryPeakHuman string // Человеко-читаемое представление UsedMemoryPeak
+ UsedMemoryPeakPerc string // Процент пикового использования памяти от текущего использования
+ UsedMemoryOverhead string // Общее количество памяти, используемое для внутренних механизмов Redis
+ UsedMemoryStartup string // Количество памяти, использованное Redis при запуске
+ UsedMemoryDataset string // Общее количество памяти, используемое для хранения данных
+ UsedMemoryDatasetPerc string // Процент использования памяти, занимаемый данными
+ AllocatorAllocated string // Общее количество памяти, выделенное аллокатором
+ AllocatorActive string // Общее количество памяти, выделенное и активно используемое аллокатором
+ AllocatorResident string // Общее количество памяти, выделенное аллокатором и занимаемое в оперативной памяти
+ TotalSystemMemory string // Общее количество оперативной памяти в системе
+ TotalSystemMemoryHuman string // Человеко-читаемое представление TotalSystemMemory
+ UsedMemoryLua string // Общее количество памяти, используемое движком Lua в Redis
+ UsedMemoryLuaHuman string // Человеко-читаемое представление UsedMemoryLua
+ Maxmemory string // Максимальное количество памяти, которое Redis может использовать
+ MaxmemoryHuman string // Человеко-читаемое представление Maxmemory
+ MaxmemoryPolicy string // Политика, которую Redis будет следовать при достижении Maxmemory
+ MemFragmentationRatio string // Отношение памяти RSS к памяти, выделенной аллокатором
+ MemFragmentationBytes string // Разница между памятью RSS и памятью, выделенной аллокатором
+ MemAllocator string // Аллокатор, используемый Redis (jemalloc или glibc)
+}
diff --git a/core/typescore/approval.go b/core/typescore/approval.go
new file mode 100644
index 0000000..10dc47d
--- /dev/null
+++ b/core/typescore/approval.go
@@ -0,0 +1,27 @@
+package typescore
+
+import "time"
+
+// Approval — заявка на согласование.
+// Status: draft | pending | approved | rejected | revoked
+// DepartmentID копируется с инициатора в момент создания — для отчётов и изоляции без JOIN.
+// FileBase64 и FileName заполняются только если ApprovalTopic.AllowsFile = true.
+type Approval struct {
+ ID *uint64 `gorm:"column:id;index;type:bigint;autoIncrement;not null;unique" ignore_update_db:"true" json:"id" db:"id" mapstructure:"id"`
+ InitiatorID *uint64 `gorm:"type:bigint;not null;index;column:initiator_id" json:"initiator_id" db:"initiator_id" mapstructure:"initiator_id"`
+ TopicID *uint64 `gorm:"type:bigint;not null;index;column:topic_id" json:"topic_id" db:"topic_id" mapstructure:"topic_id"`
+ DepartmentID *uint64 `gorm:"type:bigint;not null;index;column:department_id" json:"department_id" db:"department_id" mapstructure:"department_id"` // снимок отдела на момент создания
+ Content *string `gorm:"type:text;not null;column:content" json:"content" db:"content" mapstructure:"content"` // введённые пользователем данные по шаблону
+ Status *string `gorm:"type:text;not null;default:'pending';index;column:status" json:"status" db:"status" mapstructure:"status"`
+ RevokedByID *uint64 `gorm:"type:bigint;index;column:revoked_by_id" json:"revoked_by_id,omitempty" db:"revoked_by_id" mapstructure:"revoked_by_id"`
+ RevokedAt *time.Time `gorm:"type:timestamp;column:revoked_at" json:"revoked_at,omitempty" db:"revoked_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"`
+
+ Files []*ApprovalFile `gorm:"-" json:"files,omitempty"`
+ Initiator *User `gorm:"-" json:"initiator,omitempty"`
+ Topic *ApprovalTopic `gorm:"-" json:"topic,omitempty"`
+ Department *Department `gorm:"-" json:"department,omitempty"`
+ RevokedBy *User `gorm:"-" json:"revoked_by,omitempty"`
+ Steps []*ApprovalStep `gorm:"-" json:"steps,omitempty"`
+}
diff --git a/core/typescore/approval_additional_approver.go b/core/typescore/approval_additional_approver.go
new file mode 100644
index 0000000..2194d19
--- /dev/null
+++ b/core/typescore/approval_additional_approver.go
@@ -0,0 +1,19 @@
+package typescore
+
+import "time"
+
+type ApprovalAdditionalApprover struct {
+ ID *uint64 `gorm:"column:id;index;type:bigint;autoIncrement;not null;unique" json:"id" db:"id"`
+ ApprovalID *uint64 `gorm:"type:bigint;not null;index;column:approval_id" json:"approval_id" db:"approval_id"`
+ ApproverID *uint64 `gorm:"type:bigint;not null;index;column:approver_id" json:"approver_id" db:"approver_id"`
+ AddedByID *uint64 `gorm:"type:bigint;not null;column:added_by_id" json:"added_by_id" db:"added_by_id"`
+ Status *string `gorm:"type:text;not null;default:'pending';column:status" json:"status" db:"status"`
+ Comment *string `gorm:"type:text;column:comment" json:"comment,omitempty" db:"comment"`
+ ActedAt *time.Time `gorm:"type:timestamp;column:acted_at" json:"acted_at,omitempty" db:"acted_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"`
+
+ Approval *Approval `gorm:"-" json:"approval,omitempty"`
+ Approver *User `gorm:"-" json:"approver,omitempty"`
+ AddedBy *User `gorm:"-" json:"added_by,omitempty"`
+}
diff --git a/core/typescore/approval_delegation.go b/core/typescore/approval_delegation.go
new file mode 100644
index 0000000..03e9aae
--- /dev/null
+++ b/core/typescore/approval_delegation.go
@@ -0,0 +1,22 @@
+package typescore
+
+import "time"
+
+type ApprovalDelegation struct {
+ ID *uint64 `gorm:"column:id;index;type:bigint;autoIncrement;not null;unique" json:"id" db:"id"`
+ DelegatorID *uint64 `gorm:"type:bigint;not null;index;column:delegator_id" json:"delegator_id" db:"delegator_id"`
+ DelegateID *uint64 `gorm:"type:bigint;not null;index;column:delegate_id" json:"delegate_id" db:"delegate_id"`
+ CategoryID *uint64 `gorm:"type:bigint;index;column:category_id" json:"category_id,omitempty" db:"category_id"`
+ TopicID *uint64 `gorm:"type:bigint;index;column:topic_id" json:"topic_id,omitempty" db:"topic_id"`
+ ValidUntil *time.Time `gorm:"type:timestamp;not null;column:valid_until" json:"valid_until" db:"valid_until"`
+ IsActive *bool `gorm:"type:boolean;not null;default:true;column:is_active" json:"is_active" db:"is_active"`
+ NotifiedDay *bool `gorm:"type:boolean;not null;default:false;column:notified_day" json:"notified_day" db:"notified_day"`
+ Notified2h *bool `gorm:"type:boolean;not null;default:false;column:notified_2h" json:"notified_2h" db:"notified_2h"`
+ 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"`
+
+ Delegator *User `gorm:"-" json:"delegator,omitempty"`
+ Delegate *User `gorm:"-" json:"delegate,omitempty"`
+ Category *ApprovalTopicCategory `gorm:"-" json:"category,omitempty"`
+ Topic *ApprovalTopic `gorm:"-" json:"topic,omitempty"`
+}
diff --git a/core/typescore/approval_file.go b/core/typescore/approval_file.go
new file mode 100644
index 0000000..bc79ea2
--- /dev/null
+++ b/core/typescore/approval_file.go
@@ -0,0 +1,11 @@
+package typescore
+
+import "time"
+
+type ApprovalFile struct {
+ ID *uint64 `gorm:"column:id;autoIncrement;not null;unique" json:"id" db:"id"`
+ ApprovalID *uint64 `gorm:"type:bigint;not null;index;column:approval_id" json:"approval_id" db:"approval_id"`
+ FileBase64 *string `gorm:"type:text;not null;column:file_base64" json:"file_base64" db:"file_base64"`
+ FileName *string `gorm:"type:text;not null;column:file_name" json:"file_name" db:"file_name"`
+ CreatedAt *time.Time `gorm:"default:CURRENT_TIMESTAMP;column:created_at" json:"created_at" db:"created_at"`
+}
diff --git a/core/typescore/approval_step.go b/core/typescore/approval_step.go
new file mode 100644
index 0000000..3dfaefc
--- /dev/null
+++ b/core/typescore/approval_step.go
@@ -0,0 +1,26 @@
+package typescore
+
+import "time"
+
+// ApprovalStep — один шаг согласования.
+// Status: pending | approved | rejected
+// Comment заполняется согласующим при отклонении (может быть пустым).
+// StepOrder определяет порядок (1 = первый согласующий).
+// ApproverNameSnapshot и ApproverDepartmentSnapshot — снимок данных согласующего
+// на момент действия, чтобы отчёты не ломались при изменении оргструктуры.
+type ApprovalStep struct {
+ ID *uint64 `gorm:"column:id;index;type:bigint;autoIncrement;not null;unique" ignore_update_db:"true" json:"id" db:"id" mapstructure:"id"`
+ ApprovalID *uint64 `gorm:"type:bigint;not null;index;column:approval_id" json:"approval_id" db:"approval_id" mapstructure:"approval_id"`
+ ApproverID *uint64 `gorm:"type:bigint;not null;index;column:approver_id" json:"approver_id" db:"approver_id" mapstructure:"approver_id"`
+ StepOrder *int `gorm:"type:int;not null;column:step_order" json:"step_order" db:"step_order" mapstructure:"step_order"`
+ Status *string `gorm:"type:text;not null;default:'pending';index;column:status" json:"status" db:"status" mapstructure:"status"`
+ Comment *string `gorm:"type:text;column:comment" json:"comment,omitempty" db:"comment" mapstructure:"comment"`
+ ApproverNameSnapshot *string `gorm:"type:text;column:approver_name_snapshot" json:"approver_name_snapshot,omitempty" db:"approver_name_snapshot" mapstructure:"approver_name_snapshot"`
+ ApproverDepartmentSnapshot *string `gorm:"type:text;column:approver_department_snapshot" json:"approver_department_snapshot,omitempty" db:"approver_department_snapshot" mapstructure:"approver_department_snapshot"`
+ ActedAt *time.Time `gorm:"type:timestamp;column:acted_at" json:"acted_at,omitempty" db:"acted_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"`
+
+ Approval *Approval `gorm:"-" json:"approval,omitempty"`
+ Approver *User `gorm:"-" json:"approver,omitempty"`
+}
diff --git a/core/typescore/approval_task.go b/core/typescore/approval_task.go
new file mode 100644
index 0000000..d8ae972
--- /dev/null
+++ b/core/typescore/approval_task.go
@@ -0,0 +1,17 @@
+package typescore
+
+import "time"
+
+type ApprovalTask struct {
+ ID *uint64 `gorm:"column:id;index;type:bigint;autoIncrement;not null;unique" json:"id" db:"id"`
+ ApprovalID *uint64 `gorm:"type:bigint;not null;index;column:approval_id" json:"approval_id" db:"approval_id"`
+ ExecutorID *uint64 `gorm:"type:bigint;not null;index;column:executor_id" json:"executor_id" db:"executor_id"`
+ TaskText *string `gorm:"type:text;not null;column:task_text" json:"task_text" db:"task_text"`
+ Status *string `gorm:"type:text;not null;default:'pending';column:status" json:"status" db:"status"`
+ CompletedAt *time.Time `gorm:"type:timestamp;column:completed_at" json:"completed_at,omitempty" db:"completed_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"`
+
+ Approval *Approval `gorm:"-" json:"approval,omitempty"`
+ Executor *User `gorm:"-" json:"executor,omitempty"`
+}
diff --git a/core/typescore/approval_topic.go b/core/typescore/approval_topic.go
new file mode 100644
index 0000000..018c052
--- /dev/null
+++ b/core/typescore/approval_topic.go
@@ -0,0 +1,27 @@
+package typescore
+
+import "time"
+
+// ApprovalTopic — конкретная тема внутри категории.
+// DurationType: single_day | date_range | multi_day
+// TimeType: full_day | partial
+// PaymentType: own_expense | vacation_account | not_applicable (для partial)
+// Template хранит шаблон строки для подсказки пользователю при вводе.
+type ApprovalTopic struct {
+ ID *uint64 `gorm:"column:id;index;type:bigserial;autoIncrement;not null;unique" ignore_update_db:"true" json:"id" db:"id" mapstructure:"id"`
+ CategoryID *uint64 `gorm:"type:bigint;not null;index;column:category_id" json:"category_id" db:"category_id" mapstructure:"category_id"`
+ Name *string `gorm:"type:text;not null;column:name" json:"name" db:"name" mapstructure:"name"`
+ Code *string `gorm:"type:text;not null;unique;column:code" json:"code" db:"code" mapstructure:"code"`
+ DurationType *string `gorm:"type:text;column:duration_type" json:"duration_type,omitempty" db:"duration_type" mapstructure:"duration_type"`
+ TimeType *string `gorm:"type:text;column:time_type" json:"time_type,omitempty" db:"time_type" mapstructure:"time_type"`
+ PaymentType *string `gorm:"type:text;column:payment_type" json:"payment_type,omitempty" db:"payment_type" mapstructure:"payment_type"`
+ Template *string `gorm:"type:text;not null;column:template" json:"template" db:"template" mapstructure:"template"`
+ TaskTemplate *string `gorm:"type:text;column:task_template" json:"task_template,omitempty" db:"task_template" mapstructure:"task_template"`
+ AllowsFile *bool `gorm:"type:boolean;not null;default:false;column:allows_file" json:"allows_file" db:"allows_file" mapstructure:"allows_file"`
+ AllowApproverSelection *bool `gorm:"type:boolean;not null;default:false;column:allow_approver_selection" json:"allow_approver_selection" db:"allow_approver_selection" mapstructure:"allow_approver_selection"`
+ IsActive *bool `gorm:"type:boolean;not null;default:true;column:is_active" json:"is_active" db:"is_active" mapstructure:"is_active"`
+ CreatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:created_at" json:"created_at" db:"created_at"`
+ UpdatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:updated_at" json:"updated_at" db:"updated_at"`
+
+ Category *ApprovalTopicCategory `gorm:"-" json:"category,omitempty"`
+}
diff --git a/core/typescore/approval_topic_category.go b/core/typescore/approval_topic_category.go
new file mode 100644
index 0000000..735d5c3
--- /dev/null
+++ b/core/typescore/approval_topic_category.go
@@ -0,0 +1,15 @@
+package typescore
+
+import "time"
+
+type ApprovalTopicCategory struct {
+ ID *uint64 `gorm:"column:id;index;type:bigint;autoIncrement;not null;unique" ignore_update_db:"true" json:"id" db:"id" mapstructure:"id"`
+ Name *string `gorm:"type:text;not null;column:name" json:"name" db:"name" mapstructure:"name"`
+ Code *string `gorm:"type:text;not null;unique;column:code" json:"code" db:"code" mapstructure:"code"` // otgul, vacation, sick_leave
+ Description *string `gorm:"type:text;column:description" json:"description,omitempty" db:"description" mapstructure:"description"`
+ IsActive *bool `gorm:"type:boolean;not null;default:true;column:is_active" json:"is_active" db:"is_active" mapstructure:"is_active"`
+ CreatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:created_at" json:"created_at" db:"created_at"`
+ UpdatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:updated_at" json:"updated_at" db:"updated_at"`
+
+ Topics []*ApprovalTopic `gorm:"-" json:"topics,omitempty"`
+}
diff --git a/core/typescore/balancer.go b/core/typescore/balancer.go
new file mode 100644
index 0000000..37c2f21
--- /dev/null
+++ b/core/typescore/balancer.go
@@ -0,0 +1,36 @@
+package typescore
+
+// BalancerRequest — тело запроса на /api/balancer/send
+type BalancerRequest struct {
+ URL *string `json:"url"` // URL метода Bitrix24
+ Method *string `json:"method"` // HTTP метод (GET, POST)
+ Headers map[string]string `json:"headers,omitempty"` // Заголовки для Bitrix24
+ Body map[string]interface{} `json:"body,omitempty"` // Тело запроса
+
+ // IsRecurrent — если true, бэк автоматически загружает ВСЕ записи
+ // постранично (по 50 за запрос) и возвращает одним массивом.
+ // Nil/false = обычный разовый запрос.
+ IsRecurrent bool `json:"is_recurrent,omitempty"`
+
+ // ResultKey — ключ внутри result где лежит массив.
+ // "tasks" для tasks.task.list, пусто для crm.lead.list и др.
+ ResultKey *string `json:"result_key,omitempty"`
+}
+
+// BalancerResponse — ответ от Bitrix24 проксированный клиенту
+type BalancerResponse struct {
+ StatusCode *int `json:"status_code"`
+ Body interface{} `json:"body"`
+ QuotaLeft *int64 `json:"quota_left"`
+ IsRecurrent bool `json:"is_recurrent,omitempty"`
+ TotalFetched *int `json:"total_fetched,omitempty"`
+}
+
+// QuotaResponse — ответ на /api/balancer/quota
+type QuotaResponse struct {
+ PortalID *string `json:"portal_id"`
+ Counter *int64 `json:"counter"` // текущий счётчик
+ Limit *int64 `json:"limit"` // порог блокировки (X)
+ FreeSlots *int64 `json:"free_slots"` // доступные слоты
+ DecreasePerSec *int64 `json:"decrease_per_sec"` // скорость освобождения (Y)
+}
diff --git a/core/typescore/base_db.go b/core/typescore/base_db.go
new file mode 100644
index 0000000..34e249d
--- /dev/null
+++ b/core/typescore/base_db.go
@@ -0,0 +1,22 @@
+package typescore
+
+import "time"
+
+// объединяет общие параметры запроса.
+type ListDbOptions struct {
+ Filtering interface{}
+ LikeFields map[string]string
+ Offset *uint64
+ Limit *uint64
+ FromDate *time.Time
+ ToDate *time.Time
+ NotNullFields map[string]bool // поля, не нулевые(при запросе ставит where на эти поля not null) bool-true для числовых полей
+ SortingParams map[string]string // поля, по которым сортируется
+ SortBy string // поля, по которым сортируется
+}
+
+type InsertOptions struct {
+ Prefix string // Префикс для запроса (например, WITH)
+ Suffix string // Суффикс для запроса (например, ON CONFLICT, RETURNING)
+ IgnoreConflict bool // Флаг игнорирования конфликтов
+}
diff --git a/core/typescore/department.go b/core/typescore/department.go
new file mode 100644
index 0000000..b05c930
--- /dev/null
+++ b/core/typescore/department.go
@@ -0,0 +1,13 @@
+package typescore
+
+import "time"
+
+type Department struct {
+ ID *uint64 `gorm:"column:id;index;type:bigint;autoIncrement;not null;unique" ignore_update_db:"true" json:"id" db:"id" mapstructure:"id"`
+ Name *string `gorm:"type:text;not null;column:name" json:"name" db:"name" mapstructure:"name"`
+ Code *string `gorm:"type:text;not null;unique;column:code" json:"code" db:"code" mapstructure:"code"` // finance, hr, it
+ Description *string `gorm:"type:text;column:description" json:"description,omitempty" db:"description" mapstructure:"description"`
+ IsActive *bool `gorm:"type:boolean;not null;default:true;column:is_active" json:"is_active" db:"is_active" mapstructure:"is_active"`
+ CreatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:created_at" json:"created_at" db:"created_at"`
+ UpdatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:updated_at" json:"updated_at" db:"updated_at"`
+}
diff --git a/core/typescore/handler.go b/core/typescore/handler.go
new file mode 100644
index 0000000..17334a3
--- /dev/null
+++ b/core/typescore/handler.go
@@ -0,0 +1,9 @@
+package typescore
+
+type Response struct {
+ Success bool `json:"success"`
+ Data interface{} `json:"data,omitempty"`
+ Error error `json:"error,omitempty"`
+ Count int `json:"count,omitempty"`
+ TotalCount *uint64 `json:"total_count,omitempty"`
+}
diff --git a/core/typescore/permission.go b/core/typescore/permission.go
new file mode 100644
index 0000000..ed8cf09
--- /dev/null
+++ b/core/typescore/permission.go
@@ -0,0 +1,21 @@
+package typescore
+
+import "time"
+
+// Permission — право роли на действие в рамках категории или конкретной темы.
+// Action: create | read | update | delete | approve | revoke
+// Если TopicCategoryID заполнен, а TopicID = nil — право на все темы категории.
+// Если TopicID заполнен — право только на конкретную тему.
+type Permission struct {
+ ID *uint64 `gorm:"column:id;index;type:bigint;autoIncrement;not null;unique" ignore_update_db:"true" json:"id" db:"id" mapstructure:"id"`
+ RoleID *uint64 `gorm:"type:bigint;not null;index;column:role_id" json:"role_id" db:"role_id" mapstructure:"role_id"`
+ TopicCategoryID *uint64 `gorm:"type:bigint;index;column:topic_category_id" json:"topic_category_id,omitempty" db:"topic_category_id" mapstructure:"topic_category_id"`
+ TopicID *uint64 `gorm:"type:bigint;index;column:topic_id" json:"topic_id,omitempty" db:"topic_id" mapstructure:"topic_id"`
+ Action *string `gorm:"type:text;not null;column:action" json:"action" db:"action" mapstructure:"action"`
+ 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"`
+
+ Role *Role `gorm:"-" json:"role,omitempty"`
+ TopicCategory *ApprovalTopicCategory `gorm:"-" json:"topic_category,omitempty"`
+ Topic *ApprovalTopic `gorm:"-" json:"topic,omitempty"`
+}
diff --git a/core/typescore/report.go b/core/typescore/report.go
new file mode 100644
index 0000000..bc61490
--- /dev/null
+++ b/core/typescore/report.go
@@ -0,0 +1,20 @@
+package typescore
+
+import "time"
+
+// ReportFilter — фильтр для выгрузки отчёта по согласованиям
+type ReportFilter struct {
+ AllAccess bool // true для директора (видит всё)
+ UserID *uint64 // ID пользователя для фильтрации по ролям
+ CategoryCodes []string // DEPRECATED: теперь не используется, роли определяются через UserID
+ DateFrom *time.Time // начало периода
+ DateTo *time.Time // конец периода
+}
+
+// TaskReportFilter — фильтр для выгрузки отчёта по задачам
+type TaskReportFilter struct {
+ AllAccess bool // true для директора (видит всё)
+ UserID *uint64 // ID пользователя для фильтрации по ролям
+ DateFrom *time.Time // начало периода
+ DateTo *time.Time // конец периода
+}
diff --git a/core/typescore/role.go b/core/typescore/role.go
new file mode 100644
index 0000000..a9445d6
--- /dev/null
+++ b/core/typescore/role.go
@@ -0,0 +1,19 @@
+package typescore
+
+import "time"
+
+type Role struct {
+ ID *uint64 `gorm:"column:id;index;type:bigint;autoIncrement;not null;unique" ignore_update_db:"true" json:"id" db:"id" mapstructure:"id"`
+ Name *string `gorm:"type:text;not null;column:name" json:"name" db:"name" mapstructure:"name"`
+ Code *string `gorm:"type:text;not null;unique;column:code" json:"code" db:"code" mapstructure:"code"`
+ IsDefault *bool `gorm:"type:boolean;not null;default:false;column:is_default" json:"is_default" db:"is_default" mapstructure:"is_default"`
+ IsDirector *bool `gorm:"type:boolean;not null;default:false;column:is_director" json:"is_director" db:"is_director" mapstructure:"is_director"`
+ IsApprover *bool `gorm:"type:boolean;not null;default:false;column:is_approver" json:"is_approver" db:"is_approver" mapstructure:"is_approver"`
+ IsObserver *bool `gorm:"type:boolean;not null;default:false;column:is_observer" json:"is_observer" db:"is_observer" mapstructure:"is_observer"`
+ IsExecutor *bool `gorm:"type:boolean;not null;default:false;column:is_executor" json:"is_executor" db:"is_executor" mapstructure:"is_executor"`
+ Description *string `gorm:"type:text;column:description" json:"description,omitempty" db:"description" mapstructure:"description"`
+ 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"`
+
+ Permissions []*Permission `gorm:"-" json:"permissions,omitempty"`
+}
diff --git a/core/typescore/user.go b/core/typescore/user.go
new file mode 100644
index 0000000..386876b
--- /dev/null
+++ b/core/typescore/user.go
@@ -0,0 +1,24 @@
+package typescore
+
+import "time"
+
+type User struct {
+ ID *uint64 `gorm:"column:id;index;type:bigserial;autoIncrement;not null;unique" ignore_update_db:"true" json:"id" db:"id" mapstructure:"id"`
+ TelegramID *int64 `gorm:"type:numeric;not null;unique;column:telegram_id" json:"telegram_id" db:"telegram_id" mapstructure:"telegram_id"`
+ Username *string `gorm:"type:text;column:username" json:"username,omitempty" db:"username" mapstructure:"username"`
+ FullName *string `gorm:"type:text;not null;column:full_name" json:"full_name" db:"full_name" mapstructure:"full_name"`
+ //FirstName *string `gorm:"type:text;not null;column:first_name" json:"first_name" db:"first_name" mapstructure:"first_name"`
+ //LastName *string `gorm:"type:text;not null;column:last_name" json:"last_name" db:"last_name" mapstructure:"last_name"`
+ //Patronymic *string `gorm:"type:text;column:patronymic" json:"patronymic,omitempty" db:"patronymic" mapstructure:"patronymic"`
+ LanguageCode *string `gorm:"type:text;not null;default:'ru';column:language_code" json:"language_code" db:"language_code" mapstructure:"language_code"`
+ DepartmentID *uint64 `gorm:"type:bigint;index;column:department_id" json:"department_id,omitempty" db:"department_id" mapstructure:"department_id"`
+ IsBlocked *bool `gorm:"type:boolean;not null;default:false;index;column:is_blocked" json:"is_blocked" db:"is_blocked" mapstructure:"is_blocked"`
+ IsFired *bool `gorm:"type:boolean;not null;default:false;index;column:is_fired" json:"is_fired" db:"is_fired" mapstructure:"is_fired"`
+ BlockedAt *time.Time `gorm:"type:timestamp;column:blocked_at" json:"blocked_at,omitempty" db:"blocked_at"`
+ LastLogin *time.Time `gorm:"type:timestamp;column:last_login" json:"last_login,omitempty" db:"last_login"`
+ 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"`
+
+ Department *Department `gorm:"-" json:"department,omitempty"`
+ UserRoles []*UserRole `gorm:"-" json:"user_roles,omitempty"`
+}
diff --git a/core/typescore/user_auth.go b/core/typescore/user_auth.go
new file mode 100644
index 0000000..640baf5
--- /dev/null
+++ b/core/typescore/user_auth.go
@@ -0,0 +1,12 @@
+package typescore
+
+import "time"
+
+type UserAuth struct {
+ ID *uint64 `gorm:"column:id;index;type:bigint;autoIncrement;not null;unique" ignore_update_db:"true" json:"id" db:"id" mapstructure:"id"`
+ UserID *uint64 `gorm:"type:bigint;not null;index;column:user_id" json:"user_id" db:"user_id" mapstructure:"user_id"`
+ PasswordHash *string `gorm:"type:text;not null;column:password_hash" json:"password_hash" db:"password_hash"`
+ Salt *string `gorm:"type:text;not null;column:salt" json:"-" db:"salt"`
+ CreatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:created_at" json:"created_at" db:"created_at"`
+ UpdatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:updated_at" json:"updated_at" db:"updated_at"`
+}
diff --git a/core/typescore/user_hierarchy.go b/core/typescore/user_hierarchy.go
new file mode 100644
index 0000000..4aeea13
--- /dev/null
+++ b/core/typescore/user_hierarchy.go
@@ -0,0 +1,24 @@
+package typescore
+
+import "time"
+
+// UserHierarchy — связь подчинённого и его согласующего.
+// Согласующий может быть привязан к нескольким отделам через разные записи.
+// Priority определяет порядок шагов согласования (1 = первый).
+type UserHierarchy struct {
+ ID *uint64 `gorm:"column:id;index;type:bigint;autoIncrement;not null;unique" ignore_update_db:"true" json:"id" db:"id" mapstructure:"id"`
+ SubordinateID *uint64 `gorm:"type:bigint;not null;index;column:subordinate_id" json:"subordinate_id" db:"subordinate_id" mapstructure:"subordinate_id"`
+ ApproverID *uint64 `gorm:"type:bigint;not null;index;column:approver_id" json:"approver_id" db:"approver_id" mapstructure:"approver_id"`
+ ExecutorID *uint64 `gorm:"type:bigint;index;column:executor_id" json:"executor_id,omitempty" db:"executor_id" mapstructure:"executor_id"`
+ DepartmentID *uint64 `gorm:"type:bigint;not null;index;column:department_id" json:"department_id" db:"department_id" mapstructure:"department_id"`
+ TopicCategoryID *uint64 `gorm:"type:bigint;index;column:topic_category_id" json:"topic_category_id,omitempty" db:"topic_category_id" mapstructure:"topic_category_id"`
+ TopicID *uint64 `gorm:"type:bigint;index;column:topic_id" json:"topic_id,omitempty" db:"topic_id" mapstructure:"topic_id"`
+ Priority *int `gorm:"type:int;not null;default:1;column:priority" json:"priority" db:"priority" mapstructure:"priority"`
+ 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"`
+
+ Subordinate *User `gorm:"-" json:"subordinate,omitempty"`
+ Approver *User `gorm:"-" json:"approver,omitempty"`
+ Executor *User `gorm:"-" json:"executor,omitempty"`
+ Department *Department `gorm:"-" json:"department,omitempty"`
+}
diff --git a/core/typescore/user_role.go b/core/typescore/user_role.go
new file mode 100644
index 0000000..5058fae
--- /dev/null
+++ b/core/typescore/user_role.go
@@ -0,0 +1,16 @@
+package typescore
+
+import "time"
+
+// UserRole — связь пользователя с ролью.
+// Один пользователь может иметь несколько ролей (например, сотрудник и согласующий одновременно).
+type UserRole struct {
+ ID *uint64 `gorm:"column:id;index;type:bigint;autoIncrement;not null;unique" ignore_update_db:"true" json:"id" db:"id" mapstructure:"id"` // Автоматически заполняемое уникальное поле для большого числа записей
+ UserID *uint64 `gorm:"type:bigint;not null;index;column:user_id" json:"user_id" db:"user_id" mapstructure:"user_id"`
+ RoleID *uint64 `gorm:"type:bigint;not null;index;column:role_id" json:"role_id" db:"role_id" mapstructure:"role_id"`
+ 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"`
+
+ User *User `gorm:"-" json:"user,omitempty"` // ← добавить gorm:"-"
+ Role *Role `gorm:"-" json:"role,omitempty"` // ← добавить gorm:"-"
+}
diff --git a/core/utilscore/conversion.go b/core/utilscore/conversion.go
new file mode 100644
index 0000000..3d14c64
--- /dev/null
+++ b/core/utilscore/conversion.go
@@ -0,0 +1,58 @@
+package utilscore
+
+import (
+ "time"
+
+ "github.com/shopspring/decimal"
+)
+
+func PointerToBool(b bool) *bool {
+ return &b
+}
+
+func PointerToUint32(i uint32) *uint32 {
+ return &i
+}
+
+func PointerToDecimal(i decimal.Decimal) *decimal.Decimal {
+ return &i
+}
+
+func PointerToUint64(i uint64) *uint64 {
+ return &i
+}
+
+func PointerToString(s string) *string {
+ return &s
+}
+
+func PointerToFloat64(f float64) *float64 {
+ return &f
+}
+
+func PointerToFloat32(f float32) *float32 {
+ return &f
+}
+
+func PointerToInt(i int) *int {
+ return &i
+}
+func PointerToTime(t time.Time) *time.Time {
+ return &t
+}
+
+func PointerToInt64(i int64) *int64 {
+ return &i
+}
+
+func PointerToInt32(i int32) *int32 {
+ return &i
+}
+
+// GetStringValue получает значение из указателя на строку
+func GetStringValue(ptr *string) string {
+ if ptr == nil {
+ return ""
+ }
+ return *ptr
+}
diff --git a/core/utilscore/db/db.go b/core/utilscore/db/db.go
new file mode 100644
index 0000000..6d42aab
--- /dev/null
+++ b/core/utilscore/db/db.go
@@ -0,0 +1,174 @@
+package dbutils
+
+import (
+ "bitrix_balancer_api/core/typescore"
+ "errors"
+ "fmt"
+ "reflect"
+ "sync"
+
+ "github.com/Masterminds/squirrel"
+ "github.com/sirupsen/logrus"
+)
+
+var (
+ fieldsCache sync.Map // Используем sync.Map для кэширования
+)
+
+type cacheKey struct {
+ typ reflect.Type
+ dbName string
+}
+
+// GetOptionsDB обобщённая функция для разбора опций.
+// Если Filtering не передан, создаётся новый объект типа T.
+// Если передан, то выполняется проверка соответствия типу *T.
+func GetOptionsDB[T any](opts ...typescore.ListDbOptions) (typescore.ListDbOptions, *T, error) {
+ var options typescore.ListDbOptions
+ if len(opts) > 0 {
+ options = opts[0]
+ }
+
+ var filter *T
+ if options.Filtering == nil {
+ filter = new(T)
+ } else {
+ var ok bool
+ filter, ok = options.Filtering.(*T)
+ if !ok {
+ return typescore.ListDbOptions{}, nil, errors.New("expected *T")
+ }
+ }
+ return options, filter, nil
+}
+
+func GetStructFieldsDB(processor interface{}, dbName ...string) []string {
+ if processor == nil || reflect.ValueOf(processor).Kind() != reflect.Ptr || reflect.ValueOf(processor).Elem().Kind() != reflect.Struct {
+ logrus.Error("🔴 error GetStructFieldsDB: processor must be a non-nil pointer to a struct")
+ return nil
+ }
+
+ procType := reflect.TypeOf(processor).Elem()
+ nameDB := ""
+ if len(dbName) > 0 {
+ nameDB = dbName[0]
+ }
+ key := cacheKey{
+ typ: procType,
+ dbName: nameDB,
+ }
+
+ if fields, exists := fieldsCache.Load(key); exists {
+ return fields.([]string)
+ }
+
+ val := reflect.ValueOf(processor).Elem()
+
+ var fields []string
+ for i := 0; i < val.NumField(); i++ {
+ typeField := procType.Field(i)
+ dbTag := typeField.Tag.Get("db")
+ if dbTag != "" {
+ if typeField.Tag.Get("ignore_db") == "true" {
+ continue
+ }
+
+ // Добавляем alias, чтобы исключить конфликты при одинаковых именах полей
+ if nameDB != "" {
+ fullField := fmt.Sprintf("%s.%s", nameDB, dbTag)
+ fields = append(fields, fullField)
+ } else {
+ fields = append(fields, dbTag)
+ }
+ }
+ }
+
+ fieldsCache.Store(key, fields)
+ return fields
+}
+
+func AddNonNullFieldsToQueryUpdate(query squirrel.UpdateBuilder, paramsUpdate interface{}) squirrel.UpdateBuilder {
+ v := reflect.ValueOf(paramsUpdate)
+ t := v.Type()
+
+ for i := 0; i < v.NumField(); i++ {
+ field := v.Field(i)
+ if (field.Kind() == reflect.Ptr && !field.IsNil()) || (field.Kind() != reflect.Ptr && !field.IsZero()) {
+ // Проверяем тег ignore_update_db для игнорирования полей при обновлении
+ ignoreUpdateDbTag := t.Field(i).Tag.Get("ignore_update_db")
+ if ignoreUpdateDbTag == "true" {
+ continue
+ }
+ ignoreDbTag := t.Field(i).Tag.Get("ignore_db")
+ if ignoreDbTag == "true" {
+ continue
+ }
+ dbTag := t.Field(i).Tag.Get("db")
+ if dbTag != "system_id" && dbTag != "role" && dbTag != "created_at" {
+ query = query.Set(dbTag, field.Interface())
+ }
+ }
+ }
+
+ return query
+}
+
+// Создаем два списка для хранения названий столбцов и соответствующих значений
+func GenerateInsertRequest(query squirrel.InsertBuilder, processor interface{}, options ...typescore.InsertOptions) (*string, []interface{}, error) {
+ var columns []string
+ var values []interface{}
+ v := reflect.ValueOf(processor).Elem()
+ t := v.Type()
+
+ for i := 0; i < v.NumField(); i++ {
+ field := v.Field(i)
+ ignoreDbTag := t.Field(i).Tag.Get("ignore_db")
+ if ignoreDbTag == "true" {
+ continue
+ }
+ dbTag := t.Field(i).Tag.Get("db")
+ if dbTag == "" {
+ continue
+ }
+ if dbTag == "serial_id" || dbTag == "system_id" {
+ continue
+ }
+
+ if (field.Kind() == reflect.Ptr && !field.IsNil()) || (field.Kind() != reflect.Ptr && !field.IsZero()) {
+ columns = append(columns, dbTag)
+ values = append(values, field.Interface())
+ }
+ }
+
+ if len(columns) == 0 {
+ logrus.Error("🔴 error GenerateInsertRequest: all fields are zero")
+ return nil, nil, errors.New("all fields are zero")
+ }
+
+ // Применяем опции, если они есть
+ if len(options) > 0 {
+ for _, opt := range options {
+ if opt.Prefix != "" {
+ query = query.Prefix(opt.Prefix)
+ }
+ if opt.Suffix != "" {
+ query = query.Suffix(opt.Suffix)
+ } else if opt.IgnoreConflict {
+ query = query.Suffix("ON CONFLICT DO NOTHING")
+ }
+ }
+ }
+
+ query = query.Columns(columns...).Values(values...)
+
+ sql, args, err := query.ToSql()
+ if err != nil {
+ logrus.Error("🔴 error GenerateInsertRequest: ", err)
+ return nil, nil, err
+ }
+ if sql == "" {
+ logrus.Error("🔴 error GenerateInsertRequest: sql is empty")
+ return nil, nil, errors.New("sql is empty")
+ }
+ return &sql, args, nil
+}
diff --git a/core/utilscore/db/db_operations.go b/core/utilscore/db/db_operations.go
new file mode 100644
index 0000000..458cc5b
--- /dev/null
+++ b/core/utilscore/db/db_operations.go
@@ -0,0 +1,16 @@
+package dbutils
+
+import (
+ "github.com/Masterminds/squirrel"
+)
+
+// SetterLimitAndOffsetQuery применяет limit и offset к переданному SelectBuilder, если они не nil.
+func SetterLimitAndOffsetQuery(query squirrel.SelectBuilder, offset *uint64, limit *uint64) squirrel.SelectBuilder {
+ if limit != nil {
+ query = query.Limit(*limit)
+ }
+ if offset != nil {
+ query = query.Offset(*offset)
+ }
+ return query
+}
diff --git a/core/utilscore/db/db_rows.go b/core/utilscore/db/db_rows.go
new file mode 100644
index 0000000..309d3d0
--- /dev/null
+++ b/core/utilscore/db/db_rows.go
@@ -0,0 +1,139 @@
+package dbutils
+
+import (
+ "encoding/json"
+ "errors"
+ "reflect"
+ "sync"
+
+ "github.com/jackc/pgx/v5"
+ "github.com/sirupsen/logrus"
+)
+
+// Кэш для функции prepareFieldMap
+var prepareFieldMapCache sync.Map // Используем sync.Map для кэширования
+
+type cachedFieldInfo struct {
+ dbTag string
+ fieldPath []int
+}
+
+// ScanRowsToStructRows сканирует строки из pgx.Rows в структуру и totalCount.
+func ScanRowsToStructRows(rows pgx.Rows, dest interface{}, totalCount *uint64, totalAmount ...*float64) error {
+ if dest == nil {
+ return errors.New("dest must not be nil")
+ }
+
+ val := reflect.ValueOf(dest)
+ if val.Kind() != reflect.Ptr || val.IsNil() {
+ return errors.New("dest must be a non-nil pointer")
+ }
+
+ elem := val.Elem()
+ if elem.Kind() != reflect.Struct {
+ return errors.New("dest must be a pointer to a struct")
+ }
+
+ typ := elem.Type()
+ fieldMap := prepareFieldMap(elem, typ)
+
+ columns := getColumnsFromRows(rows)
+ args := getScanArgs(columns, fieldMap, totalCount, totalAmount...)
+
+ err := rows.Scan(args...)
+ if err != nil {
+ logrus.Error("🔴 error ScanRowsToStructRows: ", err)
+ return err
+ }
+
+ return nil
+}
+
+func getColumnsFromRows(rows pgx.Rows) []string {
+ fieldDescriptions := rows.FieldDescriptions()
+ columns := make([]string, len(fieldDescriptions))
+ for i, fd := range fieldDescriptions {
+ columns[i] = string(fd.Name)
+ }
+ return columns
+}
+
+func getScanArgs(columns []string, fieldMap map[string]interface{}, totalCount *uint64, totalAmount ...*float64) []interface{} {
+ scanArgs := make([]interface{}, len(columns))
+
+ for i, col := range columns {
+ switch col {
+ case "total_count":
+ if totalCount != nil {
+ scanArgs[i] = totalCount
+ } else {
+ scanArgs[i] = new(uint64)
+ }
+ case "total_amount":
+ if totalAmount[0] != nil {
+ scanArgs[i] = totalAmount[0]
+ } else {
+ dummy := new(float64)
+ scanArgs[i] = dummy
+ }
+ default:
+ if field, ok := fieldMap[col]; ok {
+ scanArgs[i] = field
+ } else {
+ dummy := new(interface{})
+ scanArgs[i] = dummy
+ }
+ }
+ }
+
+ return scanArgs
+}
+
+func prepareFieldMap(val reflect.Value, typ reflect.Type) map[string]interface{} {
+ if cachedFields, ok := prepareFieldMapCache.Load(typ); ok {
+ fieldMap := make(map[string]interface{})
+ // Используем закешированные данные
+ for _, info := range cachedFields.([]cachedFieldInfo) {
+ field := val.FieldByIndex(info.fieldPath)
+ if field.CanAddr() {
+ fieldMap[info.dbTag] = field.Addr().Interface()
+ }
+ }
+ return fieldMap
+ }
+
+ // Если тип не закеширован, собираем информацию о полях
+ var cachedFieldsInfo []cachedFieldInfo
+ fieldMap := make(map[string]interface{})
+ if val.Kind() == reflect.Ptr {
+ val = val.Elem()
+ }
+ for i := 0; i < val.NumField(); i++ {
+ field := val.Field(i)
+ fieldType := typ.Field(i)
+
+ if fieldType.Tag.Get("ignore_db_select") == "true" {
+ continue
+ }
+ if tag := fieldType.Tag.Get("db"); tag != "" {
+ if field.Type() == reflect.TypeOf(json.RawMessage{}) {
+ fieldMap[tag] = field.Addr().Interface()
+ } else if field.Kind() == reflect.Slice && field.Type().Elem() == reflect.TypeOf(json.RawMessage{}) {
+ fieldMap[tag] = &json.RawMessage{}
+ } else if field.Kind() == reflect.Struct && field.Type() == reflect.TypeOf(json.RawMessage{}) {
+ fieldMap[tag] = &json.RawMessage{}
+ } else {
+ fieldMap[tag] = field.Addr().Interface()
+ }
+ cachedFieldsInfo = append(cachedFieldsInfo, cachedFieldInfo{
+ dbTag: tag,
+ fieldPath: fieldType.Index,
+ })
+ }
+ }
+
+ // Сохраняем информацию в кэше
+ prepareFieldMapCache.Store(typ, cachedFieldsInfo)
+
+ return fieldMap
+}
diff --git a/core/utilscore/db/query.go b/core/utilscore/db/query.go
new file mode 100644
index 0000000..5639802
--- /dev/null
+++ b/core/utilscore/db/query.go
@@ -0,0 +1,22 @@
+package dbutils
+
+import (
+ "github.com/Masterminds/squirrel"
+)
+
+// BuildSelectQuery создает базовый SELECT-запрос.
+func BuildSelectQuery(table string, fields []string) squirrel.SelectBuilder {
+ return squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
+ Select(fields...).From(table)
+}
+
+// ApplyFilters добавляет фильтры к запросу
+func ApplyFilters(query squirrel.SelectBuilder, paramsFiltering interface{}, likeFields map[string]string, baseName ...string) squirrel.SelectBuilder {
+ var baseNamePtr *string
+ if len(baseName) > 0 {
+ baseNamePtr = &baseName[0]
+ } else {
+ baseNamePtr = nil
+ }
+ return AddNonNullFieldsToQueryWhere(query, paramsFiltering, likeFields, baseNamePtr)
+}
diff --git a/core/utilscore/db/query_where.go b/core/utilscore/db/query_where.go
new file mode 100644
index 0000000..02e9366
--- /dev/null
+++ b/core/utilscore/db/query_where.go
@@ -0,0 +1,170 @@
+package dbutils
+
+import (
+ "fmt"
+ "reflect"
+ "strings"
+ "sync"
+
+ "github.com/Masterminds/squirrel"
+)
+
+var (
+ reflectionCacheQueryWhere sync.Map // Используем sync.Map для кэширования
+)
+
+func getCachedFieldsQueryWhere(t reflect.Type) []reflect.StructField {
+ if fields, exists := reflectionCacheQueryWhere.Load(t); exists {
+ return fields.([]reflect.StructField)
+ }
+
+ var cachedFields []reflect.StructField
+ for i := 0; i < t.NumField(); i++ {
+ cachedFields = append(cachedFields, t.Field(i))
+ }
+ reflectionCacheQueryWhere.Store(t, cachedFields)
+ return cachedFields
+}
+func AddNonNullFieldsToQueryWhere(
+ query squirrel.SelectBuilder,
+ processor interface{},
+ likeFields map[string]string,
+ baseName *string,
+) squirrel.SelectBuilder {
+ val := reflect.ValueOf(processor).Elem()
+ typ := val.Type()
+
+ var or squirrel.Or
+ fields := getCachedFieldsQueryWhere(typ)
+
+ for i := 0; i < val.NumField(); i++ {
+ field := val.Field(i)
+ typeField := fields[i]
+
+ // Пропускаем невалидные или пустые поля
+ if !field.IsValid() || field.IsZero() {
+ continue
+ }
+
+ // Безопасно проверяем на nil, только если тип позволяет
+ if isNilable(field.Kind()) && field.IsNil() {
+ continue
+ }
+
+ ignoreDbTag := typeField.Tag.Get("ignore_db")
+ if ignoreDbTag == "true" {
+ continue
+ }
+
+ ignoreReqDbTag := typeField.Tag.Get("ignore_req_db")
+ if ignoreReqDbTag == "true" {
+ continue
+ }
+
+ dbTag := typeField.Tag.Get("db")
+ if dbTag != "" {
+ if baseName != nil {
+ dbTag = fmt.Sprintf("%s.%s", *baseName, dbTag)
+ }
+
+ if likeValue, ok := likeFields[dbTag]; ok {
+ // Добавляем LIKE фильтр
+ switch dbTag {
+ case "serial_id":
+ or = append(or, squirrel.Expr("CAST(serial_id AS TEXT) ILIKE ?", likeValue+"%"))
+ case "telegram_id":
+ or = append(or, squirrel.Expr("CAST(telegram_id AS TEXT) ILIKE ?", likeValue+"%"))
+ default:
+ or = append(or, squirrel.ILike{dbTag: likeValue + "%"})
+ }
+ } else {
+ query = query.Where(processFieldCached(field, dbTag))
+ }
+ }
+ }
+
+ if len(or) > 0 {
+ query = query.Where(or)
+ }
+
+ return query
+}
+
+func AddNotNullAndPositiveConditions(query squirrel.SelectBuilder, fields map[string]bool) squirrel.SelectBuilder {
+ for field, value := range fields {
+ // Для числовых полей добавляем проверку на > 0
+ if value {
+ query = query.Where(squirrel.And{
+ squirrel.NotEq{field: nil},
+ squirrel.Gt{field: 0},
+ })
+ } else {
+ // Для нечисловых полей проверяем только на null
+ query = query.Where(squirrel.NotEq{field: nil})
+ }
+
+ }
+ return query
+}
+
+// Вспомогательная функция — проверка, может ли тип быть nil
+func isNilable(kind reflect.Kind) bool {
+ switch kind {
+ case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Pointer, reflect.Slice:
+ return true
+ default:
+ return false
+ }
+}
+
+func processFieldCached(field reflect.Value, dbTag string) squirrel.Sqlizer {
+ fieldType := field.Type().String()
+
+ switch fieldType {
+ case "*bool":
+ boolVal := *field.Interface().(*bool)
+ return squirrel.Eq{dbTag: boolVal}
+ case "*string":
+ str := *field.Interface().(*string)
+ if strings.Contains(str, ",") {
+ values := strings.Split(str, ",")
+ or := squirrel.Or{}
+ for _, value := range values {
+ or = append(or, squirrel.Eq{dbTag: value})
+ }
+ return or
+ }
+ return squirrel.Eq{dbTag: str}
+ case "[]*string":
+ stringPtrSlice := field.Interface().([]*string)
+
+ if len(stringPtrSlice) == 0 {
+ return squirrel.Eq{dbTag: nil}
+ }
+
+ // Специальная обработка для поля categories
+ if dbTag == "categories" || strings.HasSuffix(dbTag, ".categories") {
+ or := squirrel.Or{}
+ for _, strPtr := range stringPtrSlice {
+ if strPtr != nil {
+ or = append(or, squirrel.Expr(
+ dbTag+" && ARRAY[?]",
+ *strPtr,
+ ))
+ }
+ }
+ return or
+ }
+
+ // Для других полей типа []*string используем обычный подход
+ or := squirrel.Or{}
+ for _, strPtr := range stringPtrSlice {
+ if strPtr != nil {
+ or = append(or, squirrel.Eq{dbTag: *strPtr})
+ }
+ }
+ return or
+ default:
+ return squirrel.Eq{dbTag: field.Interface()}
+ }
+}
diff --git a/core/utilscore/db/transaction.go b/core/utilscore/db/transaction.go
new file mode 100644
index 0000000..1effda0
--- /dev/null
+++ b/core/utilscore/db/transaction.go
@@ -0,0 +1,70 @@
+package dbutils
+
+import (
+ "context"
+ "errors"
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgxpool"
+ "github.com/sirupsen/logrus"
+ "log"
+)
+
+func RollbackTransactionDB(ctx context.Context, tx pgx.Tx) {
+ if rErr := tx.Rollback(ctx); rErr != nil && !errors.Is(rErr, pgx.ErrTxClosed) {
+ log.Printf("error: failed to rollback transaction: %v", rErr)
+ }
+}
+
+func BeginTransaction(ctx context.Context, databasePull *pgxpool.Pool) (*pgxpool.Conn, pgx.Tx, error) {
+ conn, err := databasePull.Acquire(ctx)
+ if err != nil {
+ logrus.Errorf("🔴 error: %s: %+v", "BeginTransaction-BeginTransaction", err)
+ return nil, nil, err
+ }
+ tx, err := conn.Begin(ctx)
+ if err != nil {
+ logrus.Errorf("🔴 error: %s: %+v", "BeginTransaction-Begin", err)
+ conn.Release()
+ return nil, nil, err
+ }
+ return conn, tx, nil
+}
+
+// ExecuteTx выполняет функцию fn в транзакции.
+// Если tx не nil, то используется переданная транзакция.
+// Иначе создается новая транзакция.
+func ExecuteTx(ctx context.Context, db *pgxpool.Pool, tx pgx.Tx, fn func(tx pgx.Tx) error) error {
+ var err error
+ var transactionStarted bool
+
+ if tx == nil {
+ tx, err = db.Begin(ctx)
+ if err != nil {
+ logrus.Errorf("🔴 error: %s: %+v", "ExecuteTx-Begin", err)
+ return err
+ }
+
+ transactionStarted = true
+ }
+
+ err = fn(tx)
+
+ if transactionStarted {
+ if err != nil {
+ logrus.Errorf("🔴 error: %s: %+v", "ExecuteTx-transactionStarted", err)
+ if rollbackErr := tx.Rollback(ctx); rollbackErr != nil {
+ return err
+ }
+ return err
+ }
+
+ if commitErr := tx.Commit(ctx); commitErr != nil {
+ return err
+ }
+ }
+
+ if err != nil {
+ return err
+ }
+ return nil
+}
diff --git a/core/utilscore/db/update_set.go b/core/utilscore/db/update_set.go
new file mode 100644
index 0000000..ef20333
--- /dev/null
+++ b/core/utilscore/db/update_set.go
@@ -0,0 +1,59 @@
+package dbutils
+
+import (
+ "reflect"
+ "sync"
+
+ "github.com/Masterminds/squirrel"
+)
+
+var (
+ typeCache sync.Map // Используем sync.Map для кэширования
+)
+
+type fieldInfo struct {
+ dbTag string
+ ignoreDb bool
+ ignoreReqDb bool
+ updatableDb bool
+ fieldInterface func(reflect.Value) interface{}
+}
+
+func getCachedFields(t reflect.Type) []fieldInfo {
+ if fields, exists := typeCache.Load(t); exists {
+ return fields.([]fieldInfo)
+ }
+
+ var cachedFields []fieldInfo
+ for i := 0; i < t.NumField(); i++ {
+ f := t.Field(i)
+ cInfo := fieldInfo{
+ dbTag: f.Tag.Get("db"),
+ ignoreDb: f.Tag.Get("ignore_db") == "true" || f.Tag.Get("db") == "",
+ ignoreReqDb: f.Tag.Get("ignore_req_db") == "true",
+ updatableDb: f.Tag.Get("updatable_db") != "false",
+ fieldInterface: func(v reflect.Value) interface{} {
+ return v.Interface()
+ },
+ }
+ cachedFields = append(cachedFields, cInfo)
+ }
+ typeCache.Store(t, cachedFields)
+ return cachedFields
+}
+
+func UpdateSetField(query squirrel.UpdateBuilder, processor interface{}) squirrel.UpdateBuilder {
+ v := reflect.ValueOf(processor).Elem()
+ t := v.Type()
+ fields := getCachedFields(t)
+ for i, f := range fields {
+ field := v.Field(i)
+ if (field.Kind() == reflect.Ptr && !field.IsNil()) || (field.Kind() != reflect.Ptr && !field.IsZero()) {
+ if f.ignoreDb || f.ignoreReqDb || !f.updatableDb {
+ continue
+ }
+ query = query.Set(f.dbTag, f.fieldInterface(field))
+ }
+ }
+ return query
+}
diff --git a/core/utilscore/plural.go b/core/utilscore/plural.go
new file mode 100644
index 0000000..0d69228
--- /dev/null
+++ b/core/utilscore/plural.go
@@ -0,0 +1,14 @@
+package utilscore
+
+import "fmt"
+
+func PluralFiles(n int) string {
+ switch {
+ case n%10 == 1 && n%100 != 11:
+ return fmt.Sprintf("%d файл", n)
+ case n%10 >= 2 && n%10 <= 4 && (n%100 < 10 || n%100 >= 20):
+ return fmt.Sprintf("%d файла", n)
+ default:
+ return fmt.Sprintf("%d файлов", n)
+ }
+}
diff --git a/core/utilscore/rest.go b/core/utilscore/rest.go
new file mode 100644
index 0000000..2f4a734
--- /dev/null
+++ b/core/utilscore/rest.go
@@ -0,0 +1,165 @@
+package utilscore
+
+import (
+ "fmt"
+ "github.com/mitchellh/mapstructure"
+ "github.com/shopspring/decimal"
+ "github.com/sirupsen/logrus"
+ "net/url"
+ "reflect"
+ "strconv"
+ "strings"
+)
+
+func ParseParamsGetRequest(queryParams url.Values, result interface{}) (*uint64, *uint64, map[string]string, error) {
+ likeFields := map[string]string{}
+ singleValueQueryParams := make(map[string]interface{})
+ offset := PointerToUint64(0)
+ limit := PointerToUint64(50)
+
+ paramTypes := make(map[string]string)
+
+ resultType := reflect.TypeOf(result).Elem()
+ for i := 0; i < resultType.NumField(); i++ {
+ field := resultType.Field(i)
+ tag := field.Tag.Get("mapstructure")
+ if tag != "" {
+ fieldType := field.Type
+ if fieldType.Kind() == reflect.Ptr {
+ fieldType = fieldType.Elem()
+ }
+ paramTypes[tag] = fieldType.String()
+ }
+ }
+
+ for key, values := range queryParams {
+ if len(values) > 0 {
+ value := values[0]
+ switch key {
+ case "offset":
+ offset = parseUintParam(value)
+ case "limit":
+ limit = parseUintParam(value)
+ default:
+ singleValueQueryParams[key] = parseQueryParam(value, key, paramTypes)
+ }
+ }
+ }
+
+ decoder, err := setupDecoder(result)
+ if err != nil {
+ logrus.Error("🛑 error setting up decoder: ", err)
+ return offset, limit, likeFields, err
+ }
+
+ err = decoder.Decode(singleValueQueryParams)
+ if err != nil {
+ logrus.Error("🛑 error decoding query params: ", err)
+ return offset, limit, likeFields, err
+ }
+
+ return offset, limit, likeFields, nil
+}
+
+func parseQueryParam(value string, key string, paramTypes map[string]string) interface{} {
+ switch value {
+ case "true":
+ return true
+ case "false":
+ return false
+ case "all":
+ return nil
+ default:
+ if strings.Contains(value, ",") {
+ return strings.Split(value, ",")
+ }
+
+ if paramTypes[key] == "decimal.Decimal" {
+ if decVal, err := decimal.NewFromString(value); err == nil {
+ return decVal
+ } else {
+ // Логирование ошибки
+ logrus.Error("🛑 error parsing decimal param: ", err)
+ return nil
+ }
+ }
+
+ if paramTypes[key] == "uint64" {
+ if uintVal, err := strconv.ParseUint(value, 10, 64); err == nil {
+ logrus.Error("🛑 error parsing uint64 param: ", err)
+ return uintVal
+ } else {
+ return nil
+ }
+ }
+
+ // Проверяем тип данных из paramTypes
+ if paramTypes[key] == "string" {
+ return value
+ }
+
+ if floatVal, err := strconv.ParseFloat(value, 64); err == nil {
+ return floatVal
+ }
+ return value
+ }
+}
+
+func parseUintParam(value string) *uint64 {
+ val, err := strconv.ParseUint(value, 10, 64)
+ if err == nil {
+ return &val
+ }
+ logrus.Error("🛑 error parsing uint param: ", err)
+ return nil
+}
+
+func setupDecoder(result interface{}) (*mapstructure.Decoder, error) {
+ decoderConfig := &mapstructure.DecoderConfig{
+ DecodeHook: mapstructure.ComposeDecodeHookFunc(
+ decodeHookStringSliceToString,
+ decodeHookStringToPtrStringSlice,
+ decodeHookStringToDecimal,
+ ),
+ Result: result,
+ }
+ decoder, err := mapstructure.NewDecoder(decoderConfig)
+ if err != nil {
+ logrus.Error("🛑 error creating decoder: ", err)
+ return nil, err
+ }
+ return decoder, nil
+}
+
+func decodeHookStringSliceToString(f reflect.Type, t reflect.Type, data interface{}) (interface{}, error) {
+ if t == reflect.TypeOf(new(string)) && f.Kind() == reflect.Slice {
+ slice := reflect.ValueOf(data)
+ strSlice := make([]string, slice.Len())
+ for i := 0; i < slice.Len(); i++ {
+ strSlice[i] = fmt.Sprint(slice.Index(i).Interface())
+ }
+ result := strings.Join(strSlice, ",")
+ return &result, nil
+ }
+ return data, nil
+}
+
+func decodeHookStringToPtrStringSlice(f reflect.Type, t reflect.Type, data interface{}) (interface{}, error) {
+ if t == reflect.TypeOf([]*string{}) && f.Kind() == reflect.String {
+ str := data.(string)
+ return []*string{&str}, nil
+ }
+ return data, nil
+}
+
+func decodeHookStringToDecimal(from reflect.Type, to reflect.Type, data interface{}) (interface{}, error) {
+ if from.Kind() == reflect.String && to == reflect.TypeOf(&decimal.Decimal{}) {
+ dec, err := decimal.NewFromString(data.(string))
+ if err != nil {
+ logrus.Error("🛑 error parsing decimal: ", err)
+ return nil, err
+ }
+ return &dec, nil
+ }
+ return data, nil
+}
diff --git a/core/utilscore/secure.go b/core/utilscore/secure.go
new file mode 100644
index 0000000..7842702
--- /dev/null
+++ b/core/utilscore/secure.go
@@ -0,0 +1,26 @@
+package utilscore
+
+import (
+ "crypto/hmac"
+ "crypto/sha256"
+ "encoding/hex"
+)
+
+func GenerateHMACSignature(public, timestampStr, private string) string {
+ h := hmac.New(sha256.New, []byte(private))
+ h.Write([]byte(public + ":" + timestampStr))
+ signature := h.Sum(nil)
+ return hex.EncodeToString(signature)
+}
+
+func HmacEquals(expected, actual string) bool {
+ expectedBytes, err := hex.DecodeString(expected)
+ if err != nil {
+ return false
+ }
+ actualBytes, err := hex.DecodeString(actual)
+ if err != nil {
+ return false
+ }
+ return hmac.Equal(expectedBytes, actualBytes)
+}
diff --git a/core/utilscore/sendBotMsg.go b/core/utilscore/sendBotMsg.go
new file mode 100644
index 0000000..71faca4
--- /dev/null
+++ b/core/utilscore/sendBotMsg.go
@@ -0,0 +1,9 @@
+package utilscore
+
+import tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
+
+func SendBotMessage(bot *tgbotapi.BotAPI, chatID int64, text string) {
+ msg := tgbotapi.NewMessage(chatID, text)
+ msg.ParseMode = "HTML"
+ bot.Send(msg) //nolint:errcheck
+}
diff --git a/core/utilscore/w-recover.go b/core/utilscore/w-recover.go
new file mode 100644
index 0000000..e283697
--- /dev/null
+++ b/core/utilscore/w-recover.go
@@ -0,0 +1,36 @@
+package utilscore
+
+import (
+ "github.com/google/uuid"
+ "github.com/sirupsen/logrus"
+ "net/http"
+ "runtime/debug"
+)
+
+// RecoverMiddleware глобально перехватывает паники в HTTP-стеке, логирует и возвращает 500
+func RecoverMiddleware() func(http.Handler) http.Handler {
+ return func(next http.Handler) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ defer func() {
+ if rec := recover(); rec != nil {
+ logrus.Errorf("panic recovered: %v", rec)
+ logrus.Errorf("stacktrace: %s", string(debug.Stack()))
+ w.Header().Set("Content-Type", "application/json")
+ http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
+ }
+ }()
+ next.ServeHTTP(w, r)
+ })
+ }
+}
+
+func RecoverAndLog(scope ...string) {
+ scopeString := uuid.New().String()
+ if len(scope) > 0 {
+ scopeString = scope[0]
+ }
+ if rec := recover(); rec != nil {
+ logrus.Errorf("%s: panic recovered: %v", scopeString, rec)
+ logrus.Errorf("%s: stacktrace: %s", scopeString, string(debug.Stack()))
+ }
+}
diff --git a/core/variables/api_headers.go b/core/variables/api_headers.go
new file mode 100644
index 0000000..fc9ac04
--- /dev/null
+++ b/core/variables/api_headers.go
@@ -0,0 +1,9 @@
+package variables
+
+type contextKey string
+
+func (c contextKey) String() string {
+ return string(c)
+}
+
+const AccessContextKey contextKey = "accessCode"
diff --git a/deploy.sh b/deploy.sh
new file mode 100644
index 0000000..a3a6ecc
--- /dev/null
+++ b/deploy.sh
@@ -0,0 +1,30 @@
+#!/bin/bash
+
+set -e
+trap 'echo "🔴 Deploy failed"; exit 1' ERR
+
+THIS_PATH=$(dirname "$(realpath "$0")")
+SERVICE_NAME="rest_base_service"
+SERVICE_PATH="$THIS_PATH/service/$SERVICE_NAME"
+BINARY_PATH="/usr/local/bin/$SERVICE_NAME"
+
+echo "🔨 Building core..."
+cd "$THIS_PATH/core"
+go mod tidy
+go vet ./...
+
+echo "🔨 Building $SERVICE_NAME..."
+cd "$SERVICE_PATH"
+go mod tidy
+gofmt -w .
+go build -o "$BINARY_PATH" .
+
+echo "✅ Binary deployed to $BINARY_PATH"
+
+# Перезапускаем сервис если systemd юнит уже существует
+if systemctl is-active --quiet "$SERVICE_NAME"; then
+ echo "🔄 Restarting systemd service..."
+ sudo systemctl restart "$SERVICE_NAME"
+else
+ echo "⚠️ Service not running. Start with: sudo systemctl start $SERVICE_NAME"
+fi
\ No newline at end of file
diff --git a/go.work b/go.work
new file mode 100644
index 0000000..7bc4048
--- /dev/null
+++ b/go.work
@@ -0,0 +1,8 @@
+go 1.25.6
+
+use (
+ core
+ ./service/rest_base_service
+ service/telegram_service
+ service/system_service
+)
diff --git a/go.work.sum b/go.work.sum
new file mode 100644
index 0000000..7d0f59d
--- /dev/null
+++ b/go.work.sum
@@ -0,0 +1,68 @@
+github.com/Masterminds/goutils v1.1.1 h1:5nUrii3FMTL5diU80unEVvNevw1nH4+ZV4DSLVJLSYI=
+github.com/Masterminds/goutils v1.1.1/go.mod h1:8cTjp+g8YejhMuvIA5y2vz3BpJxksy863GQaJW2MFNU=
+github.com/Masterminds/semver/v3 v3.1.1 h1:hLg3sBzpNErnxhQtUy/mmLR2I9foDujNK030IGemrRc=
+github.com/Masterminds/semver/v3 v3.1.1/go.mod h1:VPu/7SZ7ePZ3QOrcuXROw5FAcLl4a0cBrbBpGY/8hQs=
+github.com/Masterminds/sprig/v3 v3.2.1 h1:n6EPaDyLSvCEa3frruQvAiHuNp2dhBlMSmkEr+HuzGc=
+github.com/Masterminds/sprig/v3 v3.2.1/go.mod h1:UoaO7Yp8KlPnJIYWTFkMaqPUYKTfGFPhxNuwnnxkKlk=
+github.com/armon/go-radix v0.0.0-20180808171621-7fddfc383310 h1:BUAU3CGlLvorLI26FmByPp2eC2qla6E1Tw+scpcg/to=
+github.com/armon/go-radix v0.0.0-20180808171621-7fddfc383310/go.mod h1:ufUuZ+zHj4x4TnLV4JWEpy2hxWSpsRywHrMgIH9cCH8=
+github.com/bgentry/speakeasy v0.1.0 h1:ByYyxL9InA1OWqxJqqp2A5pYHUrCiAL6K3J+LKSsQkY=
+github.com/bgentry/speakeasy v0.1.0/go.mod h1:+zsyZBPWlz7T6j88CTgSN5bM796AkVf0kBD4zp0CCIs=
+github.com/creack/pty v1.1.9 h1:uDmaGzcdjhF4i/plgjmEsriH11Y0o7RKapEf/LDaM3w=
+github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
+github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
+github.com/huandu/xstrings v1.3.2 h1:L18LIDzqlW6xN2rEkpdV8+oL/IXWJ1APd+vsdYy4Wdw=
+github.com/huandu/xstrings v1.3.2/go.mod h1:y5/lhBue+AyNmUVz9RLU9xbLR0o4KIIExikq4ovT0aE=
+github.com/imdario/mergo v0.3.11 h1:3tnifQM4i+fbajXKBHXWEH+KvNHqojZ778UH75j3bGA=
+github.com/imdario/mergo v0.3.11/go.mod h1:jmQim1M+e3UYxmgPu/WyfjB3N3VflVyUjjjwH0dnCYA=
+github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU=
+github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
+github.com/mitchellh/cli v1.1.5 h1:OxRIeJXpAMztws/XHlN2vu6imG5Dpq+j61AzAX5fLng=
+github.com/mitchellh/cli v1.1.5/go.mod h1:v8+iFts2sPIKUV1ltktPXMCC8fumSKFItNcD2cLtRR4=
+github.com/mitchellh/copystructure v1.0.0 h1:Laisrj+bAB6b/yJwB5Bt3ITZhGJdqmxquMKeZ+mmkFQ=
+github.com/mitchellh/copystructure v1.0.0/go.mod h1:SNtv71yrdKgLRyLFxmLdkAbkKEFWgYaq1OVrnRcwhnw=
+github.com/mitchellh/go-wordwrap v1.0.1 h1:TLuKupo69TCn6TQSyGxwI1EblZZEsQ0vMlAFQflz0v0=
+github.com/mitchellh/go-wordwrap v1.0.1/go.mod h1:R62XHJLzvMFRBbcrT7m7WgmE1eOyTSsCt+hzestvNj0=
+github.com/mitchellh/reflectwalk v1.0.0 h1:9D+8oIskB4VJBN5SFlmc27fSlIBZaov1Wpk/IfikLNY=
+github.com/mitchellh/reflectwalk v1.0.0/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw=
+github.com/natefinch/atomic v1.0.1 h1:ZPYKxkqQOx3KZ+RsbnP/YsgvxWQPGxjC0oBt2AhwV0A=
+github.com/natefinch/atomic v1.0.1/go.mod h1:N/D/ELrljoqDyT3rZrsUmtsuzvHkeB/wWjHV22AZRbM=
+github.com/posener/complete v1.1.1 h1:ccV59UEOTzVDnDUEFdT95ZzHVZ+5+158q8+SJb2QV5w=
+github.com/posener/complete v1.1.1/go.mod h1:em0nMJCgc9GFtwrmVmEMR/ZL6WyhyjMBndrE9hABlRI=
+github.com/ryanuber/columnize v2.1.2+incompatible h1:C89EOx/XBWwIXl8wm8OPJBd7kPF25UfsK2X7Ph/zCAk=
+github.com/ryanuber/columnize v2.1.2+incompatible/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts=
+github.com/spf13/cast v1.3.1 h1:nFm6S0SMdyzrzcmThSipiEubIDy8WEXKNZ0UOgiRpng=
+github.com/spf13/cast v1.3.1/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE=
+github.com/stretchr/objx v0.1.0 h1:4G4v2dO3VZwixGIRoQ5Lfboy6nUhCyYzaqnIAPPhYs4=
+github.com/yuin/goldmark v1.4.13 h1:fVcFKWvrslecOb/tg+Cc05dkeYx540o0FuFt3nUVDoE=
+github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
+golang.org/x/crypto v0.41.0 h1:WKYxWedPGCTVVl5+WHSSrOBT0O8lx32+zxmHxijgXp4=
+golang.org/x/crypto v0.41.0/go.mod h1:pO5AFd7FA68rFak7rOAGVuygIISepHftHnr8dr6+sUc=
+golang.org/x/image v0.25.0 h1:Y6uW6rH1y5y/LK1J8BPWZtr6yZ7hrsy6hFrXjgsc2fQ=
+golang.org/x/image v0.25.0/go.mod h1:tCAmOEGthTtkalusGp1g3xa2gke8J6c2N565dTyl9Rs=
+golang.org/x/mod v0.27.0 h1:kb+q2PyFnEADO2IEF935ehFUXlWiNjJWtRNgBLSfbxQ=
+golang.org/x/mod v0.27.0/go.mod h1:rWI627Fq0DEoudcK+MBkNkCe0EetEaDSwJJkCcjpazc=
+golang.org/x/mod v0.32.0 h1:9F4d3PHLljb6x//jOyokMv3eX+YDeepZSEo3mFJy93c=
+golang.org/x/mod v0.32.0/go.mod h1:SgipZ/3h2Ci89DlEtEXWUk/HteuRin+HHhN+WbNhguU=
+golang.org/x/net v0.43.0 h1:lat02VYK2j4aLzMzecihNvTlJNQUq316m2Mr9rnM6YE=
+golang.org/x/net v0.43.0/go.mod h1:vhO1fvI4dGsIjh73sWfUVjj3N7CA9WkKJNQm2svM6Jg=
+golang.org/x/net v0.49.0/go.mod h1:/ysNB2EvaqvesRkuLAyjI1ycPZlQHM3q01F02UY/MV8=
+golang.org/x/sync v0.19.0 h1:vV+1eWNmZ5geRlYjzm2adRgW2/mcpevXNg50YZtPCE4=
+golang.org/x/sys v0.35.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
+golang.org/x/telemetry v0.0.0-20250807160809-1a19826ec488 h1:3doPGa+Gg4snce233aCWnbZVFsyFMo/dR40KK/6skyE=
+golang.org/x/telemetry v0.0.0-20250807160809-1a19826ec488/go.mod h1:fGb/2+tgXXjhjHsTNdVEEMZNWA0quBnfrO+AfoDSAKw=
+golang.org/x/telemetry v0.0.0-20260109210033-bd525da824e2 h1:O1cMQHRfwNpDfDJerqRoE2oD+AFlyid87D40L/OkkJo=
+golang.org/x/telemetry v0.0.0-20260109210033-bd525da824e2/go.mod h1:b7fPSJ0pKZ3ccUh8gnTONJxhn3c/PS6tyzQvyqw4iA8=
+golang.org/x/term v0.33.0 h1:NuFncQrRcaRvVmgRkvM3j/F00gWIAlcmlB8ACEKmGIg=
+golang.org/x/term v0.33.0/go.mod h1:s18+ql9tYWp1IfpV9DmCtQDDSRBUjKaw9M1eAv5UeF0=
+golang.org/x/term v0.34.0 h1:O/2T7POpk0ZZ7MAzMeWFSg6S5IpWd/RXDlM9hgM3DR4=
+golang.org/x/term v0.34.0/go.mod h1:5jC53AEywhIVebHgPVeg0mj8OD3VO9OzclacVrqpaAw=
+golang.org/x/term v0.40.0 h1:36e4zGLqU4yhjlmxEaagx2KuYbJq3EwY8K943ZsHcvg=
+golang.org/x/term v0.40.0/go.mod h1:w2P8uVp06p2iyKKuvXIm7N/y0UCRt3UfJTfZ7oOpglM=
+golang.org/x/text v0.28.0/go.mod h1:U8nCwOR8jO/marOQ0QbDiOngZVEBB7MAiitBuMjXiNU=
+golang.org/x/tools v0.36.0 h1:kWS0uv/zsvHEle1LbV5LE8QujrxB3wfQyxHfhOk0Qkg=
+golang.org/x/tools v0.36.0/go.mod h1:WBDiHKJK8YgLHlcQPYQzNCkUxUypCaa5ZegCVutKm+s=
+golang.org/x/tools v0.41.0 h1:a9b8iMweWG+S0OBnlU36rzLp20z1Rp10w+IY2czHTQc=
+golang.org/x/tools v0.41.0/go.mod h1:XSY6eDqxVNiYgezAVqqCeihT4j1U2CCsqvH3WhQpnlg=
+gorm.io/driver/sqlite v1.6.0 h1:WHRRrIiulaPiPFmDcod6prc4l2VGVWHz80KspNsxSfQ=
+gorm.io/driver/sqlite v1.6.0/go.mod h1:AO9V1qIQddBESngQUKWL9yoH93HIeA1X6V633rBwyT8=
diff --git a/service/.DS_Store b/service/.DS_Store
new file mode 100644
index 0000000..0382d2a
Binary files /dev/null and b/service/.DS_Store differ
diff --git a/service/rest_base_service/.golangci.yml b/service/rest_base_service/.golangci.yml
new file mode 100644
index 0000000..84625ed
--- /dev/null
+++ b/service/rest_base_service/.golangci.yml
@@ -0,0 +1,52 @@
+linters-settings:
+ errcheck: # Настройки для линтера errcheck, который проверяет, что ошибки не игнорируются
+ check-type-assertions: true # Не проверять утверждения типов на ошибки
+ check-blank: true # Проверять игнорирование ошибок через присваивание в _
+ prealloc: # Настройки для линтера prealloc, который предлагает предварительное выделение памяти для срезов
+ simple: true # Простой режим, предлагает предварительное выделение для простых циклов
+ range-loops: true # Предлагает предварительное выделение для циклов range
+ for-loops: false # Не предлагает предварительное выделение для обычных for-циклов
+ gocyclo: # Настройки для линтера gocyclo, который проверяет сложность функций
+ min-complexity: 15 # Установите порог сложности, который считаете приемлемым
+
+linters:
+ enable: # Список линтеров, которые будут включены
+ - noctx # Находит отправку HTTP-запроса без контекста.Контекст.
+ - protogetter # Сообщает о прямом чтении из полей прото-сообщения, когда следует использовать геттеры.
+ - reassign # Проверяет, что переменные пакета не переназначаются.
+ - rowserrcheck # Проверяет, успешно ли проверен Rows.Err строк.
+ - sqlclosecheck # Проверяет, что sql.Rows, sql.Stmt, sqlx.NamedStmt, pgx.Query закрыты.
+ - ineffassign # Обнаруживает, когда назначения существующим переменным не используются.
+ - nilerr # Находит код, который возвращает ноль, даже если он проверяет, что ошибка не равна нулю.
+ - makezero # Проверяет, что нулевые значения создаются правильно
+ - gochecksumtype # Проверяет, что тип контрольной суммы в go.sum соответствует содержимому
+ - copyloopvar # Проверяет, что циклические зависимости пакетов не имеют экспортируемых идентификаторов
+ - exhaustive # Проверьте полноту операторов перечисления.
+ - errchkjson # Проверяет типы, передаваемые функциям кодирования JSON. Сообщает о неподдерживаемых типах и событиях, при которых проверку возвращаемой ошибки можно опустить.
+ - durationcheck # Проверяет, что длительность таймаута не равна 0
+ - contextcheck # Проверяет, что контекст не игнорируется
+ - bodyclose # Проверяет, что тело запроса закрывается
+ - bidichk # Проверяет, что строки в исходном коде не содержат символов из разных языков
+ - govet # Проверяет код на наличие конструкций, которые могут быть ошибочными
+ - errcheck # Проверяет, что ошибки не игнорируются
+ - staticcheck # Статический анализ кода, находит ошибки, неэффективные конструкции и т.д.
+ - unused # Проверяет на неиспользуемые переменные, функции, константы
+ - gocritic # Линтер, основанный на проверке кода на соответствие определенным критериям качества и стиля
+ - stylecheck # Проверяет стиль кодирования
+ - whitespace # Проверяет проблемы с пробелами в коде
+ - gosec # Линтер gosec, который проверяет код на наличие потенциальных уязвимостей
+ - prealloc # Предлагает предварительное выделение памяти для срезов
+
+ - dupl # Находит дублирующийся код
+ - gocyclo # Проверяет сложность функций
+ - ineffassign # Обнаруживает неэффективные присваивания
+ - unparam # Находит неиспользуемые параметры функций
+
+ - gosimple # Предлагает упрощения кода
+
+ disable: # Список линтеров, которые будут отключены
+ - gofumpt # Более строгая версия gofmt, применяет дополнительные правила форматирования
+ # - golint # Отключает golint, который проверяет стиль написания кода на Go
+
+run:
+ timeout: 15m # Устанавливает тайм-аут для выполнения всех линтеров
\ No newline at end of file
diff --git a/service/rest_base_service/Dockerfile b/service/rest_base_service/Dockerfile
new file mode 100644
index 0000000..1d36a15
--- /dev/null
+++ b/service/rest_base_service/Dockerfile
@@ -0,0 +1,15 @@
+# FROM ubuntu:22.04
+FROM kartashs/ubuntu:22.04
+
+WORKDIR /app
+
+# Определяем аргумент сборки
+ARG APP_NAME
+
+COPY ./${APP_NAME} /app/${APP_NAME}
+
+RUN chmod +x /app/${APP_NAME}
+
+RUN echo "APP_NAME=${APP_NAME}"
+
+CMD ["sh", "-c", "/app/${APP_NAME}"]
\ No newline at end of file
diff --git a/service/rest_base_service/build.sh b/service/rest_base_service/build.sh
new file mode 100644
index 0000000..e8af79c
--- /dev/null
+++ b/service/rest_base_service/build.sh
@@ -0,0 +1,21 @@
+#!/bin/bash
+
+SERVICE_PATH=$(dirname "$(realpath "$0")")
+SERVICE_NAME="rest_base_service" # Название сервиса
+PARENT_PATH=$(dirname "$SERVICE_PATH")
+BACKEND_PATH=$(dirname "$PARENT_PATH")
+
+set -e
+trap 'echo "🔴 Error build $SERVICE_NAME"; exit 1' ERR
+
+sudo ls
+echo "🟡 Start Build: $SERVICE_NAME"
+echo "🔵 SERVICE_PATH: $SERVICE_PATH"
+echo "🔵 BACKEND_PATH: $BACKEND_PATH"
+
+go mod tidy
+
+go build -o "${SERVICE_NAME}_app" "$SERVICE_PATH/cmd/app.go"
+sudo chmod +x "${SERVICE_NAME}_app"
+
+echo "🟢 Finish build $SERVICE_NAME generate"
\ No newline at end of file
diff --git a/service/rest_base_service/cmd/app.go b/service/rest_base_service/cmd/app.go
new file mode 100644
index 0000000..8c6c4e9
--- /dev/null
+++ b/service/rest_base_service/cmd/app.go
@@ -0,0 +1,172 @@
+package main
+
+import (
+ configcore "bitrix_balancer_api/core/config"
+ clientcontrollers "bitrix_balancer_api/core/lib/internally/client-controllers"
+ "bitrix_balancer_api/core/lib/internally/redis"
+ "bitrix_balancer_api/core/utilscore"
+ balancerhandler "bitrix_balancer_api/rest_base_service/handler/balancer"
+ "bitrix_balancer_api/rest_base_service/types"
+ "errors"
+ "fmt"
+ "github.com/go-chi/chi/v5"
+ "github.com/go-chi/chi/v5/middleware"
+ "github.com/go-chi/cors"
+ "github.com/go-chi/httprate"
+ "github.com/sirupsen/logrus"
+ "log"
+ "net"
+ "net/http"
+ "time"
+)
+
+const (
+ readTimeout = 15 * time.Minute // Таймаут чтения
+ writeTimeout = 15 * time.Minute // Таймаут записи
+ idleTimeout = 15 * time.Minute // Таймаут бездействия
+ rateLimit = 25 // Лимит запросов
+ rateWindow = 1 * time.Second // Окно времени для лимита запросов
+)
+
+func main() {
+ // Получение конфигурации приложения
+ appConfig, clientsExternal, err := getClientsExternal()
+ if err != nil {
+ logrus.Error("error getting external clients", err)
+ return
+ }
+
+ // ** Инициализация модулей
+ ipc, err := initInternalProvider(appConfig, clientsExternal)
+ if err != nil {
+ logrus.Error("error initializing internal provider", err)
+ return
+ }
+
+ decreasePerSec := redismodule.QuotaDecreaseDefault
+ if appConfig.Bitrix.IsEnterprise {
+ decreasePerSec = redismodule.QuotaDecreaseEnterprise
+ }
+
+ go ipc.RedisClient.StartQuotaLeaker(ipc.Config.Bitrix.PortalID, decreasePerSec)
+
+ startRest(ipc)
+}
+
+func getClientsExternal() (*configcore.Config, clientcontrollers.ClientsExternal, error) {
+ options := &configcore.ConfigLoadOptions{
+ Redis: true,
+ Bitrix: true,
+ Secrets: true,
+ Server: configcore.ExposedServiceOptions{
+ RESTBaseService: true,
+ },
+ }
+
+ return clientcontrollers.ReturnClientsExternal(options)
+}
+
+func initInternalProvider(cfg *configcore.Config, clientsExternal clientcontrollers.ClientsExternal) (*types.InternalProviderControl, error) {
+ return &types.InternalProviderControl{
+ Config: cfg,
+ RedisClient: clientsExternal.Redis,
+ }, nil
+}
+
+// запуск сервера REST API
+func startRest(ipc *types.InternalProviderControl) {
+ router := chi.NewRouter()
+ corsOptions := cors.New(cors.Options{
+ AllowedOrigins: []string{"*"},
+ AllowedMethods: []string{http.MethodGet, http.MethodPost, http.MethodPut, http.MethodDelete, http.MethodOptions},
+ AllowedHeaders: []string{"Accept", "Authorization", "Content-Type", "Cache-Control", "X-Requested-With", "x-api"},
+ ExposedHeaders: []string{"Link", "Cache-Control"},
+ AllowCredentials: false,
+ MaxAge: 300, // Максимальное время жизни предварительных запросов в секундах
+ })
+
+ router.Use(corsOptions.Handler)
+ router.Use(middleware.RealIP)
+ // Глобальный перехват паник, чтобы сервис продолжал работать
+ router.Use(utilscore.RecoverMiddleware())
+ // Добавляем ограничение по IP
+ router.Use(httprate.LimitByIP(rateLimit, rateWindow))
+
+ // Регистрация обработчиков
+ err := registerRoutes(router, ipc)
+ if err != nil {
+ logrus.Error(err)
+ return
+ }
+
+ serverBind := ipc.Config.Server.RESTBaseService.BindRest
+ serverPort := ipc.Config.Server.RESTBaseService.PortRest
+ if serverBind == "" || serverPort == 0 {
+ log.Fatal(errors.New("rest_base_service: missed bind or port params"))
+ }
+ serverStartURI := fmt.Sprintf("%s:%d",
+ serverBind,
+ serverPort)
+
+ listener, err := net.Listen("tcp", serverStartURI)
+ if err != nil {
+ logrus.Error("🛑 error start listener: ", err)
+ log.Fatal(err)
+ }
+
+ httpServer := &http.Server{
+ Handler: router,
+ ReadTimeout: readTimeout,
+ WriteTimeout: writeTimeout,
+ IdleTimeout: idleTimeout,
+ }
+
+ log.Println("✅ Application initialized and started: ", serverStartURI)
+
+ if err := httpServer.Serve(listener); err != nil {
+ switch {
+ case errors.Is(err, http.ErrServerClosed):
+ logrus.Error("🛑 Server shutdown")
+ default:
+ log.Fatal(err)
+ }
+ }
+}
+
+// регистрирует маршруты
+func registerRoutes(router chi.Router, ipc *types.InternalProviderControl) error {
+ // Слайс обработчиков маршрутов
+ routeHandlers := []struct {
+ name string
+ handler func(chi.Router, *types.InternalProviderControl) error
+ }{
+ {"balancer_base", balancerhandler.RegisterBalancerRoutes},
+ }
+
+ // Регистрация всех маршрутов
+ for _, rh := range routeHandlers {
+ if errObj := rh.handler(router, ipc); errObj != nil {
+ logrus.Errorln("🔴 failed to register", rh.name, "routes:", errObj)
+ return fmt.Errorf("🔴 failed to register %s routes", rh.name)
+ }
+ }
+
+ // Вывод зарегистрированных маршрутов
+ if err := printRoutes(router); err != nil {
+ logrus.Errorln("🔴 failed to print routes:", err)
+ return fmt.Errorf("🔴 failed to print routes: %w", err)
+ }
+
+ return nil
+}
+
+func printRoutes(r chi.Router) error {
+ err := chi.Walk(r, func(method, route string, handler http.Handler, middlewares ...func(http.Handler) http.Handler) error {
+ return nil
+ })
+ if err != nil {
+ logrus.Error("failed to walk routes: ", err)
+ return err
+ }
+ return nil
+}
diff --git a/service/rest_base_service/docker_run.sh b/service/rest_base_service/docker_run.sh
new file mode 100644
index 0000000..579a7a2
--- /dev/null
+++ b/service/rest_base_service/docker_run.sh
@@ -0,0 +1,119 @@
+#!/bin/bash
+
+set -e
+trap 'echo "🔴 Скрипт остановлен"; exit' SIGINT
+
+# Должен ли порт быть доступен снаружи
+OPEN_PORT_EXTERNALLY="true"
+# Порт хоста
+HOST_PORT=15000
+# Наименование сервиса
+SERVICE_NAME="main_app"
+
+# Имя сети Docker
+DOCKER_NETWORK_NAME="networklocal1"
+# Список дополнительных сетей Docker, к которым нужно подключить контейнер
+ADDITIONAL_DOCKER_NETWORKS=""
+
+# IP-адрес для добавления в hosts контейнера
+DATABASE_HOST_IP=""
+
+W_BUILD="false"
+W_START="false"
+
+# Разбор именованных аргументов
+while [ $# -gt 0 ]; do
+ case "$1" in
+ OPEN_PORT_EXTERNALLY=*)
+ OPEN_PORT_EXTERNALLY="${1#*=}"
+ ;;
+ HOST_PORT=*)
+ HOST_PORT="${1#*=}"
+ ;;
+ SERVICE_NAME=*)
+ SERVICE_NAME="${1#*=}"
+ ;;
+ DOCKER_NETWORK_NAME=*)
+ DOCKER_NETWORK_NAME="${1#*=}"
+ ;;
+ DATABASE_HOST_IP=*)
+ DATABASE_HOST_IP="${1#*=}"
+ ;;
+ W_BUILD=*)
+ W_BUILD="${1#*=}"
+ ;;
+ W_START=*)
+ W_START="${1#*=}"
+ ;;
+ *)
+ echo "Ошибка: Неизвестный параметр $1" >&2
+ exit 1
+ ;;
+ esac
+ shift
+done
+
+
+# Наименование образа
+IMAGE_NAME="${SERVICE_NAME}_balancer_i"
+# Наименование контейнера
+CONTAINER_NAME="${SERVICE_NAME}_balancer_c"
+# Имя приложения
+APP_NAME="${SERVICE_NAME}_app"
+
+
+if [ "$W_BUILD" = "true" ]; then
+ # Билд бинарника
+ ./build.sh $APP_NAME
+
+ # Собираем образ
+ docker build --no-cache --build-arg APP_NAME=$APP_NAME -t $IMAGE_NAME .
+fi
+
+
+# Проверка и выполнение запуска контейнера
+if [ "$W_START" = "true" ]; then
+ # Останавливаем и удаляем существующий контейнер, если он существует
+ # Проверяем существование контейнера перед его остановкой и удалением
+ if docker ps -a --format "{{.Names}}" | grep -w "^$CONTAINER_NAME$"; then
+ docker stop $CONTAINER_NAME
+ docker rm $CONTAINER_NAME
+ fi
+
+ # Определяем, нужно ли открывать порт для внешнего мира
+ PORT_MAPPING=""
+ if [ "$OPEN_PORT_EXTERNALLY" = "true" ]; then
+ PORT_MAPPING="-p $HOST_PORT:$HOST_PORT"
+ fi
+
+ if [ -n "$DATABASE_HOST_IP" ]; then
+ ADD_HOST_OPTION="--add-host=database_host:$DATABASE_HOST_IP"
+ else
+ ADD_HOST_OPTION=""
+ fi
+
+ # Проверяем существование сети и создаем, если не существует
+ docker network ls | grep $DOCKER_NETWORK_NAME || docker network create $DOCKER_NETWORK_NAME
+
+ # Запускаем контейнер с новым образом в сетевом режиме host и подключаем к сети по имени
+ docker run -d \
+ $PORT_MAPPING \
+ $ADD_HOST_OPTION \
+ --network $DOCKER_NETWORK_NAME \
+ --restart always \
+ --name $CONTAINER_NAME \
+ -e APP_NAME=$APP_NAME \
+ $IMAGE_NAME
+
+ # Подключаем контейнер к дополнительным сетям Docker, если список не пустой
+ if [ -n "$ADDITIONAL_DOCKER_NETWORKS" ]; then
+ for network in $ADDITIONAL_DOCKER_NETWORKS; do
+ docker network connect $network $CONTAINER_NAME
+ echo "🟢 Container $CONTAINER_NAME is connected to additional network $network"
+ done
+ fi
+
+ echo "🟢 Container $CONTAINER_NAME is running on port $HOST_PORT"
+fi
+
+echo "🟢 Скрипт завершен $APP_NAME"
diff --git a/service/rest_base_service/go.mod b/service/rest_base_service/go.mod
new file mode 100644
index 0000000..ff46a19
--- /dev/null
+++ b/service/rest_base_service/go.mod
@@ -0,0 +1,27 @@
+module bitrix_balancer_api/rest_base_service
+
+go 1.25.6
+
+replace bitrix_balancer_api/core => ../../core
+
+require (
+ bitrix_balancer_api/core v0.0.0-00010101000000-000000000000
+ github.com/go-chi/chi/v5 v5.2.5
+ github.com/go-chi/cors v1.2.2
+ github.com/go-chi/httprate v0.15.0
+ github.com/sirupsen/logrus v1.9.4
+)
+
+require (
+ github.com/cespare/xxhash/v2 v2.3.0 // indirect
+ github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
+ github.com/google/uuid v1.6.0 // indirect
+ github.com/klauspost/cpuid/v2 v2.2.10 // indirect
+ github.com/mitchellh/mapstructure v1.5.0 // indirect
+ github.com/redis/go-redis/v9 v9.18.0 // indirect
+ github.com/shopspring/decimal v1.4.0 // indirect
+ github.com/zeebo/xxh3 v1.0.2 // indirect
+ go.uber.org/atomic v1.11.0 // indirect
+ golang.org/x/sys v0.41.0 // indirect
+ gopkg.in/yaml.v3 v3.0.1 // indirect
+)
diff --git a/service/rest_base_service/go.sum b/service/rest_base_service/go.sum
new file mode 100644
index 0000000..86b5998
--- /dev/null
+++ b/service/rest_base_service/go.sum
@@ -0,0 +1,46 @@
+github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs=
+github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c=
+github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA=
+github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0=
+github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
+github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
+github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
+github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
+github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78=
+github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc=
+github.com/go-chi/chi/v5 v5.2.5 h1:Eg4myHZBjyvJmAFjFvWgrqDTXFyOzjj7YIm3L3mu6Ug=
+github.com/go-chi/chi/v5 v5.2.5/go.mod h1:X7Gx4mteadT3eDOMTsXzmI4/rwUpOwBHLpAfupzFJP0=
+github.com/go-chi/cors v1.2.2 h1:Jmey33TE+b+rB7fT8MUy1u0I4L+NARQlK6LhzKPSyQE=
+github.com/go-chi/cors v1.2.2/go.mod h1:sSbTewc+6wYHBBCW7ytsFSn836hqM7JxpglAy2Vzc58=
+github.com/go-chi/httprate v0.15.0 h1:j54xcWV9KGmPf/X4H32/aTH+wBlrvxL7P+SdnRqxh5g=
+github.com/go-chi/httprate v0.15.0/go.mod h1:rzGHhVrsBn3IMLYDOZQsSU4fJNWcjui4fWKJcCId1R4=
+github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
+github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
+github.com/klauspost/cpuid/v2 v2.2.10 h1:tBs3QSyvjDyFTq3uoc/9xFpCuOsJQFNPiAhYdw2skhE=
+github.com/klauspost/cpuid/v2 v2.2.10/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0=
+github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY=
+github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo=
+github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
+github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
+github.com/redis/go-redis/v9 v9.18.0 h1:pMkxYPkEbMPwRdenAzUNyFNrDgHx9U+DrBabWNfSRQs=
+github.com/redis/go-redis/v9 v9.18.0/go.mod h1:k3ufPphLU5YXwNTUcCRXGxUoF1fqxnhFQmscfkCoDA0=
+github.com/shopspring/decimal v1.4.0 h1:bxl37RwXBklmTi0C79JfXCEBD1cqqHt0bbgBAGFp81k=
+github.com/shopspring/decimal v1.4.0/go.mod h1:gawqmDU56v4yIKSwfBSFip1HdCCXN8/+DMd9qYNcwME=
+github.com/sirupsen/logrus v1.9.4 h1:TsZE7l11zFCLZnZ+teH4Umoq5BhEIfIzfRDZ1Uzql2w=
+github.com/sirupsen/logrus v1.9.4/go.mod h1:ftWc9WdOfJ0a92nsE2jF5u5ZwH8Bv2zdeOC42RjbV2g=
+github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=
+github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
+github.com/zeebo/assert v1.3.0 h1:g7C04CbJuIDKNPFHmsk4hwZDO5O+kntRxzaUoNXj+IQ=
+github.com/zeebo/assert v1.3.0/go.mod h1:Pq9JiuJQpG8JLJdtkwrJESF0Foym2/D9XMU5ciN/wJ0=
+github.com/zeebo/xxh3 v1.0.2 h1:xZmwmqxHZA8AI603jOQ0tMqmBr9lPeFwGg6d+xy9DC0=
+github.com/zeebo/xxh3 v1.0.2/go.mod h1:5NWz9Sef7zIDm2JHfFlcQvNekmcEl9ekUZQQKCYaDcA=
+go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE=
+go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0=
+golang.org/x/sync v0.12.0 h1:MHc5BpPuC30uJk597Ri8TV3CNZcTLu6B6z4lJy+g6Jw=
+golang.org/x/sync v0.12.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA=
+golang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k=
+golang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
+gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
+gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
+gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
+gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
diff --git a/service/rest_base_service/handler/balancer/handler.go b/service/rest_base_service/handler/balancer/handler.go
new file mode 100644
index 0000000..dd88b50
--- /dev/null
+++ b/service/rest_base_service/handler/balancer/handler.go
@@ -0,0 +1,65 @@
+package balancerhandler
+
+import (
+ "bitrix_balancer_api/core/typescore"
+ "bitrix_balancer_api/rest_base_service/handler"
+ "context"
+ "fmt"
+ "net/http"
+ "time"
+)
+
+const (
+ quotaPollInterval = 2 * time.Second
+ quotaPollTimeout = 5 * time.Minute
+ bitrixPageSize = 50
+ maxSafetyPages = 500 // страховка: не более 25 000 записей за один вызов
+)
+
+// SendRequestHandler — POST /api/balancer/send
+// Принимает запрос, ждёт свободную квоту и проксирует в Bitrix24
+func (s *BalancerReg) SendRequestHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) {
+ var req typescore.BalancerRequest
+ if err := handler.ParseRequestBodyPost(r, &req); err != nil {
+ return nil, fmt.Errorf("invalid request body: %w", err)
+ }
+ if req.URL == nil || req.Method == nil {
+ return nil, fmt.Errorf("url and method are required")
+ }
+
+ quotaLimit, _ := quotaParams(s.ipc.Config.Bitrix.IsEnterprise)
+
+ ctx, cancel := context.WithTimeout(r.Context(), quotaPollTimeout)
+ defer cancel()
+
+ if req.IsRecurrent {
+ return s.sendRecurrentRequest(ctx, &req, quotaLimit)
+ }
+ return s.sendSingleRequest(ctx, &req, quotaLimit)
+}
+
+// GetQuotaHandler — GET /api/balancer/quota
+func (s *BalancerReg) GetQuotaHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) {
+ limit, decreasePerSec := quotaParams(s.ipc.Config.Bitrix.IsEnterprise)
+
+ ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)
+ defer cancel()
+
+ counter, err := s.ipc.RedisClient.GetQuotaCounter(ctx, s.ipc.Config.Bitrix.PortalID)
+ if err != nil {
+ return nil, fmt.Errorf("failed to get quota: %w", err)
+ }
+
+ freeSlots := limit - counter
+ if freeSlots < 0 {
+ freeSlots = 0
+ }
+
+ return &typescore.QuotaResponse{
+ PortalID: &s.ipc.Config.Bitrix.PortalID,
+ Counter: &counter,
+ Limit: &limit,
+ FreeSlots: &freeSlots,
+ DecreasePerSec: &decreasePerSec,
+ }, nil
+}
diff --git a/service/rest_base_service/handler/balancer/routes.go b/service/rest_base_service/handler/balancer/routes.go
new file mode 100644
index 0000000..2b0ad83
--- /dev/null
+++ b/service/rest_base_service/handler/balancer/routes.go
@@ -0,0 +1,30 @@
+package balancerhandler
+
+import (
+ "bitrix_balancer_api/rest_base_service/handler"
+ "bitrix_balancer_api/rest_base_service/types"
+ "github.com/go-chi/chi/v5"
+ "net/http"
+)
+
+type BalancerReg struct {
+ ipc *types.InternalProviderControl
+}
+
+func RegisterBalancerRoutes(
+ r chi.Router,
+ ipc *types.InternalProviderControl,
+) error {
+ s := &BalancerReg{
+ ipc: ipc,
+ }
+
+ r.Route("/api/balancer", func(r chi.Router) {
+ r.Use(handler.AccessCodeVerifier(ipc.Config))
+
+ handler.RegisterRoute(r, http.MethodPost, "/send", s.SendRequestHandler) // отправить запрос
+ handler.RegisterRoute(r, http.MethodGet, "/quota", s.GetQuotaHandler) // получить квоту
+ })
+
+ return nil
+}
diff --git a/service/rest_base_service/handler/balancer/utils.go b/service/rest_base_service/handler/balancer/utils.go
new file mode 100644
index 0000000..859bf3e
--- /dev/null
+++ b/service/rest_base_service/handler/balancer/utils.go
@@ -0,0 +1,229 @@
+package balancerhandler
+
+import (
+ redismodule "bitrix_balancer_api/core/lib/internally/redis"
+ "bitrix_balancer_api/core/typescore"
+ "bitrix_balancer_api/core/utilscore"
+ "bytes"
+ "context"
+ "encoding/json"
+ "fmt"
+ "github.com/sirupsen/logrus"
+ "io"
+ "net/http"
+ "time"
+)
+
+// sendSingleRequest — один запрос без пагинации
+func (s *BalancerReg) sendSingleRequest(
+ ctx context.Context,
+ req *typescore.BalancerRequest,
+ quotaLimit int64,
+) (interface{}, error) {
+ if err := s.waitForQuota(ctx, s.ipc.Config.Bitrix.PortalID, quotaLimit); err != nil {
+ return nil, fmt.Errorf("quota timeout: %w", err)
+ }
+
+ resp, err := s.proxyRequest(ctx, req)
+ if err != nil {
+ s.ipc.RedisClient.DecrementQuota(context.Background(), s.ipc.Config.Bitrix.PortalID, 1)
+ return nil, fmt.Errorf("proxy request failed: %w", err)
+ }
+
+ freeSlots, _ := s.ipc.RedisClient.GetFreeQuota(context.Background(), s.ipc.Config.Bitrix.PortalID, quotaLimit)
+ return &typescore.BalancerResponse{
+ StatusCode: utilscore.PointerToInt(resp.StatusCode),
+ Body: resp.Body,
+ QuotaLeft: &freeSlots,
+ }, nil
+}
+
+// sendRecurrentRequest — загружает ВСЕ записи постранично.
+// Крутит цикл пока Bitrix24 возвращает next, учитывая квоту перед каждым запросом.
+func (s *BalancerReg) sendRecurrentRequest(
+ ctx context.Context,
+ req *typescore.BalancerRequest,
+ quotaLimit int64,
+) (interface{}, error) {
+ allItems := make([]interface{}, 0)
+ start := 0
+
+ for page := 0; page < maxSafetyPages; page++ {
+ // Ждём свободную квоту перед каждым запросом
+ if err := s.waitForQuota(ctx, s.ipc.Config.Bitrix.PortalID, quotaLimit); err != nil {
+ return nil, fmt.Errorf("quota timeout on page %d: %w", page+1, err)
+ }
+
+ // Инжектируем start в тело
+ pageBody := make(map[string]interface{})
+ for k, v := range req.Body {
+ pageBody[k] = v
+ }
+ pageBody["start"] = start
+
+ pageReq := *req
+ pageReq.Body = pageBody
+
+ resp, err := s.proxyRequest(ctx, &pageReq)
+ if err != nil {
+ s.ipc.RedisClient.DecrementQuota(context.Background(), s.ipc.Config.Bitrix.PortalID, 1)
+ return nil, fmt.Errorf("proxy request failed on page %d: %w", page+1, err)
+ }
+
+ items, nextStart, err := extractPageItems(resp.Body, req.ResultKey)
+ if err != nil {
+ return nil, fmt.Errorf("failed to parse page %d: %w", page+1, err)
+ }
+
+ allItems = append(allItems, items...)
+
+ logrus.Infof("📦 recurrent fetch: page=%d start=%d got=%d total=%d",
+ page+1, start, len(items), len(allItems))
+
+ // Нет следующей страницы — все записи получены
+ if nextStart <= 0 || len(items) < bitrixPageSize {
+ break
+ }
+ start = nextStart
+ }
+
+ total := len(allItems)
+ freeSlots, _ := s.ipc.RedisClient.GetFreeQuota(context.Background(), s.ipc.Config.Bitrix.PortalID, quotaLimit)
+
+ return &typescore.BalancerResponse{
+ StatusCode: utilscore.PointerToInt(200),
+ Body: allItems,
+ QuotaLeft: &freeSlots,
+ IsRecurrent: true,
+ TotalFetched: &total,
+ }, nil
+}
+
+// waitForQuota блокирует выполнение пока не появится свободная квота.
+// Проверяет каждые 2 секунды согласно требованию.
+func (s *BalancerReg) waitForQuota(ctx context.Context, portalID string, limit int64) error {
+ for {
+ acquired, err := s.ipc.RedisClient.TryAcquireQuota(ctx, portalID, limit)
+ if err != nil {
+ return err
+ }
+ if acquired {
+ return nil
+ }
+
+ logrus.Infof("⏳ quota exhausted for portal %s, waiting %v...", portalID, quotaPollInterval)
+
+ select {
+ case <-ctx.Done():
+ return fmt.Errorf("quota wait timeout exceeded")
+ case <-time.After(quotaPollInterval):
+ // повторяем проверку
+ }
+ }
+}
+
+// proxyRequest выполняет реальный HTTP-запрос к Bitrix24
+func (s *BalancerReg) proxyRequest(ctx context.Context, req *typescore.BalancerRequest) (*proxyResult, error) {
+ if req.Body == nil || req.Method == nil || req.URL == nil {
+ return nil, fmt.Errorf("body or method or url is required")
+ }
+ var bodyReader io.Reader
+ if req.Body != nil && req.Method != nil && (*req.Method == http.MethodPost || *req.Method == http.MethodPut) {
+ bodyBytes, err := json.Marshal(req.Body)
+ if err != nil {
+ return nil, err
+ }
+ bodyReader = bytes.NewReader(bodyBytes)
+ }
+
+ httpReq, err := http.NewRequestWithContext(ctx, *req.Method, *req.URL, bodyReader)
+ if err != nil {
+ return nil, err
+ }
+
+ // Проставляем заголовки от клиента
+ for k, v := range req.Headers {
+ httpReq.Header.Set(k, v)
+ }
+ if req.Body != nil {
+ httpReq.Header.Set("Content-Type", "application/json")
+ }
+
+ client := &http.Client{Timeout: 30 * time.Second}
+ resp, err := client.Do(httpReq)
+ if err != nil {
+ return nil, err
+ }
+ defer resp.Body.Close()
+
+ respBytes, err := io.ReadAll(resp.Body)
+ if err != nil {
+ return nil, err
+ }
+
+ var respBody interface{}
+ if err := json.Unmarshal(respBytes, &respBody); err != nil {
+ // не JSON — возвращаем как строку
+ respBody = string(respBytes)
+ }
+
+ return &proxyResult{
+ StatusCode: resp.StatusCode,
+ Body: respBody,
+ }, nil
+}
+
+type proxyResult struct {
+ StatusCode int
+ Body interface{}
+}
+
+// quotaParams возвращает лимит и скорость декремента по тарифу
+func quotaParams(isEnterprise bool) (limit int64, decreasePerSec int64) {
+ if isEnterprise {
+ return redismodule.QuotaLimitEnterprise, redismodule.QuotaDecreaseEnterprise
+ }
+ return redismodule.QuotaLimitDefault, redismodule.QuotaDecreaseDefault
+}
+
+func extractPageItems(body interface{}, resultKey *string) ([]interface{}, int, error) {
+ bodyMap, ok := body.(map[string]interface{})
+ if !ok {
+ return nil, 0, fmt.Errorf("unexpected response format")
+ }
+
+ nextStart := 0
+ if nextVal, ok := bodyMap["next"]; ok {
+ switch v := nextVal.(type) {
+ case float64:
+ nextStart = int(v)
+ case int:
+ nextStart = v
+ }
+ }
+
+ resultRaw, ok := bodyMap["result"]
+ if !ok {
+ return nil, 0, fmt.Errorf("no 'result' field in response")
+ }
+
+ // Вложенный ключ — например "tasks" для tasks.task.list
+ if resultKey != nil && *resultKey != "" {
+ resultObj, ok := resultRaw.(map[string]interface{})
+ if !ok {
+ return nil, 0, fmt.Errorf("result is not an object, cannot use result_key '%s'", *resultKey)
+ }
+ nested, ok := resultObj[*resultKey]
+ if !ok {
+ return nil, 0, fmt.Errorf("result_key '%s' not found in result", *resultKey)
+ }
+ resultRaw = nested
+ }
+
+ items, ok := resultRaw.([]interface{})
+ if !ok {
+ return nil, 0, fmt.Errorf("result is not an array")
+ }
+
+ return items, nextStart, nil
+}
diff --git a/service/rest_base_service/handler/handler.go b/service/rest_base_service/handler/handler.go
new file mode 100644
index 0000000..407f86a
--- /dev/null
+++ b/service/rest_base_service/handler/handler.go
@@ -0,0 +1,131 @@
+package handler
+
+import (
+ "encoding/json"
+ "errors"
+ "github.com/go-chi/chi/v5"
+ "io"
+
+ "net/http"
+)
+
+// ErrorResponse структура для возврата ошибок
+type ErrorResponse struct {
+ ErrorCode int `json:"error_code"` // Код ошибки
+ ErrorDescription string `json:"error_description"` // Описание ошибки
+}
+
+// WrapHandlerParams структура для параметров обертки
+type WrapHandlerParams struct {
+ HandlerFunc func(http.ResponseWriter, *http.Request) (interface{}, error)
+}
+
+// responseWriterWrapper предотвращает повторный вызов WriteHeader
+type responseWriterWrapper struct {
+ http.ResponseWriter
+ wroteHeader bool
+}
+
+// WriteHeader перехватывает вызов WriteHeader
+func (rw *responseWriterWrapper) WriteHeader(statusCode int) {
+ if !rw.wroteHeader {
+ rw.ResponseWriter.WriteHeader(statusCode)
+ rw.wroteHeader = true
+ }
+}
+
+// Write перехватывает вызов Write
+func (rw *responseWriterWrapper) Write(b []byte) (int, error) {
+ if !rw.wroteHeader {
+ rw.WriteHeader(http.StatusOK) // Устанавливаем статус по умолчанию
+ }
+ return rw.ResponseWriter.Write(b)
+}
+
+// WrapHandlerF обертка для обработчиков
+func WrapHandlerF(p WrapHandlerParams) http.HandlerFunc {
+ return func(w http.ResponseWriter, r *http.Request) {
+ rw := &responseWriterWrapper{ResponseWriter: w}
+ payload, err := p.HandlerFunc(rw, r)
+ respondWithJSON(rw, err, payload)
+ }
+}
+
+// RegisterRoute вспомогательная функция для регистрации маршрутов
+func RegisterRoute(r chi.Router, method, path string, handlerFunc func(http.ResponseWriter, *http.Request) (interface{}, error)) {
+ wrappedHandler := WrapHandlerF(WrapHandlerParams{
+ HandlerFunc: handlerFunc,
+ })
+ switch method {
+ case http.MethodGet:
+ r.Get(path, wrappedHandler)
+ case http.MethodPost:
+ r.Post(path, wrappedHandler)
+ case http.MethodPatch:
+ r.Patch(path, wrappedHandler)
+ case http.MethodPut:
+ r.Put(path, wrappedHandler)
+ case http.MethodDelete:
+ r.Delete(path, wrappedHandler)
+ }
+}
+
+// ParseRequestBodyPost обрабатывает тело запроса и заполняет структуру запроса
+func ParseRequestBodyPost(r *http.Request, v interface{}) error {
+ defer r.Body.Close()
+
+ if r.ContentLength == 0 {
+ return errors.New("body content is empty")
+ }
+
+ body, err := io.ReadAll(r.Body)
+ if err != nil {
+ return err
+ }
+
+ if err := json.Unmarshal(body, v); err != nil {
+ return err
+ }
+
+ return nil
+}
+
+// respondWithJSON отправляет ответ в формате JSON
+func respondWithJSON(w http.ResponseWriter, err error, payload interface{}) {
+ w.Header().Set("Content-Type", "application/json")
+
+ var status int
+ var response []byte
+
+ if err != nil {
+ status = http.StatusInternalServerError
+ errorResponse := ErrorResponse{
+ ErrorCode: status,
+ ErrorDescription: err.Error(),
+ }
+ response, _ = json.Marshal(errorResponse)
+ } else {
+ response, err = json.Marshal(payload)
+ if err != nil {
+ status = http.StatusInternalServerError
+ errorResponse := ErrorResponse{
+ ErrorCode: status,
+ ErrorDescription: err.Error(),
+ }
+ response, _ = json.Marshal(errorResponse)
+ } else {
+ status = http.StatusOK
+ }
+ }
+
+ // Проверяем, является ли w нашим responseWriterWrapper
+ if rw, ok := w.(*responseWriterWrapper); ok {
+ if !rw.wroteHeader {
+ rw.WriteHeader(status)
+ }
+ } else {
+ w.WriteHeader(status)
+ }
+
+ _, _ = w.Write(response)
+}
diff --git a/service/rest_base_service/handler/middleware.go b/service/rest_base_service/handler/middleware.go
new file mode 100644
index 0000000..fa1f00f
--- /dev/null
+++ b/service/rest_base_service/handler/middleware.go
@@ -0,0 +1,76 @@
+package handler
+
+import (
+ configcore "bitrix_balancer_api/core/config"
+ "bitrix_balancer_api/core/utilscore"
+ "bitrix_balancer_api/core/variables"
+ "context"
+ "log"
+ "net/http"
+ "strconv"
+ "time"
+)
+
+// AccessCodeVerifier middleware для проверки API Signature для валидного клиента
+func AccessCodeVerifier(cfg *configcore.Config) func(http.Handler) http.Handler {
+ return func(next http.Handler) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if cfg.Secrets.ApiPublicBase == "" || cfg.Secrets.ApiPrivateBase == "" {
+ http.Error(w, "Servers secrets not configured", http.StatusInternalServerError)
+ return
+ }
+
+ authHeader := r.Header.Get("X-Signature")
+ timestampStr := r.Header.Get("X-Timestamp")
+
+ if authHeader == "" || timestampStr == "" {
+ http.Error(w, "Unauthorized client", http.StatusUnauthorized)
+ return
+ }
+
+ timestampUnix, err := strconv.ParseInt(timestampStr, 10, 64)
+ if err != nil {
+ http.Error(w, "Invalid timestamp", http.StatusBadRequest)
+ return
+ }
+
+ timestampTime := time.Unix(timestampUnix, 0).UTC()
+ now := time.Now().UTC()
+
+ timestampTimeRounded := time.Date(
+ timestampTime.Year(), timestampTime.Month(), timestampTime.Day(),
+ timestampTime.Hour(), timestampTime.Minute(), 0, 0, time.UTC,
+ )
+ nowRounded := time.Date(
+ now.Year(), now.Month(), now.Day(),
+ now.Hour(), now.Minute(), 0, 0, time.UTC,
+ )
+
+ threeMinutesAgo := nowRounded.Add(-3 * time.Minute)
+
+ if timestampTimeRounded.Before(threeMinutesAgo) {
+ log.Printf("Timestamp expired - received: %v (rounded: %v), current: %v (rounded: %v), 3min ago: %v",
+ timestampTime, timestampTimeRounded, now, nowRounded, threeMinutesAgo)
+ http.Error(w, "Timestamp expired", http.StatusUnauthorized)
+ return
+ }
+
+ if timestampTimeRounded.After(nowRounded) {
+ log.Printf("Timestamp in future - received: %v (rounded: %v), current: %v (rounded: %v)",
+ timestampTime, timestampTimeRounded, now, nowRounded)
+ http.Error(w, "Timestamp in future", http.StatusUnauthorized)
+ return
+ }
+
+ expectedSignature := utilscore.GenerateHMACSignature(cfg.Secrets.ApiPublicBase, timestampStr, cfg.Secrets.ApiPrivateBase)
+
+ if !utilscore.HmacEquals(expectedSignature, authHeader) {
+ http.Error(w, "Unauthorized client", http.StatusUnauthorized)
+ return
+ }
+
+ ctx := context.WithValue(r.Context(), variables.AccessContextKey, authHeader)
+ next.ServeHTTP(w, r.WithContext(ctx))
+ })
+ }
+}
diff --git a/service/rest_base_service/types/handler.go b/service/rest_base_service/types/handler.go
new file mode 100644
index 0000000..0ed334d
--- /dev/null
+++ b/service/rest_base_service/types/handler.go
@@ -0,0 +1,12 @@
+package types
+
+import (
+ "net/http"
+)
+
+// структура для представления маршрута с добавлением новых параметров
+type RouteParams struct {
+ Method string // метод запроса
+ Url string // url
+ HandlerFunc func(w http.ResponseWriter, r *http.Request) (interface{}, *uint64, error) // функция обработчик
+}
diff --git a/service/rest_base_service/types/types.go b/service/rest_base_service/types/types.go
new file mode 100644
index 0000000..eba2496
--- /dev/null
+++ b/service/rest_base_service/types/types.go
@@ -0,0 +1,12 @@
+package types
+
+import (
+ configcore "bitrix_balancer_api/core/config"
+ redismodule "bitrix_balancer_api/core/lib/internally/redis"
+)
+
+type InternalProviderControl struct {
+ Config *configcore.Config
+
+ RedisClient *redismodule.ModuleRedis
+}
diff --git a/service/system_service/.gitignore b/service/system_service/.gitignore
new file mode 100644
index 0000000..08d4983
--- /dev/null
+++ b/service/system_service/.gitignore
@@ -0,0 +1,5 @@
+.env
+system-service_app
+config.yml
+vendor
+app
\ No newline at end of file
diff --git a/service/system_service/.golangci.yml b/service/system_service/.golangci.yml
new file mode 100644
index 0000000..ea1405d
--- /dev/null
+++ b/service/system_service/.golangci.yml
@@ -0,0 +1,52 @@
+linters-settings:
+ errcheck: # Настройки для линтера errcheck, который проверяет, что ошибки не игнорируются
+ check-type-assertions: true # Не проверять утверждения типов на ошибки
+ check-blank: true # Проверять игнорирование ошибок через присваивание в _
+ prealloc: # Настройки для линтера prealloc, который предлагает предварительное выделение памяти для срезов
+ simple: true # Простой режим, предлагает предварительное выделение для простых циклов
+ range-loops: true # Предлагает предварительное выделение для циклов range
+ for-loops: false # Не предлагает предварительное выделение для обычных for-циклов
+ gocyclo: # Настройки для линтера gocyclo, который проверяет сложность функций
+ min-complexity: 15 # Установите порог сложности, который считаете приемлемым
+
+linters:
+ enable: # Список линтеров, которые будут включены
+ - noctx # Находит отправку HTTP-запроса без контекста.Контекст.
+ - protogetter # Сообщает о прямом чтении из полей прото-сообщения, когда следует использовать геттеры.
+ - reassign # Проверяет, что переменные пакета не переназначаются.
+ - rowserrcheck # Проверяет, успешно ли проверен Rows.Err строк.
+ - sqlclosecheck # Проверяет, что sql.Rows, sql.Stmt, sqlx.NamedStmt, pgx.Query закрыты.
+ - ineffassign # Обнаруживает, когда назначения существующим переменным не используются.
+ - nilerr # Находит код, который возвращает ноль, даже если он проверяет, что ошибка не равна нулю.
+ - makezero # Проверяет, что нулевые значения создаются правильно
+ - gochecksumtype # Проверяет, что тип контрольной суммы в go.sum соответствует содержимому
+ - copyloopvar # Проверяет, что циклические зависимости пакетов не имеют экспортируемых идентификаторов
+ - exhaustive # Проверьте полноту операторов перечисления.
+ - errchkjson # Проверяет типы, передаваемые функциям кодирования JSON. Сообщает о неподдерживаемых типах и событиях, при которых проверку возвращаемой ошибки можно опустить.
+ - durationcheck # Проверяет, что длительность таймаута не равна 0
+ - contextcheck # Проверяет, что контекст не игнорируется
+ - bodyclose # Проверяет, что тело запроса закрывается
+ - bidichk # Проверяет, что строки в исходном коде не содержат символов из разных языков
+ - govet # Проверяет код на наличие конструкций, которые могут быть ошибочными
+ - errcheck # Проверяет, что ошибки не игнорируются
+ - staticcheck # Статический анализ кода, находит ошибки, неэффективные конструкции и т.д.
+ - unused # Проверяет на неиспользуемые переменные, функции, константы
+ - gocritic # Линтер, основанный на проверке кода на соответствие определенным критериям качества и стиля
+ - stylecheck # Проверяет стиль кодирования
+ - whitespace # Проверяет проблемы с пробелами в коде
+ - gosec # Линтер gosec, который проверяет код на наличие потенциальных уязвимостей
+ - prealloc # Предлагает предварительное выделение памяти для срезов
+
+ - dupl # Находит дублирующийся код
+ - gocyclo # Проверяет сложность функций
+ - ineffassign # Обнаруживает неэффективные присваивания
+ - unparam # Находит неиспользуемые параметры функций
+
+ - gosimple # Предлагает упрощения кода
+
+ disable: # Список линтеров, которые будут отключены
+ - gofumpt # Более строгая версия gofmt, применяет дополнительные правила форматирования
+ # - golint # Отключает golint, который проверяет стиль написания кода на Go
+
+run:
+ timeout: 15m # Устанавливает тайм-аут для выполнения всех линтеров
\ No newline at end of file
diff --git a/service/system_service/Dockerfile b/service/system_service/Dockerfile
new file mode 100644
index 0000000..ef05f7e
--- /dev/null
+++ b/service/system_service/Dockerfile
@@ -0,0 +1,29 @@
+# Используем официальный образ Go для сборки приложения
+FROM golang:1.24.2 AS builder
+
+# Рабочая директория
+WORKDIR /app
+
+# Определяем аргумент сборки
+ARG APP_NAME
+RUN echo "APP_NAME=${APP_NAME}"
+
+# Копируем код внутрь контейнера
+COPY . .
+
+# Сборка приложения
+RUN go build -o ${APP_NAME} ./cmd/app.go
+
+# Создаём конечный образ на основе Ubuntu
+FROM kartashs/ubuntu:22.04
+
+WORKDIR /app
+
+# Определяем аргумент сборки
+ARG APP_NAME
+
+# Копируем собранное приложение из предыдущего образа
+COPY --from=builder /app/${APP_NAME} /app/${APP_NAME}
+
+# Запуск приложения
+CMD ["sh", "-c", "/app/${APP_NAME}"]
\ No newline at end of file
diff --git a/service/system_service/Dockerfile.serv b/service/system_service/Dockerfile.serv
new file mode 100644
index 0000000..9ca674f
--- /dev/null
+++ b/service/system_service/Dockerfile.serv
@@ -0,0 +1,38 @@
+# syntax=docker/dockerfile:1.4
+
+# Этап сборки
+FROM golang:1.24.5 AS builder
+
+# Принимаем аргументы сборки
+ARG GO_PAT
+ARG APP_NAME
+
+WORKDIR /app
+
+# Копируем исходники core и сервиса
+COPY core ./core
+COPY service/system_service ./service/system_service
+
+# Сборка приложения
+WORKDIR /app/service/system_service
+RUN go mod tidy && go vet ./... && gofmt -w ./
+RUN go build -o /app/${APP_NAME} ./cmd/app.go
+WORKDIR /app
+RUN chmod +x /app/${APP_NAME}
+
+# Финальный образ
+FROM kartashs/ubuntu:22.04
+
+WORKDIR /app
+
+# Принимаем APP_NAME в финальном слое и сохраняем как переменную окружения
+ARG APP_NAME
+ENV APP_NAME=${APP_NAME}
+
+# Копируем бинарник из builder-слоя
+COPY --from=builder /app/${APP_NAME} /app/${APP_NAME}
+
+RUN chmod +x /app/${APP_NAME}
+
+# Запуск приложения
+CMD ["sh", "-c", "/app/${APP_NAME}"]
\ No newline at end of file
diff --git a/service/system_service/cmd/app.go b/service/system_service/cmd/app.go
new file mode 100644
index 0000000..ed1a2bb
--- /dev/null
+++ b/service/system_service/cmd/app.go
@@ -0,0 +1,59 @@
+package main
+
+import (
+ configcore "bitrix_balancer_api/core/config"
+ clientcontrollers "bitrix_balancer_api/core/lib/internally/client-controllers"
+ workerjobs "bitrix_balancer_api/system_service/jobs"
+ "bitrix_balancer_api/system_service/types"
+ "errors"
+ "fmt"
+ "github.com/sirupsen/logrus"
+)
+
+func main() {
+ err := initService()
+ if err != nil {
+ logrus.Error(errors.New(fmt.Sprintf("failed to init service: %v", err)))
+ return
+ }
+ select {}
+}
+
+func initService() error {
+ clientsExternal, err := getClientsExternal()
+ if err != nil {
+ return errors.New(fmt.Sprintf("failed to load config: %v", err))
+ }
+
+ ipc, err := initInternalProvider(clientsExternal)
+ if err != nil {
+ return errors.New(fmt.Sprintf("🔴 failed to init internal provider: %v", err))
+ }
+ if ipc == nil {
+ return errors.New("failed to init internal provider: nil ipc")
+ }
+
+ // Запуск воркеров
+ err = workerjobs.WorkerJobsStart(ipc)
+ if err != nil {
+ return errors.New(fmt.Sprintf("failed to init workerjobs: %v", err))
+ }
+
+ return nil
+}
+
+func initInternalProvider(clientsExternal clientcontrollers.ClientsExternal) (*types.InternalProviderControl, error) {
+ return &types.InternalProviderControl{
+ Database: clientsExternal.DB,
+ Config: clientsExternal.Config,
+ RedisClient: clientsExternal.Redis,
+ }, nil
+}
+
+func getClientsExternal() (clientcontrollers.ClientsExternal, error) {
+ options := &configcore.ConfigLoadOptions{
+ Redis: true,
+ Database: true,
+ }
+ return clientcontrollers.ReturnClientsExternal(options)
+}
diff --git a/service/system_service/database_additionally/tables.go b/service/system_service/database_additionally/tables.go
new file mode 100644
index 0000000..53d2e3f
--- /dev/null
+++ b/service/system_service/database_additionally/tables.go
@@ -0,0 +1,2 @@
+package database_additionally
+
diff --git a/service/system_service/go.mod b/service/system_service/go.mod
new file mode 100644
index 0000000..7047d1e
--- /dev/null
+++ b/service/system_service/go.mod
@@ -0,0 +1,17 @@
+module bitrix_balancer_api/system_service
+
+go 1.25.6
+
+replace bitrix_balancer_api/core => ../../core
+
+require (
+ github.com/sirupsen/logrus v1.9.4
+ gorm.io/gorm v1.31.1
+)
+
+require (
+ github.com/jinzhu/inflection v1.0.0 // indirect
+ github.com/jinzhu/now v1.1.5 // indirect
+ golang.org/x/sys v0.13.0 // indirect
+ golang.org/x/text v0.20.0 // indirect
+)
diff --git a/service/system_service/go.sum b/service/system_service/go.sum
new file mode 100644
index 0000000..90740e3
--- /dev/null
+++ b/service/system_service/go.sum
@@ -0,0 +1,20 @@
+github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
+github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
+github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
+github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
+github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ=
+github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
+github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
+github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
+github.com/sirupsen/logrus v1.9.4 h1:TsZE7l11zFCLZnZ+teH4Umoq5BhEIfIzfRDZ1Uzql2w=
+github.com/sirupsen/logrus v1.9.4/go.mod h1:ftWc9WdOfJ0a92nsE2jF5u5ZwH8Bv2zdeOC42RjbV2g=
+github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=
+github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
+golang.org/x/sys v0.13.0 h1:Af8nKPmuFypiUBjVoU9V20FiaFXOcuZI21p0ycVYYGE=
+golang.org/x/sys v0.13.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
+golang.org/x/text v0.20.0 h1:gK/Kv2otX8gz+wn7Rmb3vT96ZwuoxnQlY+HlJVj7Qug=
+golang.org/x/text v0.20.0/go.mod h1:D4IsuqiFMhST5bX19pQ9ikHC2GsaKyk/oF+pn3ducp4=
+gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
+gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
+gorm.io/gorm v1.31.1 h1:7CA8FTFz/gRfgqgpeKIBcervUn3xSyPUmr6B2WXJ7kg=
+gorm.io/gorm v1.31.1/go.mod h1:XyQVbO2k6YkOis7C2437jSit3SsDK72s7n7rsSHd+Gs=
diff --git a/service/system_service/jobs/init.go b/service/system_service/jobs/init.go
new file mode 100644
index 0000000..b92ddc9
--- /dev/null
+++ b/service/system_service/jobs/init.go
@@ -0,0 +1,24 @@
+package workerjobs
+
+import (
+ "bitrix_balancer_api/system_service/types"
+ "github.com/sirupsen/logrus"
+)
+
+type WorkerJobs struct {
+ ipc *types.InternalProviderControl
+}
+
+func WorkerJobsStart(ipc *types.InternalProviderControl) error {
+ jobs := &WorkerJobs{
+ ipc: ipc,
+ }
+
+ err := jobs.ipc.Database.Migrate().MigrateDB()
+ if err != nil {
+ return err
+ }
+ logrus.Info("🟢🟢🟢 Database migration completed successfully")
+
+ return nil
+}
diff --git a/service/system_service/start.sh b/service/system_service/start.sh
new file mode 100755
index 0000000..d928bba
--- /dev/null
+++ b/service/system_service/start.sh
@@ -0,0 +1,49 @@
+#!/bin/bash
+
+set -e
+trap 'echo "🔴 Скрипт остановлен"; exit' SIGINT
+
+# Имя сети Docker
+DOCKER_NETWORK_NAME="networklocal1"
+# Наименование сервиса
+SERVICE_NAME="ruspet_system_service"
+
+# Наименование образа
+IMAGE_NAME="${SERVICE_NAME}_i"
+# Наименование контейнера
+CONTAINER_NAME="${SERVICE_NAME}_c"
+# Имя приложения
+APP_NAME="${SERVICE_NAME}_app"
+
+
+# Останавливаем и удаляем старый контейнер, если он существует
+if [ "$(docker ps -q -f name=$CONTAINER_NAME)" ]; then
+ docker stop $CONTAINER_NAME
+ docker rm $CONTAINER_NAME
+fi
+
+# Удаляем старый образ, если он существует
+if [ "$(docker images -q $IMAGE_NAME)" ]; then
+ docker rmi $IMAGE_NAME
+fi
+
+# Создаем директорию vendor с зависимостями
+go mod tidy
+rm -rf vendor
+go mod vendor
+
+# Проверяем существование сети и создаем, если не существует
+docker network ls | grep $DOCKER_NETWORK_NAME || docker network create $DOCKER_NETWORK_NAME
+
+# Собираем образ
+docker build --build-arg APP_NAME=$APP_NAME -t $IMAGE_NAME .
+
+# Запускаем контейнер с новым образом в сетевом режиме host и подключаем к сети по имени
+docker run -d \
+ --add-host=rmq_host:192.168.1.102 \
+ --network $DOCKER_NETWORK_NAME \
+ --restart always \
+ --name $CONTAINER_NAME \
+ -e APP_NAME=$APP_NAME \
+ --add-host=database_host:192.168.0.15 \
+ $IMAGE_NAME
\ No newline at end of file
diff --git a/service/system_service/types/types.go b/service/system_service/types/types.go
new file mode 100644
index 0000000..3f60a73
--- /dev/null
+++ b/service/system_service/types/types.go
@@ -0,0 +1,15 @@
+package types
+
+import (
+ configcore "bitrix_balancer_api/core/config"
+ database "bitrix_balancer_api/core/db"
+ "bitrix_balancer_api/core/lib/external/telegram"
+ redismodule "bitrix_balancer_api/core/lib/internally/redis"
+)
+
+type InternalProviderControl struct {
+ Config *configcore.Config
+ RedisClient *redismodule.ModuleRedis
+ TGBotClient *telegram.TgBotClient
+ Database *database.ModuleDB
+}
diff --git a/service/system_service/version b/service/system_service/version
new file mode 100644
index 0000000..aa6e22c
--- /dev/null
+++ b/service/system_service/version
@@ -0,0 +1 @@
+v-0.0.2
\ No newline at end of file
diff --git a/service/telegram_service/.DS_Store b/service/telegram_service/.DS_Store
new file mode 100644
index 0000000..d9998a3
Binary files /dev/null and b/service/telegram_service/.DS_Store differ
diff --git a/service/telegram_service/.gitignore b/service/telegram_service/.gitignore
new file mode 100644
index 0000000..9d1be24
--- /dev/null
+++ b/service/telegram_service/.gitignore
@@ -0,0 +1,5 @@
+.env
+telegram-service_app
+config.yml
+vendor
+app
\ No newline at end of file
diff --git a/service/telegram_service/.golangci.yml b/service/telegram_service/.golangci.yml
new file mode 100644
index 0000000..ea1405d
--- /dev/null
+++ b/service/telegram_service/.golangci.yml
@@ -0,0 +1,52 @@
+linters-settings:
+ errcheck: # Настройки для линтера errcheck, который проверяет, что ошибки не игнорируются
+ check-type-assertions: true # Не проверять утверждения типов на ошибки
+ check-blank: true # Проверять игнорирование ошибок через присваивание в _
+ prealloc: # Настройки для линтера prealloc, который предлагает предварительное выделение памяти для срезов
+ simple: true # Простой режим, предлагает предварительное выделение для простых циклов
+ range-loops: true # Предлагает предварительное выделение для циклов range
+ for-loops: false # Не предлагает предварительное выделение для обычных for-циклов
+ gocyclo: # Настройки для линтера gocyclo, который проверяет сложность функций
+ min-complexity: 15 # Установите порог сложности, который считаете приемлемым
+
+linters:
+ enable: # Список линтеров, которые будут включены
+ - noctx # Находит отправку HTTP-запроса без контекста.Контекст.
+ - protogetter # Сообщает о прямом чтении из полей прото-сообщения, когда следует использовать геттеры.
+ - reassign # Проверяет, что переменные пакета не переназначаются.
+ - rowserrcheck # Проверяет, успешно ли проверен Rows.Err строк.
+ - sqlclosecheck # Проверяет, что sql.Rows, sql.Stmt, sqlx.NamedStmt, pgx.Query закрыты.
+ - ineffassign # Обнаруживает, когда назначения существующим переменным не используются.
+ - nilerr # Находит код, который возвращает ноль, даже если он проверяет, что ошибка не равна нулю.
+ - makezero # Проверяет, что нулевые значения создаются правильно
+ - gochecksumtype # Проверяет, что тип контрольной суммы в go.sum соответствует содержимому
+ - copyloopvar # Проверяет, что циклические зависимости пакетов не имеют экспортируемых идентификаторов
+ - exhaustive # Проверьте полноту операторов перечисления.
+ - errchkjson # Проверяет типы, передаваемые функциям кодирования JSON. Сообщает о неподдерживаемых типах и событиях, при которых проверку возвращаемой ошибки можно опустить.
+ - durationcheck # Проверяет, что длительность таймаута не равна 0
+ - contextcheck # Проверяет, что контекст не игнорируется
+ - bodyclose # Проверяет, что тело запроса закрывается
+ - bidichk # Проверяет, что строки в исходном коде не содержат символов из разных языков
+ - govet # Проверяет код на наличие конструкций, которые могут быть ошибочными
+ - errcheck # Проверяет, что ошибки не игнорируются
+ - staticcheck # Статический анализ кода, находит ошибки, неэффективные конструкции и т.д.
+ - unused # Проверяет на неиспользуемые переменные, функции, константы
+ - gocritic # Линтер, основанный на проверке кода на соответствие определенным критериям качества и стиля
+ - stylecheck # Проверяет стиль кодирования
+ - whitespace # Проверяет проблемы с пробелами в коде
+ - gosec # Линтер gosec, который проверяет код на наличие потенциальных уязвимостей
+ - prealloc # Предлагает предварительное выделение памяти для срезов
+
+ - dupl # Находит дублирующийся код
+ - gocyclo # Проверяет сложность функций
+ - ineffassign # Обнаруживает неэффективные присваивания
+ - unparam # Находит неиспользуемые параметры функций
+
+ - gosimple # Предлагает упрощения кода
+
+ disable: # Список линтеров, которые будут отключены
+ - gofumpt # Более строгая версия gofmt, применяет дополнительные правила форматирования
+ # - golint # Отключает golint, который проверяет стиль написания кода на Go
+
+run:
+ timeout: 15m # Устанавливает тайм-аут для выполнения всех линтеров
\ No newline at end of file
diff --git a/service/telegram_service/Dockerfile b/service/telegram_service/Dockerfile
new file mode 100644
index 0000000..ef05f7e
--- /dev/null
+++ b/service/telegram_service/Dockerfile
@@ -0,0 +1,29 @@
+# Используем официальный образ Go для сборки приложения
+FROM golang:1.24.2 AS builder
+
+# Рабочая директория
+WORKDIR /app
+
+# Определяем аргумент сборки
+ARG APP_NAME
+RUN echo "APP_NAME=${APP_NAME}"
+
+# Копируем код внутрь контейнера
+COPY . .
+
+# Сборка приложения
+RUN go build -o ${APP_NAME} ./cmd/app.go
+
+# Создаём конечный образ на основе Ubuntu
+FROM kartashs/ubuntu:22.04
+
+WORKDIR /app
+
+# Определяем аргумент сборки
+ARG APP_NAME
+
+# Копируем собранное приложение из предыдущего образа
+COPY --from=builder /app/${APP_NAME} /app/${APP_NAME}
+
+# Запуск приложения
+CMD ["sh", "-c", "/app/${APP_NAME}"]
\ No newline at end of file
diff --git a/service/telegram_service/Dockerfile.serv b/service/telegram_service/Dockerfile.serv
new file mode 100644
index 0000000..ef32672
--- /dev/null
+++ b/service/telegram_service/Dockerfile.serv
@@ -0,0 +1,38 @@
+# syntax=docker/dockerfile:1.4
+
+# Этап сборки
+FROM golang:1.24.5 AS builder
+
+# Принимаем аргументы сборки
+ARG GO_PAT
+ARG APP_NAME
+
+WORKDIR /app
+
+# Копируем исходники core и сервиса
+COPY core ./core
+COPY service/telegram_service ./service/telegram_service
+
+# Сборка приложения
+WORKDIR /app/service/telegram_service
+RUN go mod tidy && go vet ./... && gofmt -w ./
+RUN go build -o /app/${APP_NAME} ./cmd/app.go
+WORKDIR /app
+RUN chmod +x /app/${APP_NAME}
+
+# Финальный образ
+FROM kartashs/ubuntu:22.04
+
+WORKDIR /app
+
+# Принимаем APP_NAME в финальном слое и сохраняем как переменную окружения
+ARG APP_NAME
+ENV APP_NAME=${APP_NAME}
+
+# Копируем бинарник из builder-слоя
+COPY --from=builder /app/${APP_NAME} /app/${APP_NAME}
+
+RUN chmod +x /app/${APP_NAME}
+
+# Запуск приложения
+CMD ["sh", "-c", "/app/${APP_NAME}"]
\ No newline at end of file
diff --git a/service/telegram_service/approvalflow/flow.go b/service/telegram_service/approvalflow/flow.go
new file mode 100644
index 0000000..6a6b2b7
--- /dev/null
+++ b/service/telegram_service/approvalflow/flow.go
@@ -0,0 +1,31 @@
+package approvalflow
+
+// FlowNode — узел дерева навигации.
+type FlowNode struct {
+ Key string
+ Label string
+ Children []*FlowNode
+ IsInput bool
+ InputKey string
+ InputHint string
+ DataKey string
+ DataValue string
+ IsFileInput bool
+}
+
+// FindNode ищет узел по ключу (BFS).
+func FindNode(root *FlowNode, key string) *FlowNode {
+ if root == nil {
+ return nil
+ }
+ queue := []*FlowNode{root}
+ for len(queue) > 0 {
+ node := queue[0]
+ queue = queue[1:]
+ if node.Key == key {
+ return node
+ }
+ queue = append(queue, node.Children...)
+ }
+ return nil
+}
diff --git a/service/telegram_service/approvalflow/topic.go b/service/telegram_service/approvalflow/topic.go
new file mode 100644
index 0000000..7048bb8
--- /dev/null
+++ b/service/telegram_service/approvalflow/topic.go
@@ -0,0 +1,14 @@
+package approvalflow
+
+import "bitrix_balancer_api/core/typescore"
+
+// Topic — интерфейс каждой темы согласования.
+// Чтобы добавить новую тему: реализовать этот интерфейс и добавить
+// одну строку в handlers/approval/registry.go → registerAll().
+type Topic interface {
+ Code() string
+ Name() string
+ BuildTree() *FlowNode
+ FormatApproverMessage(initiator *typescore.User, collected map[string]string) string
+ TopicCodeFromCollected(collected map[string]string) (string, error)
+}
diff --git a/service/telegram_service/cmd/app.go b/service/telegram_service/cmd/app.go
new file mode 100644
index 0000000..be27840
--- /dev/null
+++ b/service/telegram_service/cmd/app.go
@@ -0,0 +1,81 @@
+package main
+
+import (
+ configcore "bitrix_balancer_api/core/config"
+ "bitrix_balancer_api/core/lib/external/telegram"
+ clientcontrollers "bitrix_balancer_api/core/lib/internally/client-controllers"
+ tgupdatehandler "bitrix_balancer_api/telegram_service/common/update"
+ "bitrix_balancer_api/telegram_service/scheduler"
+ "bitrix_balancer_api/telegram_service/types"
+ "log"
+ "runtime/debug"
+)
+
+func main() {
+ err := initService()
+ if err != nil {
+ log.Println("🔴 failed to init service: ", err)
+ }
+ select {}
+}
+
+func initService() error {
+ // Получение конфигурации приложения
+ clientsExternal, err := getClientsExternal()
+ if err != nil {
+ return err
+ }
+
+ ipc, err := initInternalProvider(clientsExternal.Config, clientsExternal)
+ if err != nil {
+ return err
+ }
+
+ delegationChecker := scheduler.NewDelegationChecker(ipc)
+ delegationChecker.Start()
+
+ update := tgupdatehandler.NewUpdateHandler(ipc)
+ go func() {
+ defer handlePanic("update.GetUpdateTelegram goroutine") // Обработка паник в горутине
+ update.GetUpdateTelegram()
+ }()
+
+ return nil
+}
+
+func getClientsExternal() (clientcontrollers.ClientsExternal, error) {
+ options := &configcore.ConfigLoadOptions{
+ Redis: true,
+ Database: true,
+ Telegram: true,
+ Server: configcore.ExposedServiceOptions{
+ TelegramService: true,
+ },
+ }
+
+ return clientcontrollers.ReturnClientsExternal(options)
+}
+
+func initInternalProvider(cfg *configcore.Config, clientsExternal clientcontrollers.ClientsExternal) (*types.InternalProviderControl, error) {
+ tgBotClient, err := telegram.NewTgBotClient(&telegram.BotConfig{
+ BotKey: cfg.Telegram.BotToken,
+ })
+ if err != nil {
+ return nil, err
+ }
+
+ return &types.InternalProviderControl{
+ Config: cfg,
+ Database: clientsExternal.DB,
+ RedisClient: clientsExternal.Redis,
+ TGBotClient: tgBotClient,
+ }, nil
+}
+
+// handlePanic перехватывает паники и логирует их
+func handlePanic(context string) {
+ if r := recover(); r != nil {
+ log.Printf("🚨 Panic recovered in %s: %v", context, r)
+ log.Printf("🚨 Stack trace:\n%s", debug.Stack())
+ }
+}
diff --git a/service/telegram_service/common/.DS_Store b/service/telegram_service/common/.DS_Store
new file mode 100644
index 0000000..18f45ef
Binary files /dev/null and b/service/telegram_service/common/.DS_Store differ
diff --git a/service/telegram_service/common/update/0_init.go b/service/telegram_service/common/update/0_init.go
new file mode 100644
index 0000000..e0f84b4
--- /dev/null
+++ b/service/telegram_service/common/update/0_init.go
@@ -0,0 +1,77 @@
+package tgupdatehandler
+
+import (
+ "bitrix_balancer_api/core/typescore"
+ "bitrix_balancer_api/telegram_service/handlers/approval"
+ "bitrix_balancer_api/telegram_service/handlers/faq"
+ "bitrix_balancer_api/telegram_service/handlers/start"
+ "bitrix_balancer_api/telegram_service/types"
+ "context"
+ tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
+ "github.com/sirupsen/logrus"
+ "log"
+ "time"
+)
+
+type UpdateHandler struct {
+ ipc *types.InternalProviderControl
+ approvalHandler *approval.Handler
+ startHandler *start.Handler
+ faqHandler *faq.HandlerFAQ
+}
+
+func NewUpdateHandler(ipc *types.InternalProviderControl) *UpdateHandler {
+ if ipc == nil {
+ log.Println("🔴 error: ipc is nil")
+ return nil
+ }
+
+ approvalHandler := approval.NewHandler(ipc)
+
+ handler := &UpdateHandler{
+ ipc: ipc,
+ approvalHandler: approvalHandler,
+ startHandler: start.NewHandler(ipc, approvalHandler),
+ faqHandler: faq.NewHandler(ipc),
+ }
+
+ // TODO: вызывается только после обновлений
+ //go handler.broadcastBotUpdated()
+
+ return handler
+}
+
+func (s *UpdateHandler) broadcastBotUpdated() {
+ ctx := context.Background()
+ bot := s.ipc.TGBotClient.GetBot()
+
+ users, _, err := s.ipc.Database.User.GetUsersListDB(ctx, typescore.ListDbOptions{})
+ if err != nil {
+ logrus.Errorf("broadcastBotUpdated: GetUsersListDB err=%v", err)
+ return
+ }
+
+ text := "🔄 Бот был обновлён!\n\n" +
+ "Нажмите кнопку ниже чтобы перезапустить бота:"
+
+ keyboard := tgbotapi.NewInlineKeyboardMarkup(
+ tgbotapi.NewInlineKeyboardRow(
+ tgbotapi.NewInlineKeyboardButtonData("🚀 Перезапустить бота", "restart_bot"),
+ ),
+ )
+
+ for _, user := range users {
+ if user.TelegramID == nil {
+ continue
+ }
+ msg := tgbotapi.NewMessage(*user.TelegramID, text)
+ msg.ParseMode = "HTML"
+ msg.ReplyMarkup = keyboard
+ if _, err := bot.Send(msg); err != nil {
+ logrus.Warnf("broadcastBotUpdated: Send to telegramID=%d err=%v", *user.TelegramID, err)
+ }
+ time.Sleep(50 * time.Millisecond)
+ }
+
+ logrus.Infof("broadcastBotUpdated: отправлено %d пользователям", len(users))
+}
diff --git a/service/telegram_service/common/update/callback.go b/service/telegram_service/common/update/callback.go
new file mode 100644
index 0000000..b48d318
--- /dev/null
+++ b/service/telegram_service/common/update/callback.go
@@ -0,0 +1,392 @@
+package tgupdatehandler
+
+import (
+ "bitrix_balancer_api/telegram_service/keyboard"
+ "context"
+ "fmt"
+ tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
+ "github.com/sirupsen/logrus"
+ "strconv"
+ "strings"
+ "time"
+)
+
+func (s *UpdateHandler) handleCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery) {
+ data := cq.Data
+
+ switch {
+ case strings.HasPrefix(data, "appr:"):
+ parts := strings.SplitN(data, ":", 3)
+ if len(parts) != 3 {
+ return
+ }
+ s.approvalHandler.HandleCallback(bot, cq, parts[1], parts[2])
+
+ case strings.HasPrefix(data, "task_complete:"):
+ taskID := parseID(data, "task_complete:")
+ s.approvalHandler.HandleCompleteTask(bot, cq, taskID)
+
+ case strings.HasPrefix(data, "appr_yes:"):
+ approvalID := parseID(data, "appr_yes:")
+ logrus.Infof("handleCallback: appr_yes approvalID=%d", approvalID)
+ s.approvalHandler.HandleDecision(bot, cq, approvalID, true, "")
+
+ case strings.HasPrefix(data, "appr_stage:"):
+ approvalID := parseID(data, "appr_stage:")
+ logrus.Infof("handleCallback: appr_stage approvalID=%d", approvalID)
+ s.approvalHandler.HandleApprovalStages(bot, cq, approvalID)
+
+ // ── ОТКАЗ — специфичные ПЕРЕД общим ────────────────────────
+ case strings.HasPrefix(data, "appr_no_comment:"):
+ approvalID := parseID(data, "appr_no_comment:")
+ s.handleApprovalRejectStart(bot, cq, approvalID)
+
+ case strings.HasPrefix(data, "appr_no_defer:"):
+ approvalID := parseID(data, "appr_no_defer:")
+ s.approvalHandler.HandlePendingDeferCallback(bot, cq, approvalID, "reject")
+
+ case strings.HasPrefix(data, "appr_no_skip:"):
+ approvalID := parseID(data, "appr_no_skip:")
+ ctx := context.Background()
+ rejectKey := fmt.Sprintf("appr_reject_pending:%d", cq.From.ID)
+ s.ipc.RedisClient.Del(ctx, rejectKey) //nolint:errcheck
+ s.approvalHandler.HandleDecision(bot, cq, approvalID, false, "")
+ s.approvalHandler.States.RemovePendingComment(ctx, cq.From.ID, approvalID) //nolint:errcheck
+
+ // Общий — после специфичных
+ case strings.HasPrefix(data, "appr_no:"):
+ approvalID := parseID(data, "appr_no:")
+ bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck
+ bot.Request(tgbotapi.NewDeleteMessage(cq.Message.Chat.ID, cq.Message.MessageID)) //nolint:errcheck
+ msg := tgbotapi.NewMessage(cq.Message.Chat.ID, fmt.Sprintf("❌ Заявка #%d — выберите действие:", approvalID))
+ msg.ParseMode = "HTML"
+ msg.ReplyMarkup = keyboard.BuildRejectOptions(approvalID)
+ bot.Send(msg) //nolint:errcheck
+
+ // ── ОТЗЫВ — специфичные ПЕРЕД общим ────────────────────────
+ case strings.HasPrefix(data, "appr_revoke_comment:"):
+ approvalID := parseID(data, "appr_revoke_comment:")
+ s.handleRevokeStart(bot, cq, approvalID)
+
+ case strings.HasPrefix(data, "appr_revoke_defer:"):
+ approvalID := parseID(data, "appr_revoke_defer:")
+ s.approvalHandler.HandlePendingDeferCallback(bot, cq, approvalID, "revoke")
+
+ case strings.HasPrefix(data, "appr_revoke_skip:"):
+ approvalID := parseID(data, "appr_revoke_skip:")
+ ctx := context.Background()
+ bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck
+ s.approvalHandler.HandleRevokeWithComment(bot, cq.Message.Chat.ID, cq.From.ID, approvalID, "")
+ s.approvalHandler.States.RemovePendingComment(ctx, cq.From.ID, approvalID) //nolint:errcheck
+
+ // Общий — после специфичных
+ case strings.HasPrefix(data, "appr_revoke:"):
+ approvalID := parseID(data, "appr_revoke:")
+ bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck
+ bot.Request(tgbotapi.NewDeleteMessage(cq.Message.Chat.ID, cq.Message.MessageID)) //nolint:errcheck
+ msg := tgbotapi.NewMessage(cq.Message.Chat.ID, fmt.Sprintf("↩️ Заявка #%d — выберите действие:", approvalID))
+ msg.ParseMode = "HTML"
+ msg.ReplyMarkup = keyboard.BuildRevokeOptions(approvalID)
+ bot.Send(msg) //nolint:errcheck
+
+ // ── ОТЛОЖЕННЫЕ ──────────────────────────────────────────────
+ case strings.HasPrefix(data, "pending_item:"):
+ approvalID := parseID(data, "pending_item:")
+ s.approvalHandler.HandlePendingItemCallback(bot, cq, approvalID)
+
+ case data == "pending_back":
+ s.approvalHandler.HandlePendingBackCallback(bot, cq)
+
+ // ── НАБЛЮДАТЕЛЬ ─────────────────────────────────────────────
+ case strings.HasPrefix(data, "obs_topic:"):
+ topicCode := strings.TrimPrefix(data, "obs_topic:")
+ s.approvalHandler.HandleObserverTopicCallback(bot, cq, topicCode)
+
+ case strings.HasPrefix(data, "obs_approval:"):
+ approvalID := parseID(data, "obs_approval:")
+ s.approvalHandler.HandleObserverApprovalCallback(bot, cq, approvalID)
+
+ case strings.HasPrefix(data, "obs_remind:"):
+ approvalID := parseID(data, "obs_remind:")
+ s.approvalHandler.HandleObserverReminderCallback(bot, cq, approvalID)
+
+ case strings.HasPrefix(data, "obs_back:"):
+ topicCode := strings.TrimPrefix(data, "obs_back:")
+ s.approvalHandler.HandleObserverBackToTopic(bot, cq, topicCode)
+
+ case data == "obs_back_topics":
+ s.approvalHandler.HandleObserverBackToTopics(bot, cq)
+
+ // ── УПРАВЛЕНИЕ ФАЙЛАМИ ──────────────────────────────────────
+ case strings.HasPrefix(data, "appr_file_detach:"):
+ indexStr := strings.TrimPrefix(data, "appr_file_detach:")
+ index, err := strconv.Atoi(indexStr)
+ if err != nil {
+ logrus.Warnf("handleCallback: bad detach index %q", indexStr)
+ bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck
+ return
+ }
+ bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck
+ // НЕ удаляем сообщение — это делает showFileStatus
+ s.approvalHandler.HandleDetachFile(bot, cq.Message.Chat.ID, int64(cq.From.ID), index)
+
+ case strings.HasPrefix(data, "appr_file_submit:"):
+ bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck
+ s.approvalHandler.HandleSubmitFiles(bot, cq.Message.Chat.ID, int64(cq.From.ID), true)
+
+ case strings.HasPrefix(data, "appr_file_skip:"):
+ bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck
+ s.approvalHandler.HandleSubmitFiles(bot, cq.Message.Chat.ID, int64(cq.From.ID), false)
+
+ // ── НАВИГАЦИЯ ФЛОУ ──────────────────────────────────────────
+ case strings.HasPrefix(data, "appr_back:"):
+ topicCode := strings.TrimPrefix(data, "appr_back:")
+ s.approvalHandler.HandleBackCallback(bot, cq, topicCode)
+
+ case strings.HasPrefix(data, "appr_page:"):
+ page := 0
+ fmt.Sscanf(strings.TrimPrefix(data, "appr_page:"), "%d", &page)
+ bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck
+ s.approvalHandler.HandleMenuPage(bot, cq.Message.Chat.ID, cq.From.ID, page, cq.Message.MessageID)
+
+ case data == "appr_page_noop":
+ bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck
+
+ // ── ФЛОУ ДЕЛЕГИРОВАНИЯ ПРАВ ──────────────────────────────────────────
+ // telegram_service/handlers/update_handler.go - обновить в handleCallback
+
+ case strings.HasPrefix(data, "deleg_category_page:"):
+ page := 0
+ fmt.Sscanf(strings.TrimPrefix(data, "deleg_category_page:"), "%d", &page)
+ bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck
+ s.approvalHandler.HandleDelegationMenuPage(bot, cq.Message.Chat.ID, cq.From.ID, page, cq.Message.MessageID)
+
+ case strings.HasPrefix(data, "deleg_category:"):
+ categoryID := parseID(data, "deleg_category:")
+ s.approvalHandler.HandleDelegationCategoryCallback(bot, cq, categoryID)
+
+ case strings.HasPrefix(data, "deleg_topic_page:"):
+ parts := strings.Split(strings.TrimPrefix(data, "deleg_topic_page:"), ":")
+ if len(parts) == 2 {
+ var categoryID, page uint64
+ fmt.Sscanf(parts[0], "%d", &categoryID)
+ fmt.Sscanf(parts[1], "%d", &page)
+ bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck
+ bot.Request(tgbotapi.NewDeleteMessage(cq.Message.Chat.ID, cq.Message.MessageID)) //nolint:errcheck
+ s.approvalHandler.HandleDelegationCategoryCallbackPage(bot, cq, categoryID, int(page))
+ }
+
+ case strings.HasPrefix(data, "deleg_all_category:"):
+ categoryID := parseID(data, "deleg_all_category:")
+ s.approvalHandler.HandleDelegationAllCategoryCallback(bot, cq, categoryID)
+
+ case strings.HasPrefix(data, "deleg_topic:"):
+ topicID := parseID(data, "deleg_topic:")
+ s.approvalHandler.HandleDelegationTopicCallback(bot, cq, topicID)
+
+ case strings.HasPrefix(data, "deleg_user_page:"):
+ parts := strings.Split(strings.TrimPrefix(data, "deleg_user_page:"), ":")
+ if len(parts) == 3 {
+ var categoryID, topicID, page uint64
+ fmt.Sscanf(parts[0], "%d", &categoryID)
+ fmt.Sscanf(parts[1], "%d", &topicID)
+ fmt.Sscanf(parts[2], "%d", &page)
+ bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck
+ bot.Request(tgbotapi.NewDeleteMessage(cq.Message.Chat.ID, cq.Message.MessageID)) //nolint:errcheck
+ s.approvalHandler.HandleDelegationSelectUserPage(bot, cq, categoryID, topicID, int(page))
+ }
+
+ case strings.HasPrefix(data, "deleg_user:"):
+ delegateID := parseID(data, "deleg_user:")
+ s.approvalHandler.HandleDelegationUserCallback(bot, cq, delegateID)
+
+ case data == "deleg_back_categories":
+ bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck
+ bot.Request(tgbotapi.NewDeleteMessage(cq.Message.Chat.ID, cq.Message.MessageID)) //nolint:errcheck
+ s.approvalHandler.HandleDelegationMenu(bot, cq.Message.Chat.ID, cq.From.ID)
+
+ case data == "deleg_create":
+ bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck
+ bot.Request(tgbotapi.NewDeleteMessage(cq.Message.Chat.ID, cq.Message.MessageID)) //nolint:errcheck
+ s.approvalHandler.HandleDelegationMenu(bot, cq.Message.Chat.ID, cq.From.ID)
+
+ case data == "deleg_list":
+ bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck
+ bot.Request(tgbotapi.NewDeleteMessage(cq.Message.Chat.ID, cq.Message.MessageID)) //nolint:errcheck
+ s.approvalHandler.HandleDelegatedRightsList(bot, cq.Message.Chat.ID, cq.From.ID)
+
+ case strings.HasPrefix(data, "deleg_list_page:"):
+ page := 0
+ fmt.Sscanf(strings.TrimPrefix(data, "deleg_list_page:"), "%d", &page)
+ bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck
+ s.approvalHandler.HandleDelegatedRightsListPage(bot, cq.Message.Chat.ID, cq.From.ID, page, cq.Message.MessageID)
+
+ case strings.HasPrefix(data, "deleg_detail:"):
+ delegationID := parseID(data, "deleg_detail:")
+ s.approvalHandler.HandleDelegatedRightDetail(bot, cq, delegationID)
+
+ case strings.HasPrefix(data, "deleg_revoke:"):
+ delegationID := parseID(data, "deleg_revoke:")
+ s.approvalHandler.HandleDelegationRevoke(bot, cq, delegationID)
+
+ case strings.HasPrefix(data, "deleg_extend:"):
+ delegationID := parseID(data, "deleg_extend:")
+ s.approvalHandler.HandleDelegationExtendPrompt(bot, cq, delegationID)
+
+ case data == "deleg_page_noop":
+ bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck
+
+ // ── ДОБАВЛЕНИЕ СОГЛАСУЮЩЕГО ───────────────────────────────────────────────────
+ case strings.HasPrefix(data, "add_appr_category_page:"):
+ page := 0
+ fmt.Sscanf(strings.TrimPrefix(data, "add_appr_category_page:"), "%d", &page)
+ bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck
+ s.approvalHandler.HandleAddApproverCategoryMenuPage(bot, cq.Message.Chat.ID, cq.From.ID, page, cq.Message.MessageID)
+
+ case strings.HasPrefix(data, "add_appr_category:"):
+ categoryID := parseID(data, "add_appr_category:")
+ s.approvalHandler.HandleAddApproverCategoryCallback(bot, cq, categoryID)
+
+ case strings.HasPrefix(data, "add_appr_approval_page:"):
+ parts := strings.Split(strings.TrimPrefix(data, "add_appr_approval_page:"), ":")
+ if len(parts) == 2 {
+ var categoryID, page uint64
+ fmt.Sscanf(parts[0], "%d", &categoryID)
+ fmt.Sscanf(parts[1], "%d", &page)
+ bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck
+ bot.Request(tgbotapi.NewDeleteMessage(cq.Message.Chat.ID, cq.Message.MessageID)) //nolint:errcheck
+ s.approvalHandler.HandleAddApproverCategoryCallbackPage(bot, cq, categoryID, int(page))
+ }
+
+ case strings.HasPrefix(data, "add_appr_approval:"):
+ approvalID := parseID(data, "add_appr_approval:")
+ s.approvalHandler.HandleAddApproverApprovalCallback(bot, cq, approvalID)
+
+ case strings.HasPrefix(data, "add_appr_user_page:"):
+ parts := strings.Split(strings.TrimPrefix(data, "add_appr_user_page:"), ":")
+ if len(parts) == 3 {
+ var approvalID, categoryID, page uint64
+ fmt.Sscanf(parts[0], "%d", &approvalID)
+ fmt.Sscanf(parts[1], "%d", &categoryID)
+ fmt.Sscanf(parts[2], "%d", &page)
+ bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck
+ bot.Request(tgbotapi.NewDeleteMessage(cq.Message.Chat.ID, cq.Message.MessageID)) //nolint:errcheck
+ s.approvalHandler.HandleAddApproverApprovalCallbackPage(bot, cq, approvalID, int(page))
+ }
+
+ case strings.HasPrefix(data, "add_appr_user:"):
+ approverID := parseID(data, "add_appr_user:")
+ s.approvalHandler.HandleAddApproverUserCallback(bot, cq, approverID)
+
+ case data == "add_appr_create":
+ bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck
+ bot.Request(tgbotapi.NewDeleteMessage(cq.Message.Chat.ID, cq.Message.MessageID)) //nolint:errcheck
+ s.approvalHandler.HandleAddApproverCategoryMenu(bot, cq.Message.Chat.ID, cq.From.ID)
+
+ case data == "add_appr_list":
+ bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck
+ bot.Request(tgbotapi.NewDeleteMessage(cq.Message.Chat.ID, cq.Message.MessageID)) //nolint:errcheck
+ s.approvalHandler.HandleAddedApproversList(bot, cq.Message.Chat.ID, cq.From.ID)
+
+ case strings.HasPrefix(data, "add_appr_list_page:"):
+ page := 0
+ fmt.Sscanf(strings.TrimPrefix(data, "add_appr_list_page:"), "%d", &page)
+ bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck
+ s.approvalHandler.HandleAddedApproversListPage(bot, cq.Message.Chat.ID, cq.From.ID, page, cq.Message.MessageID)
+
+ case strings.HasPrefix(data, "add_appr_detail:"):
+ additionalApproverID := parseID(data, "add_appr_detail:")
+ s.approvalHandler.HandleAddedApproverDetail(bot, cq, additionalApproverID)
+
+ case data == "add_appr_page_noop":
+ bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck
+
+ // ── ОТЧЁТ ───────────────────────────────────────────────────
+ case data == "report_type_approvals":
+ s.approvalHandler.HandleReportTypeSelection(bot, cq, "approvals")
+
+ case data == "report_type_tasks":
+ s.approvalHandler.HandleReportTypeSelection(bot, cq, "tasks")
+
+ case data == "report_set_dates":
+ s.approvalHandler.HandleReportSetDates(bot, cq)
+
+ case data == "report_all_time":
+ s.approvalHandler.HandleReportAllTime(bot, cq)
+
+ case data == "report_generate":
+ s.approvalHandler.HandleReportGenerate(bot, cq)
+
+ // ВЫБОР СОГЛАСУЮЩЕГО
+ case strings.HasPrefix(data, "select_approver:"):
+ approverID := parseID(data, "select_approver:")
+ s.approvalHandler.HandleApproverSelectionCallback(bot, cq, approverID)
+
+ case strings.HasPrefix(data, "select_approver_page:"):
+ page := 0
+ fmt.Sscanf(strings.TrimPrefix(data, "select_approver_page:"), "%d", &page)
+ s.approvalHandler.HandleApproverSelectionPageCallback(bot, cq, page)
+
+ case data == "select_approver_noop":
+ bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck
+
+ // ── ПРОЧЕЕ ──────────────────────────────────────────────────
+ case data == "restart_bot":
+ bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck
+ bot.Request(tgbotapi.NewDeleteMessage(cq.Message.Chat.ID, cq.Message.MessageID)) //nolint:errcheck
+ s.startHandler.Handle(bot, &tgbotapi.Message{
+ Chat: &tgbotapi.Chat{ID: cq.Message.Chat.ID},
+ From: cq.From,
+ })
+
+ default:
+ logrus.Warnf("handleCallback: unknown callback: %s", data)
+ }
+}
+
+// handleApprovalRejectStart сохраняет состояние "ожидаем комментарий к отказу"
+// и просит согласующего ввести причину (или оставить пустой).
+func (s *UpdateHandler) handleApprovalRejectStart(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, approvalID uint64) {
+ ctx := context.Background()
+ bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck
+ bot.Request(tgbotapi.NewDeleteMessage(cq.Message.Chat.ID, cq.Message.MessageID)) //nolint:errcheck
+
+ rejectKey := fmt.Sprintf("appr_reject_pending:%d", cq.From.ID)
+ if err := s.ipc.RedisClient.Set(ctx, rejectKey, fmt.Sprintf("%d", approvalID), 10*time.Minute); err != nil {
+ logrus.Errorf("handleApprovalRejectStart: Set err=%v", err)
+ return
+ }
+
+ msg := tgbotapi.NewMessage(cq.Message.Chat.ID,
+ "Укажите причину отказа или нажмите кнопку ниже:")
+ msg.ParseMode = "HTML"
+ msg.ReplyMarkup = keyboard.BuildApprovalRejectComment(approvalID)
+ bot.Send(msg) //nolint:errcheck
+}
+
+func (s *UpdateHandler) handleApprovalDecision(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, approvalID uint64, approved bool, comment string) {
+ // Логика финализации шага — делегируем в approvalHandler
+ s.approvalHandler.HandleDecision(bot, cq, approvalID, approved, comment)
+}
+
+func parseID(data, prefix string) uint64 {
+ var id uint64
+ fmt.Sscanf(strings.TrimPrefix(data, prefix), "%d", &id)
+ return id
+}
+
+func (s *UpdateHandler) handleRevokeStart(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, approvalID uint64) {
+ ctx := context.Background()
+ bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck
+ bot.Request(tgbotapi.NewDeleteMessage(cq.Message.Chat.ID, cq.Message.MessageID)) //nolint:errcheck
+
+ revokeKey := fmt.Sprintf("appr_revoke_pending:%d", cq.From.ID)
+ if err := s.ipc.RedisClient.Set(ctx, revokeKey, fmt.Sprintf("%d", approvalID), 10*time.Minute); err != nil {
+ logrus.Errorf("handleRevokeStart: Set err=%v", err)
+ return
+ }
+
+ msg := tgbotapi.NewMessage(cq.Message.Chat.ID, "Укажите причину отзыва заявки:")
+ msg.ParseMode = "HTML"
+ bot.Send(msg) //nolint:errcheck
+}
diff --git a/service/telegram_service/common/update/update.go b/service/telegram_service/common/update/update.go
new file mode 100644
index 0000000..db46ba1
--- /dev/null
+++ b/service/telegram_service/common/update/update.go
@@ -0,0 +1,227 @@
+package tgupdatehandler
+
+import (
+ "context"
+ "fmt"
+ "strings"
+
+ tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
+ "github.com/sirupsen/logrus"
+)
+
+func (s *UpdateHandler) GetUpdateTelegram() {
+ bot := s.ipc.TGBotClient.GetBot()
+
+ u := tgbotapi.NewUpdate(0)
+ u.Timeout = 10
+ updates := bot.GetUpdatesChan(u)
+
+ logrus.Info("🟢 Telegram Bot запущен. Ожидание обновлений...")
+
+ for update := range updates {
+ if update.Message != nil {
+ go s.handleMessage(bot, update.Message)
+ continue
+ }
+ if update.CallbackQuery != nil {
+ go s.handleCallback(bot, update.CallbackQuery)
+ continue
+ }
+ }
+}
+
+func (s *UpdateHandler) handleMessage(bot *tgbotapi.BotAPI, msg *tgbotapi.Message) {
+ ctx := context.Background()
+
+ if msg.IsCommand() {
+ switch msg.Command() {
+ case "start":
+ s.startHandler.Handle(bot, msg)
+ case "approvals":
+ s.withDepartmentCheck(bot, msg, func() {
+ s.approvalHandler.HandleMenu(bot, msg.Chat.ID, msg.From.ID)
+ })
+ }
+ return
+ }
+
+ // Постоянные кнопки меню
+ switch msg.Text {
+ // ═══════════════════════════════════════════════════════════
+ // ГЛАВНОЕ МЕНЮ
+ // ═══════════════════════════════════════════════════════════
+ case "Согласование":
+ s.withDepartmentCheck(bot, msg, func() {
+ // Открываем подменю согласований
+ s.approvalHandler.HandleApprovalsSubmenu(bot, msg.Chat.ID, msg.From.ID)
+ })
+ return
+
+ case "Мои заявки":
+ s.withDepartmentCheck(bot, msg, func() {
+ s.approvalHandler.HandleMyApprovals(bot, msg.Chat.ID, msg.From.ID)
+ })
+ return
+
+ case "Согласовать":
+ s.withDepartmentCheck(bot, msg, func() {
+ ctx := context.Background()
+ user, err := s.ipc.Database.User.GetUserByTelegramIDDB(ctx, msg.From.ID)
+ if err != nil || user == nil || user.ID == nil {
+ return
+ }
+ isApprover, _ := s.ipc.Database.User.IsApproverDB(ctx, *user.ID)
+ if !isApprover {
+ return // молчим — кнопки нет в его клавиатуре
+ }
+ s.approvalHandler.HandleIncomingApprovals(bot, msg.Chat.ID, msg.From.ID)
+ })
+ return
+
+ case "Отложенные":
+ s.withDepartmentCheck(bot, msg, func() {
+ s.approvalHandler.HandlePendingCommentsList(bot, msg.Chat.ID, msg.From.ID)
+ })
+ return
+
+ case "❓ Как создать согласование":
+ s.withDepartmentCheck(bot, msg, func() {
+ s.faqHandler.Handle(bot, msg)
+ })
+ return
+
+ // ═══════════════════════════════════════════════════════════
+ // ПОДМЕНЮ "СОГЛАСОВАНИЯ"
+ // ═══════════════════════════════════════════════════════════
+ case "Согласования":
+ s.withDepartmentCheck(bot, msg, func() {
+ s.approvalHandler.HandleApprovalsListSubmenu(bot, msg.Chat.ID, msg.From.ID)
+ })
+ return
+
+ case "Создать согласование":
+ s.withDepartmentCheck(bot, msg, func() {
+ // Это старый функционал "Согласования" - показываем темы
+ s.approvalHandler.HandleMenu(bot, msg.Chat.ID, msg.From.ID)
+ })
+ return
+
+ case "Сформировать отчёт":
+ s.withDepartmentCheck(bot, msg, func() {
+ s.approvalHandler.HandleReportMenu(bot, msg.Chat.ID, msg.From.ID)
+ })
+ return
+
+ case "Делегирование прав":
+ s.withDepartmentCheck(bot, msg, func() {
+ s.approvalHandler.HandleDelegationMainMenu(bot, msg.Chat.ID, msg.From.ID)
+ })
+ return
+
+ case "Наблюдаемые":
+ s.withDepartmentCheck(bot, msg, func() {
+ s.approvalHandler.HandleObservedApprovals(bot, msg.Chat.ID, msg.From.ID)
+ })
+ return
+
+ case "Добавить согласующего":
+ s.withDepartmentCheck(bot, msg, func() {
+ s.approvalHandler.HandleAddApproverMainMenu(bot, msg.Chat.ID, msg.From.ID)
+ })
+ return
+
+ case "Мои задачи":
+ s.withDepartmentCheck(bot, msg, func() {
+ s.approvalHandler.HandleMyTasks(bot, msg.Chat.ID, msg.From.ID)
+ })
+ return
+
+ // ═══════════════════════════════════════════════════════════
+ // ПОДМЕНЮ "СПИСОК СОГЛАСОВАНИЙ"
+ // ═══════════════════════════════════════════════════════════
+ case "Все":
+ s.withDepartmentCheck(bot, msg, func() {
+ s.approvalHandler.HandleMyApprovalsByStatus(bot, msg.Chat.ID, msg.From.ID, "all")
+ })
+ return
+
+ case "Принятые":
+ s.withDepartmentCheck(bot, msg, func() {
+ s.approvalHandler.HandleMyApprovalsByStatus(bot, msg.Chat.ID, msg.From.ID, "approved")
+ })
+ return
+
+ case "Отклонённые":
+ s.withDepartmentCheck(bot, msg, func() {
+ s.approvalHandler.HandleMyApprovalsByStatus(bot, msg.Chat.ID, msg.From.ID, "rejected")
+ })
+ return
+
+ case "На согласовании":
+ s.withDepartmentCheck(bot, msg, func() {
+ s.approvalHandler.HandleMyApprovalsByStatus(bot, msg.Chat.ID, msg.From.ID, "pending")
+ })
+ return
+
+ // ═══════════════════════════════════════════════════════════
+ // НАВИГАЦИЯ "НАЗАД"
+ // ═══════════════════════════════════════════════════════════
+ case "← Назад":
+ s.withDepartmentCheck(bot, msg, func() {
+ s.approvalHandler.HandleBackNavigation(bot, msg.Chat.ID, msg.From.ID)
+ })
+ return
+ }
+
+ // Обработка pending состояний
+ if s.approvalHandler.HandlePendingCommentInput(bot, msg) {
+ return
+ }
+ if s.approvalHandler.HandleReportTextInput(bot, msg) {
+ return
+ }
+ if s.startHandler.HandleTextInput(bot, msg) {
+ return
+ }
+
+ // Проверка pending состояния для отказа
+ rejectKey := fmt.Sprintf("appr_reject_pending:%d", msg.From.ID)
+ if val, err := s.ipc.RedisClient.Get(ctx, rejectKey); err == nil && val != "" {
+ var approvalID uint64
+ fmt.Sscanf(val, "%d", &approvalID)
+ s.ipc.RedisClient.Del(ctx, rejectKey) //nolint:errcheck
+ s.approvalHandler.HandleDecisionWithChat(bot, msg.Chat.ID, approvalID, false, strings.TrimSpace(msg.Text))
+ return
+ }
+
+ if s.approvalHandler.HandleDelegationDateInput(bot, msg) {
+ return
+ }
+ if s.approvalHandler.HandleDelegationExtendInput(bot, msg) {
+ return
+ }
+
+ // Обработка файлов
+ if msg.Photo != nil || msg.Document != nil {
+ s.withDepartmentCheck(bot, msg, func() {
+ s.approvalHandler.HandleFileInput(bot, msg)
+ })
+ return
+ }
+
+ // Обработка текстового ввода
+ s.withDepartmentCheck(bot, msg, func() {
+ s.approvalHandler.HandleTextInput(bot, msg)
+ })
+}
+
+// withDepartmentCheck блокирует действие если отдел не назначен.
+func (s *UpdateHandler) withDepartmentCheck(bot *tgbotapi.BotAPI, msg *tgbotapi.Message, action func()) {
+ ctx := context.Background()
+
+ user, err := s.ipc.Database.User.GetUserByTelegramIDDB(ctx, msg.From.ID)
+ if err != nil || user == nil || user.DepartmentID == nil {
+ return // молчим — бот пуст
+ }
+ action()
+}
diff --git a/service/telegram_service/go.mod b/service/telegram_service/go.mod
new file mode 100644
index 0000000..cf64f92
--- /dev/null
+++ b/service/telegram_service/go.mod
@@ -0,0 +1,57 @@
+module bitrix_balancer_api/telegram_service
+
+go 1.25.6
+
+replace bitrix_balancer_api/core => ../../core
+
+require (
+ bitrix_balancer_api/core v0.0.0-00010101000000-000000000000
+ github.com/go-telegram-bot-api/telegram-bot-api/v5 v5.5.1
+ github.com/sirupsen/logrus v1.9.4
+)
+
+require (
+ github.com/Masterminds/squirrel v1.5.4 // indirect
+ github.com/cenkalti/backoff/v4 v4.3.0 // indirect
+ github.com/cespare/xxhash/v2 v2.3.0 // indirect
+ github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
+ github.com/go-jose/go-jose/v4 v4.1.1 // indirect
+ github.com/hashicorp/errwrap v1.1.0 // indirect
+ github.com/hashicorp/go-cleanhttp v0.5.2 // indirect
+ github.com/hashicorp/go-multierror v1.1.1 // indirect
+ github.com/hashicorp/go-retryablehttp v0.7.8 // indirect
+ github.com/hashicorp/go-rootcerts v1.0.2 // indirect
+ github.com/hashicorp/go-secure-stdlib/parseutil v0.2.0 // indirect
+ github.com/hashicorp/go-secure-stdlib/strutil v0.1.2 // indirect
+ github.com/hashicorp/go-sockaddr v1.0.7 // indirect
+ github.com/hashicorp/hcl v1.0.1-vault-7 // indirect
+ github.com/hashicorp/vault/api v1.22.0 // indirect
+ github.com/jackc/pgpassfile v1.0.0 // indirect
+ github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
+ github.com/jackc/pgx/v5 v5.8.0 // indirect
+ github.com/jackc/puddle/v2 v2.2.2 // indirect
+ github.com/jinzhu/inflection v1.0.0 // indirect
+ github.com/jinzhu/now v1.1.5 // indirect
+ github.com/lann/builder v0.0.0-20180802200727-47ae307949d0 // indirect
+ github.com/lann/ps v0.0.0-20150810152359-62de8c46ede0 // indirect
+ github.com/mitchellh/go-homedir v1.1.0 // indirect
+ github.com/mitchellh/mapstructure v1.5.0 // indirect
+ github.com/redis/go-redis/v9 v9.18.0 // indirect
+ github.com/richardlehane/mscfb v1.0.6 // indirect
+ github.com/richardlehane/msoleps v1.0.6 // indirect
+ github.com/ryanuber/go-glob v1.0.0 // indirect
+ github.com/tiendc/go-deepcopy v1.7.2 // indirect
+ github.com/xuri/efp v0.0.1 // indirect
+ github.com/xuri/excelize/v2 v2.10.1 // indirect
+ github.com/xuri/nfp v0.0.2-0.20250530014748-2ddeb826f9a9 // indirect
+ go.uber.org/atomic v1.11.0 // indirect
+ golang.org/x/crypto v0.48.0 // indirect
+ golang.org/x/net v0.50.0 // indirect
+ golang.org/x/sync v0.19.0 // indirect
+ golang.org/x/sys v0.41.0 // indirect
+ golang.org/x/text v0.34.0 // indirect
+ golang.org/x/time v0.12.0 // indirect
+ gopkg.in/yaml.v3 v3.0.1 // indirect
+ gorm.io/driver/postgres v1.6.0 // indirect
+ gorm.io/gorm v1.31.1 // indirect
+)
diff --git a/service/telegram_service/go.sum b/service/telegram_service/go.sum
new file mode 100644
index 0000000..ea3638a
--- /dev/null
+++ b/service/telegram_service/go.sum
@@ -0,0 +1,137 @@
+github.com/Masterminds/squirrel v1.5.4 h1:uUcX/aBc8O7Fg9kaISIUsHXdKuqehiXAMQTYX8afzqM=
+github.com/Masterminds/squirrel v1.5.4/go.mod h1:NNaOrjSoIDfDA40n7sr2tPNZRfjzjA400rg+riTZj10=
+github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs=
+github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c=
+github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA=
+github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0=
+github.com/cenkalti/backoff/v4 v4.3.0 h1:MyRJ/UdXutAwSAT+s3wNd7MfTIcy71VQueUuFK343L8=
+github.com/cenkalti/backoff/v4 v4.3.0/go.mod h1:Y3VNntkOUPxTVeUxJ/G5vcM//AlwfmyYozVcomhLiZE=
+github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
+github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
+github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
+github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
+github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
+github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78=
+github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc=
+github.com/fatih/color v1.18.0 h1:S8gINlzdQ840/4pfAwic/ZE0djQEH3wM94VfqLTZcOM=
+github.com/fatih/color v1.18.0/go.mod h1:4FelSpRwEGDpQ12mAdzqdOukCy4u8WUtOY6lkT/6HfU=
+github.com/go-jose/go-jose/v4 v4.1.1 h1:JYhSgy4mXXzAdF3nUx3ygx347LRXJRrpgyU3adRmkAI=
+github.com/go-jose/go-jose/v4 v4.1.1/go.mod h1:BdsZGqgdO3b6tTc6LSE56wcDbMMLuPsw5d4ZD5f94kA=
+github.com/go-telegram-bot-api/telegram-bot-api/v5 v5.5.1 h1:wG8n/XJQ07TmjbITcGiUaOtXxdrINDz1b0J1w0SzqDc=
+github.com/go-telegram-bot-api/telegram-bot-api/v5 v5.5.1/go.mod h1:A2S0CWkNylc2phvKXWBBdD3K0iGnDBGbzRpISP2zBl8=
+github.com/go-test/deep v1.1.1 h1:0r/53hagsehfO4bzD2Pgr/+RgHqhmf+k1Bpse2cTu1U=
+github.com/go-test/deep v1.1.1/go.mod h1:5C2ZWiW0ErCdrYzpqxLbTX7MG14M9iiw8DgHncVwcsE=
+github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4=
+github.com/hashicorp/errwrap v1.1.0 h1:OxrOeh75EUXMY8TBjag2fzXGZ40LB6IKw45YeGUDY2I=
+github.com/hashicorp/errwrap v1.1.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4=
+github.com/hashicorp/go-cleanhttp v0.5.2 h1:035FKYIWjmULyFRBKPs8TBQoi0x6d9G4xc9neXJWAZQ=
+github.com/hashicorp/go-cleanhttp v0.5.2/go.mod h1:kO/YDlP8L1346E6Sodw+PrpBSV4/SoxCXGY6BqNFT48=
+github.com/hashicorp/go-hclog v1.6.3 h1:Qr2kF+eVWjTiYmU7Y31tYlP1h0q/X3Nl3tPGdaB11/k=
+github.com/hashicorp/go-hclog v1.6.3/go.mod h1:W4Qnvbt70Wk/zYJryRzDRU/4r0kIg0PVHBcfoyhpF5M=
+github.com/hashicorp/go-multierror v1.1.1 h1:H5DkEtf6CXdFp0N0Em5UCwQpXMWke8IA0+lD48awMYo=
+github.com/hashicorp/go-multierror v1.1.1/go.mod h1:iw975J/qwKPdAO1clOe2L8331t/9/fmwbPZ6JB6eMoM=
+github.com/hashicorp/go-retryablehttp v0.7.8 h1:ylXZWnqa7Lhqpk0L1P1LzDtGcCR0rPVUrx/c8Unxc48=
+github.com/hashicorp/go-retryablehttp v0.7.8/go.mod h1:rjiScheydd+CxvumBsIrFKlx3iS0jrZ7LvzFGFmuKbw=
+github.com/hashicorp/go-rootcerts v1.0.2 h1:jzhAVGtqPKbwpyCPELlgNWhE1znq+qwJtW5Oi2viEzc=
+github.com/hashicorp/go-rootcerts v1.0.2/go.mod h1:pqUvnprVnM5bf7AOirdbb01K4ccR319Vf4pU3K5EGc8=
+github.com/hashicorp/go-secure-stdlib/parseutil v0.2.0 h1:U+kC2dOhMFQctRfhK0gRctKAPTloZdMU5ZJxaesJ/VM=
+github.com/hashicorp/go-secure-stdlib/parseutil v0.2.0/go.mod h1:Ll013mhdmsVDuoIXVfBtvgGJsXDYkTw1kooNcoCXuE0=
+github.com/hashicorp/go-secure-stdlib/strutil v0.1.2 h1:kes8mmyCpxJsI7FTwtzRqEy9CdjCtrXrXGuOpxEA7Ts=
+github.com/hashicorp/go-secure-stdlib/strutil v0.1.2/go.mod h1:Gou2R9+il93BqX25LAKCLuM+y9U2T4hlwvT1yprcna4=
+github.com/hashicorp/go-sockaddr v1.0.7 h1:G+pTkSO01HpR5qCxg7lxfsFEZaG+C0VssTy/9dbT+Fw=
+github.com/hashicorp/go-sockaddr v1.0.7/go.mod h1:FZQbEYa1pxkQ7WLpyXJ6cbjpT8q0YgQaK/JakXqGyWw=
+github.com/hashicorp/hcl v1.0.1-vault-7 h1:ag5OxFVy3QYTFTJODRzTKVZ6xvdfLLCA1cy/Y6xGI0I=
+github.com/hashicorp/hcl v1.0.1-vault-7/go.mod h1:XYhtn6ijBSAj6n4YqAaf7RBPS4I06AItNorpy+MoQNM=
+github.com/hashicorp/vault/api v1.22.0 h1:+HYFquE35/B74fHoIeXlZIP2YADVboaPjaSicHEZiH0=
+github.com/hashicorp/vault/api v1.22.0/go.mod h1:IUZA2cDvr4Ok3+NtK2Oq/r+lJeXkeCrHRmqdyWfpmGM=
+github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
+github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
+github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
+github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
+github.com/jackc/pgx/v5 v5.8.0 h1:TYPDoleBBme0xGSAX3/+NujXXtpZn9HBONkQC7IEZSo=
+github.com/jackc/pgx/v5 v5.8.0/go.mod h1:QVeDInX2m9VyzvNeiCJVjCkNFqzsNb43204HshNSZKw=
+github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
+github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
+github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
+github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
+github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ=
+github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
+github.com/klauspost/cpuid/v2 v2.0.9 h1:lgaqFMSdTdQYdZ04uHyN2d/eKdOMyi2YLSvlQIBFYa4=
+github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
+github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0=
+github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk=
+github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
+github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
+github.com/lann/builder v0.0.0-20180802200727-47ae307949d0 h1:SOEGU9fKiNWd/HOJuq6+3iTQz8KNCLtVX6idSoTLdUw=
+github.com/lann/builder v0.0.0-20180802200727-47ae307949d0/go.mod h1:dXGbAdH5GtBTC4WfIxhKZfyBF/HBFgRZSWwZ9g/He9o=
+github.com/lann/ps v0.0.0-20150810152359-62de8c46ede0 h1:P6pPBnrTSX3DEVR4fDembhRWSsG5rVo6hYhAB/ADZrk=
+github.com/lann/ps v0.0.0-20150810152359-62de8c46ede0/go.mod h1:vmVJ0l/dxyfGW6FmdpVm2joNMFikkuWg0EoCKLGUMNw=
+github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHPsaIE=
+github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8=
+github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
+github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
+github.com/mitchellh/go-homedir v1.1.0 h1:lukF9ziXFxDFPkA1vsr5zpc1XuPDn/wFntq5mG+4E0Y=
+github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0=
+github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY=
+github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo=
+github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
+github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
+github.com/redis/go-redis/v9 v9.18.0 h1:pMkxYPkEbMPwRdenAzUNyFNrDgHx9U+DrBabWNfSRQs=
+github.com/redis/go-redis/v9 v9.18.0/go.mod h1:k3ufPphLU5YXwNTUcCRXGxUoF1fqxnhFQmscfkCoDA0=
+github.com/richardlehane/mscfb v1.0.6 h1:eN3bvvZCp00bs7Zf52bxNwAx5lJDBK1tCuH19qq5aC8=
+github.com/richardlehane/mscfb v1.0.6/go.mod h1:pe0+IUIc0AHh0+teNzBlJCtSyZdFOGgV4ZK9bsoV+Jo=
+github.com/richardlehane/msoleps v1.0.6 h1:9BvkpjvD+iUBalUY4esMwv6uBkfOip/Lzvd93jvR9gg=
+github.com/richardlehane/msoleps v1.0.6/go.mod h1:BWev5JBpU9Ko2WAgmZEuiz4/u3ZYTKbjLycmwiWUfWg=
+github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=
+github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=
+github.com/ryanuber/go-glob v1.0.0 h1:iQh3xXAumdQ+4Ufa5b25cRpC5TYKlno6hsv6Cb3pkBk=
+github.com/ryanuber/go-glob v1.0.0/go.mod h1:807d1WSdnB0XRJzKNil9Om6lcp/3a0v4qIHxIXzX/Yc=
+github.com/sirupsen/logrus v1.9.4 h1:TsZE7l11zFCLZnZ+teH4Umoq5BhEIfIzfRDZ1Uzql2w=
+github.com/sirupsen/logrus v1.9.4/go.mod h1:ftWc9WdOfJ0a92nsE2jF5u5ZwH8Bv2zdeOC42RjbV2g=
+github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
+github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
+github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
+github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
+github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
+github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
+github.com/tiendc/go-deepcopy v1.7.2 h1:Ut2yYR7W9tWjTQitganoIue4UGxZwCcJy3orjrrIj44=
+github.com/tiendc/go-deepcopy v1.7.2/go.mod h1:4bKjNC2r7boYOkD2IOuZpYjmlDdzjbpTRyCx+goBCJQ=
+github.com/xuri/efp v0.0.1 h1:fws5Rv3myXyYni8uwj2qKjVaRP30PdjeYe2Y6FDsCL8=
+github.com/xuri/efp v0.0.1/go.mod h1:ybY/Jr0T0GTCnYjKqmdwxyxn2BQf2RcQIIvex5QldPI=
+github.com/xuri/excelize/v2 v2.10.1 h1:V62UlqopMqha3kOpnlHy2CcRVw1V8E63jFoWUmMzxN0=
+github.com/xuri/excelize/v2 v2.10.1/go.mod h1:iG5tARpgaEeIhTqt3/fgXCGoBRt4hNXgCp3tfXKoOIc=
+github.com/xuri/nfp v0.0.2-0.20250530014748-2ddeb826f9a9 h1:+C0TIdyyYmzadGaL/HBLbf3WdLgC29pgyhTjAT/0nuE=
+github.com/xuri/nfp v0.0.2-0.20250530014748-2ddeb826f9a9/go.mod h1:WwHg+CVyzlv/TX9xqBFXEZAuxOPxn2k1GNHwG41IIUQ=
+github.com/zeebo/xxh3 v1.0.2 h1:xZmwmqxHZA8AI603jOQ0tMqmBr9lPeFwGg6d+xy9DC0=
+github.com/zeebo/xxh3 v1.0.2/go.mod h1:5NWz9Sef7zIDm2JHfFlcQvNekmcEl9ekUZQQKCYaDcA=
+go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE=
+go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0=
+golang.org/x/crypto v0.40.0 h1:r4x+VvoG5Fm+eJcxMaY8CQM7Lb0l1lsmjGBQ6s8BfKM=
+golang.org/x/crypto v0.40.0/go.mod h1:Qr1vMER5WyS2dfPHAlsOj01wgLbsyWtFn/aY+5+ZdxY=
+golang.org/x/crypto v0.48.0 h1:/VRzVqiRSggnhY7gNRxPauEQ5Drw9haKdM0jqfcCFts=
+golang.org/x/crypto v0.48.0/go.mod h1:r0kV5h3qnFPlQnBSrULhlsRfryS2pmewsg+XfMgkVos=
+golang.org/x/net v0.42.0 h1:jzkYrhi3YQWD6MLBJcsklgQsoAcw89EcZbJw8Z614hs=
+golang.org/x/net v0.42.0/go.mod h1:FF1RA5d3u7nAYA4z2TkclSCKh68eSXtiFwcWQpPXdt8=
+golang.org/x/net v0.50.0 h1:ucWh9eiCGyDR3vtzso0WMQinm2Dnt8cFMuQa9K33J60=
+golang.org/x/net v0.50.0/go.mod h1:UgoSli3F/pBgdJBHCTc+tp3gmrU4XswgGRgtnwWTfyM=
+golang.org/x/sync v0.17.0 h1:l60nONMj9l5drqw6jlhIELNv9I0A4OFgRsG9k2oT9Ug=
+golang.org/x/sync v0.17.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
+golang.org/x/sync v0.19.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
+golang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k=
+golang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
+golang.org/x/text v0.29.0 h1:1neNs90w9YzJ9BocxfsQNHKuAT4pkghyXc4nhZ6sJvk=
+golang.org/x/text v0.29.0/go.mod h1:7MhJOA9CD2qZyOKYazxdYMF85OwPdEr9jTtBpO7ydH4=
+golang.org/x/text v0.34.0 h1:oL/Qq0Kdaqxa1KbNeMKwQq0reLCCaFtqu2eNuSeNHbk=
+golang.org/x/text v0.34.0/go.mod h1:homfLqTYRFyVYemLBFl5GgL/DWEiH5wcsQ5gSh1yziA=
+golang.org/x/time v0.12.0 h1:ScB/8o8olJvc+CQPWrK3fPZNfh7qgwCrY0zJmoEQLSE=
+golang.org/x/time v0.12.0/go.mod h1:CDIdPxbZBQxdj6cxyCIdrNogrJKMJ7pr37NYpMcMDSg=
+gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
+gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
+gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
+gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
+gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
+gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
+gorm.io/driver/postgres v1.6.0 h1:2dxzU8xJ+ivvqTRph34QX+WrRaJlmfyPqXmoGVjMBa4=
+gorm.io/driver/postgres v1.6.0/go.mod h1:vUw0mrGgrTK+uPHEhAdV4sfFELrByKVGnaVRkXDhtWo=
+gorm.io/gorm v1.31.1 h1:7CA8FTFz/gRfgqgpeKIBcervUn3xSyPUmr6B2WXJ7kg=
+gorm.io/gorm v1.31.1/go.mod h1:XyQVbO2k6YkOis7C2437jSit3SsDK72s7n7rsSHd+Gs=
diff --git a/service/telegram_service/handlers/approval/approver_selection.go b/service/telegram_service/handlers/approval/approver_selection.go
new file mode 100644
index 0000000..a589824
--- /dev/null
+++ b/service/telegram_service/handlers/approval/approver_selection.go
@@ -0,0 +1,194 @@
+package approval
+
+import (
+ "bitrix_balancer_api/core/typescore"
+ "bitrix_balancer_api/telegram_service/keyboard"
+ "bitrix_balancer_api/telegram_service/state"
+ "context"
+ "fmt"
+
+ tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
+ "github.com/sirupsen/logrus"
+)
+
+func (h *Handler) showApproverSelection(bot *tgbotapi.BotAPI, ctx context.Context, chatID int64, telegramID int64, approvalTopic *typescore.ApprovalTopic) {
+ user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID)
+ if err != nil || user == nil || user.ID == nil || user.DepartmentID == nil {
+ return
+ }
+
+ // Получаем список согласующих для этой темы
+ approvers, err := h.getAvailableApproversForTopic(ctx, *user.ID, *user.DepartmentID, approvalTopic)
+ if err != nil {
+ logrus.Errorf("showApproverSelection: getAvailableApproversForTopic err=%v", err)
+ sendText(bot, chatID, "Ошибка при получении списка согласующих.")
+ return
+ }
+
+ if len(approvers) == 0 {
+ sendText(bot, chatID, "⚠️ Нет доступных согласующих для этой темы.")
+ h.States.Clear(ctx, telegramID) //nolint:errcheck
+ return
+ }
+
+ msg := tgbotapi.NewMessage(chatID, "👤 Выберите согласующего:")
+ msg.ParseMode = "HTML"
+ msg.ReplyMarkup = keyboard.BuildApproverSelectionMenu(approvers, 0)
+ bot.Send(msg) //nolint:errcheck
+}
+
+func (h *Handler) HandleApproverSelectionCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, approverID uint64) {
+ ctx := context.Background()
+ chatID := cq.Message.Chat.ID
+ telegramID := cq.From.ID
+
+ bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck
+ bot.Request(tgbotapi.NewDeleteMessage(chatID, cq.Message.MessageID)) //nolint:errcheck
+
+ flowState, err := h.States.Get(ctx, telegramID)
+ if err != nil || flowState == nil {
+ sendText(bot, chatID, "⚠️ Состояние утеряно. Начните заново.")
+ return
+ }
+
+ flowState.SelectedApproverID = approverID
+ flowState.AwaitApproverSelection = false
+
+ h.States.Clear(ctx, telegramID) //nolint:errcheck
+ h.finalizeAndSubmit(bot, ctx, chatID, telegramID, flowState)
+}
+
+func (h *Handler) HandleApproverSelectionPageCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, page int) {
+ ctx := context.Background()
+ chatID := cq.Message.Chat.ID
+ telegramID := cq.From.ID
+
+ bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck
+ bot.Request(tgbotapi.NewDeleteMessage(chatID, cq.Message.MessageID)) //nolint:errcheck
+
+ flowState, err := h.States.Get(ctx, telegramID)
+ if err != nil || flowState == nil {
+ sendText(bot, chatID, "⚠️ Состояние утеряно. Начните заново.")
+ return
+ }
+
+ user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID)
+ if err != nil || user == nil || user.ID == nil || user.DepartmentID == nil {
+ return
+ }
+
+ topic, _ := h.registry.Get(flowState.TopicCode)
+ if topic == nil {
+ return
+ }
+
+ topicCode, _ := topic.TopicCodeFromCollected(flowState.Collected)
+ approvalTopic, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByCodeDB(ctx, topicCode)
+ if approvalTopic == nil {
+ return
+ }
+
+ approvers, err := h.getAvailableApproversForTopic(ctx, *user.ID, *user.DepartmentID, approvalTopic)
+ if err != nil {
+ logrus.Errorf("HandleApproverSelectionPageCallback: getAvailableApproversForTopic err=%v", err)
+ return
+ }
+
+ msg := tgbotapi.NewMessage(chatID, "👤 Выберите согласующего:")
+ msg.ParseMode = "HTML"
+ msg.ReplyMarkup = keyboard.BuildApproverSelectionMenu(approvers, page)
+ bot.Send(msg) //nolint:errcheck
+}
+
+func (h *Handler) getAvailableApproversForTopic(ctx context.Context, userID, departmentID uint64, approvalTopic *typescore.ApprovalTopic) ([]*typescore.User, error) {
+ if approvalTopic.ID == nil || approvalTopic.CategoryID == nil {
+ return nil, fmt.Errorf("invalid topic")
+ }
+
+ // Получаем все иерархии для этого пользователя и отдела
+ hierarchies, _, err := h.ipc.Database.UserHierarchy.GetUserHierarchyListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.UserHierarchy{
+ SubordinateID: &userID,
+ DepartmentID: &departmentID,
+ },
+ })
+ if err != nil {
+ return nil, err
+ }
+
+ // Собираем уникальных согласующих для этой темы или категории
+ approverIDs := make(map[uint64]bool)
+ for _, hier := range hierarchies {
+ if hier.ApproverID == nil {
+ continue
+ }
+
+ // Проверяем совпадение по теме
+ if hier.TopicID != nil && *hier.TopicID == *approvalTopic.ID {
+ approverIDs[*hier.ApproverID] = true
+ continue
+ }
+
+ // Проверяем совпадение по категории
+ if hier.TopicCategoryID != nil && *hier.TopicCategoryID == *approvalTopic.CategoryID {
+ approverIDs[*hier.ApproverID] = true
+ }
+ }
+
+ // Получаем полную информацию о согласующих
+ var approvers []*typescore.User
+ for approverID := range approverIDs {
+ approver, err := h.ipc.Database.User.GetUserByIDDB(ctx, approverID)
+ if err == nil && approver != nil {
+ approvers = append(approvers, approver)
+ }
+ }
+
+ return approvers, nil
+}
+
+func (h *Handler) finalizeAndSubmit(bot *tgbotapi.BotAPI, ctx context.Context, chatID int64, telegramID int64, flowState *state.ApprovalFlowState) {
+ approval, err := h.submitApproval(ctx, bot, telegramID, flowState)
+ if err != nil {
+ logrus.Error("finalizeAndSubmit: submitApproval error", err)
+ bot.Send(tgbotapi.NewMessage(chatID, "Произошла ошибка при отправке заявки. Попробуйте позже.")) //nolint:errcheck
+ return
+ }
+
+ if approval == nil || approval.ID == nil {
+ logrus.Error("finalizeAndSubmit: approval is nil after submitApproval")
+ bot.Send(tgbotapi.NewMessage(chatID, "✅ Отправлено на согласование")) //nolint:errcheck
+ return
+ }
+
+ approverName := "—"
+ if activeStep, _ := h.ipc.Database.ApprovalStep.GetActiveStepDB(ctx, *approval.ID); activeStep != nil && activeStep.ApproverID != nil {
+ if approver, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *activeStep.ApproverID); approver != nil && approver.FullName != nil {
+ approverName = *approver.FullName
+ }
+ }
+
+ topicName := "—"
+ if approval.TopicID != nil {
+ if t, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *approval.TopicID); t != nil && t.Name != nil {
+ topicName = *t.Name
+ }
+ }
+
+ content := "—"
+ if approval.Content != nil {
+ content = *approval.Content
+ }
+
+ confirmMsg := fmt.Sprintf(
+ "✅ Заявка #%d отправлена на согласование\n\n"+
+ "👤 Согласующий: %s\n"+
+ "📋 Тема: %s\n"+
+ "📝 Текст: %s",
+ *approval.ID, approverName, topicName, content,
+ )
+
+ msgChat := tgbotapi.NewMessage(chatID, confirmMsg)
+ msgChat.ParseMode = "HTML"
+ bot.Send(msgChat) //nolint:errcheck
+}
diff --git a/service/telegram_service/handlers/approval/decision.go b/service/telegram_service/handlers/approval/decision.go
new file mode 100644
index 0000000..2f00f13
--- /dev/null
+++ b/service/telegram_service/handlers/approval/decision.go
@@ -0,0 +1,686 @@
+package approval
+
+import (
+ "bitrix_balancer_api/core/typescore"
+ "bitrix_balancer_api/core/utilscore"
+ "bitrix_balancer_api/telegram_service/keyboard"
+ "context"
+ "fmt"
+ tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
+ "github.com/sirupsen/logrus"
+ "strings"
+ "time"
+)
+
+func (h *Handler) processNextStepOrComplete(bot *tgbotapi.BotAPI, ctx context.Context, approval *typescore.Approval, currentStep *typescore.ApprovalStep, approvalCard string, categoryCode string, notifier *Notifier, initiator *typescore.User, collected map[string]string, actualExecutorID uint64) {
+ approvalID := *approval.ID
+
+ nextStep, err := h.ipc.Database.ApprovalStep.GetNextStepDB(ctx, approvalID, *currentStep.StepOrder)
+ if err == nil && nextStep != nil && nextStep.ApproverID != nil {
+ pendingStatus := "pending"
+ nextStep.Status = &pendingStatus
+ h.ipc.Database.ApprovalStep.UpdateApprovalStepDB(ctx, nil, nextStep) //nolint:errcheck
+
+ nextApprover, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *nextStep.ApproverID)
+
+ actualApprover := nextApprover
+ originalApproverID := *nextStep.ApproverID
+ if approval.TopicID != nil {
+ topic, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *approval.TopicID)
+ if topic != nil && topic.CategoryID != nil {
+ if delegations, _, err := h.ipc.Database.ApprovalDelegation.GetApprovalDelegationsListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.ApprovalDelegation{
+ IsActive: utilscore.PointerToBool(true),
+ TopicID: approval.TopicID,
+ },
+ }); err == nil {
+ for _, deleg := range delegations {
+ if deleg.DelegatorID != nil && *deleg.DelegatorID == originalApproverID && deleg.DelegateID != nil {
+ delegate, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *deleg.DelegateID)
+ if delegate != nil && delegate.TelegramID != nil {
+ actualApprover = delegate
+ break
+ }
+ }
+ }
+ }
+ if actualApprover == nextApprover {
+ if delegations, _, err := h.ipc.Database.ApprovalDelegation.GetApprovalDelegationsListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.ApprovalDelegation{
+ IsActive: utilscore.PointerToBool(true),
+ CategoryID: topic.CategoryID,
+ },
+ }); err == nil {
+ for _, deleg := range delegations {
+ if deleg.DelegatorID != nil && *deleg.DelegatorID == originalApproverID && deleg.DelegateID != nil {
+ delegate, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *deleg.DelegateID)
+ if delegate != nil && delegate.TelegramID != nil {
+ actualApprover = delegate
+ break
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ // Уведомляем инициатора о прогрессе
+ if initiator.TelegramID != nil {
+ currentApproverName := "—"
+ if currentStep.ApproverNameSnapshot != nil {
+ currentApproverName = *currentStep.ApproverNameSnapshot
+ }
+
+ nextApproverName := "—"
+ if actualApprover != nil && actualApprover.FullName != nil {
+ nextApproverName = *actualApprover.FullName
+ }
+
+ topicName := "—"
+ if approval.TopicID != nil {
+ if t, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *approval.TopicID); t != nil && t.Name != nil {
+ topicName = *t.Name
+ }
+ }
+
+ content := "—"
+ if approval.Content != nil {
+ content = *approval.Content
+ }
+
+ progressText := fmt.Sprintf(
+ "⏩ Заявка #%d: на согласовании\n\n"+
+ "✅ Согласовал: %s\n"+
+ "⏳ Передано: %s\n\n"+
+ "📋 Тема: %s\n"+
+ "📝 Текст: %s",
+ approvalID, currentApproverName, nextApproverName, topicName, content,
+ )
+
+ progressMsg := tgbotapi.NewMessage(*initiator.TelegramID, progressText)
+ progressMsg.ParseMode = "HTML"
+ progressMsg.ReplyMarkup = keyboard.BuildApprovalStagesButton(approvalID)
+ bot.Send(progressMsg) //nolint:errcheck
+ }
+
+ currentStepIsDelegate := currentStep.ApproverID != nil && *currentStep.ApproverID != actualExecutorID
+
+ if currentStep.ApproverID != nil {
+ mainApprover, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *currentStep.ApproverID)
+ if mainApprover != nil && mainApprover.TelegramID != nil {
+ nextName := "следующему согласующему"
+ if actualApprover != nil && actualApprover.FullName != nil {
+ nextName = *actualApprover.FullName
+ }
+
+ messageText := ""
+ if currentStepIsDelegate {
+ executor, _ := h.ipc.Database.User.GetUserByIDDB(ctx, actualExecutorID)
+ executorName := "—"
+ if executor != nil && executor.FullName != nil {
+ executorName = *executor.FullName
+ }
+ messageText = fmt.Sprintf(
+ "➡️ Ваш делегат согласовал заявку #%d и передал: %s\n\n"+
+ "👤 Делегат: %s\n"+
+ "%s",
+ approvalID, nextName, executorName, approvalCard,
+ )
+ } else {
+ messageText = fmt.Sprintf(
+ "➡️ Заявка #%d передана: %s\n\n%s",
+ approvalID, nextName, approvalCard,
+ )
+ }
+
+ notifyMsg := tgbotapi.NewMessage(*mainApprover.TelegramID, messageText)
+ notifyMsg.ParseMode = "HTML"
+ bot.Send(notifyMsg) //nolint:errcheck
+ }
+ }
+
+ if actualApprover != nil && actualApprover.TelegramID != nil {
+ notifier.NotifyApprover(bot, actualApprover, initiator, approval, collected)
+ }
+
+ if actualApprover != nextApprover && nextApprover != nil && nextApprover.TelegramID != nil {
+ delegateName := "—"
+ if actualApprover != nil && actualApprover.FullName != nil {
+ delegateName = *actualApprover.FullName
+ }
+ notifyOwner := tgbotapi.NewMessage(*nextApprover.TelegramID, fmt.Sprintf(
+ "ℹ️ Новая заявка #%d передана делегату\n\n"+
+ "👤 Делегат: %s\n"+
+ "%s",
+ approvalID, delegateName, approvalCard,
+ ))
+ notifyOwner.ParseMode = "HTML"
+ bot.Send(notifyOwner) //nolint:errcheck
+ }
+ return
+ }
+
+ // Последний шаг - все остальное без изменений
+ approvedStatus := "approved"
+ approval.Status = &approvedStatus
+ h.ipc.Database.Approval.UpdateApprovalDB(ctx, nil, approval) //nolint:errcheck
+
+ lastStepIsDelegate := currentStep.ApproverID != nil && *currentStep.ApproverID != actualExecutorID
+
+ if currentStep.ApproverID != nil {
+ mainApprover, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *currentStep.ApproverID)
+ if mainApprover != nil && mainApprover.TelegramID != nil {
+ messageText := ""
+ if lastStepIsDelegate {
+ executor, _ := h.ipc.Database.User.GetUserByIDDB(ctx, actualExecutorID)
+ executorName := "—"
+ if executor != nil && executor.FullName != nil {
+ executorName = *executor.FullName
+ }
+ messageText = fmt.Sprintf(
+ "🎉 Ваш делегат полностью согласовал заявку #%d\n\n"+
+ "👤 Делегат: %s\n"+
+ "%s\n\nИнициатор уведомлён.",
+ approvalID, executorName, approvalCard,
+ )
+ } else {
+ messageText = fmt.Sprintf(
+ "🎉 Заявка #%d полностью согласована\n\n%s\n\nИнициатор уведомлён.",
+ approvalID, approvalCard,
+ )
+ }
+
+ notifyMsg := tgbotapi.NewMessage(*mainApprover.TelegramID, messageText)
+ notifyMsg.ParseMode = "HTML"
+ bot.Send(notifyMsg) //nolint:errcheck
+ }
+ }
+
+ if approval.TopicID != nil {
+ topic, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *approval.TopicID)
+ if topic != nil && topic.TaskTemplate != nil && *topic.TaskTemplate != "" && topic.CategoryID != nil {
+ // Ищем исполнителя
+ executor, err := h.ipc.Database.UserHierarchy.GetExecutorDB(ctx, *initiator.ID, *initiator.DepartmentID, *approval.TopicID, *topic.CategoryID)
+ if err != nil {
+ logrus.Errorf("GetExecutorDB failed: %v", err)
+ } else if executor == nil {
+ logrus.Warnf("No executor found for params: ...")
+ }
+
+ if executor != nil && executor.ID != nil {
+ existingTasks, _, _ := h.ipc.Database.ApprovalTasks.GetApprovalTasksListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.ApprovalTask{
+ ApprovalID: approval.ID,
+ },
+ })
+ if len(existingTasks) > 0 {
+ logrus.Warnf("processNextStepOrComplete: task already exists for approvalID=%d, skipping", *approval.ID)
+ return
+ }
+
+ taskStatus := "pending"
+ task := &typescore.ApprovalTask{
+ ApprovalID: approval.ID,
+ ExecutorID: executor.ID,
+ TaskText: topic.TaskTemplate,
+ Status: &taskStatus,
+ }
+
+ createdTask, _, err := h.ipc.Database.ApprovalTasks.CreateApprovalTaskDB(ctx, nil, task, true)
+ if err != nil {
+ logrus.Errorf("processNextStepOrComplete: CreateApprovalTaskDB err=%v", err)
+ }
+ h.notifyExecutor(bot, ctx, executor, initiator, approval, collected, createdTask)
+ if err != nil {
+ logrus.Errorf("processNextStepOrComplete: CreateApprovalTaskDB err=%v", err)
+ } else if createdTask != nil && executor.TelegramID != nil {
+ // Уведомляем исполнителя
+ h.notifyExecutor(bot, ctx, executor, initiator, approval, collected, createdTask)
+ }
+ }
+ }
+ }
+
+ if initiator.TelegramID != nil {
+ lastApprover, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *currentStep.ApproverID)
+ notifier.NotifyInitiatorApproved(bot, initiator, approval, collected, lastApprover)
+ }
+
+ if approval.TopicID != nil && currentStep.ApproverID != nil {
+ if delegations, _, err := h.ipc.Database.ApprovalDelegation.GetApprovalDelegationsListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.ApprovalDelegation{
+ IsActive: utilscore.PointerToBool(true),
+ TopicID: approval.TopicID,
+ },
+ }); err == nil {
+ for _, deleg := range delegations {
+ if deleg.DelegatorID != nil && deleg.DelegateID != nil && *deleg.DelegateID == *currentStep.ApproverID {
+ delegator, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *deleg.DelegatorID)
+ if delegator != nil && delegator.TelegramID != nil {
+ lastApprover, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *currentStep.ApproverID)
+ delegateName := "—"
+ if lastApprover != nil && lastApprover.FullName != nil {
+ delegateName = *lastApprover.FullName
+ }
+ notifyOwner := tgbotapi.NewMessage(*delegator.TelegramID, fmt.Sprintf(
+ "✅ Заявка #%d согласована вашим делегатом\n\n"+
+ "👤 Делегат: %s\n"+
+ "%s",
+ approvalID, delegateName, approvalCard,
+ ))
+ notifyOwner.ParseMode = "HTML"
+ bot.Send(notifyOwner) //nolint:errcheck
+ }
+ }
+ }
+ }
+ }
+
+ directors, _ := h.ipc.Database.User.GetDirectorsDB(ctx)
+ for _, director := range directors {
+ if director.TelegramID != nil {
+ notifier.NotifyDirector(bot, director, initiator, approval, collected)
+ }
+ }
+
+ if observers, err := h.ipc.Database.User.GetObserversForCategoryDB(ctx, categoryCode); err == nil && len(observers) > 0 {
+ stepApprover, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *currentStep.ApproverID)
+ notifier.NotifyObserversDecision(bot, observers, stepApprover, initiator, approval, collected, true)
+ }
+}
+
+// HandleDecisionWithChat — вызывается при текстовом вводе комментария.
+// chatID — чат согласующего для отправки обратной связи.
+func (h *Handler) HandleDecisionWithChat(bot *tgbotapi.BotAPI, approverChatID int64, approvalID uint64, approved bool, comment string) {
+ h.handleDecision(bot, nil, approverChatID, approvalID, approved, comment)
+}
+
+// HandleDecision — вызывается при нажатии inline-кнопки.
+func (h *Handler) HandleDecision(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, approvalID uint64, approved bool, comment string) {
+ var approverChatID int64
+ if cq != nil {
+ bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck
+ approverChatID = cq.Message.Chat.ID
+ }
+ h.handleDecision(bot, cq, approverChatID, approvalID, approved, comment)
+}
+
+// handleDecision — основная логика, принимает chatID явно.
+func (h *Handler) handleDecision(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, approverChatID int64, approvalID uint64, approved bool, comment string) {
+ ctx := context.Background()
+
+ if cq != nil {
+ bot.Request(tgbotapi.NewDeleteMessage(cq.Message.Chat.ID, cq.Message.MessageID)) //nolint:errcheck
+ }
+
+ var currentUserID uint64
+ if cq != nil {
+ user, _ := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, cq.From.ID)
+ if user == nil || user.ID == nil {
+ return
+ }
+ currentUserID = *user.ID
+ } else {
+ user, _ := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, approverChatID)
+ if user == nil || user.ID == nil {
+ return
+ }
+ currentUserID = *user.ID
+ }
+
+ actualExecutor, _ := h.ipc.Database.User.GetUserByIDDB(ctx, currentUserID)
+
+ approval, err := h.ipc.Database.Approval.GetApprovalByIDDB(ctx, approvalID)
+ if err != nil || approval == nil {
+ logrus.Errorf("handleDecision: approval not found id=%d err=%v", approvalID, err)
+ if approverChatID != 0 {
+ sendText(bot, approverChatID, "⚠️ Заявка не найдена.")
+ }
+ return
+ }
+
+ additionalApprovers, _, _ := h.ipc.Database.ApprovalAdditionalApprover.GetApprovalAdditionalApproversListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.ApprovalAdditionalApprover{
+ ApprovalID: &approvalID,
+ },
+ })
+ var isAdditionalApprover bool
+ var additionalApproverRecord *typescore.ApprovalAdditionalApprover
+ for _, aa := range additionalApprovers {
+ if aa.ApproverID != nil && *aa.ApproverID == currentUserID && aa.Status != nil && *aa.Status == "pending" {
+ isAdditionalApprover = true
+ additionalApproverRecord = aa
+ break
+ }
+ }
+
+ initiator, err := h.ipc.Database.User.GetUserByIDDB(ctx, *approval.InitiatorID)
+ if err != nil || initiator == nil {
+ logrus.Errorf("handleDecision: initiator not found err=%v", err)
+ return
+ }
+
+ initiatorName := "—"
+ if initiator.FullName != nil {
+ initiatorName = *initiator.FullName
+ }
+
+ topicName := "—"
+ if approval.TopicID != nil {
+ if t, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *approval.TopicID); t != nil && t.Name != nil {
+ topicName = *t.Name
+ }
+ }
+
+ content := "—"
+ if approval.Content != nil {
+ content = *approval.Content
+ }
+
+ approvalCard := fmt.Sprintf(
+ "👤 Инициатор: %s\n"+
+ "📋 Тема: %s\n"+
+ "📝 Текст: %s",
+ initiatorName, topicName, content,
+ )
+
+ categoryCode := h.getTopicCodeByApproval(ctx, approval)
+ topic, err := h.registry.Get(categoryCode)
+ if err != nil {
+ logrus.Errorf("handleDecision: topic not found code=%s err=%v", categoryCode, err)
+ return
+ }
+ notifier := NewNotifier(h.ipc, topic)
+ collected := h.getCollectedFromApproval(ctx, approval)
+
+ now := time.Now()
+
+ // ОБРАБОТКА ОТКЛОНЕНИЯ
+ if !approved {
+ if isAdditionalApprover {
+ rejectedStatus := "rejected"
+ additionalApproverRecord.Status = &rejectedStatus
+ additionalApproverRecord.Comment = &comment
+ additionalApproverRecord.ActedAt = &now
+ h.ipc.Database.ApprovalAdditionalApprover.UpdateApprovalAdditionalApproverDB(ctx, nil, additionalApproverRecord) //nolint:errcheck
+
+ rejectedStatus = "rejected"
+ approval.Status = &rejectedStatus
+ h.ipc.Database.Approval.UpdateApprovalDB(ctx, nil, approval) //nolint:errcheck
+
+ if approverChatID != 0 {
+ commentText := ""
+ if comment != "" {
+ commentText = fmt.Sprintf("\n💬 Комментарий: %s", comment)
+ }
+ sendText(bot, approverChatID, fmt.Sprintf(
+ "❌ Заявка #%d отклонена\n\n%s%s",
+ approvalID, approvalCard, commentText,
+ ))
+ }
+
+ if initiator.TelegramID != nil {
+ currentApprover, _ := h.ipc.Database.User.GetUserByIDDB(ctx, currentUserID)
+ notifier.NotifyInitiatorRejected(bot, initiator, currentApprover, approval, collected, comment)
+ }
+
+ if observers, err := h.ipc.Database.User.GetObserversForCategoryDB(ctx, categoryCode); err == nil && len(observers) > 0 {
+ currentApprover, _ := h.ipc.Database.User.GetUserByIDDB(ctx, currentUserID)
+ notifier.NotifyObserversDecision(bot, observers, currentApprover, initiator, approval, collected, false)
+ }
+ return
+ }
+
+ step, err := h.ipc.Database.ApprovalStep.GetActiveStepDB(ctx, approvalID)
+ if err != nil || step == nil {
+ logrus.Warnf("handleDecision: active step not found approvalID=%d err=%v", approvalID, err)
+ if approverChatID != 0 {
+ sendText(bot, approverChatID, "⚠️ Шаг согласования не найден или уже обработан.")
+ }
+ return
+ }
+
+ // ИСПРАВЛЕНИЕ 2: Проверяем, является ли исполнитель делегатом
+ isDelegate := step.ApproverID != nil && *step.ApproverID != currentUserID
+ var originalApprover *typescore.User
+ if isDelegate {
+ originalApprover, _ = h.ipc.Database.User.GetUserByIDDB(ctx, *step.ApproverID)
+ }
+
+ rejectedStatus := "rejected"
+ step.Status = &rejectedStatus
+ step.Comment = &comment
+ step.ActedAt = &now
+
+ // Сохраняем имя фактического исполнителя (делегата)
+ if actualExecutor != nil && actualExecutor.FullName != nil {
+ step.ApproverNameSnapshot = actualExecutor.FullName
+ }
+ h.ipc.Database.ApprovalStep.UpdateApprovalStepDB(ctx, nil, step) //nolint:errcheck
+
+ rejectedStatus = "rejected"
+ approval.Status = &rejectedStatus
+ h.ipc.Database.Approval.UpdateApprovalDB(ctx, nil, approval) //nolint:errcheck
+
+ if approverChatID != 0 {
+ commentText := ""
+ if comment != "" {
+ commentText = fmt.Sprintf("\n💬 Комментарий: %s", comment)
+ }
+ sendText(bot, approverChatID, fmt.Sprintf(
+ "❌ Заявка #%d отклонена\n\n%s%s",
+ approvalID, approvalCard, commentText,
+ ))
+ }
+
+ // ИСПРАВЛЕНИЕ 2: Уведомляем оригинального согласующего если решение принял делегат
+ if isDelegate && originalApprover != nil && originalApprover.TelegramID != nil {
+ executorName := "—"
+ if actualExecutor != nil && actualExecutor.FullName != nil {
+ executorName = *actualExecutor.FullName
+ }
+ commentText := ""
+ if comment != "" {
+ commentText = fmt.Sprintf("\n💬 Комментарий: %s", comment)
+ }
+ notifyMsg := tgbotapi.NewMessage(*originalApprover.TelegramID, fmt.Sprintf(
+ "ℹ️ Ваш делегат отклонил заявку #%d\n\n"+
+ "👤 Делегат: %s\n"+
+ "%s%s",
+ approvalID, executorName, approvalCard, commentText,
+ ))
+ notifyMsg.ParseMode = "HTML"
+ bot.Send(notifyMsg) //nolint:errcheck
+ }
+
+ if initiator.TelegramID != nil {
+ stepApprover, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *step.ApproverID)
+ notifier.NotifyInitiatorRejected(bot, initiator, stepApprover, approval, collected, comment)
+ }
+
+ if observers, err := h.ipc.Database.User.GetObserversForCategoryDB(ctx, categoryCode); err == nil && len(observers) > 0 {
+ stepApprover, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *step.ApproverID)
+ notifier.NotifyObserversDecision(bot, observers, stepApprover, initiator, approval, collected, false)
+ }
+ return
+ }
+
+ // ОБРАБОТКА ОДОБРЕНИЯ
+ if isAdditionalApprover {
+ approvedStatus := "approved"
+ additionalApproverRecord.Status = &approvedStatus
+ additionalApproverRecord.ActedAt = &now
+ h.ipc.Database.ApprovalAdditionalApprover.UpdateApprovalAdditionalApproverDB(ctx, nil, additionalApproverRecord) //nolint:errcheck
+
+ step, err := h.ipc.Database.ApprovalStep.GetActiveStepDB(ctx, approvalID)
+ if err != nil || step == nil {
+ logrus.Warnf("handleDecision: active step not found approvalID=%d err=%v", approvalID, err)
+ return
+ }
+
+ allAdditionalApproved := true
+ for _, aa := range additionalApprovers {
+ if aa.ID != nil && additionalApproverRecord.ID != nil && *aa.ID == *additionalApproverRecord.ID {
+ continue
+ }
+ if aa.Status == nil || *aa.Status == "pending" {
+ allAdditionalApproved = false
+ break
+ }
+ }
+
+ mainApproverApproved := step.Status != nil && *step.Status == "approved"
+
+ if approverChatID != 0 {
+ if !mainApproverApproved {
+ sendText(bot, approverChatID, fmt.Sprintf(
+ "✅ Вы одобрили заявку #%d\n\n%s\n\nОжидается решение основного согласующего.",
+ approvalID, approvalCard,
+ ))
+ } else if !allAdditionalApproved {
+ pendingCount := 0
+ var pendingNames []string
+ for _, aa := range additionalApprovers {
+ if aa.ID != nil && additionalApproverRecord.ID != nil && *aa.ID == *additionalApproverRecord.ID {
+ continue
+ }
+ if aa.Status != nil && *aa.Status == "pending" && aa.ApproverID != nil {
+ pendingCount++
+ approver, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *aa.ApproverID)
+ if approver != nil && approver.FullName != nil {
+ pendingNames = append(pendingNames, *approver.FullName)
+ }
+ }
+ }
+
+ pendingText := ""
+ if pendingCount > 0 {
+ pendingText = fmt.Sprintf("\n\n⏳ Ожидается решение других дополнительных согласующих (%d):\n• %s",
+ pendingCount, strings.Join(pendingNames, "\n• "))
+ }
+
+ sendText(bot, approverChatID, fmt.Sprintf(
+ "✅ Вы одобрили заявку #%d\n\n%s%s",
+ approvalID, approvalCard, pendingText,
+ ))
+ } else {
+ sendText(bot, approverChatID, fmt.Sprintf(
+ "✅ Вы одобрили заявку #%d\n\n%s\n\nВсе согласующие одобрили заявку.",
+ approvalID, approvalCard,
+ ))
+ }
+ }
+
+ if mainApproverApproved && allAdditionalApproved {
+ if step.ApproverID != nil {
+ mainApprover, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *step.ApproverID)
+ if mainApprover != nil && mainApprover.TelegramID != nil {
+ notifyMsg := tgbotapi.NewMessage(*mainApprover.TelegramID, fmt.Sprintf(
+ "✅ Все дополнительные согласующие одобрили заявку #%d\n\n%s",
+ approvalID, approvalCard,
+ ))
+ notifyMsg.ParseMode = "HTML"
+ bot.Send(notifyMsg) //nolint:errcheck
+ }
+ }
+
+ h.processNextStepOrComplete(bot, ctx, approval, step, approvalCard, categoryCode, notifier, initiator, collected, currentUserID)
+ }
+
+ return
+ }
+
+ step, err := h.ipc.Database.ApprovalStep.GetActiveStepDB(ctx, approvalID)
+ if err != nil || step == nil {
+ logrus.Warnf("handleDecision: active step not found approvalID=%d err=%v", approvalID, err)
+ if approverChatID != 0 {
+ sendText(bot, approverChatID, "⚠️ Шаг согласования не найден или уже обработан.")
+ }
+ return
+ }
+
+ // ИСПРАВЛЕНИЕ 2: Проверяем, является ли исполнитель делегатом
+ isDelegate := step.ApproverID != nil && *step.ApproverID != currentUserID
+ var originalApprover *typescore.User
+ if isDelegate {
+ originalApprover, _ = h.ipc.Database.User.GetUserByIDDB(ctx, *step.ApproverID)
+ }
+
+ approvedStatus := "approved"
+ step.Status = &approvedStatus
+ step.ActedAt = &now
+
+ // Сохраняем имя фактического исполнителя (делегата)
+ if actualExecutor != nil && actualExecutor.FullName != nil {
+ step.ApproverNameSnapshot = actualExecutor.FullName
+ }
+ h.ipc.Database.ApprovalStep.UpdateApprovalStepDB(ctx, nil, step) //nolint:errcheck
+
+ allAdditionalApproved := true
+ pendingAdditional := []*typescore.ApprovalAdditionalApprover{}
+ for _, aa := range additionalApprovers {
+ if aa.Status == nil || *aa.Status == "pending" {
+ allAdditionalApproved = false
+ pendingAdditional = append(pendingAdditional, aa)
+ }
+ if aa.Status != nil && *aa.Status == "rejected" {
+ allAdditionalApproved = false
+ break
+ }
+ }
+
+ if !allAdditionalApproved {
+ if approverChatID != 0 {
+ if len(pendingAdditional) > 0 {
+ var pendingNames []string
+ for _, aa := range pendingAdditional {
+ if aa.ApproverID != nil {
+ approver, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *aa.ApproverID)
+ if approver != nil && approver.FullName != nil {
+ pendingNames = append(pendingNames, *approver.FullName)
+ }
+ }
+ }
+
+ pendingText := fmt.Sprintf("\n\n⏳ Ожидается решение дополнительных согласующих (%d):\n• %s",
+ len(pendingAdditional), strings.Join(pendingNames, "\n• "))
+
+ sendText(bot, approverChatID, fmt.Sprintf(
+ "✅ Вы одобрили заявку #%d\n\n%s%s",
+ approvalID, approvalCard, pendingText,
+ ))
+ } else {
+ sendText(bot, approverChatID, fmt.Sprintf(
+ "✅ Вы одобрили заявку #%d\n\n%s",
+ approvalID, approvalCard,
+ ))
+ }
+ }
+ return
+ }
+
+ if approverChatID != 0 {
+ sendText(bot, approverChatID, fmt.Sprintf(
+ "✅ Вы одобрили заявку #%d\n\n%s\n\nВсе согласующие одобрили заявку.",
+ approvalID, approvalCard,
+ ))
+ }
+
+ if isDelegate && originalApprover != nil && originalApprover.TelegramID != nil {
+ executorName := "—"
+ if actualExecutor != nil && actualExecutor.FullName != nil {
+ executorName = *actualExecutor.FullName
+ }
+ notifyMsg := tgbotapi.NewMessage(*originalApprover.TelegramID, fmt.Sprintf(
+ "ℹ️ Ваш делегат одобрил заявку #%d\n\n"+
+ "👤 Делегат: %s\n"+
+ "%s",
+ approvalID, executorName, approvalCard,
+ ))
+ notifyMsg.ParseMode = "HTML"
+ bot.Send(notifyMsg) //nolint:errcheck
+ }
+
+ h.processNextStepOrComplete(bot, ctx, approval, step, approvalCard, categoryCode, notifier, initiator, collected, currentUserID)
+}
diff --git a/service/telegram_service/handlers/approval/delegation.go b/service/telegram_service/handlers/approval/delegation.go
new file mode 100644
index 0000000..f52077c
--- /dev/null
+++ b/service/telegram_service/handlers/approval/delegation.go
@@ -0,0 +1,703 @@
+package approval
+
+import (
+ "bitrix_balancer_api/core/typescore"
+ "bitrix_balancer_api/core/utilscore"
+ "bitrix_balancer_api/telegram_service/keyboard"
+ "bitrix_balancer_api/telegram_service/state"
+ "context"
+ "fmt"
+ "strings"
+ "time"
+
+ tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
+ "github.com/sirupsen/logrus"
+)
+
+func (h *Handler) HandleDelegationMainMenu(bot *tgbotapi.BotAPI, chatID int64, telegramID int64) {
+ ctx := context.Background()
+
+ user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID)
+ if err != nil || user == nil || user.ID == nil {
+ return
+ }
+
+ isApprover, _ := h.ipc.Database.User.IsApproverDB(ctx, *user.ID)
+ if !isApprover {
+ sendText(bot, chatID, "У вас нет прав согласующего.")
+ return
+ }
+
+ msg := tgbotapi.NewMessage(chatID, "🔄 Делегирование прав\n\nВыберите действие:")
+ msg.ParseMode = "HTML"
+ msg.ReplyMarkup = keyboard.BuildDelegationMainMenu()
+ bot.Send(msg) //nolint:errcheck
+}
+
+func (h *Handler) HandleDelegationMenu(bot *tgbotapi.BotAPI, chatID int64, telegramID int64) {
+ h.HandleDelegationMenuPage(bot, chatID, telegramID, 0, 0)
+}
+
+func (h *Handler) HandleDelegationMenuPage(bot *tgbotapi.BotAPI, chatID int64, telegramID int64, page int, prevMessageID int) {
+ ctx := context.Background()
+
+ user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID)
+ if err != nil || user == nil || user.ID == nil {
+ return
+ }
+
+ categories, err := h.getApproverCategories(ctx, *user.ID)
+ if err != nil {
+ logrus.Errorf("HandleDelegationMenu: getApproverCategories err=%v", err)
+ sendText(bot, chatID, "Ошибка при получении списка категорий.")
+ return
+ }
+
+ if len(categories) == 0 {
+ sendText(bot, chatID, "Нет категорий, где вы являетесь согласующим.")
+ return
+ }
+
+ if prevMessageID != 0 {
+ bot.Request(tgbotapi.NewDeleteMessage(chatID, prevMessageID)) //nolint:errcheck
+ }
+
+ msg := tgbotapi.NewMessage(chatID, "🔄 Делегирование прав\n\nВыберите категорию:")
+ msg.ParseMode = "HTML"
+ msg.ReplyMarkup = keyboard.BuildDelegationCategoryMenu(categories, page)
+ bot.Send(msg) //nolint:errcheck
+}
+
+func (h *Handler) HandleDelegationCategoryCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, categoryID uint64) {
+ h.HandleDelegationCategoryCallbackPage(bot, cq, categoryID, 0)
+}
+
+func (h *Handler) HandleDelegationCategoryCallbackPage(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, categoryID uint64, page int) {
+ ctx := context.Background()
+ chatID := cq.Message.Chat.ID
+ telegramID := cq.From.ID
+
+ bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck
+ bot.Request(tgbotapi.NewDeleteMessage(chatID, cq.Message.MessageID)) //nolint:errcheck
+
+ category, _ := h.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, categoryID)
+ categoryName := "—"
+ if category != nil && category.Name != nil {
+ categoryName = *category.Name
+ }
+
+ topics, _, err := h.ipc.Database.ApprovalTopic.GetApprovalTopicsListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.ApprovalTopic{CategoryID: &categoryID},
+ })
+ if err != nil {
+ logrus.Errorf("HandleDelegationCategoryCallback: GetApprovalTopicsListDB err=%v", err)
+ return
+ }
+
+ h.States.SetDelegation(ctx, telegramID, &state.DelegationFlowState{
+ CategoryID: categoryID,
+ Stage: "select_topic",
+ }) //nolint:errcheck
+
+ msg := tgbotapi.NewMessage(chatID, fmt.Sprintf("📋 Категория: %s\n\nВыберите тему или делегируйте всю категорию:", categoryName))
+ msg.ParseMode = "HTML"
+ msg.ReplyMarkup = keyboard.BuildDelegationTopicMenu(topics, categoryID, page)
+ bot.Send(msg) //nolint:errcheck
+}
+
+func (h *Handler) HandleDelegationTopicCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, topicID uint64) {
+ h.HandleDelegationTopicCallbackPage(bot, cq, topicID, 0)
+}
+
+func (h *Handler) HandleDelegationAllCategoryCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, categoryID uint64) {
+ h.HandleDelegationSelectUserPage(bot, cq, categoryID, 0, 0)
+}
+
+func (h *Handler) HandleDelegationTopicCallbackPage(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, topicID uint64, page int) {
+ ctx := context.Background()
+ telegramID := cq.From.ID
+
+ topic, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, topicID)
+ if topic == nil || topic.CategoryID == nil {
+ return
+ }
+
+ delegationState, _ := h.States.GetDelegation(ctx, telegramID)
+ if delegationState == nil {
+ delegationState = &state.DelegationFlowState{}
+ }
+ delegationState.CategoryID = *topic.CategoryID
+ delegationState.TopicID = topicID
+ delegationState.Stage = "select_user"
+ h.States.SetDelegation(ctx, telegramID, delegationState) //nolint:errcheck
+
+ h.HandleDelegationSelectUserPage(bot, cq, *topic.CategoryID, topicID, page)
+}
+
+func (h *Handler) HandleDelegationSelectUserPage(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, categoryID, topicID uint64, page int) {
+ ctx := context.Background()
+ chatID := cq.Message.Chat.ID
+ telegramID := cq.From.ID
+
+ bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck
+ bot.Request(tgbotapi.NewDeleteMessage(chatID, cq.Message.MessageID)) //nolint:errcheck
+
+ user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID)
+ if err != nil || user == nil || user.ID == nil {
+ return
+ }
+
+ users, _, err := h.ipc.Database.User.GetUsersListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.User{
+ IsBlocked: utilscore.PointerToBool(false),
+ },
+ })
+ if err != nil {
+ logrus.Errorf("HandleDelegationSelectUserPage: GetUsersListDB err=%v", err)
+ return
+ }
+
+ var availableUsers []*typescore.User
+ for _, u := range users {
+ if u.ID != nil && *u.ID != *user.ID {
+ availableUsers = append(availableUsers, u)
+ }
+ }
+
+ if len(availableUsers) == 0 {
+ sendText(bot, chatID, "Нет доступных пользователей для делегирования.")
+ return
+ }
+
+ scopeName := ""
+ if topicID > 0 {
+ topic, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, topicID)
+ if topic != nil && topic.Name != nil {
+ scopeName = *topic.Name
+ }
+ } else {
+ category, _ := h.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, categoryID)
+ if category != nil && category.Name != nil {
+ scopeName = *category.Name + " (все права)"
+ }
+ }
+
+ msg := tgbotapi.NewMessage(chatID, fmt.Sprintf("📋 Тема: %s\n\nВыберите пользователя:", scopeName))
+ msg.ParseMode = "HTML"
+ msg.ReplyMarkup = keyboard.BuildDelegationUserMenu(availableUsers, categoryID, topicID, page)
+ bot.Send(msg) //nolint:errcheck
+}
+
+func (h *Handler) HandleDelegationUserCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, delegateID uint64) {
+ ctx := context.Background()
+ chatID := cq.Message.Chat.ID
+ telegramID := cq.From.ID
+
+ bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck
+ bot.Request(tgbotapi.NewDeleteMessage(chatID, cq.Message.MessageID)) //nolint:errcheck
+
+ delegationState, err := h.States.GetDelegation(ctx, telegramID)
+ if err != nil || delegationState == nil {
+ sendText(bot, chatID, "⚠️ Состояние делегирования утеряно. Начните заново.")
+ return
+ }
+
+ user, _ := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID)
+ if user == nil || user.ID == nil {
+ return
+ }
+
+ // Проверка на существующее активное делегирование
+ allDelegations, _, err := h.ipc.Database.ApprovalDelegation.GetApprovalDelegationsListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.ApprovalDelegation{
+ DelegatorID: user.ID,
+ IsActive: utilscore.PointerToBool(true),
+ },
+ })
+ if err == nil {
+ for _, d := range allDelegations {
+ conflict := h.isDelegationConflict(ctx, d, delegationState.CategoryID, delegationState.TopicID)
+ if conflict {
+ h.sendDelegationAlreadyExists(bot, chatID, d, telegramID)
+ return
+ }
+ }
+ }
+
+ delegationState.DelegateID = delegateID
+ delegationState.Stage = "input_date"
+ h.States.SetDelegation(ctx, telegramID, delegationState) //nolint:errcheck
+
+ delegate, _ := h.ipc.Database.User.GetUserByIDDB(ctx, delegateID)
+ delegateName := "—"
+ if delegate != nil && delegate.FullName != nil {
+ delegateName = *delegate.FullName
+ }
+
+ msg := tgbotapi.NewMessage(chatID, fmt.Sprintf(
+ "👤 Делегат: %s\n\n"+
+ "Введите дату и время окончания делегирования в формате:\n"+
+ "ДД.ММ.ГГГГ ЧЧ:ММ или ДД.ММ.ГГГГ\n\n"+
+ "Например: 31.12.2024 18:00 или 31.12.2024",
+ delegateName,
+ ))
+ msg.ParseMode = "HTML"
+ msg.ReplyMarkup = keyboard.BuildDelegationBackToUsers(delegationState.CategoryID, delegationState.TopicID)
+ bot.Send(msg) //nolint:errcheck
+}
+
+func (h *Handler) HandleDelegationDateInput(bot *tgbotapi.BotAPI, msg *tgbotapi.Message) bool {
+ ctx := context.Background()
+ telegramID := msg.From.ID
+ chatID := msg.Chat.ID
+
+ delegationState, err := h.States.GetDelegation(ctx, telegramID)
+ if err != nil || delegationState == nil || delegationState.Stage != "input_date" {
+ return false
+ }
+
+ dateStr := strings.TrimSpace(msg.Text)
+ var validUntil time.Time
+
+ if t, err := time.Parse("02.01.2006 15:04", dateStr); err == nil {
+ validUntil = t
+ } else if t, err := time.Parse("02.01.2006", dateStr); err == nil {
+ validUntil = time.Date(t.Year(), t.Month(), t.Day(), 23, 59, 59, 0, t.Location())
+ } else {
+ sendText(bot, chatID, "⚠️ Неверный формат даты. Используйте ДД.ММ.ГГГГ ЧЧ:ММ или ДД.ММ.ГГГГ")
+ return true
+ }
+
+ if validUntil.Before(time.Now()) {
+ sendText(bot, chatID, "⚠️ Дата окончания не может быть в прошлом.")
+ return true
+ }
+
+ user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID)
+ if err != nil || user == nil || user.ID == nil {
+ return true
+ }
+
+ // ИСПРАВЛЕНИЕ 1: Проверяем, является ли текущий пользователь делегатом
+ // Если да - создаём делегирование от имени оригинального согласующего
+ actualDelegatorID := user.ID
+
+ if delegationState.TopicID > 0 {
+ // Проверяем делегирование по теме
+ existingDelegations, _, err := h.ipc.Database.ApprovalDelegation.GetApprovalDelegationsListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.ApprovalDelegation{
+ DelegateID: user.ID,
+ TopicID: &delegationState.TopicID,
+ IsActive: utilscore.PointerToBool(true),
+ },
+ })
+ if err == nil && len(existingDelegations) > 0 && existingDelegations[0].DelegatorID != nil {
+ // Пользователь сам является делегатом - используем оригинального делегатора
+ actualDelegatorID = existingDelegations[0].DelegatorID
+ }
+ } else {
+ // Проверяем делегирование по категории
+ existingDelegations, _, err := h.ipc.Database.ApprovalDelegation.GetApprovalDelegationsListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.ApprovalDelegation{
+ DelegateID: user.ID,
+ CategoryID: &delegationState.CategoryID,
+ IsActive: utilscore.PointerToBool(true),
+ },
+ })
+ if err == nil && len(existingDelegations) > 0 && existingDelegations[0].DelegatorID != nil {
+ actualDelegatorID = existingDelegations[0].DelegatorID
+ }
+ }
+
+ isActive := true
+ delegation := &typescore.ApprovalDelegation{
+ DelegatorID: actualDelegatorID, // Используем оригинального делегатора
+ DelegateID: &delegationState.DelegateID,
+ ValidUntil: &validUntil,
+ IsActive: &isActive,
+ }
+
+ if delegationState.TopicID > 0 {
+ delegation.TopicID = &delegationState.TopicID
+ } else {
+ delegation.CategoryID = &delegationState.CategoryID
+ }
+
+ _, _, err = h.ipc.Database.ApprovalDelegation.CreateApprovalDelegationDB(ctx, nil, delegation)
+ if err != nil {
+ logrus.Errorf("HandleDelegationDateInput: CreateApprovalDelegationDB err=%v", err)
+ sendText(bot, chatID, "Ошибка при создании делегирования.")
+ return true
+ }
+
+ h.States.ClearDelegation(ctx, telegramID) //nolint:errcheck
+
+ scopeName := ""
+ if delegationState.TopicID > 0 {
+ topic, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, delegationState.TopicID)
+ if topic != nil && topic.Name != nil {
+ scopeName = *topic.Name
+ }
+ } else {
+ category, _ := h.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, delegationState.CategoryID)
+ if category != nil && category.Name != nil {
+ scopeName = *category.Name
+ }
+ }
+
+ delegate, _ := h.ipc.Database.User.GetUserByIDDB(ctx, delegationState.DelegateID)
+ delegateName := "—"
+ if delegate != nil && delegate.FullName != nil {
+ delegateName = *delegate.FullName
+ }
+
+ sendText(bot, chatID, fmt.Sprintf(
+ "✅ Делегирование создано\n\n"+
+ "📋 Тема: %s\n"+
+ "👤 Делегат: %s\n"+
+ "📅 Действует до: %s",
+ scopeName, delegateName, validUntil.Format("02.01.2006 15:04"),
+ ))
+
+ // Уведомляем делегата
+ if delegate != nil && delegate.TelegramID != nil {
+ delegatorName := "—"
+ if user.FullName != nil {
+ delegatorName = *user.FullName
+ }
+ notifyMsg := tgbotapi.NewMessage(*delegate.TelegramID, fmt.Sprintf(
+ "🔄 Вам делегированы права согласования\n\n"+
+ "👤 От: %s\n"+
+ "📋 Тема: %s\n"+
+ "📅 До: %s",
+ delegatorName, scopeName, validUntil.Format("02.01.2006 15:04"),
+ ))
+ notifyMsg.ParseMode = "HTML"
+ bot.Send(notifyMsg) //nolint:errcheck
+ }
+
+ return true
+}
+
+func (h *Handler) HandleDelegatedRightsList(bot *tgbotapi.BotAPI, chatID int64, telegramID int64) {
+ h.HandleDelegatedRightsListPage(bot, chatID, telegramID, 0, 0)
+}
+
+func (h *Handler) HandleDelegatedRightsListPage(bot *tgbotapi.BotAPI, chatID int64, telegramID int64, page int, prevMessageID int) {
+ ctx := context.Background()
+
+ user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID)
+ if err != nil || user == nil || user.ID == nil {
+ return
+ }
+
+ isActive := true
+ delegations, _, err := h.ipc.Database.ApprovalDelegation.GetApprovalDelegationsListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.ApprovalDelegation{
+ DelegatorID: user.ID,
+ IsActive: &isActive,
+ },
+ })
+ if err != nil {
+ logrus.Errorf("HandleDelegatedRightsList: GetApprovalDelegationsListDB err=%v", err)
+ sendText(bot, chatID, "Ошибка при получении списка делегирований.")
+ return
+ }
+
+ if len(delegations) == 0 {
+ sendText(bot, chatID, "У вас нет активных делегирований.")
+ return
+ }
+
+ if prevMessageID != 0 {
+ bot.Request(tgbotapi.NewDeleteMessage(chatID, prevMessageID)) //nolint:errcheck
+ }
+
+ msg := tgbotapi.NewMessage(chatID, fmt.Sprintf("📋 Делегированные права (%d)\n\nВыберите делегирование:", len(delegations)))
+ msg.ParseMode = "HTML"
+ msg.ReplyMarkup = keyboard.BuildDelegatedRightsList(delegations, page, ctx, h.ipc)
+ bot.Send(msg) //nolint:errcheck
+}
+
+func (h *Handler) HandleDelegatedRightDetail(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, delegationID uint64) {
+ ctx := context.Background()
+ chatID := cq.Message.Chat.ID
+
+ bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck
+ bot.Request(tgbotapi.NewDeleteMessage(chatID, cq.Message.MessageID)) //nolint:errcheck
+
+ delegation, err := h.ipc.Database.ApprovalDelegation.GetApprovalDelegationByIDDB(ctx, delegationID)
+ if err != nil || delegation == nil {
+ sendText(bot, chatID, "⚠️ Делегирование не найдено.")
+ return
+ }
+
+ scopeName := ""
+ if delegation.TopicID != nil {
+ topic, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *delegation.TopicID)
+ if topic != nil && topic.Name != nil {
+ scopeName = *topic.Name
+ }
+ } else if delegation.CategoryID != nil {
+ category, _ := h.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, *delegation.CategoryID)
+ if category != nil && category.Name != nil {
+ scopeName = *category.Name + " (все права)"
+ }
+ }
+
+ delegateName := "—"
+ if delegation.DelegateID != nil {
+ delegate, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *delegation.DelegateID)
+ if delegate != nil && delegate.FullName != nil {
+ delegateName = *delegate.FullName
+ }
+ }
+
+ validUntil := "—"
+ if delegation.ValidUntil != nil {
+ validUntil = delegation.ValidUntil.Format("02.01.2006 15:04")
+ }
+
+ text := fmt.Sprintf(
+ "📋 Делегирование #%d\n\n"+
+ "📋 Тема: %s\n"+
+ "👤 Делегат: %s\n"+
+ "📅 Действует до: %s",
+ delegationID, scopeName, delegateName, validUntil,
+ )
+
+ msg := tgbotapi.NewMessage(chatID, text)
+ msg.ParseMode = "HTML"
+ msg.ReplyMarkup = keyboard.BuildDelegationActions(delegationID)
+ bot.Send(msg) //nolint:errcheck
+}
+
+func (h *Handler) HandleDelegationRevoke(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, delegationID uint64) {
+ ctx := context.Background()
+ chatID := cq.Message.Chat.ID
+
+ bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck
+ bot.Request(tgbotapi.NewDeleteMessage(chatID, cq.Message.MessageID)) //nolint:errcheck
+
+ delegation, err := h.ipc.Database.ApprovalDelegation.GetApprovalDelegationByIDDB(ctx, delegationID)
+ if err != nil || delegation == nil {
+ println(2)
+ sendText(bot, chatID, "⚠️ Делегирование не найдено.")
+ return
+ }
+
+ now := time.Now()
+ isActive := false
+ delegation.ValidUntil = &now
+ delegation.IsActive = &isActive
+
+ _, _, err = h.ipc.Database.ApprovalDelegation.UpdateApprovalDelegationDB(ctx, nil, delegation)
+ if err != nil {
+ logrus.Errorf("HandleDelegationRevoke: UpdateApprovalDelegationDB err=%v", err)
+ sendText(bot, chatID, "Ошибка при отзыве делегирования.")
+ return
+ }
+
+ scopeName := ""
+ if delegation.TopicID != nil {
+ topic, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *delegation.TopicID)
+ if topic != nil && topic.Name != nil {
+ scopeName = *topic.Name
+ }
+ } else if delegation.CategoryID != nil {
+ category, _ := h.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, *delegation.CategoryID)
+ if category != nil && category.Name != nil {
+ scopeName = *category.Name
+ }
+ }
+
+ sendText(bot, chatID, fmt.Sprintf("✅ Делегирование отозвано\n\n📋 Тема: %s", scopeName))
+
+ // Уведомляем делегата
+ if delegation.DelegateID != nil {
+ delegate, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *delegation.DelegateID)
+ if delegate != nil && delegate.TelegramID != nil {
+ notifyMsg := tgbotapi.NewMessage(*delegate.TelegramID, fmt.Sprintf(
+ "⚠️ Делегирование отозвано\n\n📋 Тема: %s",
+ scopeName,
+ ))
+ notifyMsg.ParseMode = "HTML"
+ bot.Send(notifyMsg) //nolint:errcheck
+ }
+ }
+}
+
+func (h *Handler) HandleDelegationExtendPrompt(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, delegationID uint64) {
+ ctx := context.Background()
+ chatID := cq.Message.Chat.ID
+ telegramID := cq.From.ID
+
+ bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck
+ bot.Request(tgbotapi.NewDeleteMessage(chatID, cq.Message.MessageID)) //nolint:errcheck
+
+ delegation, err := h.ipc.Database.ApprovalDelegation.GetApprovalDelegationByIDDB(ctx, delegationID)
+ if err != nil || delegation == nil {
+ println(3)
+ sendText(bot, chatID, "⚠️ Делегирование не найдено.")
+ return
+ }
+
+ // Сохраняем ID делегирования для продления
+ extendKey := fmt.Sprintf("deleg_extend:%d", telegramID)
+ h.ipc.RedisClient.Set(ctx, extendKey, fmt.Sprintf("%d", delegationID), 10*time.Minute) //nolint:errcheck
+
+ msg := tgbotapi.NewMessage(chatID,
+ "Введите новую дату окончания в формате:\n"+
+ "ДД.ММ.ГГГГ ЧЧ:ММ или ДД.ММ.ГГГГ")
+ msg.ParseMode = "HTML"
+ msg.ReplyMarkup = keyboard.BuildDelegationExtendCancel(delegationID)
+ bot.Send(msg) //nolint:errcheck
+}
+
+func (h *Handler) HandleDelegationExtendInput(bot *tgbotapi.BotAPI, msg *tgbotapi.Message) bool {
+ ctx := context.Background()
+ telegramID := msg.From.ID
+ chatID := msg.Chat.ID
+
+ extendKey := fmt.Sprintf("deleg_extend:%d", telegramID)
+ raw, err := h.ipc.RedisClient.Get(ctx, extendKey)
+ if err != nil || raw == "" {
+ return false
+ }
+
+ var delegationID uint64
+ fmt.Sscanf(raw, "%d", &delegationID)
+
+ dateStr := strings.TrimSpace(msg.Text)
+ var validUntil time.Time
+
+ if t, err := time.Parse("02.01.2006 15:04", dateStr); err == nil {
+ validUntil = t
+ } else if t, err := time.Parse("02.01.2006", dateStr); err == nil {
+ validUntil = time.Date(t.Year(), t.Month(), t.Day(), 23, 59, 59, 0, t.Location())
+ } else {
+ sendText(bot, chatID, "⚠️ Неверный формат даты. Используйте ДД.ММ.ГГГГ ЧЧ:ММ или ДД.ММ.ГГГГ")
+ return true
+ }
+
+ if validUntil.Before(time.Now()) {
+ sendText(bot, chatID, "⚠️ Дата окончания не может быть в прошлом.")
+ return true
+ }
+
+ delegation, err := h.ipc.Database.ApprovalDelegation.GetApprovalDelegationByIDDB(ctx, delegationID)
+ if err != nil || delegation == nil {
+ println(4)
+ sendText(bot, chatID, "⚠️ Делегирование не найдено.")
+ h.ipc.RedisClient.Del(ctx, extendKey) //nolint:errcheck
+ return true
+ }
+
+ delegation.ValidUntil = &validUntil
+ notifiedDay := false
+ notified2h := false
+ delegation.NotifiedDay = ¬ifiedDay
+ delegation.Notified2h = ¬ified2h
+
+ _, _, err = h.ipc.Database.ApprovalDelegation.UpdateApprovalDelegationDB(ctx, nil, delegation)
+ if err != nil {
+ logrus.Errorf("HandleDelegationExtendInput: UpdateApprovalDelegationDB err=%v", err)
+ sendText(bot, chatID, "Ошибка при продлении делегирования.")
+ h.ipc.RedisClient.Del(ctx, extendKey) //nolint:errcheck
+ return true
+ }
+
+ h.ipc.RedisClient.Del(ctx, extendKey) //nolint:errcheck
+
+ scopeName := ""
+ if delegation.TopicID != nil {
+ topic, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *delegation.TopicID)
+ if topic != nil && topic.Name != nil {
+ scopeName = *topic.Name
+ }
+ } else if delegation.CategoryID != nil {
+ category, _ := h.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, *delegation.CategoryID)
+ if category != nil && category.Name != nil {
+ scopeName = *category.Name
+ }
+ }
+
+ sendText(bot, chatID, fmt.Sprintf(
+ "✅ Срок делегирования изменён.\n\n"+
+ "📋 Тема: %s\n"+
+ "📅 Новый срок: %s",
+ scopeName, validUntil.Format("02.01.2006 15:04"),
+ ))
+
+ // Уведомляем делегата
+ if delegation.DelegateID != nil {
+ delegate, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *delegation.DelegateID)
+ if delegate != nil && delegate.TelegramID != nil {
+ notifyMsg := tgbotapi.NewMessage(*delegate.TelegramID, fmt.Sprintf(
+ "🔄 Срок делегирования изменён.\n\n"+
+ "📋 Тема: %s\n"+
+ "📅 Новый срок: %s",
+ scopeName, validUntil.Format("02.01.2006 15:04"),
+ ))
+ notifyMsg.ParseMode = "HTML"
+ bot.Send(notifyMsg) //nolint:errcheck
+ }
+ }
+
+ return true
+}
+
+func (h *Handler) getApproverCategories(ctx context.Context, userID uint64) ([]*typescore.ApprovalTopicCategory, error) {
+ hierarchies, _, err := h.ipc.Database.UserHierarchy.GetUserHierarchyListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.UserHierarchy{
+ ApproverID: &userID,
+ },
+ })
+ if err != nil {
+ return nil, err
+ }
+
+ categoryIDs := make(map[uint64]bool)
+ for _, hier := range hierarchies {
+ if hier.TopicID != nil {
+ topic, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *hier.TopicID)
+ if topic != nil && topic.CategoryID != nil {
+ categoryIDs[*topic.CategoryID] = true
+ }
+ }
+ }
+
+ var categories []*typescore.ApprovalTopicCategory
+ for categoryID := range categoryIDs {
+ category, err := h.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, categoryID)
+ if err == nil && category != nil {
+ categories = append(categories, category)
+ }
+ }
+
+ return categories, nil
+}
+
+func (h *Handler) isDelegationConflict(ctx context.Context, d *typescore.ApprovalDelegation, newCategoryID, newTopicID uint64) bool {
+ if d.TopicID == nil && d.CategoryID != nil {
+ if *d.CategoryID == newCategoryID {
+ return true
+ }
+ return false
+ }
+
+ if d.TopicID != nil {
+ if newTopicID > 0 && *d.TopicID == newTopicID {
+ return true
+ }
+
+ if newTopicID == 0 {
+ topic, err := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *d.TopicID)
+ if err == nil && topic != nil && topic.CategoryID != nil && *topic.CategoryID == newCategoryID {
+ return true
+ }
+ }
+ }
+
+ return false
+}
diff --git a/service/telegram_service/handlers/approval/executor.go b/service/telegram_service/handlers/approval/executor.go
new file mode 100644
index 0000000..7f9d4fd
--- /dev/null
+++ b/service/telegram_service/handlers/approval/executor.go
@@ -0,0 +1,195 @@
+package approval
+
+import (
+ "bitrix_balancer_api/core/typescore"
+ "bitrix_balancer_api/core/utilscore"
+ "bitrix_balancer_api/telegram_service/keyboard"
+ "context"
+ "fmt"
+ tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
+ "github.com/sirupsen/logrus"
+ "time"
+)
+
+func (h *Handler) HandleMyTasks(bot *tgbotapi.BotAPI, chatID int64, telegramID int64) {
+ ctx := context.Background()
+
+ user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID)
+ if err != nil || user == nil || user.ID == nil {
+ return
+ }
+
+ isExecutor, _ := h.ipc.Database.User.IsExecutorDB(ctx, *user.ID)
+ if !isExecutor {
+ sendText(bot, chatID, "У вас нет роли исполнителя.")
+ return
+ }
+
+ tasks, _, err := h.ipc.Database.ApprovalTasks.GetApprovalTasksListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.ApprovalTask{
+ ExecutorID: user.ID,
+ Status: utilscore.PointerToString("pending"),
+ },
+ })
+ if err != nil {
+ logrus.Errorf("HandleMyTasks: GetPendingTasksByExecutorDB err=%v", err)
+ sendText(bot, chatID, "Ошибка при получении списка задач.")
+ return
+ }
+
+ if len(tasks) == 0 {
+ sendText(bot, chatID, "📭 Нет активных задач.")
+ return
+ }
+
+ sendText(bot, chatID, fmt.Sprintf("📋 Мои задачи (%d):", len(tasks)))
+
+ for _, task := range tasks {
+ if task.ApprovalID == nil {
+ continue
+ }
+ approval, _ := h.ipc.Database.Approval.GetApprovalByIDDB(ctx, *task.ApprovalID)
+ if approval == nil {
+ continue
+ }
+ h.sendTaskCard(bot, chatID, approval, task)
+ }
+}
+
+func (h *Handler) sendTaskCard(bot *tgbotapi.BotAPI, chatID int64, approval *typescore.Approval, task *typescore.ApprovalTask) {
+ ctx := context.Background()
+
+ if approval.ID == nil || task.ID == nil {
+ return
+ }
+
+ initiatorName := "—"
+ if approval.InitiatorID != nil {
+ initiator, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *approval.InitiatorID)
+ if initiator != nil && initiator.FullName != nil {
+ initiatorName = *initiator.FullName
+ }
+ }
+
+ topicName := "—"
+ if approval.TopicID != nil {
+ topic, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *approval.TopicID)
+ if topic != nil && topic.Name != nil {
+ topicName = *topic.Name
+ }
+ }
+
+ content := "—"
+ if approval.Content != nil {
+ content = *approval.Content
+ }
+
+ taskText := "—"
+ if task.TaskText != nil {
+ taskText = *task.TaskText
+ }
+
+ createdAt := "—"
+ if task.CreatedAt != nil {
+ createdAt = task.CreatedAt.Format("02.01.2006 15:04")
+ }
+
+ text := fmt.Sprintf(
+ "📋 Задача по заявке #%d\n\n"+
+ "👤 Инициатор: %s\n"+
+ "📋 Тема: %s\n"+
+ "📝 Текст заявки: %s\n"+
+ "📅 Создана: %s\n\n"+
+ "🎯 Задача:\n%s",
+ *approval.ID, initiatorName, topicName, content, createdAt, taskText,
+ )
+
+ msg := tgbotapi.NewMessage(chatID, text)
+ msg.ParseMode = "HTML"
+ msg.ReplyMarkup = keyboard.BuildExecutorTaskActions(*task.ID)
+ bot.Send(msg) //nolint:errcheck
+}
+
+func (h *Handler) HandleCompleteTask(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, taskID uint64) {
+ ctx := context.Background()
+ chatID := cq.Message.Chat.ID
+ telegramID := cq.From.ID
+
+ bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck
+ bot.Request(tgbotapi.NewDeleteMessage(chatID, cq.Message.MessageID)) //nolint:errcheck
+
+ user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID)
+ if err != nil || user == nil || user.ID == nil {
+ return
+ }
+
+ task, err := h.ipc.Database.ApprovalTasks.GetApprovalTaskByIDDB(ctx, taskID)
+ if err != nil || task == nil {
+ sendText(bot, chatID, "⚠️ Задача не найдена.")
+ return
+ }
+
+ if task.ExecutorID == nil || *task.ExecutorID != *user.ID {
+ sendText(bot, chatID, "⚠️ Это не ваша задача.")
+ return
+ }
+
+ if task.Status != nil && *task.Status != "pending" {
+ sendText(bot, chatID, "⚠️ Задача уже выполнена.")
+ return
+ }
+
+ now := time.Now()
+ completedStatus := "completed"
+ task.Status = &completedStatus
+ task.CompletedAt = &now
+
+ _, _, err = h.ipc.Database.ApprovalTasks.UpdateApprovalTaskDB(ctx, nil, task)
+ if err != nil {
+ logrus.Errorf("HandleCompleteTask: UpdateApprovalTaskDB err=%v", err)
+ sendText(bot, chatID, "Ошибка при выполнении задачи.")
+ return
+ }
+
+ approval, _ := h.ipc.Database.Approval.GetApprovalByIDDB(ctx, *task.ApprovalID)
+ topicName := "—"
+ if approval != nil && approval.TopicID != nil {
+ topic, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *approval.TopicID)
+ if topic != nil && topic.Name != nil {
+ topicName = *topic.Name
+ }
+ }
+
+ sendText(bot, chatID, fmt.Sprintf(
+ "✅ Задача выполнена\n\n"+
+ "📋 Заявка: #%d — %s\n\n"+
+ "Инициатор уведомлён.",
+ *task.ApprovalID, topicName,
+ ))
+
+ // Уведомляем инициатора
+ if approval != nil && approval.InitiatorID != nil {
+ initiator, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *approval.InitiatorID)
+ if initiator != nil && initiator.TelegramID != nil {
+ executorName := "—"
+ if user.FullName != nil {
+ executorName = *user.FullName
+ }
+
+ content := "—"
+ if approval.Content != nil {
+ content = *approval.Content
+ }
+
+ notifyMsg := tgbotapi.NewMessage(*initiator.TelegramID, fmt.Sprintf(
+ "✅ Исполнитель завершил задачу\n\n"+
+ "📋 Заявка #%d — %s\n"+
+ "👤 Исполнитель: %s\n"+
+ "📝 Текст: %s",
+ *task.ApprovalID, topicName, executorName, content,
+ ))
+ notifyMsg.ParseMode = "HTML"
+ bot.Send(notifyMsg) //nolint:errcheck
+ }
+ }
+}
diff --git a/service/telegram_service/handlers/approval/handler.go b/service/telegram_service/handlers/approval/handler.go
new file mode 100644
index 0000000..9406983
--- /dev/null
+++ b/service/telegram_service/handlers/approval/handler.go
@@ -0,0 +1,501 @@
+package approval
+
+import (
+ "bitrix_balancer_api/telegram_service/approvalflow"
+ "bitrix_balancer_api/telegram_service/keyboard"
+ "bitrix_balancer_api/telegram_service/state"
+ "bitrix_balancer_api/telegram_service/types"
+ "context"
+ "encoding/base64"
+ "fmt"
+ "io"
+ "net/http"
+ "time"
+
+ tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
+ "github.com/sirupsen/logrus"
+)
+
+type Handler struct {
+ ipc *types.InternalProviderControl
+ registry *Registry
+ States *state.StateManager
+}
+
+func NewHandler(ipc *types.InternalProviderControl) *Handler {
+ return &Handler{
+ ipc: ipc,
+ registry: NewRegistry(),
+ States: state.NewStateManager(ipc.RedisClient),
+ }
+}
+
+// HandleMenu — первая страница меню.
+func (h *Handler) HandleMenu(bot *tgbotapi.BotAPI, chatID int64, telegramID int64) {
+ h.HandleMenuPage(bot, chatID, telegramID, 0, 0)
+}
+
+// HandleMenuPage — показывает меню на нужной странице.
+// prevMessageID != 0 — удаляем старое сообщение с пагинацией.
+func (h *Handler) HandleMenuPage(bot *tgbotapi.BotAPI, chatID int64, telegramID int64, page int, prevMessageID int) {
+ ctx := context.Background()
+
+ user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID)
+ if err != nil || user == nil {
+ return
+ }
+
+ allowed, err := h.getAllowedTopicCodes(ctx, user)
+ if err != nil {
+ logrus.Error("HandleMenuPage: getAllowedTopicCodes: ", err)
+ return
+ }
+
+ var visibleTopics []approvalflow.Topic
+ for _, t := range h.registry.All() {
+ if allowed[t.Code()] {
+ visibleTopics = append(visibleTopics, t)
+ }
+ }
+
+ if len(visibleTopics) == 0 {
+ msg := tgbotapi.NewMessage(chatID, "У вас нет доступных тем для согласования")
+ msg.ParseMode = "HTML"
+ bot.Send(msg) //nolint:errcheck
+ return
+ }
+
+ if prevMessageID != 0 {
+ bot.Request(tgbotapi.NewDeleteMessage(chatID, prevMessageID)) //nolint:errcheck
+ }
+
+ msg := tgbotapi.NewMessage(chatID, "Выберите тип согласования:")
+ msg.ParseMode = "HTML"
+ msg.ReplyMarkup = keyboard.BuildApprovalMenu(visibleTopics, page)
+ bot.Send(msg) //nolint:errcheck
+}
+
+// HandleCallback обрабатывает нажатие inline-кнопки внутри флоу согласования.
+// callbackData формат: appr:{topic_code}:{node_key}
+// HandleCallback обрабатывает нажатие inline-кнопки внутри флоу согласования.
+func (h *Handler) HandleCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, topicCode, nodeKey string) {
+ ctx := context.Background()
+ chatID := cq.Message.Chat.ID
+ telegramID := cq.From.ID
+
+ bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck
+ bot.Request(tgbotapi.NewDeleteMessage(chatID, cq.Message.MessageID)) //nolint:errcheck
+
+ topic, err := h.registry.Get(topicCode)
+ if err != nil {
+ logrus.Warnf("HandleCallback: unknown topic %s", topicCode)
+ return
+ }
+
+ flowState, err := h.States.Get(ctx, telegramID)
+ if err != nil {
+ logrus.Error("HandleCallback: get state error", err)
+ return
+ }
+
+ isNew := flowState == nil
+ if isNew {
+ flowState = &state.ApprovalFlowState{
+ TopicCode: topicCode,
+ NodeKey: nodeKey,
+ Collected: make(map[string]string),
+ }
+ }
+
+ tree := topic.BuildTree()
+ node := approvalflow.FindNode(tree, nodeKey)
+ if node == nil {
+ logrus.Warnf("HandleCallback: node not found: %s", nodeKey)
+ return
+ }
+
+ // Сохраняем предыдущий узел в стек (для кнопки "← Назад")
+ if !isNew {
+ flowState.History = append(flowState.History, flowState.NodeKey)
+ }
+
+ // Записываем данные узла
+ if node.DataKey != "" {
+ flowState.Collected[node.DataKey] = node.DataValue
+ }
+
+ if len(node.Children) == 0 && !node.IsInput {
+ logrus.Warnf("HandleCallback: leaf node without IsInput: %s", nodeKey)
+ return
+ }
+
+ // Единственный ребёнок — input: показываем подсказку с кнопкой назад
+ if len(node.Children) == 1 && node.Children[0].IsInput {
+ inputNode := node.Children[0]
+ if inputNode.DataKey != "" {
+ flowState.Collected[inputNode.DataKey] = inputNode.DataValue
+ }
+ flowState.AwaitInput = true
+ flowState.InputKey = inputNode.InputKey
+ flowState.NodeKey = nodeKey // оставляем nodeKey, не inputNode.Key — нужно для back
+
+ h.States.Set(ctx, telegramID, flowState) //nolint:errcheck
+
+ hint := fmt.Sprintf("Введите данные по шаблону:\n%s", inputNode.InputHint)
+ msg := tgbotapi.NewMessage(chatID, hint)
+ msg.ParseMode = "HTML"
+ msg.ReplyMarkup = keyboard.BuildApprovalInputPrompt(topicCode)
+ bot.Send(msg) //nolint:errcheck
+ return
+ }
+
+ // Показываем следующий уровень
+ flowState.NodeKey = nodeKey
+ h.States.Set(ctx, telegramID, flowState) //nolint:errcheck
+
+ msg := tgbotapi.NewMessage(chatID, "Выберите:")
+ msg.ParseMode = "HTML"
+ msg.ReplyMarkup = keyboard.BuildApprovalStep(topicCode, node.Children)
+ bot.Send(msg) //nolint:errcheck
+}
+
+func (h *Handler) HandleTextInput(bot *tgbotapi.BotAPI, msg *tgbotapi.Message) bool {
+ ctx := context.Background()
+ telegramID := msg.From.ID
+ chatID := msg.Chat.ID
+
+ flowState, err := h.States.Get(ctx, telegramID)
+ if err != nil || flowState == nil || !flowState.AwaitInput {
+ return false
+ }
+
+ flowState.Collected[flowState.InputKey] = msg.Text
+ flowState.AwaitInput = false
+
+ // Проверяем, нужно ли загружать файлы
+ if flowState.Collected["payment_type"] == "official" {
+ flowState.AwaitFileInput = true
+ h.showFileStatus(bot, chatID, int64(telegramID), flowState)
+ return true
+ }
+
+ // Проверяем, нужно ли выбирать согласующего
+ topic, _ := h.registry.Get(flowState.TopicCode)
+ if topic != nil {
+ topicCode, _ := topic.TopicCodeFromCollected(flowState.Collected)
+ approvalTopic, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByCodeDB(ctx, topicCode)
+ if approvalTopic != nil && approvalTopic.AllowApproverSelection != nil && *approvalTopic.AllowApproverSelection {
+ // Нужно выбрать согласующего
+ flowState.AwaitApproverSelection = true
+ h.States.Set(ctx, telegramID, flowState) //nolint:errcheck
+ h.showApproverSelection(bot, ctx, chatID, telegramID, approvalTopic)
+ return true
+ }
+ }
+
+ // Если выбор согласующего не нужен - отправляем заявку
+ h.States.Clear(ctx, telegramID) //nolint:errcheck
+ h.finalizeAndSubmit(bot, ctx, chatID, telegramID, flowState)
+ return true
+}
+
+// HandleFileInput обрабатывает прикреплённый файл (фото или документ) во время флоу.
+func (h *Handler) HandleFileInput(bot *tgbotapi.BotAPI, msg *tgbotapi.Message) bool {
+ ctx := context.Background()
+ telegramID := msg.From.ID
+ chatID := msg.Chat.ID
+
+ flowState, err := h.States.Get(ctx, telegramID)
+ if err != nil || flowState == nil || !flowState.AwaitFileInput {
+ return false
+ }
+
+ var fileID, fileName string
+ switch {
+ case msg.Photo != nil && len(msg.Photo) > 0:
+ best := msg.Photo[len(msg.Photo)-1]
+ fileID = best.FileID
+ fileName = fmt.Sprintf("photo_%d.jpg", len(flowState.Files)+1)
+ case msg.Document != nil:
+ fileID = msg.Document.FileID
+ fileName = msg.Document.FileName
+ default:
+ bot.Send(tgbotapi.NewMessage(chatID, "⚠️ Пожалуйста, отправьте фото или PDF-документ.")) //nolint:errcheck
+ return true
+ }
+
+ fileURL, err := bot.GetFileDirectURL(fileID)
+ if err != nil {
+ logrus.Errorf("HandleFileInput: GetFileDirectURL err=%v", err)
+ bot.Send(tgbotapi.NewMessage(chatID, "Ошибка при получении файла. Попробуйте ещё раз.")) //nolint:errcheck
+ return true
+ }
+
+ base64Data, err := fetchFileAsBase64(fileURL)
+ if err != nil {
+ logrus.Errorf("HandleFileInput: fetchFileAsBase64 err=%v", err)
+ bot.Send(tgbotapi.NewMessage(chatID, "Ошибка при обработке файла. Попробуйте ещё раз.")) //nolint:errcheck
+ return true
+ }
+
+ // Добавляем файл в список — НЕ сабмитим, ждём ещё файлы или кнопку
+ flowState.Files = append(flowState.Files, state.FileAttachment{
+ Base64: base64Data,
+ FileName: fileName,
+ })
+ // AwaitFileInput остаётся true
+
+ h.showFileStatus(bot, chatID, int64(telegramID), flowState)
+ return true
+}
+
+// HandleDetachFile удаляет файл из списка по индексу и обновляет статусное сообщение.
+func (h *Handler) HandleDetachFile(bot *tgbotapi.BotAPI, chatID int64, telegramID int64, index int) {
+ ctx := context.Background()
+
+ flowState, err := h.States.Get(ctx, telegramID)
+ if err != nil || flowState == nil {
+ return
+ }
+
+ if index < 0 || index >= len(flowState.Files) {
+ logrus.Warnf("HandleDetachFile: invalid index %d (total=%d)", index, len(flowState.Files))
+ return
+ }
+
+ removed := flowState.Files[index].FileName
+ flowState.Files = append(flowState.Files[:index], flowState.Files[index+1:]...)
+ logrus.Infof("HandleDetachFile: removed file %q, remaining=%d", removed, len(flowState.Files))
+
+ h.showFileStatus(bot, chatID, telegramID, flowState)
+}
+
+// HandleSubmitFiles финализирует заявку. withFiles=false очищает список файлов перед отправкой.
+func (h *Handler) HandleSubmitFiles(bot *tgbotapi.BotAPI, chatID int64, telegramID int64, withFiles bool) {
+ ctx := context.Background()
+
+ flowState, err := h.States.Get(ctx, telegramID)
+ if err != nil || flowState == nil {
+ return
+ }
+
+ if !withFiles {
+ flowState.Files = nil
+ }
+
+ if flowState.FileStatusMsgID != 0 {
+ bot.Request(tgbotapi.NewDeleteMessage(chatID, flowState.FileStatusMsgID)) //nolint:errcheck
+ flowState.FileStatusMsgID = 0
+ }
+
+ // Проверяем, нужно ли выбирать согласующего
+ topic, _ := h.registry.Get(flowState.TopicCode)
+ if topic != nil {
+ topicCode, _ := topic.TopicCodeFromCollected(flowState.Collected)
+ approvalTopic, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByCodeDB(ctx, topicCode)
+ if approvalTopic != nil && approvalTopic.AllowApproverSelection != nil && *approvalTopic.AllowApproverSelection {
+ // Нужно выбрать согласующего
+ flowState.AwaitApproverSelection = true
+ h.States.Set(ctx, telegramID, flowState) //nolint:errcheck
+ h.showApproverSelection(bot, ctx, chatID, telegramID, approvalTopic)
+ return
+ }
+ }
+
+ // Если выбор согласующего не нужен - отправляем заявку
+ h.States.Clear(ctx, telegramID) //nolint:errcheck
+ h.finalizeAndSubmit(bot, ctx, chatID, telegramID, flowState)
+}
+
+// fetchFileAsBase64 скачивает файл по URL и возвращает base64-строку.
+func fetchFileAsBase64(url string) (string, error) {
+ resp, err := http.Get(url) //nolint:gosec
+ if err != nil {
+ return "", err
+ }
+ defer resp.Body.Close()
+
+ data, err := io.ReadAll(resp.Body)
+ if err != nil {
+ return "", err
+ }
+ return base64.StdEncoding.EncodeToString(data), nil
+}
+
+func (h *Handler) HandleRevokeWithComment(bot *tgbotapi.BotAPI, chatID int64, telegramID int64, approvalID uint64, comment string) {
+ ctx := context.Background()
+
+ revoker, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, int64(telegramID))
+ if err != nil || revoker == nil || revoker.ID == nil {
+ sendText(bot, chatID, "⚠️ Пользователь не найден.")
+ return
+ }
+
+ approval, err := h.ipc.Database.Approval.GetApprovalByIDDB(ctx, approvalID)
+ if err != nil || approval == nil {
+ sendText(bot, chatID, "⚠️ Заявка не найдена.")
+ return
+ }
+
+ isInitiator := approval.InitiatorID != nil && *approval.InitiatorID == *revoker.ID
+ isDirector, _ := h.ipc.Database.User.IsDirectorDB(ctx, *revoker.ID)
+
+ if !isInitiator && !isDirector {
+ sendText(bot, chatID, "У вас нет прав для отзыва этой заявки.")
+ return
+ }
+
+ if approval.Status == nil {
+ sendText(bot, chatID, "⚠️ Статус заявки не определён.")
+ return
+ }
+ switch *approval.Status {
+ case "revoked":
+ sendText(bot, chatID, "Заявка уже отозвана.")
+ return
+ case "rejected":
+ sendText(bot, chatID, "Нельзя отозвать отклонённую заявку.")
+ return
+ }
+
+ now := time.Now()
+ revokedStatus := "revoked"
+ approval.Status = &revokedStatus
+ approval.RevokedByID = revoker.ID
+ approval.RevokedAt = &now
+
+ if _, _, err := h.ipc.Database.Approval.UpdateApprovalDB(ctx, nil, approval); err != nil {
+ logrus.Errorf("HandleRevokeWithComment: UpdateApprovalDB err=%v", err)
+ sendText(bot, chatID, "Ошибка при отзыве заявки.")
+ return
+ }
+
+ revokerName := "—"
+ if revoker.FullName != nil {
+ revokerName = *revoker.FullName
+ }
+
+ // Тема и текст заявки для карточки
+ topicName := "—"
+ if approval.TopicID != nil {
+ if t, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *approval.TopicID); t != nil && t.Name != nil {
+ topicName = *t.Name
+ }
+ }
+ content := "—"
+ if approval.Content != nil {
+ content = *approval.Content
+ }
+
+ approvalCard := fmt.Sprintf(
+ "📋 Тема: %s\n"+
+ "📝 Текст: %s\n"+
+ "💬 Причина отзыва: %s",
+ topicName, content, comment,
+ )
+
+ // Подтверждение тому, кто отозвал
+ sendText(bot, chatID, fmt.Sprintf(
+ "↩️ Заявка #%d отозвана\n\n%s",
+ approvalID, approvalCard,
+ ))
+
+ // Если директор отозвал чужую заявку — уведомляем инициатора
+ if isDirector && !isInitiator && approval.InitiatorID != nil {
+ initiator, err := h.ipc.Database.User.GetUserByIDDB(ctx, *approval.InitiatorID)
+ if err == nil && initiator != nil && initiator.TelegramID != nil {
+ sendText(bot, *initiator.TelegramID, fmt.Sprintf(
+ "↩️ Ваша заявка #%d отозвана директором %s\n\n%s",
+ approvalID, revokerName, approvalCard,
+ ))
+ }
+ }
+
+ // Если инициатор отозвал сам — уведомляем текущего согласующего
+ if isInitiator {
+ if activeStep, _ := h.ipc.Database.ApprovalStep.GetActiveStepDB(ctx, approvalID); activeStep != nil && activeStep.ApproverID != nil {
+ approver, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *activeStep.ApproverID)
+ if approver != nil && approver.TelegramID != nil {
+ initiatorName := "—"
+ if revoker.FullName != nil {
+ initiatorName = *revoker.FullName
+ }
+ sendText(bot, *approver.TelegramID, fmt.Sprintf(
+ "↩️ Заявка #%d отозвана инициатором %s\n\n%s",
+ approvalID, initiatorName, approvalCard,
+ ))
+ }
+ }
+ }
+}
+
+// HandleBackCallback — обработчик кнопки "← Назад".
+// Логика: pop из History → показываем children того узла.
+// Если history пуста — возвращаемся в HandleMenu (выбор темы).
+// HandleBackCallback возвращает пользователя на предыдущий шаг флоу.
+func (h *Handler) HandleBackCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, topicCode string) {
+ ctx := context.Background()
+ chatID := cq.Message.Chat.ID
+ telegramID := cq.From.ID
+
+ bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck
+ bot.Request(tgbotapi.NewDeleteMessage(chatID, cq.Message.MessageID)) //nolint:errcheck
+
+ flowState, err := h.States.Get(ctx, telegramID)
+ if err != nil || flowState == nil {
+ logrus.Warnf("HandleBackCallback: no active flow for user=%d", telegramID)
+ return
+ }
+
+ // Если в режиме файлового ввода — очищаем файлы и статусное сообщение
+ if flowState.AwaitFileInput {
+ flowState.AwaitFileInput = false
+ flowState.Files = nil
+
+ // Удаляем статусное сообщение если есть
+ if flowState.FileStatusMsgID != 0 {
+ bot.Request(tgbotapi.NewDeleteMessage(chatID, flowState.FileStatusMsgID)) //nolint:errcheck
+ flowState.FileStatusMsgID = 0
+ }
+ }
+
+ // Если в режиме текстового ввода — очищаем
+ if flowState.AwaitInput {
+ flowState.AwaitInput = false
+ flowState.InputKey = ""
+ }
+
+ // Проверяем историю
+ if len(flowState.History) == 0 {
+ // Нет истории — возвращаемся в главное меню
+ h.States.Clear(ctx, telegramID) //nolint:errcheck
+ h.HandleMenu(bot, chatID, telegramID)
+ return
+ }
+
+ // Достаём предыдущий узел из стека
+ prevNodeKey := flowState.History[len(flowState.History)-1]
+ flowState.History = flowState.History[:len(flowState.History)-1]
+ flowState.NodeKey = prevNodeKey
+
+ topic, err := h.registry.Get(topicCode)
+ if err != nil {
+ logrus.Errorf("HandleBackCallback: unknown topic %s", topicCode)
+ return
+ }
+
+ tree := topic.BuildTree()
+ node := approvalflow.FindNode(tree, prevNodeKey)
+ if node == nil {
+ logrus.Warnf("HandleBackCallback: node not found: %s", prevNodeKey)
+ return
+ }
+
+ h.States.Set(ctx, telegramID, flowState) //nolint:errcheck
+
+ // Показываем предыдущий шаг
+ msg := tgbotapi.NewMessage(chatID, "Выберите:")
+ msg.ParseMode = "HTML"
+ msg.ReplyMarkup = keyboard.BuildApprovalStep(topicCode, node.Children)
+ bot.Send(msg) //nolint:errcheck
+}
diff --git a/service/telegram_service/handlers/approval/handler_add_approver.go b/service/telegram_service/handlers/approval/handler_add_approver.go
new file mode 100644
index 0000000..30ea026
--- /dev/null
+++ b/service/telegram_service/handlers/approval/handler_add_approver.go
@@ -0,0 +1,450 @@
+package approval
+
+import (
+ "bitrix_balancer_api/core/typescore"
+ "bitrix_balancer_api/core/utilscore"
+ "bitrix_balancer_api/telegram_service/keyboard"
+ "bitrix_balancer_api/telegram_service/state"
+ "context"
+ "fmt"
+
+ tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
+ "github.com/sirupsen/logrus"
+)
+
+func (h *Handler) HandleAddApproverMainMenu(bot *tgbotapi.BotAPI, chatID int64, telegramID int64) {
+ ctx := context.Background()
+
+ user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID)
+ if err != nil || user == nil || user.ID == nil {
+ return
+ }
+
+ isApprover, _ := h.ipc.Database.User.IsApproverDB(ctx, *user.ID)
+ if !isApprover {
+ sendText(bot, chatID, "У вас нет прав согласующего.")
+ return
+ }
+
+ msg := tgbotapi.NewMessage(chatID, "➕ Добавить согласующего\n\nВыберите действие:")
+ msg.ParseMode = "HTML"
+ msg.ReplyMarkup = keyboard.BuildAddApproverMainMenu()
+ bot.Send(msg) //nolint:errcheck
+}
+
+func (h *Handler) HandleAddApproverCategoryMenu(bot *tgbotapi.BotAPI, chatID int64, telegramID int64) {
+ h.HandleAddApproverCategoryMenuPage(bot, chatID, telegramID, 0, 0)
+}
+
+func (h *Handler) HandleAddApproverCategoryMenuPage(bot *tgbotapi.BotAPI, chatID int64, telegramID int64, page int, prevMessageID int) {
+ ctx := context.Background()
+
+ user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID)
+ if err != nil || user == nil || user.ID == nil {
+ return
+ }
+
+ categories, err := h.getApproverCategoriesWithPendingApprovals(ctx, *user.ID)
+ if err != nil {
+ logrus.Errorf("HandleAddApproverCategoryMenu: err=%v", err)
+ sendText(bot, chatID, "Ошибка при получении списка категорий.")
+ return
+ }
+
+ if len(categories) == 0 {
+ sendText(bot, chatID, "Нет категорий с активными согласованиями, где вы являетесь согласующим.")
+ return
+ }
+
+ if prevMessageID != 0 {
+ bot.Request(tgbotapi.NewDeleteMessage(chatID, prevMessageID)) //nolint:errcheck
+ }
+
+ msg := tgbotapi.NewMessage(chatID, "➕ Добавить согласующего\n\nВыберите категорию:")
+ msg.ParseMode = "HTML"
+ msg.ReplyMarkup = keyboard.BuildAddApproverCategoryMenu(categories, page)
+ bot.Send(msg) //nolint:errcheck
+}
+
+func (h *Handler) HandleAddApproverCategoryCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, categoryID uint64) {
+ h.HandleAddApproverCategoryCallbackPage(bot, cq, categoryID, 0)
+}
+
+func (h *Handler) HandleAddApproverCategoryCallbackPage(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, categoryID uint64, page int) {
+ ctx := context.Background()
+ chatID := cq.Message.Chat.ID
+ telegramID := cq.From.ID
+
+ bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck
+ bot.Request(tgbotapi.NewDeleteMessage(chatID, cq.Message.MessageID)) //nolint:errcheck
+
+ user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID)
+ if err != nil || user == nil || user.ID == nil {
+ return
+ }
+
+ approvals, err := h.getPendingApprovalsByCategory(ctx, *user.ID, categoryID)
+ if err != nil {
+ logrus.Errorf("HandleAddApproverCategoryCallback: err=%v", err)
+ sendText(bot, chatID, "Ошибка при получении списка согласований.")
+ return
+ }
+
+ if len(approvals) == 0 {
+ sendText(bot, chatID, "Нет активных согласований в этой категории.")
+ return
+ }
+
+ category, _ := h.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, categoryID)
+ categoryName := "—"
+ if category != nil && category.Name != nil {
+ categoryName = *category.Name
+ }
+
+ h.States.SetAddApprover(ctx, telegramID, &state.AddApproverFlowState{
+ CategoryID: categoryID,
+ Stage: "select_approval",
+ }) //nolint:errcheck
+
+ msg := tgbotapi.NewMessage(chatID, fmt.Sprintf("📋 Категория: %s\n\nВыберите согласование:", categoryName))
+ msg.ParseMode = "HTML"
+ msg.ReplyMarkup = keyboard.BuildAddApproverApprovalMenu(approvals, categoryID, page, ctx, h.ipc)
+ bot.Send(msg) //nolint:errcheck
+}
+
+func (h *Handler) HandleAddApproverApprovalCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, approvalID uint64) {
+ h.HandleAddApproverApprovalCallbackPage(bot, cq, approvalID, 0)
+}
+
+func (h *Handler) HandleAddApproverApprovalCallbackPage(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, approvalID uint64, page int) {
+ ctx := context.Background()
+ chatID := cq.Message.Chat.ID
+ telegramID := cq.From.ID
+
+ bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck
+ bot.Request(tgbotapi.NewDeleteMessage(chatID, cq.Message.MessageID)) //nolint:errcheck
+
+ user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID)
+ if err != nil || user == nil || user.ID == nil {
+ return
+ }
+
+ approval, err := h.ipc.Database.Approval.GetApprovalByIDDB(ctx, approvalID)
+ if err != nil || approval == nil {
+ sendText(bot, chatID, "⚠️ Согласование не найдено.")
+ return
+ }
+
+ users, _, err := h.ipc.Database.User.GetUsersListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.User{
+ IsBlocked: utilscore.PointerToBool(false),
+ },
+ })
+ if err != nil {
+ logrus.Errorf("HandleAddApproverApprovalCallback: GetUsersListDB err=%v", err)
+ return
+ }
+
+ // Исключаем текущего пользователя и уже добавленных
+ alreadyAdded, _, _ := h.ipc.Database.ApprovalAdditionalApprover.GetApprovalAdditionalApproversListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.ApprovalAdditionalApprover{
+ ApprovalID: &approvalID,
+ },
+ })
+ addedIDs := make(map[uint64]bool)
+ for _, aa := range alreadyAdded {
+ if aa.ApproverID != nil {
+ addedIDs[*aa.ApproverID] = true
+ }
+ }
+
+ var availableUsers []*typescore.User
+ for _, u := range users {
+ if u.ID != nil && *u.ID != *user.ID && !addedIDs[*u.ID] {
+ availableUsers = append(availableUsers, u)
+ }
+ }
+
+ if len(availableUsers) == 0 {
+ sendText(bot, chatID, "Нет доступных пользователей для добавления.")
+ return
+ }
+
+ addApproverState, _ := h.States.GetAddApprover(ctx, telegramID)
+ if addApproverState == nil {
+ addApproverState = &state.AddApproverFlowState{}
+ }
+ addApproverState.ApprovalID = approvalID
+ addApproverState.Stage = "select_user"
+ h.States.SetAddApprover(ctx, telegramID, addApproverState) //nolint:errcheck
+
+ topicName := "—"
+ if approval.TopicID != nil {
+ topic, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *approval.TopicID)
+ if topic != nil && topic.Name != nil {
+ topicName = *topic.Name
+ }
+ }
+
+ msg := tgbotapi.NewMessage(chatID, fmt.Sprintf("📋 Заявка #%d — %s\n\nВыберите пользователя:", approvalID, topicName))
+ msg.ParseMode = "HTML"
+ msg.ReplyMarkup = keyboard.BuildAddApproverUserMenu(availableUsers, approvalID, addApproverState.CategoryID, page)
+ bot.Send(msg) //nolint:errcheck
+}
+
+func (h *Handler) HandleAddApproverUserCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, approverID uint64) {
+ ctx := context.Background()
+ chatID := cq.Message.Chat.ID
+ telegramID := cq.From.ID
+
+ bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck
+ bot.Request(tgbotapi.NewDeleteMessage(chatID, cq.Message.MessageID)) //nolint:errcheck
+
+ addApproverState, err := h.States.GetAddApprover(ctx, telegramID)
+ if err != nil || addApproverState == nil {
+ sendText(bot, chatID, "⚠️ Состояние утеряно. Начните заново.")
+ return
+ }
+
+ user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID)
+ if err != nil || user == nil || user.ID == nil {
+ return
+ }
+
+ status := "pending"
+ additionalApprover := &typescore.ApprovalAdditionalApprover{
+ ApprovalID: &addApproverState.ApprovalID,
+ ApproverID: &approverID,
+
+ AddedByID: user.ID,
+ Status: &status,
+ }
+
+ _, _, err = h.ipc.Database.ApprovalAdditionalApprover.CreateApprovalAdditionalApproverDB(ctx, nil, additionalApprover)
+ if err != nil {
+ logrus.Errorf("HandleAddApproverUserCallback: CreateApprovalAdditionalApproverDB err=%v", err)
+ sendText(bot, chatID, "Ошибка при добавлении согласующего.")
+ return
+ }
+
+ h.States.ClearAddApprover(ctx, telegramID) //nolint:errcheck
+
+ approval, _ := h.ipc.Database.Approval.GetApprovalByIDDB(ctx, addApproverState.ApprovalID)
+ topicName := "—"
+ if approval != nil && approval.TopicID != nil {
+ topic, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *approval.TopicID)
+ if topic != nil && topic.Name != nil {
+ topicName = *topic.Name
+ }
+ }
+
+ addedApprover, _ := h.ipc.Database.User.GetUserByIDDB(ctx, approverID)
+ approverName := "—"
+ if addedApprover != nil && addedApprover.FullName != nil {
+ approverName = *addedApprover.FullName
+ }
+
+ sendText(bot, chatID, fmt.Sprintf(
+ "✅ Согласующий добавлен\n\n"+
+ "📋 Заявка: #%d — %s\n"+
+ "👤 Согласующий: %s",
+ addApproverState.ApprovalID, topicName, approverName,
+ ))
+
+ // Уведомляем добавленного согласующего
+ if addedApprover != nil && addedApprover.TelegramID != nil && approval != nil {
+ initiatorName := "—"
+ if approval.InitiatorID != nil {
+ initiator, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *approval.InitiatorID)
+ if initiator != nil && initiator.FullName != nil {
+ initiatorName = *initiator.FullName
+ }
+ }
+
+ content := "—"
+ if approval.Content != nil {
+ content = *approval.Content
+ }
+
+ notifyMsg := tgbotapi.NewMessage(*addedApprover.TelegramID, fmt.Sprintf(
+ "➕ Вас добавили к согласованию заявки #%d\n\n"+
+ "👤 Инициатор: %s\n"+
+ "📋 Тема: %s\n"+
+ "📝 Текст: %s",
+ addApproverState.ApprovalID, initiatorName, topicName, content,
+ ))
+ notifyMsg.ParseMode = "HTML"
+ notifyMsg.ReplyMarkup = keyboard.BuildApproverDecision(addApproverState.ApprovalID)
+ bot.Send(notifyMsg) //nolint:errcheck
+ }
+}
+
+func (h *Handler) HandleAddedApproversList(bot *tgbotapi.BotAPI, chatID int64, telegramID int64) {
+ h.HandleAddedApproversListPage(bot, chatID, telegramID, 0, 0)
+}
+
+func (h *Handler) HandleAddedApproversListPage(bot *tgbotapi.BotAPI, chatID int64, telegramID int64, page int, prevMessageID int) {
+ ctx := context.Background()
+
+ user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID)
+ if err != nil || user == nil || user.ID == nil {
+ return
+ }
+
+ addedApprovers, _, err := h.ipc.Database.ApprovalAdditionalApprover.GetApprovalAdditionalApproversListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.ApprovalAdditionalApprover{
+ AddedByID: user.ID,
+ },
+ })
+ if err != nil {
+ logrus.Errorf("HandleAddedApproversList: err=%v", err)
+ sendText(bot, chatID, "Ошибка при получении списка.")
+ return
+ }
+
+ if len(addedApprovers) == 0 {
+ sendText(bot, chatID, "Вы еще не добавляли согласующих.")
+ return
+ }
+
+ if prevMessageID != 0 {
+ bot.Request(tgbotapi.NewDeleteMessage(chatID, prevMessageID)) //nolint:errcheck
+ }
+
+ msg := tgbotapi.NewMessage(chatID, fmt.Sprintf("📋 Ранее добавленные (%d)\n\nВыберите запись:", len(addedApprovers)))
+ msg.ParseMode = "HTML"
+ msg.ReplyMarkup = keyboard.BuildAddedApproversList(addedApprovers, page, ctx, h.ipc)
+ bot.Send(msg) //nolint:errcheck
+}
+
+func (h *Handler) HandleAddedApproverDetail(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, additionalApproverID uint64) {
+ ctx := context.Background()
+ chatID := cq.Message.Chat.ID
+
+ bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck
+ bot.Request(tgbotapi.NewDeleteMessage(chatID, cq.Message.MessageID)) //nolint:errcheck
+
+ addedApprover, err := h.ipc.Database.ApprovalAdditionalApprover.GetApprovalAdditionalApproverByIDDB(ctx, additionalApproverID)
+ if err != nil || addedApprover == nil {
+ sendText(bot, chatID, "⚠️ Запись не найдена.")
+ return
+ }
+
+ approverName := "—"
+ if addedApprover.ApproverID != nil {
+ approver, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *addedApprover.ApproverID)
+ if approver != nil && approver.FullName != nil {
+ approverName = *approver.FullName
+ }
+ }
+
+ approvalInfo := "—"
+ if addedApprover.ApprovalID != nil {
+ approval, _ := h.ipc.Database.Approval.GetApprovalByIDDB(ctx, *addedApprover.ApprovalID)
+ if approval != nil && approval.TopicID != nil {
+ topic, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *approval.TopicID)
+ topicName := "—"
+ if topic != nil && topic.Name != nil {
+ topicName = *topic.Name
+ }
+ approvalInfo = fmt.Sprintf("#%d — %s", *addedApprover.ApprovalID, topicName)
+ }
+ }
+
+ statusText := "⏳ Ожидает"
+ if addedApprover.Status != nil {
+ switch *addedApprover.Status {
+ case "approved":
+ statusText = "✅ Одобрено"
+ case "rejected":
+ statusText = "❌ Отклонено"
+ }
+ }
+
+ text := fmt.Sprintf(
+ "📋 Добавленный согласующий\n\n"+
+ "👤 Пользователь: %s\n"+
+ "📄 Заявка: %s\n"+
+ "📊 Статус: %s",
+ approverName, approvalInfo, statusText,
+ )
+
+ if addedApprover.Comment != nil && *addedApprover.Comment != "" {
+ text += fmt.Sprintf("\n💬 Комментарий: %s", *addedApprover.Comment)
+ }
+
+ msg := tgbotapi.NewMessage(chatID, text)
+ msg.ParseMode = "HTML"
+ msg.ReplyMarkup = keyboard.BuildAddedApproverDetail()
+ bot.Send(msg) //nolint:errcheck
+}
+
+func (h *Handler) getApproverCategoriesWithPendingApprovals(ctx context.Context, userID uint64) ([]*typescore.ApprovalTopicCategory, error) {
+ hierarchies, _, err := h.ipc.Database.UserHierarchy.GetUserHierarchyListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.UserHierarchy{
+ ApproverID: &userID,
+ },
+ })
+ if err != nil {
+ return nil, err
+ }
+
+ categoryIDs := make(map[uint64]bool)
+ for _, hier := range hierarchies {
+ if hier.TopicID != nil {
+ topic, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *hier.TopicID)
+ if topic != nil && topic.CategoryID != nil {
+ // Проверяем, есть ли pending заявки
+ steps, _, _ := h.ipc.Database.ApprovalStep.GetApprovalStepsListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.ApprovalStep{
+ ApproverID: &userID,
+ Status: utilscore.PointerToString("pending"),
+ },
+ })
+ if len(steps) > 0 {
+ categoryIDs[*topic.CategoryID] = true
+ }
+ }
+ }
+ }
+
+ var categories []*typescore.ApprovalTopicCategory
+ for categoryID := range categoryIDs {
+ category, err := h.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, categoryID)
+ if err == nil && category != nil {
+ categories = append(categories, category)
+ }
+ }
+
+ return categories, nil
+}
+
+func (h *Handler) getPendingApprovalsByCategory(ctx context.Context, userID, categoryID uint64) ([]*typescore.Approval, error) {
+ steps, _, err := h.ipc.Database.ApprovalStep.GetApprovalStepsListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.ApprovalStep{
+ ApproverID: &userID,
+ Status: utilscore.PointerToString("pending"),
+ },
+ })
+ if err != nil {
+ return nil, err
+ }
+
+ var approvals []*typescore.Approval
+ for _, step := range steps {
+ if step.ApprovalID == nil {
+ continue
+ }
+ approval, _ := h.ipc.Database.Approval.GetApprovalByIDDB(ctx, *step.ApprovalID)
+ if approval == nil || approval.TopicID == nil {
+ continue
+ }
+ topic, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *approval.TopicID)
+ if topic == nil || topic.CategoryID == nil || *topic.CategoryID != categoryID {
+ continue
+ }
+ approvals = append(approvals, approval)
+ }
+
+ return approvals, nil
+}
diff --git a/service/telegram_service/handlers/approval/handler_observer.go b/service/telegram_service/handlers/approval/handler_observer.go
new file mode 100644
index 0000000..9af8cae
--- /dev/null
+++ b/service/telegram_service/handlers/approval/handler_observer.go
@@ -0,0 +1,325 @@
+package approval
+
+import (
+ "bitrix_balancer_api/core/typescore"
+ "bitrix_balancer_api/telegram_service/approvalflow"
+ "bitrix_balancer_api/telegram_service/keyboard"
+ "context"
+ "fmt"
+ "time"
+
+ tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
+ "github.com/sirupsen/logrus"
+)
+
+const observerTopicTTL = 30 * time.Minute
+
+func observerTopicKey(telegramID int64) string {
+ return fmt.Sprintf("obs_topic:%d", telegramID)
+}
+
+// HandleObservedApprovals — точка входа: список тем для наблюдателя.
+func (h *Handler) HandleObservedApprovals(bot *tgbotapi.BotAPI, chatID int64, telegramID int64) {
+ ctx := context.Background()
+
+ user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID)
+ if err != nil || user == nil || user.ID == nil {
+ return
+ }
+
+ isObserver, _ := h.ipc.Database.User.IsObserverDB(ctx, *user.ID)
+ if !isObserver {
+ return
+ }
+
+ topics, err := h.getAllowedObserverTopics(ctx, user)
+ if err != nil {
+ logrus.Error("HandleObservedApprovals: getAllowedObserverTopics: ", err)
+ return
+ }
+ if len(topics) == 0 {
+ sendText(bot, chatID, "👁 Нет тем, доступных для наблюдения.")
+ return
+ }
+
+ msg := tgbotapi.NewMessage(chatID, "👁 Наблюдаемые согласования\n\nВыберите тему:")
+ msg.ParseMode = "HTML"
+ msg.ReplyMarkup = keyboard.BuildObserverTopicMenu(topics)
+ bot.Send(msg) //nolint:errcheck
+}
+
+// HandleObserverTopicCallback — выбор темы наблюдателем.
+func (h *Handler) HandleObserverTopicCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, topicCode string) {
+ ctx := context.Background()
+ chatID := cq.Message.Chat.ID
+ telegramID := cq.From.ID
+
+ bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck
+ bot.Request(tgbotapi.NewDeleteMessage(chatID, cq.Message.MessageID)) //nolint:errcheck
+
+ // Запоминаем тему для кнопки "назад" в карточке
+ h.ipc.RedisClient.Set(ctx, observerTopicKey(telegramID), topicCode, observerTopicTTL) //nolint:errcheck
+
+ h.sendObserverTopicApprovals(bot, ctx, chatID, topicCode)
+}
+
+// HandleObserverBackToTopic — возврат к списку заявок темы из карточки.
+func (h *Handler) HandleObserverBackToTopic(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, topicCode string) {
+ ctx := context.Background()
+ bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck
+ bot.Request(tgbotapi.NewDeleteMessage(cq.Message.Chat.ID, cq.Message.MessageID)) //nolint:errcheck
+ h.sendObserverTopicApprovals(bot, ctx, cq.Message.Chat.ID, topicCode)
+}
+
+// HandleObserverBackToTopics — возврат к списку тем.
+func (h *Handler) HandleObserverBackToTopics(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery) {
+ bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck
+ bot.Request(tgbotapi.NewDeleteMessage(cq.Message.Chat.ID, cq.Message.MessageID)) //nolint:errcheck
+ h.HandleObservedApprovals(bot, cq.Message.Chat.ID, cq.From.ID)
+}
+
+// HandleObserverApprovalCallback — карточка конкретной заявки.
+func (h *Handler) HandleObserverApprovalCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, approvalID uint64) {
+ ctx := context.Background()
+ chatID := cq.Message.Chat.ID
+ telegramID := cq.From.ID
+
+ bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck
+ bot.Request(tgbotapi.NewDeleteMessage(chatID, cq.Message.MessageID)) //nolint:errcheck
+
+ approval, err := h.ipc.Database.Approval.GetApprovalByIDDB(ctx, approvalID)
+ if err != nil || approval == nil {
+ sendText(bot, chatID, "⚠️ Заявка не найдена.")
+ return
+ }
+
+ // Инициатор
+ initiatorName := "—"
+ if approval.InitiatorID != nil {
+ if u, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *approval.InitiatorID); u != nil && u.FullName != nil {
+ initiatorName = *u.FullName
+ }
+ }
+
+ // Отдел
+ deptName := "—"
+ if approval.DepartmentID != nil {
+ if d, _ := h.ipc.Database.Department.GetDepartmentByIDDB(ctx, *approval.DepartmentID); d != nil && d.Name != nil {
+ deptName = *d.Name
+ }
+ }
+
+ // Тема + categoryCode для кнопки "назад"
+ topicName := "—"
+ categoryCode, _ := h.ipc.RedisClient.Get(ctx, observerTopicKey(telegramID))
+ if approval.TopicID != nil {
+ if topic, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *approval.TopicID); topic != nil {
+ if topic.Name != nil {
+ topicName = *topic.Name
+ }
+ if categoryCode == "" && topic.CategoryID != nil {
+ if cat, _ := h.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, *topic.CategoryID); cat != nil && cat.Code != nil {
+ categoryCode = *cat.Code
+ }
+ }
+ }
+ }
+
+ // Текущий согласующий
+ approverName := "—"
+ if activeStep, _ := h.ipc.Database.ApprovalStep.GetActiveStepDB(ctx, approvalID); activeStep != nil && activeStep.ApproverID != nil {
+ if u, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *activeStep.ApproverID); u != nil && u.FullName != nil {
+ approverName = *u.FullName
+ }
+ }
+
+ createdAt := "—"
+ if approval.CreatedAt != nil {
+ createdAt = approval.CreatedAt.Format("02.01.2006 15:04")
+ }
+ content := "—"
+ if approval.Content != nil {
+ content = *approval.Content
+ }
+
+ text := fmt.Sprintf(
+ "📄 Заявка #%d\n\n"+
+ "📋 Тема: %s\n"+
+ "👤 Инициатор: %s\n"+
+ "🏢 Отдел: %s\n"+
+ "📅 Создана: %s\n"+
+ "📝 Содержание: %s\n\n"+
+ "⏳ Ожидает решения: %s",
+ approvalID, topicName, initiatorName, deptName, createdAt, content, approverName,
+ )
+
+ msg := tgbotapi.NewMessage(chatID, text)
+ msg.ParseMode = "HTML"
+ msg.ReplyMarkup = keyboard.BuildObserverApprovalDetail(approvalID, categoryCode)
+ bot.Send(msg) //nolint:errcheck
+}
+
+// HandleObserverReminderCallback — напоминание согласующему от наблюдателя.
+func (h *Handler) HandleObserverReminderCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, approvalID uint64) {
+ ctx := context.Background()
+ chatID := cq.Message.Chat.ID
+
+ bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck
+
+ approval, err := h.ipc.Database.Approval.GetApprovalByIDDB(ctx, approvalID)
+ if err != nil || approval == nil {
+ sendText(bot, chatID, "⚠️ Заявка не найдена.")
+ return
+ }
+ if approval.Status == nil || *approval.Status != "pending" {
+ sendText(bot, chatID, "ℹ️ Заявка уже не ожидает согласования.")
+ return
+ }
+
+ activeStep, err := h.ipc.Database.ApprovalStep.GetActiveStepDB(ctx, approvalID)
+ if err != nil || activeStep == nil || activeStep.ApproverID == nil {
+ sendText(bot, chatID, "⚠️ Активный шаг согласования не найден.")
+ return
+ }
+
+ approver, err := h.ipc.Database.User.GetUserByIDDB(ctx, *activeStep.ApproverID)
+ if err != nil || approver == nil {
+ sendText(bot, chatID, "⚠️ Согласующий не найден.")
+ return
+ }
+ if approver.TelegramID == nil {
+ sendText(bot, chatID, "⚠️ У согласующего нет Telegram-аккаунта.")
+ return
+ }
+
+ initiatorName := "—"
+ if approval.InitiatorID != nil {
+ if u, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *approval.InitiatorID); u != nil && u.FullName != nil {
+ initiatorName = *u.FullName
+ }
+ }
+ content := "—"
+ if approval.Content != nil {
+ content = *approval.Content
+ }
+
+ reminder := fmt.Sprintf(
+ "🔔 Напоминание о заявке #%d\n\n"+
+ "👤 Инициатор: %s\n"+
+ "📝 %s\n\n"+
+ "Заявка ожидает вашего решения.",
+ approvalID, initiatorName, content,
+ )
+ reminderMsg := tgbotapi.NewMessage(*approver.TelegramID, reminder)
+ reminderMsg.ParseMode = "HTML"
+ reminderMsg.ReplyMarkup = keyboard.BuildApproverDecision(approvalID)
+ bot.Send(reminderMsg) //nolint:errcheck
+
+ approverName := "согласующему"
+ if approver.FullName != nil {
+ approverName = *approver.FullName
+ }
+ sendText(bot, chatID, fmt.Sprintf("✅ Напоминание отправлено: %s.", approverName))
+}
+
+// sendObserverTopicApprovals — общий рендер списка заявок по теме.
+func (h *Handler) sendObserverTopicApprovals(bot *tgbotapi.BotAPI, ctx context.Context, chatID int64, topicCode string) {
+ approvals, err := h.ipc.Database.Approval.GetApprovalsByCategoryDB(ctx, topicCode)
+ if err != nil {
+ logrus.Errorf("sendObserverTopicApprovals: GetApprovalsByCategoryDB err=%v", err)
+ sendText(bot, chatID, "Ошибка при получении заявок.")
+ return
+ }
+
+ // Только pending
+ var pending []*typescore.Approval
+ for _, a := range approvals {
+ if a.Status != nil && *a.Status == "pending" {
+ pending = append(pending, a)
+ }
+ }
+
+ topic, _ := h.registry.Get(topicCode)
+ topicName := topicCode
+ if topic != nil {
+ topicName = topic.Name()
+ }
+
+ if len(pending) == 0 {
+ msg := tgbotapi.NewMessage(chatID, fmt.Sprintf("👁 %s\n\nНет заявок, ожидающих согласования.", topicName))
+ msg.ParseMode = "HTML"
+ msg.ReplyMarkup = keyboard.BuildObserverApprovalList(nil, nil, nil, topicCode)
+ bot.Send(msg) //nolint:errcheck
+ return
+ }
+
+ // Пакетная загрузка инициаторов и отделов
+ initiators := make(map[uint64]*typescore.User)
+ departments := make(map[uint64]*typescore.Department)
+ for _, a := range pending {
+ if a.InitiatorID != nil {
+ if u, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *a.InitiatorID); u != nil {
+ initiators[*a.InitiatorID] = u
+ }
+ }
+ if a.DepartmentID != nil {
+ if d, _ := h.ipc.Database.Department.GetDepartmentByIDDB(ctx, *a.DepartmentID); d != nil {
+ departments[*a.DepartmentID] = d
+ }
+ }
+ }
+
+ msg := tgbotapi.NewMessage(chatID, fmt.Sprintf(
+ "👁 %s\n\nОжидают согласования: %d", topicName, len(pending),
+ ))
+ msg.ParseMode = "HTML"
+ msg.ReplyMarkup = keyboard.BuildObserverApprovalList(pending, initiators, departments, topicCode)
+ bot.Send(msg) //nolint:errcheck
+}
+
+// getAllowedObserverTopics — темы с правом observe для пользователя.
+func (h *Handler) getAllowedObserverTopics(ctx context.Context, user *typescore.User) ([]approvalflow.Topic, error) {
+ perms, err := h.ipc.Database.Permission.GetUserPermissionsDB(ctx, *user.ID, "observe")
+ if err != nil {
+ return nil, err
+ }
+ if len(perms) == 0 {
+ return nil, nil
+ }
+
+ allowedCategoryIDs := map[uint64]bool{}
+ allowedTopicIDs := map[uint64]bool{}
+ for _, p := range perms {
+ if p.TopicCategoryID != nil {
+ allowedCategoryIDs[*p.TopicCategoryID] = true
+ }
+ if p.TopicID != nil {
+ allowedTopicIDs[*p.TopicID] = true
+ }
+ }
+
+ var result []approvalflow.Topic
+ for _, t := range h.registry.All() {
+ category, err := h.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByCodeDB(ctx, t.Code())
+ if err != nil || category == nil || category.ID == nil {
+ continue
+ }
+ if allowedCategoryIDs[*category.ID] {
+ result = append(result, t)
+ continue
+ }
+ topics, _, err := h.ipc.Database.ApprovalTopic.GetApprovalTopicsListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.ApprovalTopic{CategoryID: category.ID},
+ })
+ if err != nil {
+ continue
+ }
+ for _, topic := range topics {
+ if topic.ID != nil && allowedTopicIDs[*topic.ID] {
+ result = append(result, t)
+ break
+ }
+ }
+ }
+ return result, nil
+}
diff --git a/service/telegram_service/handlers/approval/handler_pending_comments.go b/service/telegram_service/handlers/approval/handler_pending_comments.go
new file mode 100644
index 0000000..ec65d58
--- /dev/null
+++ b/service/telegram_service/handlers/approval/handler_pending_comments.go
@@ -0,0 +1,210 @@
+package approval
+
+import (
+ "bitrix_balancer_api/telegram_service/keyboard"
+ "bitrix_balancer_api/telegram_service/state"
+ "context"
+ "fmt"
+
+ tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
+ "github.com/sirupsen/logrus"
+)
+
+// HandlePendingCommentInput — перехватывает текстовый ввод, если пользователь
+// находится в состоянии ожидания комментария к отказу или отзыву.
+// Возвращает true, если ввод был обработан.
+func (h *Handler) HandlePendingCommentInput(bot *tgbotapi.BotAPI, msg *tgbotapi.Message) bool {
+ ctx := context.Background()
+ telegramID := msg.From.ID
+ chatID := msg.Chat.ID
+
+ // ── Проверяем отказ ────────────────────────────────────────
+ rejectKey := fmt.Sprintf("appr_reject_pending:%d", telegramID)
+ if raw, err := h.ipc.RedisClient.Get(ctx, rejectKey); err == nil && raw != "" {
+ var approvalID uint64
+ fmt.Sscanf(raw, "%d", &approvalID)
+
+ // Удаляем сообщение с просьбой ввести комментарий
+ if msg.ReplyToMessage != nil {
+ bot.Request(tgbotapi.NewDeleteMessage(chatID, msg.ReplyToMessage.MessageID)) //nolint:errcheck
+ }
+ // Удаляем само сообщение пользователя
+ bot.Request(tgbotapi.NewDeleteMessage(chatID, msg.MessageID)) //nolint:errcheck
+
+ h.ipc.RedisClient.Del(ctx, rejectKey) //nolint:errcheck
+ h.States.RemovePendingComment(ctx, telegramID, approvalID) //nolint:errcheck
+
+ h.HandleDecisionWithChat(bot, chatID, approvalID, false, msg.Text)
+ return true
+ }
+
+ // ── Проверяем отзыв ────────────────────────────────────────
+ revokeKey := fmt.Sprintf("appr_revoke_pending:%d", telegramID)
+ if raw, err := h.ipc.RedisClient.Get(ctx, revokeKey); err == nil && raw != "" {
+ var approvalID uint64
+ fmt.Sscanf(raw, "%d", &approvalID)
+
+ // Удаляем сообщение с просьбой ввести комментарий
+ if msg.ReplyToMessage != nil {
+ bot.Request(tgbotapi.NewDeleteMessage(chatID, msg.ReplyToMessage.MessageID)) //nolint:errcheck
+ }
+ // Удаляем само сообщение пользователя
+ bot.Request(tgbotapi.NewDeleteMessage(chatID, msg.MessageID)) //nolint:errcheck
+
+ h.ipc.RedisClient.Del(ctx, revokeKey) //nolint:errcheck
+ h.States.RemovePendingComment(ctx, telegramID, approvalID) //nolint:errcheck
+
+ h.HandleRevokeWithComment(bot, chatID, telegramID, approvalID, msg.Text)
+ return true
+ }
+
+ return false
+}
+
+// HandlePendingCommentsList — показывает список отложенных заявок.
+func (h *Handler) HandlePendingCommentsList(bot *tgbotapi.BotAPI, chatID int64, telegramID int64) {
+ ctx := context.Background()
+
+ items, err := h.States.GetPendingComments(ctx, telegramID)
+ if err != nil {
+ logrus.Errorf("HandlePendingCommentsList: err=%v", err)
+ return
+ }
+ if len(items) == 0 {
+ reply := tgbotapi.NewMessage(chatID, "✅ Нет заявок, ожидающих комментария.")
+ reply.ParseMode = "HTML"
+ bot.Send(reply) //nolint:errcheck
+ return
+ }
+
+ topicNames := h.loadTopicNamesForPending(ctx, items)
+
+ msg := tgbotapi.NewMessage(chatID,
+ fmt.Sprintf("📝 Ожидают комментария (%d):\n\nВыберите заявку для обработки:", len(items)),
+ )
+ msg.ParseMode = "HTML"
+ msg.ReplyMarkup = keyboard.BuildPendingCommentsList(items, topicNames)
+ bot.Send(msg) //nolint:errcheck
+}
+
+// HandlePendingItemCallback — карточка конкретной отложенной заявки.
+func (h *Handler) HandlePendingItemCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, approvalID uint64) {
+ ctx := context.Background()
+ chatID := cq.Message.Chat.ID
+ telegramID := cq.From.ID
+
+ bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck
+ bot.Request(tgbotapi.NewDeleteMessage(chatID, cq.Message.MessageID)) //nolint:errcheck
+
+ items, _ := h.States.GetPendingComments(ctx, telegramID)
+ var found *state.PendingCommentItem
+ for _, item := range items {
+ if item.ApprovalID == approvalID {
+ i := item
+ found = &i
+ break
+ }
+ }
+ if found == nil {
+ reply := tgbotapi.NewMessage(chatID, "⚠️ Заявка не найдена в очереди.")
+ reply.ParseMode = "HTML"
+ bot.Send(reply) //nolint:errcheck
+ return
+ }
+
+ approval, err := h.ipc.Database.Approval.GetApprovalByIDDB(ctx, approvalID)
+ if err != nil || approval == nil {
+ reply := tgbotapi.NewMessage(chatID, "⚠️ Заявка не найдена.")
+ reply.ParseMode = "HTML"
+ bot.Send(reply) //nolint:errcheck
+ return
+ }
+
+ topicName := "—"
+ if approval.TopicID != nil {
+ if t, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *approval.TopicID); t != nil && t.Name != nil {
+ topicName = *t.Name
+ }
+ }
+ content := "—"
+ if approval.Content != nil {
+ content = *approval.Content
+ }
+ initiatorName := "—"
+ if approval.InitiatorID != nil {
+ if u, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *approval.InitiatorID); u != nil && u.FullName != nil {
+ initiatorName = *u.FullName
+ }
+ }
+
+ actionLabel := "отклонить"
+ if found.Action == "revoke" {
+ actionLabel = "отозвать"
+ }
+
+ text := fmt.Sprintf(
+ "📄 Заявка #%d — %s\n\n"+
+ "👤 Инициатор: %s\n"+
+ "📋 Тема: %s\n"+
+ "📝 Текст: %s\n\n"+
+ "Выберите действие чтобы %s:",
+ approvalID, found.Action,
+ initiatorName, topicName, content, actionLabel,
+ )
+
+ msg := tgbotapi.NewMessage(chatID, text)
+ msg.ParseMode = "HTML"
+ msg.ReplyMarkup = keyboard.BuildPendingItemOptions(approvalID, found.Action)
+ bot.Send(msg) //nolint:errcheck
+}
+
+// HandlePendingBackCallback — возврат к списку отложенных.
+func (h *Handler) HandlePendingBackCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery) {
+ bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck
+ bot.Request(tgbotapi.NewDeleteMessage(cq.Message.Chat.ID, cq.Message.MessageID)) //nolint:errcheck
+ h.HandlePendingCommentsList(bot, cq.Message.Chat.ID, cq.From.ID)
+}
+
+// HandlePendingDeferCallback — добавляет заявку в очередь отложенных.
+func (h *Handler) HandlePendingDeferCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, approvalID uint64, action string) {
+ ctx := context.Background()
+ telegramID := cq.From.ID
+ chatID := cq.Message.Chat.ID
+
+ bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck
+ bot.Request(tgbotapi.NewDeleteMessage(chatID, cq.Message.MessageID)) //nolint:errcheck
+
+ if err := h.States.AddPendingComment(ctx, telegramID, state.PendingCommentItem{
+ ApprovalID: approvalID,
+ Action: action,
+ }); err != nil {
+ logrus.Errorf("HandlePendingDeferCallback: AddPendingComment err=%v", err)
+ return
+ }
+
+ items, _ := h.States.GetPendingComments(ctx, telegramID)
+ reply := tgbotapi.NewMessage(chatID, fmt.Sprintf(
+ "⏳ Заявка #%d отложена. В очереди: %d.\n\n"+
+ "Обработайте их через кнопку 📝 Ожидают комментария.",
+ approvalID, len(items),
+ ))
+ reply.ParseMode = "HTML"
+ bot.Send(reply) //nolint:errcheck
+}
+
+// loadTopicNamesForPending — вспомогательный метод для загрузки названий тем.
+func (h *Handler) loadTopicNamesForPending(ctx context.Context, items []state.PendingCommentItem) map[uint64]string {
+ topicNames := make(map[uint64]string)
+ for _, item := range items {
+ approval, err := h.ipc.Database.Approval.GetApprovalByIDDB(ctx, item.ApprovalID)
+ if err != nil || approval == nil || approval.TopicID == nil {
+ continue
+ }
+ t, err := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *approval.TopicID)
+ if err != nil || t == nil || t.Name == nil {
+ continue
+ }
+ topicNames[item.ApprovalID] = *t.Name
+ }
+ return topicNames
+}
diff --git a/service/telegram_service/handlers/approval/handler_report.go b/service/telegram_service/handlers/approval/handler_report.go
new file mode 100644
index 0000000..e483f15
--- /dev/null
+++ b/service/telegram_service/handlers/approval/handler_report.go
@@ -0,0 +1,1088 @@
+package approval
+
+import (
+ "bitrix_balancer_api/core/typescore"
+ "bitrix_balancer_api/telegram_service/keyboard"
+ "bitrix_balancer_api/telegram_service/state"
+ "bytes"
+ "context"
+ "fmt"
+ "github.com/xuri/excelize/v2"
+ "sort"
+ "strings"
+ "time"
+
+ tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
+ "github.com/sirupsen/logrus"
+)
+
+// buildExcelReport — строит xlsx-файл и возвращает байты.
+func (h *Handler) buildExcelReport(ctx context.Context, approvals []*typescore.Approval) ([]byte, error) {
+ f := excelize.NewFile()
+ sheet := "Согласования"
+ f.SetSheetName("Sheet1", sheet)
+
+ // Заголовки
+ headers := []string{
+ "ФИО инициатора",
+ "Тема согласования",
+ "Дата создания",
+ "Согласующие",
+ "Наблюдатели",
+ "Статус",
+ "Текст согласования",
+ "Отдел сотрудника",
+ "Комментарий",
+ }
+
+ cols := []string{"A", "B", "C", "D", "E", "F", "G", "H", "I"}
+
+ colWidths := map[string]float64{
+ "A": 25, "B": 35, "C": 18, "D": 30,
+ "E": 30, "F": 16, "G": 40, "H": 25, "I": 30,
+ }
+
+ // Стиль заголовка
+ headerStyle, _ := f.NewStyle(&excelize.Style{
+ Font: &excelize.Font{Bold: true, Color: "FFFFFF"},
+ Fill: excelize.Fill{Type: "pattern", Color: []string{"2E75B6"}, Pattern: 1},
+ Border: []excelize.Border{
+ {Type: "left", Color: "000000", Style: 1},
+ {Type: "right", Color: "000000", Style: 1},
+ {Type: "top", Color: "000000", Style: 1},
+ {Type: "bottom", Color: "000000", Style: 1},
+ },
+ Alignment: &excelize.Alignment{Horizontal: "center", Vertical: "center", WrapText: true},
+ })
+
+ // Стиль данных
+ dataStyle, _ := f.NewStyle(&excelize.Style{
+ Border: []excelize.Border{
+ {Type: "left", Color: "CCCCCC", Style: 1},
+ {Type: "right", Color: "CCCCCC", Style: 1},
+ {Type: "top", Color: "CCCCCC", Style: 1},
+ {Type: "bottom", Color: "CCCCCC", Style: 1},
+ },
+ Alignment: &excelize.Alignment{Vertical: "center", WrapText: true},
+ })
+
+ // Стиль отклонённых строк
+ rejectedStyle, _ := f.NewStyle(&excelize.Style{
+ Fill: excelize.Fill{Type: "pattern", Color: []string{"FFE0E0"}, Pattern: 1},
+ Border: []excelize.Border{
+ {Type: "left", Color: "CCCCCC", Style: 1},
+ {Type: "right", Color: "CCCCCC", Style: 1},
+ {Type: "top", Color: "CCCCCC", Style: 1},
+ {Type: "bottom", Color: "CCCCCC", Style: 1},
+ },
+ Alignment: &excelize.Alignment{Vertical: "center", WrapText: true},
+ })
+
+ for col, width := range colWidths {
+ f.SetColWidth(sheet, col, col, width) //nolint:errcheck
+ }
+
+ // Заголовки
+ for i, h := range headers {
+ cell := fmt.Sprintf("%s1", cols[i])
+ f.SetCellValue(sheet, cell, h) //nolint:errcheck
+ f.SetCellStyle(sheet, cell, cell, headerStyle) //nolint:errcheck
+ }
+ f.SetRowHeight(sheet, 1, 36) //nolint:errcheck
+
+ for rowIdx, a := range approvals {
+ row := rowIdx + 2
+
+ initiatorName := ""
+ if a.InitiatorID != nil {
+ if u, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *a.InitiatorID); u != nil && u.FullName != nil {
+ initiatorName = *u.FullName
+ }
+ }
+
+ topicName := ""
+ if a.TopicID != nil {
+ if t, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *a.TopicID); t != nil && t.Name != nil {
+ topicName = *t.Name
+ }
+ }
+
+ createdAt := ""
+ if a.CreatedAt != nil {
+ createdAt = a.CreatedAt.Format("02.01.2006 15:04")
+ }
+
+ var approverParts []string
+ var commentFromStep string
+ steps, _, _ := h.ipc.Database.ApprovalStep.GetApprovalStepsListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.ApprovalStep{ApprovalID: a.ID},
+ })
+ // Сортируем по StepOrder
+ sort.Slice(steps, func(i, j int) bool {
+ if steps[i].StepOrder == nil || steps[j].StepOrder == nil {
+ return false
+ }
+ return *steps[i].StepOrder < *steps[j].StepOrder
+ })
+ for _, s := range steps {
+ name := ""
+ // Сначала snapshot, если нет — тянем из БД
+ if s.ApproverNameSnapshot != nil && *s.ApproverNameSnapshot != "" {
+ name = *s.ApproverNameSnapshot
+ } else if s.ApproverID != nil {
+ if u, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *s.ApproverID); u != nil && u.FullName != nil {
+ name = *u.FullName
+ }
+ }
+
+ if name != "" {
+ approverParts = append(approverParts, name)
+ }
+
+ // Комментарий отклонения
+ if s.Status != nil && *s.Status == "rejected" && s.Comment != nil && *s.Comment != "" {
+ commentFromStep = *s.Comment
+ }
+ }
+ approversCell := strings.Join(approverParts, "\n")
+
+ // Наблюдатели по категории темы
+ var observerParts []string
+ categoryCode := h.getTopicCodeByApproval(ctx, a)
+ if categoryCode != "" {
+ observers, _ := h.ipc.Database.User.GetObserversForCategoryDB(ctx, categoryCode)
+ for _, obs := range observers {
+ if obs.FullName != nil {
+ observerParts = append(observerParts, *obs.FullName)
+ }
+ }
+ }
+ observersCell := strings.Join(observerParts, "\n")
+
+ // Статус
+ status := "—"
+ if a.Status != nil {
+ switch *a.Status {
+ case "pending":
+ status = "На согласовании"
+ case "approved":
+ status = "Согласовано"
+ case "rejected":
+ status = "Отклонено"
+ case "revoked":
+ status = "Отозвано"
+ }
+ }
+
+ // Текст согласования
+ content := ""
+ if a.Content != nil {
+ content = *a.Content
+ }
+
+ // Отдел
+ deptName := ""
+ if a.DepartmentID != nil {
+ if d, _ := h.ipc.Database.Department.GetDepartmentByIDDB(ctx, *a.DepartmentID); d != nil && d.Name != nil {
+ deptName = *d.Name
+ }
+ }
+
+ // Комментарий только для отклонённых
+ comment := ""
+ if a.Status != nil && *a.Status == "rejected" {
+ comment = commentFromStep
+ }
+
+ values := []interface{}{
+ initiatorName, topicName, createdAt,
+ approversCell, observersCell,
+ status, content, deptName, comment,
+ }
+
+ style := dataStyle
+ if a.Status != nil && *a.Status == "rejected" {
+ style = rejectedStyle
+ }
+
+ for colIdx, val := range values {
+ cell := fmt.Sprintf("%s%d", cols[colIdx], row)
+ f.SetCellValue(sheet, cell, val) //nolint:errcheck
+ f.SetCellStyle(sheet, cell, cell, style) //nolint:errcheck
+ }
+
+ // Высота строки зависит от числа согласующих
+ rowHeight := 20.0
+ if len(approverParts) > 1 {
+ rowHeight = float64(len(approverParts)) * 18
+ }
+ f.SetRowHeight(sheet, row, rowHeight) //nolint:errcheck
+ }
+
+ // Автофильтр на все столбцы
+ lastCol := cols[len(headers)-1]
+ lastRow := len(approvals) + 1
+ f.AutoFilter(sheet, //nolint:errcheck
+ fmt.Sprintf("A1:%s%d", lastCol, lastRow),
+ []excelize.AutoFilterOptions{},
+ )
+
+ // Закрепить первую строку
+ f.SetPanes(sheet, &excelize.Panes{ //nolint:errcheck
+ Freeze: true,
+ YSplit: 1,
+ TopLeftCell: "A2",
+ ActivePane: "bottomLeft",
+ })
+
+ var buf bytes.Buffer
+ if err := f.Write(&buf); err != nil {
+ return nil, err
+ }
+ return buf.Bytes(), nil
+}
+
+// getReportCategoryCodes — объединяет категории согласующего и наблюдателя.
+func (h *Handler) getReportCategoryCodes(ctx context.Context, user *typescore.User) []string {
+ seen := map[string]bool{}
+ var codes []string
+
+ addCodes := func(action string) {
+ perms, err := h.ipc.Database.Permission.GetUserPermissionsDB(ctx, *user.ID, action)
+ if err != nil {
+ return
+ }
+ for _, p := range perms {
+ if p.TopicCategoryID == nil {
+ continue
+ }
+ cat, err := h.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, *p.TopicCategoryID)
+ if err != nil || cat == nil || cat.Code == nil {
+ continue
+ }
+ if !seen[*cat.Code] {
+ seen[*cat.Code] = true
+ codes = append(codes, *cat.Code)
+ }
+ }
+ }
+
+ addCodes("create") // согласующий видит то, что сам может согласовывать
+ addCodes("observe") // наблюдатель видит свои категории
+
+ return codes
+}
+
+// buildExcelApprovalsReport — строит xlsx-файл отчёта по согласованиям и возвращает байты.
+func (h *Handler) buildExcelApprovalsReport(ctx context.Context, approvals []*typescore.Approval) ([]byte, error) {
+ f := excelize.NewFile()
+ sheet := "Согласования"
+ f.SetSheetName("Sheet1", sheet)
+
+ // Заголовки (добавлены колонки по задачам)
+ headers := []string{
+ "ФИО инициатора",
+ "Тема согласования",
+ "Дата создания",
+ "Согласующие",
+ "Наблюдатели",
+ "Статус",
+ "Текст согласования",
+ "Отдел сотрудника",
+ "Комментарий",
+ "Текст задачи",
+ "Исполнитель",
+ "Статус задачи",
+ }
+
+ cols := []string{"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L"}
+
+ colWidths := map[string]float64{
+ "A": 25, "B": 35, "C": 18, "D": 30,
+ "E": 30, "F": 16, "G": 40, "H": 25,
+ "I": 30, "J": 40, "K": 25, "L": 18,
+ }
+
+ // Стиль заголовка
+ headerStyle, _ := f.NewStyle(&excelize.Style{
+ Font: &excelize.Font{Bold: true, Color: "FFFFFF"},
+ Fill: excelize.Fill{Type: "pattern", Color: []string{"2E75B6"}, Pattern: 1},
+ Border: []excelize.Border{
+ {Type: "left", Color: "000000", Style: 1},
+ {Type: "right", Color: "000000", Style: 1},
+ {Type: "top", Color: "000000", Style: 1},
+ {Type: "bottom", Color: "000000", Style: 1},
+ },
+ Alignment: &excelize.Alignment{Horizontal: "center", Vertical: "center", WrapText: true},
+ })
+
+ // Стиль данных
+ dataStyle, _ := f.NewStyle(&excelize.Style{
+ Border: []excelize.Border{
+ {Type: "left", Color: "CCCCCC", Style: 1},
+ {Type: "right", Color: "CCCCCC", Style: 1},
+ {Type: "top", Color: "CCCCCC", Style: 1},
+ {Type: "bottom", Color: "CCCCCC", Style: 1},
+ },
+ Alignment: &excelize.Alignment{Vertical: "center", WrapText: true},
+ })
+
+ // Стиль отклонённых строк
+ rejectedStyle, _ := f.NewStyle(&excelize.Style{
+ Fill: excelize.Fill{Type: "pattern", Color: []string{"FFE0E0"}, Pattern: 1},
+ Border: []excelize.Border{
+ {Type: "left", Color: "CCCCCC", Style: 1},
+ {Type: "right", Color: "CCCCCC", Style: 1},
+ {Type: "top", Color: "CCCCCC", Style: 1},
+ {Type: "bottom", Color: "CCCCCC", Style: 1},
+ },
+ Alignment: &excelize.Alignment{Vertical: "center", WrapText: true},
+ })
+
+ for col, width := range colWidths {
+ f.SetColWidth(sheet, col, col, width) //nolint:errcheck
+ }
+
+ // Заголовки
+ for i, h := range headers {
+ cell := fmt.Sprintf("%s1", cols[i])
+ f.SetCellValue(sheet, cell, h) //nolint:errcheck
+ f.SetCellStyle(sheet, cell, cell, headerStyle) //nolint:errcheck
+ }
+ f.SetRowHeight(sheet, 1, 36) //nolint:errcheck
+
+ for rowIdx, a := range approvals {
+ row := rowIdx + 2
+
+ initiatorName := ""
+ if a.InitiatorID != nil {
+ if u, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *a.InitiatorID); u != nil && u.FullName != nil {
+ initiatorName = *u.FullName
+ }
+ }
+
+ topicName := ""
+ if a.TopicID != nil {
+ if t, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *a.TopicID); t != nil && t.Name != nil {
+ topicName = *t.Name
+ }
+ }
+
+ createdAt := ""
+ if a.CreatedAt != nil {
+ createdAt = a.CreatedAt.Format("02.01.2006 15:04")
+ }
+
+ var approverParts []string
+ var commentFromStep string
+ steps, _, _ := h.ipc.Database.ApprovalStep.GetApprovalStepsListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.ApprovalStep{ApprovalID: a.ID},
+ })
+ // Сортируем по StepOrder
+ sort.Slice(steps, func(i, j int) bool {
+ if steps[i].StepOrder == nil || steps[j].StepOrder == nil {
+ return false
+ }
+ return *steps[i].StepOrder < *steps[j].StepOrder
+ })
+ for _, s := range steps {
+ name := ""
+ // Сначала snapshot, если нет — тянем из БД
+ if s.ApproverNameSnapshot != nil && *s.ApproverNameSnapshot != "" {
+ name = *s.ApproverNameSnapshot
+ } else if s.ApproverID != nil {
+ if u, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *s.ApproverID); u != nil && u.FullName != nil {
+ name = *u.FullName
+ }
+ }
+
+ if name != "" {
+ approverParts = append(approverParts, name)
+ }
+
+ // Комментарий отклонения
+ if s.Status != nil && *s.Status == "rejected" && s.Comment != nil && *s.Comment != "" {
+ commentFromStep = *s.Comment
+ }
+ }
+ approversCell := strings.Join(approverParts, "\n")
+
+ // Наблюдатели по категории темы
+ var observerParts []string
+ categoryCode := h.getTopicCodeByApproval(ctx, a)
+ if categoryCode != "" {
+ observers, _ := h.ipc.Database.User.GetObserversForCategoryDB(ctx, categoryCode)
+ for _, obs := range observers {
+ if obs.FullName != nil {
+ observerParts = append(observerParts, *obs.FullName)
+ }
+ }
+ }
+ observersCell := strings.Join(observerParts, "\n")
+
+ // Статус
+ status := "—"
+ if a.Status != nil {
+ switch *a.Status {
+ case "pending":
+ status = "На согласовании"
+ case "approved":
+ status = "Согласовано"
+ case "rejected":
+ status = "Отклонено"
+ case "revoked":
+ status = "Отозвано"
+ }
+ }
+
+ // Текст согласования
+ content := ""
+ if a.Content != nil {
+ content = *a.Content
+ }
+
+ // Отдел
+ deptName := ""
+ if a.DepartmentID != nil {
+ if d, _ := h.ipc.Database.Department.GetDepartmentByIDDB(ctx, *a.DepartmentID); d != nil && d.Name != nil {
+ deptName = *d.Name
+ }
+ }
+
+ // Комментарий только для отклонённых
+ comment := ""
+ if a.Status != nil && *a.Status == "rejected" {
+ comment = commentFromStep
+ }
+
+ // Получаем задачи для этого согласования
+ tasks, _, _ := h.ipc.Database.ApprovalTasks.GetApprovalTasksListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.ApprovalTask{ApprovalID: a.ID},
+ })
+
+ var taskTexts []string
+ var executorNames []string
+ var taskStatuses []string
+
+ for _, task := range tasks {
+ if task.TaskText != nil {
+ taskTexts = append(taskTexts, *task.TaskText)
+ } else {
+ taskTexts = append(taskTexts, "—")
+ }
+
+ executorName := ""
+ if task.ExecutorID != nil {
+ if u, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *task.ExecutorID); u != nil && u.FullName != nil {
+ executorName = *u.FullName
+ }
+ }
+ executorNames = append(executorNames, executorName)
+
+ taskStatus := "—"
+ if task.Status != nil {
+ switch *task.Status {
+ case "pending":
+ taskStatus = "В работе"
+ case "completed":
+ taskStatus = "Выполнено"
+ case "cancelled":
+ taskStatus = "Отменено"
+ }
+ }
+ taskStatuses = append(taskStatuses, taskStatus)
+ }
+
+ taskText := strings.Join(taskTexts, "\n")
+ executorName := strings.Join(executorNames, "\n")
+ taskStatus := strings.Join(taskStatuses, "\n")
+
+ values := []interface{}{
+ initiatorName, topicName, createdAt,
+ approversCell, observersCell,
+ status, content, deptName, comment,
+ taskText, executorName, taskStatus,
+ }
+
+ style := dataStyle
+ if a.Status != nil && *a.Status == "rejected" {
+ style = rejectedStyle
+ }
+
+ for colIdx, val := range values {
+ cell := fmt.Sprintf("%s%d", cols[colIdx], row)
+ f.SetCellValue(sheet, cell, val) //nolint:errcheck
+ f.SetCellStyle(sheet, cell, cell, style) //nolint:errcheck
+ }
+
+ // Высота строки зависит от числа согласующих и задач
+ rowHeight := 20.0
+ maxLines := len(approverParts)
+ if len(taskTexts) > maxLines {
+ maxLines = len(taskTexts)
+ }
+ if maxLines > 1 {
+ rowHeight = float64(maxLines) * 18
+ }
+ f.SetRowHeight(sheet, row, rowHeight) //nolint:errcheck
+ }
+
+ // Автофильтр на все столбцы
+ lastCol := cols[len(headers)-1]
+ lastRow := len(approvals) + 1
+ f.AutoFilter(sheet, //nolint:errcheck
+ fmt.Sprintf("A1:%s%d", lastCol, lastRow),
+ []excelize.AutoFilterOptions{},
+ )
+
+ // Закрепить первую строку
+ f.SetPanes(sheet, &excelize.Panes{ //nolint:errcheck
+ Freeze: true,
+ YSplit: 1,
+ TopLeftCell: "A2",
+ ActivePane: "bottomLeft",
+ })
+
+ var buf bytes.Buffer
+ if err := f.Write(&buf); err != nil {
+ return nil, err
+ }
+ return buf.Bytes(), nil
+}
+
+// buildExcelTasksReport — строит xlsx-файл отчёта по задачам и возвращает байты.
+func (h *Handler) buildExcelTasksReport(ctx context.Context, tasks []*typescore.ApprovalTask) ([]byte, error) {
+ f := excelize.NewFile()
+ sheet := "Задачи"
+ f.SetSheetName("Sheet1", sheet)
+
+ // Заголовки
+ headers := []string{
+ "Текст задачи",
+ "Исполнитель",
+ "Статус задачи",
+ "Дата создания задачи",
+ "Дата завершения",
+ "Тема согласования",
+ "ФИО инициатора",
+ "Дата создания согласования",
+ "Статус согласования",
+ "Текст согласования",
+ "Отдел",
+ }
+
+ cols := []string{"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K"}
+
+ colWidths := map[string]float64{
+ "A": 40, "B": 25, "C": 18, "D": 18,
+ "E": 18, "F": 35, "G": 25, "H": 18,
+ "I": 20, "J": 40, "K": 25,
+ }
+
+ // Стиль заголовка
+ headerStyle, _ := f.NewStyle(&excelize.Style{
+ Font: &excelize.Font{Bold: true, Color: "FFFFFF"},
+ Fill: excelize.Fill{Type: "pattern", Color: []string{"4472C4"}, Pattern: 1},
+ Border: []excelize.Border{
+ {Type: "left", Color: "000000", Style: 1},
+ {Type: "right", Color: "000000", Style: 1},
+ {Type: "top", Color: "000000", Style: 1},
+ {Type: "bottom", Color: "000000", Style: 1},
+ },
+ Alignment: &excelize.Alignment{Horizontal: "center", Vertical: "center", WrapText: true},
+ })
+
+ // Стиль данных
+ dataStyle, _ := f.NewStyle(&excelize.Style{
+ Border: []excelize.Border{
+ {Type: "left", Color: "CCCCCC", Style: 1},
+ {Type: "right", Color: "CCCCCC", Style: 1},
+ {Type: "top", Color: "CCCCCC", Style: 1},
+ {Type: "bottom", Color: "CCCCCC", Style: 1},
+ },
+ Alignment: &excelize.Alignment{Vertical: "center", WrapText: true},
+ })
+
+ // Стиль выполненных задач
+ completedStyle, _ := f.NewStyle(&excelize.Style{
+ Fill: excelize.Fill{Type: "pattern", Color: []string{"E2EFDA"}, Pattern: 1},
+ Border: []excelize.Border{
+ {Type: "left", Color: "CCCCCC", Style: 1},
+ {Type: "right", Color: "CCCCCC", Style: 1},
+ {Type: "top", Color: "CCCCCC", Style: 1},
+ {Type: "bottom", Color: "CCCCCC", Style: 1},
+ },
+ Alignment: &excelize.Alignment{Vertical: "center", WrapText: true},
+ })
+
+ for col, width := range colWidths {
+ f.SetColWidth(sheet, col, col, width) //nolint:errcheck
+ }
+
+ // Заголовки
+ for i, h := range headers {
+ cell := fmt.Sprintf("%s1", cols[i])
+ f.SetCellValue(sheet, cell, h) //nolint:errcheck
+ f.SetCellStyle(sheet, cell, cell, headerStyle) //nolint:errcheck
+ }
+ f.SetRowHeight(sheet, 1, 36) //nolint:errcheck
+
+ for rowIdx, task := range tasks {
+ row := rowIdx + 2
+
+ // Текст задачи
+ taskText := ""
+ if task.TaskText != nil {
+ taskText = *task.TaskText
+ }
+
+ // Исполнитель
+ executorName := ""
+ if task.ExecutorID != nil {
+ if u, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *task.ExecutorID); u != nil && u.FullName != nil {
+ executorName = *u.FullName
+ }
+ }
+
+ // Статус задачи
+ taskStatus := "—"
+ if task.Status != nil {
+ switch *task.Status {
+ case "pending":
+ taskStatus = "В работе"
+ case "completed":
+ taskStatus = "Выполнено"
+ case "cancelled":
+ taskStatus = "Отменено"
+ }
+ }
+
+ // Дата создания задачи
+ taskCreatedAt := ""
+ if task.CreatedAt != nil {
+ taskCreatedAt = task.CreatedAt.Format("02.01.2006 15:04")
+ }
+
+ // Дата завершения
+ taskCompletedAt := ""
+ if task.CompletedAt != nil {
+ taskCompletedAt = task.CompletedAt.Format("02.01.2006 15:04")
+ }
+
+ // Получаем согласование
+ var approval *typescore.Approval
+ if task.ApprovalID != nil {
+ approval, _ = h.ipc.Database.Approval.GetApprovalByIDDB(ctx, *task.ApprovalID)
+ }
+
+ // Тема согласования
+ topicName := ""
+ if approval != nil && approval.TopicID != nil {
+ if t, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *approval.TopicID); t != nil && t.Name != nil {
+ topicName = *t.Name
+ }
+ }
+
+ // ФИО инициатора
+ initiatorName := ""
+ if approval != nil && approval.InitiatorID != nil {
+ if u, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *approval.InitiatorID); u != nil && u.FullName != nil {
+ initiatorName = *u.FullName
+ }
+ }
+
+ // Дата создания согласования
+ approvalCreatedAt := ""
+ if approval != nil && approval.CreatedAt != nil {
+ approvalCreatedAt = approval.CreatedAt.Format("02.01.2006 15:04")
+ }
+
+ // Статус согласования
+ approvalStatus := "—"
+ if approval != nil && approval.Status != nil {
+ switch *approval.Status {
+ case "pending":
+ approvalStatus = "На согласовании"
+ case "approved":
+ approvalStatus = "Согласовано"
+ case "rejected":
+ approvalStatus = "Отклонено"
+ case "revoked":
+ approvalStatus = "Отозвано"
+ }
+ }
+
+ // Текст согласования
+ approvalContent := ""
+ if approval != nil && approval.Content != nil {
+ approvalContent = *approval.Content
+ }
+
+ // Отдел
+ deptName := ""
+ if approval != nil && approval.DepartmentID != nil {
+ if d, _ := h.ipc.Database.Department.GetDepartmentByIDDB(ctx, *approval.DepartmentID); d != nil && d.Name != nil {
+ deptName = *d.Name
+ }
+ }
+
+ values := []interface{}{
+ taskText, executorName, taskStatus,
+ taskCreatedAt, taskCompletedAt,
+ topicName, initiatorName, approvalCreatedAt,
+ approvalStatus, approvalContent, deptName,
+ }
+
+ style := dataStyle
+ if task.Status != nil && *task.Status == "completed" {
+ style = completedStyle
+ }
+
+ for colIdx, val := range values {
+ cell := fmt.Sprintf("%s%d", cols[colIdx], row)
+ f.SetCellValue(sheet, cell, val) //nolint:errcheck
+ f.SetCellStyle(sheet, cell, cell, style) //nolint:errcheck
+ }
+
+ f.SetRowHeight(sheet, row, 20) //nolint:errcheck
+ }
+
+ // Автофильтр на все столбцы
+ lastCol := cols[len(headers)-1]
+ lastRow := len(tasks) + 1
+ f.AutoFilter(sheet, //nolint:errcheck
+ fmt.Sprintf("A1:%s%d", lastCol, lastRow),
+ []excelize.AutoFilterOptions{},
+ )
+
+ // Закрепить первую строку
+ f.SetPanes(sheet, &excelize.Panes{ //nolint:errcheck
+ Freeze: true,
+ YSplit: 1,
+ TopLeftCell: "A2",
+ ActivePane: "bottomLeft",
+ })
+
+ var buf bytes.Buffer
+ if err := f.Write(&buf); err != nil {
+ return nil, err
+ }
+ return buf.Bytes(), nil
+}
+
+const reportDateLayout = "02.01.2006"
+
+// HandleReportMenu — первый шаг: показываем выбор типа отчёта.
+func (h *Handler) HandleReportMenu(bot *tgbotapi.BotAPI, chatID int64, telegramID int64) {
+ ctx := context.Background()
+
+ user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID)
+ if err != nil || user == nil || user.ID == nil {
+ return
+ }
+
+ // Проверяем что у пользователя есть роль согласующего или наблюдателя
+ isApprover, _ := h.ipc.Database.User.IsApproverDB(ctx, *user.ID)
+ isObserver, _ := h.ipc.Database.User.IsObserverDB(ctx, *user.ID)
+ isDirector, _ := h.ipc.Database.User.IsDirectorDB(ctx, *user.ID)
+
+ if !isApprover && !isObserver && !isDirector {
+ sendText(bot, chatID, "У вас нет доступа к выгрузке отчётов.")
+ return
+ }
+
+ // Сбрасываем предыдущий фильтр
+ h.States.ClearReport(ctx, telegramID) //nolint:errcheck
+
+ msg := tgbotapi.NewMessage(chatID,
+ "📊 Выгрузка отчёта\n\n"+
+ "Выберите тип отчёта:")
+ msg.ParseMode = "HTML"
+ msg.ReplyMarkup = keyboard.BuildReportTypeMenu()
+ bot.Send(msg) //nolint:errcheck
+}
+
+// HandleReportTypeSelection — выбор типа отчёта (согласования или задачи).
+func (h *Handler) HandleReportTypeSelection(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, reportType string) {
+ ctx := context.Background()
+ telegramID := cq.From.ID
+ chatID := cq.Message.Chat.ID
+
+ bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck
+ bot.Request(tgbotapi.NewDeleteMessage(chatID, cq.Message.MessageID)) //nolint:errcheck
+
+ // Сохраняем тип отчёта в state
+ h.States.SetReport(ctx, telegramID, &state.ReportFilterState{ //nolint:errcheck
+ ReportType: reportType,
+ })
+
+ title := "согласований"
+ if reportType == "tasks" {
+ title = "задач"
+ }
+
+ msg := tgbotapi.NewMessage(chatID,
+ fmt.Sprintf("📊 Выгрузка отчёта %s\n\n"+
+ "Выберите период или выгрузите за всё время:", title))
+ msg.ParseMode = "HTML"
+ msg.ReplyMarkup = keyboard.BuildReportFilterMenu()
+ bot.Send(msg) //nolint:errcheck
+}
+
+// HandleReportSetDates — пользователь хочет указать период, просим дату ОТ.
+func (h *Handler) HandleReportSetDates(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery) {
+ ctx := context.Background()
+ telegramID := cq.From.ID
+ chatID := cq.Message.Chat.ID
+
+ bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck
+ bot.Request(tgbotapi.NewDeleteMessage(chatID, cq.Message.MessageID)) //nolint:errcheck
+
+ // Получаем текущий state чтобы сохранить ReportType
+ filterState, _ := h.States.GetReport(ctx, telegramID)
+ reportType := ""
+ if filterState != nil {
+ reportType = filterState.ReportType
+ }
+
+ h.States.SetReport(ctx, telegramID, &state.ReportFilterState{ //nolint:errcheck
+ ReportType: reportType,
+ AwaitDateFrom: true,
+ })
+
+ sendText(bot, chatID, "Введите дату начала периода в формате ДД.ММ.ГГГГ:")
+}
+
+// HandleReportAllTime — выгрузить без фильтра по дате.
+func (h *Handler) HandleReportAllTime(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery) {
+ ctx := context.Background()
+ telegramID := cq.From.ID
+ chatID := cq.Message.Chat.ID
+
+ bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck
+ bot.Request(tgbotapi.NewDeleteMessage(chatID, cq.Message.MessageID)) //nolint:errcheck
+
+ filterState, _ := h.States.GetReport(ctx, telegramID)
+ reportType := ""
+ if filterState != nil {
+ reportType = filterState.ReportType
+ }
+
+ h.generateAndSendReport(ctx, bot, chatID, telegramID, reportType, nil, nil)
+}
+
+// HandleReportGenerate — выгрузить с датой ОТ, без даты ДО (по сегодня).
+func (h *Handler) HandleReportGenerate(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery) {
+ ctx := context.Background()
+ telegramID := cq.From.ID
+ chatID := cq.Message.Chat.ID
+
+ bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck
+ bot.Request(tgbotapi.NewDeleteMessage(chatID, cq.Message.MessageID)) //nolint:errcheck
+
+ filterState, _ := h.States.GetReport(ctx, telegramID)
+ h.States.ClearReport(ctx, telegramID) //nolint:errcheck
+
+ reportType := ""
+ var dateFrom *time.Time
+ if filterState != nil {
+ reportType = filterState.ReportType
+ if filterState.DateFrom != "" {
+ if t, err := time.ParseInLocation(reportDateLayout, filterState.DateFrom, time.Local); err == nil {
+ dateFrom = &t
+ }
+ }
+ }
+
+ now := time.Now()
+ h.generateAndSendReport(ctx, bot, chatID, telegramID, reportType, dateFrom, &now)
+}
+
+// HandleReportTextInput — обрабатывает ввод дат фильтра.
+// Возвращает true если сообщение принято.
+func (h *Handler) HandleReportTextInput(bot *tgbotapi.BotAPI, msg *tgbotapi.Message) bool {
+ ctx := context.Background()
+ telegramID := msg.From.ID
+ chatID := msg.Chat.ID
+
+ filterState, err := h.States.GetReport(ctx, telegramID)
+ if err != nil || filterState == nil {
+ return false
+ }
+ if !filterState.AwaitDateFrom && !filterState.AwaitDateTo {
+ return false
+ }
+
+ input := msg.Text
+ if _, err := time.ParseInLocation(reportDateLayout, input, time.Local); err != nil {
+ sendText(bot, chatID, "⚠️ Неверный формат даты. Введите в формате ДД.ММ.ГГГГ:")
+ return true
+ }
+
+ if filterState.AwaitDateFrom {
+ filterState.DateFrom = input
+ filterState.AwaitDateFrom = false
+ filterState.AwaitDateTo = true
+ h.States.SetReport(ctx, telegramID, filterState) //nolint:errcheck
+
+ reply := tgbotapi.NewMessage(chatID,
+ fmt.Sprintf("Дата начала: %s\n\nВведите дату окончания периода в формате ДД.ММ.ГГГГ:", input))
+ reply.ParseMode = "HTML"
+ reply.ReplyMarkup = keyboard.BuildReportDateToMenu()
+ bot.Send(reply) //nolint:errcheck
+ return true
+ }
+
+ if filterState.AwaitDateTo {
+ filterState.DateTo = input
+ filterState.AwaitDateTo = false
+ reportType := filterState.ReportType
+ h.States.ClearReport(ctx, telegramID) //nolint:errcheck
+
+ dateFrom, _ := time.ParseInLocation(reportDateLayout, filterState.DateFrom, time.Local)
+ dateTo, _ := time.ParseInLocation(reportDateLayout, filterState.DateTo, time.Local)
+
+ if dateTo.Before(dateFrom) {
+ sendText(bot, chatID, "⚠️ Дата окончания не может быть раньше даты начала. Попробуйте снова — нажмите 📊 Выгрузка отчёта.")
+ return true
+ }
+
+ h.generateAndSendReport(ctx, bot, chatID, telegramID, reportType, &dateFrom, &dateTo)
+ return true
+ }
+
+ return false
+}
+
+// generateAndSendReport — сборка отчёта и отправка файла.
+func (h *Handler) generateAndSendReport(
+ ctx context.Context,
+ bot *tgbotapi.BotAPI,
+ chatID int64,
+ telegramID int64,
+ reportType string,
+ dateFrom *time.Time,
+ dateTo *time.Time,
+) {
+ user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID)
+ if err != nil || user == nil || user.ID == nil {
+ return
+ }
+
+ sendText(bot, chatID, "⏳ Формирую отчёт...")
+
+ isDirector, _ := h.ipc.Database.User.IsDirectorDB(ctx, *user.ID)
+
+ var buf []byte
+ var fileName string
+ var caption string
+
+ if reportType == "tasks" {
+ // Отчёт по задачам
+ tasks, err := h.getTasksForReport(ctx, user, isDirector, dateFrom, dateTo)
+ if err != nil {
+ logrus.Errorf("generateAndSendReport: getTasksForReport err=%v", err)
+ sendText(bot, chatID, "Ошибка при получении данных. Попробуйте позже.")
+ return
+ }
+
+ if len(tasks) == 0 {
+ sendText(bot, chatID, "📭 Нет задач за выбранный период.")
+ return
+ }
+
+ buf, err = h.buildExcelTasksReport(ctx, tasks)
+ if err != nil {
+ logrus.Errorf("generateAndSendReport: buildExcelTasksReport err=%v", err)
+ sendText(bot, chatID, "Ошибка при формировании файла. Попробуйте позже.")
+ return
+ }
+
+ now := time.Now()
+ fileName = fmt.Sprintf("Задачи %s %s.xlsx",
+ now.Format("02.01.2006"),
+ now.Format("15-04"),
+ )
+ caption = fmt.Sprintf("📋 Отчёт по задачам сформирован: %s %s", now.Format("02.01.2006"), now.Format("15:04"))
+
+ } else {
+ // Отчёт по согласованиям (по умолчанию)
+ approvals, err := h.getApprovalsForReport(ctx, user, isDirector, dateFrom, dateTo)
+ if err != nil {
+ logrus.Errorf("generateAndSendReport: getApprovalsForReport err=%v", err)
+ sendText(bot, chatID, "Ошибка при получении данных. Попробуйте позже.")
+ return
+ }
+
+ if len(approvals) == 0 {
+ sendText(bot, chatID, "📭 Нет согласований за выбранный период.")
+ return
+ }
+
+ buf, err = h.buildExcelApprovalsReport(ctx, approvals)
+ if err != nil {
+ logrus.Errorf("generateAndSendReport: buildExcelApprovalsReport err=%v", err)
+ sendText(bot, chatID, "Ошибка при формировании файла. Попробуйте позже.")
+ return
+ }
+
+ now := time.Now()
+ fileName = fmt.Sprintf("Согласования %s %s.xlsx",
+ now.Format("02.01.2006"),
+ now.Format("15-04"),
+ )
+ caption = fmt.Sprintf("📊 Отчёт по согласованиям сформирован: %s %s", now.Format("02.01.2006"), now.Format("15:04"))
+ }
+
+ fileBytes := tgbotapi.FileBytes{Name: fileName, Bytes: buf}
+ doc := tgbotapi.NewDocument(chatID, fileBytes)
+ doc.Caption = caption
+ doc.ParseMode = "HTML"
+
+ if _, err := bot.Send(doc); err != nil {
+ logrus.Errorf("generateAndSendReport: Send err=%v", err)
+ }
+}
+
+// getApprovalsForReport — получение согласований с учётом всех ролей пользователя.
+func (h *Handler) getApprovalsForReport(
+ ctx context.Context,
+ user *typescore.User,
+ isDirector bool,
+ dateFrom *time.Time,
+ dateTo *time.Time,
+) ([]*typescore.Approval, error) {
+ filter := typescore.ReportFilter{
+ AllAccess: isDirector,
+ DateFrom: dateFrom,
+ DateTo: dateTo,
+ }
+
+ if !isDirector {
+ // Для обычного пользователя собираем ID согласований, где он участвует
+ filter.UserID = user.ID
+ }
+
+ return h.ipc.Database.Approval.GetApprovalsForReportDB(ctx, filter)
+}
+
+// getTasksForReport — получение задач для отчёта.
+func (h *Handler) getTasksForReport(
+ ctx context.Context,
+ user *typescore.User,
+ isDirector bool,
+ dateFrom *time.Time,
+ dateTo *time.Time,
+) ([]*typescore.ApprovalTask, error) {
+ filter := typescore.TaskReportFilter{
+ AllAccess: isDirector,
+ DateFrom: dateFrom,
+ DateTo: dateTo,
+ }
+
+ if !isDirector {
+ filter.UserID = user.ID
+ }
+
+ return h.ipc.Database.ApprovalTasks.GetTasksForReportDB(ctx, filter)
+}
diff --git a/service/telegram_service/handlers/approval/helper.go b/service/telegram_service/handlers/approval/helper.go
new file mode 100644
index 0000000..f0f884a
--- /dev/null
+++ b/service/telegram_service/handlers/approval/helper.go
@@ -0,0 +1,405 @@
+package approval
+
+import (
+ "bitrix_balancer_api/core/typescore"
+ "bitrix_balancer_api/core/utilscore"
+ "bitrix_balancer_api/telegram_service/keyboard"
+ "bitrix_balancer_api/telegram_service/state"
+ "context"
+ "fmt"
+ tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
+ "github.com/sirupsen/logrus"
+ "strings"
+)
+
+func sendText(bot *tgbotapi.BotAPI, chatID int64, text string) {
+ msg := tgbotapi.NewMessage(chatID, text)
+ msg.ParseMode = "HTML"
+ bot.Send(msg) //nolint:errcheck
+}
+
+// submitApproval создаёт запись в БД и уведомляет согласующих.
+func (h *Handler) submitApproval(ctx context.Context, bot *tgbotapi.BotAPI, telegramID int64, flowState *state.ApprovalFlowState) (*typescore.Approval, error) {
+ topic, err := h.registry.Get(flowState.TopicCode)
+ if err != nil {
+ return nil, err
+ }
+
+ initiator, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID)
+ if err != nil {
+ return nil, fmt.Errorf("GetUserByTelegramIDDB: %w", err)
+ }
+ if initiator == nil {
+ return nil, fmt.Errorf("initiator not found for telegramID=%d", telegramID)
+ }
+ if initiator.ID == nil {
+ return nil, fmt.Errorf("initiator.ID is nil")
+ }
+ if initiator.DepartmentID == nil {
+ return nil, fmt.Errorf("initiator.DepartmentID is nil")
+ }
+
+ topicCode, err := topic.TopicCodeFromCollected(flowState.Collected)
+ if err != nil {
+ return nil, err
+ }
+
+ approvalTopic, err := h.ipc.Database.ApprovalTopic.GetApprovalTopicByCodeDB(ctx, topicCode)
+ if err != nil {
+ return nil, fmt.Errorf("GetApprovalTopicByCodeDB: %w", err)
+ }
+ if approvalTopic == nil {
+ return nil, fmt.Errorf("approval topic not found: %s", topicCode)
+ }
+ if approvalTopic.ID == nil {
+ return nil, fmt.Errorf("approvalTopic.ID is nil")
+ }
+
+ content := flowState.Collected["content"]
+ status := "pending"
+ approval := &typescore.Approval{
+ InitiatorID: initiator.ID,
+ TopicID: approvalTopic.ID,
+ DepartmentID: initiator.DepartmentID,
+ Content: &content,
+ Status: &status,
+ }
+
+ created, _, err := h.ipc.Database.Approval.CreateApprovalDB(ctx, nil, approval, true)
+ if err != nil {
+ return nil, fmt.Errorf("CreateApprovalDB: %w", err)
+ }
+ if created == nil || created.ID == nil {
+ return nil, fmt.Errorf("created approval is nil or has no ID")
+ }
+
+ // Сохраняем файлы если есть
+ for _, f := range flowState.Files {
+ f := f // захват переменной
+ base64Copy := f.Base64
+ nameCopy := f.FileName
+ file := &typescore.ApprovalFile{
+ ApprovalID: created.ID,
+ FileBase64: &base64Copy,
+ FileName: &nameCopy,
+ }
+ if _, _, err := h.ipc.Database.ApprovalFile.CreateApprovalFileDB(ctx, nil, file); err != nil {
+ logrus.Errorf("submitApproval: CreateApprovalFileDB err=%v", err)
+ // Не фатально — продолжаем, заявка уже создана
+ }
+ }
+
+ // Подгружаем файлы обратно в объект для уведомлений
+ files, err := h.ipc.Database.ApprovalFile.GetFilesByApprovalIDDB(ctx, *created.ID)
+ if err != nil {
+ logrus.Warnf("submitApproval: GetFilesByApprovalIDDB err=%v", err)
+ }
+ created.Files = files
+
+ var approvers []*typescore.User
+
+ // Если согласующий был выбран вручную - используем его
+ if flowState.SelectedApproverID > 0 {
+ selectedApprover, err := h.ipc.Database.User.GetUserByIDDB(ctx, flowState.SelectedApproverID)
+ if err != nil || selectedApprover == nil {
+ return nil, fmt.Errorf("selected approver not found: %d", flowState.SelectedApproverID)
+ }
+ approvers = []*typescore.User{selectedApprover}
+ } else {
+ // Получаем согласующих автоматически через иерархию
+ approvers, err = h.ipc.Database.UserHierarchy.GetApproversDB(ctx,
+ *initiator.ID,
+ *initiator.DepartmentID,
+ *approvalTopic.ID,
+ *approvalTopic.CategoryID,
+ )
+ if err != nil {
+ return nil, fmt.Errorf("GetApproversDB: %w", err)
+ }
+ }
+
+ if len(approvers) == 0 {
+ logrus.Warnf("submitApproval: no approvers found for userID=%d deptID=%d", *initiator.ID, *initiator.DepartmentID)
+
+ approvedStatus := "approved"
+ created.Status = &approvedStatus
+ if _, _, err := h.ipc.Database.Approval.UpdateApprovalDB(ctx, nil, created); err != nil {
+ logrus.Errorf("submitApproval: auto-approve UpdateApprovalDB err=%v", err)
+ }
+
+ if initiator.TelegramID != nil {
+ tName := ""
+ if approvalTopic.Name != nil {
+ tName = *approvalTopic.Name
+ }
+ text := fmt.Sprintf(
+ "✅ Заявка #%d автоматически согласована\n\n"+
+ "📋 Тема: %s\n"+
+ "📝 Текст: %s\n\n"+
+ "Согласующий не назначен — заявка принята автоматически.",
+ *created.ID, tName, content,
+ )
+ msg := tgbotapi.NewMessage(*initiator.TelegramID, text)
+ msg.ParseMode = "HTML"
+ msg.ReplyMarkup = keyboard.BuildRevokeButton(*created.ID)
+ bot.Send(msg) //nolint:errcheck
+ }
+
+ notifier := NewNotifier(h.ipc, topic)
+
+ directors, _ := h.ipc.Database.User.GetDirectorsDB(ctx)
+ for _, director := range directors {
+ if director.TelegramID != nil {
+ notifier.NotifyDirector(bot, director, initiator, created, flowState.Collected)
+ }
+ }
+
+ observers, _ := h.ipc.Database.User.GetObserversForCategoryDB(ctx, flowState.TopicCode)
+ for _, obs := range observers {
+ if obs.TelegramID != nil {
+ notifier.NotifyObserversNewApproval(bot, []*typescore.User{obs}, initiator, created, flowState.Collected)
+ }
+ }
+
+ return created, nil
+ }
+
+ for i, approver := range approvers {
+ if approver.ID == nil {
+ logrus.Warnf("submitApproval: approver.ID is nil at index=%d", i)
+ continue
+ }
+
+ order := i + 1
+ stepStatus := "waiting"
+ if i == 0 {
+ stepStatus = "pending" // первый активен сразу
+ }
+
+ // Снимок имени и отдела согласующего
+ approverName := ""
+ if approver.FullName != nil {
+ approverName = *approver.FullName
+ }
+ approverDept := ""
+
+ step := &typescore.ApprovalStep{
+ ApprovalID: created.ID,
+ ApproverID: approver.ID,
+ StepOrder: &order,
+ Status: &stepStatus,
+ ApproverNameSnapshot: &approverName,
+ ApproverDepartmentSnapshot: &approverDept,
+ }
+
+ if _, _, err := h.ipc.Database.ApprovalStep.CreateApprovalStepDB(ctx, nil, step); err != nil {
+ logrus.Errorf("submitApproval: CreateApprovalStepDB err=%v", err)
+ }
+ }
+
+ // Уведомляем первого согласующего (или делегата)
+ firstApprover := approvers[0]
+ if firstApprover.TelegramID == nil {
+ logrus.Warnf("submitApproval: firstApprover.TelegramID is nil, userID=%d", *firstApprover.ID)
+ return created, nil
+ }
+
+ // Проверяем делегирование
+ if approvalTopic.CategoryID != nil {
+ // Сначала проверяем делегирование конкретной темы
+ if delegations, _, err := h.ipc.Database.ApprovalDelegation.GetApprovalDelegationsListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.ApprovalDelegation{
+ IsActive: utilscore.PointerToBool(true),
+ TopicID: approvalTopic.ID,
+ }}); err == nil && len(delegations) > 0 {
+ for _, deleg := range delegations {
+ if deleg.DelegatorID != nil && *deleg.DelegatorID == *firstApprover.ID && deleg.DelegateID != nil {
+ delegate, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *deleg.DelegateID)
+ if delegate != nil && delegate.TelegramID != nil {
+
+ firstApprover = delegate
+ break
+ }
+ }
+ }
+ } else {
+ // Проверяем делегирование всей категории
+ if delegations, _, err := h.ipc.Database.ApprovalDelegation.GetApprovalDelegationsListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.ApprovalDelegation{
+ IsActive: utilscore.PointerToBool(true),
+ CategoryID: approvalTopic.CategoryID,
+ }}); err == nil && len(delegations) > 0 {
+ for _, deleg := range delegations {
+ if deleg.DelegatorID != nil && *deleg.DelegatorID == *firstApprover.ID && deleg.DelegateID != nil {
+ delegate, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *deleg.DelegateID)
+ if delegate != nil && delegate.TelegramID != nil {
+ firstApprover = delegate
+ break
+ }
+ }
+ }
+ }
+ }
+ }
+
+ notifier := NewNotifier(h.ipc, topic)
+ notifier.NotifyApprover(bot, firstApprover, initiator, created, flowState.Collected)
+
+ // Уведомляем наблюдателей о новой заявке
+ observers, err := h.ipc.Database.User.GetObserversForCategoryDB(ctx, flowState.TopicCode)
+ if err != nil {
+ logrus.Warnf("submitApproval: GetObserversForCategoryDB err=%v", err)
+ } else if len(observers) > 0 {
+ notifier.NotifyObserversNewApproval(bot, observers, initiator, created, flowState.Collected)
+ }
+
+ return created, nil
+}
+
+// getTopicCodeByApproval возвращает category code по заявке — для получения Topic из реестра.
+func (h *Handler) getTopicCodeByApproval(ctx context.Context, approval *typescore.Approval) string {
+ if approval.TopicID == nil {
+ return ""
+ }
+ topic, err := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *approval.TopicID)
+ if err != nil || topic == nil {
+ return ""
+ }
+ category, err := h.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, *topic.CategoryID)
+ if err != nil || category == nil {
+ return ""
+ }
+ if category.Code == nil {
+ return ""
+ }
+ return *category.Code
+}
+
+// getCollectedFromApproval восстанавливает map collected из сохранённого контента заявки.
+// Контент хранится как введённая строка — для уведомлений этого достаточно.
+func (h *Handler) getCollectedFromApproval(ctx context.Context, approval *typescore.Approval) map[string]string {
+ collected := map[string]string{}
+ if approval.Content != nil {
+ collected["content"] = *approval.Content
+ }
+
+ topic, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *approval.TopicID)
+ if topic != nil {
+ if topic.PaymentType != nil {
+ collected["payment_type"] = *topic.PaymentType
+ }
+ if topic.DurationType != nil {
+ collected["duration_type"] = *topic.DurationType
+ }
+ if topic.TimeType != nil {
+ collected["time_type"] = *topic.TimeType
+ }
+ }
+ return collected
+}
+
+// getAllowedTopicCodes возвращает map[category_code]bool с разрешёнными для пользователя категориями.
+// Право считается выданным если:
+// - есть запись permissions с action=create и topic_category_id совпадает с категорией темы
+// - ИЛИ есть запись с action=create и topic_id совпадает с конкретной темой
+func (h *Handler) getAllowedTopicCodes(ctx context.Context, user *typescore.User) (map[string]bool, error) {
+ allowed := map[string]bool{}
+
+ perms, err := h.ipc.Database.Permission.GetUserPermissionsDB(ctx, *user.ID, "create")
+ if err != nil {
+ return nil, err
+ }
+ logrus.Infof("getAllowedTopicCodes: userID=%d perms count=%d", *user.ID, len(perms))
+
+ if len(perms) == 0 {
+ return allowed, nil
+ }
+
+ allowedCategoryIDs := map[uint64]bool{}
+ allowedTopicIDs := map[uint64]bool{}
+ for _, p := range perms {
+ if p.TopicCategoryID != nil {
+ allowedCategoryIDs[*p.TopicCategoryID] = true
+ logrus.Infof("getAllowedTopicCodes: allowed category_id=%d", *p.TopicCategoryID)
+ }
+ if p.TopicID != nil {
+ allowedTopicIDs[*p.TopicID] = true
+ }
+ }
+
+ for _, t := range h.registry.All() {
+ logrus.Infof("getAllowedTopicCodes: checking topic code=%s", t.Code())
+
+ category, err := h.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByCodeDB(ctx, t.Code())
+ if err != nil {
+ logrus.Warnf("getAllowedTopicCodes: GetApprovalTopicCategoryByCodeDB err=%v", err)
+ continue
+ }
+ if category == nil {
+ logrus.Warnf("getAllowedTopicCodes: category not found for code=%s", t.Code())
+ continue
+ }
+ logrus.Infof("getAllowedTopicCodes: category found id=%d code=%s", *category.ID, *category.Code)
+ logrus.Infof("getAllowedTopicCodes: allowedCategoryIDs=%v match=%v", allowedCategoryIDs, allowedCategoryIDs[*category.ID])
+
+ 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
+}
+
+// showFileStatus удаляет предыдущее статусное сообщение и отправляет новое
+// с текущим списком файлов и клавиатурой управления.
+func (h *Handler) showFileStatus(bot *tgbotapi.BotAPI, chatID int64, telegramID int64, flowState *state.ApprovalFlowState) {
+ ctx := context.Background()
+
+ // Удаляем старое статусное сообщение
+ if flowState.FileStatusMsgID != 0 {
+ bot.Request(tgbotapi.NewDeleteMessage(chatID, flowState.FileStatusMsgID)) //nolint:errcheck
+ flowState.FileStatusMsgID = 0
+ }
+
+ var sb strings.Builder
+ if len(flowState.Files) == 0 {
+ sb.WriteString("📎 Файлы не прикреплены\n\n")
+ sb.WriteString("Отправьте файл или нажмите «Отправить на согласование».")
+ } else {
+ sb.WriteString(fmt.Sprintf("📎 Прикреплённые файлы (%s):\n\n", utilscore.PluralFiles(len(flowState.Files))))
+ for i, f := range flowState.Files {
+ sb.WriteString(fmt.Sprintf("%d. %s\n", i+1, f.FileName))
+ }
+ sb.WriteString("\nМожете прикрепить ещё или отправить заявку.")
+ }
+
+ msg := tgbotapi.NewMessage(chatID, sb.String())
+ msg.ParseMode = "HTML"
+ msg.ReplyMarkup = keyboard.BuildFileInputKeyboard(flowState.TopicCode, flowState.Files)
+
+ sent, err := bot.Send(msg)
+ if err != nil {
+ logrus.Errorf("showFileStatus: Send err=%v", err)
+ return
+ }
+
+ // Сохраняем ID нового статусного сообщения
+ flowState.FileStatusMsgID = sent.MessageID
+ h.States.Set(ctx, telegramID, flowState) //nolint:errcheck
+}
diff --git a/service/telegram_service/handlers/approval/list.go b/service/telegram_service/handlers/approval/list.go
new file mode 100644
index 0000000..2efbbcc
--- /dev/null
+++ b/service/telegram_service/handlers/approval/list.go
@@ -0,0 +1,359 @@
+package approval
+
+import (
+ "bitrix_balancer_api/core/typescore"
+ "bitrix_balancer_api/core/utilscore"
+ "bitrix_balancer_api/telegram_service/keyboard"
+ "context"
+ "fmt"
+ tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
+ "github.com/sirupsen/logrus"
+)
+
+// HandleMyApprovals — список активных заявок инициатора
+func (h *Handler) HandleMyApprovals(bot *tgbotapi.BotAPI, chatID int64, telegramID int64) {
+ ctx := context.Background()
+
+ user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID)
+ if err != nil || user == nil || user.ID == nil {
+ logrus.Warnf("HandleMyApprovals: user not found telegramID=%d", telegramID)
+ return
+ }
+
+ approvals, err := h.ipc.Database.Approval.GetActiveApprovalsByInitiatorDB(ctx, *user.ID)
+ if err != nil {
+ logrus.Errorf("HandleMyApprovals: GetActiveApprovalsByInitiatorDB err=%v", err)
+ sendText(bot, chatID, "Ошибка при получении списка заявок.")
+ return
+ }
+
+ if len(approvals) == 0 {
+ sendText(bot, chatID, "📂 У вас нет активных заявок.")
+ return
+ }
+
+ sendText(bot, chatID, fmt.Sprintf("📂 Ваши активные заявки (%d):", len(approvals)))
+
+ for _, a := range approvals {
+ h.sendApprovalCard(bot, chatID, a, false)
+ }
+}
+
+// HandleIncomingApprovals — список заявок ожидающих действия согласующего
+func (h *Handler) HandleIncomingApprovals(bot *tgbotapi.BotAPI, chatID int64, telegramID int64) {
+ ctx := context.Background()
+
+ user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID)
+ if err != nil || user == nil || user.ID == nil {
+ return
+ }
+
+ // Основные согласования
+ steps, _, err := h.ipc.Database.ApprovalStep.GetApprovalStepsListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.ApprovalStep{
+ ApproverID: user.ID,
+ Status: utilscore.PointerToString("pending"),
+ },
+ })
+ if err != nil {
+ logrus.Errorf("HandleIncomingApprovals: GetApprovalStepsListDB err=%v", err)
+ return
+ }
+
+ // Дополнительные согласования
+ additionalApprovers, _, err := h.ipc.Database.ApprovalAdditionalApprover.GetApprovalAdditionalApproversListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.ApprovalAdditionalApprover{
+ ApproverID: user.ID,
+ Status: utilscore.PointerToString("pending"),
+ },
+ })
+ if err != nil {
+ logrus.Warnf("HandleIncomingApprovals: GetPendingAdditionalApprovalsByApproverDB err=%v", err)
+ }
+
+ totalCount := len(steps) + len(additionalApprovers)
+ if totalCount == 0 {
+ sendText(bot, chatID, "📭 Нет заявок для согласования.")
+ return
+ }
+
+ sendText(bot, chatID, fmt.Sprintf("📬 Входящие согласования (%d):", totalCount))
+
+ // Отправляем основные согласования
+ for _, step := range steps {
+ if step.ApprovalID == nil {
+ continue
+ }
+ approval, _ := h.ipc.Database.Approval.GetApprovalByIDDB(ctx, *step.ApprovalID)
+ if approval == nil {
+ continue
+ }
+
+ // Проверяем добавленных согласующих
+ addedApprovers, _, _ := h.ipc.Database.ApprovalAdditionalApprover.GetApprovalAdditionalApproversListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.ApprovalAdditionalApprover{
+ ApprovalID: step.ApprovalID,
+ },
+ })
+ h.sendApprovalCard(bot, chatID, approval, true, addedApprovers)
+ }
+
+ // Отправляем дополнительные согласования
+ for _, aa := range additionalApprovers {
+ if aa.ApprovalID == nil {
+ continue
+ }
+ approval, _ := h.ipc.Database.Approval.GetApprovalByIDDB(ctx, *aa.ApprovalID)
+ if approval == nil {
+ continue
+ }
+ h.sendAdditionalApprovalCard(bot, chatID, approval, aa)
+ }
+}
+
+// sendApprovalCard отправляет карточку одной заявки.
+// withDecision=true — добавляет кнопки Да/Нет для согласующего.
+func (h *Handler) sendApprovalCard(bot *tgbotapi.BotAPI, chatID int64, approval *typescore.Approval, withButtons bool, addedApprovers ...[]*typescore.ApprovalAdditionalApprover) {
+ ctx := context.Background()
+
+ if approval.ID == nil {
+ return
+ }
+
+ initiatorName := "—"
+ if approval.InitiatorID != nil {
+ initiator, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *approval.InitiatorID)
+ if initiator != nil && initiator.FullName != nil {
+ initiatorName = *initiator.FullName
+ }
+ }
+
+ topicName := "—"
+ if approval.TopicID != nil {
+ topic, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *approval.TopicID)
+ if topic != nil && topic.Name != nil {
+ topicName = *topic.Name
+ }
+ }
+
+ content := "—"
+ if approval.Content != nil {
+ content = *approval.Content
+ }
+
+ createdAt := "—"
+ if approval.CreatedAt != nil {
+ createdAt = approval.CreatedAt.Format("02.01.2006 15:04")
+ }
+
+ statusEmoji := "⏳"
+ statusText := "ожидает"
+ if approval.Status != nil {
+ switch *approval.Status {
+ case "approved":
+ statusEmoji = "✅"
+ statusText = "согласовано"
+ case "rejected":
+ statusEmoji = "❌"
+ statusText = "отклонено"
+ case "revoked":
+ statusEmoji = "↩️"
+ statusText = "отозвано"
+ }
+ }
+
+ text := fmt.Sprintf(
+ "📄 Заявка #%d %s %s\n\n"+
+ "👤 Инициатор: %s\n"+
+ "📋 Тема: %s\n"+
+ "📝 Текст: %s\n"+
+ "📅 Создана: %s",
+ *approval.ID, statusEmoji, statusText, initiatorName, topicName, content, createdAt,
+ )
+
+ if len(addedApprovers) > 0 && len(addedApprovers[0]) > 0 {
+ text += "\n\n➕ Добавлены согласующие:"
+ for _, aa := range addedApprovers[0] {
+ if aa.ApproverID != nil {
+ approver, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *aa.ApproverID)
+ if approver != nil && approver.FullName != nil {
+ text += fmt.Sprintf("\n• %s", *approver.FullName)
+ }
+ }
+ }
+ }
+
+ msg := tgbotapi.NewMessage(chatID, text)
+ msg.ParseMode = "HTML"
+
+ if withButtons && approval.Status != nil && *approval.Status == "pending" {
+ // Для согласующих - кнопки Да/Нет + Стадии
+ msg.ReplyMarkup = keyboard.BuildApproverDecision(*approval.ID)
+ } else if approval.Status != nil && (*approval.Status == "pending" || *approval.Status == "approved") {
+ // Для инициатора - кнопка Отозвать + Стадии
+ msg.ReplyMarkup = keyboard.BuildRevokeButton(*approval.ID)
+ }
+
+ bot.Send(msg) //nolint:errcheck
+}
+
+// HandleApprovalStages показывает все стадии согласования заявки
+func (h *Handler) HandleApprovalStages(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, approvalID uint64) {
+ ctx := context.Background()
+ chatID := cq.Message.Chat.ID
+
+ bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck
+
+ approval, err := h.ipc.Database.Approval.GetApprovalByIDDB(ctx, approvalID)
+ if err != nil || approval == nil {
+ sendText(bot, chatID, "⚠️ Заявка не найдена.")
+ return
+ }
+
+ // Получаем все шаги заявки
+ steps, _, err := h.ipc.Database.ApprovalStep.GetApprovalStepsListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.ApprovalStep{
+ ApprovalID: &approvalID,
+ },
+ })
+ if err != nil || len(steps) == 0 {
+ sendText(bot, chatID, "⚠️ Нет информации о стадиях согласования.")
+ return
+ }
+
+ // Сортируем по порядку
+ sortedSteps := make([]*typescore.ApprovalStep, len(steps))
+ copy(sortedSteps, steps)
+ for i := 0; i < len(sortedSteps)-1; i++ {
+ for j := i + 1; j < len(sortedSteps); j++ {
+ if sortedSteps[i].StepOrder != nil && sortedSteps[j].StepOrder != nil && *sortedSteps[i].StepOrder > *sortedSteps[j].StepOrder {
+ sortedSteps[i], sortedSteps[j] = sortedSteps[j], sortedSteps[i]
+ }
+ }
+ }
+
+ topicName := "—"
+ if approval.TopicID != nil {
+ if t, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *approval.TopicID); t != nil && t.Name != nil {
+ topicName = *t.Name
+ }
+ }
+
+ content := "—"
+ if approval.Content != nil {
+ content = *approval.Content
+ }
+
+ text := fmt.Sprintf(
+ "📊 Стадии согласования заявки #%d\n\n"+
+ "📋 Тема: %s\n"+
+ "📝 Текст: %s\n\n"+
+ "Этапы согласования:\n",
+ approvalID, topicName, content,
+ )
+
+ for i, step := range sortedSteps {
+ stepNum := i + 1
+
+ approverName := "—"
+ if step.ApproverNameSnapshot != nil {
+ approverName = *step.ApproverNameSnapshot
+ } else if step.ApproverID != nil {
+ approver, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *step.ApproverID)
+ if approver != nil && approver.FullName != nil {
+ approverName = *approver.FullName
+ }
+ }
+
+ statusEmoji := ""
+ statusText := ""
+ timeInfo := ""
+
+ if step.Status != nil {
+ switch *step.Status {
+ case "approved":
+ statusEmoji = "✅"
+ statusText = "Согласовано"
+ if step.ActedAt != nil {
+ timeInfo = fmt.Sprintf(" (%s)", step.ActedAt.Format("02.01 15:04"))
+ }
+ case "rejected":
+ statusEmoji = "❌"
+ statusText = "Отклонено"
+ if step.ActedAt != nil {
+ timeInfo = fmt.Sprintf(" (%s)", step.ActedAt.Format("02.01 15:04"))
+ }
+ if step.Comment != nil && *step.Comment != "" {
+ timeInfo += fmt.Sprintf("\n 💬 %s", *step.Comment)
+ }
+ case "pending":
+ statusEmoji = "⏳"
+ statusText = "Ожидает решения"
+ default:
+ statusEmoji = "⏸"
+ statusText = "Не начато"
+ }
+ }
+
+ text += fmt.Sprintf(
+ "\n%d. %s %s\n %s%s\n",
+ stepNum, statusEmoji, approverName, statusText, timeInfo,
+ )
+ }
+
+ // Проверяем дополнительных согласующих
+ additionalApprovers, _, _ := h.ipc.Database.ApprovalAdditionalApprover.GetApprovalAdditionalApproversListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.ApprovalAdditionalApprover{
+ ApprovalID: &approvalID,
+ },
+ })
+
+ if len(additionalApprovers) > 0 {
+ text += "\n➕ Дополнительные согласующие:\n"
+ for _, aa := range additionalApprovers {
+ approverName := "—"
+ if aa.ApproverID != nil {
+ approver, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *aa.ApproverID)
+ if approver != nil && approver.FullName != nil {
+ approverName = *approver.FullName
+ }
+ }
+
+ statusEmoji := ""
+ statusText := ""
+ timeInfo := ""
+
+ if aa.Status != nil {
+ switch *aa.Status {
+ case "approved":
+ statusEmoji = "✅"
+ statusText = "Согласовано"
+ if aa.ActedAt != nil {
+ timeInfo = fmt.Sprintf(" (%s)", aa.ActedAt.Format("02.01 15:04"))
+ }
+ case "rejected":
+ statusEmoji = "❌"
+ statusText = "Отклонено"
+ if aa.ActedAt != nil {
+ timeInfo = fmt.Sprintf(" (%s)", aa.ActedAt.Format("02.01 15:04"))
+ }
+ if aa.Comment != nil && *aa.Comment != "" {
+ timeInfo += fmt.Sprintf("\n 💬 %s", *aa.Comment)
+ }
+ case "pending":
+ statusEmoji = "⏳"
+ statusText = "Ожидает решения"
+ }
+ }
+
+ text += fmt.Sprintf(
+ "\n• %s %s\n %s%s\n",
+ statusEmoji, approverName, statusText, timeInfo,
+ )
+ }
+ }
+
+ msg := tgbotapi.NewMessage(chatID, text)
+ msg.ParseMode = "HTML"
+ bot.Send(msg) //nolint:errcheck
+}
diff --git a/service/telegram_service/handlers/approval/navigation.go b/service/telegram_service/handlers/approval/navigation.go
new file mode 100644
index 0000000..f7d93ca
--- /dev/null
+++ b/service/telegram_service/handlers/approval/navigation.go
@@ -0,0 +1,175 @@
+package approval
+
+import (
+ "bitrix_balancer_api/core/typescore"
+ "bitrix_balancer_api/telegram_service/keyboard"
+ "context"
+ "fmt"
+ tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
+ "github.com/sirupsen/logrus"
+ "time"
+)
+
+// HandleApprovalsSubmenu открывает подменю "Согласования"
+func (h *Handler) HandleApprovalsSubmenu(bot *tgbotapi.BotAPI, chatID int64, telegramID int64) {
+ ctx := context.Background()
+
+ // Проверяем, является ли пользователь наблюдателем
+ user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID)
+ if err != nil || user == nil || user.ID == nil {
+ logrus.Warnf("HandleApprovalsSubmenu: user not found telegramID=%d", telegramID)
+ return
+ }
+
+ isObserver, _ := h.ipc.Database.User.IsObserverDB(ctx, *user.ID)
+ isApprover, _ := h.ipc.Database.User.IsApproverDB(ctx, *user.ID)
+
+ // Сохраняем текущее меню в Redis для навигации "Назад"
+ menuKey := fmt.Sprintf("menu_state:%d", telegramID)
+ h.ipc.RedisClient.Set(ctx, menuKey, "approvals_submenu", 10*time.Minute) //nolint:errcheck
+
+ msg := tgbotapi.NewMessage(chatID, "📋 Согласования\n\nВыберите действие:")
+ msg.ParseMode = "HTML"
+ msg.ReplyMarkup = keyboard.ApprovalsSubmenuKeyboard(isObserver, isApprover)
+ bot.Send(msg) //nolint:errcheck
+}
+
+// HandleApprovalsListSubmenu открывает подменю "Список согласований"
+func (h *Handler) HandleApprovalsListSubmenu(bot *tgbotapi.BotAPI, chatID int64, telegramID int64) {
+ ctx := context.Background()
+
+ // Сохраняем текущее меню в Redis для навигации "Назад"
+ menuKey := fmt.Sprintf("menu_state:%d", telegramID)
+ h.ipc.RedisClient.Set(ctx, menuKey, "approvals_list_submenu", 10*time.Minute) //nolint:errcheck
+
+ msg := tgbotapi.NewMessage(chatID, "📋 Список согласований\n\nВыберите фильтр:")
+ msg.ParseMode = "HTML"
+ msg.ReplyMarkup = keyboard.ApprovalsListSubmenuKeyboard()
+ bot.Send(msg) //nolint:errcheck
+}
+
+// HandleMyApprovalsByStatus показывает заявки пользователя с фильтрацией по статусу
+func (h *Handler) HandleMyApprovalsByStatus(bot *tgbotapi.BotAPI, chatID int64, telegramID int64, status string) {
+ ctx := context.Background()
+
+ user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID)
+ if err != nil || user == nil || user.ID == nil {
+ logrus.Warnf("HandleMyApprovalsByStatus: user not found telegramID=%d", telegramID)
+ return
+ }
+
+ var statusText string
+ switch status {
+ case "all":
+ statusText = "Все заявки"
+ case "approved":
+ statusText = "✅ Принятые заявки"
+ case "rejected":
+ statusText = "❌ Отклонённые заявки"
+ case "pending":
+ statusText = "⏳ Ожидающие заявки"
+ default:
+ // По умолчанию показываем активные
+ statusText = "Активные заявки"
+ }
+
+ approvals, _, err := h.ipc.Database.Approval.GetApprovalsListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.Approval{
+ InitiatorID: user.ID,
+ Status: &status,
+ },
+ })
+ if err != nil {
+ logrus.Errorf("HandleMyApprovalsByStatus: GetApprovals err=%v", err)
+ sendText(bot, chatID, "Ошибка при получении списка заявок.")
+ return
+ }
+
+ if len(approvals) == 0 {
+ sendText(bot, chatID, fmt.Sprintf("📂 %s: не найдено.", statusText))
+ return
+ }
+
+ sendText(bot, chatID, fmt.Sprintf("📂 %s (%d):", statusText, len(approvals)))
+
+ for _, a := range approvals {
+ h.sendApprovalCard(bot, chatID, a, false)
+ }
+}
+
+// HandleBackNavigation обрабатывает навигацию "Назад"
+func (h *Handler) HandleBackNavigation(bot *tgbotapi.BotAPI, chatID int64, telegramID int64) {
+ ctx := context.Background()
+
+ // Получаем текущее состояние меню из Redis
+ menuKey := fmt.Sprintf("menu_state:%d", telegramID)
+ currentMenu, err := h.ipc.RedisClient.Get(ctx, menuKey)
+
+ user, userErr := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID)
+ if userErr != nil || user == nil || user.ID == nil {
+ logrus.Warnf("HandleBackNavigation: user not found telegramID=%d", telegramID)
+ return
+ }
+
+ isObserver, _ := h.ipc.Database.User.IsObserverDB(ctx, *user.ID)
+ isApprover, _ := h.ipc.Database.User.IsApproverDB(ctx, *user.ID)
+
+ if err != nil || currentMenu == "" {
+ // Если состояние не найдено, возвращаемся в главное меню
+ h.sendMainMenu(bot, chatID, telegramID, isObserver, isApprover)
+ return
+ }
+
+ switch currentMenu {
+ case "approvals_list_submenu":
+ // Из "Список согласований" возвращаемся в "Согласования"
+ h.ipc.RedisClient.Del(ctx, menuKey) //nolint:errcheck
+ h.HandleApprovalsSubmenu(bot, chatID, telegramID)
+
+ case "approvals_submenu":
+ // Из "Согласования" возвращаемся в главное меню
+ h.ipc.RedisClient.Del(ctx, menuKey) //nolint:errcheck
+ h.sendMainMenu(bot, chatID, telegramID, isObserver, isApprover)
+
+ default:
+ // По умолчанию возвращаемся в главное меню
+ h.ipc.RedisClient.Del(ctx, menuKey) //nolint:errcheck
+ h.sendMainMenu(bot, chatID, telegramID, isObserver, isApprover)
+ }
+}
+
+// sendMainMenu отправляет главное меню с соответствующей клавиатурой
+func (h *Handler) sendMainMenu(bot *tgbotapi.BotAPI, chatID int64, telegramID int64, isObserver bool, isApprover bool) {
+ ctx := context.Background()
+
+ user, _ := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID)
+ isExecutor := false
+ if user != nil && user.ID != nil {
+ isExecutor, _ = h.ipc.Database.User.IsExecutorDB(ctx, *user.ID)
+ }
+
+ var replyMarkup tgbotapi.ReplyKeyboardMarkup
+
+ if isApprover && isObserver && isExecutor {
+ replyMarkup = keyboard.ApproverObserverExecutorMenuKeyboard()
+ } else if isApprover && isExecutor {
+ replyMarkup = keyboard.ApproverExecutorMenuKeyboard()
+ } else if isObserver && isExecutor {
+ replyMarkup = keyboard.ObserverExecutorMenuKeyboard()
+ } else if isApprover && isObserver {
+ replyMarkup = keyboard.ApproverObserverMenuKeyboard()
+ } else if isApprover {
+ replyMarkup = keyboard.ApproverMenuKeyboard()
+ } else if isObserver {
+ replyMarkup = keyboard.ObserverMenuKeyboard()
+ } else if isExecutor {
+ replyMarkup = keyboard.ExecutorMenuKeyboard()
+ } else {
+ replyMarkup = keyboard.MainMenuKeyboard()
+ }
+
+ msg := tgbotapi.NewMessage(chatID, "🏠 Главное меню")
+ msg.ParseMode = "HTML"
+ msg.ReplyMarkup = replyMarkup
+ bot.Send(msg) //nolint:errcheck
+}
diff --git a/service/telegram_service/handlers/approval/notify.go b/service/telegram_service/handlers/approval/notify.go
new file mode 100644
index 0000000..0ad98a0
--- /dev/null
+++ b/service/telegram_service/handlers/approval/notify.go
@@ -0,0 +1,424 @@
+package approval
+
+import (
+ "bitrix_balancer_api/core/typescore"
+ "bitrix_balancer_api/telegram_service/approvalflow"
+ "bitrix_balancer_api/telegram_service/keyboard"
+ "bitrix_balancer_api/telegram_service/types"
+ "context"
+ "encoding/base64"
+ "fmt"
+ "github.com/sirupsen/logrus"
+
+ tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
+)
+
+type Notifier struct {
+ ipc *types.InternalProviderControl
+ topic approvalflow.Topic
+}
+
+func NewNotifier(ipc *types.InternalProviderControl, topic approvalflow.Topic) *Notifier {
+ return &Notifier{ipc: ipc, topic: topic}
+}
+
+func (h *Handler) notifyExecutor(
+ bot *tgbotapi.BotAPI,
+ ctx context.Context,
+ executor *typescore.User,
+ initiator *typescore.User,
+ approval *typescore.Approval,
+ collected map[string]string,
+ task *typescore.ApprovalTask,
+) {
+ if executor.TelegramID == nil || task.ID == nil {
+ return
+ }
+
+ initiatorName := "—"
+ if initiator.FullName != nil {
+ initiatorName = *initiator.FullName
+ }
+
+ topicName := "—"
+ if approval.TopicID != nil {
+ topic, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *approval.TopicID)
+ if topic != nil && topic.Name != nil {
+ topicName = *topic.Name
+ }
+ }
+
+ content := "—"
+ if approval.Content != nil {
+ content = *approval.Content
+ }
+
+ taskText := "—"
+ if task.TaskText != nil {
+ taskText = *task.TaskText
+ }
+
+ text := fmt.Sprintf(
+ "📋 Новая задача по заявке #%d\n\n"+
+ "👤 Инициатор: %s\n"+
+ "📋 Тема: %s\n"+
+ "📝 Текст заявки: %s\n\n"+
+ "🎯 Задача:\n%s",
+ *approval.ID, initiatorName, topicName, content, taskText,
+ )
+
+ msg := tgbotapi.NewMessage(*executor.TelegramID, text)
+ msg.ParseMode = "HTML"
+ msg.ReplyMarkup = keyboard.BuildExecutorTaskActions(*task.ID)
+ bot.Send(msg) //nolint:errcheck
+}
+
+// NotifyApprover отправляет уведомление согласующему с кнопками Да/Нет.
+func (n *Notifier) NotifyApprover(
+ bot *tgbotapi.BotAPI,
+ approver *typescore.User,
+ initiator *typescore.User,
+ approval *typescore.Approval,
+ collected map[string]string,
+) {
+ if approver.TelegramID == nil {
+ return
+ }
+
+ text := fmt.Sprintf("📬 Новая заявка #%d на согласование\n\n", *approval.ID) +
+ n.topic.FormatApproverMessage(initiator, collected)
+
+ if len(approval.Files) == 0 {
+ n.sendTextToApprover(bot, approver, approval, text)
+ return
+ }
+
+ n.sendFilesToRecipient(
+ bot,
+ *approver.TelegramID,
+ approval,
+ text,
+ keyboard.BuildApproverDecision(*approval.ID),
+ )
+}
+
+func (n *Notifier) sendTextToApprover(bot *tgbotapi.BotAPI, approver *typescore.User, approval *typescore.Approval, text string) {
+ msg := tgbotapi.NewMessage(*approver.TelegramID, text)
+ msg.ParseMode = "HTML"
+ msg.ReplyMarkup = keyboard.BuildApproverDecision(*approval.ID)
+ bot.Send(msg) //nolint:errcheck
+}
+
+// NotifyInitiatorApproved уведомляет инициатора об одобрении.
+func (n *Notifier) NotifyInitiatorApproved(
+ bot *tgbotapi.BotAPI,
+ initiator *typescore.User,
+ approval *typescore.Approval,
+ collected map[string]string,
+ lastApprover *typescore.User,
+) {
+ if initiator.TelegramID == nil {
+ logrus.Warnf("NotifyInitiatorApproved: TelegramID is nil")
+ return
+ }
+ logrus.Infof("NotifyInitiatorApproved: sending to telegramID=%d approvalID=%d", *initiator.TelegramID, *approval.ID)
+
+ approverName := "—"
+ if lastApprover != nil && lastApprover.FullName != nil {
+ approverName = *lastApprover.FullName
+ }
+
+ content := collected["content"]
+ if content == "" {
+ content = "—"
+ }
+
+ text := fmt.Sprintf(
+ "✅ Заявка #%d полностью согласована\n\n"+
+ "👤 Последний согласующий: %s\n"+
+ "📋 Тема: %s\n"+
+ "📝 Текст: %s",
+ *approval.ID, approverName, n.topic.Name(), content,
+ )
+
+ msg := tgbotapi.NewMessage(*initiator.TelegramID, text)
+ msg.ParseMode = "HTML"
+ msg.ReplyMarkup = keyboard.BuildRevokeButton(*approval.ID)
+ if _, err := bot.Send(msg); err != nil {
+ logrus.Errorf("NotifyInitiatorApproved: Send err=%v", err)
+ }
+}
+
+// NotifyInitiatorRejected уведомляет инициатора об отклонении.
+func (n *Notifier) NotifyInitiatorRejected(
+ bot *tgbotapi.BotAPI,
+ initiator *typescore.User,
+ approver *typescore.User,
+ approval *typescore.Approval,
+ collected map[string]string,
+ comment string,
+) {
+ if initiator.TelegramID == nil {
+ return
+ }
+
+ approverName := "—"
+ if approver != nil && approver.FullName != nil {
+ approverName = *approver.FullName
+ }
+
+ content := collected["content"]
+ if content == "" {
+ content = "—"
+ }
+
+ text := fmt.Sprintf(
+ "❌ Заявка #%d отклонена\n\n"+
+ "👤 Согласующий: %s\n"+
+ "📋 Тема: %s\n"+
+ "📝 Текст: %s",
+ *approval.ID, approverName, n.topic.Name(), content,
+ )
+
+ if comment != "" {
+ text += fmt.Sprintf("\n💬 Причина: %s", comment)
+ }
+
+ msg := tgbotapi.NewMessage(*initiator.TelegramID, text)
+ msg.ParseMode = "HTML"
+ bot.Send(msg) //nolint:errcheck
+}
+
+// NotifyDirector уведомляет директора о финально согласованной заявке.
+func (n *Notifier) NotifyDirector(bot *tgbotapi.BotAPI, director *typescore.User, initiator *typescore.User, approval *typescore.Approval, collected map[string]string) {
+ if director.TelegramID == nil {
+ return
+ }
+ text := "📌 Финальное согласование\n\n" + n.topic.FormatApproverMessage(initiator, collected)
+ msg := tgbotapi.NewMessage(*director.TelegramID, text)
+ msg.ParseMode = "HTML"
+ msg.ReplyMarkup = keyboard.BuildRevokeButton(*approval.ID)
+ bot.Send(msg) //nolint:errcheck
+}
+
+// NotifyObserversNewApproval — новая заявка отправлена на согласование.
+func (n *Notifier) NotifyObserversNewApproval(
+ bot *tgbotapi.BotAPI,
+ observers []*typescore.User,
+ initiator *typescore.User,
+ approval *typescore.Approval,
+ collected map[string]string,
+) {
+ for _, obs := range observers {
+ if obs.TelegramID == nil {
+ continue
+ }
+
+ text := fmt.Sprintf("👁 Новая заявка #%d\n\n", *approval.ID) +
+ n.topic.FormatApproverMessage(initiator, collected)
+
+ if len(approval.Files) == 0 {
+ msg := tgbotapi.NewMessage(*obs.TelegramID, text)
+ msg.ParseMode = "HTML"
+ bot.Send(msg) //nolint:errcheck
+ continue
+ }
+
+ n.sendFilesToRecipient(bot, *obs.TelegramID, approval, text, nil) // без кнопок
+ }
+}
+
+// NotifyObserversDecision — кто, кому и что согласовал/отклонил.
+func (n *Notifier) NotifyObserversDecision(
+ bot *tgbotapi.BotAPI,
+ observers []*typescore.User,
+ approver *typescore.User,
+ initiator *typescore.User,
+ approval *typescore.Approval,
+ collected map[string]string,
+ approved bool,
+) {
+ approverName := "—"
+ if approver != nil && approver.FullName != nil {
+ approverName = *approver.FullName
+ }
+ initiatorName := "—"
+ if initiator != nil && initiator.FullName != nil {
+ initiatorName = *initiator.FullName
+ }
+ content := collected["content"]
+
+ action := "✅ согласовал(а)"
+ if !approved {
+ action = "❌ отклонил(а)"
+ }
+
+ text := fmt.Sprintf(
+ "👁 Решение по заявке #%d\n\n"+
+ "%s %s заявку %s\n"+
+ "📝 %s",
+ *approval.ID, approverName, action, initiatorName, content,
+ )
+
+ for _, obs := range observers {
+ if obs.TelegramID == nil {
+ continue
+ }
+ msg := tgbotapi.NewMessage(*obs.TelegramID, text)
+ msg.ParseMode = "HTML"
+ bot.Send(msg) //nolint:errcheck
+ }
+}
+
+// sendFilesToRecipient отправляет файлы из approval получателю.
+// Текст прикрепляется к первому файлу (caption), клавиатура — к последнему.
+// Если файл не декодируется — пропускается с логированием.
+func (n *Notifier) sendFilesToRecipient(
+ bot *tgbotapi.BotAPI,
+ chatID int64,
+ approval *typescore.Approval,
+ text string,
+ replyMarkup interface{},
+) {
+ // Декодируем все файлы заранее, чтобы не слать половину при ошибке
+ type decoded struct {
+ name string
+ bytes []byte
+ }
+
+ var validFiles []decoded
+ for _, f := range approval.Files {
+ if f.FileBase64 == nil || f.FileName == nil {
+ continue
+ }
+ data, err := base64.StdEncoding.DecodeString(*f.FileBase64)
+ if err != nil {
+ logrus.Errorf("sendFilesToRecipient: base64 decode file=%s err=%v", *f.FileName, err)
+ continue
+ }
+ validFiles = append(validFiles, decoded{name: *f.FileName, bytes: data})
+ }
+
+ if len(validFiles) == 0 {
+ // Все файлы битые — шлём хотя бы текст
+ msg := tgbotapi.NewMessage(chatID, text)
+ msg.ParseMode = "HTML"
+ if replyMarkup != nil {
+ msg.ReplyMarkup = replyMarkup
+ }
+ bot.Send(msg) //nolint:errcheck
+ return
+ }
+
+ for i, f := range validFiles {
+ doc := tgbotapi.NewDocument(chatID, tgbotapi.FileBytes{
+ Name: f.name,
+ Bytes: f.bytes,
+ })
+ doc.ParseMode = "HTML"
+
+ // Текст — только к первому файлу
+ if i == 0 {
+ doc.Caption = text
+ }
+ // Клавиатура — только к последнему файлу
+ if i == len(validFiles)-1 && replyMarkup != nil {
+ doc.ReplyMarkup = replyMarkup
+ }
+
+ if _, err := bot.Send(doc); err != nil {
+ logrus.Errorf("sendFilesToRecipient: Send file=%s err=%v", f.name, err)
+ }
+ }
+}
+
+func (h *Handler) sendDelegationAlreadyExists(bot *tgbotapi.BotAPI, chatID int64, existing *typescore.ApprovalDelegation, telegramID int64) {
+ ctx := context.Background()
+
+ scopeName := "—"
+ if existing.TopicID != nil {
+ topic, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *existing.TopicID)
+ if topic != nil && topic.Name != nil {
+ scopeName = *topic.Name
+ }
+ } else if existing.CategoryID != nil {
+ category, _ := h.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, *existing.CategoryID)
+ if category != nil && category.Name != nil {
+ scopeName = *category.Name + " (все права)"
+ }
+ }
+
+ delegateName := "—"
+ if existing.DelegateID != nil {
+ delegate, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *existing.DelegateID)
+ if delegate != nil && delegate.FullName != nil {
+ delegateName = *delegate.FullName
+ }
+ }
+
+ validUntil := "—"
+ if existing.ValidUntil != nil {
+ validUntil = existing.ValidUntil.Format("02.01.2006 15:04")
+ }
+
+ msg := tgbotapi.NewMessage(chatID, fmt.Sprintf(
+ "⚠️ Делегирование уже существует\n\n"+
+ "📋 Тема: %s\n"+
+ "👤 Делегат: %s\n"+
+ "📅 Действует до: %s",
+ scopeName, delegateName, validUntil,
+ ))
+ msg.ParseMode = "HTML"
+ bot.Send(msg) //nolint:errcheck
+ h.States.ClearDelegation(ctx, telegramID) //nolint:errcheck
+}
+
+func (h *Handler) sendAdditionalApprovalCard(bot *tgbotapi.BotAPI, chatID int64, approval *typescore.Approval, additionalApprover *typescore.ApprovalAdditionalApprover) {
+ ctx := context.Background()
+
+ if approval.ID == nil {
+ return
+ }
+
+ initiatorName := "—"
+ if approval.InitiatorID != nil {
+ initiator, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *approval.InitiatorID)
+ if initiator != nil && initiator.FullName != nil {
+ initiatorName = *initiator.FullName
+ }
+ }
+
+ topicName := "—"
+ if approval.TopicID != nil {
+ topic, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *approval.TopicID)
+ if topic != nil && topic.Name != nil {
+ topicName = *topic.Name
+ }
+ }
+
+ content := "—"
+ if approval.Content != nil {
+ content = *approval.Content
+ }
+
+ addedByName := "—"
+ if additionalApprover.AddedByID != nil {
+ addedBy, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *additionalApprover.AddedByID)
+ if addedBy != nil && addedBy.FullName != nil {
+ addedByName = *addedBy.FullName
+ }
+ }
+
+ text := fmt.Sprintf(
+ "📄 Заявка #%d (добавлен: %s)\n\n"+
+ "👤 Инициатор: %s\n"+
+ "📋 Тема: %s\n"+
+ "📝 Текст: %s",
+ *approval.ID, addedByName, initiatorName, topicName, content,
+ )
+
+ msg := tgbotapi.NewMessage(chatID, text)
+ msg.ParseMode = "HTML"
+ msg.ReplyMarkup = keyboard.BuildApproverDecision(*approval.ID)
+ bot.Send(msg) //nolint:errcheck
+}
diff --git a/service/telegram_service/handlers/approval/registry.go b/service/telegram_service/handlers/approval/registry.go
new file mode 100644
index 0000000..5f8e0d8
--- /dev/null
+++ b/service/telegram_service/handlers/approval/registry.go
@@ -0,0 +1,81 @@
+package approval
+
+import (
+ "bitrix_balancer_api/telegram_service/approvalflow"
+ "bitrix_balancer_api/telegram_service/handlers/approval/topics/free"
+ sickleave "bitrix_balancer_api/telegram_service/handlers/approval/topics/sick_leave"
+ timeoff "bitrix_balancer_api/telegram_service/handlers/approval/topics/time_off"
+ "bitrix_balancer_api/telegram_service/handlers/approval/topics/vacation"
+ "fmt"
+)
+
+type Registry struct {
+ topics map[string]approvalflow.Topic
+ order []string
+}
+
+func NewRegistry() *Registry {
+ r := &Registry{topics: make(map[string]approvalflow.Topic)}
+ r.registerAll()
+ return r
+}
+
+func (r *Registry) registerAll() {
+ // Структурированные темы
+ r.register(timeoff.NewTimeOffTopic())
+ r.register(vacation.NewVacationTopic())
+ r.register(sickleave.NewSickLeaveTopic())
+
+ // Свободные темы — порядок соответствует миграции
+ freeTopics := []struct{ code, name string }{
+ {"alphapet_delivery", "Альфапэт доставка"},
+ {"v_shipments", "В. Отгрузки"},
+ {"non_budget_expenses", "Внебюджетные расходы"},
+ {"non_budget_expenses_pet_line", "Внебюджетные расходы ПЭТ Лайн"},
+ {"returns", "Возвраты"},
+ {"new_clients", "Заведение новых клиентов"},
+ {"orders_krasnodar", "Заказы. Краснодар"},
+ {"orders_crimea", "Заказы. Крым"},
+ {"manager_expenses", "Менеджерские расходы"},
+ {"shipments_soh", "Отгрузки на СОХ"},
+ {"shipments", "Отгрузки"},
+ {"nonstandard_contract", "Нестандартные условия договора поставки"},
+ {"expenses_alphapet", "Расходы АЛЬФАПЭТ"},
+ {"expenses_warehouse_gvardeysk", "Расходы склад Гвардейское"},
+ {"ruspet_delivery", "РУСПЭТ ДОСТАВКА + НАПРЯМУЮ К КЛИЕНТУ"},
+ {"vacancies", "Вакансии"},
+ {"vacation_approval_sales", "Согласование отпусков Отдел продаж"},
+ {"approval_general", "Согласование отпусков/отгулов/больничных"},
+ {"ps_belarus", "ПС Беларусь"},
+ {"ps_krasnodar", "ПС Краснодар"},
+ {"ps_crimea", "ПС Крым"},
+ {"delivery_rates_ap", "Ставки доставки АП"},
+ {"payments_cashless", "Утверждение оплат безнал"},
+ {"rates_logistics", "Утверждение ставок Логистика"},
+ {"freelancers_approval", "Утверждение фрилансеров"},
+ }
+ for _, t := range freeTopics {
+ r.register(free.NewFreeTopic(t.code, t.name))
+ }
+}
+
+func (r *Registry) register(t approvalflow.Topic) {
+ r.topics[t.Code()] = t
+ r.order = append(r.order, t.Code())
+}
+
+func (r *Registry) Get(code string) (approvalflow.Topic, error) {
+ t, ok := r.topics[code]
+ if !ok {
+ return nil, fmt.Errorf("unknown topic code: %s", code)
+ }
+ return t, nil
+}
+
+func (r *Registry) All() []approvalflow.Topic {
+ result := make([]approvalflow.Topic, 0, len(r.order))
+ for _, code := range r.order {
+ result = append(result, r.topics[code])
+ }
+ return result
+}
diff --git a/service/telegram_service/handlers/approval/topics/free/topic.go b/service/telegram_service/handlers/approval/topics/free/topic.go
new file mode 100644
index 0000000..3d7b73c
--- /dev/null
+++ b/service/telegram_service/handlers/approval/topics/free/topic.go
@@ -0,0 +1,52 @@
+package free
+
+import (
+ "bitrix_balancer_api/core/typescore"
+ "bitrix_balancer_api/telegram_service/approvalflow"
+ "fmt"
+)
+
+// FreeTopic — тема с единственным шагом: свободный текстовый ввод.
+// Подходит для всех тем без разветвлённой логики.
+type FreeTopic struct {
+ code string
+ name string
+}
+
+func NewFreeTopic(code, name string) *FreeTopic {
+ return &FreeTopic{code: code, name: name}
+}
+
+func (o *FreeTopic) Code() string { return o.code }
+func (o *FreeTopic) Name() string { return o.name }
+
+func (o *FreeTopic) BuildTree() *approvalflow.FlowNode {
+ return &approvalflow.FlowNode{
+ Key: o.code,
+ Label: o.name,
+ Children: []*approvalflow.FlowNode{
+ {
+ Key: o.code + "_input",
+ IsInput: true,
+ InputKey: "content",
+ InputHint: "Напишите текст согласования",
+ },
+ },
+ }
+}
+
+func (o *FreeTopic) TopicCodeFromCollected(_ map[string]string) (string, error) {
+ return o.code, nil
+}
+
+func (o *FreeTopic) FormatApproverMessage(initiator *typescore.User, collected map[string]string) string {
+ name := ""
+ if initiator.FullName != nil {
+ name = *initiator.FullName
+ }
+ return fmt.Sprintf(
+ "📋 %s\n\n"+
+ "%s:\n%s",
+ o.name, name, collected["content"],
+ )
+}
diff --git a/service/telegram_service/handlers/approval/topics/sick_leave/topic.go b/service/telegram_service/handlers/approval/topics/sick_leave/topic.go
new file mode 100644
index 0000000..ab81c27
--- /dev/null
+++ b/service/telegram_service/handlers/approval/topics/sick_leave/topic.go
@@ -0,0 +1,118 @@
+package sickleave
+
+import (
+ "bitrix_balancer_api/core/typescore"
+ "bitrix_balancer_api/telegram_service/approvalflow"
+ "fmt"
+)
+
+type SickLeaveTopic struct{}
+
+func NewSickLeaveTopic() *SickLeaveTopic { return &SickLeaveTopic{} }
+
+func (o *SickLeaveTopic) Code() string { return "sickleave" }
+func (o *SickLeaveTopic) Name() string { return "Больничный" }
+
+// BuildTree: длительность → тип (за свой счёт / в счёт отпуска / официальный больничный).
+// Официальный больничный требует прикрепить справку.
+func (o *SickLeaveTopic) BuildTree() *approvalflow.FlowNode {
+ return &approvalflow.FlowNode{
+ Key: "sickleave",
+ Label: "Больничный",
+ Children: []*approvalflow.FlowNode{
+ o.buildDuration("single_day", "На один день",
+ "22.02.2022"),
+ o.buildDuration("date_range", "Диапазон дат",
+ "22.02.2022 - 25.02.2022"),
+ o.buildDuration("multi_day", "Несколько дней",
+ "22.02.2022, 24.02.2022, 26.02.2022"),
+ },
+ }
+}
+
+func (o *SickLeaveTopic) buildDuration(durKey, durLabel, hint string) *approvalflow.FlowNode {
+ return &approvalflow.FlowNode{
+ Key: durKey, Label: durLabel,
+ DataKey: "duration_type", DataValue: durKey,
+ Children: []*approvalflow.FlowNode{
+ {
+ Key: durKey + "_own", Label: "За свой счёт",
+ DataKey: "payment_type", DataValue: "own_expense",
+ Children: []*approvalflow.FlowNode{
+ {
+ Key: durKey + "_own_input",
+ IsInput: true,
+ InputKey: "content",
+ InputHint: hint,
+ DataKey: "time_type", DataValue: "full_day",
+ },
+ },
+ },
+ {
+ Key: durKey + "_vac", Label: "В счёт отпуска",
+ DataKey: "payment_type", DataValue: "vacation_account",
+ Children: []*approvalflow.FlowNode{
+ {
+ Key: durKey + "_vac_input",
+ IsInput: true,
+ InputKey: "content",
+ InputHint: hint,
+ DataKey: "time_type", DataValue: "full_day",
+ },
+ },
+ },
+ {
+ // Официальный больничный: сначала вводят даты, потом прикрепляют справку
+ Key: durKey + "_official", Label: "Официальный больничный",
+ DataKey: "payment_type", DataValue: "official",
+ Children: []*approvalflow.FlowNode{
+ {
+ Key: durKey + "_official_input",
+ IsInput: true,
+ InputKey: "content",
+ InputHint: hint,
+ DataKey: "time_type", DataValue: "full_day",
+ },
+ },
+ },
+ },
+ }
+}
+
+func (o *SickLeaveTopic) TopicCodeFromCollected(collected map[string]string) (string, error) {
+ dur := collected["duration_type"]
+ payment := collected["payment_type"]
+ if dur == "" || payment == "" {
+ return "", fmt.Errorf("неполные данные для определения темы: %v", collected)
+ }
+ return fmt.Sprintf("sickleave_%s_full_day_%s", dur, payment), nil
+}
+
+func (o *SickLeaveTopic) FormatApproverMessage(initiator *typescore.User, collected map[string]string) string {
+ name := ""
+ if initiator.FullName != nil {
+ name = *initiator.FullName
+ }
+
+ var paymentLabel string
+ switch collected["payment_type"] {
+ case "vacation_account":
+ paymentLabel = "в счёт ежегодного отпуска"
+ case "official":
+ paymentLabel = "официальный больничный (со справкой)"
+ default:
+ paymentLabel = "за свой счёт"
+ }
+
+ msg := fmt.Sprintf(
+ "📋 Тип: Больничный\n\n"+
+ "%s: прошу согласовать больничный\n"+
+ "%s\n"+
+ "%s",
+ name, collected["content"], paymentLabel,
+ )
+ if collected["file_name"] != "" {
+ msg += fmt.Sprintf("\n📎 Справка: %s", collected["file_name"])
+ }
+ return msg
+}
diff --git a/service/telegram_service/handlers/approval/topics/time_off/time_off.go b/service/telegram_service/handlers/approval/topics/time_off/time_off.go
new file mode 100644
index 0000000..a935726
--- /dev/null
+++ b/service/telegram_service/handlers/approval/topics/time_off/time_off.go
@@ -0,0 +1,126 @@
+package timeoff
+
+import (
+ "bitrix_balancer_api/core/typescore"
+ "bitrix_balancer_api/telegram_service/approvalflow"
+ "fmt"
+)
+
+type TimeOffTopic struct{}
+
+func NewTimeOffTopic() *TimeOffTopic { return &TimeOffTopic{} }
+
+func (o *TimeOffTopic) Code() string { return "timeoff" }
+func (o *TimeOffTopic) Name() string { return "Отгул" }
+
+// BuildTree строит дерево навигации согласно бизнес-логике:
+// длительность → тип дня → тип оплаты (только для весь день) → ввод
+func (o *TimeOffTopic) BuildTree() *approvalflow.FlowNode {
+ return &approvalflow.FlowNode{
+ Key: "timeoff",
+ Label: "Отгул",
+ Children: []*approvalflow.FlowNode{
+ o.buildDuration("single_day", "На один день",
+ "22.02.2022",
+ "22.02.2022 с 16:00 по 18:00"),
+ o.buildDuration("date_range", "Диапазон дат",
+ "22.02.2022 - 25.02.2022",
+ "22.02.2022 - 25.02.2022 с 16:00 по 18:00"),
+ o.buildDuration("multi_day", "Несколько дней",
+ "22.02.2022, 24.02.2022, 26.02.2022",
+ "22.02.2022 с 10:00 по 14:00, 24.02.2022 с 09:00 по 12:00"),
+ },
+ }
+}
+
+// buildDuration — общий строитель поддерева для каждого типа длительности.
+// fullHint и partialHint — шаблоны ввода для каждой ветки.
+func (o *TimeOffTopic) buildDuration(durKey, durLabel, fullHint, partialHint string) *approvalflow.FlowNode {
+ return &approvalflow.FlowNode{
+ Key: durKey, Label: durLabel,
+ DataKey: "duration_type", DataValue: durKey,
+ Children: []*approvalflow.FlowNode{
+ {
+ // Весь день → выбор типа оплаты
+ Key: durKey + "_full", Label: "Весь день",
+ DataKey: "time_type", DataValue: "full_day",
+ Children: []*approvalflow.FlowNode{
+ {
+ Key: durKey + "_full_own", Label: "За свой счёт",
+ DataKey: "payment_type", DataValue: "own_expense",
+ Children: []*approvalflow.FlowNode{
+ {
+ Key: durKey + "_full_own_input",
+ IsInput: true,
+ InputKey: "content",
+ InputHint: fullHint,
+ },
+ },
+ },
+ {
+ Key: durKey + "_full_vac", Label: "В счёт отпуска",
+ DataKey: "payment_type", DataValue: "vacation_account",
+ Children: []*approvalflow.FlowNode{
+ {
+ Key: durKey + "_full_vac_input",
+ IsInput: true,
+ InputKey: "content",
+ InputHint: fullHint,
+ },
+ },
+ },
+ },
+ },
+ {
+ // Частично → сразу ввод (оплата только за свой счёт)
+ Key: durKey + "_partial", Label: "Частично",
+ DataKey: "time_type", DataValue: "partial",
+ Children: []*approvalflow.FlowNode{
+ // payment_type проставляем автоматически, узел ввода сразу
+ {
+ Key: durKey + "_partial_input",
+ IsInput: true,
+ InputKey: "content",
+ InputHint: partialHint,
+ DataKey: "payment_type", DataValue: "own_expense", // авто
+ },
+ },
+ },
+ },
+ }
+}
+
+// TopicCodeFromCollected возвращает code конкретной записи approvalflow_topics.
+// Формат: timeoff_{duration_type}_{time_type}_{payment_type}
+func (o *TimeOffTopic) TopicCodeFromCollected(collected map[string]string) (string, error) {
+ dur := collected["duration_type"]
+ timeType := collected["time_type"]
+ payment := collected["payment_type"]
+ if dur == "" || timeType == "" || payment == "" {
+ return "", fmt.Errorf("неполные данные для определения темы: %v", collected)
+ }
+ return fmt.Sprintf("timeoff_%s_%s_%s", dur, timeType, payment), nil
+}
+
+// FormatApproverMessage форматирует сообщение для согласующего.
+func (o *TimeOffTopic) FormatApproverMessage(initiator *typescore.User, collected map[string]string) string {
+ name := ""
+ if initiator.FullName != nil {
+ name = *initiator.FullName
+ }
+
+ paymentLabel := "за свой счёт"
+ if collected["payment_type"] == "vacation_account" {
+ paymentLabel = "в счёт ежегодного отпуска"
+ }
+
+ return fmt.Sprintf(
+ "📋 Тип: Отгул\n\n"+
+ "%s: прошу согласовать отгул\n"+
+ "%s\n"+
+ "%s",
+ name,
+ collected["content"],
+ paymentLabel,
+ )
+}
diff --git a/service/telegram_service/handlers/approval/topics/vacation/topic.go b/service/telegram_service/handlers/approval/topics/vacation/topic.go
new file mode 100644
index 0000000..21b926a
--- /dev/null
+++ b/service/telegram_service/handlers/approval/topics/vacation/topic.go
@@ -0,0 +1,91 @@
+package vacation
+
+import (
+ "bitrix_balancer_api/core/typescore"
+ "bitrix_balancer_api/telegram_service/approvalflow"
+ "fmt"
+)
+
+type VacationTopic struct{}
+
+func NewVacationTopic() *VacationTopic { return &VacationTopic{} }
+
+func (o *VacationTopic) Code() string { return "vacation" }
+func (o *VacationTopic) Name() string { return "Отпуск" }
+
+// BuildTree: длительность → тип оплаты → ввод.
+// Время всегда "весь день", частичный вариант недоступен.
+func (o *VacationTopic) BuildTree() *approvalflow.FlowNode {
+ return &approvalflow.FlowNode{
+ Key: "vacation",
+ Label: "Отпуск",
+ Children: []*approvalflow.FlowNode{
+ o.buildDuration("single_day", "На один день", "22.02.2022"),
+ o.buildDuration("date_range", "Диапазон дат", "22.02.2022 - 25.02.2022"),
+ o.buildDuration("multi_day", "Несколько дней", "22.02.2022, 24.02.2022, 26.02.2022"),
+ },
+ }
+}
+
+func (o *VacationTopic) buildDuration(durKey, durLabel, hint string) *approvalflow.FlowNode {
+ return &approvalflow.FlowNode{
+ Key: durKey, Label: durLabel,
+ DataKey: "duration_type", DataValue: durKey,
+ // time_type всегда full_day — проставляем сразу, не показываем выбор
+ Children: []*approvalflow.FlowNode{
+ {
+ Key: durKey + "_own", Label: "За свой счёт",
+ DataKey: "payment_type", DataValue: "own_expense",
+ Children: []*approvalflow.FlowNode{
+ {
+ Key: durKey + "_own_input",
+ IsInput: true,
+ InputKey: "content",
+ InputHint: hint,
+ DataKey: "time_type", DataValue: "full_day",
+ },
+ },
+ },
+ {
+ Key: durKey + "_vac", Label: "В счёт отпуска",
+ DataKey: "payment_type", DataValue: "vacation_account",
+ Children: []*approvalflow.FlowNode{
+ {
+ Key: durKey + "_vac_input",
+ IsInput: true,
+ InputKey: "content",
+ InputHint: hint,
+ DataKey: "time_type", DataValue: "full_day",
+ },
+ },
+ },
+ },
+ }
+}
+
+func (o *VacationTopic) TopicCodeFromCollected(collected map[string]string) (string, error) {
+ dur := collected["duration_type"]
+ payment := collected["payment_type"]
+ if dur == "" || payment == "" {
+ return "", fmt.Errorf("неполные данные для определения темы: %v", collected)
+ }
+ return fmt.Sprintf("vacation_%s_full_day_%s", dur, payment), nil
+}
+
+func (o *VacationTopic) FormatApproverMessage(initiator *typescore.User, collected map[string]string) string {
+ name := ""
+ if initiator.FullName != nil {
+ name = *initiator.FullName
+ }
+ paymentLabel := "за свой счёт"
+ if collected["payment_type"] == "vacation_account" {
+ paymentLabel = "в счёт ежегодного отпуска"
+ }
+ return fmt.Sprintf(
+ "📋 Тип: Отпуск\n\n"+
+ "%s: прошу согласовать отпуск\n"+
+ "%s\n"+
+ "%s",
+ name, collected["content"], paymentLabel,
+ )
+}
diff --git a/service/telegram_service/handlers/faq/handler.go b/service/telegram_service/handlers/faq/handler.go
new file mode 100644
index 0000000..7b4b082
--- /dev/null
+++ b/service/telegram_service/handlers/faq/handler.go
@@ -0,0 +1,98 @@
+package faq
+
+import (
+ "bitrix_balancer_api/core/typescore"
+ "bitrix_balancer_api/core/utilscore"
+ "bitrix_balancer_api/telegram_service/keyboard"
+ "bitrix_balancer_api/telegram_service/types"
+ "context"
+ "fmt"
+ tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
+ "github.com/sirupsen/logrus"
+)
+
+type HandlerFAQ struct {
+ ipc *types.InternalProviderControl
+}
+
+func NewHandler(ipc *types.InternalProviderControl) *HandlerFAQ {
+ return &HandlerFAQ{
+ ipc: ipc,
+ }
+}
+
+// Handle — точка входа для команды /start.
+// Если пользователь уже зарегистрирован — приветствуем.
+// Если нет — запускаем флоу регистрации.
+func (h *HandlerFAQ) Handle(bot *tgbotapi.BotAPI, msg *tgbotapi.Message) {
+ ctx := context.Background()
+
+ existing, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, msg.From.ID)
+ if err != nil {
+ logrus.Error("start.Handle: GetUserByTelegramIDDB: ", err)
+ return
+ }
+
+ // Пользователь уже есть — показываем главное меню или сообщение об ожидании отдела
+ if existing != nil {
+ h.sendHowToCreate(bot, msg.Chat.ID, msg.From.ID, existing)
+ return
+ }
+}
+
+func (h *HandlerFAQ) sendHowToCreate(bot *tgbotapi.BotAPI, chatID int64, telegramID int64, user *typescore.User) {
+ ctx := context.Background()
+ name := ""
+ if user.FullName != nil {
+ name = *user.FullName
+ }
+
+ if user.DepartmentID == nil {
+ utilscore.SendBotMessage(bot, chatID, fmt.Sprintf(
+ "👋 Здравствуйте, %s!\n\n"+
+ "Ожидайте назначения в отдел.\n"+
+ "Только по назначению в отдел вы сможете начать работу с системой согласований.", name,
+ ))
+ return
+ }
+
+ // Определяем клавиатуру по роли
+ replyMarkup := h.buildMenuKeyboard(ctx, user)
+
+ msg := tgbotapi.NewMessage(chatID, fmt.Sprintf(
+ "👋 Здравствуйте, %s!\n\n"+
+ "Данный раздел предназначен для ознакомления с порядком работы в системе согласований.\n\n"+
+ "В инструкции будет представлена информация о:\n"+
+ "• создании заявок\n"+
+ "• направлении заявок на согласование\n"+
+ "• отслеживании статуса заявок\n"+
+ "• обработке входящих задач\n\n"+
+ "📘 Инструкция находится в разработке и будет доступна в ближайшее время.\n"+
+ "По возникающим вопросам вы можете обратиться к администратору системы.",
+ name,
+ ))
+ msg.ParseMode = "HTML"
+ msg.ReplyMarkup = replyMarkup
+ bot.Send(msg) //nolint:errcheck
+}
+
+// buildMenuKeyboard возвращает клавиатуру в зависимости от роли пользователя
+func (h *HandlerFAQ) buildMenuKeyboard(ctx context.Context, user *typescore.User) tgbotapi.ReplyKeyboardMarkup {
+ if user.ID == nil {
+ return keyboard.MainMenuKeyboard()
+ }
+
+ isApprover, _ := h.ipc.Database.User.IsApproverDB(ctx, *user.ID)
+ isObserver, _ := h.ipc.Database.User.IsObserverDB(ctx, *user.ID)
+
+ switch {
+ case isApprover && isObserver:
+ return keyboard.ApproverObserverMenuKeyboard()
+ case isApprover:
+ return keyboard.ApproverMenuKeyboard()
+ case isObserver:
+ return keyboard.ObserverMenuKeyboard()
+ default:
+ return keyboard.MainMenuKeyboard()
+ }
+}
diff --git a/service/telegram_service/handlers/start/handler.go b/service/telegram_service/handlers/start/handler.go
new file mode 100644
index 0000000..304b4ba
--- /dev/null
+++ b/service/telegram_service/handlers/start/handler.go
@@ -0,0 +1,193 @@
+package start
+
+import (
+ "bitrix_balancer_api/core/typescore"
+ "bitrix_balancer_api/core/utilscore"
+ "bitrix_balancer_api/telegram_service/handlers/approval"
+ "bitrix_balancer_api/telegram_service/keyboard"
+ "bitrix_balancer_api/telegram_service/types"
+ "context"
+ "fmt"
+
+ tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
+ "github.com/sirupsen/logrus"
+)
+
+type Handler struct {
+ approvalHandler *approval.Handler
+ ipc *types.InternalProviderControl
+}
+
+func NewHandler(ipc *types.InternalProviderControl, approvalHandler *approval.Handler) *Handler {
+ return &Handler{
+ ipc: ipc,
+ approvalHandler: approvalHandler,
+ }
+}
+
+// Handle — точка входа для команды /start.
+// Если пользователь уже зарегистрирован — приветствуем.
+// Если нет — запускаем флоу регистрации.
+func (h *Handler) Handle(bot *tgbotapi.BotAPI, msg *tgbotapi.Message) {
+ ctx := context.Background()
+
+ existing, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, msg.From.ID)
+ if err != nil {
+ logrus.Error("start.Handle: GetUserByTelegramIDDB: ", err)
+ return
+ }
+
+ // Пользователь уже есть — показываем главное меню или сообщение об ожидании отдела
+ if existing != nil {
+ h.sendWelcomeBack(bot, msg.Chat.ID, msg.From.ID, existing)
+ return
+ }
+
+ // Новый пользователь — сохраняем состояние "ожидаем ФИО"
+ stateKey := registrationStateKey(msg.From.ID)
+ if err := h.ipc.RedisClient.Set(ctx, stateKey, stateAwaitingFullName, registrationTTL); err != nil {
+ logrus.Error("start.Handle: Set redis state: ", err)
+ return
+ }
+
+ utilscore.SendBotMessage(bot, msg.Chat.ID,
+ "👋 Добро пожаловать в Портал сотрудника РусПЭТ!\n\n"+
+ "Для регистрации введите ваше полное имя (ФИО).\n\n"+
+ "Например: Иванов Иван",
+ )
+}
+
+// HandleTextInput обрабатывает текстовый ввод в рамках флоу регистрации.
+// Возвращает true если сообщение было обработано (пользователь в процессе регистрации).
+func (h *Handler) HandleTextInput(bot *tgbotapi.BotAPI, msg *tgbotapi.Message) bool {
+ ctx := context.Background()
+ stateKey := registrationStateKey(msg.From.ID)
+
+ state, err := h.ipc.RedisClient.Get(ctx, stateKey)
+ if err != nil || state == "" {
+ return false // не наш ввод
+ }
+
+ switch state {
+ case stateAwaitingFullName:
+ h.handleFullNameInput(ctx, bot, msg, stateKey)
+ return true
+ }
+
+ return false
+}
+
+func (h *Handler) handleFullNameInput(ctx context.Context, bot *tgbotapi.BotAPI, msg *tgbotapi.Message, stateKey string) {
+ fullName := sanitizeFullName(msg.Text)
+
+ if !isValidFullName(fullName) {
+ utilscore.SendBotMessage(bot, msg.Chat.ID,
+ "⚠️ Пожалуйста, введите корректное ФИО.\n\n"+
+ "Например: Иванов Иван",
+ )
+ return
+ }
+
+ // Создаём пользователя
+ telegramID := msg.From.ID
+ username := msg.From.UserName
+ langCode := msg.From.LanguageCode
+
+ user := &typescore.User{
+ TelegramID: &telegramID,
+ FullName: &fullName,
+ LanguageCode: &langCode,
+ }
+ if username != "" {
+ user.Username = &username
+ }
+
+ created, _, err := h.ipc.Database.User.CreateUserDB(ctx, nil, user, true)
+ if err != nil {
+ logrus.Error("start.handleFullNameInput: CreateUserDB: ", err)
+ utilscore.SendBotMessage(bot, msg.Chat.ID, "Произошла ошибка при регистрации. Попробуйте ещё раз — /start")
+ return
+ }
+
+ // Сбрасываем состояние регистрации
+ h.ipc.RedisClient.Del(ctx, stateKey) //nolint:errcheck
+
+ logrus.Infof("✅ Новый пользователь зарегистрирован: %s (tg_id=%d)", fullName, telegramID)
+
+ h.sendRegistrationDone(bot, msg.Chat.ID, created)
+}
+
+// sendWelcomeBack — приветствие для уже зарегистрированного пользователя.
+func (h *Handler) sendWelcomeBack(bot *tgbotapi.BotAPI, chatID int64, telegramID int64, user *typescore.User) {
+ ctx := context.Background()
+ name := ""
+ if user.FullName != nil {
+ name = *user.FullName
+ }
+
+ if user.DepartmentID == nil {
+ utilscore.SendBotMessage(bot, chatID, fmt.Sprintf(
+ "👋 Здравствуйте, %s!\n\n"+
+ "⏳ Ваша учётная запись ожидает назначения в отдел.\n"+
+ "Обратитесь к администратору.", name,
+ ))
+ return
+ }
+
+ // Определяем клавиатуру по роли
+ replyMarkup := h.buildMenuKeyboard(ctx, user)
+
+ msg := tgbotapi.NewMessage(chatID, fmt.Sprintf("👋 Здравствуйте, %s!", name))
+ msg.ParseMode = "HTML"
+ msg.ReplyMarkup = replyMarkup
+ bot.Send(msg) //nolint:errcheck
+}
+
+// buildMenuKeyboard возвращает клавиатуру в зависимости от роли пользователя
+func (h *Handler) buildMenuKeyboard(ctx context.Context, user *typescore.User) tgbotapi.ReplyKeyboardMarkup {
+ if user.ID == nil {
+ return keyboard.MainMenuKeyboard()
+ }
+
+ isApprover, _ := h.ipc.Database.User.IsApproverDB(ctx, *user.ID)
+ isObserver, _ := h.ipc.Database.User.IsObserverDB(ctx, *user.ID)
+ isExecutor, _ := h.ipc.Database.User.IsExecutorDB(ctx, *user.ID)
+
+ var replyMarkup tgbotapi.ReplyKeyboardMarkup
+
+ // Все комбинации ролей
+ if isApprover && isObserver && isExecutor {
+ replyMarkup = keyboard.ApproverObserverExecutorMenuKeyboard()
+ } else if isApprover && isExecutor {
+ replyMarkup = keyboard.ApproverExecutorMenuKeyboard()
+ } else if isObserver && isExecutor {
+ replyMarkup = keyboard.ObserverExecutorMenuKeyboard()
+ } else if isApprover && isObserver {
+ replyMarkup = keyboard.ApproverObserverMenuKeyboard()
+ } else if isApprover {
+ replyMarkup = keyboard.ApproverMenuKeyboard()
+ } else if isObserver {
+ replyMarkup = keyboard.ObserverMenuKeyboard()
+ } else if isExecutor {
+ replyMarkup = keyboard.ExecutorMenuKeyboard()
+ } else {
+ replyMarkup = keyboard.MainMenuKeyboard()
+ }
+
+ return replyMarkup
+}
+
+// sendRegistrationDone — подтверждение успешной регистрации.
+func (h *Handler) sendRegistrationDone(bot *tgbotapi.BotAPI, chatID int64, user *typescore.User) {
+ name := ""
+ if user.FullName != nil {
+ name = *user.FullName
+ }
+
+ utilscore.SendBotMessage(bot, chatID, fmt.Sprintf(
+ "✅ Вы успешно зарегистрированы!\n\n"+
+ "Имя: %s\n\n"+
+ "⏳ Ожидайте назначения в отдел. После этого вам станут доступны функции портала.\n",
+ name,
+ ))
+}
diff --git a/service/telegram_service/handlers/start/helpers.go b/service/telegram_service/handlers/start/helpers.go
new file mode 100644
index 0000000..56dcb7e
--- /dev/null
+++ b/service/telegram_service/handlers/start/helpers.go
@@ -0,0 +1,47 @@
+package start
+
+import (
+ "fmt"
+ "strings"
+ "time"
+ "unicode"
+)
+
+const (
+ stateAwaitingFullName = "awaiting_full_name"
+ registrationTTL = 30 * time.Minute
+)
+
+func registrationStateKey(telegramID int64) string {
+ return fmt.Sprintf("registration:%d", telegramID)
+}
+
+// sanitizeFullName убирает лишние пробелы и приводит к нормальному виду.
+func sanitizeFullName(input string) string {
+ parts := strings.Fields(input) // разбивает по любым пробелам, убирает пустые
+ for i, p := range parts {
+ runes := []rune(p)
+ if len(runes) > 0 {
+ runes[0] = unicode.ToUpper(runes[0])
+ }
+ parts[i] = string(runes)
+ }
+ return strings.Join(parts, " ")
+}
+
+// isValidFullName проверяет что введено минимум два слова (имя + фамилия)
+// и нет посторонних символов.
+func isValidFullName(name string) bool {
+ parts := strings.Fields(name)
+ if len(parts) < 2 {
+ return false
+ }
+ for _, part := range parts {
+ for _, r := range part {
+ if !unicode.IsLetter(r) && r != '-' {
+ return false
+ }
+ }
+ }
+ return true
+}
diff --git a/service/telegram_service/keyboard/add_approver.go b/service/telegram_service/keyboard/add_approver.go
new file mode 100644
index 0000000..b79bff9
--- /dev/null
+++ b/service/telegram_service/keyboard/add_approver.go
@@ -0,0 +1,281 @@
+package keyboard
+
+import (
+ "bitrix_balancer_api/core/typescore"
+ "bitrix_balancer_api/telegram_service/types"
+ "context"
+ "fmt"
+ tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
+)
+
+const addApproverCategoriesPerPage = 6
+const addApproverApprovalsPerPage = 6
+const addApproverUsersPerPage = 8
+const addedApproversListPerPage = 6
+
+func BuildAddApproverMainMenu() tgbotapi.InlineKeyboardMarkup {
+ return tgbotapi.NewInlineKeyboardMarkup(
+ tgbotapi.NewInlineKeyboardRow(
+ tgbotapi.NewInlineKeyboardButtonData("➕ Добавить", "add_appr_create"),
+ ),
+ tgbotapi.NewInlineKeyboardRow(
+ tgbotapi.NewInlineKeyboardButtonData("📋 Ранее добавленные", "add_appr_list"),
+ ),
+ )
+}
+
+func BuildAddApproverCategoryMenu(categories []*typescore.ApprovalTopicCategory, page int) tgbotapi.InlineKeyboardMarkup {
+ total := len(categories)
+ totalPages := (total + addApproverCategoriesPerPage - 1) / addApproverCategoriesPerPage
+
+ if page < 0 {
+ page = 0
+ }
+ if page >= totalPages && totalPages > 0 {
+ page = totalPages - 1
+ }
+
+ start := page * addApproverCategoriesPerPage
+ end := start + addApproverCategoriesPerPage
+ if end > total {
+ end = total
+ }
+
+ var rows [][]tgbotapi.InlineKeyboardButton
+
+ for _, c := range categories[start:end] {
+ if c.ID == nil || c.Name == nil {
+ continue
+ }
+ btn := tgbotapi.NewInlineKeyboardButtonData(
+ *c.Name,
+ fmt.Sprintf("add_appr_category:%d", *c.ID),
+ )
+ rows = append(rows, tgbotapi.NewInlineKeyboardRow(btn))
+ }
+
+ if totalPages > 1 {
+ var navRow []tgbotapi.InlineKeyboardButton
+ if page > 0 {
+ navRow = append(navRow, tgbotapi.NewInlineKeyboardButtonData(
+ "← Назад",
+ fmt.Sprintf("add_appr_category_page:%d", page-1),
+ ))
+ }
+ if page < totalPages-1 {
+ navRow = append(navRow, tgbotapi.NewInlineKeyboardButtonData(
+ fmt.Sprintf("%d / %d →", page+1, totalPages),
+ fmt.Sprintf("add_appr_category_page:%d", page+1),
+ ))
+ } else {
+ navRow = append(navRow, tgbotapi.NewInlineKeyboardButtonData(
+ fmt.Sprintf("%d / %d", page+1, totalPages),
+ "add_appr_page_noop",
+ ))
+ }
+ rows = append(rows, navRow)
+ }
+
+ return tgbotapi.NewInlineKeyboardMarkup(rows...)
+}
+
+func BuildAddApproverApprovalMenu(approvals []*typescore.Approval, categoryID uint64, page int, ctx context.Context, ipc *types.InternalProviderControl) tgbotapi.InlineKeyboardMarkup {
+ total := len(approvals)
+ totalPages := (total + addApproverApprovalsPerPage - 1) / addApproverApprovalsPerPage
+
+ if page < 0 {
+ page = 0
+ }
+ if page >= totalPages && totalPages > 0 {
+ page = totalPages - 1
+ }
+
+ start := page * addApproverApprovalsPerPage
+ end := start + addApproverApprovalsPerPage
+ if end > total {
+ end = total
+ }
+
+ var rows [][]tgbotapi.InlineKeyboardButton
+
+ for _, a := range approvals[start:end] {
+ if a.ID == nil {
+ continue
+ }
+
+ topicName := "—"
+ if a.TopicID != nil {
+ topic, _ := ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *a.TopicID)
+ if topic != nil && topic.Name != nil {
+ topicName = *topic.Name
+ }
+ }
+
+ label := fmt.Sprintf("#%d — %s", *a.ID, topicName)
+ btn := tgbotapi.NewInlineKeyboardButtonData(
+ label,
+ fmt.Sprintf("add_appr_approval:%d", *a.ID),
+ )
+ rows = append(rows, tgbotapi.NewInlineKeyboardRow(btn))
+ }
+
+ if totalPages > 1 {
+ var navRow []tgbotapi.InlineKeyboardButton
+ if page > 0 {
+ navRow = append(navRow, tgbotapi.NewInlineKeyboardButtonData(
+ "← Назад",
+ fmt.Sprintf("add_appr_approval_page:%d:%d", categoryID, page-1),
+ ))
+ }
+ if page < totalPages-1 {
+ navRow = append(navRow, tgbotapi.NewInlineKeyboardButtonData(
+ fmt.Sprintf("%d / %d →", page+1, totalPages),
+ fmt.Sprintf("add_appr_approval_page:%d:%d", categoryID, page+1),
+ ))
+ } else {
+ navRow = append(navRow, tgbotapi.NewInlineKeyboardButtonData(
+ fmt.Sprintf("%d / %d", page+1, totalPages),
+ "add_appr_page_noop",
+ ))
+ }
+ rows = append(rows, navRow)
+ }
+
+ rows = append(rows, tgbotapi.NewInlineKeyboardRow(
+ tgbotapi.NewInlineKeyboardButtonData("← К категориям", "add_appr_create"),
+ ))
+
+ return tgbotapi.NewInlineKeyboardMarkup(rows...)
+}
+
+func BuildAddApproverUserMenu(users []*typescore.User, approvalID, categoryID uint64, page int) tgbotapi.InlineKeyboardMarkup {
+ total := len(users)
+ totalPages := (total + addApproverUsersPerPage - 1) / addApproverUsersPerPage
+
+ if page < 0 {
+ page = 0
+ }
+ if page >= totalPages && totalPages > 0 {
+ page = totalPages - 1
+ }
+
+ start := page * addApproverUsersPerPage
+ end := start + addApproverUsersPerPage
+ if end > total {
+ end = total
+ }
+
+ var rows [][]tgbotapi.InlineKeyboardButton
+
+ for _, u := range users[start:end] {
+ if u.ID == nil || u.FullName == nil {
+ continue
+ }
+ btn := tgbotapi.NewInlineKeyboardButtonData(
+ *u.FullName,
+ fmt.Sprintf("add_appr_user:%d", *u.ID),
+ )
+ rows = append(rows, tgbotapi.NewInlineKeyboardRow(btn))
+ }
+
+ if totalPages > 1 {
+ var navRow []tgbotapi.InlineKeyboardButton
+ if page > 0 {
+ navRow = append(navRow, tgbotapi.NewInlineKeyboardButtonData(
+ "← Назад",
+ fmt.Sprintf("add_appr_user_page:%d:%d:%d", approvalID, categoryID, page-1),
+ ))
+ }
+ if page < totalPages-1 {
+ navRow = append(navRow, tgbotapi.NewInlineKeyboardButtonData(
+ fmt.Sprintf("%d / %d →", page+1, totalPages),
+ fmt.Sprintf("add_appr_user_page:%d:%d:%d", approvalID, categoryID, page+1),
+ ))
+ } else {
+ navRow = append(navRow, tgbotapi.NewInlineKeyboardButtonData(
+ fmt.Sprintf("%d / %d", page+1, totalPages),
+ "add_appr_page_noop",
+ ))
+ }
+ rows = append(rows, navRow)
+ }
+
+ rows = append(rows, tgbotapi.NewInlineKeyboardRow(
+ tgbotapi.NewInlineKeyboardButtonData("← Назад", fmt.Sprintf("add_appr_category:%d", categoryID)),
+ ))
+
+ return tgbotapi.NewInlineKeyboardMarkup(rows...)
+}
+
+func BuildAddedApproversList(addedApprovers []*typescore.ApprovalAdditionalApprover, page int, ctx context.Context, ipc *types.InternalProviderControl) tgbotapi.InlineKeyboardMarkup {
+ total := len(addedApprovers)
+ totalPages := (total + addedApproversListPerPage - 1) / addedApproversListPerPage
+
+ if page < 0 {
+ page = 0
+ }
+ if page >= totalPages && totalPages > 0 {
+ page = totalPages - 1
+ }
+
+ start := page * addedApproversListPerPage
+ end := start + addedApproversListPerPage
+ if end > total {
+ end = total
+ }
+
+ var rows [][]tgbotapi.InlineKeyboardButton
+
+ for _, aa := range addedApprovers[start:end] {
+ if aa.ID == nil || aa.ApprovalID == nil {
+ continue
+ }
+
+ approverName := "—"
+ if aa.ApproverID != nil {
+ approver, _ := ipc.Database.User.GetUserByIDDB(ctx, *aa.ApproverID)
+ if approver != nil && approver.FullName != nil {
+ approverName = *approver.FullName
+ }
+ }
+
+ label := fmt.Sprintf("#%d — %s", *aa.ApprovalID, approverName)
+ btn := tgbotapi.NewInlineKeyboardButtonData(
+ label,
+ fmt.Sprintf("add_appr_detail:%d", *aa.ID),
+ )
+ rows = append(rows, tgbotapi.NewInlineKeyboardRow(btn))
+ }
+
+ if totalPages > 1 {
+ var navRow []tgbotapi.InlineKeyboardButton
+ if page > 0 {
+ navRow = append(navRow, tgbotapi.NewInlineKeyboardButtonData(
+ "← Назад",
+ fmt.Sprintf("add_appr_list_page:%d", page-1),
+ ))
+ }
+ if page < totalPages-1 {
+ navRow = append(navRow, tgbotapi.NewInlineKeyboardButtonData(
+ fmt.Sprintf("%d / %d →", page+1, totalPages),
+ fmt.Sprintf("add_appr_list_page:%d", page+1),
+ ))
+ } else {
+ navRow = append(navRow, tgbotapi.NewInlineKeyboardButtonData(
+ fmt.Sprintf("%d / %d", page+1, totalPages),
+ "add_appr_page_noop",
+ ))
+ }
+ rows = append(rows, navRow)
+ }
+
+ return tgbotapi.NewInlineKeyboardMarkup(rows...)
+}
+
+func BuildAddedApproverDetail() tgbotapi.InlineKeyboardMarkup {
+ return tgbotapi.NewInlineKeyboardMarkup(
+ tgbotapi.NewInlineKeyboardRow(
+ tgbotapi.NewInlineKeyboardButtonData("← К списку", "add_appr_list"),
+ ),
+ )
+}
diff --git a/service/telegram_service/keyboard/approval.go b/service/telegram_service/keyboard/approval.go
new file mode 100644
index 0000000..46427bc
--- /dev/null
+++ b/service/telegram_service/keyboard/approval.go
@@ -0,0 +1,223 @@
+package keyboard
+
+import (
+ "bitrix_balancer_api/telegram_service/approvalflow"
+ "bitrix_balancer_api/telegram_service/state"
+ "fmt"
+ tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
+)
+
+// Формат callback-data для всех кнопок согласования:
+// appr:{topic_code}:{node_key} — навигация по флоу
+// appr_yes:{approval_id} — одобрить
+// appr_no:{approval_id} — отклонить
+// appr_revoke:{approval_id} — отозвать
+
+func BuildApprovalRejectComment(approvalID uint64) tgbotapi.InlineKeyboardMarkup {
+ return tgbotapi.NewInlineKeyboardMarkup(
+ tgbotapi.NewInlineKeyboardRow(
+ tgbotapi.NewInlineKeyboardButtonData(
+ "Отправить без комментария",
+ fmt.Sprintf("appr_no_skip:%d", approvalID),
+ ),
+ ),
+ )
+}
+
+const topicsPerPage = 6
+
+// BuildApprovalMenu строит меню тем с пагинацией.
+// page — 0-индексированная страница.
+func BuildApprovalMenu(topics []approvalflow.Topic, page int) tgbotapi.InlineKeyboardMarkup {
+ total := len(topics)
+ totalPages := (total + topicsPerPage - 1) / topicsPerPage
+
+ // Ограничиваем page
+ if page < 0 {
+ page = 0
+ }
+ if page >= totalPages && totalPages > 0 {
+ page = totalPages - 1
+ }
+
+ start := page * topicsPerPage
+ end := start + topicsPerPage
+ if end > total {
+ end = total
+ }
+
+ var rows [][]tgbotapi.InlineKeyboardButton
+
+ for _, t := range topics[start:end] {
+ btn := tgbotapi.NewInlineKeyboardButtonData(
+ t.Name(),
+ fmt.Sprintf("appr:%s:%s", t.Code(), t.Code()),
+ )
+ rows = append(rows, tgbotapi.NewInlineKeyboardRow(btn))
+ }
+
+ if totalPages > 1 {
+ var navRow []tgbotapi.InlineKeyboardButton
+ if page > 0 {
+ navRow = append(navRow, tgbotapi.NewInlineKeyboardButtonData(
+ "← Назад",
+ fmt.Sprintf("appr_page:%d", page-1),
+ ))
+ }
+ if page < totalPages-1 {
+ navRow = append(navRow, tgbotapi.NewInlineKeyboardButtonData(
+ fmt.Sprintf("%d / %d →", page+1, totalPages),
+ fmt.Sprintf("appr_page:%d", page+1),
+ ))
+ } else {
+ navRow = append(navRow, tgbotapi.NewInlineKeyboardButtonData(
+ fmt.Sprintf("%d / %d", page+1, totalPages),
+ "appr_page_noop",
+ ))
+ }
+ rows = append(rows, navRow)
+ }
+
+ return tgbotapi.NewInlineKeyboardMarkup(rows...)
+}
+
+// BuildApprovalStep строит клавиатуру для текущего шага флоу.
+func BuildApprovalStep(topicCode string, nodes []*approvalflow.FlowNode) tgbotapi.InlineKeyboardMarkup {
+ var rows [][]tgbotapi.InlineKeyboardButton
+ for _, node := range nodes {
+ btn := tgbotapi.NewInlineKeyboardButtonData(
+ node.Label,
+ fmt.Sprintf("appr:%s:%s", topicCode, node.Key),
+ )
+ rows = append(rows, tgbotapi.NewInlineKeyboardRow(btn))
+ }
+ rows = append(rows, tgbotapi.NewInlineKeyboardRow(
+ tgbotapi.NewInlineKeyboardButtonData("← Назад", fmt.Sprintf("appr_back:%s", topicCode)),
+ ))
+ return tgbotapi.NewInlineKeyboardMarkup(rows...)
+}
+
+// BuildApproverDecision строит кнопки Да/Нет для согласующего.
+func BuildApproverDecision(approvalID uint64) tgbotapi.InlineKeyboardMarkup {
+ return tgbotapi.NewInlineKeyboardMarkup(
+ tgbotapi.NewInlineKeyboardRow(
+ tgbotapi.NewInlineKeyboardButtonData("✅ Да", fmt.Sprintf("appr_yes:%d", approvalID)),
+ tgbotapi.NewInlineKeyboardButtonData("❌ Нет", fmt.Sprintf("appr_no:%d", approvalID)),
+ ),
+ tgbotapi.NewInlineKeyboardRow(
+ tgbotapi.NewInlineKeyboardButtonData("Стадия согласования", fmt.Sprintf("appr_stage:%d", approvalID)),
+ ),
+ )
+}
+
+// BuildRevokeButton строит кнопку отзыва для инициатора и директора.
+func BuildRevokeButton(approvalID uint64) tgbotapi.InlineKeyboardMarkup {
+ return tgbotapi.NewInlineKeyboardMarkup(
+ tgbotapi.NewInlineKeyboardRow(
+ tgbotapi.NewInlineKeyboardButtonData("↩️ Отозвать", fmt.Sprintf("appr_revoke:%d", approvalID)),
+ ),
+ tgbotapi.NewInlineKeyboardRow(
+ tgbotapi.NewInlineKeyboardButtonData("Стадия согласования", fmt.Sprintf("appr_stage:%d", approvalID)),
+ ),
+ )
+}
+
+// BuildApprovalInputPrompt — подсказка ввода с кнопкой назад.
+func BuildApprovalInputPrompt(topicCode string) tgbotapi.InlineKeyboardMarkup {
+ return tgbotapi.NewInlineKeyboardMarkup(
+ tgbotapi.NewInlineKeyboardRow(
+ tgbotapi.NewInlineKeyboardButtonData("← Назад", fmt.Sprintf("appr_back:%s", topicCode)),
+ ),
+ )
+}
+
+// BuildRejectOptions — варианты при нажатии "Нет".
+func BuildRejectOptions(approvalID uint64) tgbotapi.InlineKeyboardMarkup {
+ return tgbotapi.NewInlineKeyboardMarkup(
+ tgbotapi.NewInlineKeyboardRow(
+ tgbotapi.NewInlineKeyboardButtonData(
+ "💬 Ввести комментарий",
+ fmt.Sprintf("appr_no_comment:%d", approvalID),
+ ),
+ ),
+ tgbotapi.NewInlineKeyboardRow(
+ tgbotapi.NewInlineKeyboardButtonData(
+ "⏳ Отложить",
+ fmt.Sprintf("appr_no_defer:%d", approvalID),
+ ),
+ ),
+ tgbotapi.NewInlineKeyboardRow(
+ tgbotapi.NewInlineKeyboardButtonData(
+ "✅ Без комментария",
+ fmt.Sprintf("appr_no_skip:%d", approvalID),
+ ),
+ ),
+ )
+}
+
+// BuildRevokeOptions — варианты при нажатии "Отозвать".
+func BuildRevokeOptions(approvalID uint64) tgbotapi.InlineKeyboardMarkup {
+ return tgbotapi.NewInlineKeyboardMarkup(
+ tgbotapi.NewInlineKeyboardRow(
+ tgbotapi.NewInlineKeyboardButtonData(
+ "💬 Ввести комментарий",
+ fmt.Sprintf("appr_revoke_comment:%d", approvalID),
+ ),
+ ),
+ tgbotapi.NewInlineKeyboardRow(
+ tgbotapi.NewInlineKeyboardButtonData(
+ "⏳ Отложить",
+ fmt.Sprintf("appr_revoke_defer:%d", approvalID),
+ ),
+ ),
+ tgbotapi.NewInlineKeyboardRow(
+ tgbotapi.NewInlineKeyboardButtonData(
+ "✅ Без комментария",
+ fmt.Sprintf("appr_revoke_skip:%d", approvalID),
+ ),
+ ),
+ )
+}
+
+// BuildPendingCommentsList — список отложенных заявок.
+func BuildPendingCommentsList(items []state.PendingCommentItem, topicNames map[uint64]string) tgbotapi.InlineKeyboardMarkup {
+ var rows [][]tgbotapi.InlineKeyboardButton
+ for _, item := range items {
+ icon := "❌"
+ if item.Action == "revoke" {
+ icon = "↩️"
+ }
+ label := fmt.Sprintf("%s #%d", icon, item.ApprovalID)
+ if name, ok := topicNames[item.ApprovalID]; ok {
+ label += " — " + name
+ }
+ rows = append(rows, tgbotapi.NewInlineKeyboardRow(
+ tgbotapi.NewInlineKeyboardButtonData(
+ label,
+ fmt.Sprintf("pending_item:%d", item.ApprovalID),
+ ),
+ ))
+ }
+ return tgbotapi.NewInlineKeyboardMarkup(rows...)
+}
+
+// BuildPendingItemOptions — действия по конкретной отложенной заявке.
+func BuildPendingItemOptions(approvalID uint64, action string) tgbotapi.InlineKeyboardMarkup {
+ commentCB := fmt.Sprintf("appr_no_comment:%d", approvalID)
+ skipCB := fmt.Sprintf("appr_no_skip:%d", approvalID)
+ if action == "revoke" {
+ commentCB = fmt.Sprintf("appr_revoke_comment:%d", approvalID)
+ skipCB = fmt.Sprintf("appr_revoke_skip:%d", approvalID)
+ }
+ return tgbotapi.NewInlineKeyboardMarkup(
+ tgbotapi.NewInlineKeyboardRow(
+ tgbotapi.NewInlineKeyboardButtonData("💬 Ввести комментарий", commentCB),
+ ),
+ tgbotapi.NewInlineKeyboardRow(
+ tgbotapi.NewInlineKeyboardButtonData("✅ Без комментария", skipCB),
+ ),
+ tgbotapi.NewInlineKeyboardRow(
+ tgbotapi.NewInlineKeyboardButtonData("← Назад", "pending_back"),
+ ),
+ )
+}
diff --git a/service/telegram_service/keyboard/approval_stage.go b/service/telegram_service/keyboard/approval_stage.go
new file mode 100644
index 0000000..c28a918
--- /dev/null
+++ b/service/telegram_service/keyboard/approval_stage.go
@@ -0,0 +1,17 @@
+package keyboard
+
+import (
+ "fmt"
+ tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
+)
+
+func BuildApprovalStagesButton(approvalID uint64) tgbotapi.InlineKeyboardMarkup {
+ return tgbotapi.NewInlineKeyboardMarkup(
+ tgbotapi.NewInlineKeyboardRow(
+ tgbotapi.NewInlineKeyboardButtonData(
+ "Стадия согласования",
+ fmt.Sprintf("appr_stage:%d", approvalID),
+ ),
+ ),
+ )
+}
diff --git a/service/telegram_service/keyboard/approver_select.go b/service/telegram_service/keyboard/approver_select.go
new file mode 100644
index 0000000..c00b823
--- /dev/null
+++ b/service/telegram_service/keyboard/approver_select.go
@@ -0,0 +1,64 @@
+package keyboard
+
+import (
+ "bitrix_balancer_api/core/typescore"
+ "fmt"
+ tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
+)
+
+const approverSelectionPerPage = 8
+
+func BuildApproverSelectionMenu(approvers []*typescore.User, page int) tgbotapi.InlineKeyboardMarkup {
+ total := len(approvers)
+ totalPages := (total + approverSelectionPerPage - 1) / approverSelectionPerPage
+
+ if page < 0 {
+ page = 0
+ }
+ if page >= totalPages && totalPages > 0 {
+ page = totalPages - 1
+ }
+
+ start := page * approverSelectionPerPage
+ end := start + approverSelectionPerPage
+ if end > total {
+ end = total
+ }
+
+ var rows [][]tgbotapi.InlineKeyboardButton
+
+ for _, a := range approvers[start:end] {
+ if a.ID == nil || a.FullName == nil {
+ continue
+ }
+ btn := tgbotapi.NewInlineKeyboardButtonData(
+ *a.FullName,
+ fmt.Sprintf("select_approver:%d", *a.ID),
+ )
+ rows = append(rows, tgbotapi.NewInlineKeyboardRow(btn))
+ }
+
+ if totalPages > 1 {
+ var navRow []tgbotapi.InlineKeyboardButton
+ if page > 0 {
+ navRow = append(navRow, tgbotapi.NewInlineKeyboardButtonData(
+ "← Назад",
+ fmt.Sprintf("select_approver_page:%d", page-1),
+ ))
+ }
+ if page < totalPages-1 {
+ navRow = append(navRow, tgbotapi.NewInlineKeyboardButtonData(
+ fmt.Sprintf("%d / %d →", page+1, totalPages),
+ fmt.Sprintf("select_approver_page:%d", page+1),
+ ))
+ } else {
+ navRow = append(navRow, tgbotapi.NewInlineKeyboardButtonData(
+ fmt.Sprintf("%d / %d", page+1, totalPages),
+ "select_approver_noop",
+ ))
+ }
+ rows = append(rows, navRow)
+ }
+
+ return tgbotapi.NewInlineKeyboardMarkup(rows...)
+}
diff --git a/service/telegram_service/keyboard/builder.go b/service/telegram_service/keyboard/builder.go
new file mode 100644
index 0000000..2148f75
--- /dev/null
+++ b/service/telegram_service/keyboard/builder.go
@@ -0,0 +1,188 @@
+package keyboard
+
+import tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
+
+// MainMenuKeyboard - главное меню (без изменений в структуре)
+func MainMenuKeyboard() tgbotapi.ReplyKeyboardMarkup {
+ return tgbotapi.NewReplyKeyboard(
+ tgbotapi.NewKeyboardButtonRow(
+ tgbotapi.NewKeyboardButton("Согласование"),
+ tgbotapi.NewKeyboardButton("Мои заявки"),
+ ),
+ tgbotapi.NewKeyboardButtonRow(
+ tgbotapi.NewKeyboardButton("Отложенные"),
+ ),
+ tgbotapi.NewKeyboardButtonRow(
+ tgbotapi.NewKeyboardButton("❓ Как создать согласование"),
+ ),
+ )
+}
+
+func ExecutorMenuKeyboard() tgbotapi.ReplyKeyboardMarkup {
+ return tgbotapi.NewReplyKeyboard(
+ tgbotapi.NewKeyboardButtonRow(
+ tgbotapi.NewKeyboardButton("Согласование"),
+ tgbotapi.NewKeyboardButton("Мои заявки"),
+ ),
+ tgbotapi.NewKeyboardButtonRow(
+ tgbotapi.NewKeyboardButton("Мои задачи"),
+ ),
+ tgbotapi.NewKeyboardButtonRow(
+ tgbotapi.NewKeyboardButton("❓ Как создать согласование"),
+ ),
+ )
+}
+
+func ApproverExecutorMenuKeyboard() tgbotapi.ReplyKeyboardMarkup {
+ return tgbotapi.NewReplyKeyboard(
+ tgbotapi.NewKeyboardButtonRow(
+ tgbotapi.NewKeyboardButton("Согласование"),
+ tgbotapi.NewKeyboardButton("Мои заявки"),
+ ),
+ tgbotapi.NewKeyboardButtonRow(
+ tgbotapi.NewKeyboardButton("Согласовать"),
+ tgbotapi.NewKeyboardButton("Мои задачи"),
+ ),
+ tgbotapi.NewKeyboardButtonRow(
+ tgbotapi.NewKeyboardButton("Отложенные"),
+ ),
+ tgbotapi.NewKeyboardButtonRow(
+ tgbotapi.NewKeyboardButton("❓ Как создать согласование"),
+ ),
+ )
+}
+
+func ObserverExecutorMenuKeyboard() tgbotapi.ReplyKeyboardMarkup {
+ return tgbotapi.NewReplyKeyboard(
+ tgbotapi.NewKeyboardButtonRow(
+ tgbotapi.NewKeyboardButton("Согласование"),
+ tgbotapi.NewKeyboardButton("Мои заявки"),
+ ),
+ tgbotapi.NewKeyboardButtonRow(
+ tgbotapi.NewKeyboardButton("Наблюдаемые"),
+ tgbotapi.NewKeyboardButton("Мои задачи"),
+ ),
+ tgbotapi.NewKeyboardButtonRow(
+ tgbotapi.NewKeyboardButton("Отложенные"),
+ ),
+ tgbotapi.NewKeyboardButtonRow(
+ tgbotapi.NewKeyboardButton("❓ Как создать согласование"),
+ ),
+ )
+}
+
+func ApproverObserverExecutorMenuKeyboard() tgbotapi.ReplyKeyboardMarkup {
+ return tgbotapi.NewReplyKeyboard(
+ tgbotapi.NewKeyboardButtonRow(
+ tgbotapi.NewKeyboardButton("Согласование"),
+ tgbotapi.NewKeyboardButton("Мои заявки"),
+ ),
+ tgbotapi.NewKeyboardButtonRow(
+ tgbotapi.NewKeyboardButton("Согласовать"),
+ tgbotapi.NewKeyboardButton("Мои задачи"),
+ ),
+ tgbotapi.NewKeyboardButtonRow(
+ tgbotapi.NewKeyboardButton("Отложенные"),
+ tgbotapi.NewKeyboardButton("Наблюдаемые"),
+ ),
+ tgbotapi.NewKeyboardButtonRow(
+ tgbotapi.NewKeyboardButton("❓ Как создать согласование"),
+ ),
+ )
+}
+
+// ApprovalsSubmenuKeyboard - подменю "Согласования"
+func ApprovalsSubmenuKeyboard(isObserver, isApprover bool) tgbotapi.ReplyKeyboardMarkup {
+ rows := [][]tgbotapi.KeyboardButton{
+ tgbotapi.NewKeyboardButtonRow(
+ tgbotapi.NewKeyboardButton("Согласования"),
+ tgbotapi.NewKeyboardButton("Создать согласование"),
+ ),
+ }
+ if isApprover {
+ rows = append(rows, tgbotapi.NewKeyboardButtonRow(
+ tgbotapi.NewKeyboardButton("Сформировать отчёт"),
+ tgbotapi.NewKeyboardButton("Делегирование прав"),
+ ))
+ rows = append(rows, tgbotapi.NewKeyboardButtonRow(
+ tgbotapi.NewKeyboardButton("Добавить согласующего"),
+ ))
+ }
+
+ rows = append(rows, tgbotapi.NewKeyboardButtonRow(
+ tgbotapi.NewKeyboardButton("← Назад"),
+ ))
+
+ return tgbotapi.NewReplyKeyboard(rows...)
+}
+
+// ApprovalsListSubmenuKeyboard - подменю "Список согласований"
+func ApprovalsListSubmenuKeyboard() tgbotapi.ReplyKeyboardMarkup {
+ return tgbotapi.NewReplyKeyboard(
+ tgbotapi.NewKeyboardButtonRow(
+ tgbotapi.NewKeyboardButton("Все"),
+ tgbotapi.NewKeyboardButton("Принятые"),
+ ),
+ tgbotapi.NewKeyboardButtonRow(
+ tgbotapi.NewKeyboardButton("Отклонённые"),
+ tgbotapi.NewKeyboardButton("На согласовании"),
+ ),
+ tgbotapi.NewKeyboardButtonRow(
+ tgbotapi.NewKeyboardButton("← Назад"),
+ ),
+ )
+}
+
+// ObserverMenuKeyboard - меню для наблюдателя
+func ObserverMenuKeyboard() tgbotapi.ReplyKeyboardMarkup {
+ return tgbotapi.NewReplyKeyboard(
+ tgbotapi.NewKeyboardButtonRow(
+ tgbotapi.NewKeyboardButton("Согласование"),
+ tgbotapi.NewKeyboardButton("Мои заявки"),
+ ),
+ tgbotapi.NewKeyboardButtonRow(
+ tgbotapi.NewKeyboardButton("Отложенные"),
+ tgbotapi.NewKeyboardButton("Наблюдаемые"),
+ ),
+ tgbotapi.NewKeyboardButtonRow(
+ tgbotapi.NewKeyboardButton("❓ Как создать согласование"),
+ ),
+ )
+}
+
+// ApproverMenuKeyboard - меню для согласующего
+func ApproverMenuKeyboard() tgbotapi.ReplyKeyboardMarkup {
+ return tgbotapi.NewReplyKeyboard(
+ tgbotapi.NewKeyboardButtonRow(
+ tgbotapi.NewKeyboardButton("Согласование"),
+ tgbotapi.NewKeyboardButton("Мои заявки"),
+ ),
+ tgbotapi.NewKeyboardButtonRow(
+ tgbotapi.NewKeyboardButton("Согласовать"),
+ tgbotapi.NewKeyboardButton("Отложенные"),
+ ),
+ tgbotapi.NewKeyboardButtonRow(
+ tgbotapi.NewKeyboardButton("❓ Как создать согласование"),
+ ),
+ )
+}
+
+// ApproverObserverMenuKeyboard - меню для согласующего + наблюдателя
+func ApproverObserverMenuKeyboard() tgbotapi.ReplyKeyboardMarkup {
+ return tgbotapi.NewReplyKeyboard(
+ tgbotapi.NewKeyboardButtonRow(
+ tgbotapi.NewKeyboardButton("Согласование"),
+ tgbotapi.NewKeyboardButton("Мои заявки"),
+ ),
+ tgbotapi.NewKeyboardButtonRow(
+ tgbotapi.NewKeyboardButton("Согласовать"),
+ tgbotapi.NewKeyboardButton("Отложенные"),
+ ),
+ tgbotapi.NewKeyboardButtonRow(
+ tgbotapi.NewKeyboardButton("Наблюдаемые"),
+ ),
+ tgbotapi.NewKeyboardButtonRow(
+ tgbotapi.NewKeyboardButton("❓ Как создать согласование"),
+ ),
+ )
+}
diff --git a/service/telegram_service/keyboard/delegation.go b/service/telegram_service/keyboard/delegation.go
new file mode 100644
index 0000000..edfd35a
--- /dev/null
+++ b/service/telegram_service/keyboard/delegation.go
@@ -0,0 +1,316 @@
+// telegram_service/keyboard/delegation.go - полностью переписать
+
+package keyboard
+
+import (
+ "bitrix_balancer_api/core/typescore"
+ "bitrix_balancer_api/telegram_service/types"
+ "context"
+ "fmt"
+ tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
+)
+
+const delegationCategoriesPerPage = 6
+const delegationTopicsPerPage = 6
+const delegationUsersPerPage = 8
+const delegationListPerPage = 6
+
+func BuildDelegationMainMenu() tgbotapi.InlineKeyboardMarkup {
+ return tgbotapi.NewInlineKeyboardMarkup(
+ tgbotapi.NewInlineKeyboardRow(
+ tgbotapi.NewInlineKeyboardButtonData("➕ Делегировать", "deleg_create"),
+ ),
+ tgbotapi.NewInlineKeyboardRow(
+ tgbotapi.NewInlineKeyboardButtonData("Делегированные права", "deleg_list"),
+ ),
+ )
+}
+
+func BuildDelegationCategoryMenu(categories []*typescore.ApprovalTopicCategory, page int) tgbotapi.InlineKeyboardMarkup {
+ total := len(categories)
+ totalPages := (total + delegationCategoriesPerPage - 1) / delegationCategoriesPerPage
+
+ if page < 0 {
+ page = 0
+ }
+ if page >= totalPages && totalPages > 0 {
+ page = totalPages - 1
+ }
+
+ start := page * delegationCategoriesPerPage
+ end := start + delegationCategoriesPerPage
+ if end > total {
+ end = total
+ }
+
+ var rows [][]tgbotapi.InlineKeyboardButton
+
+ for _, c := range categories[start:end] {
+ if c.ID == nil || c.Name == nil {
+ continue
+ }
+ btn := tgbotapi.NewInlineKeyboardButtonData(
+ *c.Name,
+ fmt.Sprintf("deleg_category:%d", *c.ID),
+ )
+ rows = append(rows, tgbotapi.NewInlineKeyboardRow(btn))
+ }
+
+ if totalPages > 1 {
+ var navRow []tgbotapi.InlineKeyboardButton
+ if page > 0 {
+ navRow = append(navRow, tgbotapi.NewInlineKeyboardButtonData(
+ "← Назад",
+ fmt.Sprintf("deleg_category_page:%d", page-1),
+ ))
+ }
+ if page < totalPages-1 {
+ navRow = append(navRow, tgbotapi.NewInlineKeyboardButtonData(
+ fmt.Sprintf("%d / %d →", page+1, totalPages),
+ fmt.Sprintf("deleg_category_page:%d", page+1),
+ ))
+ } else {
+ navRow = append(navRow, tgbotapi.NewInlineKeyboardButtonData(
+ fmt.Sprintf("%d / %d", page+1, totalPages),
+ "deleg_page_noop",
+ ))
+ }
+ rows = append(rows, navRow)
+ }
+
+ return tgbotapi.NewInlineKeyboardMarkup(rows...)
+}
+
+func BuildDelegationTopicMenu(topics []*typescore.ApprovalTopic, categoryID uint64, page int) tgbotapi.InlineKeyboardMarkup {
+ total := len(topics)
+ totalPages := (total + delegationTopicsPerPage - 1) / delegationTopicsPerPage
+
+ if page < 0 {
+ page = 0
+ }
+ if page >= totalPages && totalPages > 0 {
+ page = totalPages - 1
+ }
+
+ start := page * delegationTopicsPerPage
+ end := start + delegationTopicsPerPage
+ if end > total {
+ end = total
+ }
+
+ var rows [][]tgbotapi.InlineKeyboardButton
+
+ // Кнопка "Все"
+ rows = append(rows, tgbotapi.NewInlineKeyboardRow(
+ tgbotapi.NewInlineKeyboardButtonData(
+ "✅ Вся категория",
+ fmt.Sprintf("deleg_all_category:%d", categoryID),
+ ),
+ ))
+
+ for _, t := range topics[start:end] {
+ if t.ID == nil || t.Name == nil {
+ continue
+ }
+ btn := tgbotapi.NewInlineKeyboardButtonData(
+ *t.Name,
+ fmt.Sprintf("deleg_topic:%d", *t.ID),
+ )
+ rows = append(rows, tgbotapi.NewInlineKeyboardRow(btn))
+ }
+
+ if totalPages > 1 {
+ var navRow []tgbotapi.InlineKeyboardButton
+ if page > 0 {
+ navRow = append(navRow, tgbotapi.NewInlineKeyboardButtonData(
+ "← Назад",
+ fmt.Sprintf("deleg_topic_page:%d:%d", categoryID, page-1),
+ ))
+ }
+ if page < totalPages-1 {
+ navRow = append(navRow, tgbotapi.NewInlineKeyboardButtonData(
+ fmt.Sprintf("%d / %d →", page+1, totalPages),
+ fmt.Sprintf("deleg_topic_page:%d:%d", categoryID, page+1),
+ ))
+ } else {
+ navRow = append(navRow, tgbotapi.NewInlineKeyboardButtonData(
+ fmt.Sprintf("%d / %d", page+1, totalPages),
+ "deleg_page_noop",
+ ))
+ }
+ rows = append(rows, navRow)
+ }
+
+ rows = append(rows, tgbotapi.NewInlineKeyboardRow(
+ tgbotapi.NewInlineKeyboardButtonData("← К категориям", "deleg_back_categories"),
+ ))
+
+ return tgbotapi.NewInlineKeyboardMarkup(rows...)
+}
+
+func BuildDelegationUserMenu(users []*typescore.User, categoryID, topicID uint64, page int) tgbotapi.InlineKeyboardMarkup {
+ total := len(users)
+ totalPages := (total + delegationUsersPerPage - 1) / delegationUsersPerPage
+
+ if page < 0 {
+ page = 0
+ }
+ if page >= totalPages && totalPages > 0 {
+ page = totalPages - 1
+ }
+
+ start := page * delegationUsersPerPage
+ end := start + delegationUsersPerPage
+ if end > total {
+ end = total
+ }
+
+ var rows [][]tgbotapi.InlineKeyboardButton
+
+ for _, u := range users[start:end] {
+ if u.ID == nil || u.FullName == nil {
+ continue
+ }
+ btn := tgbotapi.NewInlineKeyboardButtonData(
+ *u.FullName,
+ fmt.Sprintf("deleg_user:%d", *u.ID),
+ )
+ rows = append(rows, tgbotapi.NewInlineKeyboardRow(btn))
+ }
+
+ if totalPages > 1 {
+ var navRow []tgbotapi.InlineKeyboardButton
+ if page > 0 {
+ navRow = append(navRow, tgbotapi.NewInlineKeyboardButtonData(
+ "← Назад",
+ fmt.Sprintf("deleg_user_page:%d:%d:%d", categoryID, topicID, page-1),
+ ))
+ }
+ if page < totalPages-1 {
+ navRow = append(navRow, tgbotapi.NewInlineKeyboardButtonData(
+ fmt.Sprintf("%d / %d →", page+1, totalPages),
+ fmt.Sprintf("deleg_user_page:%d:%d:%d", categoryID, topicID, page+1),
+ ))
+ } else {
+ navRow = append(navRow, tgbotapi.NewInlineKeyboardButtonData(
+ fmt.Sprintf("%d / %d", page+1, totalPages),
+ "deleg_page_noop",
+ ))
+ }
+ rows = append(rows, navRow)
+ }
+
+ backCallback := fmt.Sprintf("deleg_category:%d", categoryID)
+ if topicID > 0 {
+ backCallback = fmt.Sprintf("deleg_category:%d", categoryID)
+ }
+
+ rows = append(rows, tgbotapi.NewInlineKeyboardRow(
+ tgbotapi.NewInlineKeyboardButtonData("← Назад", backCallback),
+ ))
+
+ return tgbotapi.NewInlineKeyboardMarkup(rows...)
+}
+
+func BuildDelegationBackToUsers(categoryID, topicID uint64) tgbotapi.InlineKeyboardMarkup {
+ callback := fmt.Sprintf("deleg_all_category:%d", categoryID)
+ if topicID > 0 {
+ callback = fmt.Sprintf("deleg_topic:%d", topicID)
+ }
+ return tgbotapi.NewInlineKeyboardMarkup(
+ tgbotapi.NewInlineKeyboardRow(
+ tgbotapi.NewInlineKeyboardButtonData("← Назад", callback),
+ ),
+ )
+}
+
+func BuildDelegatedRightsList(delegations []*typescore.ApprovalDelegation, page int, ctx context.Context, ipc *types.InternalProviderControl) tgbotapi.InlineKeyboardMarkup {
+ total := len(delegations)
+ totalPages := (total + delegationListPerPage - 1) / delegationListPerPage
+
+ if page < 0 {
+ page = 0
+ }
+ if page >= totalPages && totalPages > 0 {
+ page = totalPages - 1
+ }
+
+ start := page * delegationListPerPage
+ end := start + delegationListPerPage
+ if end > total {
+ end = total
+ }
+
+ var rows [][]tgbotapi.InlineKeyboardButton
+
+ for _, d := range delegations[start:end] {
+ if d.ID == nil {
+ continue
+ }
+
+ scopeName := "—"
+ if d.TopicID != nil {
+ topic, _ := ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *d.TopicID)
+ if topic != nil && topic.Name != nil {
+ scopeName = *topic.Name
+ }
+ } else if d.CategoryID != nil {
+ category, _ := ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, *d.CategoryID)
+ if category != nil && category.Name != nil {
+ scopeName = *category.Name
+ }
+ }
+
+ btn := tgbotapi.NewInlineKeyboardButtonData(
+ scopeName,
+ fmt.Sprintf("deleg_detail:%d", *d.ID),
+ )
+ rows = append(rows, tgbotapi.NewInlineKeyboardRow(btn))
+ }
+
+ if totalPages > 1 {
+ var navRow []tgbotapi.InlineKeyboardButton
+ if page > 0 {
+ navRow = append(navRow, tgbotapi.NewInlineKeyboardButtonData(
+ "← Назад",
+ fmt.Sprintf("deleg_list_page:%d", page-1),
+ ))
+ }
+ if page < totalPages-1 {
+ navRow = append(navRow, tgbotapi.NewInlineKeyboardButtonData(
+ fmt.Sprintf("%d / %d →", page+1, totalPages),
+ fmt.Sprintf("deleg_list_page:%d", page+1),
+ ))
+ } else {
+ navRow = append(navRow, tgbotapi.NewInlineKeyboardButtonData(
+ fmt.Sprintf("%d / %d", page+1, totalPages),
+ "deleg_page_noop",
+ ))
+ }
+ rows = append(rows, navRow)
+ }
+
+ return tgbotapi.NewInlineKeyboardMarkup(rows...)
+}
+
+func BuildDelegationActions(delegationID uint64) tgbotapi.InlineKeyboardMarkup {
+ return tgbotapi.NewInlineKeyboardMarkup(
+ tgbotapi.NewInlineKeyboardRow(
+ tgbotapi.NewInlineKeyboardButtonData("Изменить срок", fmt.Sprintf("deleg_extend:%d", delegationID)),
+ ),
+ tgbotapi.NewInlineKeyboardRow(
+ tgbotapi.NewInlineKeyboardButtonData("❌ Отозвать", fmt.Sprintf("deleg_revoke:%d", delegationID)),
+ ),
+ tgbotapi.NewInlineKeyboardRow(
+ tgbotapi.NewInlineKeyboardButtonData("← К списку", "deleg_list"),
+ ),
+ )
+}
+
+func BuildDelegationExtendCancel(delegationID uint64) tgbotapi.InlineKeyboardMarkup {
+ return tgbotapi.NewInlineKeyboardMarkup(
+ tgbotapi.NewInlineKeyboardRow(
+ tgbotapi.NewInlineKeyboardButtonData("← Отмена", fmt.Sprintf("deleg_detail:%d", delegationID)),
+ ),
+ )
+}
diff --git a/service/telegram_service/keyboard/executor.go b/service/telegram_service/keyboard/executor.go
new file mode 100644
index 0000000..5904da6
--- /dev/null
+++ b/service/telegram_service/keyboard/executor.go
@@ -0,0 +1,14 @@
+package keyboard
+
+import (
+ "fmt"
+ tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
+)
+
+func BuildExecutorTaskActions(taskID uint64) tgbotapi.InlineKeyboardMarkup {
+ return tgbotapi.NewInlineKeyboardMarkup(
+ tgbotapi.NewInlineKeyboardRow(
+ tgbotapi.NewInlineKeyboardButtonData("✅ Выполнено", fmt.Sprintf("task_complete:%d", taskID)),
+ ),
+ )
+}
diff --git a/service/telegram_service/keyboard/file_input.go b/service/telegram_service/keyboard/file_input.go
new file mode 100644
index 0000000..e2fc01f
--- /dev/null
+++ b/service/telegram_service/keyboard/file_input.go
@@ -0,0 +1,52 @@
+package keyboard
+
+import (
+ "bitrix_balancer_api/core/utilscore"
+ "bitrix_balancer_api/telegram_service/state"
+ "fmt"
+ tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
+)
+
+// BuildFileInputKeyboard строит клавиатуру с кнопками открепления каждого файла,
+// кнопкой отправки (с количеством) и кнопкой отправки без файлов.
+// keyboard/file_input.go
+func BuildFileInputKeyboard(topicCode string, files []state.FileAttachment) tgbotapi.InlineKeyboardMarkup {
+ var rows [][]tgbotapi.InlineKeyboardButton
+
+ // Кнопка «Открепить» для каждого файла
+ for i, f := range files {
+ label := []rune(f.FileName)
+ if len(label) > 25 {
+ label = append(label[:22], []rune("...")...)
+ }
+ rows = append(rows, tgbotapi.NewInlineKeyboardRow(
+ tgbotapi.NewInlineKeyboardButtonData(
+ "🗑 "+string(label),
+ fmt.Sprintf("appr_file_detach:%d", i),
+ ),
+ ))
+ }
+
+ // Кнопка отправки — показывает количество файлов
+ submitLabel := "✅ Отправить на согласование"
+ if n := len(files); n > 0 {
+ submitLabel = fmt.Sprintf("✅ Отправить (%s)", utilscore.PluralFiles(n))
+ }
+ rows = append(rows, tgbotapi.NewInlineKeyboardRow(
+ tgbotapi.NewInlineKeyboardButtonData(submitLabel, "appr_file_submit:"+topicCode),
+ ))
+
+ // Кнопка «без файлов» появляется только если уже что-то прикреплено
+ if len(files) > 0 {
+ rows = append(rows, tgbotapi.NewInlineKeyboardRow(
+ tgbotapi.NewInlineKeyboardButtonData("📤 Отправить без файлов", "appr_file_skip:"+topicCode),
+ ))
+ }
+
+ // Кнопка «Назад» — всегда внизу
+ rows = append(rows, tgbotapi.NewInlineKeyboardRow(
+ tgbotapi.NewInlineKeyboardButtonData("← Назад", "appr_back:"+topicCode),
+ ))
+
+ return tgbotapi.NewInlineKeyboardMarkup(rows...)
+}
diff --git a/service/telegram_service/keyboard/observer.go b/service/telegram_service/keyboard/observer.go
new file mode 100644
index 0000000..cf595a1
--- /dev/null
+++ b/service/telegram_service/keyboard/observer.go
@@ -0,0 +1,72 @@
+package keyboard
+
+import (
+ "bitrix_balancer_api/core/typescore"
+ "bitrix_balancer_api/telegram_service/approvalflow"
+ "fmt"
+ tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
+)
+
+// BuildObserverTopicMenu — список тем для наблюдателя.
+func BuildObserverTopicMenu(topics []approvalflow.Topic) tgbotapi.InlineKeyboardMarkup {
+ var rows [][]tgbotapi.InlineKeyboardButton
+ for _, t := range topics {
+ btn := tgbotapi.NewInlineKeyboardButtonData(
+ t.Name(),
+ fmt.Sprintf("obs_topic:%s", t.Code()),
+ )
+ rows = append(rows, tgbotapi.NewInlineKeyboardRow(btn))
+ }
+ return tgbotapi.NewInlineKeyboardMarkup(rows...)
+}
+
+// BuildObserverApprovalList — список заявок в теме (ФИО — Отдел).
+func BuildObserverApprovalList(
+ approvals []*typescore.Approval,
+ initiators map[uint64]*typescore.User,
+ departments map[uint64]*typescore.Department,
+ topicCode string,
+) tgbotapi.InlineKeyboardMarkup {
+ var rows [][]tgbotapi.InlineKeyboardButton
+ for _, a := range approvals {
+ if a.ID == nil {
+ continue
+ }
+ label := fmt.Sprintf("#%d", *a.ID)
+ if a.InitiatorID != nil {
+ if u, ok := initiators[*a.InitiatorID]; ok && u.FullName != nil {
+ label += " " + *u.FullName
+ }
+ }
+ if a.DepartmentID != nil {
+ if d, ok := departments[*a.DepartmentID]; ok && d.Name != nil {
+ label += " — " + *d.Name
+ }
+ }
+ rows = append(rows, tgbotapi.NewInlineKeyboardRow(
+ tgbotapi.NewInlineKeyboardButtonData(label, fmt.Sprintf("obs_approval:%d", *a.ID)),
+ ))
+ }
+ rows = append(rows, tgbotapi.NewInlineKeyboardRow(
+ tgbotapi.NewInlineKeyboardButtonData("🔙 К темам", "obs_back_topics"),
+ ))
+ return tgbotapi.NewInlineKeyboardMarkup(rows...)
+}
+
+// BuildObserverApprovalDetail — карточка заявки с кнопками наблюдателя.
+func BuildObserverApprovalDetail(approvalID uint64, topicCode string) tgbotapi.InlineKeyboardMarkup {
+ return tgbotapi.NewInlineKeyboardMarkup(
+ tgbotapi.NewInlineKeyboardRow(
+ tgbotapi.NewInlineKeyboardButtonData(
+ "🔔 Напомнить согласующему",
+ fmt.Sprintf("obs_remind:%d", approvalID),
+ ),
+ ),
+ tgbotapi.NewInlineKeyboardRow(
+ tgbotapi.NewInlineKeyboardButtonData(
+ "🔙 Назад к списку",
+ fmt.Sprintf("obs_back:%s", topicCode),
+ ),
+ ),
+ )
+}
diff --git a/service/telegram_service/keyboard/report.go b/service/telegram_service/keyboard/report.go
new file mode 100644
index 0000000..c9f3428
--- /dev/null
+++ b/service/telegram_service/keyboard/report.go
@@ -0,0 +1,36 @@
+package keyboard
+
+import tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
+
+// BuildReportTypeMenu — выбор типа отчёта (согласования или задачи)
+func BuildReportTypeMenu() tgbotapi.InlineKeyboardMarkup {
+ return tgbotapi.NewInlineKeyboardMarkup(
+ tgbotapi.NewInlineKeyboardRow(
+ tgbotapi.NewInlineKeyboardButtonData("📊 Согласования", "report_type_approvals"),
+ ),
+ tgbotapi.NewInlineKeyboardRow(
+ tgbotapi.NewInlineKeyboardButtonData("📋 Задачи", "report_type_tasks"),
+ ),
+ )
+}
+
+// BuildReportFilterMenu — выбор периода для отчёта
+func BuildReportFilterMenu() tgbotapi.InlineKeyboardMarkup {
+ return tgbotapi.NewInlineKeyboardMarkup(
+ tgbotapi.NewInlineKeyboardRow(
+ tgbotapi.NewInlineKeyboardButtonData("📅 Указать период", "report_set_dates"),
+ ),
+ tgbotapi.NewInlineKeyboardRow(
+ tgbotapi.NewInlineKeyboardButtonData("📤 Выгрузить за всё время", "report_all_time"),
+ ),
+ )
+}
+
+// BuildReportDateToMenu — кнопка для выгрузки по сегодня
+func BuildReportDateToMenu() tgbotapi.InlineKeyboardMarkup {
+ return tgbotapi.NewInlineKeyboardMarkup(
+ tgbotapi.NewInlineKeyboardRow(
+ tgbotapi.NewInlineKeyboardButtonData("📤 Выгрузить (по сегодня)", "report_generate"),
+ ),
+ )
+}
diff --git a/service/telegram_service/scheduler/delegation_checker.go b/service/telegram_service/scheduler/delegation_checker.go
new file mode 100644
index 0000000..b0c13a2
--- /dev/null
+++ b/service/telegram_service/scheduler/delegation_checker.go
@@ -0,0 +1,139 @@
+package scheduler
+
+import (
+ "bitrix_balancer_api/core/typescore"
+ "bitrix_balancer_api/telegram_service/types"
+ "context"
+ "fmt"
+ "time"
+
+ tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
+ "github.com/sirupsen/logrus"
+)
+
+type DelegationChecker struct {
+ ipc *types.InternalProviderControl
+}
+
+func NewDelegationChecker(ipc *types.InternalProviderControl) *DelegationChecker {
+ return &DelegationChecker{ipc: ipc}
+}
+
+func (dc *DelegationChecker) Start() {
+ ticker := time.NewTicker(30 * time.Minute)
+ go func() {
+ for range ticker.C {
+ dc.checkDelegations()
+ }
+ }()
+ // Первая проверка сразу
+ go dc.checkDelegations()
+}
+
+func (dc *DelegationChecker) checkDelegations() {
+ ctx := context.Background()
+ bot := dc.ipc.TGBotClient.GetBot()
+
+ isActive := true
+ delegations, _, err := dc.ipc.Database.ApprovalDelegation.GetApprovalDelegationsListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.ApprovalDelegation{
+ IsActive: &isActive,
+ },
+ })
+ if err != nil {
+ logrus.Errorf("DelegationChecker: GetApprovalDelegationsListDB err=%v", err)
+ return
+ }
+
+ now := time.Now()
+
+ for _, deleg := range delegations {
+ if deleg.ValidUntil == nil {
+ continue
+ }
+
+ timeLeft := deleg.ValidUntil.Sub(now)
+
+ // Истекло - деактивируем
+ if timeLeft <= 0 {
+ inactive := false
+ deleg.IsActive = &inactive
+ dc.ipc.Database.ApprovalDelegation.UpdateApprovalDelegationDB(ctx, nil, deleg) //nolint:errcheck
+ dc.notifyExpired(bot, ctx, deleg)
+ continue
+ }
+
+ // За 24 часа
+ if timeLeft <= 24*time.Hour && (deleg.NotifiedDay == nil || !*deleg.NotifiedDay) {
+ dc.notifyExpiringDay(bot, ctx, deleg)
+ notified := true
+ deleg.NotifiedDay = ¬ified
+ dc.ipc.Database.ApprovalDelegation.UpdateApprovalDelegationDB(ctx, nil, deleg) //nolint:errcheck
+ continue
+ }
+
+ // За 2 часа
+ if timeLeft <= 2*time.Hour && (deleg.Notified2h == nil || !*deleg.Notified2h) {
+ dc.notifyExpiring2h(bot, ctx, deleg)
+ notified := true
+ deleg.Notified2h = ¬ified
+ dc.ipc.Database.ApprovalDelegation.UpdateApprovalDelegationDB(ctx, nil, deleg) //nolint:errcheck
+ }
+ }
+}
+
+func (dc *DelegationChecker) notifyExpiringDay(bot *tgbotapi.BotAPI, ctx context.Context, deleg *typescore.ApprovalDelegation) {
+ dc.sendExpiringNotification(bot, ctx, deleg, "⏰ Делегирование истекает через 24 часа")
+}
+
+func (dc *DelegationChecker) notifyExpiring2h(bot *tgbotapi.BotAPI, ctx context.Context, deleg *typescore.ApprovalDelegation) {
+ dc.sendExpiringNotification(bot, ctx, deleg, "⏰ Делегирование истекает через 2 часа")
+}
+
+func (dc *DelegationChecker) notifyExpired(bot *tgbotapi.BotAPI, ctx context.Context, deleg *typescore.ApprovalDelegation) {
+ dc.sendExpiringNotification(bot, ctx, deleg, "⏱ Срок делегирования истёк")
+}
+
+func (dc *DelegationChecker) sendExpiringNotification(bot *tgbotapi.BotAPI, ctx context.Context, deleg *typescore.ApprovalDelegation, title string) {
+ if deleg.DelegatorID == nil || deleg.DelegateID == nil || deleg.TopicID == nil || deleg.ValidUntil == nil {
+ return
+ }
+
+ topic, _ := dc.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *deleg.TopicID)
+ topicName := "—"
+ if topic != nil && topic.Name != nil {
+ topicName = *topic.Name
+ }
+
+ text := fmt.Sprintf(
+ "%s\n\n"+
+ "📋 Тема: %s\n"+
+ "📅 Окончание: %s",
+ title, topicName, deleg.ValidUntil.Format("02.01.2006 15:04"),
+ )
+
+ // Уведомляем делегатора
+ delegator, _ := dc.ipc.Database.User.GetUserByIDDB(ctx, *deleg.DelegatorID)
+ if delegator != nil && delegator.TelegramID != nil {
+ delegate, _ := dc.ipc.Database.User.GetUserByIDDB(ctx, *deleg.DelegateID)
+ delegateName := "—"
+ if delegate != nil && delegate.FullName != nil {
+ delegateName = *delegate.FullName
+ }
+ msg := tgbotapi.NewMessage(*delegator.TelegramID, text+fmt.Sprintf("\n👤 Делегат: %s", delegateName))
+ msg.ParseMode = "HTML"
+ bot.Send(msg) //nolint:errcheck
+ }
+
+ // Уведомляем делегата
+ delegate, _ := dc.ipc.Database.User.GetUserByIDDB(ctx, *deleg.DelegateID)
+ if delegate != nil && delegate.TelegramID != nil {
+ delegatorName := "—"
+ if delegator != nil && delegator.FullName != nil {
+ delegatorName = *delegator.FullName
+ }
+ msg := tgbotapi.NewMessage(*delegate.TelegramID, text+fmt.Sprintf("\n👤 От: %s", delegatorName))
+ msg.ParseMode = "HTML"
+ bot.Send(msg) //nolint:errcheck
+ }
+}
diff --git a/service/telegram_service/start.sh b/service/telegram_service/start.sh
new file mode 100755
index 0000000..1220e87
--- /dev/null
+++ b/service/telegram_service/start.sh
@@ -0,0 +1,49 @@
+#!/bin/bash
+
+set -e
+trap 'echo "🔴 Скрипт остановлен"; exit' SIGINT
+
+# Имя сети Docker
+DOCKER_NETWORK_NAME="networklocal1"
+# Наименование сервиса
+SERVICE_NAME="ruspet_telegram_service"
+
+# Наименование образа
+IMAGE_NAME="${SERVICE_NAME}_i"
+# Наименование контейнера
+CONTAINER_NAME="${SERVICE_NAME}_c"
+# Имя приложения
+APP_NAME="${SERVICE_NAME}_app"
+
+
+# Останавливаем и удаляем старый контейнер, если он существует
+if [ "$(docker ps -q -f name=$CONTAINER_NAME)" ]; then
+ docker stop $CONTAINER_NAME
+ docker rm $CONTAINER_NAME
+fi
+
+# Удаляем старый образ, если он существует
+if [ "$(docker images -q $IMAGE_NAME)" ]; then
+ docker rmi $IMAGE_NAME
+fi
+
+# Создаем директорию vendor с зависимостями
+go mod tidy
+rm -rf vendor
+go mod vendor
+
+# Проверяем существование сети и создаем, если не существует
+docker network ls | grep $DOCKER_NETWORK_NAME || docker network create $DOCKER_NETWORK_NAME
+
+# Собираем образ
+docker build --build-arg APP_NAME=$APP_NAME -t $IMAGE_NAME .
+
+# Запускаем контейнер с новым образом в сетевом режиме host и подключаем к сети по имени
+docker run -d \
+ --add-host=rmq_host:192.168.1.102 \
+ --network $DOCKER_NETWORK_NAME \
+ --restart always \
+ --name $CONTAINER_NAME \
+ -e APP_NAME=$APP_NAME \
+ --add-host=database_host:192.168.0.15 \
+ $IMAGE_NAME
\ No newline at end of file
diff --git a/service/telegram_service/state/add_approver.go b/service/telegram_service/state/add_approver.go
new file mode 100644
index 0000000..8ebd339
--- /dev/null
+++ b/service/telegram_service/state/add_approver.go
@@ -0,0 +1,42 @@
+package state
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "time"
+)
+
+type AddApproverFlowState struct {
+ CategoryID uint64 `json:"category_id"`
+ ApprovalID uint64 `json:"approval_id"`
+ Stage string `json:"stage"` // "select_category", "select_approval", "select_user"
+}
+
+func addApproverKey(telegramID int64) string {
+ return fmt.Sprintf("add_approver_flow:%d", telegramID)
+}
+
+func (s *StateManager) SetAddApprover(ctx context.Context, telegramID int64, state *AddApproverFlowState) error {
+ data, err := json.Marshal(state)
+ if err != nil {
+ return err
+ }
+ return s.redis.Set(ctx, addApproverKey(telegramID), string(data), 30*time.Minute)
+}
+
+func (s *StateManager) GetAddApprover(ctx context.Context, telegramID int64) (*AddApproverFlowState, error) {
+ data, err := s.redis.Get(ctx, addApproverKey(telegramID))
+ if err != nil {
+ return nil, nil
+ }
+ var state AddApproverFlowState
+ if err := json.Unmarshal([]byte(data), &state); err != nil {
+ return nil, err
+ }
+ return &state, nil
+}
+
+func (s *StateManager) ClearAddApprover(ctx context.Context, telegramID int64) error {
+ return s.redis.Del(ctx, addApproverKey(telegramID))
+}
diff --git a/service/telegram_service/state/delegation.go b/service/telegram_service/state/delegation.go
new file mode 100644
index 0000000..5ebe297
--- /dev/null
+++ b/service/telegram_service/state/delegation.go
@@ -0,0 +1,45 @@
+// telegram_service/state/delegation.go - новый файл
+
+package state
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "time"
+)
+
+type DelegationFlowState struct {
+ CategoryID uint64 `json:"category_id"`
+ TopicID uint64 `json:"topic_id,omitempty"`
+ DelegateID uint64 `json:"delegate_id"`
+ Stage string `json:"stage"` // "select_category", "select_topic", "select_user", "input_date"
+}
+
+func delegationKey(telegramID int64) string {
+ return fmt.Sprintf("delegation_flow:%d", telegramID)
+}
+
+func (s *StateManager) SetDelegation(ctx context.Context, telegramID int64, state *DelegationFlowState) error {
+ data, err := json.Marshal(state)
+ if err != nil {
+ return err
+ }
+ return s.redis.Set(ctx, delegationKey(telegramID), string(data), 30*time.Minute)
+}
+
+func (s *StateManager) GetDelegation(ctx context.Context, telegramID int64) (*DelegationFlowState, error) {
+ data, err := s.redis.Get(ctx, delegationKey(telegramID))
+ if err != nil {
+ return nil, nil
+ }
+ var state DelegationFlowState
+ if err := json.Unmarshal([]byte(data), &state); err != nil {
+ return nil, err
+ }
+ return &state, nil
+}
+
+func (s *StateManager) ClearDelegation(ctx context.Context, telegramID int64) error {
+ return s.redis.Del(ctx, delegationKey(telegramID))
+}
diff --git a/service/telegram_service/state/pending_state.go b/service/telegram_service/state/pending_state.go
new file mode 100644
index 0000000..df07f46
--- /dev/null
+++ b/service/telegram_service/state/pending_state.go
@@ -0,0 +1,67 @@
+package state
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "time"
+)
+
+// PendingCommentItem — одна отложенная заявка, ожидающая комментария.
+type PendingCommentItem struct {
+ ApprovalID uint64 `json:"approval_id"`
+ Action string `json:"action"` // "reject" | "revoke"
+}
+
+func pendingCommentsKey(telegramID int64) string {
+ return fmt.Sprintf("appr_pending_comments:%d", telegramID)
+}
+
+func (s *StateManager) GetPendingComments(ctx context.Context, telegramID int64) ([]PendingCommentItem, error) {
+ data, err := s.redis.Get(ctx, pendingCommentsKey(telegramID))
+ if err != nil {
+ return nil, nil
+ }
+ var items []PendingCommentItem
+ if err := json.Unmarshal([]byte(data), &items); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
+func (s *StateManager) AddPendingComment(ctx context.Context, telegramID int64, item PendingCommentItem) error {
+ items, _ := s.GetPendingComments(ctx, telegramID)
+ for _, existing := range items {
+ if existing.ApprovalID == item.ApprovalID {
+ return nil // уже есть — не дублируем
+ }
+ }
+ items = append(items, item)
+ data, err := json.Marshal(items)
+ if err != nil {
+ return err
+ }
+ return s.redis.Set(ctx, pendingCommentsKey(telegramID), string(data), 24*time.Hour)
+}
+
+func (s *StateManager) RemovePendingComment(ctx context.Context, telegramID int64, approvalID uint64) error {
+ items, _ := s.GetPendingComments(ctx, telegramID)
+ var filtered []PendingCommentItem
+ for _, item := range items {
+ if item.ApprovalID != approvalID {
+ filtered = append(filtered, item)
+ }
+ }
+ if len(filtered) == 0 {
+ return s.redis.Del(ctx, pendingCommentsKey(telegramID))
+ }
+ data, err := json.Marshal(filtered)
+ if err != nil {
+ return err
+ }
+ return s.redis.Set(ctx, pendingCommentsKey(telegramID), string(data), 24*time.Hour)
+}
+
+func (s *StateManager) ClearPendingComments(ctx context.Context, telegramID int64) error {
+ return s.redis.Del(ctx, pendingCommentsKey(telegramID))
+}
diff --git a/service/telegram_service/state/report_state.go b/service/telegram_service/state/report_state.go
new file mode 100644
index 0000000..2a4ce3a
--- /dev/null
+++ b/service/telegram_service/state/report_state.go
@@ -0,0 +1,44 @@
+package state
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+)
+
+// ReportFilterState — состояние фильтра отчёта для пользователя
+type ReportFilterState struct {
+ ReportType string // "approvals" или "tasks"
+ DateFrom string // дата начала в формате "ДД.ММ.ГГГГ"
+ DateTo string // дата окончания в формате "ДД.ММ.ГГГГ"
+ AwaitDateFrom bool // ожидаем ввод даты начала
+ AwaitDateTo bool // ожидаем ввод даты окончания
+}
+
+func reportKey(telegramID int64) string {
+ return fmt.Sprintf("report_filter:%d", telegramID)
+}
+
+func (s *StateManager) SetReport(ctx context.Context, telegramID int64, state *ReportFilterState) error {
+ data, err := json.Marshal(state)
+ if err != nil {
+ return err
+ }
+ return s.redis.Set(ctx, reportKey(telegramID), string(data), stateTTL)
+}
+
+func (s *StateManager) GetReport(ctx context.Context, telegramID int64) (*ReportFilterState, error) {
+ data, err := s.redis.Get(ctx, reportKey(telegramID))
+ if err != nil {
+ return nil, nil
+ }
+ var state ReportFilterState
+ if err := json.Unmarshal([]byte(data), &state); err != nil {
+ return nil, err
+ }
+ return &state, nil
+}
+
+func (s *StateManager) ClearReport(ctx context.Context, telegramID int64) error {
+ return s.redis.Del(ctx, reportKey(telegramID))
+}
diff --git a/service/telegram_service/state/state.go b/service/telegram_service/state/state.go
new file mode 100644
index 0000000..cdf9779
--- /dev/null
+++ b/service/telegram_service/state/state.go
@@ -0,0 +1,69 @@
+package state
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "time"
+
+ redismodule "bitrix_balancer_api/core/lib/internally/redis"
+)
+
+const stateTTL = 30 * time.Minute
+
+type FileAttachment struct {
+ Base64 string
+ FileName string
+}
+
+// ApprovalFlowState — состояние пользователя внутри флоу согласования.
+// Хранится в Redis, сбрасывается по TTL или после отправки заявки.
+type ApprovalFlowState struct {
+ TopicCode string `json:"topic_code"`
+ NodeKey string `json:"node_key"`
+ Collected map[string]string `json:"collected"`
+ AwaitInput bool `json:"await_input"`
+ InputKey string `json:"input_key"`
+ History []string `json:"history"`
+ AwaitFileInput bool `json:"await_file_input"`
+ Files []FileAttachment `json:"files"`
+ FileStatusMsgID int `json:"file_status_msg_id"`
+ SelectedApproverID uint64 `json:"selected_approver_id,omitempty"`
+ AwaitApproverSelection bool `json:"await_approver_selection"`
+}
+
+type StateManager struct {
+ redis *redismodule.ModuleRedis
+}
+
+func NewStateManager(redis *redismodule.ModuleRedis) *StateManager {
+ return &StateManager{redis: redis}
+}
+
+func key(telegramID int64) string {
+ return fmt.Sprintf("approval_flow:%d", telegramID)
+}
+
+func (s *StateManager) Set(ctx context.Context, telegramID int64, state *ApprovalFlowState) error {
+ data, err := json.Marshal(state)
+ if err != nil {
+ return err
+ }
+ return s.redis.Set(ctx, key(telegramID), string(data), stateTTL)
+}
+
+func (s *StateManager) Get(ctx context.Context, telegramID int64) (*ApprovalFlowState, error) {
+ data, err := s.redis.Get(ctx, key(telegramID))
+ if err != nil {
+ return nil, nil // нет активного состояния — это норма
+ }
+ var state ApprovalFlowState
+ if err := json.Unmarshal([]byte(data), &state); err != nil {
+ return nil, err
+ }
+ return &state, nil
+}
+
+func (s *StateManager) Clear(ctx context.Context, telegramID int64) error {
+ return s.redis.Del(ctx, key(telegramID))
+}
diff --git a/service/telegram_service/types/types.go b/service/telegram_service/types/types.go
new file mode 100644
index 0000000..3f60a73
--- /dev/null
+++ b/service/telegram_service/types/types.go
@@ -0,0 +1,15 @@
+package types
+
+import (
+ configcore "bitrix_balancer_api/core/config"
+ database "bitrix_balancer_api/core/db"
+ "bitrix_balancer_api/core/lib/external/telegram"
+ redismodule "bitrix_balancer_api/core/lib/internally/redis"
+)
+
+type InternalProviderControl struct {
+ Config *configcore.Config
+ RedisClient *redismodule.ModuleRedis
+ TGBotClient *telegram.TgBotClient
+ Database *database.ModuleDB
+}
diff --git a/service/telegram_service/version b/service/telegram_service/version
new file mode 100644
index 0000000..aa6e22c
--- /dev/null
+++ b/service/telegram_service/version
@@ -0,0 +1 @@
+v-0.0.2
\ No newline at end of file
diff --git a/update-go-and-deps.sh b/update-go-and-deps.sh
new file mode 100644
index 0000000..b1c66eb
--- /dev/null
+++ b/update-go-and-deps.sh
@@ -0,0 +1,87 @@
+#!/bin/bash
+
+ROOT=$(pwd)
+
+# Определяем версии Go
+LOCAL_GO_FULL=$(go version 2>/dev/null | awk '{print $3}' || echo "unknown")
+[[ "$LOCAL_GO_FULL" == "unknown" ]] && { echo "❌ Go is not installed"; exit 1; }
+LOCAL_GO=${LOCAL_GO_FULL#go}
+
+LATEST_GO_FULL=$(curl -fsSL 'https://go.dev/VERSION?m=text' | grep '^go[0-9]' | head -n1)
+[[ -z "$LATEST_GO_FULL" ]] && { echo "❌ Failed to fetch latest Go version"; exit 1; }
+LATEST_GO=${LATEST_GO_FULL#go}
+
+echo "🛠️ Local Go: go $LOCAL_GO"
+echo "🆕 Latest Go: $LATEST_GO_FULL"
+
+update_module() {
+ local mod_path="$1"
+ local module_name="$2"
+ local dir=$(dirname "$mod_path")
+
+ cd "$dir" || return 1
+
+ current_go=$(grep '^go ' "$mod_path" 2>/dev/null | awk '{print $2}' || echo "unknown")
+ echo " 📁 $module_name | go.mod: $current_go → $LATEST_GO"
+
+ go mod edit -go="$LATEST_GO" || return 1
+
+ echo " 📥 go get -u"
+ go get -u ./... 2>&1 | grep -v "unmatched selector" || true
+
+ echo " 🧹 go mod tidy"
+ go mod tidy || return 1
+
+ if [[ -f go.mod ]]; then
+ total_deps=$(go list -m all 2>/dev/null | wc -l | tr -d ' ')
+ upgraded_deps=$(go list -u -m all 2>/dev/null | grep -c '\[.*\]' 2>/dev/null || echo 0)
+ echo " 📦 $((total_deps - 1)) deps | 🔼 $upgraded_deps upgraded"
+ fi
+
+ echo " 🔨 go build"
+ go build ./... || return 1
+
+ echo " ✅ $module_name"
+ cd "$ROOT"
+ return 0
+}
+
+# Обновляем core
+CORE_MOD="$ROOT/core/go.mod"
+if [[ -f "$CORE_MOD" ]]; then
+ echo -e "\n🔷 Core module"
+ read -rp " ▶️ Update core to $LATEST_GO? (y/N): " confirm
+ if [[ "$confirm" =~ ^[Yy]$ ]]; then
+ update_module "$CORE_MOD" "core" || { echo -e "\n🛑 Core update failed. Aborted."; exit 1; }
+ else
+ echo " ➖ Skipped."
+ fi
+fi
+
+# Обновляем сервисы
+SERVICES_DIR="$ROOT/service"
+mapfile -t MOD_FILES < <(find "$SERVICES_DIR" -name "go.mod" -type f | sort)
+
+SERVICE_COUNT=${#MOD_FILES[@]}
+if [[ $SERVICE_COUNT -eq 0 ]]; then
+ echo -e "\n📦 No services found."
+else
+ echo -e "\n📦 Found $SERVICE_COUNT service(s):"
+ for mod in "${MOD_FILES[@]}"; do
+ name=$(basename "$(dirname "$mod")")
+ current_go=$(grep '^go ' "$mod" 2>/dev/null | awk '{print $2}' || echo "?")
+ echo " - $name (go $current_go)"
+ done
+
+ read -rp $'\n ▶️ Update ALL lib to '"$LATEST_GO"'? (y/N): ' confirm
+ if [[ "$confirm" =~ ^[Yy]$ ]]; then
+ echo -e "\n🚀 Updating services...\n"
+ for mod in "${MOD_FILES[@]}"; do
+ name=$(basename "$(dirname "$mod")")
+ update_module "$mod" "$name" || { echo -e "\n🛑 Failed on $name. Aborted."; exit 1; }
+ done
+ echo -e "\n🎉 Successfully updated $SERVICE_COUNT service(s)."
+ else
+ echo " ➖ All services skipped."
+ fi
+fi
\ No newline at end of file